#include "pcfx.h"
#include "interrupt.h"
#include "timer.h"

static int32 div15;
static uint16 control;
static uint16 period;
static uint16 counter;

// FIXME, we should also run FXTIMER_Run() in FXTIMER_Write16
void FXTIMER_Run(int cycles)
{
 div15 -= cycles;

 while(div15 <= 0)
 {
  div15 += 15;

  if(control & 0x2)
  {
   counter--;
   while(counter <= 0)
   {
    counter += period;
    if(control & 0x1)
    {
     PCFXIRQ_Assert(9, TRUE);
    }
    if(control & 0x4)
    {
     control &= ~0x2;
     break;
    }
     
   }
  }
 }
}

uint16 FXTIMER_Read16(uint32 A)
{
 switch(A & 0xF80)
 {
  case 0xF00: return(control);
  case 0xF80: return(period);
 }
}

void FXTIMER_Write16(uint32 A, uint16 V)
{
 PCFXIRQ_Assert(9, FALSE);

 switch(A & 0xF80)
 {
  case 0xF00: if(!(control & 0x2) && (V & 0x2))
		counter = period;
	      control = V; 
	      break;
  case 0xF80: period = V; break;
 }
}
