/* nag_tabulate_margin (g11bcc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 7, 2002.
 */

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

int main(void)
{
  /* Scalars */
  Integer        exit_status, i, j, k, maxst, mcells, mdim;
  Integer        ncells, ncol, ndim, nrow;
  Nag_TableStats stat;
  /* Arrays */
  char           nag_enum_arg[40];
  double         *auxt = 0, *stable = 0, *table = 0;
  Integer        *idim = 0, *isdim = 0, *mlevel = 0;
  NagError       fail;

  INIT_FAIL(fail);

  exit_status = 0;
  printf("nag_tabulate_margin (g11bcc) Example Program Results\n");

  /* Skip heading in data file */
  scanf("%*[^\n] ");
  scanf("%39s%ld%ld%*[^\n] ", nag_enum_arg, &ncells, &ndim);
  /* nag_enum_name_to_value (x04nac).
   * Converts NAG enum member name to value
   */
  stat = (Nag_TableStats) nag_enum_name_to_value(nag_enum_arg);

  maxst = 54;

  /* Allocate arrays */
  if (!(auxt = NAG_ALLOC(maxst, double)) ||
      !(stable = NAG_ALLOC(maxst, double)) ||
      !(table = NAG_ALLOC(ncells, double)) ||
      !(idim = NAG_ALLOC(ndim, Integer)) ||
      !(isdim = NAG_ALLOC(ndim, Integer)) ||
      !(mlevel = NAG_ALLOC(ndim, Integer)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }

  for (i = 1; i <= ncells; ++i)
    scanf("%lf", &table[i-1]);
  scanf("%*[^\n] ");

  for (j = 1; j <= ndim; ++j)
    scanf("%ld", &idim[j-1]);
  scanf("%*[^\n] ");

  for (j = 1; j <= ndim; ++j)
    scanf("%ld", &isdim[j-1]);
  scanf("%*[^\n] ");

  /* nag_tabulate_margin (g11bcc).
   * Computes marginal tables for multiway table computed by
   * nag_tabulate_stats (g11bac) or nag_tabulate_percentile
   * (g11bbc)
   */
  nag_tabulate_margin(stat, table, ncells, ndim, idim, isdim, stable,
                      maxst, &mcells, &mdim, mlevel, auxt, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_tabulate_margin (g11bcc).\n%s\n",
              fail.message);
      exit_status = 1;
      goto END;
    }


  printf("\n");
  printf(" Marginal Table\n");
  printf("\n");

  ncol = mlevel[mdim-1];
  nrow = mcells / ncol;
  k = 1;
  for (i = 1; i <= nrow; ++i)
    {
      for (j = k; j <= k + ncol - 1; ++j)
        printf("%7.2f ", stable[j-1]);
      printf("\n");
      k += ncol;
    }

 END:
  NAG_FREE(auxt);
  NAG_FREE(stable);
  NAG_FREE(table);
  NAG_FREE(idim);
  NAG_FREE(isdim);
  NAG_FREE(mlevel);

  return exit_status;
}