#include "bootpack.h"

char *wave_wav;

extern char *pcm_buffer;

void beep_task(void)
{
	int next_beep = 0;
	int end_beep = 0;
	int play_flag = 0;
	
	int i;
	int *fat;
	struct BOOTINFO *binfo = (struct BOOTINFO *) ADR_BOOTINFO;
	struct TASK *task = task_now();
	struct MEMMAN *memman = (struct MEMMAN *) MEMMAN_ADDR;
	struct BEEP_REQ *beep_req = 0;
	struct TIMER *timer;
	struct FILEINFO *finfo;
	
	fat = (int *) memman_alloc_4k(memman, 4 * 2880);
	file_readfat(fat, (unsigned char *) (ADR_DISKIMG + 0x000200));
	task->fat = fat;
	
	for(;;) {
		if (fifo32_status(&task->fifo) == 0) {
			task_sleep(task);
		} else {
			i = fifo32_get(&task->fifo);
			if(i == 256 || i == 257) {
				play_flag = i - 256;
				next_beep = 0;
			}
			if(i >= 512 && i <= 1024 + 512 - 1) {
				//binfo->vram[0] = 0x00;
				//binfo->vram[1] = 0x00;
				//binfo->vram[2] = 0xff;
				end_beep = i - 512;
			}
			if(i == 3) {
				beep_req = (struct BEEP_REQ *) fifo32_get(&task->fifo);
			}
			if(i == 4) {
				next_beep++;
				play_beep(0);
			}
			
			if(play_flag == 1 && beep_req != 0 && next_beep < end_beep) {
				timer_settime(timer, beep_req[next_beep].time);
				play_beep(beep_req[next_beep].freq);
			}
		}
	}
}

int block = 0;

void play_beep(int freq)
{
	int i;
	
	if (freq == 0) {
		i = io_in8(0x61);
		io_out8(0x61, i & 0x0d);
	} else {
		i = 1193180000 / (freq*1000);
		io_out8(0x43, 0xb6);
		io_out8(0x42, i & 0xff);
		io_out8(0x42, i >> 8);
	}
}
