/* nag_zgges3 (f08xqc) Example Program.
 *
 * Copyright 2017 Numerical Algorithms Group.
 *
 * Mark 26.1, 2017.
 */

#include <stdio.h>
#include <math.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <naga02.h>
#include <nagf08.h>
#include <nagf16.h>
#include <nagm01.h>
#include <nagx02.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 e[], size_t rank[],
                              double emod[]);
#ifdef __cplusplus
}
#endif

int main(void)
{

  /* Scalars */
  Complex           alph, bet;
  double            norma, normb, normd, norme, eps;
  Integer           i, j, n, sdim, pda, pdb, pdc, pdd, pde, pdvsl, pdvsr;
  Integer           exit_status = 0, isinf = 0;

  /* Arrays */
  Complex           *a = 0, *alpha = 0, *b = 0, *beta = 0, *c = 0;
  Complex           *d = 0, *e = 0, *vsl = 0, *vsr = 0;
  double            *emod = 0;
  size_t            *rank = 0;
  Nag_LeftVecsType  jobvsl;
  Nag_RightVecsType jobvsr;
  char              nag_enum_arg[40];

  /* 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_zgges3 (f08xqc) 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;
    return exit_status;
  }
  scanf(" %39s%*[^\n]", nag_enum_arg);
  /* nag_enum_name_to_value (x04nac).
   * Converts NAG enum member name to value
   */
  jobvsl = (Nag_LeftVecsType) nag_enum_name_to_value(nag_enum_arg);
  scanf(" %39s%*[^\n]", nag_enum_arg);
  jobvsr = (Nag_RightVecsType) nag_enum_name_to_value(nag_enum_arg);

  pdvsl = (jobvsl == Nag_LeftVecs ? n : 1);
  pdvsr = (jobvsr == Nag_RightVecs ? n : 1);
  pda = n;
  pdb = n;
  pdc = n;
  pdd = n;
  pde = n;
  /* Allocate memory */
  if (!(a = NAG_ALLOC(n * n, Complex)) ||
      !(b = NAG_ALLOC(n * n, Complex)) ||
      !(c = NAG_ALLOC(n * n, Complex)) ||
      !(d = NAG_ALLOC(n * n, Complex)) ||
      !(e = NAG_ALLOC(n * n, Complex)) ||
      !(emod = NAG_ALLOC(n, double)) ||
      !(rank = NAG_ALLOC(n, size_t)) ||
      !(alpha = NAG_ALLOC(n, Complex)) ||
      !(beta = NAG_ALLOC(n, Complex)) ||
      !(vsl = NAG_ALLOC(pdvsl * pdvsl, Complex)) ||
      !(vsr = NAG_ALLOC(pdvsr * pdvsr, Complex)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }

  /* Read in the matrices A and B */
  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]");

  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]");

  /* Copy A and B to D and E respectively: nag_zge_copy (f16tfc),
   * Complex valued general matrix copy.
   */
  nag_zge_copy(order, Nag_NoTrans, n, n, a, pda, d, pdd, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_zge_copy (f16tfc).\n%s\n", fail.message);
    exit_status = 2;
    goto END;
  }
  nag_zge_copy(order, Nag_NoTrans, n, n, b, pdb, e, pde, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_zge_copy (f16tfc).\n%s\n", fail.message);
    exit_status = 3;
    goto END;
  }
  /* nag_zge_norm (f16uac): Find norms of input matrices A and B. */
  nag_zge_norm(order, Nag_OneNorm, n, n, a, pda, &norma, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_zge_norm (f16uac).\n%s\n", fail.message);
    exit_status = 4;
    goto END;
  }
  nag_zge_norm(order, Nag_OneNorm, n, n, b, pdb, &normb, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_zge_norm (f16uac).\n%s\n", fail.message);
    exit_status = 5;
    goto END;
  }

  /* nag_gen_complx_mat_print_comp (x04dbc): Print matrices A and B. */
  fflush(stdout);
  nag_gen_complx_mat_print_comp(order, Nag_GeneralMatrix, Nag_NonUnitDiag, n,
                                n, a, pda, Nag_BracketForm, "%6.2f",
                                "Matrix A", Nag_IntegerLabels, 0,
                                Nag_IntegerLabels, 0, 80, 0, 0, &fail);
  printf("\n");
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_gen_complx_mat_print_comp (x04dbc).\n%s\n",
           fail.message);
    exit_status = 6;
    goto END;
  }
  fflush(stdout);
  nag_gen_complx_mat_print_comp(order, Nag_GeneralMatrix, Nag_NonUnitDiag, n,
                                n, b, pdb, Nag_BracketForm, "%6.2f",
                                "Matrix B", Nag_IntegerLabels, 0,
                                Nag_IntegerLabels, 0, 80, 0, 0, &fail);
  printf("\n");
  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;
  }

  /* Find the generalized Schur form using nag_zgges3 (f08xqc). */
  nag_zgges3(order, jobvsl, jobvsr, Nag_NoSortEigVals, NULLFN, n, a, pda, b,
            pdb, &sdim, alpha, beta, vsl, pdvsl, vsr, pdvsr, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_zgges3 (f08xqc).\n%s\n", fail.message);
    exit_status = 8;
    goto END;
  }

  /* Check generalized Schur Form by reconstruction of Schur vectors are
   * available.
   */
  if (jobvsl == Nag_NotLeftVecs || jobvsr == Nag_NotRightVecs) {
    /* Cannot check factorization by reconstruction Schur vectors. */
    goto END;
  }

  /* Reconstruct A as Q*S*Z^H and subtract from original (D) using the steps
   * C = Q (Q in vsl) using nag_zge_copy (f16tfc).
   * C = C*S (S in a, upper triangular) using nag_ztrmm (f16zfc).
   * D = D - C*Z^H (Z in vsr) using nag_zgemm (f16zac).
   */
  nag_zge_copy(order, Nag_NoTrans, n, n, vsl, pdvsl, c, pdc, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_zge_copy (f16tfc).\n%s\n", fail.message);
    exit_status = 9;
    goto END;
  }
  alph = nag_complex(1.0, 0.0);
  /* nag_ztrmm (f16zfc)  Triangular complex matrix-matrix multiply. */
  nag_ztrmm(order, Nag_RightSide, Nag_Upper, Nag_NoTrans, Nag_NonUnitDiag, n,
            n, alph, a, pda, c, pdc, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_ztrmm (f16zfc).\n%s\n", fail.message);
    exit_status = 10;
    goto END;
  }
  alph = nag_complex(-1.0, 0.0);
  bet = nag_complex(1.0, 0.0);
  nag_zgemm(order, Nag_NoTrans, Nag_ConjTrans, n, n, n, alph, c, pdc, vsr,
            pdvsr, bet, d, pdd, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_zgemm (f16zac).\n%s\n", fail.message);
    exit_status = 11;
    goto END;
  }

  /* Reconstruct B as Q*T*Z^H and subtract from original (E) using the steps
   * Q = Q*T (Q in vsl, T in b, upper triangular) using nag_ztrmm (f16zfc).
   * E = E - Q*Z^H (Z in vsr) using nag_zgemm (f16zac).
   */
  alph = nag_complex(1.0, 0.0);
  nag_ztrmm(order, Nag_RightSide, Nag_Upper, Nag_NoTrans, Nag_NonUnitDiag, n,
            n, alph, b, pdb, vsl, pdvsl, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_ztrmm (f16zfc).\n%s\n", fail.message);
    exit_status = 12;
    goto END;
  }
  alph = nag_complex(-1.0, 0.0);
  bet = nag_complex(1.0, 0.0);
  nag_zgemm(order, Nag_NoTrans, Nag_ConjTrans, n, n, n, alph, vsl, pdvsl, vsr,
            pdvsr, bet, e, pde, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_zgemm (f16zac).\n%s\n", fail.message);
    exit_status = 13;
    goto END;
  }

  /* nag_zge_norm (f16uac): Find norms of difference matrices D and E. */
  nag_zge_norm(order, Nag_OneNorm, n, n, d, pdd, &normd, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_zge_norm (f16uac).\n%s\n", fail.message);
    exit_status = 14;
    goto END;
  }
  nag_zge_norm(order, Nag_OneNorm, n, n, e, pde, &norme, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_zge_norm (f16uac).\n%s\n", fail.message);
    exit_status = 15;
    goto END;
  }

  /* Get the machine precision, using nag_machine_precision (x02ajc) */
  eps = nag_machine_precision;
  if (MAX(normd, norme) > pow(eps, 0.8) * MAX(norma, normb)) {
    printf("The norm of the error in the reconstructed matrices is greater "
           "than expected.\nThe Schur factorization has failed.\n");
    exit_status = 16;
    goto END;
  }

  /* Print details on eigenvalues */
  for (j = 0; j < n; ++j) {
    /* Check for infinite eigenvalues */
    if (nag_complex_abs(beta[j]) < x02ajc()) {
      isinf  = j + 1;
    } else {
      alpha[j] = nag_complex_divide(alpha[j],beta[j]);
    }
  }
  if (isinf) {
    printf("Eigenvalue %2" NAG_IFMT " is numerically infinite.\n",isinf);
  } else {

    /* Sort values by decreasing modulus and store in e[] */
    exit_status=sort_values(n, alpha, rank, emod);

    /* Print the (finite) eigenvalues
     * using nag_gen_complx_mat_print (x04dac).
     */
    fflush(stdout);
    printf("\n");
    nag_gen_complx_mat_print(Nag_ColMajor, Nag_GeneralMatrix, Nag_NonUnitDiag,
                             1, n, alpha, 1, "Eigenvalues:", NULL, &fail);
    if (fail.code != NE_NOERROR) {
      printf("Error from nag_gen_complx_mat_print (x04dac).\n%s\n",
             fail.message);
      exit_status = 3;
      goto END;
    }
  }

END:
  NAG_FREE(a);
  NAG_FREE(b);
  NAG_FREE(c);
  NAG_FREE(d);
  NAG_FREE(e);
  NAG_FREE(alpha);
  NAG_FREE(beta);
  NAG_FREE(vsl);
  NAG_FREE(vsr);
  NAG_FREE(emod);
  NAG_FREE(rank);

  return exit_status;
}
static Integer sort_values (Integer n, 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_abs (a02ddc): Moduli of complex number. */
    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));
}