    PROGRAM f08mefe

!      F08MEF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : dbdsqr, f06qhf, nag_wp, x04caf
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       REAL (KIND=nag_wp), PARAMETER   :: one = 1.0_nag_wp
       REAL (KIND=nag_wp), PARAMETER   :: zero = 0.0_nag_wp
       INTEGER, PARAMETER              :: nin = 5, nout = 6
!      .. Local Scalars ..
       INTEGER                         :: ifail, info, ldc, ldu, ldvt, n
       CHARACTER (1)                   :: uplo
!      .. Local Arrays ..
       REAL (KIND=nag_wp), ALLOCATABLE :: c(:,:), d(:), e(:), u(:,:), vt(:,:), &
                                          work(:)
!      .. Executable Statements ..
       WRITE (nout,*) 'F08MEF Example Program Results'
!      Skip heading in data file
       READ (nin,*)
       READ (nin,*) n
       ldc = 1
       ldu = n
       ldvt = n
       ALLOCATE (c(ldc,1),d(n),e(n-1),u(ldu,n),vt(ldvt,n),work(4*n))

!      Read B from data file

       READ (nin,*) d(1:n)
       READ (nin,*) e(1:n-1)

       READ (nin,*) uplo

!      Initialise U and VT to be the unit matrix
       CALL f06qhf('General',n,n,zero,one,u,ldu)
       CALL f06qhf('General',n,n,zero,one,vt,ldvt)

!      Calculate the SVD of B
!      The NAG name equivalent of dbdsqr is f08mef
       CALL dbdsqr(uplo,n,n,n,0,d,e,vt,ldvt,u,ldu,c,ldc,work,info)

       WRITE (nout,*)
       IF (info>0) THEN
          WRITE (nout,*) 'Failure to converge.'
       ELSE

!         Print singular values, left & right singular vectors

          WRITE (nout,*) 'Singular values'
          WRITE (nout,99999) d(1:n)
          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,n,vt,ldvt, &
             'Right singular vectors, by row',ifail)

          WRITE (nout,*)
          FLUSH (nout)

          ifail = 0
          CALL x04caf('General',' ',n,n,u,ldu, &
             'Left singular vectors, by column',ifail)

       END IF

99999  FORMAT (3X,(8F8.4))
    END PROGRAM f08mefe
