/* nag_tsa_spectrum_bivar (g13cdc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 4, 1996.
 * Mark 8 revised, 2004.
 *
 */

#include <nag.h>
#include <stdio.h>
#include <nag_stdlib.h>
#include <naga02.h>
#include <nagg13.h>

#define L      80
#define KC     8*L
#define NXYMAX 300

int main(void)
{

  Complex  *g;
  Integer  exit_status = 0, i, is, j, kc = KC, l = L, mw, ng, nxy;
  NagError fail;
  double   pw, pxy, *x = 0, *y = 0;

  INIT_FAIL(fail);

  printf("nag_tsa_spectrum_bivar (g13cdc) Example Program Results\n");

  /* Skip heading in data file */
  scanf("%*[^\n] ");
  scanf("%ld ", &nxy);
  if (nxy > 0 && nxy <= NXYMAX)
    {
      if (!(x = NAG_ALLOC(KC, double)) ||
          !(y = NAG_ALLOC(KC, double)))
        {
          printf("Allocation failure\n");
          exit_status = -1;
          goto END;
        }
      for (i = 1; i <= nxy; ++i)
        scanf("%lf ", &x[i - 1]);
      for (i = 1; i <= nxy; ++i)
        scanf("%lf ", &y[i - 1]);

      /* Set parameters for call to nag_tsa_spectrum_bivar (g13cdc) */
      /* Mean correction and 10 percent taper */
      pxy = 0.1;
      /* Window shape parameter and zero covariance at lag 16 */
      pw = 0.5;
      mw = 16;
      /* Alignment shift of 3 */
      is = 3;

      /* nag_tsa_spectrum_bivar (g13cdc).
       * Multivariate time series, smoothed sample cross spectrum
       * using spectral smoothing by the trapezium frequency
       * (Daniell) window
       */
      nag_tsa_spectrum_bivar(nxy, Nag_Mean, pxy, mw, is, pw, l, kc, x, y, &g,
                             &ng, &fail);
      if (fail.code != NE_NOERROR)
        {
          printf("Error from nag_tsa_spectrum_bivar (g13cdc).\n%s\n",
                  fail.message);
          exit_status = 1;
          goto END;
        }

      printf("\n                       Returned sample spectrum\n");
      printf("\n       Real  Imaginary       Real  Imaginary   "
              "    Real  Imaginary\n");
      printf("       part     part         part     part     "
              "    part     part\n\n");
      for (j = 1; j <= ng; ++j)
        printf("%5ld%8.4f%9.4f%s",
                /* nag_complex_real (a02bbc).
                 * Real part of a complex number
                 */
                j, nag_complex_real(g[j - 1]), a02bcc(g[j - 1]),
                (j%3 == 0?"\n":""));
      printf("\n");
      NAG_FREE(g);
    }
 END:
  NAG_FREE(x);
  NAG_FREE(y);
  return exit_status;
}