/* nag_multi_normal (g01hbc) Example Program.
 *
 * Copyright 2017 Numerical Algorithms Group.
 *
 * Mark 26.1, 2017.
 *
 */

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

#define SIGMA(I, J) sigma[((I) -1)*n + (J) -1]
int main(void)
{
  Integer exit_status = 0, i, j, maxpts, n;
  char nag_enum_arg[40];
  double *a = 0, *b = 0, *mean = 0, prob, *sigma = 0, tol;
  Nag_TailProbability tail;
  NagError fail;

  INIT_FAIL(fail);

  printf("nag_multi_normal (g01hbc) Example Program Results\n");

  /* Skip heading in data file */
  scanf("%*[^\n]");
  scanf("%" NAG_IFMT " %lf %39s", &n, &tol, nag_enum_arg);
  /* nag_enum_name_to_value (x04nac).
   * Converts NAG enum member name to value
   */
  tail = (Nag_TailProbability) nag_enum_name_to_value(nag_enum_arg);

  if (!(a = NAG_ALLOC(n, double))
      || !(b = NAG_ALLOC(n, double))
      || !(mean = NAG_ALLOC(n, double))
      || !(sigma = NAG_ALLOC(n * n, double)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }

  for (j = 1; j <= n; ++j)
    scanf("%lf", &mean[j - 1]);
  for (i = 1; i <= n; ++i)
    for (j = 1; j <= n; ++j)
      scanf("%lf", &SIGMA(i, j));
  if (tail == Nag_Central || tail == Nag_UpperTail)
    for (j = 1; j <= n; ++j)
      scanf("%lf", &a[j - 1]);
  if (tail == Nag_Central || tail == Nag_LowerTail)
    for (j = 1; j <= n; ++j)
      scanf("%lf", &b[j - 1]);
  maxpts = 2000;
  /* nag_multi_normal (g01hbc).
   * Computes probabilities for the multivariate Normal
   * distribution
   */
  prob = nag_multi_normal(tail, n, a, b, mean, sigma, n, tol, maxpts, &fail);
  if (fail.code == NE_NOERROR || fail.code == NE_ACC
      || fail.code == NE_ROUND_OFF) {
    printf("\nMultivariate Normal probability =  %6.4f\n", prob);
  }
  else {
    printf("Error from nag_multi_normal (g01hbc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }
END:
  NAG_FREE(a);
  NAG_FREE(b);
  NAG_FREE(mean);
  NAG_FREE(sigma);
  return exit_status;
}