    Program f08mefe

!     F08MEF Example Program Text

!     Mark 24 Release. NAG Copyright 2012.

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