/* nag_real_cholesky_skyline (f01mcc) Example Program.
 *
 * Copyright 2017 Numerical Algorithms Group.
 *
 * Mark 26.1, 2017.
 */

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

int main(void)
{
  Integer exit_status = 0, i, k, k1, k2, lal, n, *row = 0;
  NagError fail;
  double *a = 0, *al = 0, *d = 0;

  INIT_FAIL(fail);

  printf("nag_real_cholesky_skyline (f01mcc) Example Program Results\n");
  /* Skip heading in data file */
  scanf("%*[^\n]");
  scanf("%" NAG_IFMT "", &n);
  if (n >= 1) {
    if (!(row = NAG_ALLOC(n, Integer)) || !(d = NAG_ALLOC(n, double)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }
  }
  else {
    printf("Invalid n.\n");
    exit_status = 1;
    return exit_status;
  }
  lal = 0;
  for (i = 0; i < n; i++) {
    scanf("%" NAG_IFMT "", &row[i]);
    lal += row[i];
  }
  if (!(a = NAG_ALLOC(lal, double)) || !(al = NAG_ALLOC(lal, double)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }

  k2 = 0;
  for (i = 0; i < n; ++i) {
    k1 = k2;
    k2 = k2 + row[i];
    for (k = k1; k < k2; k++)
      scanf("%lf", &a[k]);
  }
  /* nag_real_cholesky_skyline (f01mcc).
   * LDL^T factorization of real symmetric positive-definite
   * variable-bandwidth (skyline) matrix
   */
  nag_real_cholesky_skyline(n, a, lal, row, al, d, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_real_cholesky_skyline (f01mcc).\n%s\n",
           fail.message);
    exit_status = 1;
    goto END;
  }
  printf("\n");
  printf("   i    d[i]   Row i of unit lower triangle\n\n");
  k2 = 0;
  for (i = 0; i < n; ++i) {
    k1 = k2;
    k2 = k2 + row[i];
    printf(" %3" NAG_IFMT "%8.3f", i, d[i]);
    for (k = k1; k < k2; k++)
      printf("%8.3f", al[k]);
    printf("\n");
  }
END:
  NAG_FREE(row);
  NAG_FREE(a);
  NAG_FREE(al);
  NAG_FREE(d);
  return exit_status;
}