/* nag_2d_spline_eval (e02dec) 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 <nage02.h>

int main(void)
{
  Integer      exit_status = 0, i, m;
  NagError     fail;
  Nag_2dSpline spline;
  double       *ff = 0, *x = 0, *y = 0;

  INIT_FAIL(fail);

  /* Initialise spline */
  spline.lamda = 0;
  spline.mu = 0;
  spline.c = 0;

  printf("nag_2d_spline_eval (e02dec) Example Program Results\n");
  scanf("%*[^\n]"); /* Skip heading in data file */
  /* Read m, the number of spline evaluation points. */
  scanf("%ld", &m);
  if (m >= 1)
    {
      if (!(x = NAG_ALLOC(m, double)) ||
          !(y = NAG_ALLOC(m, double)) ||
          !(ff = NAG_ALLOC(m, double)))
        {
          printf("Allocation failure\n");
          exit_status = -1;
          goto END;
        }
    }
  else
    {
      printf("Invalid m.\n");
      exit_status = 1;
      return exit_status;
    }
  /* Read nx and ny, the number of knots in the x and y directions. */
  scanf("%ld%ld", &(spline.nx), &(spline.ny));
  if (spline.nx >= 8 && spline.ny >= 8)
    {
      if (!(spline.c = NAG_ALLOC((spline.nx-4)*(spline.ny-4), double)) ||
          !(spline.lamda = NAG_ALLOC(spline.nx, double)) ||
          !(spline.mu = NAG_ALLOC(spline.ny, double)))
        {
          printf("Allocation failure\n");
          exit_status = -1;
          goto END;
        }
    }
  else
    {
      printf("Invalid spline.nx or spline.ny.\n");
      exit_status = 1;
      return exit_status;
    }

  /* read the knots lamda[0] .. lamda[nx-1] and mu[0] .. mu[ny-1]. */
  for (i = 0; i < spline.nx; i++)
    scanf("%lf", &(spline.lamda[i]));
  for (i = 0; i < spline.ny;  i++)
    scanf("%lf", &(spline.mu[i]));
  /* Read c, the bicubic spline coefficients. */
  for (i = 0; i < (spline.nx-4)*(spline.ny-4);
       scanf("%lf", &(spline.c[i])), i++) ;
  /* Read the x and y co-ordinates of the evaluation points. */
  for (i = 0; i < m; i++)
    scanf("%lf%lf", &x[i], &y[i]);
  /* Evaluate the spline at the m points. */
  /* nag_2d_spline_eval (e02dec).
   * Evaluation of bicubic spline, at a set of points
   */
  nag_2d_spline_eval(m, x, y, ff, &spline, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_2d_spline_eval (e02dec).\n%s\n",
              fail.message);
      exit_status = 1;
      goto END;
    }

  /* Print the results. */
  printf("      i          x[i]       y[i]       ff[i]\n");
  for (i = 0; i < m; i++)
    printf("%7ld    %11.3f%11.3f%11.3f\n", i, x[i], y[i], ff[i]);
  NAG_FREE(spline.lamda);
  NAG_FREE(spline.mu);
  NAG_FREE(spline.c);
 END:
  NAG_FREE(x);
  NAG_FREE(y);
  NAG_FREE(ff);
  return exit_status;
}