!   C05QBF Example Program Text
!   Mark 24 Release. NAG Copyright 2012.

    Module c05qbfe_mod

!     C05QBF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter                   :: n = 9, nout = 6
    Contains
      Subroutine fcn(n,x,fvec,iuser,ruser,iflag)

!       .. Scalar Arguments ..
        Integer, Intent (Inout)              :: iflag
        Integer, Intent (In)                 :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out)     :: fvec(n)
        Real (Kind=nag_wp), Intent (Inout)   :: ruser(*)
        Real (Kind=nag_wp), Intent (In)      :: x(n)
        Integer, Intent (Inout)              :: iuser(*)
!       .. Executable Statements ..
        fvec(1:n) = (3.0_nag_wp-2.0_nag_wp*x(1:n))*x(1:n) + 1.0_nag_wp
        fvec(2:n) = fvec(2:n) - x(1:(n-1))
        fvec(1:(n-1)) = fvec(1:(n-1)) - 2.0_nag_wp*x(2:n)

        Return

      End Subroutine fcn
    End Module c05qbfe_mod
    Program c05qbfe

!     C05QBF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: c05qbf, dnrm2, nag_wp, x02ajf
      Use c05qbfe_mod, Only: fcn, n, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)                   :: fnorm, xtol
      Integer                              :: i, ifail, j
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable      :: fvec(:), x(:)
      Real (Kind=nag_wp)                   :: ruser(1)
      Integer                              :: iuser(1)
!     .. Intrinsic Procedures ..
      Intrinsic                            :: sqrt
!     .. Executable Statements ..
      Write (nout,*) 'C05QBF Example Program Results'

      Allocate (fvec(n),x(n))

!     The following starting values provide a rough solution.

      x(1:n) = -1.0E0_nag_wp
      xtol = sqrt(x02ajf())

      ifail = -1
      Call c05qbf(fcn,n,x,fvec,xtol,iuser,ruser,ifail)

      Select Case (ifail)
      Case (0)
!       The NAG name equivalent of dnrm2 is f06ejf
        fnorm = dnrm2(n,fvec,1)
        Write (nout,*)
        Write (nout,99999) 'Final 2-norm of the residuals =', fnorm
        Write (nout,*)
        Write (nout,*) 'Final approximate solution'
        Write (nout,*)
        Write (nout,99998)(x(j),j=1,n)
      Case (2:4)
        Write (nout,*)
        Write (nout,*) 'Approximate solution'
        Write (nout,*)
        Write (nout,99998)(x(i),i=1,n)
      End Select

99999 Format (1X,A,E12.4)
99998 Format (1X,3F12.4)
    End Program c05qbfe
