#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "dsp_read_write.h"
#include "myfft.h"

int data_ffted[2210];//it contains  after ffted data

int usage()
{
printf("This is whisle,  /dev/dsp control sample program
        choose options
        -1   printing main Frequency of wave.(Hz) this is default
        -0   printing direct ouput data of /dev/dsp\n 
        -h   May I help you? but you alreday done.Now You chose this option\n"
       );
exit(1);
}

int biggest_element( )
{
int most;
int most_biggest_element_number;
int i;

most = data_ffted[1];
most_biggest_element_number = 1 ;

for( i = 1; i < 1105 ; i ++)
  {
    if( data_ffted[i] > most )
      {
	most = data_ffted[i];
	most_biggest_element_number = i ;
      }
  }
return most_biggest_element_number;
}

main( int argc, char **argv)
{
  int mode = 1; // 0 : direct dsp read 1: print most containg frequency of wave
  int i=0;
  int dsp_out;
  int dsp_in;
  unsigned int out_put;
  int zyo=0;
  int count = 0;
  int tmp = 0;
  double datar[2210],datai[2210];
  int ch;
  unsigned  char s[50];

  //  dsp_out = dsp_oopen();
  dsp_in  = dsp_iopen();
  dsp_mono_set(dsp_in);
  dsp_n_bit_set(dsp_in , 8);  
  dsp_n_sampling_rate(dsp_in , 8000);
  
  //get the options
  while((ch=getopt(argc, argv, "dfh"))!=EOF){
    switch(ch){
    case 'd':
      mode = 1;
      break;
    case 'f':
      mode = 0;
      break;


    }
  }




  for( zyo=0 ; zyo < 2210 ; zyo++)
    {
      data_ffted[zyo] = 0;
      datar[zyo] = 0;
       datai[zyo] = 0;
    }
   
  zyo=0;
  count = 0;
    while(1)
      {
	 
	 
	memset( s, '\0', 50);
	dsp_getn(1, dsp_in, s);

	out_put =   (unsigned int)(s[0]);
	datar[count]= (double)(int)(out_put -124); //8bit data
	datai[count]= (double)(0);

	if(mode ==0 ) // direct dsp output
	printf("%d\n", (int)(out_put-128)); //8bit data
	 
	count++;

	if( count >= 2210)
	  {
	    myfft(11,datar,datai,-1);
	    
	    for(i=0;i< 1105 ; i++ ){

	      data_ffted[i] = (int)( sqrt ( (datar[i]*datar[i])+(datai[i]*datai[i]) ) );
	      //printf("%d\n", (int)( sqrt ( (datar[i]*datar[i])+(datai[i]*datai[i]) ) ) );
	    }

	    count = 0;

	    if(mode == 1) // 1 : fft print
	    printf("%d Hz  %d \n", (int)(3.9285*biggest_element()), data_ffted[ (int)(3.9285*biggest_element())] );
	    tmp  = (int)(3.9825*biggest_element() );

	    if( tmp > 1000 && tmp < 1100)
	   //   system("kterm &");
	    
	    if( tmp > 1600 && tmp < 1700)
	      system("xmms &");

	  }

      }
  

}







