/*
 * loadsamples.c -- read audio files into sample buffers..
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "synth.h"
#include "loadsamples.h"

int readsample(char * filename, waveform * wav) {
  if (readausamples(filename, &wav->samples, &wav->length) != 0)
    return -1; 

  /* this stuff needs to be figured out later */
  wav->repeatstart = 0;
  wav->repeatend = wav->length - 1;
  wav->freq = 440 << FREQSHIFT; 

  return 0;
}


int readausamples(char * filename, short **samp1, unsigned long *len) {
  FILE * ifp;
  aufile_hdr filehdr;
  long fsize, numsamples;

  if ((ifp = fopen(filename, "rb")) == NULL) {
    return -1;
  }

  fread(&filehdr, sizeof(aufile_hdr), 1, ifp);
 
  fseek(ifp, 0, SEEK_END);
  fsize =  ftell(ifp);

  if (filehdr.magic != AUDIO_FILE_MAGIC)
    return -1;

  if (filehdr.encoding != AUDIO_FILE_ENCODING_LINEAR_16) 
    return -1;

  if (filehdr.sample_rate != 44100)
    return -1;

  /* only read a mono file for now.. */
  /* we won't worry about channel 2 yet */
  if (filehdr.channels > 1 || filehdr.channels < 1)
    return -1;

  if (filehdr.data_size == AUDIO_UNKNOWN_SIZE || filehdr.data_size == 0) {
    filehdr.data_size = fsize - filehdr.hdr_size;
  }

  numsamples = filehdr.data_size / (2 * filehdr.channels);
  fseek(ifp, filehdr.hdr_size, SEEK_SET);       

  *len = numsamples;
  *samp1 = malloc(numsamples * sizeof(short)); 
  fread(*samp1, numsamples * sizeof(short), 1, ifp);

  /* we won't worry about channel 2 yet */

  fclose(ifp);
  
  return 0;
}





