#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include <snd.h>
#include <mos.h>



static char *eup=NULL;
static int signature=0;
static int length=0;

static void LoadBGM(void)
{
	FILE *fp=fopen("DATA/CarmenOv.eup","rb");
	if(NULL!=fp)
	{
		int i;
		size_t fsize=0;
		char *header=NULL;
		char fmbFName[16],fmbName[16],pmbFName[16],pmbName[16],ful[256];
		int eupSize,topSignature,topTempo;


		fseek(fp,0,SEEK_END);
		fsize=ftell(fp);
		fseek(fp,0,SEEK_SET);

		header=malloc(2048);
		fread(header,1,2048,fp);

		for(i=0; i<32; ++i)
		{
			SND_eup_mute_set(i,     (int)header[852+i]);
			SND_eup_port_set(i,     (int)header[884+i]);
			SND_eup_midi_ch_set(i,  (int)header[916+i]);
			SND_eup_bias_set(i,     (int)header[948+i]);
			SND_eup_transpose_set(i,(int)header[980+i]);
		}

		for(i=0; i<6; ++i)
		{
			SND_midi_ch_assign(i,(int)header[1748+i]);
		}
		for(i=0; i<8; ++i)
		{
			SND_midi_ch_assign(i+64,(int)header[1754+i]);
		}

		for(i=0; i<8 && 0!=header[1762+i]; ++i)
		{
			fmbFName[i]=header[1762+i];
		}
		fmbFName[i  ]='.';
		fmbFName[i+1]='F';
		fmbFName[i+2]='M';
		fmbFName[i+3]='B';
		fmbFName[i+4]=0;

		for(i=0; i<8 && 0!=header[1770+i]; ++i)
		{
			pmbFName[i]=header[1770+i];
		}
		pmbFName[i  ]='.';
		pmbFName[i+1]='P';
		pmbFName[i+2]='M';
		pmbFName[i+3]='B';
		pmbFName[i+4]=0;

		free(header);
		header=NULL;


		strcpy(ful,"DATA/");
		strcat(ful,fmbFName);
		SND_fm_bank_load(ful,fmbName);

		strcpy(ful,"DATA/");
		strcat(ful,pmbFName);
		SND_pcm_bank_load(ful,pmbName);

		SND_pcm_mode_set(0);

		fread(&eupSize,1,4,fp);
		fread(&topSignature,1,1,fp);
		fread(&topTempo,1,1,fp);

		signature=(int)topSignature;
		SND_eup_tempo_set((int)topTempo);

		eupSize=fsize-2048-4-1-1;
		length=eupSize;
		eup=malloc(eupSize);
		fread(eup,1,eupSize,fp);
	}
}

void StartBGM(void)
{
	LoadBGM();
	if(NULL!=eup && 0<length)
	{
		SND_eup_play_start(eup,length,signature);
	}
}

void EndBGM(void)
{
	if(NULL!=eup && 0<length)
	{
		SND_eup_play_stop();
		free(eup);
	}
}

int GetBGMCounter(void)
{
	if(NULL!=eup)
	{
		// return SND_eup_stat_ptr()-eup;
		return SND_eup_stat_meas();
	}
	return 0;
}

int GetBGMClock(void)
{
	if(NULL!=eup)
	{
		return SND_eup_stat_clock();
	}
	return 0;
}

int IsBGMPlaying(void)
{
	return SND_eup_stat_flag();
}
