/* nag_quad_md_gauss (d01fbc) Example Program.
 *
 * Copyright 2017 Numerical Algorithms Group.
 *
 * Mark 26.1, 2017.
 */
#include <stdio.h>
#include <math.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <nagd01.h>
#include <nagx04.h>

#ifdef __cplusplus
extern "C"
{
#endif
  static double NAG_CALL fun(Integer ndim, const double x[], Nag_Comm *comm);
#ifdef __cplusplus
}
#endif

int main(void)
{
  static double ruser[1] = { -1.0 };
  Integer exit_status = 0;
  Integer ndim;
  double a, ans, b;
  Integer i, j, lwa;
  double *abscis = 0, *weight = 0;
  Integer *nptvec = 0;
  char nag_enum_arg[40];
  Nag_Comm comm;
  Nag_QuadType quadtype;
  NagError fail;

  INIT_FAIL(fail);

  printf("nag_quad_md_gauss (d01fbc) Example Program Results\n");

  /* For communication with user-supplied functions: */
  comm.user = ruser;

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

  if (!(nptvec = NAG_ALLOC(ndim, Integer)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }
  lwa = 0.0;
  for (i = 0; i < ndim; i++) {
    scanf("%" NAG_IFMT " ", &nptvec[i]);
    lwa = lwa + nptvec[i];
  }
  scanf("%*[^\n] ");
  if (!(abscis = NAG_ALLOC(lwa, double)) ||
      !(weight = NAG_ALLOC(lwa, double)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }

  j = 0;
  for (i = 0; i < ndim; i++) {
    /* Nag_QuadType */
    scanf("%39s%*[^\n] ", nag_enum_arg);
    quadtype = (Nag_QuadType) nag_enum_name_to_value(nag_enum_arg);
    scanf("%lf %lf%*[^\n] ", &a, &b);

    /* nag_quad_1d_gauss_wset (d01tbc).
     * Pre-computed weights and abscissae for
     * Gaussian quadrature rules, restricted choice of rule.
     */
    nag_quad_1d_gauss_wset(quadtype, a, b, nptvec[i], &weight[j], &abscis[j],
                           &fail);
    if (fail.code != NE_NOERROR) {
      printf("Error from nag_quad_1d_gauss_wset (d01tbc).\n%s\n",
             fail.message);
      exit_status = 1;
      goto END;
    }
    j = j + nptvec[i];
  }

  /* nag_quad_md_gauss (d01fbc).
   * Multidimensional Gaussian quadrature over hyper-rectangle.
   */
  ans = nag_quad_md_gauss(ndim, nptvec, lwa, weight, abscis, fun, &comm,
                          &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_quad_md_gauss (d01fbc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  printf("\nAnswer = %10.5f\n", ans);

END:
  NAG_FREE(nptvec);
  NAG_FREE(abscis);
  NAG_FREE(weight);

  return exit_status;
}

static double NAG_CALL fun(Integer ndim, const double x[], Nag_Comm *comm)
{
  if (comm->user[0] == -1.0) {
    printf("(User-supplied callback fun, first invocation.)\n");
    comm->user[0] = 0.0;
  }
  return pow((x[0] * x[1] * x[2]), 6) / pow((x[3] + 2.0), 8)
         * exp(-2.0 * x[1] - 0.5 * x[2] * x[2]);
}