/* nag_real_symm_general_eigensystem (f02aec) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 2 revised, 1992.
 * Mark 8 revised, 2004.
 */

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

#define A(I, J) a[(I) *tda + J]
#define B(I, J) b[(I) *tdb + J]
#define V(I, J) v[(I) *tdv + J]

int main(void)
{

  Integer  exit_status = 0, i, j, n, tda, tdb, tdv;
  NagError fail;
  double   *a = 0, *b = 0, *r = 0, *v = 0;

  INIT_FAIL(fail);

  printf("nag_real_symm_general_eigensystem (f02aec) Example Program"
          " Results\n");
  /* Skip heading in data file */
  scanf("%*[^\n]");
  scanf("%ld", &n);
  if (n >= 1)
    {
      if (!(a = NAG_ALLOC(n*n, double)) ||
          !(b = NAG_ALLOC(n*n, double)) ||
          !(r = NAG_ALLOC(n, double)) ||
          !(v = NAG_ALLOC(n*n, double)))
        {
          printf("Allocation failure\n");
          exit_status = -1;
          goto END;
        }
      tda = n;
      tdb = n;
      tdv = n;
    }
  else
    {
      printf("Invalid n.\n");
      exit_status = 1;
      return exit_status;
    }
  for (i = 0; i < n; i++)
    {
      for (j = 0; j < n; j++)
        scanf("%lf", &A(i, j));
      for (j = 0; j < n; j++)
        scanf("%lf", &B(i, j));
    }
  /* nag_real_symm_general_eigensystem (f02aec).
   * All eigenvalues and eigenvectors of generalized real
   * symmetric-definite eigenproblem
   */
  nag_real_symm_general_eigensystem(n, a, tda, b, tdb, r, v, tdv, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf(
              "Error from nag_real_symm_general_eigensystem (f02aec).\n%s\n",
              fail.message);
      exit_status = 1;
      goto END;
    }
  printf("Eigenvalues\n");
  for (i = 0; i < n; i++)
    printf("%9.4f%s", r[i], (i%8 == 7 || i == n-1)?"\n":" ");
  printf("Eigenvectors\n");
  for (i = 0; i < n; i++)
    for (j = 0; j < n; j++)
      printf("%9.4f%s", V(i, j), (j%8 == 7 || j == n-1)?"\n":" ");
 END:
  NAG_FREE(a);
  NAG_FREE(b);
  NAG_FREE(r);
  NAG_FREE(v);
  return exit_status;
}