/* nag_real_eigensystem (f02agc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 1, 1990.
 * Mark 8 revised, 2004.
 */

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

#define COMPLEX(A) A.re, A.im
#define A(I, J)    a[(I) *tda + J]
#define V(I, J)    v[(I) *tdv + J]

int main(void)
{

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

  INIT_FAIL(fail);

  printf("nag_real_eigensystem (f02agc) Example Program Results\n");
  /* Skip heading in data file */
  scanf("%*[^\n]");
  scanf("%ld", &n);

  if (n >= 1)
    {
      if (!(a = NAG_ALLOC(n*n, double)) ||
          !(iter = NAG_ALLOC(n, Integer)) ||
          !(r = NAG_ALLOC(n, Complex)) ||
          !(v = NAG_ALLOC(n*n, Complex)))
        {
          printf("Allocation failure\n");
          exit_status = -1;
          goto END;
        }
      tda = 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));
  /* nag_real_eigensystem (f02agc).
   * All eigenvalues and eigenvectors of real matrix
   */
  nag_real_eigensystem(n, a, tda, r, v, tdv, iter, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_real_eigensystem (f02agc).\n%s\n",
              fail.message);
      exit_status = 1;
      goto END;
    }
  printf("Eigenvalues\n");
  for (i = 0; i < n; i++)
    printf("(%7.3f, %7.3f) \n", COMPLEX(r[i]));
  printf("\nEigenvectors\n");
  for (i = 0; i < n; i++)
    for (j = 0; j < n; j++)
      printf("(%7.3f, %7.3f) %s", COMPLEX(V(i, j)),
              (j%4 == 3 || j == n-1)?"\n":" ");
 END:
  NAG_FREE(a);
  NAG_FREE(iter);
  NAG_FREE(r);
  NAG_FREE(v);
  return exit_status;
}