/* nag_surviv_logrank (g12abc) Example Program.
*
* Copyright 2017 Numerical Algorithms Group.
*
* Mark 26.1, 2017.
*/

/* 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;

/* Initialize 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("%" NAG_IFMT " %" NAG_IFMT " %" NAG_IFMT "%*[^\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%" NAG_IFMT "%" NAG_IFMT "", &t[i], &ic[i], &grp[i]);
if (lfreq > 0)
scanf("%" NAG_IFMT "%*[^\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 %1" NAG_IFMT " %8.2f  %8.2f\n", "Group", i + 1, obsd[i],
expt[i]);
printf("\n");
printf(" No. Unique Failure Times =  %3" NAG_IFMT "\n", nd);
printf("\n");
printf(" Test Statistic           =  %8.4f\n", ts);
printf(" Degrees of Freedom       =  %3" NAG_IFMT "\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;
}