/* nag_quad_md_numth_vec (d01gdc) 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 void NAG_CALL vecfun(Integer ndim, const double x[], double fv[],
                              Integer m, Nag_Comm *comm);
  static void NAG_CALL vecreg(Integer ndim, const double x[], Integer j,
                              double c[], double d[], Integer m,
                              Nag_Comm *comm);
#ifdef __cplusplus
}
#endif

int main(void)
{
  static double ruser[2] = { -1.0, -1.0 };
  Integer exit_status = 0;
  Integer ndim;
  Integer npts, nrand;
  double err, res;
  double *vk = 0;
  Nag_Boolean transform;
  char nag_enum_arg[40];
  Nag_Comm comm;
  NagError fail;

  INIT_FAIL(fail);

  printf("nag_quad_md_numth_vec (d01gdc) 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 " %" NAG_IFMT " %" NAG_IFMT "", &ndim, &npts, &nrand);
  /* Nag_Boolean */
  scanf("%39s %*[^\n] ", nag_enum_arg);
  transform = (Nag_Boolean) nag_enum_name_to_value(nag_enum_arg);

  if (!(vk = NAG_ALLOC(ndim, double)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }

  /* nag_quad_md_numth_vec (d01gdc).
   * Multidimensional quadrature, general product region,
   * number-theoretic method.
   */
  nag_quad_md_numth_vec(ndim, vecfun, vecreg, npts, vk, nrand, transform,
                        &res, &err, &comm, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_quad_md_numth_vec (d01gdc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  printf("\nResult = %13.5f, standard error = %10.2e\n", res, err);

END:
  NAG_FREE(vk);

  return exit_status;
}

static void NAG_CALL vecfun(Integer ndim, const double x[], double fv[],
                            Integer m, Nag_Comm *comm)
{
  Integer i, index, j;
  double sum;

  if (comm->user[0] == -1.0) {
    printf("(User-supplied callback vecfun, first invocation.)\n");
    comm->user[0] = 0.0;
  }
  for (i = 0; i < m; i++) {
    sum = 0.0;
    for (j = 0, index = 0; j < ndim; j++, index += m)
      sum += x[i + index];
    fv[i] = cos(0.5 + 2.0 * sum - 4.0);
  }
}

static void NAG_CALL vecreg(Integer ndim, const double x[], Integer j,
                            double c[], double d[], Integer m, Nag_Comm *comm)
{
  Integer i;

  if (comm->user[1] == -1.0) {
    printf("(User-supplied callback vecreg, first invocation.)\n");
    comm->user[1] = 0.0;
  }
  for (i = 0; i < m; i++) {
    c[i] = 0.0;
    d[i] = 1.0;
  }
}