/* nag_ken_spe_corr_coeff (g02brc) 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 CORR(I, J) corr[(I) *tdcorr + J]

int main(void)
{
  Integer exit_status = 0, i, j, m, n, *sobs = 0, *sobsptr, *svar = 0;
  Integer *svarptr;
  Integer tdcorr, tdx;
  NagError fail;
  char s, w;
  double *corr = 0, *x = 0;

  INIT_FAIL(fail);

  printf("nag_ken_spe_corr_coeff (g02brc) Example Program Results\n");

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

  /* Read data */
  scanf("%" NAG_IFMT "%" NAG_IFMT "\n", &m, &n);
  if (m >= 2 && n >= 2) {
    if (!(x = NAG_ALLOC(n * m, double)) ||
        !(corr = NAG_ALLOC(m * m, double)) ||
        !(svar = NAG_ALLOC(m, Integer)) || !(sobs = NAG_ALLOC(n, Integer)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }
    tdx = m;
    tdcorr = m;
  }
  else {
    printf("Invalid m or n.\n");
    exit_status = 1;
    return exit_status;
  }
  for (i = 0; i < n; i++)
    for (j = 0; j < m; j++)
      scanf("%lf", &X(i, j));

  /* Read flag specifying if svar is to be supplied */
  scanf(" %c", &s);
  if (s == 'S' || s == 's') {
    /* Assign pointer to svar and read in values for svar */
    svarptr = svar;
    for (i = 0; i < m; i++)
      scanf("%" NAG_IFMT "", &svar[i]);
  }
  else {
    /* Assign pointer to NULL and discard rest of line */
    svarptr = (Integer *) 0;
    /* skip rest of line */
    scanf(" %*[^\n]");
  }

  /* Read flag specifying if sobs is to be supllied */
  scanf(" %c", &w);
  if (w == 'W' || w == 'w') {
    /* Assign pointer to sobs and read in values for sobs */
    sobsptr = sobs;
    for (i = 0; i < n; i++)
      scanf("%" NAG_IFMT "", &sobs[i]);
  }
  else {
    /* Assign pointer to NULL and discard rest of line */
    sobsptr = (Integer *) 0;
    /* skip rest of line */
    scanf(" %*[^\n]");
  }

  /* Calculate the Kendall and Spearman coefficients */
  /* nag_ken_spe_corr_coeff (g02brc).
   * Kendall and/or Spearman non-parametric rank correlation
   * coefficients, allows variables and observations to be
   * selectively disregarded
   */
  nag_ken_spe_corr_coeff(n, m, x, tdx, svarptr, sobsptr, corr, tdcorr, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_ken_spe_corr_coeff (g02brc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  printf("\nCorrelation coefficients:\n\n");
  for (i = 0; i < m; i++) {
    for (j = 0; j < m; j++)
      printf("%8.5f ", CORR(i, j));
    printf("\n");
  }
END:
  NAG_FREE(x);
  NAG_FREE(corr);
  NAG_FREE(svar);
  NAG_FREE(sobs);
  return exit_status;
}