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

#include "waveio.h"

/**********  Compute Normalized Average Sample Power in a SOUNDFILE   */

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

    fileIn = opensoundin(argv[1],&hdr);
    if (fileIn)      {
        length = hdr.dlength / 2;
        norm = 1.0 / length / 32767.0 / 32767.0;
        while(length-- > 0)     {
            fread(&data,2,1,fileIn);
            temp = data*data;
	    power += temp;
        }
        power = power * norm;
        printf("Avg sample power in file %s is: %f\n",argv[1],power);
    }
    else {
       printf("File Problems\n");
    }
    fclose(fileIn);

    return 1;
}
