/* file = fft-if.c */ 
/* Nigel Ward, University of Tokyo, April 1994 */

#include "cheap.h" 

/*=============================================================================*/
do_fft(data, start_sample, fft_output)
     float data[], fft_output[];
     int start_sample;
{
  int i;
  float smoothed[SAMPLES_PER_FRAME + 1];
 
  for(i = 0; i < SAMPLES_PER_FRAME; i++)
    /*  multiply by Hamming window, to smooth */
    smoothed[i] = data[start_sample + i]
      * (.54 - .46 * cos(2 * M_PI * (float) i / (float) SAMPLES_PER_FRAME)); 
  
  EnergyFFT(smoothed, fft_output, SAMPLES_PER_FRAME);
}

/*-----------------------------------------------------------------------------*/
/* RealFFT produces real and imaginary parts.
   To get the total "energy", take sqrt of sum of squares of real and imag parts
   (is this right? is it the best thing to do?) */
EnergyFFT(data, result, nsamples)
     float data[], result[];
     int nsamples;
{
  float temp[SAMPLES_PER_FRAME];
  int i;

  RealFFT(data, temp, nsamples);
  for (i = 0; i < nsamples; i++)
    /* square root of squares of real and imaginary parts */
    result[i] = sqrt(  (double) (temp[2*i]    *  temp[2*i])   +   
                                (temp[2*i+1]  *  temp[2*i+1]));
}

/* ----------------------------------------------------------------------------- */
/* for testing fft: for example, record a guitar pluck, run it thru FFT, then 
   verify that the peak value in the FFT output appears at the expected frequency */
show_peak(array, length)
     float array[];
     int length;
{
  float max_value = 0.0;
  int max_place = 0;
  int i;
  /* start with i of 3, to avoid unreliable DC values */
  for (i=3;i<length/2;i++)
    if(fabs(array[i]) > max_value) {
      max_value = fabs(array[i]);
      max_place = i;
    }
  printf("  peak value at %d", max_place);
  printf(" (peak value is %6.2f)", max_value);
  printf(" corresponding to %f Hz \n",
	   max_place * ( SAMPLING_RATE / (float) length)  );
}

 /* ============================================================================= */
