#include <cstdio>
#include <snd.h>
#include "pcmloader.h"

using std::pair;

void PcmData::play()
{
  SND_SetVoice(SND_GetFirstUnusedVoice(), // voice
               VOICE_MONO_8BIT, // format
               8000, // frequency
               0, // delay
               buf, // PCM data
               len, // data length
               255, // left volume
               255, // right volume
               NULL); // callback
}


PcmData *PcmLoader::get(const char *filename)
{
  string key(filename);
  map<string,PcmData*>::iterator it;
  it = pcms.find(key);
  if(it == pcms.end())
    return NULL;
  
  return it->second;
}

int PcmLoader::readfile(const char *filename, char **pBuf)
{
  FILE *file;
  int len;
  
  if(!pBuf)
    return 0;
  
  file = fopen(filename, "r");
  if(!file)
    return 0;
  
  fseek(file,0,SEEK_END);
  len = ftell(file);
  fseek(file,0,SEEK_SET);
  *pBuf = (char*)malloc(len+1);
  if(!*pBuf) {
    fclose(file);
    return 0;
  }

  fread(*pBuf, len, 1, file);
  fclose(file);
  
  return len;
}

PcmData *PcmLoader::load(const char *filename)
{
  map<string,PcmData*>::iterator it;
  string key(filename);
  char *buf;
  int len;
  
  len = readfile(filename, &buf);
  if(!len) {
    it = pcms.find(key);
    if(it == pcms.end())
      return NULL;
    return it->second;
  }

  PcmData *newpcm = new PcmData(buf,len);

  it = pcms.find(key);
  if(it != pcms.end()) {
    delete it->second;
    pcms.erase(it);
  }
  
  pair<string,PcmData*> pr(key,newpcm);
  pcms.insert(pr);
  return newpcm;
}
