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

int32 TNPlug_TestPlayer (struct TNPlugIFace *Self, uint8 *testme, uint8 *testbuffer,
	uint32 totalsize, uint32 testsize)
{
	int32 ret = 0;
	char *ext;
	ext = strrchr((char *)testme, '.');
	if (ext) {
		if (!IUtility->Stricmp(ext, ".acm")) {
			ret = PLM_File;
		}
	}
	return ret;
}

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

	if (inTuneNet->playmode == PLM_File) {
		struct TNDecHandle *handle;
		const struct ACMInfo *info;

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

		if (acm_open_file(&handle->acm, openme)) goto out;

		info = acm_info(handle->acm);

		handle->pcm_size = (info->rate << 1) * info->channels;
		inTuneNet->pcm[0] = IExec->AllocVec(handle->pcm_size, 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 = info->rate;
			inTuneNet->dec_channels = info->channels;
			inTuneNet->bitrate = acm_bitrate(handle->acm);
			inTuneNet->mix_lr = TN_STEREO_50PER;

			inTuneNet->Tune[0] = 0;

			inTuneNet->ms_duration = acm_time_total(handle->acm);

			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) {
	struct TNDecHandle *handle = inTuneNet->handle;
	if (handle) {
		acm_close(handle->acm);
		IExec->FreeVec(handle);
		inTuneNet->handle = NULL;
	}
	IExec->FreeVec(inTuneNet->pcm[0]);
	inTuneNet->pcm[0] = inTuneNet->pcm[1] = NULL;
}
