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

#include <math.h>
#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        alpha, beta, eps, norm, serrbd;
  Integer       exit_status = 0, i, j, m, n, pda, pdd, pdu, pdvt;

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

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

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

  INIT_FAIL(fail);

  printf("nag_dgesvd (f08kbc) Example Program Results\n\n");
  /* Skip heading in data file */
  scanf("%*[^\n]");
  
  scanf("%ld%ld%*[^\n]", &m, &n);
  if (m < 0 || n < 0)
    {
      printf("Invalid m or n\n");
      exit_status = 1;
      goto END;
    }
  
  /* Allocate memory */
  if (!(a      = NAG_ALLOC(m * n, double)) ||
      !(d      = NAG_ALLOC(m * n, double)) ||
      !(rcondu = NAG_ALLOC(n, double)) ||
      !(rcondv = NAG_ALLOC(n, double)) ||
      !(s      = NAG_ALLOC(MIN(m, n), double)) ||
      !(u      = NAG_ALLOC(m * m, double)) ||
      !(uerrbd = NAG_ALLOC(n, double)) ||
      !(verrbd = NAG_ALLOC(n, double)) ||
      !(vt     = NAG_ALLOC(n * n, double)) ||
      !(work   = NAG_ALLOC(MIN(m, n), double)) )
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }
      
  pdu = m;
  pdvt = n;
#ifdef NAG_COLUMN_MAJOR
  pda = m;
  pdd = m;
#else
  pda = n;
  pdd = n;
#endif
  
  /* Read the m by n matrix A from data file */
  for (i = 1; i <= m; ++i)
    for (j = 1; j <= n; ++j) scanf("%lf", &A(i, j));
  scanf("%*[^\n]");

  /* Copy a into d */
  for(i = 0; i < m*n; i++) d[i] = a[i];
  
  /* nag_gen_real_mat_print (x04cac)
   * Print real general matrix A.
   */
  fflush(stdout);
  nag_gen_real_mat_print(order, Nag_GeneralMatrix, Nag_NonUnitDiag, m, n, a,
                         pda, "Matrix A", 0, &fail);
  printf("\n");
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_gen_real_mat_print (x04cac).\n%s\n", fail.message);
      exit_status = 1;
      goto END;
    }

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

  /* U <- U*S */
  for(i = 1; i <= m; i++)
    for(j = 1; j <= n; j++) U(i, j) *= s[j-1];
  
  /* nag_dgemm (f16yac): 
   * Compute D = D - U*S*V^T from the factorization of A
   * and store in d */
  alpha = -1.0;
  beta = 1.0;
  nag_dgemm(order, Nag_NoTrans, Nag_NoTrans, m, n, n, alpha, u, pdu, vt, pdvt,
            beta, d, pdd, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_dgemm (f16yac).\n%s\n", fail.message);
      exit_status = 1;
      goto END;
    }
  
  /* nag_dge_norm (f16rac)
   * Find norm of matrix D and print warning if it is too large.
   */
  nag_dge_norm(order, Nag_OneNorm, m, n, d, pdd, &norm, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_dge_norm (f16rac).\n%s\n", fail.message);
      exit_status = 1;
      goto END;
    }

  /* nag_machine_precision (x02ajc): the machine precision. */
  eps = nag_machine_precision;
  if (norm > pow(eps,0.8))
    {
      printf("\nNorm of A-(U*S*V^T) is much greater than 0.\n"
             "Schur factorization has failed.\n");
      exit_status = 1;
      goto END;
    }
  /* Get the machine precision, eps and compute the approximate
   * error bound for the computed singular values.  
   * Note that for the 2-norm, s[0] = norm(A).
   */
  serrbd = eps * s[0];
      
  /* Estimate reciprocal condition numbers for the singular vectors using
   * nag_ddisna (f08flc).
   */
  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];
    }

  /* Print the approximate error bounds for the singular values and vectors */
  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(rcondu);
  NAG_FREE(rcondv);
  NAG_FREE(s);
  NAG_FREE(u);
  NAG_FREE(uerrbd);
  NAG_FREE(verrbd);
  NAG_FREE(vt);
  NAG_FREE(work);

  return exit_status;
}
#undef A
#undef U