/* nag_dggev3 (f08wcc) Example Program.
 *
 * Copyright 2017 Numerical Algorithms Group.
 *
 * Mark 26.1, 2017.
 */

#include <math.h>
#include <stdio.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <nagf08.h>
#include <nagx02.h>
#include <nagx04.h>
#include <nagm01.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(Integer n, double alphai[], double v[],
                                   Complex w[], size_t rank[],
                                   const char *title);
  static Integer sort_values (Integer n, Complex alpha[], size_t rank[],
                              double temp[]);
#ifdef __cplusplus
}
#endif

int main(void)
{
  /* Scalars */
  Integer           i, isinf, j, n, pda, pdb, pdvl, pdvr;
  Integer           exit_status = 0;

  /* Arrays */
  Complex           *eval=0, *evec=0; 
  double            *a = 0, *alphai = 0, *alphar = 0, *b = 0, *beta = 0;
  double            *vl = 0, *vr = 0, *ea = 0;
  char              nag_enum_arg[40];
  size_t            *rank = 0;

  /* Nag Types */
  NagError          fail;
  Nag_OrderType     order;
  Nag_LeftVecsType  jobvl;
  Nag_RightVecsType jobvr;

#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_dggev3 (f08wcc) Example Program Results\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
   */
  jobvl = (Nag_LeftVecsType) nag_enum_name_to_value(nag_enum_arg);
  scanf(" %39s%*[^\n]", nag_enum_arg);
  jobvr = (Nag_RightVecsType) nag_enum_name_to_value(nag_enum_arg);
  pda = n;
  pdb = n;
  pdvl = (jobvl == Nag_LeftVecs ? n : 1);
  pdvr = (jobvr == Nag_RightVecs ? n : 1);

  /* Allocate memory */
  if (!(a = NAG_ALLOC(n * n, double)) ||
      !(alphai = NAG_ALLOC(n, double)) ||
      !(alphar = NAG_ALLOC(n, double)) ||
      !(b = NAG_ALLOC(n * n, double)) ||
      !(beta = NAG_ALLOC(n, double)) ||
      !(vl = NAG_ALLOC(pdvl * pdvl, double)) ||
      !(vr = NAG_ALLOC(pdvr * pdvr, double)) ||
      !(ea = NAG_ALLOC(n, double)) ||
      !(eval = NAG_ALLOC(n, Complex)) ||
      !(evec = NAG_ALLOC(n * n, Complex)) ||
      !(rank = NAG_ALLOC(n, size_t)))
   {
    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", &A(i, j));
  scanf("%*[^\n]");
  for (i = 1; i <= n; ++i)
    for (j = 1; j <= n; ++j)
      scanf("%lf", &B(i, j));
  scanf("%*[^\n]");

  /* Solve the generalized eigenvalue problem Ax = lambda Bx using the 
   * level 3 blocked routine nag_dggev3 (f08wcc) which returns:
   *  - eigenvalues as (alphar[] + i*alphai[])./beta[];
   *  - left and right eigenvectors in vl and vr respectively.
   */
  nag_dggev3(order, jobvl, jobvr, n, a, pda, b, pdb, alphar, alphai, beta, vl,
            pdvl, vr, pdvr, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_dggev3 (f08wcc).\n%s\n", fail.message);
    exit_status = 2;
    goto END;
  }

  isinf = 0;
  for (j = 0; j < n; ++j) {
    /* Check for infinite, real and complex eigenvalues in that order */
    if (fabs(beta[j]) < x02ajc()) {
      isinf  = j + 1;
    } else {
      eval[j].re = alphar[j]/beta[j];
      eval[j].im = alphai[j]/beta[j] + 10.0*x02ajc();
    }
  }
  if (isinf) {
    printf("Eigenvalue %2" NAG_IFMT " is numerically infinite.\n",isinf);
  } else {
    /* Print the ordered (finite) eigenvalues. */
    exit_status = sort_values(n, eval, rank, ea);
    if (exit_status) {
      goto END;
    }
  }

  if (jobvl == Nag_LeftVecs) {
    /* Normalize and print the left eigenvectors */
    exit_status = normalize_vectors(n, alphai, vl, evec, rank,
                                    "Left eigenvectors:");
    printf("\n");
  }
  if (jobvr == Nag_RightVecs) {
    /* Normalize and print the right eigenvectors */
    exit_status = normalize_vectors(n, alphai, vr, evec, rank,
                                    "Right eigenvectors:");
    printf("\n");
  }

END:
  NAG_FREE(a);
  NAG_FREE(alphai);
  NAG_FREE(alphar);
  NAG_FREE(b);
  NAG_FREE(beta);
  NAG_FREE(vl);
  NAG_FREE(vr);
  NAG_FREE(ea);
  NAG_FREE(eval);
  NAG_FREE(evec);
  NAG_FREE(rank);

  return exit_status;
}

static Integer normalize_vectors(Integer n, double alphai[], double v[],
                                 Complex w[], 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    r, rr;
  Integer   i, j, jj, k, errors = 0;
  NagError  fail;

  INIT_FAIL(fail);

#ifdef NAG_COLUMN_MAJOR
#define V(I, J) v[(J-1)*n + I - 1]
#else
#define V(I, J) v[(I-1)*n + J - 1]
#endif
#define W(I, J) w[(I-1)*n + J - 1]

  /* Re-normalize the eigenvectors, largest absolute element real. */
  k = 0;
  for (i = 1; i<=n; i++) {
    if (fabs(alphai[i-1])<x02ajc()) {
      jj = 1;
      r = 0.0;
      for (j = 1; j <= n; j++) {
        W(j,i).re = V(j,i);
        W(j,i).im = 0.0;
        rr = fabs(V(j,i));
        if (rr>r) {
          r = rr;
          jj = j;
        }
      }
    } else if (k==0) {
      jj = 1;
      r = 0.0;
      for (j = 1; j <= n; j++) {
        W(j,i).re = V(j,i);
        W(j,i).im = V(j,i+1);
        rr = sqrt(V(j,i)*V(j,i) + V(j,i+1)*V(j,i+1));
        if (rr>r) {
          r = rr;
          jj = j;
        }
      }
      k = 1;
    } else {
      for (j = 1; j <= n; j++) {
        W(j,i) = nag_complex_conjg(W(j,i-1));
      }
      k = 0;
    }
    scal = nag_complex_conjg(W(jj,i));
    scal.re = scal.re/r;
    scal.im = scal.im/r;
    for (j = 1; j <= n; j++) {
      /* nag_complex_multiply (a02ccc), multiply two complex numbers */
      W(j,i) = nag_complex_multiply(W(j,i),scal);
    }
  }
  for (j = 1; j <=n; j++) {
    /* Sort eigenvectors by eigenvalue rank using 
     * nag_reorder_vector (m01esc).
     */
    nag_reorder_vector((Pointer) &W(j,1), (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;
    }
  }
  /* Print the normalized eigenvectors using
   * nag_gen_complx_mat_print_comp (x04dbc)
   */
  fflush(stdout);
  nag_gen_complx_mat_print_comp(Nag_RowMajor, Nag_GeneralMatrix,
                                Nag_NonUnitDiag,
                                n, n, w, n, Nag_BracketForm, "%7.4f",
                                title, Nag_NoLabels, 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:
#undef V
#undef W
  return errors;
}

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

  INIT_FAIL(fail);

  /* Accumulate eigenvalue modulii in temp. */
  for (i = 0; i < n; ++i) {
    /* nag_complex_abs (a02cdc) - modulus of complex number. */
    temp[i] = nag_complex_abs(vec[i]);
  }
  /* 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) vec, (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 Eigenvalues:\n");
  for (i = 0; i < n; ++i) {
    printf(" %4" NAG_IFMT "     (%7.3f,%7.3f)\n", i + 1, vec[i].re, vec[i].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));
}