/* nag_dormhr (f08ngc) 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 <nagx02.h>
#include <nagx04.h>

int main(void)
{
  /* Scalars */
  Integer       i, j, k, l, m, n, pda, pdh, pdvl, pdvr, pdz;
  Integer       tau_len, ifaill_len, select_len, w_len;
  Integer       exit_status = 0;
  double        thresh, r, s;
  Complex       eig, eig1;
  /* Arrays */
  double        *a = 0, *h = 0, *vl = 0, *vr = 0, *z = 0, *wi = 0, *wr = 0;
  double        *tau = 0;
  Integer       *ifaill = 0, *ifailr = 0;

  /* Nag Types */
  NagError      fail;
  Nag_OrderType order;
  Nag_Boolean   *select = 0;

#ifdef NAG_COLUMN_MAJOR
#define A(I, J) a[(J - 1) * pda + I - 1]
#define H(I, J) h[(J - 1) * pdh + I - 1]
#define VR(I, J) vr[(J - 1) * pdvr + I - 1]
  order = Nag_ColMajor;
#else
#define A(I, J) a[(I - 1) * pda + J - 1]
#define H(I, J) h[(I - 1) * pdh + J - 1]
#define VR(I, J) vr[(I - 1) * pdvr + J - 1]
  order = Nag_RowMajor;
#endif

  INIT_FAIL(fail);

  printf("nag_dormhr (f08ngc) Example Program Results\n\n");

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

  pda = n;
  pdh = n;
  pdvl = n;
  pdvr = n;
  pdz = 1;
  tau_len = n;
  w_len = n;
  ifaill_len = n;
  select_len = n;

  /* Allocate memory */
  if (!(a = NAG_ALLOC(n * n, double)) ||
      !(h = NAG_ALLOC(n * n, double)) ||
      !(vl = NAG_ALLOC(n * n, double)) ||
      !(vr = NAG_ALLOC(n * n, double)) ||
      !(z = NAG_ALLOC(1 * 1, double)) ||
      !(wi = NAG_ALLOC(w_len, double)) ||
      !(wr = NAG_ALLOC(w_len, double)) ||
      !(ifaill = NAG_ALLOC(ifaill_len, Integer)) ||
      !(ifailr = NAG_ALLOC(ifaill_len, Integer)) ||
      !(select = NAG_ALLOC(select_len, Nag_Boolean)) ||
      !(tau = NAG_ALLOC(tau_len, double)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }
  /* Read A from data file */
  for (i = 1; i <= n; ++i)
    for (j = 1; j <= n; ++j)
      scanf("%lf", &A(i, j));
  scanf("%*[^\n]");
  scanf("%lf%*[^\n]", &thresh);

  /* Reduce A to upper Hessenberg form */
  /* nag_dgehrd (f08nec).
   * Orthogonal reduction of real general matrix to upper
   * Hessenberg form
   */
  nag_dgehrd(order, n, 1, n, a, pda, tau, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_dgehrd (f08nec).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  /* Copy A to H */
  for (i = 1; i <= n; ++i)
    for (j = 1; j <= n; ++j)
      H(i, j) = A(i, j);

  /* Calculate the eigenvalues of H (same as A) */
  /* nag_dhseqr (f08pec).
   * Eigenvalues and Schur factorization of real upper
   * Hessenberg matrix reduced from real general matrix
   */
  nag_dhseqr(order, Nag_EigVals, Nag_NotZ, n, 1, n, h, pdh, wr,
             wi, z, pdz, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_dhseqr (f08pec).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  /* Print eigenvalues */
  printf(" Eigenvalues\n");
  for (i = 0; i < n; ++i)
    printf(" (%8.4f,%8.4f)\n", wr[i], wi[i]);
  printf("\n");
  for (i = 0; i < n; ++i)
    select[i] = wr[i] < thresh ? Nag_TRUE : Nag_FALSE;
  /* Calculate the eigenvectors of H (as specified by SELECT), */
  /* storing the result in VR */
  /* nag_dhsein (f08pkc).
   * Selected right and/or left eigenvectors of real upper
   * Hessenberg matrix by inverse iteration
   */
  nag_dhsein(order, Nag_RightSide, Nag_HSEQRSource, Nag_NoVec, select,
             n, a, pda, wr, wi, vl, pdvl, vr, pdvr, n, &m, ifaill,
             ifailr, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_dhsein (f08pkc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  /* Calculate the eigenvectors of A = Q * VR */
  /* nag_dormhr (f08ngc).
   * Apply orthogonal transformation matrix from reduction to
   * Hessenberg form determined by nag_dgehrd (f08nec)
   */
  nag_dormhr(order, Nag_LeftSide, Nag_NoTrans, n, m, 1, n, a, pda,
             tau, vr, pdvr, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_dormhr (f08ngc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  /* Scale selected eigenvectors */
  j = 0;
  for (k = 0; k < n; k++) {
    if (select[k]) {
      j++;
      if (wi[k] == 0.0) {
        r = 0.0;
        l = 0;
        s = 0.0;
        for (i = 1; i <= n; i++) {
          h[i-1] = VR(i, j)*VR(i, j);
          s += h[i-1];
          if (h[i-1]>r) {
            l = i-1;
            r = h[l];
          }
        }
        if (VR(l,j)<0.0) {
          for (i=1;i<=n;i++) {
            VR(i,j) = -VR(i,j)/sqrt(s);
          }
        } else {
          for (i=1;i<=n;i++) {
            VR(i,j) = VR(i,j)/sqrt(s);
          }
        }
      } else {
        r = 0.0;
        l = 0;
        s = 0.0;
        for (i = 1; i <= n; i++) {
          h[i-1] = VR(i, j)*VR(i, j) + VR(i, j+1)*VR(i, j+1);
          s += h[i-1];
          if (h[i-1]>r) {
            l = i-1;
            r = h[l];
          }
        }
        r = sqrt(r*s);
        eig1.re = VR(l+1, j)/r;
        eig1.im = -VR(l+1, j+1)/r;
        for (i = 1; i <= n; i++) {
          eig = nag_complex(VR(i, j), VR(i, j+1));
          eig = nag_complex_multiply(eig, eig1);
          if (fabs(eig.re)<10.0*x02ajc()) {
            VR(i, j) = 0.0;
          } else {
            VR(i, j) = eig.re;
          }
          if (fabs(eig.im)<10.0*x02ajc()) {
            VR(i, j+1) = 0.0;
          } else {
            VR(i, j+1) = eig.im;
          }
        }
        j++;
        k++;
      }
    }
  }
  /* Print Eigenvectors */
  /* nag_gen_real_mat_print (x04cac).
   * Print real general matrix (easy-to-use)
   */
  fflush(stdout);
  nag_gen_real_mat_print(order, Nag_GeneralMatrix, Nag_NonUnitDiag, n, m, vr,
                         pdvr, "Contents of array VR", 0, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_gen_real_mat_print (x04cac).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }
END:
  NAG_FREE(a);
  NAG_FREE(h);
  NAG_FREE(vl);
  NAG_FREE(vr);
  NAG_FREE(z);
  NAG_FREE(wi);
  NAG_FREE(wr);
  NAG_FREE(ifaill);
  NAG_FREE(ifailr);
  NAG_FREE(select);
  NAG_FREE(tau);
  return exit_status;
}