#include "global.h"
#include "main.h"
#include "maths.h"

#include "demo.h"

int demoStatus = DEMO_NO;
int demoFrameCtr = 0;
int demoNumBlks;
int demoLength = 0;

DEMOFRAME *pDemoBuff=NULL;

PadDataType *pReadPad = &padData;

PadDataType demoPad;

void demoStartRecording(void)
{
	int buffNumBlks = DEMO_BUFFSIZE / sizeof(DEMOFRAME);
	int buffSize = buffNumBlks * sizeof(DEMOFRAME);

	demoNumBlks = buffNumBlks;

	DB("DEMO: Allocating 0x%x bytes (in %d frames)\n", buffSize, buffNumBlks);
	if(!pDemoBuff)
	{
		pDemoBuff = (DEMOFRAME *)MALLOC(buffSize);
		ASSERT(pDemoBuff);
		DB("DEMO: Allocated OK\n");
	}

	pReadPad=&padData;
	demoFrameCtr = 0;
	demoLength = 0;
	demoStatus = DEMO_RECORDING;
}

void demoStopRecording(void)
{
	demoLength = demoFrameCtr;
	demoFrameCtr = 0;
}

void demoRecordFrame(int frameNo, VECTOR *pCharPos, int *pRot, unsigned short digital, unsigned short debounce)
{
	// CPW: COPYVECTOR(&pDemoBuff[demoFrameCtr].charPos, pCharPos);

	if(demoFrameCtr<demoNumBlks)
	{
		pDemoBuff[demoFrameCtr].flags = 0;

		if(pCharPos)
		{
			pDemoBuff[demoFrameCtr].x = pCharPos->vx;
			pDemoBuff[demoFrameCtr].y = pCharPos->vy;
			pDemoBuff[demoFrameCtr].z = pCharPos->vz;

			pDemoBuff[demoFrameCtr].flags|=DEMO_POSITIONSTORED;
		}

		if(pRot)
		{
			pDemoBuff[demoFrameCtr].rot = *pRot;

			pDemoBuff[demoFrameCtr].flags|=DEMO_ROTATIONSTORED;
		}

		pDemoBuff[demoFrameCtr].frameNo = frame;

		pDemoBuff[demoFrameCtr].digital = pReadPad->digital[0];
		pDemoBuff[demoFrameCtr].debounce = pReadPad->debounce[0];
		DB("Recording (%d/%d)\n", demoFrameCtr, demoNumBlks);
	}
	else
	{
		demoStatus = DEMO_NO;
		DB("Record buffer is full!\n");
	}

	demoFrameCtr++;
}

void demoStartPlaying(void)
{
	pReadPad = &demoPad;

	pReadPad->digital[4] = 0;
	pReadPad->debounce[4] = 0;

	demoFrameCtr = 0;
	memcpy(pReadPad, &padData, sizeof(PadDataType));
	demoStatus = DEMO_PLAYING;
}	

void demoStopPlaying(void)
{
}

void demoPlaybackFrame(int frame, VECTOR *pCharPos, int *pRot)
{
	if(frame<0)
		frame = demoFrameCtr;

	if(demoFrameCtr<demoLength)
	{
		pReadPad->digital[0] = pDemoBuff[frame].digital;
		pReadPad->debounce[0] = pDemoBuff[frame].debounce;

		
		if(pCharPos && (pDemoBuff[demoFrameCtr].flags & DEMO_POSITIONSTORED))
		{
		// CPW: 	pCharPos
		}

		DB("Playing (%d/%d)\n", demoFrameCtr, demoNumBlks);
	}
	else
	{
		DB("Demo has ended\n");
		demoStatus = DEMO_NO;
	}

	demoFrameCtr++;
}
