    PROGRAM f08kcfe

!      F08KCF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : dgelsd, nag_wp
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       INTEGER, PARAMETER              :: nin = 5, nout = 6
!      .. Local Scalars ..
       REAL (KIND=nag_wp)              :: rcond
       INTEGER                         :: i, info, lda, liwork, lwork, m, n,   &
                                          rank
!      .. Local Arrays ..
       REAL (KIND=nag_wp), ALLOCATABLE :: a(:,:), b(:), s(:), work(:)
       REAL (KIND=nag_wp)              :: lw(1)
       INTEGER, ALLOCATABLE            :: iwork(:)
       INTEGER                         :: liw(1)
!      .. Intrinsic Functions ..
       INTRINSIC                          nint
!      .. Executable Statements ..
       WRITE (nout,*) 'F08KCF Example Program Results'
       WRITE (nout,*)
!      Skip heading in data file
       READ (nin,*)
       READ (nin,*) m, n
       lda = m
       ALLOCATE (a(lda,n),b(n),s(m))

!      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

!      Call f08kcf/dgelsd in workspace query mode.
       lwork = -1
!      The NAG name equivalent of dgelsd is f08kcf
       CALL dgelsd(m,n,1,a,lda,b,n,s,rcond,rank,lw,lwork,liw,info)
       lwork = nint(lw(1))
       liwork = liw(1)
       ALLOCATE (work(lwork),iwork(liwork))

!      Now Solve the least squares problem min( norm2(b - Ax) ) for the
!      x of minimum norm.
       CALL dgelsd(m,n,1,a,lda,b,n,s,rcond,rank,work,lwork,iwork,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:m)
       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 f08kcfe
