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

#include <stdio.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              eps, norma, normb, tola, tolb;
  Integer             i, irank, j, k, l, m, n, ncycle, p, pda, pdb, pdu, pdv;
  Integer             pdq, printq, printr, printu, printv, vsize;
  Integer             exit_status = 0;

  /* Arrays */
  Complex             *a = 0, *b = 0, *q = 0, *u = 0, *v = 0;
  double              *alpha = 0, *beta = 0;
  char                nag_enum_arg[40];

  /* Nag Types */
  NagError            fail;
  Nag_OrderType       order;
  Nag_ComputeUType    jobu;
  Nag_ComputeVType    jobv;
  Nag_ComputeQType    jobq;
  Nag_MatrixType      genmat = Nag_GeneralMatrix, upmat = Nag_UpperMatrix;
  Nag_DiagType        diag   = Nag_NonUnitDiag;
  Nag_LabelType       intlab = Nag_IntegerLabels;
  Nag_ComplexFormType brac   = Nag_BracketForm;

#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_ztgsja (f08ysc) Example Program Results\n\n");

  /* Skip heading in data file */
  scanf("%*[^\n]");
  scanf("%ld%ld%ld%*[^\n]", &m, &n, &p);
  if (m < 0 || n < 0 || p < 0)
    {
      printf("Invalid m, n or p\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
   */
  jobu = (Nag_ComputeUType) nag_enum_name_to_value(nag_enum_arg);
  scanf(" %39s%*[^\n]", nag_enum_arg);
  jobv = (Nag_ComputeVType) nag_enum_name_to_value(nag_enum_arg);
  scanf(" %39s%*[^\n]", nag_enum_arg);
  jobq = (Nag_ComputeQType) nag_enum_name_to_value(nag_enum_arg);

  pdu = (jobu!=Nag_NotU?m:1);
  pdv = (jobv!=Nag_NotV?p:1);
  pdq = (jobq!=Nag_NotQ?n:1);
  vsize = (jobv!=Nag_NotV?p*m:1);
#ifdef NAG_COLUMN_MAJOR
  pda = m;
  pdb = p;
#else
  pda = n;
  pdb = n;
#endif

  /* Read in 0s or 1s to determine whether matrices U, V, Q or R are to be
   * printed.
   */
  scanf("%ld%ld%ld%ld%*[^\n]",
        &printu, &printv, &printq, &printr);

  /* Allocate memory */
  if (!(a     = NAG_ALLOC(m*n, Complex)) ||
      !(b     = NAG_ALLOC(p*n, Complex)) ||
      !(alpha = NAG_ALLOC(n, double)) ||
      !(beta  = NAG_ALLOC(n, double)) ||
      !(q     = NAG_ALLOC(pdq*pdq, Complex)) ||
      !(u     = NAG_ALLOC(pdu*pdu, Complex)) ||
      !(v     = NAG_ALLOC(vsize, Complex)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }

  /* Read the m by n matrix A and p by n matrix B from data file */
  for (i = 1; i <= m; ++i)
    for (j = 1; j <= n; ++j)
      scanf(" ( %lf , %lf )", &A(i, j).re, &A(i, j).im);
  scanf("%*[^\n]");
  for (i = 1; i <= p; ++i)
    for (j = 1; j <= n; ++j)
      scanf(" ( %lf , %lf )", &B(i, j).re, &B(i, j).im);
  scanf("%*[^\n]");

  /* Compute tola and tolb as        */
  /* tola = max(m,n)*norm(A)*macheps */
  /* tolb = max(p,n)*norm(B)*macheps */
  nag_zge_norm(order, Nag_OneNorm, m, n, a, pda, &norma, &fail);
  nag_zge_norm(order, Nag_OneNorm, p, n, b, pdb, &normb, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_zge_norm (f16uac).\n%s\n", fail.message);
      exit_status = 1;
      goto END;
    }

  /* Compute tola and tolb using nag_machine_precision (x02ajc) */
  eps = nag_machine_precision;
  tola = MAX(m, n) * norma * eps;
  tolb = MAX(p, n) * normb * eps;

  /* Preprocess step: 
   * compute transformations to reduce (A, B) to upper triangular form
   * (A = U1*S*(Q1^H), B = V1*T*(Q1^H)) 
   * using nag_zggsvp (f08vsc).
   */
  nag_zggsvp(order, jobu, jobv, jobq, m, p, n, a, pda, b, pdb, tola, tolb, &k,
             &l, u, pdu, v, pdv, q, pdq, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_zggsvp (f08vsc).\n%s\n", fail.message);
      exit_status = 1;
      goto END;
    }

  /* Compute the generalized singular value decomposition of preprocessed (A, B)
   * (A = U*D1*(0 R)*(Q**H), B = V*D2*(0 R)*(Q**H))
   * using nag_ztgsja (f08ysc).
   */
  nag_ztgsja(order, jobu, jobv, jobq, m, p, n, k, l, a, pda, b, pdb, tola,
             tolb, alpha, beta, u, pdu, v, pdv, q, pdq, &ncycle, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_ztgsja (f08ysc).\n%s\n", fail.message);
      exit_status = 1;
      goto END;
    }

  /* Print the generalized singular value pairs alpha, beta */
  irank = MIN(k + l,m);
  printf("Number of infinite generalized singular values (k): %5ld\n", k);
  printf("Number of   finite generalized singular values (l): %5ld\n", l);
  printf("Effective  Numerical  rank  of (A^H B^HT)^H  (k+l): %5ld\n",
         irank);
  printf("\nFinite generalized singular values:\n");

  for (j = k; j < irank; ++j)  printf("%45s%12.4e\n", "", alpha[j]/beta[j]);

  printf("\nNumber of cycles of the Kogbetliantz method: %12ld\n\n", ncycle);

  if (printu && jobu!=Nag_NotU) {
    fflush(stdout);
    nag_gen_complx_mat_print_comp(order, genmat, diag, m, m, u, pdu, brac,
                                  "%13.4e", "Orthogonal matrix U", intlab,
                                  NULL, intlab, NULL, 80, 0, NULL, &fail);
    if (fail.code != NE_NOERROR) goto PRINTERR;
  }
  if (printv && jobv!=Nag_NotV) {
    printf("\n");
    fflush(stdout);
    nag_gen_complx_mat_print_comp(order, genmat, diag, p, p, v, pdv, brac,
                                  "%13.4e", "Orthogonal matrix V", intlab,
                                  NULL, intlab, NULL, 80, 0, NULL, &fail);
    if (fail.code != NE_NOERROR) goto PRINTERR;
  }
  if (printq && jobq!=Nag_NotQ) {
    printf("\n");
    fflush(stdout);
    nag_gen_complx_mat_print_comp(order, genmat, diag, n, n, q, pdq, brac,
                                  "%13.4e", "Orthogonal matrix Q", intlab,
                                  NULL, intlab, NULL, 80, 0, NULL, &fail);
    if (fail.code != NE_NOERROR) goto PRINTERR;
  }
  if (printr) {
    printf("\n");
    fflush(stdout);
    nag_gen_complx_mat_print_comp(order, upmat, diag, irank, irank,
                                  &A(1, n - irank + 1), pda, brac, "%13.4e",
                                  "Non singular upper triangular matrix R",
                                  intlab, NULL, intlab, NULL, 80, 0, NULL,
                                  &fail);
  }
 PRINTERR: 
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_gen_real_mat_print_comp (x04cbc).\n%s\n",
             fail.message);
      exit_status = 1;
    }

 END:
  NAG_FREE(a);
  NAG_FREE(b);
  NAG_FREE(alpha);
  NAG_FREE(beta);
  NAG_FREE(q);
  NAG_FREE(u);
  NAG_FREE(v);

  return exit_status;
}