
/* program to calculate Fourier coefficients for a given repeating bit 
   pattern, approximating the integrals by using the trapezoidal method

   compilation:

      g++ -g -o anbn AnBn.C

   usage:

      anbn max_n bit_pattern

   where max_n is the number of harmonics

   for example, to find the coefficients up through the 5th harmonic for
   the pattern 10110110101... (i.e. 101 keeps repeating), type

      anbn 5 1 0 1

   note that the coefficients depend only on the bit pattern, and
   are independent of the units of time, e.g. microseconds vs.
   milliseconds; thus the period T can be taken to be 1 unit of
   time (though the value of T in terms of number of bit is
   still important); note that this means that the coefficients 
   are independent of the bit transmission rate 

   so for example if our repeating bit pattern is 101, so that the
   period's length in units of bits (not units of time) is 3, then
   our signal x(t) will have the value +1 from 0 to 0.33333..., -1
   from 0.33333... to 0.66666, +1 from 0.66666 to 1.00000, etc.

   (since we are doing numerical integration, there is no need to
   shift x(t) in an attempt to exploit symmetries and save work in
   integration)

*/

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

#define pi 3.14159265

#define n_rectangles 100000

float c(float t, int n)

{  return cos(2*pi*n*t);  }

float s(float t, int n)

{  return sin(2*pi*n*t);  }

main(int argc, char **argv)

{  int i,r,bit_number,max_n,sum_bits,bit_period,xt,*bits;  
   float ia,ib,mid,width = 1.0 / n_rectangles;  

   max_n = atoi(argv[1]);

   bit_period = argc - 2;
   bits = new int[bit_period];
   sum_bits = 0;
   for (i = 0; i < bit_period; i++)  {
      bits[i] = atoi(argv[2+i]);
      sum_bits += bits[i];
   }

   printf("a0 = %f\n",width*sum_bits); 
   
   for (i = 1; i <= max_n; i++)  {
      ia = ib = 0.0;
      for (r = 0; r < n_rectangles; r++)  {
         mid = (r+0.5)*width;
	 bit_number = (int) (mid*bit_period);
         xt = bits[bit_number]; if (xt == 0) xt = -1;
         ia += width * xt * c(mid,i);
         ib += width * xt * s(mid,i);
      }
      printf("a%i = %f,  b%d = %f\n",i,2*ia,i,2*ib); 
   }
}

