Program f08wqfe

!     F08WQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x02ajf, x04daf, zggev3
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: scal
      Integer                          :: i, ifail, info, k, lda, ldb, ldvr,   &
                                          lwork, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), alpha(:), b(:,:), beta(:), &
                                          vr(:,:), work(:)
      Complex (Kind=nag_wp)            :: dummy(1,1)
      Real (Kind=nag_wp), Allocatable  :: rwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, all, conjg, maxloc, nint, real
!     .. Executable Statements ..
      Write (nout,*) 'F08WQF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldb = n
      ldvr = n
      Allocate (a(lda,n),alpha(n),b(ldb,n),beta(n),vr(ldvr,n),rwork(8*n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
!     The NAG name equivalent of zggev3 is f08wqf
      Call zggev3('No left vectors','Vectors (right)',n,a,lda,b,ldb,alpha,     &
        beta,dummy,1,vr,ldvr,dummy,lwork,rwork,info)

      lwork = nint(real(dummy(1,1)))
      Allocate (work(lwork))

!     Read in the matrices A and B

      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:n),i=1,n)

!     Solve the generalized eigenvalue problem

!     The NAG name equivalent of zggev3 is f08wqf
      Call zggev3('No left vectors','Vectors (right)',n,a,lda,b,ldb,alpha,     &
        beta,dummy,1,vr,ldvr,work,lwork,rwork,info)

      If (info>0) Then
        Write (nout,*)
        Write (nout,99999) 'Failure in ZGGEV3. INFO =', info
      Else If (all(abs(beta(1:n))>x02ajf())) Then
!       Re-normalize the eigenvectors, largest absolute element real
        Do i = 1, n
          rwork(1:n) = abs(vr(1:n,i))
          k = maxloc(rwork(1:n),1)
          scal = conjg(vr(k,i))/rwork(k)
          vr(1:n,i) = vr(1:n,i)*scal
        End Do
        alpha(1:n) = alpha(1:n)/beta(1:n)
        ifail = 0
        Call x04daf('Gen',' ',1,n,alpha,1,'Eigenvalues:',ifail)
        Write (nout,*)
        Call x04daf('Gen',' ',n,n,vr,ldvr,'Right Eigenvectors (columns):',     &
          ifail)
      Else
        Write (nout,*) 'Some of the eigenvalues are infinite.'
        Write (nout,*)
        ifail = 0
        Call x04daf('Gen',' ',1,n,alpha,1,'Alpha',ifail)
        Call x04daf('Gen',' ',1,n,beta,1,'Beta',ifail)
      End If

99999 Format (1X,A,I4)
    End Program f08wqfe