/* nag_censored_normal (g07bbc) Example Program.
 *
 * Copyright 2017 Numerical Algorithms Group.
 *
 * Mark 26.1, 2017.
 */

#include <stdio.h>
#include <string.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <nagg07.h>

int main(void)
{
  /* Scalars */
  double corr, dev, sexmu, sexsig, tol, xmu, xsig;
  Integer exit_status, i, maxit, n, nit;
  /* Arrays */
  char nag_enum_arg[40];
  double *x = 0, *xc = 0;
  Integer *ic = 0, *nobs = 0;
  Nag_CEMethod method;
  NagError fail;

  INIT_FAIL(fail);

  exit_status = 0;
  printf("nag_censored_normal (g07bbc) Example Program Results\n");

  /* Skip heading in data file */
  scanf("%*[^\n] ");
  scanf("%" NAG_IFMT " %39s %lf%lf%lf%" NAG_IFMT "%*[^\n] ", &n, nag_enum_arg,
        &xmu, &xsig, &tol, &maxit);
  /* nag_enum_name_to_value (x04nac).
   * Converts NAG enum member name to value
   */
  method = (Nag_CEMethod) nag_enum_name_to_value(nag_enum_arg);

  /* Allocate memory */
  if (!(x = NAG_ALLOC(n, double)) ||
      !(xc = NAG_ALLOC(n, double)) ||
      !(ic = NAG_ALLOC(n, Integer)) || !(nobs = NAG_ALLOC(4, Integer)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }

  for (i = 1; i <= n; ++i)
    scanf("%lf%lf%" NAG_IFMT "", &x[i - 1], &xc[i - 1], &ic[i - 1]);
  scanf("%*[^\n] ");

  /* nag_censored_normal (g07bbc).
   * Computes maximum likelihood estimates for parameters of
   * the Normal distribution from grouped and/or censored data
   */
  nag_censored_normal(method, n, x, xc, ic, &xmu, &xsig, tol, maxit,
                      &sexmu, &sexsig, &corr, &dev, nobs, &nit, &fail);

  if (fail.code != NE_NOERROR) {
    printf("Error from nag_censored_normal (g07bbc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  printf("\n");
  printf(" Mean = %8.4f\n", xmu);
  printf(" Standard deviation = %8.4f\n", xsig);
  printf(" Standard error of mean = %8.4f\n", sexmu);
  printf(" Standard error of sigma = %8.4f\n", sexsig);
  printf(" Correlation coefficient = %8.4f\n", corr);
  printf(" Number of right censored observations = %2" NAG_IFMT "\n",
         nobs[0]);
  printf(" Number of left censored observations = %2" NAG_IFMT "\n", nobs[1]);
  printf(" Number of interval censored observations = %2" NAG_IFMT "\n",
         nobs[2]);
  printf(" Number of exactly specified observations = %2" NAG_IFMT "\n",
         nobs[3]);
  printf(" Number of iterations = %2" NAG_IFMT "\n", nit);
  printf(" Log-likelihood = %8.4f\n", dev);

END:
  NAG_FREE(x);
  NAG_FREE(xc);
  NAG_FREE(ic);
  NAG_FREE(nobs);

  return exit_status;
}