/* nag_frequency_table (g01aec) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 6a revised, 2001.
 */

#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 class;
  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("%ld", &nprob);
  for (i = 1; i <= nprob; ++i)
    {
      scanf("%ld %39s %ld", &n, nag_enum_arg, &num_class);
      /* nag_enum_name_to_value (x04nac).
       * Converts NAG enum member name to value
       */
      class = (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 %ld\n", i);
      printf("Number of cases %ld\n", n);
      printf(
              "Number of classes, including extreme classes %ld\n",
              num_class);
      if (class != 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, class, 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 %11ld\n", c[0], jfreq[0]);
          if (num_class-1 > 1)
            {
              for (j = 2; j <= num_class-1; ++j)
                printf("%8.2f to %8.2f %11ld\n", c[j - 2],
                        c[j - 1], jfreq[j - 1]);
            }
          printf("%8.2f     and over  %9ld\n\n",
                  c[num_class - 2], jfreq[num_class-1]);
          printf("Total frequency = %ld\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;
}