/* nag_dstegr (f08jlc) 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>
#include <nagx04.h>

int main(void)
{
  /* Scalars */
  double vl = 0.0, vu = 0.0;
  Integer i, j, m, n, pdz;
  Integer exit_status = 0;
  /* Arrays */
  char nag_enum_arg[40];
  double *d = 0, *e = 0, *w = 0, *z = 0;
  Integer *isuppz = 0;
  /* Nag Types */
  Nag_OrderType order;
  Nag_JobType job;
  Nag_RangeType range;
  NagError fail;

#ifdef NAG_COLUMN_MAJOR
#define Z(I, J) z[(J - 1) * pdz + I - 1]
  order = Nag_ColMajor;
#else
#define Z(I, J) z[(I - 1) * pdz + J - 1]
  order = Nag_RowMajor;
#endif

  INIT_FAIL(fail);

  printf("nag_dstegr (f08jlc) Example Program Results\n\n");

  /* Skip heading in data file */
  scanf("%*[^\n]");
  scanf("%" NAG_IFMT "%*[^\n]", &n);
  m = n;

  /* Read job and range */
  scanf("%39s%*[^\n]", nag_enum_arg);
  /* nag_enum_name_to_value (x04nac).
   * Converts NAG enum member name to value.
   */
  job = (Nag_JobType) nag_enum_name_to_value(nag_enum_arg);
  scanf("%39s%*[^\n]", nag_enum_arg);
  range = (Nag_RangeType) nag_enum_name_to_value(nag_enum_arg);

#ifdef NAG_COLUMN_MAJOR
  pdz = n;
#else
  pdz = m;
#endif

  /* Allocate memory */
  if (!(d = NAG_ALLOC(n, double)) ||
      !(e = NAG_ALLOC(n, double)) ||
      !(w = NAG_ALLOC(n, double)) ||
      !(z = NAG_ALLOC(n * m, double)) ||
      !(isuppz = NAG_ALLOC(2 * m, Integer)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }

  /* Read the symmetric tridiagonal matrix T from data file, first
   * the diagonal elements, then the off diagonal elements.
   */
  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]");

  /* nag_dstegr (f08jlc).
   * Calculate all the eigenvalues of T.
   */
  nag_dstegr(order, job, range, n, d, e, vl, vu, 0, 0, &m, w, z,
             pdz, isuppz, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_dstegr (f08jlc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  /* Normalize the eigenvectors */
  for (j = 1; j <= m; j++)
    for (i = n; i >= 1; i--)
      Z(i, j) = Z(i, j) / Z(1, j);

  /* Print eigenvalues and eigenvectors */
  printf(" %s\n", "Eigenvalues");
  for (i = 0; i < m; ++i)
    printf("%8.4f%s", w[i], (i + 1) % 8 == 0 ? "\n" : " ");
  printf("\n\n");

  /* nag_gen_real_mat_print (x04cac).
   * Print eigenvectors.
   */
  fflush(stdout);
  nag_gen_real_mat_print(order, Nag_GeneralMatrix, Nag_NonUnitDiag, n, m,
                         z, pdz, "Eigenvectors", 0, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_gen_real_mat_print (x04cac).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

END:
  NAG_FREE(d);
  NAG_FREE(e);
  NAG_FREE(w);
  NAG_FREE(z);
  NAG_FREE(isuppz);

  return exit_status;
}

#undef Z