/* nag_dtgexc (f08yfc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 23, 2011.
 */

#include <stdio.h>
#include <math.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <nagf08.h>
#include <nagf16.h>
#include <nagx02.h>
#include <nagx04.h>

int main(void)
{
  /* Scalars */
  double        alpha, beta, eps, norma, normb, norms, normt;
  Integer       i, ifst, ilst, j, n, pda, pdb, pdc, pdq, pds;
  Integer       pdt, pdz, exit_status = 0;
  /* Arrays */
  double        *a = 0, *b = 0, *c = 0, *q = 0, *s = 0, *t = 0, *z = 0;
  char          nag_enum_arg[40];

  /* Nag Types */
  NagError      fail;
  Nag_OrderType order;
  Nag_Boolean   wantq, wantz;

#ifdef NAG_COLUMN_MAJOR
#define S(I, J) s[(J-1)*pds + I - 1]
#define T(I, J) t[(J-1)*pdt + I - 1]
  order = Nag_ColMajor;
#else
#define S(I, J) s[(I-1)*pds + J - 1]
#define T(I, J) t[(I-1)*pdt + J - 1]
  order = Nag_RowMajor;
#endif

  INIT_FAIL(fail);

  printf("nag_dtgexc (f08yfc) Example Program Results\n\n");

  /* Skip heading in data file */
  scanf("%*[^\n]");
  scanf("%ld%*[^\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
   */
  wantq = (Nag_Boolean) nag_enum_name_to_value(nag_enum_arg);
  scanf(" %39s%*[^\n]", nag_enum_arg);
  wantz = (Nag_Boolean) nag_enum_name_to_value(nag_enum_arg);

  pds = n;
  pdt = n;

  pdq = (wantq?n:1);
  pdz = (wantz?n:1);
  pda = (wantq && wantz?n:1);
  pdb = pda;
  pdc = pda;

  /* Allocate memory */
  if (!(s = NAG_ALLOC(n*n, double)) ||
      !(t = NAG_ALLOC(n*n, double)) ||
      !(a = NAG_ALLOC(pda*pda, double)) ||
      !(b = NAG_ALLOC(pdb*pdb, double)) ||
      !(c = NAG_ALLOC(pdc*pdc, double)) ||
      !(q = NAG_ALLOC(pdq*pdq, double)) ||
      !(z = NAG_ALLOC(pdz*pdz, double)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }

  /* Read S and T from data file */
  for (i = 1; i <= n; ++i)
    for (j = 1; j <= n; ++j) scanf("%lf", &S(i, j));
  scanf("%*[^\n]");
  for (i = 1; i <= n; ++i)
    for (j = 1; j <= n; ++j) scanf("%lf", &T(i, j));
  scanf("%*[^\n]");

  /* Compute norm of matrices S and T using nag_dge_norm (f16rac). */
  nag_dge_norm(order, Nag_OneNorm, n, n, s, pds, &norms, &fail);
  nag_dge_norm(order, Nag_OneNorm, n, n, t, pdt, &normt, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_dge_norm (f16rac).\n%s\n", fail.message);
      exit_status = 1;
      goto END;
    }
  norms = sqrt(norms*norms + normt*normt);

  /* Copy matrices S and T to matrices A and B using nag_dge_copy (f16qfc),
   * real valued general matrix copy.
   * The copies will be used as comparison against reconstructed matrices.
   */
  if (wantq && wantz) {
    nag_dge_copy(order, Nag_NoTrans, n, n, s, pds, a, pda, &fail);
    nag_dge_copy(order, Nag_NoTrans, n, n, t, pdt, b, pdb, &fail);
    if (fail.code != NE_NOERROR)
      {
        printf("Error from nag_dge_copy (f16qfc).\n%s\n", fail.message);
        exit_status = 1;
        goto END;
      }
  }
  /* Initialize Q an Z to identity matrices using nag_dge_load (f16qhc). */
  alpha = 0.0;
  beta = 1.0;
  if (wantq) nag_dge_load(order, n, n, alpha, beta, q, pdq, &fail);
  if (wantz) nag_dge_load(order, n, n, alpha, beta, z, pdz, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_dge_load (f16qhc).\n%s\n", fail.message);
      exit_status = 1;
      goto END;
    }
  
  /* Read the row indices of diagonal elements or blocks to be swapped. */
  scanf("%ld%ld%*[^\n]", &ifst, &ilst);

  /* nag_gen_real_mat_print (x04cac): Print Matrix S and Matrix T. */
  fflush(stdout);
  nag_gen_real_mat_print(order, Nag_GeneralMatrix, Nag_NonUnitDiag, n, n,
                         s, pds, "Matrix S", 0, &fail);
  printf("\n");
  if (fail.code != NE_NOERROR) goto PRERR;
  fflush(stdout);
  nag_gen_real_mat_print(order, Nag_GeneralMatrix, Nag_NonUnitDiag, n, n,
                         t, pdt, "Matrix T", 0, &fail);
  printf("\n");
  if (fail.code != NE_NOERROR) goto PRERR;

  /* Reorder S and T */
  nag_dtgexc(order, wantq, wantz, n, s, pds, t, pdt, q, pdq, z, pdz, &ifst,
             &ilst, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_dtgexc (f08yfc).\n%s\n", fail.message);
      exit_status = 1;
      goto END;
    }

  /* nag_gen_real_mat_print (x04cac): Print reordered S and T. */
  fflush(stdout);
  nag_gen_real_mat_print(order, Nag_GeneralMatrix, Nag_NonUnitDiag, n, n,
                         s, pds, "Reordered matrix S", 0, &fail);
  printf("\n");
  if (fail.code != NE_NOERROR) goto PRERR;
  fflush(stdout);
  nag_gen_real_mat_print(order, Nag_GeneralMatrix, Nag_NonUnitDiag, n, n,
                         t, pdt, "Reordered matrix T", 0, &fail);
  printf("\n");
 PRERR:      
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_gen_real_mat_print (x04cac).\n%s\n",
             fail.message);
      exit_status = 1;
      goto END;
    }

  if (wantq && wantz) {
    /* Reconstruct original S and T by applying orthogonal transformations:
     * e.g. S = Q^T S' Z, and subtract from original S and T using
     * nag_dgemm (f16yac), twice each.
     */ 
    alpha = 1.0;
    beta = 0.0;
    nag_dgemm(order, Nag_NoTrans, Nag_NoTrans, n, n, n, alpha, q, pdq, s, pds,
              beta, c, pdc, &fail);
    if (fail.code != NE_NOERROR) goto DGEMMERR;
    beta = -1.0;
    nag_dgemm(order, Nag_NoTrans, Nag_Trans, n, n, n, alpha, c, pdc, z, pdz,
              beta, a, pda, &fail);
    if (fail.code != NE_NOERROR) goto DGEMMERR;
    /* nag_dgemm (f16yac): Compute B - Qt*Tt*Zt^T */ 
    alpha = 1.0;
    beta = 0.0;
    nag_dgemm(order, Nag_NoTrans, Nag_NoTrans, n, n, n, alpha, q, pdq, t, pdt,
            beta, c, pdc, &fail);
    if (fail.code != NE_NOERROR) goto DGEMMERR;
    beta = -1.0;
    nag_dgemm(order, Nag_NoTrans, Nag_Trans, n, n, n, alpha, c, pdc, z, pdz,
              beta, b, pdb, &fail);
  DGEMMERR:      
    if (fail.code != NE_NOERROR)
      {
        printf("Error from nag_dgemm (f16yac).\n%s\n", fail.message);
        exit_status = 1;
        goto END;
      }
    /* Compute norm of difference matrices using nag_dge_norm (f16rac). */
    nag_dge_norm(order, Nag_OneNorm, n, n, a, pda, &norma, &fail);
    nag_dge_norm(order, Nag_OneNorm, n, n, b, pdb, &normb, &fail);
    if (fail.code != NE_NOERROR)
      {
        printf("Error from nag_dge_norm (f16rac).\n%s\n", fail.message);
        exit_status = 1;
        goto END;
      }
    norma = sqrt(norma*norma + normb*normb);
  
    /* nag_machine_precision (x02ajc) */
    eps = nag_machine_precision;
    if (norma > pow(eps,0.8)*norms)
      {
        printf("The norm of the error in the reconstructed matrices is greater "
               "than expected.\nThe Schur factorization has failed.\n");
        exit_status = 1;
        goto END;
      }
  }
  
 END:
  NAG_FREE(a);
  NAG_FREE(b);
  NAG_FREE(c);
  NAG_FREE(q);
  NAG_FREE(s);
  NAG_FREE(t);
  NAG_FREE(z);

  return exit_status;
}