/* nag_1d_quad_inf_1 (d01smc) Example Program.
 *
 * NAGPRODCODE Version.
 *
 * Copyright 2016 Numerical Algorithms Group.
 *
 * Mark 26, 2016.
 *
 */

#include <nag.h>
#include <stdio.h>
#include <nag_stdlib.h>
#include <math.h>
#include <nagd01.h>

#ifdef __cplusplus
extern "C"
{
#endif
  static double NAG_CALL f(double x, Nag_User *comm);
#ifdef __cplusplus
}
#endif

int main(void)
{
  static Integer use_comm[1] = { 1 };
  Integer exit_status = 0;
  double a;
  double epsabs, abserr, epsrel, result;
  Nag_QuadProgress qp;
  Integer max_num_subint;
  NagError fail;
  Nag_User comm;

  INIT_FAIL(fail);

  printf("nag_1d_quad_inf_1 (d01smc) Example Program Results\n");

  /* For communication with user-supplied functions: */
  comm.p = (Pointer) &use_comm;

  epsabs = 0.0;
  epsrel = 0.0001;
  a = 0.0;
  max_num_subint = 200;

  /* nag_1d_quad_inf_1 (d01smc).
   * One-dimensional adaptive quadrature over infinite or
   * semi-infinite interval, thread-safe
   */
  nag_1d_quad_inf_1(f, Nag_UpperSemiInfinite, a, epsabs, epsrel,
                    max_num_subint, &result, &abserr, &qp, &comm, &fail);
  printf("a      - lower limit of integration = %10.4f\n", a);
  printf("b      - upper limit of integration = infinity\n");
  printf("epsabs - absolute accuracy requested = %11.2e\n", epsabs);
  printf("epsrel - relative accuracy requested = %11.2e\n\n", epsrel);
  if (fail.code != NE_NOERROR)
    printf("Error from nag_1d_quad_inf_1 (d01smc)  %s\n", fail.message);
  if (fail.code != NE_INT_ARG_LT && fail.code != NE_BAD_PARAM &&
      fail.code != NE_ALLOC_FAIL && fail.code != NE_NO_LICENCE) {
    printf("result - approximation to the integral = %9.5f\n", result);
    printf("abserr - estimate of the absolute error = %11.2e\n", abserr);
    printf("qp.fun_count  - number of function evaluations = %4" NAG_IFMT
           "\n", qp.fun_count);
    printf("qp.num_subint  - number of subintervals used = %4" NAG_IFMT "\n",
           qp.num_subint);
    /* Free memory used by qp */
    NAG_FREE(qp.sub_int_beg_pts);
    NAG_FREE(qp.sub_int_end_pts);
    NAG_FREE(qp.sub_int_result);
    NAG_FREE(qp.sub_int_error);
  }
  else {
    exit_status = 1;
    goto END;
  }

END:
  return exit_status;
}

static double NAG_CALL f(double x, Nag_User *comm)
{
  Integer *use_comm = (Integer *) comm->p;

  if (use_comm[0]) {
    printf("(User-supplied callback f, first invocation.)\n");
    use_comm[0] = 0;
  }

  return 1.0 / ((x + 1.0) * sqrt(x));
}