/* nag_zgbbrd (f08lsc) Example Program.
 *
 * NAGPRODCODE Version.
 *
 * Copyright 2016 Numerical Algorithms Group.
 *
 * Mark 26, 2016.
 */

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

int main(void)
{
  /* Scalars */
  Integer i, j, kl, ku, m, n, ncc, pdab, pdc, pdq, pdpt;
  Integer d_len, e_len;
  Integer exit_status = 0;
  NagError fail;
  Nag_OrderType order;
  /* Arrays */
  Complex *ab = 0, *c = 0, *pt = 0, *q = 0;
  double *d = 0, *e = 0;

#ifdef NAG_COLUMN_MAJOR
#define AB(I, J) ab[(J - 1) * pdab + ku + I - J]
  order = Nag_ColMajor;
#else
#define AB(I, J) ab[(I - 1) * pdab + kl + J - I]
  order = Nag_RowMajor;
#endif

  INIT_FAIL(fail);

  printf("nag_zgbbrd (f08lsc) Example Program Results\n");

  /* Skip heading in data file */
  scanf("%*[^\n] ");
  scanf("%" NAG_IFMT "%" NAG_IFMT "%" NAG_IFMT "%" NAG_IFMT "%" NAG_IFMT
        "%*[^\n] ", &m, &n, &kl, &ku, &ncc);
#ifdef NAG_COLUMN_MAJOR
  pdab = kl + ku + 1;
  pdq = m;
  pdpt = n;
  pdc = m;
#else
  pdab = kl + ku + 1;
  pdq = m;
  pdpt = n;
  pdc = MAX(1, ncc);
#endif
  d_len = MIN(m, n);
  e_len = MIN(m, n) - 1;

  /* Allocate memory */
  if (!(ab = NAG_ALLOC((kl + ku + 1) * m, Complex)) ||
      !(c = NAG_ALLOC(m * MAX(1, ncc), Complex)) ||
      !(d = NAG_ALLOC(d_len, double)) ||
      !(e = NAG_ALLOC(e_len, double)) ||
      !(pt = NAG_ALLOC(n * n, Complex)) || !(q = NAG_ALLOC(m * m, Complex)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }

  /* Read A from data file */
  for (i = 1; i <= m; ++i) {
    for (j = MAX(1, i - kl); j <= MIN(n, i + ku); ++j)
      scanf(" ( %lf , %lf )", &AB(i, j).re, &AB(i, j).im);
  }
  scanf("%*[^\n] ");
  /* Reduce A to bidiagonal form */
  /* nag_zgbbrd (f08lsc).
   * Reduction of complex rectangular band matrix to upper
   * bidiagonal form
   */
  nag_zgbbrd(order, Nag_DoNotForm, m, n, ncc, kl, ku, ab,
             pdab, d, e, q, pdq, pt, pdpt, c, pdc, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_zgbbrd (f08lsc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  /* Print bidiagonal form */
  printf("\nDiagonal\n");
  for (i = 1; i <= MIN(m, n); ++i)
    printf("%9.4f%s", d[i - 1], i % 8 == 0 ? "\n" : " ");
  if (m >= n)
    printf("\nSuperdiagonal\n");
  else
    printf("\nSubdiagonal\n");
  for (i = 1; i <= MIN(m, n) - 1; ++i)
    printf("%9.4f%s", e[i - 1], i % 8 == 0 ? "\n" : " ");
  printf("\n");

END:
  NAG_FREE(ab);
  NAG_FREE(c);
  NAG_FREE(d);
  NAG_FREE(e);
  NAG_FREE(pt);
  NAG_FREE(q);

  return exit_status;
}