/* nag_2d_triangulate (e01eac) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 25, 2014.
 */

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

int main(void)
{

  /* Scalars */
  Integer  exit_status, i, m, n;

  /* Arrays */
  double   *f = 0, *pf = 0, *px = 0, *py = 0, *x = 0, *y = 0;
  Integer  *triang = 0;

  /* Nag Types */
  NagError fail;

  exit_status = 0;
  INIT_FAIL(fail);

  printf("nag_2d_triangulate (e01eac) Example Program Results\n\n");

  /* Skip heading in data file and read array lengths */
  scanf("%*[^\n]");
  scanf("%ld%*[^\n]", &n);
  scanf("%ld%*[^\n]", &m);

  if (!(x  = NAG_ALLOC(n, double))||
      !(y  = NAG_ALLOC(n, double))||
      !(f  = NAG_ALLOC(n, double))||
      !(triang = NAG_ALLOC(7*n, Integer))||
      !(px = NAG_ALLOC(m, double))||
      !(py = NAG_ALLOC(m, double))||
      !(pf = NAG_ALLOC(m, double)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }

  /* Read scattered 2d data points and function values. */
  for ( i=0; i<n; i++) {
    scanf("%lf%lf%lf%*[^\n]", &x[i], &y[i], &f[i]);
  }

  /* Obtain triangulation of scattered points (x,y) using
   * nag_2d_triangulate (e01eac).
   */
  nag_2d_triangulate(n, x, y, triang, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_2d_triangulate (e01eac).\n%s\n",
           fail.message);
    exit_status = 1;
    goto END;
  }

  /* Read points at which interpolated values required. */
  for ( i=0; i<m; i++) {
    scanf("%lf%lf%*[^\n]", &px[i], &py[i]);
  }
  /* Use triangulation to perform barycentric interpolation on to the
   * set of m points (px,py) using nag_2d_triang_bary_eval (e01ebc).
   */
  nag_2d_triang_bary_eval(m, n, x, y, f, triang, px, py, pf, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_2d_triang_bary_eval (e01ebc).\n%s\n",
           fail.message);
    exit_status = 1;
    goto END;
  }

  /* Display results*/
  printf("    %4s   %7s   %19s\n", "px", "py", "Interpolated Value");
  for (i=0; i<m; i++) {
  printf("   %7.4f   %7.4f       %7.4f\n", px[i], py[i], pf[i]);
  }

 END:
  NAG_FREE(f);
  NAG_FREE(pf);
  NAG_FREE(px);
  NAG_FREE(py);
  NAG_FREE(x);
  NAG_FREE(y);
  NAG_FREE(triang);

  return exit_status;
}