/* nag_zgttrf (f07crc) 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 */
  Complex  *d = 0, *dl = 0, *du = 0, *du2 = 0;
  Integer  *ipiv = 0;

  /* Nag Types */
  NagError fail;

  INIT_FAIL(fail);

  printf("nag_zgttrf (f07crc) 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, Complex)) ||
      !(dl   = NAG_ALLOC(n-1, Complex)) ||
      !(du   = NAG_ALLOC(n-1, Complex)) ||
      !(du2  = NAG_ALLOC(n-2, Complex)) ||
      !(ipiv = NAG_ALLOC(n, Integer)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }

  /* Read the tridiagonal matrix A from data file */
  for (i = 0; i < n - 1; ++i) scanf(" ( %lf , %lf )", &du[i].re, &du[i].im);
  scanf("%*[^\n]");
  for (i = 0; i < n; ++i) scanf(" ( %lf , %lf )", &d[i].re, &d[i].im);
  scanf("%*[^\n]");
  for (i = 0; i < n - 1; ++i) scanf(" ( %lf , %lf )", &dl[i].re, &dl[i].im);
  scanf("%*[^\n]");

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

  /* Print details of the factorization */
  printf("Details of factorization (U)\n\n");

  printf("%17s%24s%22s\n", "Main diagonal", "First super-diagonal", 
         "Second super-diagonal");
  for (i = 0; i < n; ++i)
    {
      printf("(%8.4f, %8.4f)", d[i].re, d[i].im);
      if (i < n-1) printf(" (%8.4f, %8.4f)", du[i].re, du[i].im);
      if (i < n-2) printf(" (%8.4f, %8.4f)", du2[i].re, du2[i].im);
      printf("\n");
    }

  printf("\n Multipliers\n");
  for (i = 0; i < n - 1; ++i) printf("(%8.4f, %8.4f)\n", dl[i].re, dl[i].im);

  printf("\n Vector of interchanges\n");
  for (i = 0; i < n; ++i) printf("%7ld%s", ipiv[i], i%5 == 4?"\n":" ");
  printf("\n");
 END:
  NAG_FREE(d);
  NAG_FREE(dl);
  NAG_FREE(du);
  NAG_FREE(du2);
  NAG_FREE(ipiv);

  return exit_status;
}