/* nag_linf_fit (e02gcc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 7, 2001.
 */

#include <stdio.h>
#include <math.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <nage02.h>

int main(void)
{
  /* Scalars */
  double        relerr, resmax, t, tol;
  Integer       exit_status, i, irank, iter, m, n, pda;
  NagError      fail;
  Nag_OrderType order;

  /* Arrays */
  double        *a = 0, *b = 0, *x = 0;

#ifdef NAG_COLUMN_MAJOR
#define A(I, J) a[(J-1)*pda + I - 1]
  order = Nag_ColMajor;
#else
#define A(I, J) a[(I-1)*pda + J - 1]
  order = Nag_RowMajor;
#endif

  INIT_FAIL(fail);

  exit_status = 0;
  printf("nag_linf_fit (e02gcc) Example Program Results\n");

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

  n = 3;
  scanf("%ld%*[^\n] ", &m);
  if (m > 0)
    {
      /* Allocate memory */
      if (!(a = NAG_ALLOC((n+3)*(m+1), double)) ||
          !(b = NAG_ALLOC(m, double)) ||
          !(x = NAG_ALLOC(n, double)))
        {
          printf("Allocation failure\n");
          exit_status = -1;
          goto END;
        }

      if (order == Nag_ColMajor)
        pda = n + 3;
      else
        pda = m + 1;

      for (i = 1; i <= m; ++i)
        {
          scanf("%lf%lf%*[^\n] ", &t, &b[i-1]);
          A(1, i) = exp(t);
          A(2, i) = exp(-t);
          A(3, i) = 1.0;
        }
      tol = 0.0;
      relerr = 0.0;
      /* nag_linf_fit (e02gcc).
       * L_infinity-approximation by general linear function
       */
      nag_linf_fit(order, m, n, a, b, tol, &relerr, x, &resmax, &irank, &iter,
                   &fail);
      if (fail.code != NE_NOERROR)
        {
          printf("Error from nag_linf_fit (e02gcc).\n%s\n",
                  fail.message);
          exit_status = 1;
          goto END;
        }
      else
        {
          printf("\n");
          printf("resmax = %11.2e  Rank = %5ld  Iterations ="
                  " %5ld\n", resmax, irank, iter);

          printf("\n");
          printf("Solution\n");

          for (i = 1; i <= n; ++i)
            printf("%10.4f", x[i-1]);
          printf("\n");
        }
    }
 END:
  NAG_FREE(a);
  NAG_FREE(b);
  NAG_FREE(x);

  return exit_status;
}