/* nag_surviv_logrank (g12abc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 23, 2011.
 */

/* Pre-processor includes */
#include <stdio.h>
#include <math.h>
#include <ctype.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <nagg12.h>

int main(void)
{

  /* Integer scalar and array declarations */
  Integer i, n, ngrp, lfreq, df, nd, ldn, exit_status;
  Integer *ic = 0, *grp = 0, *ifreq = 0, *di = 0, *ni = 0;

  /* NAG structures */
  NagError fail;

  /* Double scalar and array declarations */
  double ts, p;
  double *t = 0, *obsd = 0, *expt = 0;

  /* Performing a logrank test, so no weights needed */
  double *wt = 0;

  exit_status = 0;

  /* Initialise the error structure */
  INIT_FAIL(fail);


  printf("nag_surviv_logrank (g12abc) Example Program Results\n");

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

  /* Read in the problem size */
  scanf("%ld %ld %ld%*[^\n] ", &n, &ngrp, &lfreq);
  ldn = n;

  /* Allocate memory to input and output arrays */
  if (!(t = NAG_ALLOC(n, double)) ||
      !(ic = NAG_ALLOC(n, Integer)) ||
      !(grp = NAG_ALLOC(n, Integer)) ||
      !(obsd = NAG_ALLOC(ngrp, double)) ||
      !(expt = NAG_ALLOC(ngrp, double)) ||
      !(di = NAG_ALLOC(ldn, Integer)) ||
      !(ni = NAG_ALLOC(ldn, Integer)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }

  if (lfreq > 0) {
    lfreq = n;
    if (!(ifreq = NAG_ALLOC(lfreq, Integer))) {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }
  }

  /* Read in the times, censored flag, group information and if supplied the
     frequencies */
  for (i=0; i<n; i++) {
    scanf("%lf%ld%ld", &t[i], &ic[i], &grp[i]);
    if (lfreq > 0)
      scanf("%ld%*[^\n] ", &ifreq[i]);
  }

  /* Calculate the logrank statistic using nag_surviv_logrank (g12abc) */
  nag_surviv_logrank(n, t, ic, grp, ngrp, ifreq, wt, &ts, &df, &p, obsd,
                     expt, &nd, di, ni, ldn, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_surviv_logrank (g12abc).\n%s\n",
            fail.message);
    exit_status = 1;
    goto END;
  }

  /* Display the test information */
  printf("\n");
  printf("           Observed  Expected\n");
  for (i = 0; i < ngrp; i++)
    printf(" %-5s %1ld %8.2f  %8.2f\n", "Group",i+1,obsd[i], expt[i]);
  printf("\n");
  printf(" No. Unique Failure Times =  %3ld\n", nd);
  printf("\n");
  printf(" Test Statistic           =  %8.4f\n", ts);
  printf(" Degrees of Freedom       =  %3ld\n", df);
  printf(" p-value                  =  %8.4f\n", p);

  END:
  NAG_FREE(t);
  NAG_FREE(ic);
  NAG_FREE(ifreq);
  NAG_FREE(wt);
  NAG_FREE(grp);
  NAG_FREE(obsd);
  NAG_FREE(expt);
  NAG_FREE(di);
  NAG_FREE(ni);

  return exit_status;
}