/* nag_convolution_real (c06ekc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 1, 1990.
 * Mark 8 revised, 2004.
 */

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

int main(void)
{
  Integer  exit_status = 0, j, n;
  NagError fail;
  double   *xa = 0, *xb = 0, *ya = 0, *yb = 0;

  INIT_FAIL(fail);

  printf("nag_convolution_real (c06ekc) Example Program Results\n");
  /* Skip heading in data file */
  scanf("%*[^\n]");
  while (scanf("%ld", &n) != EOF)
    {
      if (n > 1)
        {
          if (!(xa = NAG_ALLOC(n, double)) ||
              !(xb = NAG_ALLOC(n, double)) ||
              !(ya = NAG_ALLOC(n, double)) ||
              !(yb = NAG_ALLOC(n, double)))
            {
              printf("Allocation failure\n");
              exit_status = -1;
              goto END;
            }
        }
      else
        {
          printf("Invalid n.\n");
          exit_status = 1;
          return exit_status;
        }
      for (j = 0; j < n; ++j)
        {
          scanf("%lf%lf", &xa[j], &ya[j]);
          xb[j] = xa[j];
          yb[j] = ya[j];
        }
      /* nag_convolution_real (c06ekc).
       * Circular convolution or correlation of two real vectors
       */
      nag_convolution_real(Nag_Convolution, n, xa, ya, &fail);
      if (fail.code != NE_NOERROR)
        {
          printf("Error from nag_convolution_real (c06ekc).\n%s\n",
                  fail.message);
          exit_status = 1;
          goto END;
        }
      /* nag_convolution_real (c06ekc), see above. */
      nag_convolution_real(Nag_Correlation, n, xb, yb, &fail);
      if (fail.code != NE_NOERROR)
        {
          printf("Error from nag_convolution_real (c06ekc).\n%s\n",
                  fail.message);
          exit_status = 1;
          goto END;
        }
      printf("\n          Convolution   Correlation\n\n");
      for (j = 0; j < n; ++j)
        printf("%5ld %13.5f %13.5f\n", j, xa[j], xb[j]);
 END:
      NAG_FREE(xa);
      NAG_FREE(xb);
      NAG_FREE(ya);
      NAG_FREE(yb);
    }
  return exit_status;
}