/* nag_normal_scores_var (g01dcc) 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)
{

  /* Scalars */
  double errest, etol, exp1, exp2, sumssq;
  Integer exit_status, i, j, k, n, vec_elem;
  NagError fail;

  /* Arrays */
  double *pp = 0, *vec = 0;

  INIT_FAIL(fail);

  printf("nag_normal_scores_var (g01dcc) Example Program Results\n");
  etol = 1e-4;
  exit_status = 0;
  n = 6;

  /* Allocate memory */
  if (!(pp = NAG_ALLOC(n, double)) ||
      !(vec = NAG_ALLOC(n * (n + 1) / 2, double)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }

  /* nag_normal_scores_exact (g01dac).
   * Normal scores, accurate values
   */
  nag_normal_scores_exact(n, pp, etol, &errest, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_normal_scores_exact (g01dac).\n%s\n",
           fail.message);
    exit_status = 1;
    goto END;
  }
  exp1 = pp[5];
  exp2 = pp[4];
  sumssq = 0.0;
  for (i = 1; i <= 6; ++i)
    sumssq += pp[i - 1] * pp[i - 1];

  /* nag_normal_scores_var (g01dcc).
   * Normal scores, approximate variance-covariance matrix
   */
  nag_normal_scores_var(n, exp1, exp2, sumssq, vec, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_normal_scores_exact (g01dac).\n%s\n",
           fail.message);
    exit_status = 1;
    goto END;
  }

  printf("\nSample size = %2" NAG_IFMT "\n\n", n);
  printf("Variance-covariance matrix\n");
  k = 1;
  for (j = 1; j <= n; ++j) {
    vec_elem = 1;
    for (i = k; i <= k + j - 1; ++i) {
      printf("%8.4f%s", vec[i - 1], vec_elem % 6 == 0 ? "\n" : " ");
      vec_elem++;
    }
    printf("\n");
    k += j;
  }
END:
  NAG_FREE(pp);
  NAG_FREE(vec);

  return exit_status;
}