/* nag_outlier_peirce (g07gac) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 23, 2011.
 */

/* Pre-processor includes */
#include <stdio.h>
#include <math.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <nagg07.h>

int main(void)
{

  /* Integer scalar and array declarations */
  Integer i, n, niout, p, exit_status, ldiff;
  Integer *iout = 0;

  /* NAG structures */
  NagError fail;

  /* Double scalar and array declarations */
  double *y = 0, *diff = 0, *llamb = 0;

  /* Let the routine calculate the mean and variance from the supplied data */
  double mean = 0.0;
  double var = 0.0;

  exit_status = 0;

  /* Initialise the error structure */
  INIT_FAIL(fail);


  printf("nag_outlier_peirce (g07gac) Example Program Results\n");

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

  /* Read in the problem size */
  scanf("%ld %ld %ld%*[^\n] ", &n, &p, &ldiff);

  if (!(y = NAG_ALLOC(n, double)) ||
      !(diff = NAG_ALLOC(ldiff,double)) ||
      !(llamb = NAG_ALLOC(ldiff,double)) ||
      !(iout = NAG_ALLOC(n, Integer)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }

  /* Read in the data */
  for (i=0; i<n; i++)
    scanf("%lf%*[^\n] ", &y[i]);

  /* Use nag_outlier_peirce (g07gac) to get a list of potential outliers */
  nag_outlier_peirce(n, p, y, mean, var, iout, &niout, ldiff, diff, llamb,
                     &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_outlier_peirce (g07gac).\n%s\n",
            fail.message);
    exit_status = 1;
    goto END;
  }

  /* Display the potential outliers */
  printf("\n");
  printf(" Number of potential outliers: %ld\n", niout);
  if (ldiff > 0) {
    printf(" %5s  %5s %8s   %8s    %8s\n", "No.", "Index", "Value",
            "Diff", "ln(lambda^2)");
  } else {
    printf(" %5s  %5s %8s\n", "No.", "Index", "Value");
  }
  for (i = 0; i < niout; i++)
    if (i < ldiff) {
      printf("%5ld %5ld %10.2f %10.2f %10.2f\n",i+1,
              iout[i], y[iout[i] - 1], diff[i], llamb[i]);
    } else {
      printf("%5ld %5ld %10.2f\n",i+1, iout[i],
              y[iout[i] - 1]);
    }

  END:
  NAG_FREE(y);
  NAG_FREE(diff);
  NAG_FREE(llamb);
  NAG_FREE(iout);

  return exit_status;
}