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

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

int main(void)
{
  Integer exit_status = 0, i, n;
  Nag_SumSquare mean;
  Nag_Boolean weight;
  char nag_enum_arg[40];
  double a, b, df, err_a, err_b, rsq, rss;
  double *wt = 0, *wtptr, *x = 0, *y = 0;
  NagError fail;

  INIT_FAIL(fail);

  printf("nag_simple_linear_regression (g02cac) Example Program Results\n");
  /* Skip heading in data file */
  scanf("%*[^\n]");
  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);
  scanf("%" NAG_IFMT "", &n);
  if (n >= (mean == Nag_AboutMean ? 2 : 1)) {
    if (!(x = NAG_ALLOC(n, double)) ||
        !(y = NAG_ALLOC(n, double)) || !(wt = 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) {
    wtptr = wt;
    for (i = 0; i < n; ++i)
      scanf("%lf%lf%lf", &x[i], &y[i], &wt[i]);
  }
  else {
    wtptr = (double *) 0;
    for (i = 0; i < n; ++i)
      scanf("%lf%lf", &x[i], &y[i]);
  }

  /* nag_simple_linear_regression (g02cac).
   * Simple linear regression with or without a constant term,
   * data may be weighted
   */
  nag_simple_linear_regression(mean, n, x, y, wtptr, &a, &b, &err_a, &err_b,
                               &rsq, &rss, &df, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_simple_linear_regression (g02cac).\n%s\n",
           fail.message);
    exit_status = 1;
    goto END;
  }

  if (mean == Nag_AboutMean) {
    printf("\nRegression constant a = %6.4f\n\n", a);
    printf("Standard error of the regression constant a = %6.4f\n\n", err_a);
  }

  printf("Regression coefficient b = %6.4f\n\n", b);
  printf("Standard error of the regression coefficient b = %6.4f\n\n", err_b);

  printf("The regression coefficient of determination = %6.4f\n\n", rsq);
  printf("The sum of squares of the residuals about the "
         "regression = %6.4f\n\n", rss);
  printf("Number of degrees of freedom about the "
         "regression = %6.4f\n\n", df);

END:
  NAG_FREE(x);
  NAG_FREE(y);
  NAG_FREE(wt);

  return exit_status;
}