!   C05NBF Example Program Text
!   Mark 23 Release. NAG Copyright 2011.

    MODULE c05nbfe_mod

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

!      .. Use Statements ..
       USE nag_library, ONLY : nag_wp
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       REAL (KIND=nag_wp), PARAMETER       :: one = 1.0_nag_wp
       REAL (KIND=nag_wp), PARAMETER       :: three = 3.0_nag_wp
       REAL (KIND=nag_wp), PARAMETER       :: two = 2.0_nag_wp
       INTEGER, PARAMETER                  :: n = 9, nout = 6
    CONTAINS
!dec$ attributes offload : mic :: fcn
       SUBROUTINE fcn(n,x,fvec,iflag)

!         .. Implicit None Statement ..
          IMPLICIT NONE
!         .. 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 (IN)     :: x(n)
!         .. Executable Statements ..
          fvec(1:n) = three*x(1:n) - two*x(1:n)*x(1:n) + one
          fvec(2:n) = fvec(2:n) - x(1:(n-1))
          fvec(1:(n-1)) = fvec(1:(n-1)) - two*x(2:n)

          RETURN

!dec$ attributes offload : mic :: fcn
       END SUBROUTINE fcn
    END MODULE c05nbfe_mod
    PROGRAM c05nbfe

!      C05NBF Example Main Program

!      .. Use Statements ..
       USE nag_library, ONLY : c05nbf, dnrm2, nag_wp, x02ajf
       USE c05nbfe_mod, ONLY : fcn, n, nout, one
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Local Scalars ..
       REAL (KIND=nag_wp)                  :: fnorm, xtol
       INTEGER                             :: i, ifail, j, lwa
!      .. Local Arrays ..
       REAL (KIND=nag_wp), ALLOCATABLE     :: fvec(:), x(:)
       REAL (KIND=nag_wp)                  :: wa(1)
!      .. Intrinsic Functions ..
       INTRINSIC                              sqrt
!      .. Executable Statements ..
       WRITE (nout,*) 'C05NBF Example Program Results'

       ALLOCATE (fvec(n),x(n))

!      The following starting values provide a rough solution.

       x(1:n) = -one
       xtol = sqrt(x02ajf())

       ifail = -1
       CALL c05nbf(fcn,n,x,fvec,xtol,wa,lwa,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:)
          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 c05nbfe
