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

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

int main(void)
{
  Integer exit_status = 0, i, *iwrk = 0, n, nord;
  NagError fail;
  char weight[2];
  double rss, *weights = 0, *wtord = 0, *wtptr, *x = 0, *xord = 0, *y = 0;
  double *yord = 0;

  INIT_FAIL(fail);

  printf("nag_order_data (g10zac) Example Program Results\n");

  /* Skip heading in data file */
  scanf("%*[^\n]");
  scanf("%" NAG_IFMT "", &n);
  if (!(x = NAG_ALLOC(n, double))
      || !(y = NAG_ALLOC(n, double))
      || !(weights = NAG_ALLOC(n, double))
      || !(xord = NAG_ALLOC(n, double))
      || !(yord = NAG_ALLOC(n, double))
      || !(wtord = NAG_ALLOC(n, double))
      || !(iwrk = NAG_ALLOC(n, Integer)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }
  scanf(" %1s ", weight);
  for (i = 1; i <= n; ++i)
    scanf("%lf %lf", &x[i - 1], &y[i - 1]);
  if (*weight == 'W')
    wtptr = weights;
  else
    wtptr = 0;

  /* nag_order_data (g10zac).
   * Reorder data to give ordered distinct observations
   */
  nag_order_data(n, x, y, wtptr, &nord, xord, yord, wtord, &rss, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_order_data (g10zac).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  /* Print results */
  printf("\n");
  printf("%s%6" NAG_IFMT "\n", "Number of distinct observations = ", nord);
  printf("%s%13.5f\n", "Residual sum of squares = ", rss);
  printf("\n");
  printf("              X                 Y              WEIGHTS\n");
  for (i = 1; i <= nord; ++i)
    printf("     %13.5f     %13.5f     %13.5f\n", xord[i - 1],
           yord[i - 1], wtord[i - 1]);
END:
  NAG_FREE(x);
  NAG_FREE(y);
  NAG_FREE(weights);
  NAG_FREE(xord);
  NAG_FREE(yord);
  NAG_FREE(wtord);
  NAG_FREE(iwrk);
  return exit_status;
}