#include <sys/timeb.h>
#include "c:\Projects\Common\Library_Timer2\timer2.cpp"

static bool KEEPALIVE = false;
static HANDLE hThread;

/* ========================================================================= */
NOMANGLE short CCONV MyBeep(void)
{
   MessageBeep( (WORD) - 1 );
   Beep(1,1);
   return 1;
}
/* ========================================================================= */
NOMANGLE short CCONV GCD_StopKeepAlive()
{
	//unsigned long lpExitCode;
	if (KEEPALIVE == true)
	{
		KEEPALIVE = false;
		//ExitThread(GetExitCodeThread(hThread, &lpExitCode));
	}
	
	return (short) 0;
}
/* ========================================================================= */
NOMANGLE short CCONV GCD_StartKeepAlive()
{
	unsigned long iID;
	//MyBeep();

	if(KEEPALIVE == false)
	{
		KEEPALIVE = true;
		hThread = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)KeepAlive,NULL,0,&iID);
	}
	
	return (short) 0;
}
/* ========================================================================= */
NOMANGLE void CCONV MilliSecondDelay(short mSec)
{
	/*	float startTime, nowTime, endTime;
	struct timeb timeCheck;
	int i=0;
	struct _timeb timebuffer;
	char *timeline;

	_ftime( &timebuffer );
	timeline = ctime( & ( timebuffer.time ) );

	ftime(&timeCheck);
	startTime =  timeCheck.millitm;
	endTime   = startTime +  mSec ;
	nowTime   = startTime;

	do
	{
		ftime(&timeCheck);
		nowTime = timeCheck.millitm;
	} while(endTime>nowTime);

*/	
	double  millisecond_duration;
	clock_t start = clock();
	do 
	{
		millisecond_duration = (double)( 1000 * (clock() - start) / CLOCKS_PER_SEC );
	}	while(millisecond_duration < mSec);


}
/* ========================================================================= */
long WINAPI KeepAlive()
{
//	int i,j;
	short mSec = 200;
	char chZeroByte[1] = {0}; 
	//unsigned long ulReceiveCount;

	while(KEEPALIVE) //&& (hdevice!=INVALID_HANDLE_VALUE))
	{	
		//Sleep(mSec);

		//  Write a 0x00 byte to the serial port
		//if(WriteFile(hdevice,chZeroByte,1,&ulReceiveCount,&owrite)==false)
		//{
		//	fprintf(error_stream,  
		//		"WriteFile in KeepAlive Failed, ErrorCode = %d", GetLastError());
		//}
		
//		MilliSecondDelay(3000);
//		for(i=0;i<6000;i++) for(j=0;j<1000;j++) {}

		Sleep(3000);
//		MyBeep();
		MessageBeep(0xFFFFFFFF);
	}
	return 0;
}