#include <stdio.h>
#include <math.h>

#include "cwaveguide.h"

#define TEST_SAMPLE "3FX00006.raw"

void Test_Norm () {
	static const int frameLength = 320;
	static const char *outPCMName = "TestNormOut.pcm";
	static const char *outPCMName = "TestNormOut.pcm";
	
	FILE *fh, *fhOut;
	short inBuf[frameLength];
	short outBuf[frameLength];
	float fBuf[frameLength];
	int i;
	int num;
	int frame = 0;
	
	float power = 0;

	if((fh = fopen(TEST_SAMPLE, "rb")) == NULL) {
		printf("file open error : %s\n", TEST_SAMPLE);
		return;
	}

	if((fhOut = fopen(outPCMName, "wb")) == NULL) {
		printf("file open error : %s\n", outPCMName);
		return;
	}

	num = fread(&inBuf[0], sizeof(short), frameLength, fh);
	
	while((unsigned int)frameLength == fread(&inBuf[0], sizeof(short), frameLength, fh)) {
		for(i = 0; i < frameLength; i++) {
			fBuf[i] = (float)inBuf[i];
		}

		// calc frame power
		power = 0;
		for(i = 0; i < frameLength; i++) {
			fBuf[i] = (float)inBuf[i];
			power += pow(fBuf[i], 2);
		}
		power /= (float)frameLength;
		fprintf(fhOut, "frame=%04d, power=%f", frame, power);
		
		frame++;
	}
}

void Test_cwaveguide() {
	cwaveguide delay;
	FILE *fh;

	float feedbackValue = 0.9f; // TODO check
	double delayValue = 1024;
	
	if((fh = fopen(TEST_SAMPLE, "rb")) == NULL) {
		printf("file open error : %s\n", TEST_SAMPLE);
		return;
	}

	// TODO open out file handler

	short s;
	while (1 == fread(&s, sizeof(short), 1, fh)) {
		float out = delay.feed(s, feedbackValue, delayValue);

		// TODO write out
		printf("%04x, %f\n", s, out);
	}
	
	fclose(fh);
}

int main(int argc, char *argv[])
{
	// Test Routine
 	Test_cwaveguide();
	Test_Norm();
	
	return 0;
}
