/* nag_monotonic_evaluate (e01bfc) Example Program.
 *
 * NAGPRODCODE Version.
 *
 * Copyright 2016 Numerical Algorithms Group
 *
 * Mark 26, 2016.
 */

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

int main(void)
{
  Integer exit_status = 0, i, m, n, r;
  NagError fail;
  double *d = 0, *f = 0, *pf = 0, *px = 0, step, *x = 0;

  INIT_FAIL(fail);

  printf("nag_monotonic_evaluate (e01bfc) Example Program Results\n");
  scanf("%*[^\n]"); /* Skip to end of line */
  scanf("%" NAG_IFMT "", &n);
  if (n >= 2) {
    if (!(d = NAG_ALLOC(n, double)) ||
        !(f = NAG_ALLOC(n, double)) || !(x = NAG_ALLOC(n, double)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }
  }
  else {
    printf("Invalid n.\n");
    exit_status = 1;
    return exit_status;
  }
  for (r = 0; r < n; r++)
    scanf("%lf%lf%lf", &x[r], &f[r], &d[r]);
  scanf("%" NAG_IFMT "", &m);
  if (m >= 1) {
    if (!(pf = NAG_ALLOC(m, double)) || !(px = NAG_ALLOC(m, double)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }
  }
  else {
    printf("Invalid m.\n");
    exit_status = 1;
    return exit_status;
  }
  /* Compute M Equally spaced points from x[0] to x[n-1]. */
  step = (x[n - 1] - x[0]) / (double) (m - 1);
  for (i = 0; i < m; i++)
    px[i] = MIN(x[0] + i * step, x[n - 1]);
  /* nag_monotonic_evaluate (e01bfc).
   * Evaluation of interpolant computed by
   * nag_monotonic_interpolant (e01bec), function only
   */
  nag_monotonic_evaluate(n, x, f, d, m, px, pf, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_monotonic_evaluate (e01bfc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }
  printf("                 Interpolated\n");
  printf("      Abscissa      Value\n");
  for (i = 0; i < m; i++)
    printf("%13.4f%13.4f\n", px[i], pf[i]);
END:
  NAG_FREE(d);
  NAG_FREE(f);
  NAG_FREE(pf);
  NAG_FREE(px);
  NAG_FREE(x);
  return exit_status;
}