#include <stdlib.h>
// #include <malloc.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <assert.h>

#include "waveio.h"

/**********  Remove (most) Mean from a SOUNDFILE   */

int main(int argc,char *argv[])
{
    FILE *fileIn, *fileOut;
    float lastIn = 0.0, lastOut = 0.0;
    short data;
    long length;
    struct soundhdr hdr;
    
    if (argc!=3) {
        fprintf(stderr,"usage: removedc filein.wav fileout.wav\n");
        exit(0);
    }

    fileIn = opensoundin(argv[1],&hdr);
    fileOut = opensoundout(argv[2],&hdr);
    if (fileIn && fileOut)      {
        length = hdr.dlength / 2;
        while (length-- > 0)    {
            fread(&data,2,1,fileIn);
            lastOut = (0.99*lastOut) + ((float) data - lastIn);
            lastIn = data;
            data = lastOut;
            fwrite(&data,2,1,fileOut);
        }
        while(fread(&data,1,1,fileIn))         //  Grumble, RIFF tail
            fwrite(&data,1,1,fileOut);               
    }
    else {
       printf("File Problems\n");
    }
    fclose(fileIn);
    fclose(fileOut);

    return 1;
}

