/* nag_4d_shep_interp (e01tkc) Example Program.
 *
 * Copyright 2017 Numerical Algorithms Group.
 *
 * Mark 26.1, 2017.
 */

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

#define X(I, J) x[I *4 + J]
#define XE(I, J) xe[I *4 + J]

int main(void)
{
  /* Scalars */
  Integer exit_status, i, j, m, n, nq, nw, liq, lrq;
  NagError fail;

  /* Arrays */
  double *f = 0, *q = 0, *qx = 0, *rq = 0, *xe = 0, *x = 0;
  Integer *iq = 0;

  exit_status = 0;

  INIT_FAIL(fail);

  printf("nag_4d_shep_interp (e01tkc) Example Program Results\n");

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

  /* Input the number of nodes. */
  scanf("%" NAG_IFMT "%*[^\n] ", &m);

  /* Allocate memory */
  lrq = 21 * m + 11;
  liq = 2 * m + 1;
  if (!(f = NAG_ALLOC(m, double)) ||
      !(x = NAG_ALLOC(m * 4, double)) ||
      !(rq = NAG_ALLOC(lrq, double)) || !(iq = NAG_ALLOC(liq, Integer)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }

  /* Input the data points X and F. */
  for (i = 0; i < m; ++i) {
    for (j = 0; j < 4; ++j) {
      scanf("%lf", &X(i, j));
    }
    scanf("%lf%*[^\n] ", &f[i]);
  }

  /* Generate the interpolant. */
  nq = 0;
  nw = 0;

  /* nag_4d_shep_interp (e01tkc).
   * Interpolating functions, modified Shepard's method, four variables
   */
  nag_4d_shep_interp(m, x, f, nw, nq, iq, rq, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_4d_shep_interp (e01tkc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  /* Input the number of evaluation points. */
  scanf("%" NAG_IFMT "%*[^\n] ", &n);

  /* Allocate memory for nag_4d_shep_eval (e01tlc) */
  if (!(q = NAG_ALLOC(n, double)) ||
      !(qx = NAG_ALLOC(n * 4, double)) || !(xe = NAG_ALLOC(n * 4, double)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }

  /* Input the evaluation points. */
  for (i = 0; i < n; ++i) {
    for (j = 0; j < 4; ++j) {
      scanf("%lf", &XE(i, j));
    }
    scanf("%*[^\n] ");
  }

  /* nag_4d_shep_eval (e01tlc).
   * Evaluate interpolant computed by nag_4d_shep_interp (e01tkc), and first
   * derivatives, at oints in xe.
   */
  fail.print = Nag_TRUE;
  nag_4d_shep_eval(m, x, f, iq, rq, n, xe, q, qx, &fail);

  printf("\n Evaluation of interpolant at various (4D) points\n");
  printf("\n%6s%26s%17s\n", " pt.no.", "point coordinates", "value");
  for (i = 0; i < n; ++i)
    printf("%5" NAG_IFMT "%8.2f%8.2f%8.2f%8.2f%14.4f\n", i, XE(i, 0),
           XE(i, 1), XE(i, 2), XE(i, 3), q[i]);

END:
  NAG_FREE(f);
  NAG_FREE(q);
  NAG_FREE(qx);
  NAG_FREE(rq);
  NAG_FREE(xe);
  NAG_FREE(x);
  NAG_FREE(iq);

  return exit_status;
}