/* nag_prod_limit_surviv_fn (g12aac) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 4, 1996.
 * Mark 8 revised, 2004.
 *
 */

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

int main(void)
{

  Integer  exit_status = 0, i, *ic = 0, *ifreq = 0, n, nd;
  NagError fail;
  double   *p = 0, *psig = 0, *t = 0, *tp = 0;

  INIT_FAIL(fail);

  printf("nag_prod_limit_surviv_fn (g12aac) Example Program Results\n");

  /* Skip heading in data file */
  scanf("%*[^\n] ");
  scanf("%ld ", &n);
  if (n >= 2)
    {
      if (!(psig = NAG_ALLOC(n, double)) ||
          !(p = NAG_ALLOC(n, double)) ||
          !(t = NAG_ALLOC(n, double)) ||
          !(tp = NAG_ALLOC(n, double)) ||
          !(ifreq = NAG_ALLOC(n, Integer)) ||
          !(ic = NAG_ALLOC(n, Integer)))
        {
          printf("Allocation failure\n");
          exit_status = -1;
          goto END;
        }
    }
  else
    {
      printf("Invalid n.\n");
      exit_status = 1;
      return exit_status;
    }

  for (i = 0; i < n; ++i)
    scanf("%lf %ld %ld ", &t[i], &ic[i], &ifreq[i]);

  /* nag_prod_limit_surviv_fn (g12aac).
   * Computes Kaplan-Meier (product-limit) estimates of
   * survival probabilities
   */
  nag_prod_limit_surviv_fn(n, t, ic, ifreq, &nd, tp, p, psig, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_prod_limit_surviv_fn (g12aac).\n%s\n",
              fail.message);
      exit_status = 1;
      goto END;
    }

  printf("\n   Time   Survival    Standard\n");
  printf("         probability  deviation\n\n");
  for (i = 0; i < nd; ++i)
    printf(" %6.1f%10.3f  %10.3f\n", tp[i], p[i], psig[i]);

 END:
  NAG_FREE(psig);
  NAG_FREE(p);
  NAG_FREE(t);
  NAG_FREE(tp);
  NAG_FREE(ifreq);
  NAG_FREE(ic);
  return exit_status;
}