!   E04DGF Example Program Text
!   Mark 24 Release. NAG Copyright 2012.
    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
      Subroutine objfun(mode,n,x,objf,objgrd,nstate,iuser,ruser)
!       Routine to evaluate F(x) and its 1st derivatives.

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

      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
