    PROGRAM f08chfe

!      F08CHF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : dgerqf, dormrq, dtrtrs, nag_wp
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       REAL (KIND=nag_wp), PARAMETER   :: zero = 0.0E0_nag_wp
       INTEGER, PARAMETER              :: nb = 64, nin = 5, nout = 6
!      .. Local Scalars ..
       INTEGER                         :: i, info, lda, lwork, m, n
!      .. Local Arrays ..
       REAL (KIND=nag_wp), ALLOCATABLE :: a(:,:), b(:), tau(:), work(:), x(:)
!      .. Executable Statements ..
       WRITE (nout,*) 'F08CHF Example Program Results'
       WRITE (nout,*)
!      Skip heading in data file
       READ (nin,*)
       READ (nin,*) m, n
       lda = m
       lwork = nb*m
       ALLOCATE (a(lda,n),b(m),tau(m),work(lwork),x(n))

!      Read the matrix A and the vector b from data file

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

!      Compute the RQ factorization of A
!      The NAG name equivalent of dgerqf is f08chf
       CALL dgerqf(m,n,a,lda,tau,work,lwork,info)

!      Copy the m element vector b into elements x(n-m+1), ..., x(n) of x

       x(n-m+1:n) = b(1:m)

!      Solve R*y2 = b, storing the result in x2
!      The NAG name equivalent of dtrtrs is f07tef
       CALL dtrtrs('Upper','No transpose','Non-Unit',m,1,a(1,n-m+1),lda, &
          x(n-m+1),m,info)

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

          x(1:n-m) = zero

!         Compute the minimum-norm solution x = (Q**T)*y
!         The NAG name equivalent of dormrq is f08ckf
          CALL dormrq('Left','Transpose',n,1,m,a,lda,tau,x,n,work,lwork,info)

!         Print minimum-norm solution

          WRITE (nout,*) 'Minimum-norm solution'
          WRITE (nout,99999) x(1:n)

       END IF

99999  FORMAT (1X,8F9.4)
    END PROGRAM f08chfe
