/* nag_frequency_table (g01aec) Example Program.
 *
 * NAGPRODCODE Version.
 *
 * Copyright 2016 Numerical Algorithms Group.
 *
 * Mark 26, 2016.
 */

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

int main(void)
{
  Integer exit_status = 0, i, j, *jfreq = 0, n, nprob, num_class;
  char nag_enum_arg[40];
  Nag_ClassBoundary classb;
  double *a = 0, *c = 0, xmax, xmin;
  NagError fail;

  INIT_FAIL(fail);

  printf("nag_frequency_table (g01aec) Example Program Results\n\n");

  /* Skip heading in data file */
  scanf("%*[^\n] ");
  scanf("%" NAG_IFMT "", &nprob);
  for (i = 1; i <= nprob; ++i) {
    scanf("%" NAG_IFMT " %39s %" NAG_IFMT "", &n, nag_enum_arg, &num_class);
    /* nag_enum_name_to_value (x04nac).
     * Converts NAG enum member name to value
     */
    classb = (Nag_ClassBoundary) nag_enum_name_to_value(nag_enum_arg);
    if (!(a = NAG_ALLOC(n, double))
        || !(c = NAG_ALLOC(num_class - 1, double))
        || !(jfreq = NAG_ALLOC(num_class, Integer)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }
    for (j = 1; j <= n; ++j)
      scanf("%lf", &a[j - 1]);
    printf("Problem %" NAG_IFMT "\n", i);
    printf("Number of cases %" NAG_IFMT "\n", n);
    printf("Number of classes, including extreme classes %" NAG_IFMT "\n",
           num_class);
    if (classb != Nag_ClassBoundaryUser)
      printf("Routine-supplied class boundaries\n\n");
    else {
      for (j = 1; j <= num_class - 1; ++j)
        scanf("%lf", &c[j - 1]);
      printf("User-supplied class boundaries\n");
    }
    /* nag_frequency_table (g01aec).
     * Frequency table from raw data
     */
    nag_frequency_table(n, a, num_class, classb, c, jfreq, &xmin, &xmax,
                        &fail);
    if (fail.code == NE_NOERROR) {
      printf("Successful call of " "nag_frequency_table (g01aec)\n\n");
      printf("*** Frequency  distribution ***\n\n");
      printf("       Class            Frequency\n\n");
      printf("   Up to    %8.2f %11" NAG_IFMT "\n", c[0], jfreq[0]);
      if (num_class - 1 > 1) {
        for (j = 2; j <= num_class - 1; ++j)
          printf("%8.2f to %8.2f %11" NAG_IFMT "\n", c[j - 2],
                 c[j - 1], jfreq[j - 1]);
      }
      printf("%8.2f     and over  %9" NAG_IFMT "\n\n",
             c[num_class - 2], jfreq[num_class - 1]);
      printf("Total frequency = %" NAG_IFMT "\n", n);
      printf("Minimum = %9.2f\n", xmin);
      printf("Maximum = %9.2f\n", xmax);
    }
    else {
      printf("Error from nag_frequency_table (g01aec).\n%s\n", fail.message);
      exit_status = 1;
      goto END;
    }
    NAG_FREE(a);
    NAG_FREE(c);
    NAG_FREE(jfreq);
  }

END:
  NAG_FREE(a);
  NAG_FREE(c);
  NAG_FREE(jfreq);

  return exit_status;
}