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

#include "waveio.h"

/**********  Compute Peak Amplitude of a SOUNDFILE   */

int main(int argc,char *argv[])
{
    FILE *fileIn;
    short data,peak=0,abspeak=0;
    long length;
    struct soundhdr hdr;
    
    if (argc!=2) {
        fprintf(stderr,"usage: peak filein.wav\n");
        exit(0);
    }

    fileIn = opensoundin(argv[1],&hdr);
    if (fileIn)      {
        length = hdr.dlength / 2;
        while(length-- > 0)     {
            fread(&data,2,1,fileIn);
            if (abs(data) > abspeak)    {
                abspeak = abs(data);
                peak = data;
            }
        }
        printf("Peak in file %s is: %i (abs=%i)\n",argv[1],peak,abspeak);
    }
    else {
       printf("File Problems\n");
    }
    fclose(fileIn);

    return 1;
}
