/* nag_wilcoxon_test (g08agc) Example Program.
 *
 * Copyright 2017 Numerical Algorithms Group.
 *
 * Mark 26.1, 2017.
 */

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

int main(void)
{
  Integer exit_status = 0, i, n, non_zero;
  NagError fail;
  double *data = 0, median, p, w, *x = 0, *y = 0, z;

  INIT_FAIL(fail);

  printf("nag_wilcoxon_test (g08agc) Example Program Results");

  /* Skip heading in data file */
  scanf("%*[^\n]");
  scanf("%" NAG_IFMT "", &n);
  if (!(x = NAG_ALLOC(n, double))
      || !(y = NAG_ALLOC(n, double))
      || !(data = NAG_ALLOC(n, double)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }

  for (i = 1; i <= n; ++i)
    scanf("%lf", &x[i - 1]);

  for (i = 1; i <= n; ++i)
    scanf("%lf", &y[i - 1]);

  printf("\n\n");
  printf("%s\n", "Wilcoxon one sample signed ranks test");
  printf("\n");
  printf("%s", "Data values\n");
  for (i = 1; i <= n; ++i)
    printf("%5.1f%s", x[i - 1], i % 8 ? "" : "\n");
  for (i = 1; i <= n; ++i)
    printf("%5.1f%s", y[i - 1], i % 8 ? "" : "\n");

  for (i = 1; i <= n; ++i)
    data[i - 1] = x[i - 1] - y[i - 1];
  median = 0.0;
  /* nag_wilcoxon_test (g08agc).
   * Performs the Wilcoxon one-sample (matched pairs) signed
   * rank test
   */
  nag_wilcoxon_test(n, data, median, Nag_TwoTail, Nag_IncSignZerosN, &w, &z,
                    &p, &non_zero, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_wilcoxon_test (g08agc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  printf("\n\n");
  printf("%s%8.4f\n", "Test statistic            = ", w);
  printf("%s%8.4f\n", "Normalized test statistic = ", z);
  printf("%s%8" NAG_IFMT "\n", "Degrees of freedom        = ", non_zero);
  printf("%s%8.4f\n", "Two tail probability      = ", p);

END:
  NAG_FREE(x);
  NAG_FREE(y);
  NAG_FREE(data);
  return exit_status;
}