/* Replace "dll.h" with the name of your header */
#include "dll.h"
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <SDL/SDL.h>

static short	*wbuffer;
static int	wlength;
static int	pos;
static int	lastFreq = 0;

DLLIMPORT void InitPlayBuff(void)
{
	SDL_Init(SDL_INIT_AUDIO);
}

DLLIMPORT void ShutdownPlayBuff(void)
{
	SDL_Quit();
}

static void playbackCallback(void *userdata, Uint8 *stream, int len)
{
	unsigned short	*buffer = (unsigned short*)stream;
	int		i;
	len /= 2;
	for (i=0;i<len;i++)
	{
		if (pos >= wlength)
			buffer[i] = 0;
		else
			buffer[i] = wbuffer[pos++];
	}
}

DLLIMPORT void PlaySoundBuffer(short *buffer, int length, int freq)
{
	SDL_AudioSpec	spec;
	if (lastFreq != freq)
	{
		if (lastFreq != 0)
			SDL_CloseAudio();
		lastFreq = freq;
		memset(&spec, 0, sizeof(spec));
		spec.freq = freq;
		spec.format = AUDIO_S16;
		spec.channels = 1;
		spec.samples = length/4;
		spec.callback = playbackCallback;
		SDL_OpenAudio(&spec, NULL);
		SDL_PauseAudio(0);
	}
	wbuffer = buffer;
	wlength = length;
	pos = 0;
}


BOOL APIENTRY DllMain (HINSTANCE hInst     /* Library instance handle. */ ,
                       DWORD reason        /* Reason this function is being called. */ ,
                       LPVOID reserved     /* Not used. */ )
{
    switch (reason)
    {
      case DLL_PROCESS_ATTACH:
        break;

      case DLL_PROCESS_DETACH:
        break;

      case DLL_THREAD_ATTACH:
        break;

      case DLL_THREAD_DETACH:
        break;
    }

    /* Returns TRUE on success, FALSE on failure */
    return TRUE;
}
