/* nag_kruskal_wallis_test (g08afc) Example Program.
 *
 * NAGPRODCODE Version.
 *
 * Copyright 2016 Numerical Algorithms Group.
 *
 * Mark 26, 2016.
 */

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

int main(void)
{
  Integer count, exit_status = 0, i, ii, k, *l = 0, lx, nhi, ni, nlo;
  NagError fail;
  double h, p, *x = 0;

  INIT_FAIL(fail);

  printf("nag_kruskal_wallis_test (g08afc) Example Program Results\n");

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

  k = 5;
  if (!(l = NAG_ALLOC(k, Integer)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }
  for (i = 1; i <= k; i++)
    scanf("%" NAG_IFMT "", &l[i - 1]);
  printf("\n");
  printf("%s\n", "Kruskal-Wallis test");
  printf("\n");
  printf("%s\n", "Data values");
  printf("\n");
  printf("%s\n", "  Group    Observations");

  lx = 0;
  for (i = 1; i <= 5; ++i)
    lx += l[i - 1];

  if (!(x = NAG_ALLOC(lx, double)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }
  for (i = 1; i <= lx; ++i)
    scanf("%lf", &x[i - 1]);

  nlo = 1;
  for (i = 1; i <= k; ++i) {
    ni = l[i - 1];
    nhi = nlo + ni - 1;
    printf(" %5" NAG_IFMT "     ", i);
    count = 1;
    for (ii = nlo; ii <= nhi; ++ii) {
      printf("%4.0f%s", x[ii - 1], count % 10 ? "" : "\n");
      count++;
    }
    nlo += ni;
    printf("\n");
  }
  /* nag_kruskal_wallis_test (g08afc).
   * Kruskal-Wallis one-way analysis of variance on k samples
   * of unequal size
   */
  nag_kruskal_wallis_test(k, l, x, lx, &h, &p, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_kruskal_wallis_test (g08afc).\n%s\n",
           fail.message);
    exit_status = 1;
    goto END;
  }
  printf("\n");
  printf("%s%9.3f\n", "Test statistic       ", h);
  printf("%s%9" NAG_IFMT "\n", "Degrees of freedom   ", k - 1);
  printf("%s%9.3f\n", "Significance         ", p);
END:
  NAG_FREE(l);
  NAG_FREE(x);
  return exit_status;
}