/* nag_robust_m_estim_1var (g07dbc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 4, 1996.
 *
 * Mark 6 revised, 2000.
 * Mark 8 revised, 2004.
 */

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

int main(void)
{
  Integer           exit_status = 0, i, maxit, n, nit;
  Nag_SigmaSimulEst sigma_est;
  char              sigma_est_str[40];
  double            c, dchi, h1, h2, h3, *rs = 0, sigma, sigsav, *sorted_x = 0,
                    thesav, theta;
  double            tol, *x = 0;
  NagError          fail;

  INIT_FAIL(fail);

  printf(
          "nag_robust_m_estim_1var (g07dbc) Example Program Results\n\n");

  /* Skip heading in data file */
  scanf("%*[^\n]\n");
  scanf("%ld %*[^\n]\n", &n);
  if (n > 1)
    {
      if (!(x = NAG_ALLOC(n, double)) ||
          !(rs = NAG_ALLOC(n, double)) ||
          !(sorted_x = 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 = 1; i <= n; ++i)
    scanf("%lf", &x[i - 1]);
  scanf("%*[^\n]\n");
  scanf("%lf %lf %lf %lf %ld %*[^\n]\n", &h1, &h2, &h3, &dchi,
         &maxit);
  printf("%25sInput parameters     Output parameters\n", "");
  printf(
          "   sigma_est         sigma    theta   tol       sigma   theta\n\n");
  while ((scanf("%39s %lf %lf %lf%*[^\n]", sigma_est_str, &sigma, &theta,
                &tol)) != EOF)
    {
      /* nag_enum_name_to_value (x04nac).
       * Converts NAG enum member name to value
       */
      sigma_est = (Nag_SigmaSimulEst) nag_enum_name_to_value(sigma_est_str);
      sigsav = sigma;
      thesav = theta;
      c = 0.0;

      /* nag_robust_m_estim_1var (g07dbc).
       * Robust estimation, M-estimates for location and scale
       * parameters, standard weight functions
       */
      nag_robust_m_estim_1var(sigma_est, n, x, Nag_HampelFun, c, h1, h2, h3,
                              dchi, &theta, &sigma, maxit, tol, rs, &nit,
                              sorted_x, &fail);
      if (fail.code != NE_NOERROR)
        {
          printf("Error from nag_robust_m_estim_1var (g07dbc).\n%s\n",
                  fail.message);
          exit_status = 1;
          goto END;
        }

      printf("%s    %8.4f %8.4f %7.4f %9.4f %8.4f\n", sigma_est_str,
              sigsav, thesav, tol, sigma, theta);
    }

 END:
  NAG_FREE(x);
  NAG_FREE(rs);
  NAG_FREE(sorted_x);

  return exit_status;
}