/* nag_mv_prin_coord_analysis (g03fac) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 5, 1998.
 * Mark 7 revised, 2001.
 * Mark 8 revised, 2004.
 *
 */

#include <nag.h>
#include <stdio.h>
#include <nag_stdlib.h>
#include <nagg03.h>

#define XTMP(I) xtmp[(I) -1]
#define YTMP(I) ytmp[(I) -1]


#define X(I, J) x[(I) *tdx + J]
int main(void)
{
  Integer         exit_status = 0, i, j, n, ndim, nn, tdx;
  char            nag_enum_arg[40];
  double          *d = 0, *e = 0, *x = 0;
  Nag_Eigenvalues roots;
  NagError        fail;

  INIT_FAIL(fail);

  printf(
          "nag_mv_prin_coord_analysis (g03fac) Example Program Results\n\n");

  /* Skip heading in data file */
  scanf("%*[^\n]");
  scanf("%ld", &n);
  scanf("%ld", &ndim);
  scanf("%39s", nag_enum_arg);
  /* nag_enum_name_to_value (x04nac).
   * Converts NAG enum member name to value
   */
  roots = (Nag_Eigenvalues) nag_enum_name_to_value(nag_enum_arg);

  if (ndim >= 1 && n > ndim)
    {
      if (!(d = NAG_ALLOC(n*(n-1)/2, double)) ||
          !(e = NAG_ALLOC(n, double)) ||
          !(x = NAG_ALLOC(n*n, double)))
        {
          printf("Allocation failure\n");
          exit_status = -1;
          goto END;
        }
      tdx = n;
    }
  else
    {
      printf("Invalid ndim or n.\n");
      exit_status = 1;
      return exit_status;
    }
  nn = n * (n - 1) / 2;
  for (i = 0; i < nn; ++i)
    scanf("%lf", &d[i]);

  /* nag_mv_prin_coord_analysis (g03fac).
   * Principal co-ordinate analysis
   */
  nag_mv_prin_coord_analysis(roots, n, d, ndim, x, tdx, e, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_mv_prin_coord_analysis (g03fac).\n%s\n",
              fail.message);
      exit_status = 1;
      goto END;
    }
  printf("\nScaled Eigenvalues\n\n");

  if (roots == Nag_LargeEigVals)
    {
      for (i = 0; i < ndim; ++i)
        printf("%10.4f", e[i]);
    }
  else
    {
      for (i = 0; i < n; ++i)
        printf("%10.4f", e[i]);
      printf("\n");
    }
  printf("\nCo-ordinates\n\n");
  for (i = 0; i < n; ++i)
    {
      for (j = 0; j < ndim; ++j)
        printf("%10.4f", X(i, j));
      printf("\n");
    }
 END:
  NAG_FREE(d);
  NAG_FREE(e);
  NAG_FREE(x);
  return exit_status;
}