#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#include "lib/minifmod.h"
#include "sound.h"
#include "resource.h"


FMUSIC_MODULE *mod;


unsigned int memopen(char *name)
{
	MEMFILE *memfile;

	memfile = new MEMFILE;

	HRSRC		rec;
	HGLOBAL		handle;
	
	rec = FindResource(NULL, MAKEINTRESOURCE(IDR_MUSIC), "RAWDATA" );
	handle = LoadResource(NULL, rec);
	
	memfile->data = (unsigned char*)LockResource (handle);
	memfile->length = SizeofResource (NULL, rec);
	memfile->pos = 0;

	return (unsigned int)memfile;
}

void memclose(unsigned int handle)
{
	MEMFILE *memfile = (MEMFILE *)handle;

	delete (memfile);
}

int memread(void *buffer, int size, unsigned int handle)
{
	MEMFILE *memfile = (MEMFILE *)handle;

	if (memfile->pos + size >= memfile->length)
		size = memfile->length - memfile->pos;

	memcpy(buffer, (char *)memfile->data+memfile->pos, size);
	memfile->pos += size;
	
	return size;
}

void memseek(unsigned int handle, int pos, signed char mode)
{
	MEMFILE *memfile = (MEMFILE *)handle;

	if (mode == SEEK_SET) 
		memfile->pos = pos;
	else if (mode == SEEK_CUR) 
		memfile->pos += pos;
	else if (mode == SEEK_END)
		memfile->pos = memfile->length + pos;

	if (memfile->pos > memfile->length)
		memfile->pos = memfile->length;
}

int memtell(unsigned int handle)
{
	MEMFILE *memfile = (MEMFILE *)handle;

	return memfile->pos;
}

void SoundInit ()
{
	FSOUND_File_SetCallbacks(memopen, memclose, memread, memseek, memtell);
	FSOUND_Init (44100, 0);
	mod = FMUSIC_LoadSong("", NULL);
}

void SoundKill ()
{
	FMUSIC_FreeSong(mod);
	FSOUND_Close();
}
