/* nag_real_symm_sparse_eigensystem_option (f12fdc) Example Program.
 *
 * Copyright 2017 Numerical Algorithms Group.
 *
 * Mark 26.1, 2017.
 */

#include <math.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <stdio.h>
#include <nagf12.h>
#include <nagf16.h>

static void mv(Integer, double *, double *);
static void my_dgttrf(Integer, double *, double *, double *,
                      double *, Integer *, Integer *);
static void my_dgttrs(Integer, double *, double *, double *,
                      double *, Integer *, double *, double *);

int main(void)
{
  /* Constants */
  Integer licomm = 140, imon = 0;

  /* Scalars */
  double estnrm, h, r1, r2, sigma;
  Integer exit_status, info, irevcm, j, lcomm, n, nconv, ncv;
  Integer nev, niter, nshift;
  /* Nag types */
  NagError fail;
  /* Arrays */
  double *dd = 0, *dl = 0, *du = 0, *du2 = 0, *comm = 0, *eigest = 0;
  double *eigv = 0, *resid = 0, *v = 0, *x2 = 0;
  Integer *icomm = 0, *ipiv = 0;
  /* Pointers */
  double *mx = 0, *x = 0, *y = 0;

  exit_status = 0;
  INIT_FAIL(fail);

  printf("nag_real_symm_sparse_eigensystem_option (f12fdc) Example "
         "Program Results\n");
  /* Skip heading in data file */
  scanf("%*[^\n] ");

  /* Read values for nx, nev and cnv from data file. */
  scanf("%" NAG_IFMT "%" NAG_IFMT "%" NAG_IFMT "%*[^\n] ", &n, &nev, &ncv);

  /* Allocate memory */
  lcomm = 3 * n + ncv * ncv + 8 * ncv + 60;
  if (!(dd = NAG_ALLOC(n, double)) ||
      !(dl = NAG_ALLOC(n, double)) ||
      !(du = NAG_ALLOC(n, double)) ||
      !(du2 = NAG_ALLOC(n, double)) ||
      !(comm = NAG_ALLOC(lcomm, double)) ||
      !(eigv = NAG_ALLOC(ncv, double)) ||
      !(eigest = NAG_ALLOC(ncv, double)) ||
      !(resid = NAG_ALLOC(n, double)) ||
      !(v = NAG_ALLOC(n * ncv, double)) ||
      !(x2 = NAG_ALLOC(n, double)) ||
      !(icomm = NAG_ALLOC(licomm, Integer)) ||
      !(ipiv = NAG_ALLOC(n, Integer)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }
  /* Initialize communication arrays for problem using
     nag_real_symm_sparse_eigensystem_init (f12fac). */
  nag_real_symm_sparse_eigensystem_init(n, nev, ncv, icomm, licomm, comm,
                                        lcomm, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_real_symm_sparse_eigensystem_init (f12fac).\n%s\n",
           fail.message);
    exit_status = 1;
    goto END;
  }
  /* Select the problem type using
     nag_real_symm_sparse_eigensystem_option (f12fdc). */
  nag_real_symm_sparse_eigensystem_option("generalized", icomm, comm, &fail);

  /* Select the operating mode using
     nag_real_symm_sparse_eigensystem_option (f12fdc). */
  nag_real_symm_sparse_eigensystem_option("shifted inverse", icomm, comm,
                                          &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_real_symm_sparse_eigensystem_option (f12fdc).\n%s\n",
           fail.message);
    exit_status = 1;
    goto END;
  }

  /* Setup M and factorise */
  h = 1.0 / (double) (n + 1);
  r1 = 2.0 * h / 3.0;
  r2 = h / 6.0;
  sigma = 0.0;
  for (j = 0; j <= n - 1; ++j) {
    dd[j] = 2.0 / h - sigma * r1;
    dl[j] = -1.0 / h - sigma * r2;
    du[j] = dl[j];
  }
  my_dgttrf(n, dl, dd, du, du2, ipiv, &info);

  irevcm = 0;
