/* nag_mann_whitney (g08amc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 6a revised, 2001.
 */

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

int main(void)
{

  Integer  exit_status = 0, i, n1, n2;
  NagError fail;
  double   p, u, *x = 0, *y = 0, z;

  INIT_FAIL(fail);

  printf("nag_mann_whitney (g08amc) Example Program Results\n\n");

  /* Skip heading in data file */
  scanf("%*[^\n]");
  scanf("%ld %ld ", &n1, &n2);
  printf("%s%5ld\n", "Sample size of group 1 = ", n1);
  printf("%s%5ld\n", "Sample size of group 2 = ", n2);
  if (!(x = NAG_ALLOC(n1, double))
     || !(y = NAG_ALLOC(n2, double)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }
  printf("\n");
  for (i = 1; i <= n1; ++i)
    scanf("%lf", &x[i - 1]);
  printf("%s\n", "Mann-Whitney U test");
  printf("\n");
  printf("%s\n", "Data values");
  printf("\n");
  printf("%s", "    Group 1  ");
  for (i = 1; i <= n1; ++i)
    printf("%5.1f%s", x[i - 1], i%8?"":"\n             ");
  for (i = 1; i <= n2; ++i)
    scanf("%lf", &y[i - 1]);
  printf("\n");
  printf("%s", "    Group 2  ");
  for (i = 1; i <= n2; ++i)
    printf("%5.1f%s", y[i - 1], i%8?"":"\n             ");

  /* nag_mann_whitney (g08amc).
   * Performs the Mann-Whitney U test on two independent
   * samples
   */
  nag_mann_whitney(n1, x, n2, y, Nag_LowerTail, Nag_CompProbApprox,
                   &u, &z, &p, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_mann_whitney (g08amc).\n%s\n",
              fail.message);
      exit_status = 1;
      goto END;
    }
  printf("\n\n");
  printf("%s%8.4f\n", "Test statistic                 = ", u);
  printf("%s%8.4f\n", "Normal Statistic               = ", z);
  printf("%s%8.4f\n", "Approximate tail probability   = ", p);
  /* nag_mann_whitney (g08amc), see above. */
  nag_mann_whitney(n1, x, n2, y, Nag_LowerTail, Nag_CompProbExact,
                   &u, &z, &p, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_mann_whitney (g08amc).\n%s\n",
              fail.message);
      exit_status = 1;
      goto END;
    }
  printf("%s%8.4f\n", "Exact tail probability         = ", p);
 END:
  NAG_FREE(x);
  NAG_FREE(y);
  return exit_status;
}