/* nag_zhgeqz (f08xsc) Example Program.
 *
 * Copyright 2017 Numerical Algorithms Group.
 *
 * Mark 26.1, 2017.
 */

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

#ifdef __cplusplus
extern "C"
{
#endif
  static Integer NAG_CALL compare(const Nag_Pointer a, const Nag_Pointer b);
  static Integer sort_values (Integer n, Complex alpha[], Complex beta[],
                              Complex e[], size_t rank[], double emod[]);
#ifdef __cplusplus
}
#endif

int main(void)
{
  /* Scalars */
  Integer        i, ihi, ilo, irows, j, n, pda, pdb, ninf;
  Integer        exit_status = 0;

  /* Arrays */
  Complex       *a = 0, *alpha = 0, *b = 0, *beta = 0, *q = 0, *tau = 0;
  Complex       *z = 0, *e = 0;
  double        *lscale = 0, *rscale = 0, *emod = 0;
  size_t        *rank = 0;

  /* Nag Types */
  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]
  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_zhgeqz (f08xsc) Example Program Results\n\n");
  /* Skip heading in data file */
  scanf("%*[^\n] ");
  scanf("%" NAG_IFMT "%*[^\n] ", &n);
  pda = n;
  pdb = n;

  /* Allocate memory */
  if (!(a      = NAG_ALLOC(n * n, Complex)) ||
      !(b      = NAG_ALLOC(n * n, Complex)) ||
      !(alpha  = NAG_ALLOC(n, Complex)) ||
      !(beta   = NAG_ALLOC(n, Complex)) ||
      !(q      = NAG_ALLOC(1 * 1, Complex)) ||
      !(tau    = NAG_ALLOC(n, Complex)) ||
      !(lscale = NAG_ALLOC(n, double)) ||
      !(rscale = NAG_ALLOC(n, double)) ||
      !(rank   = NAG_ALLOC(n, size_t)) ||
      !(emod   = NAG_ALLOC(n, double)) ||
      !(e      = NAG_ALLOC(n, Complex)) ||
      !(z      = NAG_ALLOC(1 * 1, Complex)))
  {
    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 matrix pair (A,B) */
  /* nag_zggbal (f08wvc).
   * Balance a pair of complex general matrices
   */
  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;
  }

  /* Matrix A after balancing */
  /* nag_gen_complx_mat_print_comp (x04dbc).
   * Print complex general matrix (comprehensive)
   */
  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) {
    printf("Error from nag_gen_complx_mat_print_comp (x04dbc).\n%s\n",
           fail.message);
    exit_status = 2;
    goto END;
  }
  printf("\n");

  /* Matrix B after balancing */
  /* nag_gen_complx_mat_print_comp (x04dbc), see above. */
  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 = 3;
    goto END;
  }
  printf("\n");

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

  /* Apply the orthogonal transformation to matrix A */
  /* nag_zunmqr (f08auc).
   * Apply unitary transformation determined by nag_zgeqrf
   * (f08asc) or nag_zgeqpf (f08bsc)
   */
  nag_zunmqr(order, Nag_LeftSide, Nag_ConjTrans, irows, irows, 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 = 5;
    goto END;
  }

  /* Compute the generalized Hessenberg form of (A,B) */
  /* nag_zgghd3 (f08wtc).
   * Unitary reduction of a pair of complex general matrices
   * to generalized upper Hessenberg form
   */
  nag_zgghd3(order, Nag_NotQ, Nag_NotZ, irows, 1, irows, &A(ilo, ilo),
             pda, &B(ilo, ilo), pdb, q, 1, z, 1, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_zgghd3 (f08wtc).\n%s\n", fail.message);
    exit_status = 6;
    goto END;
  }

  /* Matrix A in generalized Hessenberg form */
  /* nag_gen_complx_mat_print_comp (x04dbc), see above. */
  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("Error from nag_gen_complx_mat_print_comp (x04dbc).\n%s\n",
           fail.message);
    exit_status = 7;
    goto END;
  }
  printf("\n");
  /* Matrix B in generalized Hessenberg form */
  /* nag_gen_complx_mat_print_comp (x04dbc), see above. */
  fflush(stdout);
  nag_gen_complx_mat_print_comp(order, Nag_GeneralMatrix, Nag_NonUnitDiag, n,
                                n, b, pdb, Nag_BracketForm, "%7.3f",
                                "Matrix B is triangular",
                                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 = 8;
    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_EigVals, Nag_NotQ, Nag_NotZ, n, ilo, ihi, a,
             pda, b, pdb, alpha, beta, q, 1, z, 1, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_zhgeqz (f08xsc).\n%s\n", fail.message);
    exit_status = 9;
    goto END;
  }

  /* Print the generalized eigenvalues */
  printf("\n Generalized eigenvalues\n");
  ninf = 0;
  for (i = 0; i < n; ++i) {
    if (beta[i].re == 0.0) {
      ninf = ninf + 1;
      printf(" %4" NAG_IFMT "     Infinite eigenvalue\n", i + 1);
    }
  }
  if (ninf==0) {
    /* Sort values by decreasing modulus and store in e[] */
    exit_status=sort_values (n, alpha, beta, e, rank, emod);
    for (i = 0; i < n; ++i) {
      printf(" %4" NAG_IFMT "     (%7.3f,%7.3f)\n", i + 1, e[i].re, e[i].im);
    }
  }
 END:
  NAG_FREE(a);
  NAG_FREE(alpha);
  NAG_FREE(b);
  NAG_FREE(beta);
  NAG_FREE(lscale);
  NAG_FREE(q);
  NAG_FREE(rank);
  NAG_FREE(rscale);
  NAG_FREE(tau);
  NAG_FREE(e);
  NAG_FREE(emod);
  NAG_FREE(z);

  return exit_status;
}
static Integer sort_values (Integer n, Complex alpha[], Complex beta[],
                            Complex e[], size_t rank[], double emod[])
{
  Integer       i, exit_status = 0;
  NagError      fail;

  INIT_FAIL(fail);

  for (i = 0; i < n; ++i) {
    /* nag_complex_divide (a02cdc): Quotient of two complex numbers;
     * nag_complex_abs (a02ddc): Moduli of complex number.
     */
    e[i] = nag_complex_divide(alpha[i], beta[i]);
    emod[i] = nag_complex_abs(e[i]);
  }
  /* Rank sort eigenvalues by absolute values using 
   * nag_rank_sort (m01dsc).
   */
  nag_rank_sort((Pointer) emod, (size_t) n, (ptrdiff_t) (sizeof(double)),
                compare, Nag_Descending, rank, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_rank_sort (m01dsc).\n%s\n", fail.message);
    exit_status = 10;
    goto END;
  }
  /* 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);
    exit_status = 11;
    goto END;
  }
  /* Sort eigenvalues using nag_reorder_vector (m01esc). */
  nag_reorder_vector((Pointer) e, (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);
    exit_status = 12;
    goto END;
  }
 END:
  return exit_status;
}
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));
}