/* Pathogen Warrior
 * Copyright 2004 Jetro Lauha - http://iki.fi/jetro/
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * $Id: sound.cpp,v 1.4 2004/07/14 15:37:03 tonic Exp $
 * $Revision: 1.4 $
 */

#include "main.h"
#include "SDL_mixer.h"


#define CHANNELS    8
#define MUSICFILE   "data/music.s3m"
#define MUSICVOLMUL 0.7f
#define SFXVOLMUL   0.85f


static int soundInitialized = 0, soundEnabled = 1, musicEnabled = 0;
static Mix_Music *music;
static int musicChn = -1;
static float musicVolume = 1.0f;


static void loadMusic()
{
    music = Mix_LoadMUS(MUSICFILE);
    if (music == NULL)
    {
        errorMessage("Music Load Error", "Error loading file %s\nError: %s",
                     MUSICFILE, SDL_GetError());
        exit(1);
    }
}


void initSound()
{
    if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0)
    {
        errorMessage("Sound Disabled", "Unable to initialized audio! (%s)", SDL_GetError());
        soundInitialized = soundEnabled = 0;
        return;
    }
    soundInitialized = 1;
    Mix_AllocateChannels(CHANNELS);

    loadMusic();

    setMusic(1);
}


void deinitSound()
{
    if (!soundInitialized)
        return;

    setMusic(0);

    Mix_FreeMusic(music);

    Mix_CloseAudio();
}


void setSound(int enabled)
{
    if (!soundInitialized)
        return;

    soundEnabled = enabled ? 1 : 0;
}


void setMusic(int enabled)
{
    if (!soundInitialized)
        return;

    if (enabled && !musicEnabled)
    {
        // turn music on
        musicChn = Mix_FadeInMusic(music, -1, 1000);
        musicEnabled = musicChn >= 0 ? 1 : 0;   // not sure if this is needed
        setMusicVolume(musicVolume);
    }
    else if (musicEnabled && !enabled)
    {
        // turn music off
        Mix_FadeOutMusic(100);
        musicEnabled = 0;
    }
}


void setMusicVolume(float volume)
{
    if (!soundInitialized)
        return;

    musicVolume = volume;

    if (musicEnabled)
        Mix_Volume(musicChn, (int)(volume * MUSICVOLMUL * 128));
}


int getSoundEnabled()
{
    return soundEnabled;
}


int getMusicEnabled()
{
    return musicEnabled;
}
