#include <sys/bios.h>

/* from a3 to g#5 */
int pitch[36] = {
   1612, 1636, 1659, 1681, 1702, 1721, 1739, 1757, 1773, 1789, 1803, 1817, 
   1830, 1842, 1854, 1864, 1875, 1882, 1894, 1902, 1911, 1918, 1925, 1932, 
   1939, 1945, 1951, 1956, 1961, 1966, 1971, 1975, 1979, 1983, 1987, 1990
};

unsigned char wave[16] = {
   0xa8, 0xdc, 0xee, 0xef, 0xde, 0xbc, 0x9a, 0x89, 
   0x67, 0x56, 0x34, 0x12, 0x01, 0x11, 0x32, 0x75
};

unsigned char envelope[32] = {
   15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0,  
   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};

int sound_count[4];
int note_length[4];

void init_sound() {
   int channel;

   sound_init();

   for (channel=0; channel<4; channel++) {
      sound_set_volume(channel, 0);
      sound_set_wave(channel, wave);
      sound_count[channel] = 0;
      note_length[channel] = 0;
   }
   sound_set_channel(0x0f);
   sound_set_output(0x0f);
}


void put_note(int channel, int note, int length) {
   sound_count[channel] = 0;
   note_length[channel] = length;
   sound_set_pitch(channel, pitch[note]);
}

void remove_note(int channel) {
   sound_set_volume(channel, 0);
   sound_count[channel] = 0;
   note_length[channel] = 0;
}

void process_notes() {
   int channel;
   for(channel=0; channel<4; channel++) {
      if (sound_count[channel] < note_length[channel]) {
	 if (sound_count[channel]<32) 
	   sound_set_volume(channel, envelope[sound_count[channel]]*0x11);
	 else
	   sound_set_volume(channel, 0);
	 sound_count[channel]++;
	 if (sound_count[channel] >= note_length[channel])
	   remove_note(channel);
      }
   }
}
