/* nag_dstevr (f08jdc) Example Program.
 *
 * Copyright 2017 Numerical Algorithms Group.
 *
 * Mark 26.1, 2017.
 */

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

int main(void)
{
  /* Scalars */
  double abstol, vl = 0.0, vu = 0.0;
  Integer exit_status = 0, i, il, iu, j, m, n, pdz;
  /* Arrays */
  double *d = 0, *e = 0, *w = 0, *z = 0;
  Integer *isuppz = 0;
  /* Nag Types */
  Nag_OrderType order;
  NagError fail;

#ifdef NAG_COLUMN_MAJOR
  order = Nag_ColMajor;
#else
  order = Nag_RowMajor;
#endif

  INIT_FAIL(fail);

  printf("nag_dstevr (f08jdc) Example Program Results\n\n");

  /* Skip heading in data file and read n and the lower and upper
   * indices of the eigenvalues to be found.
   */
  scanf("%*[^\n]");
  scanf("%" NAG_IFMT "%" NAG_IFMT "%" NAG_IFMT "%*[^\n]", &n, &il, &iu);

  m = iu - il + 1;
  pdz = n;

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

  /* Read the diagonal and off-diagonal elements of the matrix A
   * from data file.
   */
  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]");

  /* Set the absolute error tolerance for eigenvalues.
   * With abstol set to zero, the default value is used instead.
   */
  abstol = 0.0;

  /* nag_dstevr (f08jdc).
   * Solve the symmetric tridiagonal eigenvalue problem.
   */
  nag_dstevr(order, Nag_DoBoth, Nag_Indices, n, d, e, vl, vu, il, iu, abstol,
             &m, w, z, pdz, isuppz, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_dstevr (f08jdc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

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

  /* nag_gen_real_mat_print (x04cac).
   * Print selected eigenvectors.
   */
  fflush(stdout);
  nag_gen_real_mat_print(order, Nag_GeneralMatrix, Nag_NonUnitDiag, n,
                         m, z, pdz, "Selected 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;
}