/* L-14 MCS 572 Fri 23 Sep 2016 : fftw_use.c.
 * The simple program below illustrates an application of FFTW
 * (the fastest Fourier Transform in the West) to signal processing. */

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

double my_signal ( double t );
/* 
 * Defines a signal composed of 
 * a cosine of frequency 4 and amplitude 2, 
 * a sine of frequency 10 and amplitude 5. */

void sample_signal 
 ( double f ( double t ), int m,
   double *x, double *y );
/*
 * Takes m = 2^k samples of the signal f,
 * returns abscisses in x and samples in y. */

int main ( int argc, char *argv[] )
{
   const int n = 256;
   double *x, *y;
   x = (double*)calloc(n,sizeof(double));
   y = (double*)calloc(n,sizeof(double));
   sample_signal(my_signal,n,x,y);

   int m = n/2+1;
   fftw_complex *out;
   out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*m);

   fftw_plan p;
   p = fftw_plan_dft_r2c_1d(n,y,out,FFTW_ESTIMATE);
   fftw_execute(p);

   printf("scanning through the output of FFTW...\n");
   double tol = 1.0e-8;  /* threshold on noise */
   int i;
   for(i=0; i<m; i++)
   {
      double v = fabs(out[i][0])/(m-1)
               + fabs(out[i][1])/(m-1);
      if(v > tol)
      {
         printf("at %d : (%.5e,%.5e)\n",i,out[i][0],out[i][1]);
         printf("=> frequency %d and amplitude %.3e\n", i,v);
      }
   }

   return 0;
}

double my_signal ( double t )
{
   double s1 = 2.0*cos(4.0*2.0*M_PI*t);
   double s2 = 5.0*sin(10.0*2.0*M_PI*t);
   return s1+s2;
}

void sample_signal 
 ( double f ( double t ), int m,
   double *x, double *y )
{
   int i;
   double h = 1.0/m;
   for(i=0; i<m; i++) 
   {
      x[i] = i*h;
      y[i] = f(x[i]);
   }
}
