/* nag_median_1var (g07dac) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 1, 1990.
 *
 * Mark 3 revised, 1994.
 * Mark 8 revised, 2004.
 */

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

int main(void)
{
  Integer  exit_status = 0, i, n;
  NagError fail;
  double   *x = 0, xmd, xme, xsd, *y = 0;

  INIT_FAIL(fail);

  printf("nag_median_1var (g07dac) Example Program Results\n");
  /* Skip heading in data file */
  scanf("%*[^\n]");
  scanf("%ld", &n);
  if (n > 1)
    {
      if (!(x = NAG_ALLOC(n, double)) ||
          !(y = NAG_ALLOC(n, double))
          )
        {
          printf("Allocation failure\n");
          exit_status = -1;
          goto END;
        }
    }
  else
    {
      printf("Invalid n.\n");
      exit_status = 1;
      return exit_status;
    }
  for (i = 0; i < n; ++i)
    scanf("%lf", &x[i]);
  /* nag_median_1var (g07dac).
   * Robust estimation, median, median absolute deviation,
   * robust standard deviation
   */
  nag_median_1var(n, x, y, &xme, &xmd, &xsd, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_median_1var (g07dac).\n%s\n",
              fail.message);
      exit_status = 1;
      goto END;
    }

  printf("Output y:\n");
  for (i = 0; i < n; ++i)
    printf("%6.3f%s", y[i], (i%11 == 10 || i == n-1)?"\n":" ");
  printf("\nxme = %6.3f, xmd = %6.3f, xsd = %6.3f\n", xme, xmd, xsd);
 END:
  NAG_FREE(x);
  NAG_FREE(y);
  return exit_status;
}