#include <clip.h>

/***************************************************************************/
/* DO change */

#define FILENAME	"C:\\Home\\Music\\SPC\\n-z\\Treasure Hunter G [Hitoshi YmoH Sakimoto-Wow, What a Story].spc"

#define BUFLEN		SPC2BUFLEN
#define INIT()		spc2drv_init(g_data)
#define stream_callback	spc2drv_stream_callback

/***************************************************************************/
/* do NOT change */

#define NWHDR		8	/* これ以上増やすとwaveOutWriteでエラーになるみたい */
HWAVEOUT g_wout;
WAVEFORMATEX g_fmt;
WAVEHDR g_whdr[NWHDR];
short g_wbuff[NWHDR][BUFLEN];
unsigned char g_data[1024 * 1024];

/***************************************************************************/


/***************************************************************************/

void CALLBACK
waveOutProc(HWAVEOUT hwo, UINT uMsg, DWORD dwInstance, DWORD dwParam1, DWORD dwParam2)
{
	static int I;
	int retval;

	if(uMsg != WOM_DONE) return;

	stream_callback(g_wbuff[I], 0);
	retval = waveOutWrite(hwo, &g_whdr[I], sizeof g_whdr[I]);
	assert(retval == 0);

	I = (I + 1) % NWHDR;
}

int
main(int argc, char* argv[])
{
	int retval, i, len;
	FILE* fp;
	SPC2INF inf;

	/* init driver */
	fp = fopen(FILENAME, "rb");
	if(!fp) abort();
	len = fread(g_data, 1, sizeof g_data, fp);
	fclose(fp);
	retval = INIT();
	if(retval != 0) abort();

	retval = spc2_inf(g_data, &inf);
	printf("SongTitle: %s\n", inf.song_title);
	printf("GameTitle: %s\n", inf.game_title);
	printf("Dumper: %s\n", inf.dumper);
	printf("Comments: %s\n", inf.comments);
	printf("Date: %s\n", inf.date);
	printf("PlayTime: %d[sec]\n", inf.play_time);
	printf("FadeTime: %d[msec]\n", inf.fade_time);
	printf("Artist: %s\n", inf.artist);
	printf("ChannelDisable: %d\n", inf.channel_disable);
	printf("Emulator: %d\n", inf.emulator);

	/* init stream */
	memset(&g_fmt, 0, sizeof g_fmt);
	g_fmt.wFormatTag = WAVE_FORMAT_PCM;
	g_fmt.nChannels = 1;
	g_fmt.nSamplesPerSec = 16000;
	g_fmt.nAvgBytesPerSec = 16000 * 2;
	g_fmt.nBlockAlign = 2;
	g_fmt.wBitsPerSample = 16;
	retval = waveOutOpen(&g_wout, WAVE_MAPPER, &g_fmt, (DWORD)waveOutProc, 0, CALLBACK_FUNCTION);
	assert(retval == 0);
	for(i = 0; i < NWHDR; i++) {
		memset(&g_whdr[i], 0, sizeof g_whdr[i]);
		g_whdr[i].lpData = (char*)g_wbuff[i];
		g_whdr[i].dwBufferLength = sizeof g_wbuff[i];
		retval = waveOutPrepareHeader(g_wout, &g_whdr[i], sizeof g_whdr[i]);
		assert(retval == 0);
	}

	/* start playing */
	for(i = 0; i < NWHDR; i++) {
		retval = waveOutWrite(g_wout, &g_whdr[i], sizeof g_whdr[i]);
		assert(retval == 0);
	}
	Sleep(INFINITE);

	return 0;
}

