/* nag_1d_spline_deriv (e02bcc) 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, i, j, l, m, ncap, ncap7;
  NagError      fail;
  Nag_DerivType derivs;
  Nag_Spline    spline;
  double        s[4], x;

  INIT_FAIL(fail);

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

  printf("nag_1d_spline_deriv (e02bcc) Example Program Results\n");
  scanf("%*[^\n]"); /* Skip heading in data file */
  while (scanf("%ld%ld", &ncap, &m) != EOF)
    {
      if (m <= 0)
        {
          printf("Invalid m.\n");
          exit_status = 1;
          return exit_status;
        }
      if (ncap > 0)
        {
          ncap7 = ncap+7;
          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]));
      printf("        x             Spline    1st deriv  "
              "2nd deriv   3rd deriv");
      for (i = 1; i <= m; i++)
        {
          scanf("%lf", &x);
          derivs = Nag_LeftDerivs;
          for (j = 1; j <= 2; j++)
            {
              /* nag_1d_spline_deriv (e02bcc).
               * Evaluation of fitted cubic spline, function and
               * derivatives
               */
              nag_1d_spline_deriv(derivs, x, s, &spline, &fail);
              if (fail.code != NE_NOERROR)
                {
                  printf(
                          "Error from nag_1d_spline_deriv (e02bcc).\n%s\n",
                          fail.message);
                  exit_status = 1;
                  goto END;
                }

              if (derivs == Nag_LeftDerivs)
                {
                  printf("\n\n%11.4f   Left", x);
                  for (l = 0; l < 4; l++)
                    printf("%11.4f", s[l]);
                }
              else
                {
                  printf("\n%11.4f  Right", x);
                  for (l = 0; l < 4; l++)
                    printf("%11.4f", s[l]);
                }
              derivs = Nag_RightDerivs;
            }
        }
      printf("\n");
 END:
      NAG_FREE(spline.c);
      NAG_FREE(spline.lamda);
    }
  return exit_status;
}