/* nag_zgeqp3 (f08btc) Example Program.
 *
 * Copyright 2017 Numerical Algorithms Group.
 *
 * Mark 26.1, 2017.
 */

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

int main(void)
{
  /* Scalars */
  Complex one = { 1.0, 0.0 };
  Complex zero = { 0.0, 0.0 };
  double tol;
  Integer i, j, k, m, n, nrhs, pda, pdb, pdw;
  Integer exit_status = 0;
  /* Arrays */
  Complex *a = 0, *b = 0, *tau = 0, *work = 0;
  double *rnorm = 0;
  Integer *jpvt = 0;
  /* Nag Types */
  Nag_OrderType order;
  NagError fail;

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

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

#ifdef NAG_COLUMN_MAJOR
  pda = m;
  pdb = m;
  pdw = m;
#else
  pda = n;
  pdb = nrhs;
  pdw = 1;
#endif

  /* Allocate memory */
  if (!(a = NAG_ALLOC(m * n, Complex)) ||
      !(b = NAG_ALLOC(m * nrhs, Complex)) ||
      !(tau = NAG_ALLOC(n, Complex)) ||
      !(work = NAG_ALLOC(n, Complex)) ||
      !(rnorm = NAG_ALLOC(nrhs, double)) || !(jpvt = NAG_ALLOC(n, Integer)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }

  /* Read A and 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 <= m; ++i)
    for (j = 1; j <= nrhs; ++j)
      scanf(" ( %lf , %lf )", &B(i, j).re, &B(i, j).im);
  scanf("%*[^\n]");

  /* nag_iload (f16dbc).
   * Initialize jpvt to be zero so that all columns are free.
   */
  nag_iload(n, 0, jpvt, 1, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_iload (f16dbc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  /* nag_zgeqp3 (f08btc).
   * Compute the QR factorization of A.
   */
  nag_zgeqp3(order, m, n, a, pda, jpvt, tau, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_zgeqp3 (f08btc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  /* nag_zunmqr (f08auc).
   * Compute C = (C1) = (Q^H)*B, storing the result in B.
   *             (C2)
   */
  nag_zunmqr(order, Nag_LeftSide, Nag_ConjTrans, m, nrhs, n, a, pda, tau,
             b, pdb, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_zunmqr (f08auc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  /* Choose tol to reflect the relative accuracy of the input data */
  tol = 0.01;

  /* nag_complex_abs (a02dbc).
   * Determine and print the rank, k, of R relative to tol.
   */
  for (k = 1; k <= n; ++k)
    if (nag_complex_abs(A(k, k)) <= tol * nag_complex_abs(A(1, 1)))
      break;
  --k;

  printf("Tolerance used to estimate the rank of A\n");
  printf("%11.2e\n", tol);
  printf("Estimated rank of A\n");
  printf("%8" NAG_IFMT "\n\n", k);

  /* nag_ztrsm (f16zjc).
   * Compute least squares solutions by back-substitution in
   * R(1:k,1:k)*Y = C1, storing the result in B.
   */
  nag_ztrsm(order, Nag_LeftSide, Nag_Upper, Nag_NoTrans, Nag_NonUnitDiag, k,
            nrhs, one, a, pda, b, pdb, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_ztrsm (f16zjc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  /* nag_zge_norm (f16uac).
   * Compute estimates of the square roots of the residual sums of
   * squares (2-norm of each of the columns of C2).
   */
  for (j = 1; j <= nrhs; ++j) {
    nag_zge_norm(order, Nag_FrobeniusNorm, m - k, 1, &B(k + 1, j), pdb,
                 &rnorm[j - 1], &fail);
    if (fail.code != NE_NOERROR) {
      printf("Error from nag_zge_norm (f16uac).\n%s\n", fail.message);
      exit_status = 1;
      goto END;
    }
  }

  /* nag_zge_load (f16thc).
   * Set the remaining elements of the solutions to zero (to give
   * the basic solutions).
   */
  nag_zge_load(order, n - k, nrhs, zero, zero, &B(k + 1, 1), pdb, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_zge_load (f16thc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  /* Permute the least squares solutions stored in B to give X = P*Y */
  for (j = 1; j <= nrhs; ++j) {
    for (i = 1; i <= n; ++i) {
      work[jpvt[i - 1] - 1].re = B(i, j).re;
      work[jpvt[i - 1] - 1].im = B(i, j).im;
    }
    /* nag_zge_copy (f16tfc). 
     * Copy matrix.
     */
    nag_zge_copy(order, Nag_NoTrans, n, 1, work, pdw, &B(1, j), pdb, &fail);
    if (fail.code != NE_NOERROR) {
      printf("Error from nag_zge_copy (f16tfc).\n%s\n", fail.message);
      exit_status = 1;
      goto END;
    }
  }

  /* nag_gen_complx_mat_print_comp (x04dbc).
   * Print least squares solutions.
   */
  fflush(stdout);
  nag_gen_complx_mat_print_comp(order, Nag_GeneralMatrix, Nag_NonUnitDiag, n,
                                nrhs, b, pdb, Nag_BracketForm, "%7.4f",
                                "Least squares solution(s)",
                                Nag_IntegerLabels, 0, Nag_IntegerLabels, 0,
                                80, 0, 0, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_gen_complx_mat_print_comp (x04dbc).\n%s\n",
           fail.message);
    exit_status = 1;
    goto END;
  }

  /* Print the square roots of the residual sums of squares */
  printf("\nSquare root(s) of the residual sum(s) of squares\n");

  for (j = 0; j < nrhs; ++j)
    printf("%11.2e%s", rnorm[j], (j + 1) % 7 == 0 || j == nrhs-1 ? "\n" : " ");

END:
  NAG_FREE(a);
  NAG_FREE(b);
  NAG_FREE(tau);
  NAG_FREE(work);
  NAG_FREE(rnorm);
  NAG_FREE(jpvt);

  return exit_status;
}

#undef A
#undef B