/******************************************************************************
*									      *
*	(C) 1993 by K. Ballueder					      *
*									      *
*	See README and COPYING for details.				      *
*									      *
*	Please feel free to contact me:					      *
*		kballued@charon.physik.uni-osnabrueck.de		      *
*		kballued@jupiter.rz.uni-osnabrueck.de			      *
*									      *
******************************************************************************/


/******

  SOUND.c  : Soundroutinen fuer BDASH

******/
#ifdef OS_DOS
#	include <dos.h>
#	include <alloc.h>
#else
#	include <malloc.h>
#endif

#include <limits.h>	/* PATH_MAX */
#include <stdio.h>
#include <string.h>
#include "bdash.h"
#include "sound.h"
#include "io.h"
#include "zfopen.h"

int sounds_ready = 0;   /* Alles klar zum Abspielen? */

struct sound sounds[NUM_OF_SOUNDFX]; 

/*
 * Laden der benoetigten Sounddateien
 */

void load_sounds(void)
{
	int init_snd_dev(void);

#ifdef OS_DOS
	union REGS registers;
	void far *address;
#else
	void *address;
#endif

  	FILE *description, *sndfile;
  	char inputbuffer[PATH_MAX], soundfile[PATH_MAX];
  	int i, nread;
	int rate, len;
	
		
	if((description = fopen(DATAPATH SND_DESCR_FILE,"rt"))==NULL)
  	{ 	perror("Sound descriptions not found"); 
  		return;
  	}
  	puts("loading sounds...");
  	for(i=0;i<NUM_OF_SOUNDFX;i++)
  	{ 	if(fscanf(description,"%s %d %d",inputbuffer,&len,&rate) < 3) /* Fehler */
  	    		fatal_error("Error in "DATAPATH SND_DESCR_FILE);
    		if((address = malloc(len))==NULL)
      			fatal_error("Out of memory in load_sounds()\a\n");
      		else
      		{
#ifdef OS_DOS
    			sounds[i].seg = FP_SEG(address); sounds[i].off = FP_OFF(address);
    			sounds[i].len_lsw = len-(sounds[i].len_msw = len>>16);
#else
			sounds[i].bufstart = address;
			sounds[i].len = len;
#endif
			sounds[i].rate = rate;
			strcpy(soundfile,DATAPATH);
			strcat(soundfile,inputbuffer);
			if((sndfile=zfopen(soundfile,"rb"))==NULL)
			{	fprintf(stderr,"Unable to load specified sound: %s\a\n", inputbuffer);
#ifdef OS_DOS
				sound[i].seg = 0;
#else
				sounds[i].bufstart = NULL;
#endif
			}
			else
			{	nread = fread(address,1,len,sndfile);
				debug_printf("read sound #%d\trate=%d\tlen=%d\tbytes read=%d\n", i,
				sounds[i].rate, sounds[i].len, nread);
				fclose(sndfile);
			}
		}
	}
	fclose(description);
	
	if(init_snd_dev() == 0)	/* cannot initialize snd device */
		return;
		
	sounds_ready = 1;
}

void soundeffect(enum soundfx  nr)
{
	if(! sounds_ready)
		return;
#ifdef OS_DOS
	if(sounds[nr].seg != 0)
#else
	if(sounds[nr].bufstart != NULL)
#endif
	{	debug_printf("Calling SND_CALL()\n");
		SND_CALL(nr);
	}
}
