/* nag_monotonic_deriv (e01bgc) 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 <nage01.h>

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

  INIT_FAIL(fail);

  printf("nag_monotonic_deriv (e01bgc) Example Program Results\n");
  scanf("%*[^\n]");  /* Skip heading in data file */
  scanf("%ld", &n);
  if (n >= 2)
    {
      if (!(x = NAG_ALLOC(n, double)) ||
          !(f = NAG_ALLOC(n, double)) ||
          !(d = 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("%ld", &m);
  if (m >= 1)
    {
      if (!(pd = NAG_ALLOC(m, double)) ||
          !(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_deriv (e01bgc).
   * Evaluation of interpolant computed by
   * nag_monotonic_interpolant (e01bec), function and first
   * derivative
   */
  nag_monotonic_deriv(n, x, f, d, m, px, pf, pd, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_monotonic_deriv (e01bgc).\n%s\n",
              fail.message);
      exit_status = 1;
      goto END;
    }
  printf("                            Interpolated");
  printf("      Interpolated\n");
  printf("       Abscissa                Value");
  printf("           Derivative\n");
  for (i = 0; i < m; i++)
    printf("%15.4f      %15.4f      %15.3e\n", px[i], pf[i], pd[i]);
 END:
  NAG_FREE(x);
  NAG_FREE(pd);
  NAG_FREE(pf);
  NAG_FREE(px);
  NAG_FREE(f);
  NAG_FREE(d);
  return exit_status;
}