#include "tn_tfm.h"
#include <string.h>

#define AUDIO_BUFFER_SIZE (800 << 1)

int32 TNPlug_TestPlayer (struct TNPlugIFace *Self, uint8 *testme, uint8 *testbuffer,
	uint32 totalsize, uint32 testsize)
{
	const char *ext;
	int32 res = 0;
	ext = strrchr((char *)testme, '.');
	if (ext++) {
		if (!stricmp(ext, "tfc") || !stricmp(ext, "tfd")) {
			res = PLM_FileLoad;
		}
	}
	return res;
}

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

	if (inTuneNet->playmode == PLM_FileLoad) {
		struct TNDecHandle *handle;

		dbug(("creating handle\n"));
		handle = IExec->AllocVec(sizeof(*handle), MEMF_SHARED|MEMF_CLEAR);
		inTuneNet->handle = handle;
		if (!handle) goto out;

		handle->pcm_size = AUDIO_BUFFER_SIZE >> 1;
		inTuneNet->pcm[0] = IExec->AllocVec(handle->pcm_size << 1, MEMF_SHARED);
		if (!inTuneNet->pcm[0]) goto out;

		if (!tfm_open(&handle->TFM, (char *)openme, (uint8 *)inTuneNet->in_file,
			inTuneNet->in_file_size, 3500000, 44100))
		{
			goto out;
		}

		res = TRUE;
out:
		if (res) {
			dbug(("success\n"));
			inTuneNet->DirectRender = ARender_InternalBuffer;

			inTuneNet->current_subsong = 0;
			inTuneNet->max_subsongs = 0;
			
			inTuneNet->dec_frequency = 44100;
			inTuneNet->dec_channels = 1;
			inTuneNet->bitrate = 0;
			inTuneNet->mix_lr = TN_STEREO_50PER;

			inTuneNet->Tune[0] = 0;

			inTuneNet->ms_duration = 0;

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

			inTuneNet->songEOF = TRUE;
		} else {
			dbug(("failure\n"));
			TNPlug_ClosePlayer(Self, inTuneNet);
		}
	}

	return res;
}

void TNPlug_ClosePlayer (struct TNPlugIFace *Self, struct TuneNet *inTuneNet) {
	struct TNDecHandle *handle = inTuneNet->handle;
	if (handle) {
		tfm_close(&handle->TFM);
		IExec->FreeVec(handle);
		inTuneNet->handle = NULL;
	}
	IExec->FreeVec(inTuneNet->pcm[0]);
	inTuneNet->pcm[0] =
	inTuneNet->pcm[1] = NULL;
}
