/*
Copyright (c) 1998 Michael Haar, Ulrich Haar, Michael Thayer,
  Tobias Mueller, Tobias Lenz
All rights reserved.
Terroid Programming by Michael Haar, Michael Thayer, Ulrich Haar
Terroid Graphics by Ulrich Haar, Michael Haar
Terroid Music by Michael Thayer
Terroid Level design by Michael Haar, Ulrich Haar, Tobias Lenz
Terroid Beta testing by Tobias Mueller, Tobias Lenz

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice and credits, this unmodified list of conditions and the
   following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice and credits, this unmodified list of conditions and the
   following disclaimer in the documentation and/or other materials
   provided with the distribution.
3. Any credits displayed during programme execution must include the
   above or an equivalent credit list.
4. The name of the author may not be used to endorse or promote products
   derived from this software without specific prior written permission.
5. The authors Michael Thayer and Michael Haar are to be informed,
   preferable by electronic mail, when this software is distributed
   commercially.  A single notification is required for any given
   distribution, and explicit copies of that distribution (e.g. for all
   resellers of a given Linux distribution).
6. If any modifications are made to the software, then a description of them
   must be included when the software is redistributed, or alternatively,
   the distributed binary or source code must be described as a product
   based on source code by Michael Haar, Michael Thayer and Ulrich Haar.

THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/*************************************************/
/* DIGITAL Nightmares Soundsystem - using MikMod */
/* Copyright (c) Mar 1996 by Michael Haar        */
/*************************************************/

#include <stdlib.h>
#include <stdio.h>
#include <dn.h>
#include <mikmod.h>

/* global vars */
UNIMOD *mymod = NULL;
BOOLEAN modinit_ok = FALSE, soundinit_ok = FALSE;
BOOLEAN mod_play = FALSE;
int sound_fadegeschw;
extern float speed_constant ;

/* prototypes */
BOOLEAN init_mod(char *fname, BYTE device, BYTE channels_more);
BOOLEAN init_sample(char *fname, SAMPLE **s, BYTE device, BYTE channels);
void start_mod(BOOLEAN repeat, int volume, int fade);
void start_sample(SAMPLE *s, int channel);
void play_mod(int fading); /* this one to call in the mainloop */
void play_sound(void); /* or this */
BOOLEAN mod_ready(void);
void stop_sound(void);
void free_mod(void);
void free_sample(SAMPLE *s);
void exit_sound(void);
void SoundFading(int geschw);

/* functions */
void tickhandler(void)
{
	if(mymod != NULL)
	{
		MP_HandleTick();    /* play 1 tick of the module */
		MD_SetBPM(mp_bpm);
	}
}

BOOLEAN init_mod(char *fname, BYTE device, BYTE channels_more)
{
	if(soundinit_ok)
	{
		stop_sound();
		soundinit_ok = FALSE;
		exit_sound();
	}

	if(!modinit_ok)
	{
		modinit_ok = TRUE;
		/*
			Initialize soundcard parameters.. you _have_ to do this
			before calling MD_Init(), and it's illegal to change them
			after you've called MD_Init()
		*/
		md_mixfreq      = 44100;                     /* standard mixing freq */
		md_dmabufsize   = 16000;                    /* standard dma buf size */
		md_mode         = DMODE_16BITS|DMODE_STEREO; /* standard mixing mode */
		md_device       = device;                /* standard device: autodetect */
	
		/*
			Register the loaders we want to use..
		*/
		ML_RegisterLoader(&load_mod);
		ML_RegisterLoader(&load_s3m);
		ML_RegisterLoader(&load_xm);

		/*
			Register the drivers we want to use:
		*/
		MD_RegisterDriver(&drv_nos);
		MD_RegisterDriver(&drv_vox);
	
		MD_RegisterPlayer(tickhandler);

		/*
			set the number of voices to use.. you
			could add extra channels here (e.g. md_numchn=mf->numchn+4; )
			to use for your own soundeffects:
		*/
		if(!MD_Init())
			return(FALSE);

		if(gfxmode < 0x13)	
			printf("Using %s for %d bit %s sound at %u Hz\n\n", md_driver->Name, (md_mode&DMODE_16BITS) ? 16:8, (md_mode&DMODE_STEREO) ? "stereo":"mono", md_mixfreq);

		md_numchn = channels_more;
	}

	mymod = ML_LoadFN(fname);

	if(mymod == NULL)
		return(FALSE);

	md_numchn += mymod->numchn;

	return(TRUE);
}

