!   E04DGF Example Program Text
!   Mark 23 Release. NAG Copyright 2011.
    MODULE e04dgfe_mod

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

!      .. Use Statements ..
       USE nag_library, ONLY : nag_wp
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       INTEGER, PARAMETER                  :: nin = 5, nout = 6
    CONTAINS
!dec$ attributes offload : mic :: objfun
       SUBROUTINE objfun(mode,n,x,objf,objgrd,nstate,iuser,ruser)
!         Routine to evaluate F(x) and its 1st derivatives.

!         .. Implicit None Statement ..
          IMPLICIT NONE
!         .. Scalar Arguments ..
          REAL (KIND=nag_wp), INTENT (OUT)    :: objf
          INTEGER, INTENT (INOUT)             :: mode
          INTEGER, INTENT (IN)                :: n, nstate
!         .. Array Arguments ..
          REAL (KIND=nag_wp), INTENT (OUT)    :: objgrd(n)
          REAL (KIND=nag_wp), INTENT (INOUT)  :: ruser(*)
          REAL (KIND=nag_wp), INTENT (IN)     :: x(n)
          INTEGER, INTENT (INOUT)             :: iuser(*)
!         .. Local Scalars ..
          REAL (KIND=nag_wp)                  :: expx1, x1, x2
!         .. Intrinsic Functions ..
          INTRINSIC                              exp
!         .. Executable Statements ..
          x1 = x(1)
          x2 = x(2)
          expx1 = exp(x1)
          objf = expx1*(4.0_nag_wp*x1**2+2.0_nag_wp*x2**2+4.0_nag_wp*x1*x2+ &
             2.0_nag_wp*x2+1.0_nag_wp)

          IF (mode==2) THEN
             objgrd(1:n) = (/ 4.0_nag_wp*expx1*(2.0_nag_wp*x1+x2) + objf, &
                2.0_nag_wp*expx1*(2.0_nag_wp*x2+2.0_nag_wp*x1+1.0_nag_wp) /)
          END IF

          RETURN

!dec$ attributes offload : mic :: objfun
       END SUBROUTINE objfun
    END MODULE e04dgfe_mod
    PROGRAM e04dgfe

!      E04DGF Example Main Program

!      .. Use Statements ..
       USE nag_library, ONLY : e04dgf, nag_wp
       USE e04dgfe_mod, ONLY : nin, nout, objfun
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Local Scalars ..
       REAL (KIND=nag_wp)                  :: objf
       INTEGER                             :: ifail, iter, n
!      .. Local Arrays ..
       REAL (KIND=nag_wp), ALLOCATABLE     :: objgrd(:), work(:), x(:)
       REAL (KIND=nag_wp)                  :: ruser(1)
       INTEGER                             :: iuser(1)
       INTEGER, ALLOCATABLE                :: iwork(:)
!      .. Executable Statements ..
       WRITE (nout,*) 'E04DGF Example Program Results'
       FLUSH (nout)

!      Skip heading in data file
       READ (nin,*)

       READ (nin,*) n
       ALLOCATE (iwork(n+1),objgrd(n),x(n),work(13*n))

       READ (nin,*) x(1:n)

!      Solve the problem

       ifail = -1
       CALL e04dgf(n,objfun,iter,objf,objgrd,x,iwork,work,iuser,ruser,ifail)

    END PROGRAM e04dgfe
