#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sndfile.h>
#include <fftw3.h>
#include <math.h>

int read_wav();
int do_fft();
int samples_read(int);
int samples_fft();
int setup_fft();
int free_fft();
void show_samples();

FILE *fline;

#define SAMPLERATE 12000
int sduration = 2;		// Duration of one set of samples
char audiofile[200] = "test.wav";
int *samplebuf;
int *outputbuf;
int samplesperrun;
int newfile = 1;
int maxlevel = 0;

double *din;
fftw_complex *cpout;
fftw_plan plan;


int main(int argc, char *argv[])
{
	int samplenum = 0;
	int ret,i;
	FILE *ftest,*fw;
	
	strcpy(audiofile,argv[1]);
	
	samplesperrun = SAMPLERATE * sduration;
	samplebuf = malloc(sizeof(int)*samplesperrun);
	outputbuf = malloc(sizeof(int)*(samplesperrun/2 + 1));
	setup_fft();

	// wait until file exists
	printf("wait for wav file %s\n",audiofile);
	while(1)
	{
		ftest = fopen(audiofile,"r");
		if(ftest != 0) 
		{
			fclose(ftest);
			break;
		}
		sleep(1);
	}
	printf("wav file found %s\n",audiofile);

	while(1)
	{
		// read samples from audio file
		//printf("read sample %d\n",samplenum);
		ret = samples_read(samplenum);
		if(ret == -2) 
		{
			//printf("exit \n");
				break;
		}
		else if(ret == -1)
		{	
			//printf("sleep \n");
			sleep(1);
		}
		else
		{
			//printf("decode \n");
			// seek maximum value for level meter
			maxlevel = -999999999;
			for(i=0; i<samplesperrun; i++)
			{
				if(abs(samplebuf[i]) > maxlevel) maxlevel = samplebuf[i];
			}
			
			//printf("Maxlevel: %X\n",maxlevel);
			// store maxlevel
			fw = fopen("wav/maxlevel.out","w");
			if(fw)
			{
				fprintf(fw,"%c",(maxlevel>>24)&0xff);	// we need the highest byte only. max. allowed value= 0x7f
				fclose(fw);
			}
			else
			{
			}
			
			// calculate fft on these samples
			//printf("calc FFT for sample %d\n",samplenum);
			samples_fft();
			//show_samples();
			
			samplenum++;
		}
	}

	
	free_fft();
	free(samplebuf);
	free(outputbuf);
	
	printf("\nexit fft\n");

	return 0;
}

/* 
 * read 12000 samples from WAV file beginning at position samplenum*12000
 * */

int samples_read(int samplenum)
{
SNDFILE *wavfile;
SF_INFO info;
sf_count_t ret;
	
	// open wav file
    wavfile = sf_open(audiofile,SFM_READ,&info);
    if (wavfile == NULL)
    {
        //printf("Failed to open file: %s error\n",audiofile);
        exit(-2);
    }
    
    // go to the end of the requested position
    ret = sf_seek(wavfile,(samplenum+1)*(samplesperrun)-1,SEEK_SET);
	if(ret == -1)
	{
		// no full 1s range available
		return -1;
	}
	
	// go to the requested position
	ret = sf_seek(wavfile,samplenum*samplesperrun,SEEK_SET);
	if(ret == -1)
	{
		// no full 1s range available
		return -2;
	}
	
	// read the samples
	ret = sf_read_int(wavfile,samplebuf,samplesperrun);
	if(ret != samplesperrun) 
	{
		return -2;
	}
	

    sf_close(wavfile);
	return 0;
}

int setup_fft()
{
	printf("alloc input \n");
	din = (double *)malloc(sizeof (double) * samplesperrun);
	
	printf("alloc output \n");
	cpout  = (fftw_complex *)fftw_malloc(sizeof (fftw_complex) * samplesperrun);

	printf("make plan \n");
	plan = fftw_plan_dft_r2c_1d(samplesperrun, din, cpout,FFTW_MEASURE);
	
	return 0;
}

int free_fft()
{
	fftw_destroy_plan(plan);
	free(din);
	fftw_free(cpout);

	return 0;
}

int samples_fft()
{
	int i;
	
	int outcnt;
	double real,imag,mag;

	// copy input data (samples)
	//printf("copy input data \n");
	int j=0;
	for(i=0; i<samplesperrun; i++)
		din[j++] = (double)samplebuf[i];
	
	//printf("execute FFT\n");
	fftw_execute(plan);
	
	outcnt = samplesperrun/2 + 1;
	//printf("outcnt: %d \n",outcnt);
	
	// frequency steps in fft's output
	double fstep = (double)SAMPLERATE / (double)outcnt /(2);
	
	//printf("print output data \n");
	
	double freq=0;
	int line=0;
	int val;
	fline = fopen("wav/dline.out","w");
	for(i=0; i<outcnt; i++)
	{
		real = cpout[i][0];
		imag = cpout[i][1];
		mag = sqrt((real * real) + (imag * imag));
		
		//if(freq>=1300 && freq <=1700)
		{
			val = (int)(mag/100000000);
			if(newfile==1) val=10000; // separator line

			fprintf(fline,"%c",(val>>8)&0xff);
			fprintf(fline,"%c",val&0xff);
			outputbuf[i] = (int)(mag/100000000);
		}
		freq += fstep;
	}
	fclose(fline);
	newfile=0;

}

void show_samples()
{
	int i;
	int maxcols = 100;	// number of cols on screen
	int xpos;
	char c;
	int start = 1400;
	int stop = 1600;

	// we only print the samples from index 2800 to index 3200 (1400-1600 Hz)
	printf("\n");
	for(i=start*sduration; i<stop*sduration; i+=(sduration*2))
	//for(i=2600; i<3000; i+=2)
	{
		//xpos = i - 2800;			// 0..400
		//xpos = (xpos*maxcols)/400;	// 0..100	
		
		if(outputbuf[i] < 100) c=' ';
		else if(outputbuf[i] < 500) c='.';
		else if(outputbuf[i] < 1000) c=':';
		else if(outputbuf[i] < 3000) c='-';
		else if(outputbuf[i] < 5000) c='o';
		else if(outputbuf[i] < 10000) c='x';
		else if(outputbuf[i] < 20000) c='O';
		else c='X';
		
		printf("%c",c);
	}
}
