    PROGRAM f08befe

!      F08BEF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : dgeqpf, dormqr, dtrsv, nag_wp, x04caf
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       REAL (KIND=nag_wp), PARAMETER   :: zero = 0.0E0_nag_wp
       INTEGER, PARAMETER              :: nin = 5, nout = 6
!      .. Local Scalars ..
       REAL (KIND=nag_wp)              :: tol
       INTEGER                         :: i, ifail, info, k, lda, ldb, ldx,    &
                                          lwork, m, n, nrhs
!      .. Local Arrays ..
       REAL (KIND=nag_wp), ALLOCATABLE :: a(:,:), b(:,:), tau(:), work(:),     &
                                          x(:,:)
       INTEGER, ALLOCATABLE            :: jpvt(:)
!      .. Intrinsic Functions ..
       INTRINSIC                          abs
!      .. Executable Statements ..
       WRITE (nout,*) 'F08BEF Example Program Results'
!      Skip heading in data file
       READ (nin,*)
       READ (nin,*) m, n, nrhs
       lda = m
       ldb = m
       ldx = m
       lwork = 64*n
       ALLOCATE (a(lda,n),b(ldb,nrhs),tau(n),work(lwork),x(ldx,nrhs),jpvt(n))

!      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)

!      Initialize JPVT to be zero so that all columns are free

       jpvt(1:n) = 0

!      Compute the QR factorization of A

!      The NAG name equivalent of dgeqpf is f08bef
       CALL dgeqpf(m,n,a,lda,jpvt,tau,work,info)

!      Choose TOL to reflect the relative accuracy of the input data

       tol = 0.01E0_nag_wp

!      Determine which columns of R to use

LOOP:  DO k = 1, n
          IF (abs(a(k,k))<=tol*abs(a(1,1))) EXIT LOOP
       END DO LOOP

!      Compute C = (Q**T)*B, storing the result in B

       k = k - 1

!      The NAG name equivalent of dormqr is f08agf
       CALL dormqr('Left','Transpose',m,nrhs,n,a,lda,tau,b,ldb,work,lwork, &
          info)

!      Compute least-squares solution by backsubstitution in R*B = C
       DO i = 1, nrhs

!         The NAG name equivalent of dtrsv is f06pjf
          CALL dtrsv('Upper','No transpose','Non-Unit',k,a,lda,b(1,i),1)

!         Set the unused elements of the I-th solution vector to zero

          b(k+1:n,i) = zero

       END DO

!      Unscramble the least-squares solution stored in B

       DO i = 1, n
          x(jpvt(i),1:nrhs) = b(i,1:nrhs)
       END DO

!      Print least-squares solution

       WRITE (nout,*)
       FLUSH (nout)

!      ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
       ifail = 0
       CALL x04caf('General',' ',n,nrhs,x,ldx,'Least-squares solution',ifail)

    END PROGRAM f08befe
