#include "tn_cube.h"
#include <pokecubed.h>

extern "C" {

int32 TNPlug_TestPlayer (struct TNPlugIFace *Self, uint8 *testme, uint8 *testbuffer,
	uint32 totalsize, uint32 testsize)
{
	int32 res = 0;
	pokecubed *cubed = new pokecubed();

	if (cubed) {
		if (cubed->isFilePlayable((char *)testme)) {
			res = PLM_File;
		}
		delete(cubed);
	}

	return res;
}

BOOL TNPlug_OpenPlayer (struct TNPlugIFace *Self, uint8 *openme, struct TuneNet *inTuneNet) {
	BOOL res = FALSE;

	if (inTuneNet->playmode == PLM_File) {
		pokecubed *cubed;
		uint32 freq, chans;

		cubed = new pokecubed();
		inTuneNet->handle = cubed;
		if (!cubed) goto out;

		if (!cubed->loadFile((char *)openme)) goto out;
		
		freq = cubed->getFrequency();
		chans = cubed->getNumberOfChannels();

		inTuneNet->pcm[0] = (WORD *)IExec->AllocVec(freq*chans, MEMF_SHARED);
		if (!inTuneNet->pcm[0]) goto out;
		inTuneNet->pcm[1] = inTuneNet->pcm[0] + 1;

		res = TRUE;
out:
		if (res) {
			inTuneNet->DirectRender = ARender_InternalBuffer;
			inTuneNet->max_subsongs =
			inTuneNet->current_subsong = 0;

			inTuneNet->dec_frequency = freq;
			inTuneNet->dec_channels = chans;
			inTuneNet->bitrate = 0;
			inTuneNet->mix_lr = TN_STEREO_50PER;

			inTuneNet->Tune[0] = 0;

			inTuneNet->ms_duration = (ULONG)(cubed->getNumberOfSamples() * 1000.0 / freq);

			inTuneNet->ST_Name[0] = 0;
			inTuneNet->ST_Url[0] = 0;
			inTuneNet->ST_Note[0] = 0;

			inTuneNet->songEOF = TRUE;
		} else {
			TNPlug_ClosePlayer(Self, inTuneNet);
		}
	}

	return res;
}

void TNPlug_ClosePlayer (struct TNPlugIFace *Self, struct TuneNet *inTuneNet) {
	pokecubed *cubed = (pokecubed *)inTuneNet->handle;
	if (cubed) {
		delete(cubed);
		inTuneNet->handle = NULL;
	}
	IExec->FreeVec(inTuneNet->pcm[0]);
	inTuneNet->pcm[0] =
	inTuneNet->pcm[1] = NULL;
}

}
