    PROGRAM f08bafe

!      F08BAF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : dgelsy, nag_wp
!      .. 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 ..
       REAL (KIND=nag_wp), ALLOCATABLE :: a(:,:), b(:), work(:)
       INTEGER, ALLOCATABLE            :: jpvt(:)
!      .. Executable Statements ..
       WRITE (nout,*) 'F08BAF Example Program Results'
       WRITE (nout,*)
!      Skip heading in data file
       READ (nin,*)
       READ (nin,*) m, n
       lda = m
       lwork = 3*n + nb*(n+1)
       ALLOCATE (a(lda,n),b(m),work(lwork),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 dgelsy is f08baf
       CALL dgelsy(m,n,1,a,lda,b,m,jpvt,rcond,rank,work,lwork,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 (1X,7F11.4)
99998  FORMAT (3X,1P,E11.2)
99997  FORMAT (1X,I6)
    END PROGRAM f08bafe
