/* nag_regress_confid_interval (g02cbc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 3, 1992.
 * Mark 8 revised, 2004.
 */

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

int main(void)
{
  Integer       exit_status = 0, i, n;
  double        clm, clp;
  double        *h = 0, *res = 0, rms, *wt = 0, *x = 0, *y = 0, *yhat = 0;
  double        *yl = 0, *yml = 0, *ymu = 0, *yu = 0;
  char          nag_enum_arg[40];
  Nag_SumSquare mean;
  Nag_Boolean   weight;
  NagError      fail;

  INIT_FAIL(fail);

  printf(
          "nag_regress_confid_interval (g02cbc) Example Program Results\n");
  /* Skip heading in data file */
  scanf("%*[^\n]");
  scanf("%ld\n", &n);
  scanf("%lf%lf\n", &clm, &clp);
  scanf(" %39s", nag_enum_arg);
  /* nag_enum_name_to_value (x04nac).
   * Converts NAG enum member name to value
   */
  mean = (Nag_SumSquare) nag_enum_name_to_value(nag_enum_arg);
  scanf(" %39s", nag_enum_arg);
  weight = (Nag_Boolean) nag_enum_name_to_value(nag_enum_arg);
  if (n >= (mean == Nag_AboutMean?2:1))
    {
      if (!(x = NAG_ALLOC(n, double)) ||
          !(y = NAG_ALLOC(n, double)) ||
          !(wt = NAG_ALLOC(n, double)) ||
          !(yhat = NAG_ALLOC(n, double)) ||
          !(yml = NAG_ALLOC(n, double)) ||
          !(ymu = NAG_ALLOC(n, double)) ||
          !(yl = NAG_ALLOC(n, double)) ||
          !(yu = NAG_ALLOC(n, double)) ||
          !(h = NAG_ALLOC(n, double)) ||
          !(res = NAG_ALLOC(n, double))
          )
        {
          printf("Allocation failure\n");
          exit_status = -1;
          goto END;
        }
    }
  else
    {
      printf("Invalid n.\n");
      exit_status = 1;
      return exit_status;
    }
  if (weight)
    for (i = 0; i < n; i++)
      scanf("%lf%lf%lf\n", &x[i], &y[i], &wt[i]);
  else
    for (i = 0; i < n; ++i)
      scanf("%lf%lf\n", &x[i], &y[i]);

  /* nag_regress_confid_interval (g02cbc).
   * Simple linear regression confidence intervals for the
   * regression line and individual points
   */
  nag_regress_confid_interval(mean, n, x, y, wt, clm, clp, yhat, yml, ymu, yl,
                              yu, h, res, &rms, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_regress_confid_interval (g02cbc).\n%s\n",
              fail.message);
      exit_status = 1;
      goto END;
    }

  printf("\ni       yhat[i]    yml[i]    ymu[i]      yl[i]      yu[i]"
          " \n\n");
  for (i = 0; i < n; ++i)
    {
      printf("%ld %10.2f %10.2f", i, yhat[i], yml[i]);
      printf("%10.2f  %10.2f %10.2f\n", ymu[i], yl[i], yu[i]);
    }

 END:
  NAG_FREE(x);
  NAG_FREE(y);
  NAG_FREE(wt);
  NAG_FREE(yhat);
  NAG_FREE(yml);
  NAG_FREE(ymu);
  NAG_FREE(yl);
  NAG_FREE(yu);
  NAG_FREE(h);
  NAG_FREE(res);

  return exit_status;
}