/*
  PCM WAV Uncompressed I/O Library - PCM WAV Format
  T3 - Fontys Hogescholen
  Copyright 2006 Joris van Rooij

  This program is free software; you can redistribute it and/or
  modify it under the terms of the GNU General Public License
  as published by the Free Software Foundation; either version 2
  of the License, or (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include "pcm.h"

unsigned int calculate_time (const struct wavheader wavfile) {
  return wavfile.data_size / (wavfile.num_channels * wavfile.sample_rate * (wavfile.bits_per_sample / 8));
}

void read_wav (char **data, struct wavheader *wavfile, char *filename) {
  FILE *rawwav = fopen(filename, "rb");

  if (rawwav == NULL) {
    fprintf(stderr, "Could not open PCM WAV file: %s\n", filename);
    return;
  }
  fread(wavfile, sizeof(struct wavheader), 1, rawwav);
  if (wavfile->id == PCM_RIFF && wavfile->format == PCM_FORMAT && wavfile->audio_format == 1) {
    *data = malloc(wavfile->data_size);
    if (*data == NULL) {
      fprintf(stderr, "Out of memory: %s\n", filename);
      return;
    }
    fseek(rawwav, sizeof(struct wavheader), SEEK_SET);
    fread(*data, 1, wavfile->data_size, rawwav);
  } else
    *data = NULL;
  fclose(rawwav);
}

void write_wav (const char *data, const struct wavheader wavfile, const char *filename) {
  FILE *outwav = fopen(filename, "wb+");
  if (outwav == NULL) {
    fprintf(stderr, "Could not write to file: %s\n", filename);
    return;
  }
  fwrite(&wavfile, 1, sizeof(wavfile), outwav);
  fwrite(data, 1, wavfile.data_size, outwav);
  fclose(outwav);
}