/*
 * GOATTRACKER reSID interface
 */

#include <stdlib.h>

#include "sid.h"
#include "gsound.h"

#define PAL_CLOCK_RATE 985248
#define NTSC_CLOCK_RATE 1022730
SID *sid;

extern "C" {

int clockrate;
int samplerate;

/* "Our" SID registers */
unsigned char sidreg[32];

int sid_created = 0;

void sid_init(int speed, unsigned m, unsigned ntsc);
int sid_fillbuffer(short *ptr, int samples);
void sid_dumpregs(void);

void sid_init(int speed, unsigned m, unsigned ntsc)
{
  int c;

  if (ntsc) clockrate = NTSC_CLOCK_RATE;
    else clockrate = PAL_CLOCK_RATE;
  samplerate = speed;

  if (!sid_created)
  {
    sid = new SID;
    sid_created = 1;
  }
  sid->set_sampling_parameters(clockrate, SAMPLE_FAST, speed, 20000);
  sid->reset();
  for (c = 0; c <= 0x18; c++)
  {
    sidreg[c] = 0x00;
  }
  if (m == 1)
  {
    sid->set_chip_model(MOS8580);
  }
  else
  {
    sid->set_chip_model(MOS6581);
  }
}

int sid_fillbuffer(short *ptr, int samples)
{
  int tdelta = clockrate * samples / samplerate;
  return sid->clock(tdelta, ptr, samples);
}

void sid_dumpregs(void)
{
  int c;
  for (c = 0; c <= 0x18; c++)
  {
    sid->write(c, sidreg[c]);
  }
}

}
