#include "standard.h"
#include "global.h"

/*** locals ***/
local double LdSync,LdFreq;	// sync remembers the last value of the system timer to allow frame rate to be calced

extern "C" void TIME_Reset()
{
	LARGE_INTEGER fq;
	QueryPerformanceCounter(&fq);
	LdSync=(double)fq.LowPart+(double)fq.HighPart*(double)0xffffffff;
	LdSync/=LdFreq;
}

bool TIME_Init()
{
	Log(LT_Enter,"TIME_Init");
	LARGE_INTEGER fq;
	
	if (!QueryPerformanceFrequency(&fq))
		return false;

	LdFreq=(double)fq.LowPart+(double)fq.HighPart*(double)0xffffffff;
	LdFreq/=60.0;
	TIME_Reset();
	return true;
}

// Get the number of frames that has passed since the last call (60 per second)

int Sync(void)
{
	int nFrames;
	LARGE_INTEGER ct;
	double dCounter;
	QueryPerformanceCounter(&ct);
	dCounter=(double)ct.LowPart+(double)ct.HighPart*(double)0xffffffff;	// WARNING: inaccuracy as HighPart increases and double loses low bit precision?
	dCounter/=LdFreq;
	nFrames=long(dCounter)-long(LdSync);	// Use the non-fractional bits to get the frame count
	LdSync=dCounter;
	return nFrames;
}
