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

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

#define X(I, J) x[(I) *tdx + J]
#define Z(I, J) z[(I) *tdz + J]
int main(void)
{
  Integer exit_status = 0, i, *isx = 0, j, m, n, nvar, tdx, tdz;
  NagError fail;
  double *e = 0, *s = 0, *x = 0, *z = 0;

  INIT_FAIL(fail);

  printf("nag_mv_z_scores (g03zac) Example Program Results\n\n");

  /* Skip headings in data file */
  scanf("%*[^\n]");
  scanf("%" NAG_IFMT "", &n);
  scanf("%" NAG_IFMT "", &m);
  scanf("%" NAG_IFMT "", &nvar);

  if (n >= 1 && nvar >= 1 && m >= nvar) {
    if (!(e = NAG_ALLOC(m, double)) ||
        !(s = NAG_ALLOC(m, double)) ||
        !(x = NAG_ALLOC((n) * (m), double)) ||
        !(z = NAG_ALLOC((n) * (nvar), double)) ||
        !(isx = NAG_ALLOC(m, Integer)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }
    tdx = m;
    tdz = nvar;
  }
  else {
    printf("Invalid n or nvar.\n");
    exit_status = 1;
    return exit_status;
  }
  for (i = 0; i < n; ++i) {
    for (j = 0; j < m; ++j)
      scanf("%lf", &X(i, j));
  }
  for (j = 0; j < m; ++j)
    scanf("%" NAG_IFMT "", &isx[j]);

  for (j = 0; j < m; ++j)
    scanf("%lf", &e[j]);

  for (j = 0; j < m; ++j)
    scanf("%lf", &s[j]);

  /* nag_mv_z_scores (g03zac).
   * Standardize values of a data matrix
   */
  nag_mv_z_scores(n, m, x, tdx, nvar, isx, s, e, z, tdz, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_mv_z_scores (g03zac).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  printf("\nStandardized Values\n\n");
  for (i = 0; i < n; ++i) {
    for (j = 0; j < nvar; ++j)
      printf("%8.3f", Z(i, j));
    printf("\n");
  }
END:
  NAG_FREE(e);
  NAG_FREE(s);
  NAG_FREE(x);
  NAG_FREE(z);
  NAG_FREE(isx);
  return exit_status;
}