//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "CPUThread.h"
#include "OSCABoard.h"

#pragma package(smart_init)
//---------------------------------------------------------------------------

//   Important: Methods and properties of objects in VCL can only be
//   used in a method called using Synchronize, for example:
//
//      Synchronize(&UpdateCaption);
//
//   where UpdateCaption could look like:
//
//      void __fastcall Z80Thread::UpdateCaption()
//      {
//        Form1->Caption = "Updated in a thread";
//      }
//---------------------------------------------------------------------------

__fastcall Z80Thread::Z80Thread(TOSCABoard *mainBoard)
	: m_pMainBoard(mainBoard), TThread(true)
{
}
//---------------------------------------------------------------------------
void Z80Thread::SetName()
{
	THREADNAME_INFO info;
	info.dwType = 0x1000;
	info.szName = "MainCPU";
	info.dwThreadID = -1;
	info.dwFlags = 0;
	this->Priority = tpHigher;

	__try
	{
		RaiseException( 0x406D1388, 0, sizeof(info)/sizeof(DWORD),(DWORD*)&info );
	}
	__except (EXCEPTION_CONTINUE_EXECUTION)
	{
	}
}
//---------------------------------------------------------------------------
void __fastcall Z80Thread::RunCPU(void)
{
	try {
		if (m_pMainBoard)
			m_pMainBoard->Execute();
	} catch(...) { };
}

void __fastcall Z80Thread::Reset(bool resetState)
{
	this->m_bResetComplete = false;
	this->m_bResetting = resetState;
}

bool __fastcall Z80Thread::IsReset(void)
{
	return this->m_bResetComplete;
}

void __fastcall Z80Thread::Execute()
{
	SetName();
	//---- Place thread code here ----

	while(!this->Terminated)
	{
		if (!this->m_bResetting)
		{
			DWORD lastTicks = GetTickCount();
			//Synchronize(&this->RunCPU);
			RunCPU();
			DWORD elapsed = GetTickCount() - lastTicks;

			if (elapsed < 9)
			{
				Sleep(9 - elapsed);
			}
			//else
//				Sleep(1);
		}
		else
		{
			this->m_bResetComplete = true;
			Sleep(10);
		}
	}
}
//---------------------------------------------------------------------------
