#include "Sound.h"

#ifndef WINCPCTELERA
    // Music.
    extern void* E1_START;

    // Sound effects.
    extern void* SFX_SOUNDEFFECTS;
#else
    // Must be defined as void in C file for cpctelera.
    void* E1_START;
    void* SFX_SOUNDEFFECTS;
#endif

// The number of the sound effect chosen.
u8 effectNumber_;

// The channel that the chosen effect will be played on.
u8 effectChannel_;

// The volume that the chosen effect will be played at.
u8 effectVolume_;

// Indicates whether a new sound effect has been chosen.
// This is used to switch sound effects when there is a change.
u8 effectChanged_;

// Indicates that the song in the music data has changed.
u8 songChanged_;

// The currently selected arkos music data to play.
void* currentMusicData_;

// The number of the song currently selected.
u8 songNumber_;

void initSound()
{
    effectChanged_ = FALSE;
    songChanged_ = FALSE;

    if (soundMode)
    {
        initSoundEffects(&SFX_SOUNDEFFECTS);

        initMusic(&E1_START);

        // Turn on sound if enabled.
        soundMode = SOUND_MODE_ON;
    }
}

void initSoundEffects(void* soundData)
{
#ifndef WINCPCTELERA
    PLAYER_ARKOS_INITSOUNDEFFECTS(soundData);
#endif
}

void initMusic(void* musicData)
{
    currentMusicData_ = musicData;
}

void playSoundEffect(u8 effectNumber, u8 channel, u8 volume)
{
    effectNumber_ = effectNumber;
    effectChannel_ = channel;
    effectVolume_ = volume;

    effectChanged_ = TRUE;
}

void playMusic(u8 songNumber)
{
    songNumber_ = songNumber;

    songChanged_ = TRUE;
}

void playSound()
{
    // Play the sound effect if a new effect has been chosen.
    if (soundMode && effectChanged_)
    {
#ifndef WINCPCTELERA
        PLAYER_ARKOS_PLAYSOUNDEFFECT(effectNumber_, effectChannel_, effectVolume_);
#endif
        effectChanged_ = FALSE;
    }

    // Initialise the music within arkos2 if the chosen song has changed 
    // (or the first time the sound for the music is being played).
    if (songChanged_)
    {
#ifndef WINCPCTELERA
        PLAYER_ARKOS_INIT(currentMusicData_, songNumber_);
#endif
        songChanged_ = FALSE;
    }

    if (soundMode)
    {
        // Plays the current sound and music (as chosen and initialised).
#ifndef WINCPCTELERA
        PLAYER_ARKOS_PLAY();
#endif
    }
}

void stopSound()
{
#ifndef WINCPCTELERA
    PLAYER_ARKOS_STOP();
#endif

    if (soundMode)
    {
        // Turns off the sound if enabled.
        soundMode = SOUND_MODE_OFF;
    }
}