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

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

int main(void)
{
  Integer exit_status = 0, i, n;
  NagError fail;
  Nag_Smooth_Type smoother;
  double *rough0 = 0, *smooth0 = 0, *rough1 = 0, *smooth1 = 0, *y = 0;

  INIT_FAIL(fail);

  printf("nag_running_median_smoother (g10cac) Example Program Results\n");
  /* Skip heading in data file */
  scanf("%*[^\n]");
  scanf("%" NAG_IFMT "", &n);
  if (n >= 1) {
    if (!(rough0 = NAG_ALLOC(n, double)) ||
        !(smooth0 = NAG_ALLOC(n, double)) ||
        !(rough1 = NAG_ALLOC(n, double)) ||
        !(smooth1 = 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", &y[i]);

  /* nag_running_median_smoother (g10cac).
   * Compute smoothed data sequence using running median smoothers
   */
  /* Smooth sequence using 3RSSH,twice */
  smoother = Nag_3RSSH;
  nag_running_median_smoother(smoother, n, y, smooth1, rough1, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_running_median_smoother (g10cac).\n%s\n",
           fail.message);
    exit_status = 1;
    goto END;
  }

  /* Smooth sequence using 4253H,twice */
  smoother = Nag_4253H;
  nag_running_median_smoother(smoother, n, y, smooth0, rough0, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_running_median_smoother (g10cac).\n%s\n",
           fail.message);
    exit_status = 1;
    goto END;
  }

  /* Display results */
  printf("\n");
  printf("                      Using 3RSSH,twice         Using 4253H,twice\n");
  printf(" Index     Data      Smooth        Rough       Smooth       Rough\n");
  for (i = 0; i < n; ++i)
    printf("%4" NAG_IFMT " %10.1f %12.4f %12.4f %12.1f %12.1f\n", i, y[i],
           smooth1[i], rough1[i], smooth0[i], rough0[i]);
END:
  NAG_FREE(rough0);
  NAG_FREE(smooth0);
  NAG_FREE(rough1);
  NAG_FREE(smooth1);
  NAG_FREE(y);
  return exit_status;
}