/* nag_estim_gen_pareto (g07bfc) Example Program.
 *
 * Copyright 2017 Numerical Algorithms Group.
 *
 * Mark 26.1, 2017.
 */
/* Pre-processor includes */
#include <stdio.h>
#include <math.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <nagg07.h>

int main(void)
{
  /* Integer scalar and array declarations */
  Integer exit_status = 0;
  Integer i, n;

  /* Double scalar and array declarations */
  double asvc[4], beta, ll, obsvc[4], xi, *y = 0;

  /* Character scalar and array declarations */
  char soptopt[12];

  /* NAG types */
  NagError fail;
  Nag_OptimOpt optopt;

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

  printf("nag_estim_gen_pareto (g07bfc) Example Program Results\n\n");

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

  /* Read parameter values */
  scanf("%" NAG_IFMT "%11s%*[^\n]", &n, soptopt);
  optopt = (Nag_OptimOpt) nag_enum_name_to_value(soptopt);

  /* Allocate data array */
  if (!(y = NAG_ALLOC(n, double)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }

  /* Read data values */
  for (i = 1; i <= n; i++)
    scanf("%lf", &y[i - 1]);
  scanf("%*[^\n]");

  /* Calculate the GPD parameter estimates */
  nag_estim_gen_pareto(n, y, optopt, &xi, &beta, asvc, obsvc, &ll, &fail);

  /* Print parameter estimates */
  switch (fail.code) {
  case NE_NOERROR:
  case NW_PARAM_DIST:
  case NW_PARAM_DIST_ASYM:
  case NW_PARAM_DIST_OBS:
    printf(" Parameter estimates\n");
    printf(" %-12s%12.6e\n %-12s%12.6e\n", "xi", xi, "beta", beta);
    break;
  default:
    printf("Error from nag_estim_gen_pareto (g07bfc).\n%s\n", fail.message);
    exit_status = -1;
    goto END;
  }

  /* Print parameter distribution */
  if (optopt == Nag_MOMMLE || optopt == Nag_PWMMLE) {
    switch (fail.code) {
    case NW_PARAM_DIST:
    case NW_PARAM_DIST_OBS:
      printf(" %s\n", fail.message);
      exit_status = -1;
      break;
    default:
      printf("\n Observed distribution\n");
      printf(" %-20s%12.6e\n %-20s%12.6e\n %-20s%12.6e\n",
             "Var(xi)", obsvc[0], "Var(beta)", obsvc[3], "Covar(xi,beta)",
             obsvc[1]);
      printf("\n Final log-likelihood: %12.6e\n", ll);
    }
  }
  else {
    switch (fail.code) {
    case NW_PARAM_DIST:
    case NW_PARAM_DIST_ASYM:
      printf(" %s\n", fail.message);
      exit_status = -1;
      break;
    default:
      printf("\n Asymptotic distribution\n");
      printf(" %-20s%12.6e\n %-20s%12.6e\n %-20s%12.6e\n",
             "Var(xi)", asvc[0], "Var(beta)", asvc[3], "Covar(xi,beta)",
             asvc[1]);
    }
  }

END:
  NAG_FREE(y);

  return exit_status;
}