    PROGRAM f08bnfe

!      F08BNF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : nag_wp, zgelsy
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       INTEGER, PARAMETER              :: nb = 64, nin = 5, nout = 6
!      .. Local Scalars ..
       REAL (KIND=nag_wp)              :: rcond
       INTEGER                         :: i, info, lda, lwork, m, n, rank
!      .. Local Arrays ..
       COMPLEX (KIND=nag_wp), ALLOCATABLE :: a(:,:), b(:), work(:)
       REAL (KIND=nag_wp), ALLOCATABLE :: rwork(:)
       INTEGER, ALLOCATABLE            :: jpvt(:)
!      .. Executable Statements ..
       WRITE (nout,*) 'F08BNF Example Program Results'
       WRITE (nout,*)
!      Skip heading in data file
       READ (nin,*)
       READ (nin,*) m, n
       lda = m
       lwork = nb*(n+1)
       ALLOCATE (a(lda,n),b(m),work(lwork),rwork(2*n),jpvt(n))

!      Read A and B from data file

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

!      Initialize JPVT to be zero so that all columns are free

       jpvt(1:n) = 0

!      Choose RCOND to reflect the relative accuracy of the input data

       rcond = 0.01_nag_wp

!      Solve the least squares problem min( norm2(b - Ax) ) for the x
!      of minimum norm.

!      The NAG name equivalent of zgelsy is f08bnf
       CALL zgelsy(m,n,1,a,lda,b,m,jpvt,rcond,rank,work,lwork,rwork,info)

!      Print solution

       WRITE (nout,*) 'Least squares solution'
       WRITE (nout,99999) b(1:n)

!      Print the effective rank of A

       WRITE (nout,*)
       WRITE (nout,*) 'Tolerance used to estimate the rank of A'
       WRITE (nout,99998) rcond
       WRITE (nout,*) 'Estimated rank of A'
       WRITE (nout,99997) rank

99999  FORMAT (4(' (',F7.4,',',F7.4,')':))
99998  FORMAT (1X,1P,E10.2)
99997  FORMAT (1X,I6)
    END PROGRAM f08bnfe
