/* nag_zgesvd (f08kpc) Example Program.
 *
 * Copyright 2017 Numerical Algorithms Group.
 *
 * Mark 26.1, 2017.
 */

#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>
#include <naga02.h>

int main(void)
{

  /* Scalars */
  Complex alpha, beta;
  double eps, norm, serrbd;
  Integer exit_status = 0, i, j, m, n, pda, pdd, pdu, pdvt;

  /* Arrays */
  Complex *a = 0, *d = 0, *u = 0, *vt = 0;
  double *rcondu = 0, *rcondv = 0, *s = 0, *uerrbd = 0, *verrbd = 0;
  double *rwork = 0;

  /* Nag Types */
  NagError fail;
  Nag_OrderType order;

#ifdef NAG_COLUMN_MAJOR
#define A(I, J) a[(J - 1) * pda + I - 1]
  order = Nag_ColMajor;
#else
#define A(I, J) a[(I - 1) * pda + J - 1]
  order = Nag_RowMajor;
#endif

  INIT_FAIL(fail);

  printf("nag_zgesvd (f08kpc) Example Program Results\n\n");

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

  /* Allocate memory: these assume that A is overwritten by U, and
   * all of VT is required.
   */
  if (!(a = NAG_ALLOC(m * n, Complex)) ||
      !(d = NAG_ALLOC(m * n, Complex)) ||
      !(u = NAG_ALLOC(1, Complex)) ||
      !(vt = NAG_ALLOC(MIN(m, n) * n, Complex)) ||
      !(rcondu = NAG_ALLOC(MIN(m, n), double)) ||
      !(rcondv = NAG_ALLOC(MIN(m, n), double)) ||
      !(s = NAG_ALLOC(MIN(m, n), double)) ||
      !(uerrbd = NAG_ALLOC(MIN(m, n), double)) ||
      !(verrbd = NAG_ALLOC(MIN(m, n), double)) ||
      !(rwork = NAG_ALLOC(MIN(m, n), double)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }

#ifdef NAG_COLUMN_MAJOR
  pda = m;
#else
  pda = n;
#endif
  pdu = 1;
  pdvt = n;
  pdd = pda;

  /* Read the m by n matrix A 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]");

  /* Copy A to D: nag_zge_copy (f16tfc),
   * Complex valued general matrix copy.
   */
  nag_zge_copy(order, Nag_NoTrans, m, n, a, pda, d, pdd, &fail);

  /* nag_gen_complx_mat_print_comp (x04dbc): Print matrix A */
  fflush(stdout);
  nag_gen_complx_mat_print_comp(order, Nag_GeneralMatrix, Nag_NonUnitDiag, m,
                                n, a, pda, Nag_BracketForm, "%7.4f",
                                "Matrix A", Nag_IntegerLabels, 0,
                                Nag_IntegerLabels, 0, 80, 0, 0, &fail);
  printf("\n");
  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;
  }

  /* nag_zgesvd (f08kpc)
   * Compute the singular values and left and right singular vectors
   * of A (A = U*S*(V^H), m.ge.n)
   */
  nag_zgesvd(order, Nag_Overwrite, Nag_AllVT, m, n, a, pda, s, u, pdu, vt,
             pdvt, rwork, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_zgesvd (f08kpc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  /* Reconstruct A from its decomposition and subtract from original A:
   * first, A <- U(A)*S, then D <- D - U*S*V^H using
   * nag_zgemm (f16zac).
   */
  for (i = 1; i <= m; i++)
    for (j = 1; j <= MIN(m, n); j++)
      A(i, j).re *= s[j - 1], A(i, j).im *= s[j - 1];

  alpha = nag_complex(-1.0, 0.0);
  beta = nag_complex(1.0, 0.0);
  nag_zgemm(order, Nag_NoTrans, Nag_NoTrans, m, n, n, alpha, a, pda, vt, pdvt,
            beta, d, pdd, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_zgemm (f16zac).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  /* Find norm of difference matrix D and print warning if it is too large:
   * nag_zge_norm (f16uac) using one-norm.
   */
  nag_zge_norm(order, Nag_OneNorm, m, n, d, pdd, &norm, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_zge_norm (f16uac).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }
  /* Get the machine precision, using nag_machine_precision (x02ajc) */
  eps = nag_machine_precision;
  if (norm > pow(eps, 0.8)) {
    printf("Norm of A-(U*S*V^H) is much greater than 0.\n"
           " Schur factorization has failed.\n");
    exit_status = 1;
    goto END;
  }
  /* Print singular values and error estimates on values and vectors. */
  printf("\nSingular values\n");
  for (i = 0; i < n; ++i)
    printf("%10.4f%s", s[i], i % 8 == 7 ? "\n" : " ");
  printf("\n\n");

  /* Approximate error bound for the computed singular values.
   * Note that for the 2-norm, s[0] = norm(A).
   */
  serrbd = eps * s[0];

  /* Call nag_ddisna (f08flc) to estimate reciprocal condition numbers for the
   * singular vectors.
   */
  nag_ddisna(Nag_LeftSingVecs, m, n, s, rcondu, &fail);
  nag_ddisna(Nag_RightSingVecs, m, n, s, rcondv, &fail);

  /* Compute the error estimates for the singular vectors */
  for (i = 0; i < n; ++i) {
    uerrbd[i] = serrbd / rcondu[i];
    verrbd[i] = serrbd / rcondv[i];
  }
  printf("Error estimate for the singular values\n%11.1e\n", serrbd);

  printf("\nError estimates for the left singular vectors\n");
  for (i = 0; i < n; ++i)
    printf(" %10.1e%s", uerrbd[i], i % 6 == 5 ? "\n" : "");

  printf("\n\nError estimates for the right singular vectors\n");
  for (i = 0; i < n; ++i)
    printf(" %10.1e%s", verrbd[i], i % 6 == 5 ? "\n" : "");
  printf("\n");

END:
  NAG_FREE(a);
  NAG_FREE(d);
  NAG_FREE(u);
  NAG_FREE(vt);
  NAG_FREE(rcondu);
  NAG_FREE(rcondv);
  NAG_FREE(s);
  NAG_FREE(uerrbd);
  NAG_FREE(verrbd);
  NAG_FREE(rwork);

  return exit_status;
}

#undef A