#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// oslib
#include "os.h"
#include "osmodule.h"
#include "OS:h.sound"

// this source file handles playback through the 16 bit internal Acorn soundcard


static int sound_claimed = 0;
static void *address, *arg;
static int previoussamplerate;


void linearhandler_stop() {

  void *oldcode, *oldarg;

  if (!sound_claimed)  return;
  sound_claimed = 0;

  // read current handler
  xsound_linear_handler(0, NULL, NULL, &oldcode, &oldarg);
  if ((oldcode == address) && (oldarg == arg)) {
    xsound_linear_handler(1, NULL, NULL, NULL, NULL);
    xsoundsamplerate_select(previoussamplerate, NULL, NULL);
  }
}


int linearhandler_start(int freq, void *fillcode, void *parameter) {

  int rateindex, nsr, prevrate, sr, rate;

  if (freq < 4000 || freq > 50000)  return -1;
  if (sound_claimed)  return -1;

  // make sure 16 bit sound is supported
  if (xsoundsamplerate_read_count(&nsr))  return -1;

  // find the best playback-frequency
  rateindex = -1;
  xsoundsamplerate_lookup(1, &prevrate);
  prevrate = prevrate >> 10;

  for (sr = 2; sr <= nsr; sr++) {
    xsoundsamplerate_lookup(sr, &rate);
    rate = rate >> 10;
    if ((rateindex == -1) && (prevrate < freq) && (rate >= freq))
        rateindex = sr;
    prevrate = rate;
  }
  if (rateindex == -1)  return -1;

  // select samplerate
  xsoundsamplerate_read_current(&previoussamplerate, NULL);
  xsoundsamplerate_select(rateindex, NULL, NULL);

  address = fillcode;
  arg = parameter;

  xsound_linear_handler(1, address, arg, NULL, NULL);
  sound_claimed = 1;

  return 0;
}
