/* nag_det_real_band_sym (f03bhc) Example Program.
 *
 * Copyright 2017 Numerical Algorithms Group.
 *
 * Mark 26.1, 2017.
 */
#include <math.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <nagf03.h>
#include <nagf07.h>
#include <nagx04.h>

int main(void)
{
  /* Scalars */
  Integer exit_status = 0;
  Integer i, id, j, kd, kl, ku, k, n, pdab;
  double d;
  /* Arrays */
  char nag_enum_arg[40];
  double *ab = 0;
  /* NAG types */
  NagError fail;
  Nag_UploType uplo;
  Nag_OrderType order;

  printf("nag_det_real_band_sym (f03bhc) Example Program Results\n\n");

  /* Skip heading in data file  */
  scanf("%*[^\n] ");
  scanf("%" NAG_IFMT "%" NAG_IFMT "%*[^\n]", &n, &kd);
  k = kd + 1;
  pdab = k;

  if (!(ab = NAG_ALLOC(k * n, double)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }
  scanf("%39s %*[^\n] ", nag_enum_arg);
  uplo = (Nag_UploType) nag_enum_name_to_value(nag_enum_arg);

  /* Define matrix element A_ij in terms of elements of array ab[] */
#ifdef NAG_COLUMN_MAJOR
#define AB_UPPER(I, J) ab[(J-1)*pdab + k + I - J - 1]
#define AB_LOWER(I, J) ab[(J-1)*pdab + I - J]
  order = Nag_ColMajor;
#else
#define AB_UPPER(I, J) ab[(I-1)*pdab + J - I]
#define AB_LOWER(I, J) ab[(I-1)*pdab + k + J - I - 1]
  order = Nag_RowMajor;
#endif
  if (uplo == Nag_Upper) {
    /* Read in upper triangular banded matrix  */
    ku = kd;
    kl = 0;
    for (i = 1; i <= n; i++)
      for (j = i; j <= MIN(i + kd, n); j++)
        scanf("%lf", &AB_UPPER(i, j));
    scanf("%*[^\n] ");
  }
  else if (uplo == Nag_Lower) {
    /* Read in lower triangular banded matrix  */
    ku = 0;
    kl = kd;
    for (i = 1; i <= n; i++)
      for (j = MAX(1, i - kd); j <= i; j++)
        scanf("%lf", &AB_LOWER(i, j));
    scanf("%*[^\n] ");
  }
  else {
    printf("Illegal value read for uplo\n");
    exit_status = -4;
    goto END;
  }

  INIT_FAIL(fail);
  /* Factorize A using nag_dpbtrf (f07hdc)
   * Cholesky factorization of real symmetric positive definite band matrix
   */
  nag_dpbtrf(order, uplo, n, kd, ab, pdab, &fail);
  if (fail.code != NE_NOERROR) {
    printf("%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  /* nag_band_real_mat_print (x04cec)
   * Print real packed banded matrix (easy-to-use)
   */
  fflush(stdout);
  nag_band_real_mat_print(order, n, n, kl, ku, ab, pdab,
                          "Array ab after factorization", NULL, &fail);
  if (fail.code != NE_NOERROR) {
    printf("%s\n", fail.message);
    exit_status = 2;
    goto END;
  }

  /* nag_det_real_band_sym (f03bhc)
   * Determinant of real symmetric positive definite banded matrix
   */
  nag_det_real_band_sym(order, uplo, n, kd, ab, pdab, &d, &id, &fail);
  if (fail.code != NE_NOERROR) {
    printf("%s\n", fail.message);
    exit_status = 3;
    goto END;
  }

  printf("\nd = %12.5f  id = %10" NAG_IFMT "\n", d, id);
  printf("Value of determinant = %13.5e\n", d * pow(2.0, id));

END:
  NAG_FREE(ab);

  return exit_status;
}