#include "Doom.h"
#include <IntMath.h>

#define S_CLIPPING_DIST (3600*0x10000)		/* Clip sounds beyond this distance */
#define S_CLOSE_DIST (200*0x10000)			/* Too close! */
#define S_ATTENUATOR ((S_CLIPPING_DIST-S_CLOSE_DIST)>>FRACBITS)
#define S_STEREO_SWING (96*0x10000)

/**********************************

	Clear the sound buffers and stop all sound

**********************************/

void S_Clear(void)
{
	Word i;
	i = 1;
	do {
		StopSound(i);
	} while (++i<NUMSFX);
}

/**********************************

	Start a new sound, use the origin to affect
	the stereo panning

**********************************/

void S_StartSound(Fixed *OriginXY,Word sound_id)
{
	Fixed dist;
	angle_t angle;
	int vol;
	int sep;
	
	if (sound_id<NUMSFX && sound_id) {
		if (OriginXY) {
			mobj_t *Listener;
			
			Listener = players.mo;
			if (OriginXY!=&Listener->x) {
				dist = GetApproxDistance(Listener->x-OriginXY[0],Listener->y-OriginXY[1]);
				if (dist>S_CLIPPING_DIST) {
					return;			/* Too far away! */
				}
				angle = PointToAngle(Listener->x,Listener->y,OriginXY[0],OriginXY[1]);
				angle = angle-Listener->angle;			
				angle>>=ANGLETOFINESHIFT;
				if (dist>=S_CLOSE_DIST) {
					vol = (255 * ((S_CLIPPING_DIST-dist)>>FRACBITS))/S_ATTENUATOR;
					if (!vol) {		/* Too quiet? */
						return;
					}
					sep = 128-(IMFixMul(S_STEREO_SWING,finesine[angle])>>FRACBITS);
					RightVolume = (sep*vol)>>8;
					LeftVolume = ((256-sep)*vol)>>8;
				}
			}
		}
		PlaySound(sound_id);
	}
}

/**********************************

	Start music

**********************************/

static Byte SongLookup[] = {
	 0,
	 11,	/* Intro */
	 12,	 /* Final (18) */
	 3,		/* Bunny */
	 5,		/* Intermission (4) */
	 5, 	/* Level 1 */
	 6, 	/* Level 2 */
	 7, 	/* Level 3 */
	 8, 	/* Level 4 */
	 9,		/* Level 5 */
	 10,	/* Level 6 */
	 11,	/* Level 7 */
	 12,	/* Level 8 */
	 13,	/* Level 9 */
	 14,	/* Level 10 */
	15,		/* Level 11 */
	5,		/*5 Level 12  (19) */
	6,		/*6 Level 13 (20) */
	7,		/*7 Level 14 (21) */
	8,		/*8 Level 15 (22) */
	9,		/*9 Level 16 (23) */
	10,		/*10 Level 17 (24) */
	11,		/*11 Level 18 (25) */
	13,		/*13 Level 19 (26) */
	14,		/*14 Level 20 (27) */
	15,		/*15 Level 21 (28) */
	10,		/*10 Level 22 (30) */
	12,		/*12 Level 23 (31) */
	29, 1, 1, 1, 1, 1, 1,	/* Level 24 (Secret) */
	1
};
	
void S_StartSong(Word music_id,Boolean looping)
{
		if (MusicVolume!=0) {
//			PauseMusic();
//			}
	PlaySong(SongLookup[music_id]);
	}
}

/**********************************

    Stop music

**********************************/

void S_StopSong(void)
{
	PlaySong(0);
}
