/* nag_regsn_std_resid_influence (g02fac) 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>

#define SRES(I, J) sres[(I) *tdsres + J]
int main(void)
{
  Integer exit_status = 0, i, ip, j, n, nres, tdsres;
  double *h = 0, *res = 0, rms, *sres = 0;
  NagError fail;

  INIT_FAIL(fail);

  printf("nag_regsn_std_resid_influence (g02fac) Example Program Results\n");
  /* Skip heading in data file */
  scanf("%*[^\n]");
  scanf("%" NAG_IFMT " %" NAG_IFMT " %" NAG_IFMT " %lf", &n, &ip, &nres,
        &rms);
  if (nres <= n && n > ip + 1) {
    if (!(h = NAG_ALLOC(n, double)) ||
        !(res = NAG_ALLOC(n, double)) || !(sres = NAG_ALLOC(n * 4, double)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }
    tdsres = 4;
  }
  else {
    printf("Invalid nres or n or ip.\n");
    exit_status = 1;
    return exit_status;
  }
  for (i = 0; i < n; i++)
    scanf("%lf%lf", &res[i], &h[i]);
  /* nag_regsn_std_resid_influence (g02fac).
   * Calculates standardized residuals and influence
   * statistics
   */
  nag_regsn_std_resid_influence(n, ip, nres, res, h, rms, sres, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_regsn_std_resid_influence (g02fac).\n%s\n",
           fail.message);
    exit_status = 1;
    goto END;
  }
  printf("\n");
  printf("         Internally     Externally\n");
  printf(" Obs.    studentized    studentized    Cook's D    Atkinson's T\n");
  printf("          residuals      residuals\n\n");
  for (i = 0; i < nres; i++) {
    printf("%2" NAG_IFMT "", i + 1);
    for (j = 0; j < 4; j++)
      printf("%14.3f", SRES(i, j));
    printf("\n");
  }
END:
  NAG_FREE(h);
  NAG_FREE(res);
  NAG_FREE(sres);
  return exit_status;
}