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

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

int main(void)
{
  /* Scalars */
  double           norma, normb, eps, tola, tolb;
  Integer          i, irank, j, k, l, m, n, ncycle, p, pda, pdb, pdq, pdu, pdv;
  Integer          printq, printr, printu, printv, vsize;
  Integer          exit_status = 0;

  /* Arrays */
  double           *a = 0, *alpha = 0, *b = 0, *beta = 0, *q = 0, *u = 0,
                   *v = 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;

#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_dtgsja (f08yec) 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, double)) ||
      !(b     = NAG_ALLOC(p*n, double)) ||
      !(alpha = NAG_ALLOC(n, double)) ||
      !(beta  = NAG_ALLOC(n, double)) ||
      !(q     = NAG_ALLOC(pdq*pdq, double)) ||
      !(u     = NAG_ALLOC(pdu*pdu, double)) ||
      !(v     = NAG_ALLOC(vsize, double)))
    {
      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", &A(i, j));
  scanf("%*[^\n]");
  for (i = 1; i <= p; ++i)
    for (j = 1; j <= n; ++j) scanf("%lf", &B(i, j));
  scanf("%*[^\n]");


  nag_dge_norm(order, Nag_FrobeniusNorm, m, n, a, pda, &norma, &fail);
  nag_dge_norm(order, Nag_FrobeniusNorm, p, 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;
    }

  /* 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**T), B = V1*T*(Q1**T)) 
   * using nag_dggsvp (f08vec).
   */
  nag_dggsvp(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_dggsvp (f08vec).\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**T), B = V*D2*(0 R)*(Q**T))
   * using nag_dtgsja (f08yec). */
  nag_dtgsja(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_dtgsja (f08yec).\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**T B**T)**T (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_real_mat_print_comp(order, genmat, diag, m, m, u, pdu, "%13.4e",
                                "Orthogonal matrix U", intlab, NULL, intlab,
                                NULL, 80, 0, NULL, &fail);
    if (fail.code != NE_NOERROR) goto PRINTERR;
    printf("\n");
  }
  if (printv && jobv!=Nag_NotV) {
    fflush(stdout);
    nag_gen_real_mat_print_comp(order, genmat, diag, p, p, v, pdv, "%13.4e",
                                "Orthogonal matrix V", intlab, NULL, intlab,
                                NULL, 80, 0, NULL, &fail);
    if (fail.code != NE_NOERROR) goto PRINTERR;
    printf("\n");
  }
  if (printq && jobq!=Nag_NotQ) {
    fflush(stdout);
    nag_gen_real_mat_print_comp(order, genmat, diag, n, n, q, pdq, "%13.4e",
                                "Orthogonal matrix Q", intlab, NULL, intlab,
                                NULL, 80, 0, NULL, &fail);
    if (fail.code != NE_NOERROR) goto PRINTERR;
    printf("\n");
  }
  if (printr) {
    fflush(stdout);
    nag_gen_real_mat_print_comp(order, upmat, diag, irank, irank,
                                &A(1, n - irank + 1), pda, "%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(alpha);
  NAG_FREE(b);
  NAG_FREE(beta);
  NAG_FREE(q);
  NAG_FREE(u);
  NAG_FREE(v);

  return exit_status;
}