#include<memory.h>
#include<SDL.h>
#include<stdio.h>
#include"pcspkr.h"

/* TODO: not all things should be ints/doubles */

unsigned int wldiv2;
unsigned int wl; 
unsigned int t = 0;



/* the current algorithm is simply creating a wave like this:
 * 
 *
 *      -------
 *      |     
 *      |     
 *      |     
 *      |     
 *-------     
 *
 * and this pattern repeats...
 */


/* the old algorithm is simple integer division based on
 * assuming triangular lines which are modulus'd by 256
 * (why???)
 * the equation is:
 * x(t) = -AMP + t * (2 * AMP) / (wl / 2)
 *
 *
 * where wl equals FREQ / freq
 *
 * where FREQ <--> audio frequency
 * requested sound frequency
 */


void audio_callback(void *bla,Uint8 *stream,int len)
{
	/* TODO: unefficient? */
	if (wldiv2)
	{
		while(len)
		{
			if (t < (wldiv2))
				*stream = -AMP;
			else if (t < wl)
				*stream = +AMP;
			else 
				t = -1;
				
			stream++;
			len--;
			t++;
		
		}
	}
	else
	{
		memset(stream,0,len);
	}
}


void pcspkr_sound(unsigned int _wl)
{
	if (_wl == 0) _wl = 0x10000;
	wl = _wl / 52;
	wldiv2 = wl / 2;
	t = 0;
	SDL_PauseAudio(0);
}

void init_pcspkr()
{
	SDL_AudioSpec desired;
	
	SDL_Init(SDL_INIT_AUDIO);
	desired.freq = 22050;
	desired.format = AUDIO_S8;
	desired.samples = 128;
	desired.callback = audio_callback;
	desired.userdata = NULL;
	desired.channels = 1;
		
	if (SDL_OpenAudio(&desired,NULL))
	{
		puts("error");
		printf("%s\n",SDL_GetError());
	}


}

void pcspkr_nosound()
{
	SDL_PauseAudio(1);
}


