/*******************************************************************************
 * cfftTb.c :   testbench of cfft functions
 * author   :   duweitao
 * date     :   2008-June-24th
 * version  :   0.1
 * modify   :   initial version
 ******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include "cfft.h"
int main(void){
  int           N ;
  cfftdata_t*   in;
  cfftdata_t*   out;
  char          t[80];
  double temp1, temp2;

  int err   = 0;
  int idx   = 0;
  handleCfft_t hCfft = NULL;
  FILE *fpIn  = NULL;
  FILE *fpOut = NULL;
  char *fInName  = "fftInputData.txt";
  char *fOutName = "cfftOut.m";
  // open input data file
  fpIn= fopen(fInName, "r");
  if(fpIn == NULL){
    fprintf(stdout, "ERROR, cannot open input file <%s>\n", fInName);
    return 1;
  }
  // get fft length
  fgets(t,80,fpIn);
  sscanf(t, "%d", &N);
  // allocate memory
  in = (cfftdata_t*) malloc(sizeof(cfftdata_t)*N*2);
  memset(in, 0, sizeof(cfftdata_t)*N*2);
  out = (cfftdata_t*) malloc(sizeof(cfftdata_t)*N*2);
  memset(out, 0, sizeof(cfftdata_t)*N*2);

  // get input data
  for(idx = 0; idx < N; idx ++){
    fgets(t, 80, fpIn);
    sscanf(t, "%lf %lf", &temp1, &temp2);
    in[2*idx]   = (cfftdata_t) temp1;
    in[2*idx+1] = (cfftdata_t) temp2;
  }
  // initial handle
  err = CfftInit(N, &hCfft);
  if(err){
    fprintf(stdout,"%s\n", hCfft->errMsg);
    return 1;
  }
  // compute fft
  err = CfftRun(in, out, hCfft);
  if(err){
    fprintf(stdout,"%s\n", hCfft->errMsg);
    return 1;
  }
  // close handle
  CfftClose(hCfft);
  if(hCfft){
   free(hCfft);
   hCfft = NULL;
  }  
  // print the output data in matlab format
  fpOut = fopen(fOutName, "w");
  fprintf(fpOut, "CfftOutData = [\n");
  for(idx = 0; idx < N; idx ++){
    fprintf(fpOut, "  %f%+fj", out[idx*2], out[idx*2+1]);
    if(idx != N-1)
    fprintf(fpOut, ";\n");
  }
  fprintf(fpOut, "];");
  fflush(fpOut);
  fclose(fpOut);

  return 0;
}
