/*
** chord.c for Chord 1.0
**
** Made by caput_r
** Login caput_r <caput_r@epita.fr>
**
** Started on  Tue Sep 27 01:34:52 2005 remi caput
** Last update Tue Sep 27 02:51:08 2005 remi caput
*/

#include "chord.h"

struct s_chord	gl_chord;

int		CHD_Init (int maxchan, int flags)
{
	memset (&gl_chord, 0, sizeof (gl_chord));

	if (FMOD_System_Create (&gl_chord.system) == FMOD_OK)
	{
		if (FMOD_System_Init (gl_chord.system, maxchan, flags, NULL) == FMOD_OK)
			return 0;

		FMOD_System_Release (gl_chord.system);
	}

	return 1;
}

int							CHD_InternalAlloc (unsigned int* index)
{
	struct s_chord_item*	alloc;

	if (gl_chord.list.count == gl_chord.list.size)
	{
		gl_chord.list.size += REALLOC_SOUND;

		if (!(alloc = realloc (gl_chord.list.array, gl_chord.list.size * sizeof (*gl_chord.list.array))))
			return 1;

		gl_chord.list.array = alloc;
	}

	*index = gl_chord.list.count++;

	return 0;
}

int		CHD_LoadSound (const char* path, int mode, unsigned int* index)
{
	if (CHD_InternalAlloc (index))
		return 1;

	if (FMOD_System_CreateSound (gl_chord.system, path, mode, 0, &gl_chord.list.array[*index].handle) != FMOD_OK)
		return 1;

	return 0;
}

int		CHD_LoadStream (const char* path, int mode, unsigned int* index)
{
	if (CHD_InternalAlloc (index))
		return 1;

	if (FMOD_System_CreateStream (gl_chord.system, path, mode, 0, &gl_chord.list.array[*index].handle) != FMOD_OK)
		return 1;

	return 0;
}

void	CHD_Loop (void)
{
	FMOD_System_Update (gl_chord.system);
}

void	CHD_PlayStart (unsigned int index, char pause)
{
	FMOD_System_PlaySound (gl_chord.system, FMOD_CHANNEL_FREE, gl_chord.list.array[index].handle, pause, &gl_chord.list.array[index].channel);

	FMOD_Channel_GetFrequency (gl_chord.list.array[index].channel, &gl_chord.list.array[index].frequency);
}

void	CHD_PlayStop (unsigned int index)
{
	FMOD_Channel_Stop (gl_chord.list.array[index].channel);
}

void	CHD_SetFrequency (unsigned int index, float frequency, char relative)
{
	FMOD_Channel_SetFrequency (gl_chord.list.array[index].channel, relative ? gl_chord.list.array[index].frequency * frequency : frequency);
}

void	CHD_SetLoop (unsigned int index, int loop)
{
	FMOD_Channel_SetLoopCount (gl_chord.list.array[index].channel, loop);
}

void	CHD_SetMode (unsigned int index, char mute)
{
	FMOD_Channel_SetMute (gl_chord.list.array[index].channel, mute);
}

void	CHD_SetPan (unsigned int index, float pan)
{
	FMOD_Channel_SetPan (gl_chord.list.array[index].channel, pan);
}

void	CHD_SetPaused (unsigned int index, char pause)
{
	FMOD_Channel_SetPaused (gl_chord.list.array[index].channel, pause);
}

void	CHD_SetVolume (unsigned int index, float volume)
{
	FMOD_Channel_SetVolume (gl_chord.list.array[index].channel, volume);
}

void	CHD_Stop (void)
{
	while (gl_chord.list.count)
		FMOD_Sound_Release (gl_chord.list.array[--gl_chord.list.count].handle);

	if (gl_chord.system)
		FMOD_System_Release (gl_chord.system);
}
