/* nag_opt_conj_grad (e04dgc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 2, 1991.
 * Mark 7 revised, 2001.
 * Mark 8 revised, 2004.
 *
 */

#include <nag.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <nag_stdlib.h>
#include <nage04.h>

#ifdef __cplusplus
extern "C" {
#endif
static void NAG_CALL objfun(Integer n, const double x[], double *objf,
                            double g[], Nag_Comm *comm);
#ifdef __cplusplus
}
#endif

int main(void)
{
  const char  *optionsfile = "e04dgce.opt";
  static double ruser[1] = {-1.0};
  Integer     exit_status = 0;
  Nag_Boolean print;
  Integer     n;
  Nag_E04_Opt options;
  double      *g = 0, objf, *x = 0;
  Nag_Comm    comm;
  NagError    fail;

  INIT_FAIL(fail);


  printf("nag_opt_conj_grad (e04dgc) Example Program Results\n");

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

  fflush(stdout);

  /* Initialise options structure and read option values from file */
  print = Nag_TRUE;
  n = 2; /* Number of variables */
  if (n >= 1)
    {
      if (!(x = NAG_ALLOC(n, double)) ||
          !(g = NAG_ALLOC(n, double)))
        {
          printf("Allocation failure\n");
          exit_status = -1;
          goto END;
        }
    }
  else
    {
      printf("Invalid n.\n");
      exit_status = 1;
      return exit_status;
    }
  /* nag_opt_init (e04xxc).
   * Initialization function for option setting
   */
  nag_opt_init(&options);
  /* nag_opt_read (e04xyc).
   * Read options from a text file
   */
  nag_opt_read("e04dgc", optionsfile, &options, print, "stdout", &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_opt_read (e04xyc).\n%s\n", fail.message);
      exit_status = 1;
      goto END;
    }
  /* Set the initial estimate of the solution. */
  x[0] = -1.0;
  x[1] = 1.0;

  /* Solve the problem. */
  /* nag_opt_conj_grad (e04dgc), see above. */
  nag_opt_conj_grad(n, objfun, x, &objf, g, &options, &comm, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_opt_conj_grad (e04dgc).\n%s\n",
              fail.message);
      exit_status = 1;
      goto END;
    }

 END:
  NAG_FREE(x);
  NAG_FREE(g);

  return exit_status;
}

static void NAG_CALL objfun(Integer n, const double x[], double *objf,
                            double g[], Nag_Comm *comm)
{
  /* Function to evaluate objective function and its 1st derivatives. */

  double ex1, x1, x2;

  if (comm->user[0] == -1.0)
    {
      printf("(User-supplied callback objfun, first invocation.)\n");
      fflush(stdout);
      comm->user[0] = 0.0;
    }

  ex1 = exp(x[0]);
  x1 = x[0];
  x2 = x[1];

  *objf = ex1*(4*x1*x1 + 2*x2*x2 + 4*x1*x2 + 2*x2 + 1);

  g[0] = 4*ex1*(2*x1 + x2) + *objf;
  g[1] = 2*ex1*(2*x2 + 2*x1 + 1);
} /* objfun */