/* nag_nearest_correlation_shrinking (g02anc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 25, 2014.
 */

#include <stdio.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <nagg02.h>
#include <nagx04.h>

int main(void)
{

#define G(I,J) g[(J-1)*pdg + I-1]

  /*  Scalars */
  Integer exit_status = 0;
  double alpha, eigmin, eigtol, errtol, norm;
  Integer i, j, iter, k, n, pdg, pdx;

  /*  Arrays */
  double *g = 0, *x = 0;

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

  INIT_FAIL(fail);

  /* Output preamble */
  printf("nag_nearest_correlation_shrinking (g02anc)");
  printf(" Example Program Results\n\n");
  fflush(stdout);

  /* Skip heading in data file */
  scanf("%*[^\n] ");

  /* Read in the problem size and k */
  scanf("%ld%ld%*[^\n] ", &n,  &k);

  pdg = n;
  pdx = n;
  if ( 
      !(g = NAG_ALLOC(pdg*n, double))||
      !(x = NAG_ALLOC(pdx*n, double))
       )
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }

  /* Read in the matrix g*/
  for ( i=1; i<=n; i++)
    for (j=1;j<=n; j++)
      scanf("%lf", &G(i, j));
  scanf("%*[^\n] ");
  
  /* Use the defaults for ERRTOL and EIGTOL */
  errtol = -1.0;
  eigtol = -1.0;

  /* 
   * nag_nearest_correlation_shrinking (g02anc).
   * Calculate nearest perturbed correlation matrix with preserved leading block
   */
  nag_nearest_correlation_shrinking(g, pdg, n, k, errtol, eigtol, x, pdx, 
                                    &alpha, &iter, &eigmin, &norm, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_nearest_correlation_shrinking (g02anc).\n%s\n",
             fail.message);
      exit_status = 1;
      goto END;
    }

  /* Display results */

  order = Nag_ColMajor;
  /* 
   * nag_gen_real_mat_print (x04cac).
   * Prints real general matrix 
   */
  nag_gen_real_mat_print(order, Nag_GeneralMatrix, Nag_NonUnitDiag, n, n, g,
                         pdg, "Symmetrised Input Matrix G", NULL, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_gen_real_mat_print (x04cac).\n%s\n", fail.message);
      exit_status = 2;
      goto END;
    }

  printf("\n");
  fflush(stdout);
  nag_gen_real_mat_print(order, Nag_GeneralMatrix, Nag_NonUnitDiag, n, n, x,
                         pdx, "Nearest Perturbed Correlation Matrix X", NULL, 
                         &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_gen_real_mat_print (x04cac).\n%s\n", fail.message);
      exit_status = 3;
      goto END;
    }

  printf("\n%s %34ld \n\n","k:",  k);
  printf("%s %9ld \n\n","Number of iterations taken:",  iter);
  printf("%s %34.4f \n\n","alpha: ",  alpha);
  printf("%s %29.4f \n\n","norm value: ",  norm);
  printf("%s %15.4f \n","Smallest eigenvalue of A: ",  eigmin);
  
 END:
  NAG_FREE(g);
  NAG_FREE(x);
  return exit_status;
}