REVCOMLOOP:
  /* Repeated calls to reverse communication routine
     nag_real_symm_sparse_eigensystem_iter (f12fbc). */
  nag_real_symm_sparse_eigensystem_iter(&irevcm, resid, v, &x, &y, &mx,
                                        &nshift, comm, icomm, &fail);
  if (irevcm != 5) {
    if (irevcm == -1) {
      /* Perform  y <--- OP*x = inv[A-SIGMA*M]*M*x. */
      mv(n, x, x2);
      my_dgttrs(n, dl, dd, du, du2, ipiv, x2, y);
    }
    else if (irevcm == 1) {
      /* Perform y <-- OP*x = inv[A-sigma*M]*M*x;
         M*x has been saved in COMM(ICOMM(3)) or MX. */
      my_dgttrs(n, dl, dd, du, du2, ipiv, mx, y);
    }
    else if (irevcm == 2) {
      /* Perform  y <--- M*x. */
      mv(n, x, y);
    }
    else if (irevcm == 4 && imon == 1) {
      /* If imon=1, get monitoring information using
         nag_real_symm_sparse_eigensystem_monit (f12fec). */
      nag_real_symm_sparse_eigensystem_monit(&niter, &nconv, eigv, eigest,
                                             icomm, comm);
      /* Compute 2-norm of Ritz estimates using
         nag_dge_norm (f16rac). */
      nag_dge_norm(Nag_ColMajor, Nag_FrobeniusNorm, nev, 1, eigest, nev,
                   &estnrm, &fail);
      printf("Iteration %3" NAG_IFMT ", ", niter);
      printf(" No. converged = %3" NAG_IFMT ",", nconv);
      printf(" norm of estimates = %17.8e\n", estnrm);
    }
    goto REVCOMLOOP;
  }
  if (fail.code == NE_NOERROR) {
    /* Post-Process using nag_real_symm_sparse_eigensystem_sol
       (f12fcc) to compute eigenvalues/vectors. */
    nag_real_symm_sparse_eigensystem_sol(&nconv, eigv, v, sigma, resid, v,
                                         comm, icomm, &fail);
    printf("\n The %4" NAG_IFMT " generalized Ritz values", nconv);
    printf(" closest to %8.4f are:\n\n", sigma);
    for (j = 0; j <= nconv - 1; ++j) {
      printf("%8" NAG_IFMT "%5s%12.4f\n", j + 1, "", eigv[j]);
    }
  }
  else {
    printf(" Error from nag_real_symm_sparse_eigensystem_iter "
           "(f12fbc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }
END:
  NAG_FREE(dd);
  NAG_FREE(dl);
  NAG_FREE(du);
  NAG_FREE(du2);
  NAG_FREE(comm);
  NAG_FREE(eigv);
  NAG_FREE(eigest);
  NAG_FREE(resid);
  NAG_FREE(v);
  NAG_FREE(x2);
  NAG_FREE(icomm);
  NAG_FREE(ipiv);

  return exit_status;
}

static void mv(Integer n, double *v, double *y)
{
  /* Scalars */
  double h;
  Integer j;

  /* Function Body */
  h = 1.0 / ((double) (n + 1) * 6.);
  y[0] = h * (v[0] * 4.0 + v[1]);
  for (j = 1; j <= n - 2; ++j) {
    y[j] = h * (v[j - 1] + v[j] * 4.0 + v[j + 1]);
  }
  y[n - 1] = h * (v[n - 2] + v[n - 1] * 4.0);
  return;
} /* mv */

static void my_dgttrf(Integer n, double dl[], double d[],
                      double du[], double du2[], Integer ipiv[],
                      Integer *info)
{
  /* A simple C version of the Lapack routine dgttrf with argument
     checking removed */
  /* Scalars */
  double temp, fact;
  Integer i;
  /* Function Body */
  *info = 0;
  for (i = 0; i < n; ++i) {
    ipiv[i] = i;
  }
  for (i = 0; i < n - 2; ++i) {
    du2[i] = 0.0;
  }
  for (i = 0; i < n - 2; i++) {
    if (fabs(d[i]) >= fabs(dl[i])) {
      /* No row interchange required, eliminate dl[i]. */
      if (d[i] != 0.0) {
        fact = dl[i] / d[i];
        dl[i] = fact;
        d[i + 1] = d[i + 1] - fact * du[i];
      }
    }
    else {
      /* Interchange rows I and I+1, eliminate dl[I] */
      fact = d[i] / dl[i];
      d[i] = dl[i];
      dl[i] = fact;
      temp = du[i];
      du[i] = d[i + 1];
      d[i + 1] = temp - fact * d[i + 1];
      du2[i] = du[i + 1];
      du[i + 1] = -fact * du[i + 1];
      ipiv[i] = i + 1;
    }
  }
  if (n > 1) {
    i = n - 2;
    if (fabs(d[i]) >= fabs(dl[i])) {
      if (d[i] != 0.0) {
        fact = dl[i] / d[i];
        dl[i] = fact;
        d[i + 1] = d[i + 1] - fact * du[i];
      }
    }
    else {
      fact = d[i] / dl[i];
      d[i] = dl[i];
      dl[i] = fact;
      temp = du[i];
      du[i] = d[i + 1];
      d[i + 1] = temp - fact * d[i + 1];
      ipiv[i] = i + 1;
    }
  }
  /* Check for a zero on the diagonal of U. */
  for (i = 0; i < n; ++i) {
    if (d[i] == 0.0) {
      *info = i;
      goto END;
    }
  }
END:
  return;
}

static void my_dgttrs(Integer n, double dl[], double d[],
                      double du[], double du2[], Integer ipiv[],
                      double b[], double y[])
{
  /* A simple C version of the Lapack routine dgttrs with argument
     checking removed, the number of right-hand-sides=1, Trans='N' */
  /* Scalars */
  Integer i, ip;
  double temp;
  /* Solve L*x = b. */
  for (i = 0; i <= n - 1; ++i) {
    y[i] = b[i];
  }
  for (i = 0; i < n - 1; ++i) {
    ip = ipiv[i];
    temp = y[i + 1 - ip + i] - dl[i] * y[ip];
    y[i] = y[ip];
    y[i + 1] = temp;
  }
  /* Solve U*x = b. */
  y[n - 1] = y[n - 1] / d[n - 1];
  if (n > 1) {
    y[n - 2] = (y[n - 2] - du[n - 2] * y[n - 1]) / d[n - 2];
  }
  for (i = n - 3; i >= 0; --i) {
    y[i] = (y[i] - du[i] * y[i + 1] - du2[i] * y[i + 2]) / d[i];
  }
  return;
}