/* nag_inteq_fredholm2_split (d05aac) Example Program.
 *
 * NAGPRODCODE Version.
 *
 * Copyright 2016 Numerical Algorithms Group.
 *
 * Mark 26, 2016.
 */
#include <math.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <nagc06.h>
#include <nagd05.h>
#include <nagx01.h>

#ifdef __cplusplus
extern "C"
{
#endif

  static double NAG_CALL k1(double x, double s, Nag_Comm *comm);
  static double NAG_CALL k2(double x, double s, Nag_Comm *comm);
  static double NAG_CALL g(double x, Nag_Comm *comm);

#ifdef __cplusplus
}
#endif

int main(void)
{
  /* Scalars */
  double a = 0.0, b = 1.0, lambda = 1.0, x = 0.1;
  double res;
  Integer exit_status = 0;
  Integer n = 5;
  Integer i;
  /* Arrays */
  static double ruser[3] = { -1.0, -1.0, -1.0 };
  double *c = 0, *f = 0;
  /* NAG types */
  Nag_Comm comm;
  NagError fail;
  Nag_KernelForm kform = Nag_CentroSymmEven;
  Nag_Series s = Nag_SeriesEven;

  INIT_FAIL(fail);

  printf("nag_inteq_fredholm2_split (d05aac) Example Program Results\n");

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

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

  /*
     nag_inteq_fredholm2_split (d05aac).
     Linear non-singular Fredholm integral equation, second kind, split kernel.
   */
  nag_inteq_fredholm2_split(lambda, a, b, n, k1, k2, g, kform, f, c, &comm,
                            &fail);

  if (fail.code != NE_NOERROR) {
    printf("Error from nag_inteq_fredholm2_split (d05aac).\n%s\n",
           fail.message);
    exit_status = 1;
    goto END;
  }

  printf("\nKernel is centro-symmetric and g is even, "
         "so the solution is even\n\n");

  printf("Chebyshev coefficients of the approximation to f(x)\n\n");
  for (i = 0; i < n; i++)
    printf("%14.4e", c[i]);
  printf("\n\n");

  /*
     nag_sum_cheby_series (c06dcc).
     Sum of a Chebyshev series at a set of points.
   */
  nag_sum_cheby_series(&x, 1, a, b, c, n, s, &res, &fail);

  if (fail.code != NE_NOERROR) {
    printf("Error from nag_sum_cheby_series (c06dcc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  printf(" Solution: x = %5.2f and  f(x) = %10.4f\n", x, res);

END:

  NAG_FREE(c);
  NAG_FREE(f);

  return exit_status;
}

static double NAG_CALL k1(double x, double s, Nag_Comm *comm)
{
  if (comm->user[0] == -1.0) {
    printf("(User-supplied callback k1, first invocation.)\n");
    comm->user[0] = 0.0;
  }
  return s * (1.0 - x);
}

static double NAG_CALL k2(double x, double s, Nag_Comm *comm)
{
  if (comm->user[1] == -1.0) {
    printf("(User-supplied callback k2, first invocation.)\n");
    comm->user[1] = 0.0;
  }
  return x * (1.0 - s);
}

static double NAG_CALL g(double x, Nag_Comm *comm)
{
  if (comm->user[2] == -1.0) {
    printf("(User-supplied callback g, first invocation.)\n");
    comm->user[2] = 0.0;
  }
  return (1.0 - 1.0 / pow(nag_pi, 2)) * sin(nag_pi * x);
}