/* nag_sum_fft_realherm_1d (c06pac) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 24, 2013.
 */

#include <nag.h>
#include <stdio.h>
#include <nag_stdlib.h>
#include <nagc06.h>

int main(void)
{
  /* Scalars */
  Integer   exit_status = 0, i, n;
  /* Arrays */
  double    *x = 0, *x_orig, *x_back;
  /* Nag Types */
  NagError  fail;

  INIT_FAIL(fail);

  printf("nag_sum_fft_realherm_1d (c06pac) Example Program Results\n");

  /* Read dimensions of array and array values from data file. */
  scanf("%*[^\n]%ld%*[^\n]", &n);
  if (!(x = NAG_ALLOC(n+2, double)) ||
      !(x_orig = NAG_ALLOC(n, double)) ||
      !(x_back = NAG_ALLOC(n+2, double)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }
  for (i = 0; i < n; i++) {
    scanf("%lf", &x_orig[i]);
    x[i] = x_orig[i];
  }

  /* Compute discrete Fourier transform of real array x using
   * nag_sum_fft_realherm_1d (c06pac).
   */
  nag_sum_fft_realherm_1d(Nag_ForwardTransform, x, n, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_sum_fft_realherm_1d (c06pac).\n%s\n",
             fail.message);
      exit_status = 1;
      goto END;
    }
  
  for (i = 0; i < n + 2; i++) x_back[i] = x[i];
  
  /* Compute inverse discrete Fourier transform of Hermitian array x using
   * nag_sum_fft_realherm_1d (c06pac).
   */
  nag_sum_fft_realherm_1d(Nag_BackwardTransform, x_back, n, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_sum_fft_realherm_1d (c06pac).\n%s\n",
             fail.message);
      exit_status = 2;
      goto END;
    }
   
  printf("\n%2s%7s%22s%17s\n","i","x","z = FFT(x)","InvFFT(z)");
  for (i = 0; i < n; i++) {
    if (i<=n/2) {
      printf("%2ld  %8.5f   (%8.5f, %8.5f )   %8.5f\n", i, x_orig[i],
             x[2*i], x[2*i+1], x_back[i]);
    } else {
      printf("%2ld  %8.5f   (%8.5f, %8.5f )   %8.5f\n", i, x_orig[i],
             x[2*(n-i)], -x[2*(n-i)+1], x_back[i]);
    }
  }
 END:
  NAG_FREE(x);
  NAG_FREE(x_orig);
  NAG_FREE(x_back);

  return exit_status;
}