    PROGRAM f08pefe

!      F08PEF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : dgemm, dhseqr, dlange => f06raf, nag_wp, &
                               x02ajf, x04caf
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       INTEGER, PARAMETER              :: nin = 5, nout = 6
!      .. Local Scalars ..
       REAL (KIND=nag_wp)              :: alpha, beta, norm
       INTEGER                         :: i, ifail, info, ldc, ldd, ldh, ldz,  &
                                          lwork, n
!      .. Local Arrays ..
       REAL (KIND=nag_wp), ALLOCATABLE :: c(:,:), d(:,:), h(:,:), wi(:),       &
                                          work(:), wr(:), z(:,:)
!      .. Executable Statements ..
       WRITE (nout,*) 'F08PEF Example Program Results'
!      Skip heading in data file
       READ (nin,*)
       READ (nin,*) n
       ldc = n
       ldd = n
       ldh = n
       ldz = n
       lwork = n
       ALLOCATE (c(ldc,n),d(ldd,n),h(ldh,n),wi(n),work(lwork),wr(n),z(ldz,n))

!      Read H from data file

       READ (nin,*) (h(i,1:n),i=1,n)

!      Copy H into D
       d(1:n,1:n) = h(1:n,1:n)

!      Print Matrix H
!      ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
       ifail = 0
       CALL x04caf('General',' ',n,n,h,ldh,'Matrix H',ifail)

!      Calculate the eigenvalues and Schur factorization of H

!      The NAG name equivalent of dhseqr is f08pef
       CALL dhseqr('Schur form','Initialize Z',n,1,n,h,ldh,wr,wi,z,ldz,work, &
          lwork,info)

       WRITE (nout,*)
       IF (info>0) THEN
          WRITE (nout,*) 'Failure to converge.'
       ELSE

!         Compute H - Z*T*Z^T from the factorization of A and store in matrix D
!         The NAG name equivelent of dgemm is f06yaf
          alpha = 1.0_nag_wp
          beta = 0.0_nag_wp
          CALL dgemm('N','N',n,n,n,alpha,z,ldz,h,ldh,beta,c,ldc)
          alpha = -1.0_nag_wp
          beta = 1.0_nag_wp
          CALL dgemm('N','T',n,n,n,alpha,c,ldc,z,ldz,beta,d,ldd)

!         Find norm of matrix D and print warning if it is too large
!         f06raf is the NAG name equivalent of the LAPACK auxiliary dlange
          norm = dlange('O',ldd,n,d,ldd,work)
          IF (norm>x02ajf()**0.8_nag_wp) THEN
             WRITE (nout,*) 'Norm of H-(Z*T*Z^T) is much greater than 0.'
             WRITE (nout,*) 'Schur factorization has failed.'
          ELSE
!            Print eigenvalues
             WRITE (nout,*) 'Eigenvalues'
             WRITE (nout,99999)(' (',wr(i),',',wi(i),')',i=1,n)
          END IF
       END IF

99999  FORMAT (1X,A,F8.4,A,F8.4,A)
    END PROGRAM f08pefe
