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

#include <stdio.h>
#include <math.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <naga02.h>
#include <nagf06.h>
#include <nagf08.h>
#include <nagf16.h>
#include <nagm01.h>
#include <nagx04.h>
#include <naga02.h>

#ifdef __cplusplus
extern "C"
{
#endif
  static Integer NAG_CALL compare(const Nag_Pointer a, const Nag_Pointer b);
  static Integer normalize_vectors(Nag_OrderType order, Integer n, Complex qz[],
                                   Complex tz[], double temp[], size_t rank[],
                                   const char *title);
  static Integer sort_values (Integer n, Complex alpha[], Complex beta[],
                              size_t rank[], double temp[]);
#ifdef __cplusplus
}
#endif

int main(void)
{
  /* Scalars */
  Integer       i, icols, ihi, ilo, irows, j, m, n, pda, pdb, pdq, pdz;
  Integer       exit_status = 0, prbal = 0, prhess = 0;
  Complex       one, zero;
  /* Arrays */
  Complex       *a = 0, *alpha = 0, *b = 0, *beta = 0, *q = 0, *tau = 0;
  Complex       *z = 0;
  double        *lscale = 0, *rscale = 0, *temp = 0;
  size_t        *rank = 0;
  /* Nag Types */
  Nag_Boolean   ileft, iright;
  NagError      fail;
  Nag_OrderType order;

#ifdef NAG_COLUMN_MAJOR
#define A(I, J) a[(J-1)*pda + I - 1]
#define B(I, J) b[(J-1)*pdb + I - 1]
#define Q(I, J) q[(J-1)*pdq + 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]
#define Q(I, J) q[(I-1)*pdq + J - 1]
  order = Nag_RowMajor;
#endif

  INIT_FAIL(fail);

  printf("nag_ztgevc (f08yxc) Example Program Results\n\n");

  /* ileft  is true if left  eigenvectors are required;
   * iright is true if right eigenvectors are required.
   */
  ileft = Nag_TRUE;
  iright = Nag_TRUE;
  zero = nag_complex(0.0, 0.0);
  one = nag_complex(1.0, 0.0);

  /* Skip heading in data file and read matrix size. */
  scanf("%*[^\n] ");
  scanf("%" NAG_IFMT "%*[^\n] ", &n);

  pda = n;
  pdb = n;
  pdq = n;
  pdz = n;

  /* Allocate memory */
  if (!(a = NAG_ALLOC(n * n, Complex)) ||
      !(b = NAG_ALLOC(n * n, Complex)) ||
      !(q = NAG_ALLOC(n * n, Complex)) ||
      !(z = NAG_ALLOC(n * n, Complex)) ||
      !(alpha = NAG_ALLOC(n, Complex)) ||
      !(beta = NAG_ALLOC(n, Complex)) ||
      !(tau = NAG_ALLOC(n, Complex)) ||
      !(temp = NAG_ALLOC(n, double)) ||
      !(rank = NAG_ALLOC(n, size_t)) ||
      !(lscale = NAG_ALLOC(n, double)) || !(rscale = NAG_ALLOC(n, double)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }

  /* READ matrix A from data file */
  for (i = 1; i <= n; ++i)
    for (j = 1; j <= n; ++j)
      scanf(" ( %lf , %lf )", &A(i, j).re, &A(i, j).im);
  scanf("%*[^\n] ");

  /* READ matrix B from data file */
  for (i = 1; i <= n; ++i)
    for (j = 1; j <= n; ++j)
      scanf(" ( %lf , %lf )", &B(i, j).re, &B(i, j).im);
  scanf("%*[^\n] ");

  /* Balance pair (A,B) of complex general matrices using  
   * nag_zggbal (f08wvc).
   */
  nag_zggbal(order, Nag_DoBoth, n, a, pda, b, pdb, &ilo, &ihi, lscale,
             rscale, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_zggbal (f08wvc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  if (prbal) {
    /* Print complex general matrices A and B after balancing using 
     * nag_gen_complx_mat_print_comp (x04dbc).
     */
    fflush(stdout);
    nag_gen_complx_mat_print_comp(order, Nag_GeneralMatrix, Nag_NonUnitDiag, n,
                                  n, a, pda, Nag_BracketForm, "%7.4f",
                                  "Matrix A after balancing",
                                  Nag_IntegerLabels, 0, Nag_IntegerLabels, 0,
                                  80, 0, 0, &fail);
    if (fail.code == NE_NOERROR) {
      fflush(stdout);
      nag_gen_complx_mat_print_comp(order, Nag_GeneralMatrix, Nag_NonUnitDiag,
                                    n, n, b, pdb, Nag_BracketForm, "%7.4f",
                                    "Matrix B after balancing",
                                    Nag_IntegerLabels, 0, Nag_IntegerLabels, 0,
                                    80, 0, 0, &fail);
    }
    if (fail.code != NE_NOERROR) {
      printf("Error from nag_gen_complx_mat_print_comp (x04dbc).\n%s\n",
             fail.message);
      exit_status = 1;
      goto END;
    }
    printf("\n");
  }

  /* Reduce B to triangular form using QR and premultiply A by Q^H. */
  irows = ihi + 1 - ilo;
  icols = n + 1 - ilo;
  /* nag_zgeqrf (f08asc).
   * QR factorization of complex general rectangular matrix B.
   */
  nag_zgeqrf(order, irows, icols, &B(ilo, ilo), pdb, tau, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_zgeqrf (f08asc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  /* Apply the orthogonal transformation Q^H to matrix A using
   * nag_zunmqr (f08auc).
   */
  nag_zunmqr(order, Nag_LeftSide, Nag_ConjTrans, irows, icols, irows,
             &B(ilo, ilo), pdb, tau, &A(ilo, ilo), pda, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_zunmqr (f08auc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  /* Initialize Q (if left eigenvectors are required) */
  if (ileft) {
    /* Q = I */
    nag_zge_load(order, n, n, zero, one, q, pdq, &fail);
    /* Q = B using nag_zge_copy (f16tfc). */
    nag_zge_copy(order, Nag_NoTrans, irows - 1, irows - 1, &B(ilo + 1, ilo),
                 pdb, &Q(ilo + 1, ilo), pdq, &fail);
    /* Form Q from QR factorization using nag_zungqr (f08atc). */
    nag_zungqr(order, irows, irows, irows, &Q(ilo, ilo), pdq, tau, &fail);
    if (fail.code != NE_NOERROR) {
      printf("Error from nag_zungqr (f08atc).\n%s\n", fail.message);
      exit_status = 1;
      goto END;
    }
  }

  if (iright) {
    /* Z = I. */
    nag_zge_load(order, n, n, zero, one, z, pdz, &fail);
  }

  /* Compute the generalized Hessenberg form of (A,B) by Unitary reduction
   * using nag_zgghrd (f08wsc).
   */
  nag_zgghrd(order, Nag_UpdateSchur, Nag_UpdateZ, n, ilo, ihi, a, pda, b, pdb,
             q, pdq, z, pdz, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_zgghrd (f08wsc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }
  if (prhess) {
    /* Print generalized Hessenberg form of (A,B) using
     * nag_gen_complx_mat_print_comp (x04dbc).
     */
    fflush(stdout);
    nag_gen_complx_mat_print_comp(order, Nag_GeneralMatrix, Nag_NonUnitDiag, n,
                                  n, a, pda, Nag_BracketForm, "%7.3f",
                                  "Matrix A in Hessenberg form",
                                  Nag_IntegerLabels, 0, Nag_IntegerLabels, 0,
                                  80, 0, 0, &fail);
    if (fail.code == NE_NOERROR) {
      printf("\n");

      fflush(stdout);
      nag_gen_complx_mat_print_comp(order, Nag_GeneralMatrix, Nag_NonUnitDiag,
                                    n, n, b, pdb, Nag_BracketForm, "%7.3f",
                                    "Matrix B in Hessenberg form",
                                    Nag_IntegerLabels, 0, Nag_IntegerLabels, 0,
                                    80, 0, 0, &fail);
    }
    if (fail.code != NE_NOERROR) {
      printf("Error from nag_gen_complx_mat_print_comp (x04dbc).\n%s\n",
             fail.message);
      exit_status = 1;
      goto END;
    }
  }

  /* Compute the generalized Schur form - nag_zhgeqz (f08xsc).
   * Eigenvalues and generalized Schur factorization of
   * complex generalized upper Hessenberg form reduced from a
   * pair of complex general matrices
   */
  nag_zhgeqz(order, Nag_Schur, Nag_AccumulateQ, Nag_AccumulateZ, n, ilo, ihi,
             a, pda, b, pdb, alpha, beta, q, pdq, z, pdz, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_zhgeqz (f08xsc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  /* Print the ordered generalized eigenvalues if finite */
  exit_status = sort_values(n, alpha, beta, rank, temp);
  if (exit_status) {
    goto END;
  }

  /* nag_ztgevc (f08yxc).
   * Left and right eigenvectors of a pair of complex upper
   * triangular matrices
   */
  nag_ztgevc(order, Nag_BothSides, Nag_BackTransform, NULL, n, a, pda,
             b, pdb, q, pdq, z, pdz, n, &m, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_ztgevc (f08yxc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }
  if (iright) {
    /* nag_zggbak (f08wwc).
     * Transform eigenvectors of a pair of complex balanced
     * matrices to those of original matrix pair supplied to
     * nag_zggbal (f08wvc)
     */
    nag_zggbak(order, Nag_DoBoth, Nag_RightSide, n, ilo, ihi, lscale,
               rscale, n, z, pdz, &fail);
    if (fail.code != NE_NOERROR) {
      printf("Error from nag_zggbak (f08wwc).\n%s\n", fail.message);
      exit_status = 1;
      goto END;
    }

    /* Normalize and print the right eigenvectors */
    exit_status = normalize_vectors(order, n, z, a, temp, rank,
                                    "Right eigenvectors");
    printf("\n");
  }

  /* Compute left eigenvectors of the original matrix */
  if (ileft) {
    /* nag_zggbak (f08wwc), see above. */
    nag_zggbak(order, Nag_DoBoth, Nag_LeftSide, n, ilo, ihi, lscale,
               rscale, n, q, pdq, &fail);
    if (fail.code != NE_NOERROR) {
      printf("Error from nag_zggbak (f08wwc).\n%s\n", fail.message);
      exit_status = 1;
      goto END;
    }

    /* Normalize and print the left eigenvectors */
    exit_status = normalize_vectors(order, n, q, a, temp, rank,
                                    "Left eigenvectors");
  }
END:
  NAG_FREE(a);
  NAG_FREE(b);
  NAG_FREE(q);
  NAG_FREE(z);
  NAG_FREE(alpha);
  NAG_FREE(beta);
  NAG_FREE(tau);
  NAG_FREE(temp);
  NAG_FREE(rank);
  NAG_FREE(lscale);
  NAG_FREE(rscale);

  return exit_status;
}

static Integer normalize_vectors(Nag_OrderType order, Integer n, Complex qz[],
                                 Complex tz[], double temp[], size_t rank[],
                                 const char *title)
{
  /* Each complex eigenvector is normalized so that the element of largest
   * magnitude is scaled to be real and positive.
   */

  Complex   scal;
  double    norm, r;
  Integer   i, j, k, errors = 0;
  NagError  fail;

  INIT_FAIL(fail);

#ifdef NAG_COLUMN_MAJOR
#define Z(I, J) qz[(J-1)*n + I - 1]
#define T(I, J) tz[(J-1)*n + I - 1]
  order = Nag_ColMajor;
#else
#define Z(I, J) qz[(I-1)*n + J - 1]
#define T(I, J) tz[(I-1)*n + J - 1]
  order = Nag_RowMajor;
#endif

  for (j = 1; j <=n; j++) {
    /* Find element of eigenvector with largest absolute value using
     * nag_complex_abs (a02dbc) and nag_dmax_val (f16jnc). 
     */
    norm = 0.0;
    for (i = 1; i <= n; i++) {
      temp[i-1] = nag_complex_abs(Z(i,j));
      norm = norm + temp[i-1]*temp[i-1];
    }
    norm = sqrt(norm);
    nag_dmax_val(n, temp, 1, &k, &r, &fail);
    if (fail.code != NE_NOERROR) {
      printf("Error from nag_dmax_val (f16jnc).\n%s\n", fail.message);
      errors = 1;
      goto END;
    }
    k = k + 1;
    scal.re = Z(k,j).re/r/norm;
    scal.im = -Z(k,j).im/r/norm;
    for (i = 1; i <= n; i++)
      Z(i, j) = nag_complex_multiply(Z(i, j), scal);
    Z(k, j).im = 0.0;

  }
  for (j = 1; j <=n; j++) {
    k = (Integer) rank[j-1];
    for (i = 1; i <= n; i++) {
      T(i,j) = Z(i,k+1);
    }
  }
  /* Print the normalized eigenvectors using
   * nag_gen_complx_mat_print_comp (x04dbc)
   */
  fflush(stdout);
  nag_gen_complx_mat_print_comp(order, Nag_GeneralMatrix, Nag_NonUnitDiag,
                                n, n, tz, n, Nag_BracketForm, "%7.4f",
                                title, Nag_IntegerLabels, 0,
                                Nag_IntegerLabels, 0, 80, 0, 0, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_gen_complx_mat_print_comp (x04dbc).\n%s\n",
           fail.message);
    errors = 3;
  }
END:
  return errors;
}

static Integer sort_values (Integer n, Complex alpha[], Complex beta[],
                            size_t rank[], double temp[])
{
  Integer  i, errors = 0, isinf = 0;
  Complex  e;
  NagError fail;

  INIT_FAIL(fail);

  /* Accumulate eigenvalue modulii in temp. */
  for (i = 0; i < n; ++i) {
    if (beta[i].re != 0.0) {
      /* nag_complex_divide (a02cdc) - Quotient of two complex numbers. */
      e = nag_complex_divide(alpha[i], beta[i]);
      temp[i] = nag_complex_abs(e);
      alpha[i] = e;
    } else {
      isinf = i;
      printf(" %4" NAG_IFMT "Eigenvalue is infinite\n", isinf + 1);
      goto END;
    }
  }
  /* Rank sort eigenvalues by absolute values using nag_rank_sort (m01dsc). */
  nag_rank_sort((Pointer) temp, (size_t) n, (ptrdiff_t) (sizeof(double)),
                compare, Nag_Descending, rank, &fail);
  /* Turn ranks into indices using nag_make_indices (m01zac). */
  nag_make_indices(rank, (size_t) n, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_make_indices (m01zac).\n%s\n", fail.message);
    errors = 1;
    goto END;
  }
  /* Sort eigenvalues using nag_reorder_vector (m01esc). */
  nag_reorder_vector((Pointer) alpha, (size_t) n, sizeof(Complex),
                     (ptrdiff_t) sizeof(Complex), rank, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_reorder_vector (m01esc).\n%s\n", fail.message);
    errors = 2;
    goto END;
  }
  printf("\n Generalized eigenvalues\n");
  for (i = 0; i < n; ++i) {
    e = alpha[i];
    printf(" %4" NAG_IFMT "     (%7.3f,%7.3f)\n", i + 1, e.re, e.im);
  }
  printf("\n");
 END:
  return errors;
}

static Integer NAG_CALL compare(const Nag_Pointer a, const Nag_Pointer b)
{
  double x = *((const double *) a) - *((const double *) b);
  return (x < 0.0 ? -1 : (x == 0.0 ? 0 : 1));
}