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

#include <iostream>
#include "Oscillator.h"

static const char *inFile = "/Users/samb/Sound/raw/3FX00006.raw";
static const char *outFile = "./out.log";

void Test_Norm () {
	static const int frameLength = 320;
	
	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(inFile, "rb")) == NULL) {
		printf("file open error : %s\n", inFile);
		return;
	}

	if((fhOut = fopen(outFile, "wb")) == NULL) {
		printf("file open error : %s\n", outFile);
		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\n", frame, power);
		
		frame++;
	}
}

void Test_Oscillator () {
	Oscillator osc(1024);
	FILE *fh;
	FILE *foh;
	
	if((fh = fopen("OscillatorTestOut.pcm", "rb")) == NULL) {
		printf("file open error OscillatorTestOut\n");
		return;
	}

	if((foh = fopen("out.pcm", "wb")) == NULL) {
		printf("file open error %s\n", "out.pcm");
		return;
	}
	
	for(int i = 0 ; i < 44100; i++) {
		short value = (short)(osc.UpdateWithLinearInterpolation(1) * 0x3fff);
		//short value = (short)(osc.UpdateWithoutInterpolation(0.1f) * 0x7fff);
		
		fwrite(&value, sizeof(short), 1, foh);
	}
}

int main(int argc, char *argv[])
{
	std::ios::sync_with_stdio();
	// Test Routine
 	Test_Oscillator(); // segmentation error!
//	Test_Norm();
	
	return 0;
}
