    PROGRAM f08kqfe

!      F08KQF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : nag_wp, zgelsd
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       INTEGER, PARAMETER              :: nin = 5, nout = 6
!      .. Local Scalars ..
       REAL (KIND=nag_wp)              :: rcond
       INTEGER                         :: i, info, lda, liwork, lrwork, lwork, &
                                          m, n, rank
!      .. Local Arrays ..
       COMPLEX (KIND=nag_wp), ALLOCATABLE :: a(:,:), b(:), work(:)
       COMPLEX (KIND=nag_wp)           :: lw(1)
       REAL (KIND=nag_wp)              :: lrw(1)
       REAL (KIND=nag_wp), ALLOCATABLE :: rwork(:), s(:)
       INTEGER, ALLOCATABLE            :: iwork(:)
       INTEGER                         :: liw(1)
!      .. Intrinsic Functions ..
       INTRINSIC                          nint, real
!      .. Executable Statements ..
       WRITE (nout,*) 'F08KQF 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.01E0_nag_wp

!      Call f08kqf/zgelsd in workspace query mode.
       lwork = -1
       CALL zgelsd(m,n,1,a,lda,b,n,s,rcond,rank,lw,lwork,lrw,liw,info)
       lwork = nint(real(lw(1)))
       lrwork = nint(lrw(1))
       liwork = liw(1)
       ALLOCATE (work(lwork),rwork(lrwork),iwork(liwork))

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

!      The NAG name equivalent of zgelsd is f08kqf
       CALL zgelsd(m,n,1,a,lda,b,n,s,rcond,rank,work,lwork,rwork,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,99996) s(1:m)
       ELSE IF (info>0) THEN
          WRITE (nout,*) 'The SVD algorithm failed to converge'
       END IF

99999  FORMAT (4(' (',F7.4,',',F7.4,')':))
99998  FORMAT (3X,1P,E11.2)
99997  FORMAT (1X,I6)
99996  FORMAT (1X,7F11.4)
    END PROGRAM f08kqfe
