```/* nag_tabulate_stats (g11bac) Example Program.
*
* Copyright 2017 Numerical Algorithms Group.
*
* Mark 26.1, 2017.
*/

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

int main(void)
{
Integer exit_status = 0, i, items, j, k, ltmax, maxt, n, ncells;
Integer ncol, ndim, nfac, nrow, tdf;
Integer *count = 0, *factor = 0, *idim = 0, *isf = 0, *lfac = 0;
double *comm_ar = 0, *table = 0, *wt = 0, *y = 0;
char nag_enum_arg[40];
Nag_TableStats stat;
Nag_Weightstype weight;
NagError fail;

#define FACTOR(I, J) factor[((I) -1)*nfac + (J) -1]

INIT_FAIL(fail);

printf("nag_tabulate_stats (g11bac) Example Program Results\n");

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

ltmax = 18;
maxt = ltmax;
if (!(isf = NAG_ALLOC(nfac, Integer))
|| !(lfac = NAG_ALLOC(nfac, Integer))
|| !(idim = NAG_ALLOC(nfac, Integer))
|| !(factor = NAG_ALLOC(n * nfac, Integer))
|| !(count = NAG_ALLOC(maxt, Integer))
|| !(y = NAG_ALLOC(n, double))
|| !(wt = NAG_ALLOC(n, double))
|| !(table = NAG_ALLOC(maxt, double))
|| !(comm_ar = NAG_ALLOC(2 * maxt, double)))
{
printf("Allocation failure\n");
exit_status = -1;
goto END;
}

if (weight == Nag_Weights || weight == Nag_Weightsvar) {
for (i = 1; i <= n; ++i) {
for (j = 1; j <= nfac; ++j)
scanf("%" NAG_IFMT "", &FACTOR(i, j));
scanf("%lf %lf", &y[i - 1], &wt[i - 1]);
}
}
else {
for (i = 1; i <= n; ++i) {
for (j = 1; j <= nfac; ++j)
scanf("%" NAG_IFMT "", &FACTOR(i, j));
scanf("%lf", &y[i - 1]);
}
}
for (j = 1; j <= nfac; ++j)
scanf("%" NAG_IFMT "", &lfac[j - 1]);
for (j = 1; j <= nfac; ++j)
scanf("%" NAG_IFMT "", &isf[j - 1]);
tdf = 3;
maxt = ltmax;

/* nag_tabulate_stats (g11bac).
* Computes multiway table from set of classification
* factors using selected statistic
*/
nag_tabulate_stats(stat, Nag_TableUpdateI, weight, n, nfac, isf,
lfac, factor, tdf, y, wt, table, maxt, &ncells, &ndim,
idim, count, comm_ar, &fail);
if (fail.code != NE_NOERROR) {
printf("Error from nag_tabulate_stats (g11bac).\n%s\n", fail.message);
exit_status = 1;
goto END;
}
printf("\n");
printf("%s\n", "Table");
printf("\n");
ncol = idim[ndim - 1];
nrow = ncells / ncol;
k = 1;
for (i = 1; i <= nrow; ++i) {
for (j = k, items = 1; j <= k + ncol - 1; ++j, items++)
printf("%8.2f(%2" NAG_IFMT ")%s", table[j - 1],
count[j - 1], items % 6 ? "" : "\n");
k += ncol;
}

END:
NAG_FREE(isf);
NAG_FREE(lfac);
NAG_FREE(idim);
NAG_FREE(factor);
NAG_FREE(count);
NAG_FREE(y);
NAG_FREE(wt);
NAG_FREE(table);
NAG_FREE(comm_ar);

return exit_status;
}
```