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

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

#define MMAX 7

int main(void)
{
  Integer exit_status = 0, i, j, m = MMAX;
  NagError fail;
  Nag_Spline spline;
  double fit, *x = 0, xarg, *y = 0;

  INIT_FAIL(fail);

  /* Initialize spline */
  spline.lamda = 0;
  spline.c = 0;

  printf("nag_1d_spline_interpolant (e01bac) Example Program Results\n");

  if (m >= 1) {
    if (!(y = NAG_ALLOC(m, double)) || !(x = NAG_ALLOC(m, double)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }
  }
  else {
    exit_status = 1;
    return exit_status;
  }

  x[0] = 0.0;
  x[1] = 0.2;
  x[2] = 0.4;
  x[3] = 0.6;
  x[4] = 0.75;
  x[5] = 0.9;
  x[6] = 1.0;

  for (i = 0; i < m; ++i)
    y[i] = exp(x[i]);
  /* nag_1d_spline_interpolant (e01bac).
   * Interpolating function, cubic spline interpolant, one
   * variable
   */
  nag_1d_spline_interpolant(m, x, y, &spline, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_1d_spline_interpolant (e01bac).\n%s\n",
           fail.message);
    exit_status = 1;
    goto END;
  }

  printf("\nNumber of distinct knots = %" NAG_IFMT "\n\n", m - 2);
  printf("Distinct knots located at \n\n");
  for (j = 3; j < m + 1; j++)
    printf("%8.4f%s", spline.lamda[j], (j - 3) % 5 == 4
           || j == m ? "\n" : " ");
  printf("\n\n    J    B-spline coeff c\n\n");
  for (j = 0; j < m; ++j)
    printf("    %" NAG_IFMT "  %13.4f\n", j + 1, spline.c[j]);
  printf("\n    J       Abscissa            Ordinate            Spline\n\n");
  for (j = 0; j < m; ++j) {
    /* nag_1d_spline_evaluate (e02bbc).
     * Evaluation of fitted cubic spline, function only
     */
    nag_1d_spline_evaluate(x[j], &fit, &spline, &fail);
    if (fail.code != NE_NOERROR) {
      printf("Error from nag_1d_spline_evaluate (e02bbc).\n%s\n",
             fail.message);
      exit_status = 1;
      goto END;
    }

    printf("    %" NAG_IFMT " %13.4f      %13.4f       %13.4f\n",
           j + 1, x[j], y[j], fit);
    if (j < m - 1) {
      xarg = (x[j] + x[j + 1]) * 0.5;
      /* nag_1d_spline_evaluate (e02bbc), see above. */
      nag_1d_spline_evaluate(xarg, &fit, &spline, &fail);
      if (fail.code != NE_NOERROR) {
        printf("Error from nag_1d_spline_evaluate (e02bbc).\n%s\n",
               fail.message);
        exit_status = 1;
        goto END;
      }
      printf("      %13.4f                          %13.4f\n", xarg, fit);
    }
  }
  /* Free memory allocated by nag_1d_spline_interpolant (e01bac) */
END:
  NAG_FREE(y);
  NAG_FREE(x);
  NAG_FREE(spline.lamda);
  NAG_FREE(spline.c);
  return exit_status;
}