/* nag_2d_cheb_eval (e02cbc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 7, 2001.
 * Mark 7b revised, 2004.
 */

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

int main(void)
{
  /* Scalars */
  double   x1, xm, xmax, xmin, y, ymax, ymin;
  Integer  exit_status, i, j, k, l, m, n, ncoef, one;
  NagError fail;

  /* Arrays */
  double   *a = 0, *ff = 0, *x = 0;

  INIT_FAIL(fail);

  exit_status = 0;
  printf("nag_2d_cheb_eval (e02cbc) Example Program Results\n");

  /* Skip heading in data file */
  scanf("%*[^\n] ");
  while (scanf("%ld%ld%ld%*[^\n] ", &n, &k, &l) != EOF)
    {
      /* Allocate array a */
      ncoef = (k + 1) * (l + 1);
      if (!(a = NAG_ALLOC(ncoef, double)))
        {
          printf("Allocation failure\n");
          exit_status = -1;
          goto END;
        }

      for (i = 0; i < ncoef; ++i)
        scanf("%lf", &a[i]);
      scanf("%*[^\n] ");
      scanf("%lf%lf%*[^\n] ", &ymin, &ymax);

      for (i = 0; i < n; ++i)
        {
          scanf("%lf%ld%lf%lf%lf%lf%*[^\n] ",
                 &y, &m, &xmin, &xmax, &x1, &xm);

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

          for (j = 0; j < m; ++j)
            x[j] = x1 + (xm - x1) * (double) j / (double)(m - 1);

          one = 1;
          /* nag_2d_cheb_eval (e02cbc).
           * Evaluation of fitted polynomial in two variables
           */
          nag_2d_cheb_eval(one, m, k, l, x, xmin, xmax, y, ymin, ymax,
                           ff, a, &fail);
          if (fail.code != NE_NOERROR)
            {
              printf("Error from nag_2d_cheb_eval (e02cbc).\n%s\n",
                      fail.message);
              exit_status = 1;
              goto END;
            }

          printf("\n");
          printf("y = %13.4e\n", y);
          printf("\n");
          printf("  i     x(i)      Poly(x(i),y)\n");
          for (j = 0; j < m; ++j)
            printf("%3ld%13.4e%13.4e\n", j, x[j], ff[j]);

          NAG_FREE(ff);
          NAG_FREE(x);
        }

      NAG_FREE(a);
    }

 END:
  NAG_FREE(a);
  NAG_FREE(ff);
  NAG_FREE(x);

  return exit_status;
}