/* nag_dggsvp3 (f08vgc) Example Program.
 *
 * Copyright 2017 Numerical Algorithms Group.
 *
 * Mark 26.1, 2017.
 */

#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, norm, tola, tolb;
  Integer        i, irank, j, k, l, m, n, ncycle, p, pda, pdb, pdq,
                 pdu, pdv;
  Integer        printq, printr, printu, printv;
  Integer        exit_status = 0;
  /* Arrays */
  double         *a = 0, *b = 0, *q = 0, *u = 0, *v = 0, *alpha = 0, *beta = 0;

  /* Nag Types */
  NagError fail;
  Nag_OrderType  order;
  Nag_DiagType   diag = Nag_NonUnitDiag;
  Nag_MatrixType genmat = Nag_GeneralMatrix, upmat = Nag_UpperMatrix;
  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_dggsvp3 (f08vgc) Example Program Results\n\n");

  /* Skip heading in data file */
  scanf("%*[^\n]");
  scanf("%" NAG_IFMT "%" NAG_IFMT "%" NAG_IFMT "%*[^\n]", &m, &n, &p);
  if (n < 0 || m < 0 || p < 0) {
    printf("Invalid n, m or p\n");
    exit_status = 1;
    goto END;
  }

#ifdef NAG_COLUMN_MAJOR
  pda = m;
  pdb = p;
  pdv = p;
#else
  pda = n;
  pdb = n;
  pdv = m;
#endif
  pdq = n;
  pdu = m;

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

  /* Allocate memory */
  if (!(a = NAG_ALLOC(m * n, double)) ||
      !(b = NAG_ALLOC(p * n, double)) ||
      !(q = NAG_ALLOC(n * n, double)) ||
      !(u = NAG_ALLOC(m * m, double)) ||
      !(v = NAG_ALLOC(n * n, double)) ||
      !(alpha = NAG_ALLOC(n, double)) ||
      !(beta  = NAG_ALLOC(n, 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]");

  /* get norms of A and B using nag_dge_norm (f16rac). */
  nag_dge_norm(order, Nag_OneNorm, m, n, a, pda, &norm, &fail);
  nag_dge_norm(order, Nag_OneNorm, p, n, b, pdb, &norm, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_dge_norm (f16rac).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  /* Get the machine precision, using nag_machine_precision (x02ajc) */
  eps = nag_machine_precision;

  tola = MAX(m, n) * norm * eps;
  tolb = MAX(p, n) * norm * eps;

  /* Compute the factorization of (A, B) (A = U*S*(Q^T), B = V*T*(Q^T))
   * using nag_dggsvp3 (f08vgc).
   */
  nag_dggsvp3(order, Nag_AllU, Nag_ComputeV, Nag_ComputeQ, 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_dggsvp3 (f08vgc).\n%s\n", fail.message);
    exit_status = 2;
    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, Nag_AllU, Nag_ComputeV, Nag_ComputeQ, 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 = 3;
    goto END;
  }

  /* Print the generalized singular value pairs alpha, beta */
  irank = MIN(k + l, m);
  printf("Number of infinite generalized singular values (k): %5" NAG_IFMT
         "\n", k);
  printf("Number of   finite generalized singular values (l): %5" NAG_IFMT
         "\n", l);
  printf("Effective Numerical rank  of  ( A^T B^T)^T   (k+l): %5" NAG_IFMT
         "\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: %12" NAG_IFMT "\n\n",
         ncycle);

  if (printu) {
    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) {
    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) {
    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",
                                "Nonsingular 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 = 4;
  }

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;
}