/* nag_1d_aitken_interp (e01aac) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 23, 2011.
 */

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

int main(void)
{
  /* Scalars */
  Integer exit_status = 0;
  Integer i, j, k, n;
  double  x;
  NagError fail;
  /* Arrays */
  double  *a = 0, *b = 0, *c = 0;

  INIT_FAIL(fail);

  printf("nag_1d_aitken_interp (e01aac) Example Program Results\n\n");

  /* Skip heading in data file*/
  scanf("%*[^\n] ");
  scanf("%"NAG_IFMT "", &n);
  scanf("%lf", &x);
  scanf("%*[^\n] ");

  /* Allocate memory */
  if (!(a = NAG_ALLOC((n+1), double)) ||
      !(b = NAG_ALLOC((n+1), double)) ||
      !(c = NAG_ALLOC((n*(n+1)/2), double)))
    {
      printf("Allocation failure\n\n");
      exit_status = -1;
      goto END;
    }

  for (i = 0; i <= n; i++)
    scanf("%lf", &a[i]);
  scanf("%*[^\n] ");
  for (i = 0; i <= n; i++)
    scanf("%lf", &b[i]);
  scanf("%*[^\n] ");

  /* nag_1d_aitken_interp (e01aac).
   * Interpolated values, Aitken's technique,
   * unequally spaced data, one variable.
   */
  nag_1d_aitken_interp(n, a, b, c, x, &fail);
  if (fail.code != NE_NOERROR){
    printf("Error from nag_1d_aitken_interp (e01aac).\n%s\n",
           fail.message);
    exit_status = 1;
    goto END;
  }

  printf("Interpolated values\n");
  k = 0;
  for (i = 1; i <= n - 1; i++){
    for (j = k; j <= k + n - i; j++)
      printf("%12.5f", c[j]);
    printf("\n");
    k = j;
  }
  printf("\nInterpolation point = %12.5f\n", x);
  printf("\nFunction value at interpolation point = %12.5f\n", c[n*(n+1)/2-1]);

 END:
  NAG_FREE(a);
  NAG_FREE(b);
  NAG_FREE(c);

  return exit_status;
}