/* nag_prob_binomial_vector (g01sjc) Example Program.
 *
 * Copyright 2017 Numerical Algorithms Group.
 *
 * Mark 26.1, 2017.
 */
#include <stdio.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <nagg01.h>

int main(void)
{
  /* Integer scalar and array declarations */
  Integer lk, lp, ln, i, lout;
  Integer *ivalid = 0, *k = 0, *n = 0;
  Integer exit_status = 0;

  /* NAG structures */
  NagError fail;

  /* Double scalar and array declarations */
  double *peqk = 0, *pgtk = 0, *plek = 0, *p = 0;

  /* Initialize the error structure to print out any error messages */
  INIT_FAIL(fail);

  printf("nag_prob_binomial_vector (g01sjc) Example Program Results\n\n");

  /* Skip heading in data file */
  scanf("%*[^\n] ");
  scanf("%" NAG_IFMT "%*[^\n] ", &ln);
  if (!(n = NAG_ALLOC(ln, Integer)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }
  for (i = 0; i < ln; i++)
    scanf("%" NAG_IFMT "", &n[i]);
  scanf("%*[^\n] ");
  scanf("%" NAG_IFMT "%*[^\n] ", &lp);
  if (!(p = NAG_ALLOC(lp, double)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }
  for (i = 0; i < lp; i++)
    scanf("%lf", &p[i]);
  scanf("%*[^\n] ");
  scanf("%" NAG_IFMT "%*[^\n] ", &lk);
  if (!(k = NAG_ALLOC(lk, Integer)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }
  for (i = 0; i < lk; i++)
    scanf("%" NAG_IFMT "", &k[i]);
  scanf("%*[^\n] ");

  /* Allocate memory for output */
  lout = MAX(ln, MAX(lp, lk));
  if (!(peqk = NAG_ALLOC(lout, double)) ||
      !(pgtk = NAG_ALLOC(lout, double)) ||
      !(plek = NAG_ALLOC(lout, double)) ||
      !(ivalid = NAG_ALLOC(lout, Integer)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }

  /* Calculate probability */
  nag_prob_binomial_vector(ln, n, lp, p, lk, k,
                           plek, pgtk, peqk, ivalid, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_prob_binomial_vector (g01sjc).\n%s\n",
           fail.message);
    exit_status = 1;
    if (fail.code != NW_IVALID)
      goto END;
  }

  /* Display title */
  printf("     n         p         k       ");
  printf("plek      pgtk      peqk  ivalid\n");
  printf(" --------------------------------");
  printf("----------------------------------\n");

  /* Display results */
  for (i = 0; i < lout; i++) {
    printf(" %6" NAG_IFMT "    %6.3f    %6" NAG_IFMT "",
           n[i % ln], p[i % lp], k[i % lk]);
    printf("    %6.3f    %6.3f    %6.3f   %3" NAG_IFMT "\n",
           plek[i], pgtk[i], peqk[i], ivalid[i]);
  }
END:
  NAG_FREE(n);
  NAG_FREE(p);
  NAG_FREE(k);
  NAG_FREE(plek);
  NAG_FREE(pgtk);
  NAG_FREE(peqk);
  NAG_FREE(ivalid);

  return (exit_status);
}