/* nag_tsa_auto_corr (g13abc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 2, 1991.
 * Mark 8 revised, 2004.
 *
 */

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

int main(void)
{

  Integer  exit_status = 0, i, nk, nx;
  NagError fail;
  double   mean, *r = 0, stat, *x = 0, xv;

  INIT_FAIL(fail);

  printf("nag_tsa_auto_corr (g13abc) Example Program Results\n");
  /* Skip heading in data file */
  scanf("%*[^\n]");
  scanf("%ld %ld", &nx, &nk);

  if (nk > 0 && nx > 1 && nk < nx)
    {
      if (!(r = NAG_ALLOC(nk, double)) ||
          !(x = NAG_ALLOC(nx, double)))
        {
          printf("Allocation failure\n");
          exit_status = -1;
          goto END;
        }
    }
  else
    {
      printf("Invalid nx or nk.\n");
      exit_status = 1;
      return exit_status;
    }
  for (i = 0; i < nx; ++i)
    scanf("%lf", &x[i]);
  printf("\nThe first %2ld coefficients are required\n", nk);

  /* nag_tsa_auto_corr (g13abc).
   * Sample autocorrelation function
   */
  nag_tsa_auto_corr(x, nx, nk, &mean, &xv, r, &stat, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_tsa_auto_corr (g13abc).\n%s\n",
              fail.message);
      exit_status = 1;
      goto END;
    }

  printf("The input array has sample mean %12.4f\n", mean);
  printf("The input array has sample variance %12.4f\n", xv);
  printf("The sample autocorrelation coefficients are\n\n");
  printf("   Lag    Coeff\n");
  for (i = 0; i < 10; ++i)
    printf("%6ld%10.4f\n", i+1, r[i]);
  printf("\nThe value of stat is %12.4f\n", stat);
 END:
  NAG_FREE(r);
  NAG_FREE(x);
  return exit_status;
}