    PROGRAM f08kafe

!      F08KAF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

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

!      Read A and B from data file

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

!      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 dgelss is f08kaf
       CALL dgelss(m,n,1,a,lda,b,m,s,rcond,rank,work,lwork,info)

       IF (info==0) THEN

!         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

!         Print singular values of A

          WRITE (nout,*)
          WRITE (nout,*) 'Singular values of A'
          WRITE (nout,99999) s(1:n)

!         Compute and print estimate of the square root of the
!         residual sum of squares

          IF (rank==n) THEN
!            The NAG name equivalent of dnrm2 is f06ejf
             rnorm = dnrm2(m-n,b(n+1),1)
             WRITE (nout,*)
             WRITE (nout,*) 'Square root of the residual sum of squares'
             WRITE (nout,99998) rnorm
          END IF
       ELSE
          WRITE (nout,*) 'The SVD algorithm failed to converge'
       END IF

99999  FORMAT (1X,7F11.4)
99998  FORMAT (3X,1P,E11.2)
99997  FORMAT (1X,I6)
    END PROGRAM f08kafe
