#include "gba.h"
#include "sound.h"

void (*IntrTable[14])(void);

void interrupt_dummy(void) {
};

void interrupt_key(void) {
  asm volatile ("\n\
      mov	a1, #0x8c	@ Point at BIOS hard reset.\n\
      bx	a1		@ Go."
  );
}

extern u32 cur_sample, num_samples, sound_playing;
extern u8* loc_sample;

void interrupt_sound(void)
{ 
	u32* s = (u32*)loc_sample;
	if(!sound_playing) return;
	
	if(!(cur_sample & 3))
	{
		u32 sample;
		//= s[cur_sample >> 2];
		sample = loc_sample[cur_sample] << 24 |
			loc_sample[cur_sample + 1] << 16 |
			loc_sample[cur_sample + 2] << 8 |
			loc_sample[cur_sample + 3];

		/*sample = (sample >> 24) | 
			((sample & 0x00ff0000) >> 8) |
			((sample & 0x0000ff00) << 8) |
			(sample << 24);*/
		//sample = ((sample & 0xffff0000) >> 16) | ((sample & 0x0000ffff)<< 16);
		//REG_SOUNDCNT_H |= DSA_FIFO_RESET;
		*((volatile u32*)REG_FIFO_A) = sample;
	}
	cur_sample++;

	if(cur_sample > num_samples)
	{
		//sample finished!,stop Direct sound
		REG_TM0CNT=0; //disable timer 0
		sound_playing = 0;
	}

	//clear the interrupt(s)
	REG_IF |= REG_IF;
};


void interrupt_init(void) {
  int i;

  // Set all interrupts to dummy functions.
  for(i = 0; i < 14; i ++) IntrTable[i] = (void (*)(void))interrupt_dummy;

  // Set selected interrupts to do something fun/useful.
  IntrTable[12] = (void (*)(void))interrupt_key;
	IntrTable[3] =  (void (*)(void))interrupt_sound;
}
