/* nag_tsa_transf_prelim_fit (g13bdc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 7, 2001.
 */

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

int main(void)
{
  /* Scalars */
  double          r0, s;
  Integer         exit_status, i, iwa, nl, nwds;

  /* Arrays */
  double          *r = 0, *wa = 0, *wds = 0;
  Integer         isf[3];
  Nag_TransfOrder transfv;
  NagError        fail;

  INIT_FAIL(fail);

  exit_status = 0;

  printf(
          "nag_tsa_transf_prelim_fit (g13bdc) Example Program Results\n");

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

  if (nl > 0)
    {
      /* Allocate array r */
      if (!(r = NAG_ALLOC(nl, double)))
        {
          printf("Allocation failure\n");
          exit_status = -1;
          goto END;
        }

      for (i = 1; i <= nl; ++i)
        scanf("%lf", &r[i-1]);
      scanf("%*[^\n] ");
      scanf("%ld %ld %ld", &transfv.nag_b, &transfv.nag_q,
             &transfv.nag_p);
      scanf("%lf%*[^\n] ", &s);

      nwds = transfv.nag_q + transfv.nag_p + 1;
      iwa = transfv.nag_p * (transfv.nag_p + 1);

      /* Allocate arrays wa and wds */
      if (!(wa = NAG_ALLOC(iwa, double)) ||
          !(wds = NAG_ALLOC(nwds, double)))
        {
          printf("Allocation failure\n");
          exit_status = -1;
          goto END;
        }

      /* nag_tsa_transf_prelim_fit (g13bdc).
       * Multivariate time series, preliminary estimation of
       * transfer function model
       */
      nag_tsa_transf_prelim_fit(r0, r, nl, &transfv, s, wds, isf, &fail);
      if (fail.code != NE_NOERROR)
        {
          printf(
                  "Error from nag_tsa_transf_prelim_fit (g13bdc).\n%s\n",
                  fail.message);
          exit_status = 1;
          goto END;
        }

      printf("\n");
      printf("Success/failure indicator%4ld%4ld\n",
              isf[0], isf[1]);
      printf("\n");
      printf("Transfer function model B, Q, P =");

      printf("%4ld %4ld %4ld\n", transfv.nag_b, transfv.nag_q,
              transfv.nag_p);

      printf("\n");
      printf("Parameter initial estimates\n");

      for (i = 1; i <= nwds; ++i)
        printf("%10.4f", wds[i-1]);
      printf("\n");
    }

 END:
  NAG_FREE(r);
  NAG_FREE(wa);
  NAG_FREE(wds);

  return exit_status;
}