/* nag_binary_factor_service (g11sbc) 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, p, ns, j, n, nrx, pdx;
  /* Arrays */
  char          nag_enum_arg[40];
  Integer       *irl = 0;
  Nag_Boolean   *x = 0;
  Nag_OrderType order;
  NagError      fail;

#ifdef NAG_COLUMN_MAJOR
#define X(I, J) x[(J-1)*pdx + I - 1]
  order = Nag_ColMajor;
#else
#define X(I, J) x[(I-1)*pdx + J - 1]
  order = Nag_RowMajor;
#endif

  INIT_FAIL(fail);

  exit_status = 0;
  printf(
          "nag_binary_factor_service (g11sbc) Example Program Results\n");

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

  if (n > 0 && p > 0)
    {
      /* Allocate arrays */
      nrx = n;
      if (!(irl = NAG_ALLOC(n, Integer)) ||
          !(x = NAG_ALLOC(nrx * p, Nag_Boolean)))
        {
          printf("Allocation failure\n");
          exit_status = -1;
          goto END;
        }

      if (order == Nag_ColMajor)
        pdx = nrx;
      else
        pdx = p;

      for (i = 1; i <= n; ++i)
        {
          for (j = 1; j <= p; ++j)
            {
              scanf(" %39s", nag_enum_arg);
              /* nag_enum_name_to_value (x04nac).
               * Converts NAG enum member name to value
               */
              X(i, j) = (Nag_Boolean) nag_enum_name_to_value(nag_enum_arg);
            }
          scanf("%*[^\n] ");
        }

      /* nag_binary_factor_service (g11sbc).
       * Frequency count for nag_binary_factor (g11sac)
       */
      nag_binary_factor_service(order, p, n, &ns, x, pdx, irl, &fail);
      if (fail.code != NE_NOERROR)
        {
          printf(
                  "Error from nag_binary_factor_service (g11sbc).\n%s\n",
                  fail.message);
          exit_status = 1;
          goto END;
        }

      printf("\n");
      printf("Frequency                 Score pattern\n");
      printf("\n");
      for (i = 1; i <= ns; ++i)
        {
          printf("%5ld            ", irl[i-1]);
          for (j = 1; j <= p; ++j)
            printf("%-9s  ", nag_enum_value_to_name(X(i, j)));

          printf("\n");
        }
    }

 END:
  NAG_FREE(irl);
  NAG_FREE(x);

  return exit_status;
}