#include "main.h"

FMUSIC_MODULE *l_pMod = NULL;

void F_CALLBACKAPI instcallback(FMUSIC_MODULE *mod, unsigned char param)
{
     DisplayGridOnSound();
     VUOnSound(param);
}

void InitSound(void)
{
	FSOUND_SetOutput(FSOUND_OUTPUT_DSOUND);
	
    if(!FSOUND_SetBufferSize(100))
        MessageBox(NULL,FMOD_ErrorString(FSOUND_GetError()),"ERROR",MB_ICONEXCLAMATION);

    if(!FSOUND_SetMemorySystem(malloc(4*1024*1024), 4*1024*1024, NULL, NULL, NULL)) 
        MessageBox(NULL,FMOD_ErrorString(FSOUND_GetError()),"ERROR",MB_ICONEXCLAMATION);

	FSOUND_SetDriver(0);
    if (!FSOUND_Init(44100, 32, FSOUND_INIT_USEDEFAULTMIDISYNTH))
        MessageBox(NULL,FMOD_ErrorString(FSOUND_GetError()),"ERROR",MB_ICONEXCLAMATION);

    l_pMod = FMUSIC_LoadSong("media/demochip.xm");

    FMUSIC_SetInstCallback(l_pMod, instcallback, 1);
    FMUSIC_SetInstCallback(l_pMod, instcallback, 2);
    FMUSIC_SetInstCallback(l_pMod, instcallback, 3);
    FMUSIC_SetInstCallback(l_pMod, instcallback, 4);
    FMUSIC_SetInstCallback(l_pMod, instcallback, 5);
}

void RunSound(void)
{
    FMUSIC_SetMasterVolume(l_pMod, 192);
    FMUSIC_SetLooping(l_pMod, true);
    FMUSIC_PlaySong(l_pMod);
}

void FadeSound(void)
{
    static uint uiLastTick = GetTickCount();
    float fMod = ((GetTickCount() - uiLastTick) / 1000.0f); 
    FMUSIC_SetMasterVolume(l_pMod, 192.0f - (192.0f * fMod));
}

void KillSound(void)
{
	FMUSIC_StopSong(l_pMod);
	FMUSIC_FreeSong(l_pMod);
    FSOUND_Close();
}
