    PROGRAM f08cefe

!      F08CEF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : dgeqlf, dnrm2, dormql, dtrtrs, nag_wp, x04caf
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       INTEGER, PARAMETER              :: nb = 64, nin = 5, nout = 6
!      .. Local Scalars ..
       INTEGER                         :: i, ifail, info, j, lda, ldb, lwork,  &
                                          m, n, nrhs
!      .. Local Arrays ..
       REAL (KIND=nag_wp), ALLOCATABLE :: a(:,:), b(:,:), rnorm(:), tau(:),    &
                                          work(:)
!      .. Executable Statements ..
       WRITE (nout,*) 'F08CEF Example Program Results'
       WRITE (nout,*)
       FLUSH (nout)
!      Skip heading in data file
       READ (nin,*)
       READ (nin,*) m, n, nrhs
       lda = m
       ldb = m
       lwork = nb*n
       ALLOCATE (a(lda,n),b(ldb,nrhs),rnorm(nrhs),tau(n),work(lwork))

!      Read A and B from data file

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

!      Compute the QL factorization of A
!      The NAG name equivalent of dgeqlf is f08cef
       CALL dgeqlf(m,n,a,lda,tau,work,lwork,info)

!      Compute C = (C1) = (Q**T)*B, storing the result in B
!                   (C2)
!      The NAG name equivalent of dormql is f08cgf
       CALL dormql('Left','Transpose',m,nrhs,n,a,lda,tau,b,ldb,work,lwork, &
          info)

!      Compute least-squares solutions by backsubstitution in
!      L*X = C2
!      The NAG name equivalent of dtrtrs is f07tef
       CALL dtrtrs('Lower','No transpose','Non-Unit',n,nrhs,a(m-n+1,1),lda, &
          b(m-n+1,1),ldb,info)

       IF (info>0) THEN
          WRITE (nout,*) 'The lower triangular factor, L, of A is singular, '
          WRITE (nout,*) 'the least squares solution could not be computed'
       ELSE

!         Print least-squares solution(s)

!         ifail: behaviour on error exit
!                =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
          ifail = 0
          CALL x04caf('General',' ',n,nrhs,b(m-n+1,1),ldb, &
             'Least-squares solution(s)',ifail)

!         Compute and print estimates of the square roots of the residual
!         sums of squares

!         The NAG name equivalent of dnrm2 is f06ejf
          DO j = 1, nrhs
             rnorm(j) = dnrm2(m-n,b(1,j),1)
          END DO

          WRITE (nout,*)
          WRITE (nout,*) 'Square root(s) of the residual sum(s) of squares'
          WRITE (nout,99999) rnorm(1:nrhs)
       END IF

99999  FORMAT (5X,1P,7E11.2)
    END PROGRAM f08cefe
