/* nag_1d_spline_evaluate (e02bbc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 2, 1991.
 *
 * Mark 3 revised, 1994.
 * Mark 8 revised, 2004.
 */

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

int main(void)
{
  Integer    exit_status = 0, j, m, ncap, ncap7, r;
  Nag_Spline spline;
  double     a, b, s, x;
  NagError   fail;

  INIT_FAIL(fail);

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

  printf("nag_1d_spline_evaluate (e02bbc) Example Program Results\n");
  scanf("%*[^\n]");  /* Skip heading in data file */
  while (scanf("%ld", &m) != EOF)
    {
      if (m <= 0)
        {
          printf("Invalid m.\n");
          exit_status = 1;
          return exit_status;
        }
      scanf("%ld", &ncap);
      ncap7 = ncap+7;
      if (ncap > 0)
        {
          spline.n = ncap7;
          if (!(spline.c = NAG_ALLOC(ncap7, double)) ||
              !(spline.lamda = NAG_ALLOC(ncap7, double)))
            {
              printf("Allocation failure\n");
              exit_status = -1;
              goto END;
            }
        }
      else
        {
          printf("Invalid ncap.\n");
          exit_status = 1;
          return exit_status;
        }
      for (j = 0; j < ncap7; j++)
        scanf("%lf", &(spline.lamda[j]));
      for (j = 0; j < ncap+3; j++)
        scanf("%lf", &(spline.c[j]));
      a = spline.lamda[3];
      b = spline.lamda[ncap+3];
      printf("Augmented set of knots stored in spline.lamda:\n");
      for (j = 0; j < ncap7; j++)
        printf("%10.4f%s", spline.lamda[j],
                (j%6 == 5 || j == ncap7-1)?"\n":" ");
      printf("\nB-spline coefficients stored in spline.c\n\n");
      for (j = 0; j < ncap+3; j++)
        printf("%10.4f%s", spline.c[j],
                (j%6 == 5 || j == ncap+2)?"\n":" ");
      printf("\n      x         Value of cubic spline\n\n");
      for (r = 1; r <= m; ++r)
        {
          x = ((double)(m-r) * a + (double)(r-1) * b) / (double)(m-1);
          /* nag_1d_spline_evaluate (e02bbc).
           * Evaluation of fitted cubic spline, function only
           */
          nag_1d_spline_evaluate(x, &s, &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("%10.4f%15.4f\n", x, s);
        }
      NAG_FREE(spline.c);
      NAG_FREE(spline.lamda);
    }
 END:
  return exit_status;
}