#include "FftContainer.h"

template <int N>
FftContainer<N>::FftContainer() :
	plan_r2c(NULL),
	plan_c2r(NULL),
	bufferIndex(0),
	manipulation(NULL)
{
	plan_r2c = fftw_plan_dft_r2c_1d(N, timeSigBuffer, freqSigBuffer, FFTW_ESTIMATE);
	plan_c2r = fftw_plan_dft_c2r_1d(N, freqSigBuffer, timeSigOutBuffer, FFTW_ESTIMATE);

	memset(timeSigBuffer, 0, sizeof(timeSigBuffer));
	memset(freqSigBuffer, 0, sizeof(freqSigBuffer));
	memset(timeSigOutBuffer, 0, sizeof(timeSigOutBuffer));
}

template <int N>
FftContainer<N>::~FftContainer()
{
	fftw_destroy_plan(plan_r2c);
	fftw_destroy_plan(plan_c2r);
}

template <int N>
double FftContainer<N>::tick(double inValue)
{
	double outValue = 0;
	
	// TODO buffering timeSigBuffer <- value
	
	timeSigBuffer[bufferIndex++] = inValue;

	outValue = freqSigBuffer[bufferIndex++];
	
	if(bufferIndex == N) {
		bufferIndex = 0;
	
		fftw_execute(plan_r2c);

		// change complex signal
		// TODO manipulate
		if(manipulation != NULL) {
			manipulation->exec(freqSigBuffer);
		}
	
		fftw_execute(plan_c2r);

		// TODO buffering output time signal buffer
	}

	return outValue;
}
