/* nag_dgeev (f08nac) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 23, 2011.
 */

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

int main(void)
{

  /* Scalars */
  Integer       i, j, n, pda, pdvr;
  Integer       exit_status = 0;

  /* Arrays */
  double        *a = 0, *vr = 0, *wi = 0, *wr = 0;
  double         dummy [1];

  /* Nag Types */
  NagError      fail;
  Nag_OrderType order;

#ifdef NAG_COLUMN_MAJOR
#define A(I, J)  a[(J-1)*pda + I - 1]
#define VR(I, J) vr[(J)*pdvr + I]
  order = Nag_ColMajor;
#else
#define A(I, J)  a[(I-1)*pda + J - 1]
#define VR(I, J) vr[(I)*pdvr + J]
  order = Nag_RowMajor;
#endif

  INIT_FAIL(fail);

  printf("nag_dgeev (f08nac) Example Program Results\n");

  /* Skip heading in data file */
  scanf("%*[^\n]");
  scanf("%ld%*[^\n]", &n);
  if (n < 0)
    {
      printf("Invalid n\n");
      exit_status = 1;
      goto END;
    }

  pda = n;
  pdvr = n;
  /* Allocate memory */
  if (!(a = NAG_ALLOC(n * n, double)) ||
      !(vr = NAG_ALLOC(n * n, double)) ||
      !(wi = NAG_ALLOC(n, double)) ||
      !(wr = NAG_ALLOC(n, double)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }

  /* Read the matrix A from data file */
  for (i = 1; i <= n; ++i)
    for (j = 1; j <= n; ++j) scanf("%lf", &A(i, j));
  scanf("%*[^\n]");

  /* Compute the eigenvalues and right eigenvectors only of A 
   * using nag_dgeev (f08nac).
   */
  nag_dgeev(order, Nag_NotLeftVecs, Nag_RightVecs, n, a, pda, wr, wi,
            dummy, 1, vr, pdvr, &fail);

  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_dgeev (f08nac).\n%s\n", fail.message);
      exit_status = 1;
      goto END;
    }

  /* Print eigenvalues and right eigenvectors. */
  for (j = 0; j < n; ++j)
    {
      printf("\nEigenvalue %3ld = ", j+1);
      if (wi[j] == 0.0)
        printf("%13.4e\n", wr[j]);
      else
        printf(" (%13.4e, %13.4e)\n", wr[j], wi[j]);

      printf("\nEigenvector %2ld\n", j+1);
      if (wi[j] == 0.0)
        for (i = 0; i < n; ++i) printf("%17s%13.4e\n", "", VR(i, j));
      else if (wi[j] > 0.0)
        for (i = 0; i < n; ++i) 
          printf("%18s(%13.4e, %13.4e)\n", "", VR(i, j), VR(i, j+1));
      else
        for (i = 0; i < n; ++i)
          printf("%18s(%13.4e, %13.4e)\n", "", VR(i, j-1), -VR(i, j));
      printf("\n");
    }

 END:
  NAG_FREE(a);
  NAG_FREE(vr);
  NAG_FREE(wi);
  NAG_FREE(wr);

  return exit_status;
}
#undef A
#undef VR