/* nag_mv_ordinal_multidimscale (g03fcc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 5, 1998.
 * Mark 6 revised, 2000.
 * Mark 7 revised, 2001.
 * Mark 8 revised, 2004.
 *
 */

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

#define NMAX  14
#define NNMAX NMAX*(NMAX-1)/2

#define X(I, J) x[(I-1)*tdx + (J-1)]
#define XTMP(I) xtmp[(I) -1]
#define YTMP(I) ytmp[(I) -1]

int main(void)
{
  Integer            exit_status = 0, i, j, n, ndim, nn, tdx = NMAX;
  double             *d = 0, *dfit = 0, *e = 0, stress, *x = 0;
  char               nag_enum_arg[40];
  Nag_ScaleCriterion type;
  NagError           fail;

  INIT_FAIL(fail);

  printf(
          "nag_mv_ordinal_multidimscale (g03fcc) 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
   */
  type = (Nag_ScaleCriterion) nag_enum_name_to_value(nag_enum_arg);

  if (ndim >= 1 && n > ndim)
    {
      if (!(d = NAG_ALLOC(n*(n-1)/2, double)) ||
          !(dfit = NAG_ALLOC(4*(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 = 1; i <= nn; ++i)
    scanf("%lf", &d[i-1]);

  /* nag_mv_prin_coord_analysis (g03fac).
   * Principal co-ordinate analysis
   */
  nag_mv_prin_coord_analysis(Nag_LargeEigVals, 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;
    }

  /* nag_mv_ordinal_multidimscale (g03fcc).
   * Multidimensional scaling
   */
  nag_mv_ordinal_multidimscale(type, n, ndim, d, x, tdx, &stress, dfit,
                               E04_DEFAULT, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_mv_ordinal_multidimscale (g03fcc).\n%s\n",
              fail.message);
      exit_status = 1;
      goto END;
    }

  printf("\n          STRESS = %13.4e\n\n", stress);
  printf("Co-ordinates\n\n");

  for (i = 1; i <= n; ++i)
    {
      for (j = 1; j <= ndim; ++j)
        printf("%10.4f", X(i, j));
      printf("\n");
    }

 END:
  NAG_FREE(d);
  NAG_FREE(dfit);
  NAG_FREE(e);
  NAG_FREE(x);

  return exit_status;
}