/* nag_dpttrf (f07jdc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 23, 2011.
 */

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

int main(void)
{

  /* Scalars */
  Integer  exit_status = 0, i, n;

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

  /* Nag Types */
  NagError fail;

  INIT_FAIL(fail);

  printf("nag_dpttrf (f07jdc) 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]");

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

  /* Print details of the factorization */
  printf("Details of factorization\n\n");
  printf(" The diagonal elements of D\n");
  for (i = 0; i < n; ++i) printf("%9.4f%s", d[i], i%8 == 7?"\n":" ");

  printf("\n\n Sub-diagonal elements of the Cholesky factor L\n");
  for (i = 0; i < n-1; ++i) printf("%9.4f%s", e[i], i%8 == 7?"\n":" ");
  printf("\n");

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

  return exit_status;
}