/* nag_tsa_auto_corr_part (g13acc) 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, nl, nvl;
  NagError fail;
  double   *ar = 0, *p = 0, *r = 0, *v = 0;

  INIT_FAIL(fail);

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

  if (nl > 0 && nk > 0 && nl <= nk)
    {
      if (!(ar = NAG_ALLOC(nl, double)) ||
          !(p = NAG_ALLOC(nl, double)) ||
          !(r = NAG_ALLOC(nk, double)) ||
          !(v = NAG_ALLOC(nl, double)))
        {
          printf("Allocation failure\n");
          exit_status = -1;
          goto END;
        }
    }
  else
    {
      printf("Invalid nl or nk.\n");
      exit_status = 1;
      return exit_status;
    }
  for (i = 0; i < nk; ++i)
    scanf("%lf", &r[i]);

  /* nag_tsa_auto_corr_part (g13acc).
   * Partial autocorrelation function
   */
  nag_tsa_auto_corr_part(r, nk, nl, p, v, ar, &nvl, &fail);

  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_tsa_auto_corr_part (g13acc).\n%s\n",
              fail.message);
      exit_status = 1;
    }
  if (fail.code == NE_CORR_NOT_POS_DEF)
    printf("   Only %2ld valid sets were generated\n\n", nvl);
  if (fail.code == NE_NOERROR || fail.code == NE_CORR_NOT_POS_DEF)
    {
      printf("\n Lag  Partial    Predictor error  Autoregressive\n");
      printf("      autocorrn  variance ratio   parameter\n\n");
      for (i = 0; i < nvl; ++i)
        printf(" %2ld%9.3f%16.3f%14.3f\n", i+1, p[i], v[i],
                ar[i]);
    }
 END:
  NAG_FREE(ar);
  NAG_FREE(p);
  NAG_FREE(r);
  NAG_FREE(v);
  return exit_status;
}