BOOLEAN init_sample(char *fname, SAMPLE **s, BYTE device, BYTE channels)
{
	if(!soundinit_ok && !modinit_ok)
	{
		soundinit_ok = TRUE;
		/*
			Initialize soundcard parameters.. you _have_ to do this
			before calling MD_Init(), and it's illegal to change them
			after you've called MD_Init()
		*/
		md_mixfreq      = 44100;                     /* standard mixing freq */
		md_dmabufsize   = 8000;                     /* standard dma buf size */
		md_mode         = DMODE_16BITS|DMODE_STEREO; /* standard mixing mode */
		md_device       = device;                 /* standard device: autodetect */
	
		/*
			Register the drivers we want to use:
		*/
	
		MD_RegisterDriver(&drv_nos);
		MD_RegisterDriver(&drv_vox);
	
		if(!MD_Init())
			return(FALSE);
	
		if(gfxmode < 0x13)	
			printf("Using %s for %d bit %s sound at %u Hz\n\n", md_driver->Name, (md_mode&DMODE_16BITS) ? 16:8, (md_mode&DMODE_STEREO) ? "stereo":"mono", md_mixfreq);

		md_numchn = channels;

		MD_PlayStart();
	}

	if(!(*s = MW_LoadWavFN(fname)))
		return(FALSE);

	sound_fadegeschw = 0;

	return(TRUE);
}

void start_mod(BOOLEAN repeat, int volume, int fade)
{
	MD_PlayStop();

	/* initialize modplayer to play this module */
	MP_Init(mymod);

	speed_constant = 1.0 ;
	mp_volume = volume;
	mp_loop = repeat;
	sound_fadegeschw = fade;

	MD_PlayStart();

	mod_play = TRUE;
}

void start_sample(SAMPLE *s, int channel)
{
	if (!s)
	  {
	    return ;
	  }
	MD_VoiceSetVolume(channel, 64);
	MD_VoiceSetPanning(channel, 0);
	MD_VoiceSetFrequency(channel, 12000);
	MD_VoicePlay(channel, s->handle, 0, s->length, 0, 0, s->flags);
}

void play_mod(int fading)
{
	if((mp_volume > -fading) && (mp_volume < 100 - fading))
		mp_volume += fading;
	MD_Update();
}

void play_sound(void)
{
	if(sound_fadegeschw)
	{
		if((mp_volume > -sound_fadegeschw) && (mp_volume < 100 - sound_fadegeschw))
			mp_volume += sound_fadegeschw;
		else
		{
			sound_fadegeschw = 0;
			if(mp_volume == 0)
			stop_sound();
		}
	}	

	MD_Update();
}

BOOLEAN mod_ready(void)
{
	return(MP_Ready());
}

void stop_sound(void)
{
	mod_play = FALSE;
	mp_volume = 0;
}

void free_mod(void)
{
	if(mymod != NULL)
		ML_Free(mymod);
	mymod = NULL;
}

void free_sample(SAMPLE *s)
{
	if(s != NULL)
		MW_FreeWav(s);
}

void exit_sound(void)
{
	MD_PlayStop();

	MD_Exit();
	if(mymod != NULL)
		free_mod();
}

void SoundFading(int geschw)
{
	sound_fadegeschw = geschw;
}
