/* nag_regsn_quant_linear_iid (g02qfc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 23, 2011.
 */
/* Pre-processor includes */
#include <stdio.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <nagg02.h>

#define B(i,j) b[(j) * m + i]
#define BU(i,j) bu[(j) * m + i]
#define BL(i,j) bl[(j) * m + i]
#define X(i,j) x[(i) * m + j]

int main(void)
{
  /* Integer scalar and array declarations */
  Integer i, j, l, m, n, ntau;
  Integer *info = 0;
  Integer exit_status = 0;

  /* NAG structures */
  NagError fail;

  /* Double scalar and array declarations */
  double df;
  double *b = 0, *bl = 0, *bu = 0, *tau = 0, *x = 0, *y = 0;

  /* Initialise the error structure */
  INIT_FAIL(fail);

  printf("nag_regsn_quant_linear_iid (g02qfc) Example Program Results\n\n");

  /* Skip heading in data file */
  scanf("%*[^\n] ");

  /* Read in the problem size */
  scanf("%ld%ld%ld%*[^\n] ",&n,&m,&ntau);

  /* Allocate memory for input arrays */
  if (!(y = NAG_ALLOC(n, double)) ||
      !(tau = NAG_ALLOC(ntau, double)) ||
      !(x = NAG_ALLOC(n*m, double)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }

  /* Read in the data */
  for (i = 0; i < n; i++) {
    for (j = 0; j < m; j++)
      scanf("%lf", &X(i,j));
    scanf("%lf",&y[i]);
  }
  scanf("%*[^\n] ");

  /* Read in the quantiles required */
  for (l = 0; l < ntau; l++) {
    scanf("%lf",&tau[l]);
  }
  scanf("%*[^\n] ");

  /* Allocate memory for output arrays */
  if (!(b = NAG_ALLOC(m*ntau, double)) ||
      !(info = NAG_ALLOC(ntau, Integer)) ||
      !(bl = NAG_ALLOC(m*ntau, double)) ||
      !(bu = NAG_ALLOC(m*ntau, double)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }

  /* nag_regsn_quant_linear_iid (g02qfc).Quantile linear regression, simple
     interface, independent, identically distributed (IID) errors */
  nag_regsn_quant_linear_iid(n,m,x,y,ntau,tau,&df,b,bl,bu,info,&fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_regsn_quant_linear_iid (g02qfc).\n%s\n",
            fail.message);
    if (fail.code == NW_POTENTIAL_PROBLEM) {
      printf("Additional error information: ");
      for (i = 0; i < ntau; i++)
        printf("%ld ",info[i]);
      printf("\n");
    } else {
      exit_status = 1;
      goto END;
    }
  }

  /* Display the parameter estimates */
  for (l = 0; l < ntau; l++) {
    printf(" Quantile: %6.3f\n\n", tau[l]);
    printf("         Lower   Parameter   Upper\n");
    printf("         Limit   Estimate    Limit\n");
    for (j = 0; j < m; j++) {
      printf(" %3ld   %7.3f   %7.3f   %7.3f\n", j + 1, BL(j,l), B(j,l),
              BU(j,l));
    }
    printf("\n\n");
  }

 END:

  NAG_FREE(info);
  NAG_FREE(b);
  NAG_FREE(bl);
  NAG_FREE(bu);
  NAG_FREE(tau);
  NAG_FREE(x);
  NAG_FREE(y);

  return(exit_status);
}