/* nag_tsa_spectrum_univar_cov (g13cac) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 7, 2002.
 * Mark 7b revised, 2004.
 */

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

int main(void)
{
  /* Scalars */
  double   px;
  Integer  exit_status, i, ic, iw, kc, lf, mtx, mw, nc, ng, nx, nxg;
  NagError fail;

  /* Arrays */
  double   *c = 0, *xg = 0;
  double   stats[4];


  INIT_FAIL(fail);

  exit_status = 0;

  printf(
          "nag_tsa_spectrum_univar_cov (g13cac) Example Program Results\n");

  /* Skip heading in data file */
  scanf("%*[^\n] ");
  scanf("%ld%ld%*[^\n] ", &nx, &nc);

  if (nx > 0 && nc > 0)
    {
      mtx = 1;
      px = 0.1;
      iw = 4;
      mw = 100;
      ic = 0;
      kc = 360;
      lf = 200;

      if (ic == 0)
        nxg = MAX(kc, lf);
      else
        nxg = lf;

      /* Allocate memory */
      if (!(c = NAG_ALLOC(nc, double)) ||
          !(xg = NAG_ALLOC(nxg, double)))
        {
          printf("Allocation failure\n");
          exit_status = -1;
          goto END;
        }

      for (i = 1; i <= nx; ++i)
        scanf("%lf", &xg[i-1]);
      scanf("%*[^\n] ");

      /* nag_tsa_spectrum_univar_cov (g13cac).
       * Univariate time series, smoothed sample spectrum using
       * rectangular, Bartlett, Tukey or Parzen lag window
       */
      nag_tsa_spectrum_univar_cov(nx, mtx, px, iw, mw, ic, nc, c, kc, lf,
                                  Nag_Unlogged, nxg, xg, &ng, stats, &fail);
      if (fail.code != NE_NOERROR)
        {
          printf(
                  "Error from nag_tsa_spectrum_univar_cov (g13cac).\n%s\n",
                  fail.message);
          exit_status = 1;
          goto END;
        }

      printf("\n");

      printf("Covariances\n");
      for (i = 1; i <= nc; ++i)
        {
          printf("%11.4f", c[i-1]);
          if (i % 6 == 0 || i == nc)
            printf("\n");
        }
      printf("\n");
      printf("Degrees of freedom =%4.1f      Bandwidth =%7.4f\n",
              stats[0], stats[3]);
      printf("\n");
      printf("95 percent confidence limits -     Lower =%7.4f  "
              "Upper =%7.4f\n", stats[1], stats[2]);
      printf("\n");
      printf("      Spectrum      Spectrum      Spectrum"
              "      Spectrum\n");
      printf("      estimate      estimate      estimate"
              "      estimate\n");
      for (i = 1; i <= ng; ++i)
        {
          printf("%4ld%10.4f", i, xg[i-1]);
          if (i % 4 == 0 || i == ng)
            printf("\n");
        }
    }

 END:
  NAG_FREE(c);
  NAG_FREE(xg);

  return exit_status;
}