/* nag_mv_discrim (g03dac) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 5, 1998.
 * Mark 8 revised, 2004.
 *
 */

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

#define GMEAN(I, J) gmean[(I) *tdgmean + J]
#define X(I, J)     x[(I) *tdx + J]
int main(void)
{
  Integer  exit_status = 0, i, *ing = 0, *isx = 0, j, m, n, ng, *nig = 0, nvar,
           tdgmean;
  Integer  tdx;
  NagError fail;
  char     weight[2];
  double   *det = 0, df, *gc = 0, *gmean = 0, sig, stat, *wt = 0, *wtptr = 0;
  double   *x = 0;

  INIT_FAIL(fail);

  printf("nag_mv_discrim (g03dac) Example Program Results\n\n");

  /* Skip headings in data file */
  scanf("%*[^\n]");
  scanf("%ld", &n);
  scanf("%ld", &m);
  scanf("%ld", &nvar);
  scanf("%ld", &ng);
  scanf("%1s", weight);
  if (n >= 1 && nvar >= 1 && m >= nvar && ng >= 2)
    {
      if (!(det = NAG_ALLOC(ng, double)) ||
          !(gc = NAG_ALLOC((ng+1)*nvar*(nvar+1)/2, double)) ||
          !(gmean = NAG_ALLOC(ng*nvar, double)) ||
          !(wt = NAG_ALLOC(n, double)) ||
          !(x = NAG_ALLOC(n*m, double)) ||
          !(ing = NAG_ALLOC(n, Integer)) ||
          !(isx = NAG_ALLOC(m, Integer)) ||
          !(nig = NAG_ALLOC(ng, Integer)))
        {
          printf("Allocation failure\n");
          exit_status = -1;
          goto END;
        }
      tdgmean = nvar;
      tdx = m;
    }
  else
    {
      printf("Invalid n or nvar or m or ng.\n");
      exit_status = 1;
      return exit_status;
    }
  if (*weight == 'W')
    {
      for (i = 0; i < n; ++i)
        {
          for (j = 0; j < m; ++j)
            scanf("%lf", &X(i, j));
          scanf("%ld", &ing[i]);
          scanf("%lf", &wt[i]);
        }
      wtptr = wt;
    }
  else
    {
      for (i = 0; i < n; ++i)
        {
          for (j = 0; j < m; ++j)
            scanf("%lf", &X(i, j));
          scanf("%ld", &ing[i]);
        }
    }
  for (j = 0; j < m; ++j)
    scanf("%ld", &isx[j]);

  /* nag_mv_discrim (g03dac).
   * Test for equality of within-group covariance matrices
   */
  nag_mv_discrim(n, m, x, tdx, isx, nvar, ing, ng, wtptr, nig,
                 gmean, tdgmean, det, gc, &stat, &df, &sig, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_mv_discrim (g03dac).\n%s\n", fail.message);
      exit_status = 1;
      goto END;
    }

  printf("\nGroup means\n\n");
  for (i = 0; i < ng; ++i)
    {
      for (j = 0; j < nvar; ++j)
        printf("%10.4f", GMEAN(i, j));
      printf("\n");
    }
  printf("\nLOG of determinants\n\n");
  for (j = 0; j < ng; ++j)
    printf("%10.4f", det[j]);
  printf("\n\n%s%7.4f\n", "stat = ", stat);
  printf("%s%7.4f\n", "  df = ", df);
  printf("%s%7.4f\n", " sig = ", sig);
 END:
  NAG_FREE(det);
  NAG_FREE(gc);
  NAG_FREE(gmean);
  NAG_FREE(wt);
  NAG_FREE(x);
  NAG_FREE(ing);
  NAG_FREE(isx);
  NAG_FREE(nig);
  return exit_status;
}