#include <v_lib.h>

#define	SAMPLE_RATE (11025)

V_LOCAL	void
GenerateSines(
	vec_t *ReOut,
	u32_t samples,
	u32_t channels,
	vec_t freqs[],vec_t volumes[],vec_t *phase_info)
{
	u32_t s,c;
	vec_t out;
	vec_t *phase=(vec_t*)alloca(channels * sizeof(vec_t));
	vec_t *dph=(vec_t*)alloca(channels * sizeof(vec_t));
	vec_t *amp=(vec_t*)alloca(channels * sizeof(vec_t));
	if(phase_info)
		memCopy(phase,phase_info,channels * sizeof(vec_t));
	else
		memZero(phase,channels * sizeof(vec_t));
	for(c=0;c<channels;c++)
	{
		amp[c] = volumes[c] / (vec_t)channels;
		dph[c] = M_2PI * freqs[c] / (vec_t)SAMPLE_RATE;
	}
	for(s=0;s<samples;s++)
	{
		out = 0;
		for(c=0;c<channels;c++)
		{
			out += amp[c] * (vec_t)sin(phase[c]);
			phase[c]+=dph[c];
		}
		if(out < -1)
			out = -1;
		else
			if(out > 1)
				out = 1;
		ReOut[s]=out;
	}
	if(phase_info)
		memCopy(phase_info,phase,channels * sizeof(vec_t));
}

V_LOCAL	void
DumpSignal(FILE *out,vec_t *buf,int nsamples)
{
	int i;
	for(i=0;i<nsamples;i++)
		fprintf(out,"%8u\t%g\n",i,buf[i]);
}

int main()
{
	u32_t i;
	u32_t start;
	vhandle_t ctx;
	unsigned p = 16;
	unsigned len = 1 << p;
	vec_t *buf,freqs[10],volumes[10];
	ctx = fftCreateContext(p,true);
	
	buf = (vec_t*)memAlloc(len * sizeof(vec_t));
	
	freqs[0]=100;
	volumes[0]=0.5f;
	freqs[1]=300;
	volumes[1]=0.25f;
	freqs[2]=900;
	volumes[2]=0.05f;
	GenerateSines(buf,len,3,freqs,volumes,NULL);
	
	puts("FFT");

	start = timeTickCount();
	for(i = 0;i < 10;i++)
	{
		fftForward(ctx,buf);
		fftInverse(ctx,buf);
	}
	start = timeTickCount() - start;
//	DumpSignal(stdout,buf,len);

	printf("Done: %u ms per %uk block\n",start / 20,len / 1024);

	memFree(buf);
	return 0;
}

