/*
  PCM WAV Uncompressed I/O Library - Main File
  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 <string.h>
#include <stdlib.h>
#include "pcm.h"
#include "filters.h"

int main (int argc, char *argv[]) {

  if (argc != 4) {
    printf("filter - a quick prog to learn PCM WAV filtering\nThis is free software, you are welcome to redistribute it under the terms of the GNU GPL\n\nUsage: %s wavfile resultfile filter\n", argv[0]);
    return 1;
  }
  
  /* Read file */
  printf("Read data: ");
  struct wavheader wavfile;
  char *data;
  read_wav(&data, &wavfile, argv[1]);
  
  if (wavfile.id == PCM_RIFF && wavfile.format == PCM_FORMAT && wavfile.audio_format == 1) {
    printf("This is PCM WAV, %dHz, %dbit, %d channel(s), %d seconds, %d bytes raw audio data\n",
            wavfile.sample_rate, wavfile.bits_per_sample, wavfile.num_channels, calculate_time(wavfile), wavfile.data_size);
    printf("%s Done\n", argv[1]);
    
    /* Filter calls */
    printf("Call filter: ");
    char *out = NULL;
    struct wavheader outfile;
    if (strcmp(argv[3], "echo") == 0) {
      printf("Echo ");
      filter_echo(&out, &outfile, data, wavfile, 300, 30);
    } else if (strcmp(argv[3], "backwards") == 0) {
      printf("Backwards ");
      filter_backwards(&out, &outfile, data, wavfile);
    } else if (strcmp(argv[3], "stretch") == 0) {
      printf("Stretch ");
      filter_stretch(&out, &outfile, data, wavfile, 50);
    }
    if (out == NULL) {
      fprintf(stderr, "Filter error: %s\n", argv[1]);
      return 4;
    }
    printf("Done\n");

    /* Write file */
    printf("Write file: ");
    write_wav(out, outfile, argv[2]);
    printf("%s Done\n", argv[2]);
    
    printf("Free used memory: ");
    free(data);
    free(out);
    printf("Done\n");
    
  } else {
    fprintf(stderr, "This is not PCM WAV: %s\n", argv[1]);
    return 5;
  }
    
  return 0;
}