/* nag_2d_shep_interp (e01sgc) Example Program.
 *
 * Copyright 2017 Numerical Algorithms Group.
 *
 * Mark 26.1, 2017.
 */

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

int main(void)
{

  /* Scalars */
  Integer exit_status, i, m, n, nq, nw;
  Integer liq, lrq;

  /* Arrays */
  double *f = 0, *q = 0, *qx = 0, *qy = 0, *rq = 0, *u = 0, *v = 0, *x = 0;
  double *y = 0;
  Integer *iq = 0;

  /* Nag Types */
  NagError fail;

  exit_status = 0;
  INIT_FAIL(fail);

  printf("nag_2d_shep_interp (e01sgc) Example Program Results\n\n");

  /* Skip heading in data file */
  scanf("%*[^\n] ");

  /* Input the number of nodes. */
  scanf("%" NAG_IFMT "%*[^\n] ", &m);
  if (m > 6) {
    liq = 2 * m + 1;
    lrq = 6 * m + 5;
    /* Allocate memory */
    if (!(f = NAG_ALLOC(m, double)) ||
        !(rq = NAG_ALLOC(lrq, double)) ||
        !(x = NAG_ALLOC(m, double)) ||
        !(y = NAG_ALLOC(m, double)) || !(iq = NAG_ALLOC(liq, Integer)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }
  }
  else {
    printf("Invalid m.\n");
    exit_status = 1;
    return exit_status;
  }

  /* Input the data points X,Y and F. */

  for (i = 1; i <= m; ++i) {
    scanf("%lf%lf%lf%*[^\n] ", &x[i - 1], &y[i - 1], &f[i - 1]);
  }

  /* Generate the interpolant. */
  nq = 0;
  nw = 0;
  /* nag_2d_shep_interp (e01sgc).
   * Interpolating functions, modified Shepard's method, two
   * variables
   */
  nag_2d_shep_interp(m, x, y, f, nw, nq, iq, rq, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_2d_shep_interp (e01sgc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  /* Input the number of evaluation points. */
  scanf("%" NAG_IFMT "%*[^\n] ", &n);
  if (!(q = NAG_ALLOC(n, double)) ||
      !(qx = NAG_ALLOC(n, double)) ||
      !(qy = NAG_ALLOC(n, double)) ||
      !(u = NAG_ALLOC(n, double)) || !(v = NAG_ALLOC(n, double)))
  {
    printf("Allocation failure\n");
    exit_status = 1;
    goto END;
  }

  /* Input the evaluation points. */

  for (i = 1; i <= n; ++i) {
    scanf("%lf%lf%*[^\n] ", &u[i - 1], &v[i - 1]);
  }

  /* Evaluate the interpolant using nag_2d_shep_eval (e01shc). */

  /* nag_2d_shep_eval (e01shc).
   * Interpolated values, evaluate interpolant computed by
   * nag_2d_shep_interp (e01sgc), function and first
   * derivatives, two variables
   */
  nag_2d_shep_eval(m, x, y, f, iq, rq, n, u, v, q, qx, qy, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_2d_shep_interp (e01sgc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  printf("%s", "     I      U(I)      V(I)      Q(I)");
  printf("\n");
  for (i = 1; i <= n; ++i) {
    printf("%6" NAG_IFMT "%10.2f%10.2f%10.2f\n", i, u[i - 1], v[i - 1],
           q[i - 1]);
  }

END:
  NAG_FREE(f);
  NAG_FREE(q);
  NAG_FREE(qx);
  NAG_FREE(qy);
  NAG_FREE(rq);
  NAG_FREE(u);
  NAG_FREE(v);
  NAG_FREE(x);
  NAG_FREE(y);
  NAG_FREE(iq);

  return exit_status;
}