/* nag_corr_cov (g02bxc) Example Program.
 *
 * NAGPRODCODE Version.
 *
 * Copyright 2016 Numerical Algorithms Group.
 *
 * Mark 26, 2016.
 */

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

#define X(I, J) x[(I) *tdx + J]
#define R(I, J) r[(I) *tdr + J]
#define V(I, J) v[(I) *tdv + J]
int main(void)
{
  Integer exit_status = 0, i, j, m, n, tdr, tdv, tdx, test;
  NagError fail;
  char w;
  double *r = 0, *std = 0, sw, *v = 0, *wmean = 0, *wt = 0, *wtptr, *x = 0;

  INIT_FAIL(fail);

  printf("nag_corr_cov (g02bxc) Example Program Results\n");

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

  test = 0;
  while ((scanf("%" NAG_IFMT "%" NAG_IFMT " %c", &m, &n, &w) != EOF))
  {
    if (m >= 1 && n >= 1) {
      if (!(x = NAG_ALLOC(n * m, double)) ||
          !(r = NAG_ALLOC(m * m, double)) ||
          !(v = NAG_ALLOC(m * m, double)) ||
          !(wt = NAG_ALLOC(n, double)) ||
          !(wmean = NAG_ALLOC(m, double)) || !(std = NAG_ALLOC(m, double)))
      {
        printf("Allocation failure\n");
        exit_status = -1;
        goto END;
      }
      tdx = m;
      tdr = m;
      tdv = m;
    }
    else {
      printf("Invalid m or n.\n");
      exit_status = 1;
      return exit_status;
    }
    for (i = 0; i < n; i++)
      scanf("%lf", &wt[i]);
    for (i = 0; i < n; i++)
      for (j = 0; j < m; j++)
        scanf("%lf", &X(i, j));

    if (w == 'w')
      wtptr = wt;
    else
      wtptr = (double *) 0;

    /* nag_corr_cov (g02bxc).
     * Product-moment correlation, unweighted/weighted
     * correlation and covariance matrix, allows variables to be
     * disregarded
     */
    nag_corr_cov(n, m, x, tdx, (Integer *) 0, wtptr, &sw, wmean, std,
                 r, tdr, v, tdv, &fail);
    if (fail.code != NE_NOERROR) {
      printf("Error from nag_corr_cov (g02bxc).\n%s\n", fail.message);
      exit_status = 1;
      goto END;
    }

    if (wtptr)
      printf("\nCase %" NAG_IFMT " --- Using weights\n", ++test);
    else
      printf("\nCase %" NAG_IFMT " --- Not using weights\n", ++test);

    printf("\nInput data\n");
    for (i = 0; i < n; i++)
      printf("%6.1f%6.1f%6.1f%6.1f\n", X(i, 0), X(i, 1), X(i, 2), wt[i]);

    printf("\n");
    printf("Sample means.\n");
    for (i = 0; i < m; i++)
      printf("%6.1f\n", wmean[i]);
    printf("\nStandard deviation.\n");
    for (i = 0; i < m; i++)
      printf("%6.1f\n", std[i]);

    printf("\nCorrelation matrix.\n");
    for (i = 0; i < m; i++) {
      for (j = 0; j < m; j++)
        printf("  %7.4f  ", R(i, j));
      printf("\n");
    }

    printf("\nVariance matrix.\n");
    for (i = 0; i < m; i++) {
      for (j = 0; j < m; j++)
        printf("  %7.3f  ", V(i, j));
      printf("\n");
    }
    printf("\nSum of weights %6.1f\n", sw);
  END:
    NAG_FREE(x);
    NAG_FREE(r);
    NAG_FREE(v);
    NAG_FREE(wt);
    NAG_FREE(wmean);
    NAG_FREE(std);
  }
  return exit_status;
}