/* nag_zhegv (f08snc) Example Program.
 *
 * Copyright 2017 Numerical Algorithms Group.
 *
 * Mark 26.1, 2017.
 */

#include <math.h>
#include <stdio.h>
#include <nag.h>
#include <nagx04.h>
#include <nag_stdlib.h>
#include <nagf07.h>
#include <nagf08.h>
#include <nagf16.h>
#include <nagx02.h>
#include <naga02.h>

int main(void)
{
  /* Scalars */
  Complex       scal;
  double        anorm, bnorm, eps, r, rcond, rcondb, t1, t2, t3;
  Integer       i, j, k, n, pda, pdb;
  Integer       exit_status = 0, inc = 1;
  /* Arrays */
  Complex       *a = 0, *b = 0;
  double        *eerbnd = 0, *rcondz = 0, *w = 0, *zerbnd = 0, *temp = 0;
  char          nag_enum_arg[40];

  /* Nag Types */
  NagError      fail;
  Nag_OrderType order;
  Nag_UploType  uplo;

#ifdef NAG_COLUMN_MAJOR
#define A(I, J) a[(J-1)*pda + I - 1]
#define B(I, J) b[(J-1)*pdb + I - 1]
  order = Nag_ColMajor;
#else
#define A(I, J) a[(I-1)*pda + J - 1]
#define B(I, J) b[(I-1)*pdb + J - 1]
  order = Nag_RowMajor;
#endif

  INIT_FAIL(fail);

  printf("nag_zhegv (f08snc) Example Program Results\n\n");

  /* Skip heading in data file */
  scanf("%*[^\n]");
  scanf("%" NAG_IFMT "%*[^\n]", &n);
  if (n < 0) {
    printf("Invalid n\n");
    exit_status = 1;
    goto END;;
  }
  scanf(" %39s%*[^\n]", nag_enum_arg);
  /* nag_enum_name_to_value (x04nac).
   * Converts NAG enum member name to value
   */
  uplo = (Nag_UploType) nag_enum_name_to_value(nag_enum_arg);

  pda = n;
  pdb = n;
  /* Allocate memory */
  if (!(a = NAG_ALLOC(n * n, Complex)) ||
      !(b = NAG_ALLOC(n * n, Complex)) ||
      !(eerbnd = NAG_ALLOC(n, double)) ||
      !(rcondz = NAG_ALLOC(n, double)) ||
      !(temp = NAG_ALLOC(n, double)) ||
      !(w = NAG_ALLOC(n, double)) || !(zerbnd = NAG_ALLOC(n, double)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }

  /* Read the triangular parts of the matrices A and B */
  if (uplo == Nag_Upper) {
    for (i = 1; i <= n; ++i)
      for (j = i; j <= n; ++j)
        scanf(" ( %lf , %lf ) ", &A(i, j).re, &A(i, j).im);
    scanf("%*[^\n]");
    for (i = 1; i <= n; ++i)
      for (j = i; j <= n; ++j)
        scanf(" ( %lf , %lf ) ", &B(i, j).re, &B(i, j).im);
  }
  else {
    for (i = 1; i <= n; ++i)
      for (j = 1; j <= i; ++j)
        scanf(" ( %lf , %lf ) ", &A(i, j).re, &A(i, j).im);
    scanf("%*[^\n]");
    for (i = 1; i <= n; ++i)
      for (j = 1; j <= i; ++j)
        scanf(" ( %lf , %lf ) ", &B(i, j).re, &B(i, j).im);
  }
  scanf("%*[^\n]");

  /* Compute the one-norms of the symmetric matrices A and B
   * using nag_zhe_norm (f16ucc).
   */
  nag_zhe_norm(order, Nag_OneNorm, uplo, n, a, pda, &anorm, &fail);
  nag_zhe_norm(order, Nag_OneNorm, uplo, n, b, pdb, &bnorm, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_zhe_norm (f16ucc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  /* Solve the generalized Hermitian eigenvalue problem A*x = lambda*B*x
   * using nag_zhegv (f08snc). 
   */
  nag_zhegv(order, 1, Nag_DoBoth, uplo, n, a, pda, b, pdb, w, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_zhegv (f08snc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  /* Print eigensolution */
  printf(" Eigenvalues\n  ");
  for (j = 0; j < n; ++j)
    printf(" %11.4f%s", w[j], j % 6 == 5 ? "\n" : "");
  printf("\n");

  /* Normalize the eigenvectors, largest element real
   * (normalization w.r.t B unaffected: Z^HBZ = I).
   */
  for (j = 1; j <= n; j++) {
     for (i = 1; i <= n; i++) {
       /* nag_complex_abs (a02dbc).
        * Modulus of a complex number
        */
       temp[i-1] = nag_complex_abs(A(i,j));
     }
     /* nag_dmax_val (f16jnc).
      * Get maximum value (r) and location of that value (k) of double array.
      */
     nag_dmax_val(n, temp, inc, &k, &r, &fail);
     if (fail.code != NE_NOERROR) {
       printf("Error from nag_dmax_val (f16jnc).\n%s\n", fail.message);
       exit_status = 1;
       goto END;
     }
     k = k + 1;
     scal.re = A(k,j).re/r;
     scal.im = -A(k,j).im/r;
     for (i = 1; i <= n; i++)
       A(i, j) = nag_complex_multiply(A(i, j), scal);
     A(k, j).im = 0.0;
  }
  /* Print normalized vectors using nag_gen_complx_mat_print (x04dac). */
  fflush(stdout);
  nag_gen_complx_mat_print(order, Nag_GeneralMatrix, Nag_NonUnitDiag, n, n,
                           a, pda, "Eigenvectors", 0, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_gen_complx_mat_print (x04dac).\n%s\n",
           fail.message);
    exit_status = 1;
    goto END;
  }

  /* Estimate the reciprocal condition number of the Cholesky factor of B.
   * nag_ztrcon (f07tuc)
   * Note that: cond(B) = 1/(rcond*rcond)
   */
  nag_ztrcon(order, Nag_OneNorm, uplo, Nag_NonUnitDiag, n, b, pdb, &rcond,
             &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_ztrcon (f07tuc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  /* Print the reciprocal condition number of B */
  rcondb = rcond * rcond;
  printf("\nEstimate of reciprocal condition number for B\n    %11.1e\n",
         rcondb);

  /* Get the machine precision, using nag_machine_precision (x02ajc) */
  eps = nag_machine_precision;
  if (rcond < eps) {
    printf("\nB is very ill-conditioned, error estimates have not been"
           " computed\n");
    goto END;
  }

  /* Call nag_ddisna (f08flc) to estimate reciprocal condition numbers for the
   * eigenvectors of (A - lambda*B)
   */
  nag_ddisna(Nag_EigVecs, n, n, w, rcondz, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_ddisna (f08flc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  /* Compute the error estimates for the eigenvalues and  eigenvectors. */
  t1 = eps / rcondb;
  t2 = anorm / bnorm;
  t3 = t2 / rcond;
  for (i = 0; i < n; ++i) {
    eerbnd[i] = t1 * (t2 + fabs(w[i]));
    zerbnd[i] = t1 * (t3 + fabs(w[i])) / rcondz[i];
  }

  /* Print the approximate error bounds for the eigenvalues and vectors. */
  printf("\nError estimates for the eigenvalues\n    ");
  for (i = 0; i < n; ++i)
    printf(" %10.1e%s", eerbnd[i], i % 6 == 5 ? "\n" : "");

  printf("\n\nError estimates for the eigenvectors\n    ");
  for (i = 0; i < n; ++i)
    printf(" %10.1e%s", zerbnd[i], i % 6 == 5 ? "\n" : "");
  printf("\n");

END:
  NAG_FREE(a);
  NAG_FREE(b);
  NAG_FREE(eerbnd);
  NAG_FREE(rcondz);
  NAG_FREE(w);
  NAG_FREE(zerbnd);
  NAG_FREE(temp);

  return exit_status;
}