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

#include "waveio.h"

/**********  Apply Gain to a SOUNDFILE   */

int main(int argc,char *argv[])
{
    FILE *fileIn, *fileOut;
    float gain;
    short data;
    long length;
    struct soundhdr hdr;
    
    if (argc!=4) {
        fprintf(stderr,"usage: gain GainAmt filein.wav/snd fileout.wav/snd\n");
        fprintf(stderr,"       GainAmt is a float, 1.0 = leave it alone\n");
        exit(0);
    }
    gain = atof(argv[1]);
    fileIn = opensoundin(argv[2],&hdr);
    fileOut = opensoundout(argv[3],&hdr);
    if (fileIn && fileOut)      {
        length = hdr.dlength / 2;
        while (length-- > 0)    {
            fread(&data,2,1,fileIn);
            data *= gain;
            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;
}

