/* nag_kernel_density_gauss (g10bbc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 24, 2013.
 */
/* Pre-processor includes */
#include <stdio.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <nagg01.h>
#include <nagg10.h>

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

  /* Nag Types */
  NagError fail;
  Nag_Boolean fcall;
  Nag_WindowType wtype;

  /* Double scalar and array declarations */
  double shi, slo, window;
  double *rcomm = 0, *smooth = 0, *t = 0, *x = 0;

  /* Character scalar and array declarations */
  char cwtype[40];

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

  printf("nag_kernel_density_gauss (g10bbc) Example Program Results\n\n");

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

  /* Read in density estimation information */
  scanf("%39s %lf %lf %lf %ld%*[^\n] ", cwtype, &window, &slo, &shi,
        &ns);
  wtype = (Nag_WindowType) nag_enum_name_to_value(cwtype); 

  /* Read in the size of the dataset */
  scanf("%ld%*[^\n] ", &n);

  if (!(smooth = NAG_ALLOC(ns, double)) ||
      !(t = NAG_ALLOC(ns, double)) ||
      !(rcomm = NAG_ALLOC(ns+20, double)) ||
      !(x = NAG_ALLOC(n, double)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }

  /* Only calling the routine once */
  fcall = Nag_TRUE;

  /* Read in data */
  for (i = 0; i < n; i++)
    {
      scanf("%lf", &x[i]);
    }
  scanf("%*[^\n] ");

  /* Call nag_kernel_density_gauss (g10bbc) to perform kernel 
   * density estimation
   */
  nag_kernel_density_gauss(n,x,wtype,&window,&slo,&shi,ns,smooth,t,fcall,
                           rcomm,&fail);
  if (fail.code != NE_NOERROR && fail.code != NW_POTENTIAL_PROBLEM)
    {
      printf("Error from nag_kernel_density_gauss (g10bbc).\n%s\n",
             fail.message);
      exit_status = -1;
      goto END;
    }

  /* Display the summary of results */
  printf("Window Width Used = %13.4e\n", window);
  printf("Interval = (%13.4e,%13.4e)\n", slo, shi);
  printf("\n");
  printf("First %ld output values:\n", MIN(ns,20));
  printf("\n");
  printf("      Time        Density\n");
  printf("      Point       Estimate\n");
  printf(" ---------------------------\n");
  for (i = 0; i < MIN(20,ns); i++)
    printf(" %13.3e %13.3e\n", t[i], smooth[i]);

 END:
  NAG_FREE(smooth);
  NAG_FREE(t);
  NAG_FREE(rcomm);
  NAG_FREE(x);

  return exit_status;
}