/* nag_dptcon (f07jgc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 23, 2011.
 *
 * UNFINISHED - replace commented out climp calls
 */
#include <stdio.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <nagf07.h>
#include <nagx02.h>

int main(void)
{
  /* Scalars */
  double   anorm, rcond;
  Integer  exit_status = 0, i, n;

  /* Arrays */
  double   *d = 0, *e = 0;

  /* Nag Types */
  NagError fail;

  INIT_FAIL(fail);

  printf("nag_dptcon (f07jgc) Example Program Results\n\n");
  /* Skip heading in data file */
  scanf("%*[^\n]");
  scanf("%ld%*[^\n]", &n);
  if (n < 0)
    {
      printf("Invalid n\n");
      exit_status = 1;
      goto END;
    }
  /* Allocate memory */
  if (!(d = NAG_ALLOC(n, double)) ||
      !(e = NAG_ALLOC(n-1, double)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }

  /* Read the lower bidiagonal part of the tridiagonal matrix A from */
  /* data file */
  for (i = 0; i < n; ++i) scanf("%lf", &d[i]);
  scanf("%*[^\n]");
  for (i = 0; i < n - 1; ++i) scanf("%lf", &e[i]);
  scanf("%*[^\n]");

  /* Compute the 1-norm of A */
  anorm = MAX(ABS(d[0])+ABS(e[0]), ABS(e[n-2])+ABS(d[n-1]));
  for (i = 1; i < n-1; ++i) 
    anorm = MAX(anorm, ABS(d[i])+ABS(e[i])+ABS(e[i-1]));

  /* Factorize the tridiagonal matrix A using nag_dgbsv (f07bac). */
  nag_dpttrf(n, d, e, &fail);

  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_dgbsv (f07bac).\n%s\n", fail.message);
      exit_status = 1;
      goto END;
    }

  /* Estimate the condition number of A using nag_dptcon (f07jgc). */
  nag_dptcon(n, d, e, anorm, &rcond, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_dptcon (f07jgc).\n%s\n", fail.message);
      exit_status = 1;
      goto END;
    }

  /* Print the estimated condition number */
  if (rcond >= nag_machine_precision)
    printf("Estimate of condition number = %11.2e\n\n", 1.0/rcond);
  else
    printf("A is singular to working precision. RCOND = %11.2e\n\n", rcond);

 END:
  NAG_FREE(d);
  NAG_FREE(e);

  return exit_status;
}