/* nag_zptcon (f07juc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 23, 2011.
 *
 * UNFINISHED - replace commented out climp calls
 */

#include <math.h>
#include <nag.h>
#include <nagf07.h>
#include <nag_stdlib.h>
#include <nagx02.h>

int main(void)
{
#define CABS(e) sqrt(e.re * e.re + e.im * e.im)


  /* Scalars */
  double   anorm, rcond;
  Integer  exit_status = 0, i, n;

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

  /* Nag Types */
  NagError fail;

  INIT_FAIL(fail);

  printf("nag_zptcon (f07juc) 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 (!(e = NAG_ALLOC(n-1, Complex)) ||
      !(d = NAG_ALLOC(n, 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 , %lf )", &e[i].re, &e[i].im);
  scanf("%*[^\n]");

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

  /* Factorize A using nag_zpttrf (f07jrc). */
  nag_zpttrf(n, d, e, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_zpttrf (f07jrc).\n%s\n", fail.message);
      exit_status = 1;
      goto END;
    }

  /* Estimate the condition number of A using nag_zptcon (f07juc). */
  nag_zptcon(n, d, e, anorm, &rcond, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_zptcon (f07juc).\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(e);
  NAG_FREE(d);

  return exit_status;
}