    MODULE nlp_ex05_mod
      ! .. Implicit None Statement ..
      IMPLICIT NONE
      ! .. Default Accessibility ..
      PUBLIC
      ! .. Intrinsic Functions ..
      INTRINSIC KIND, PRESENT
      ! .. Parameters ..
      INTEGER, PARAMETER :: wp = KIND(1.0D0)

    CONTAINS

      SUBROUTINE obj_fun(first_call,x,finish,obj_f,obj_grad)
        ! .. Implicit None Statement ..
        IMPLICIT NONE
        ! .. Scalar Arguments ..
        REAL (wp), INTENT (OUT) :: obj_f
        LOGICAL, INTENT (INOUT) :: finish
        LOGICAL, INTENT (IN) :: first_call
        ! .. Array Arguments ..
        REAL (wp), OPTIONAL, INTENT (INOUT) :: obj_grad(:)
        REAL (wp), INTENT (IN) :: x(:)
        ! .. Executable Statements ..

        obj_f = 100.0_wp*(x(2)-x(1)**2)**2 + (1.0_wp-x(1))**2 + &
         90.0_wp*(x(4)-x(3)**2)**2 + (1.0_wp-x(3))**2 + &
         10.1_wp*((x(2)-1.0_wp)**2+(x(4)-1.0_wp)**2) + &
         19.8_wp*(x(2)-1.0_wp)*(x(4)-1.0_wp)

        IF (PRESENT(obj_grad)) THEN
          obj_grad(1) = -400.0_wp*x(1)*(x(2)-x(1)**2) - 2.0_wp*(1.0_wp-x(1))
          obj_grad(2) = 200.0_wp*(x(2)-x(1)**2) + 20.2_wp*(x(2)-1.0_wp) + &
           19.8_wp*(x(4)-1.0_wp)
          obj_grad(3) = -360.0_wp*x(3)*(x(4)-x(3)**2) - 2.0_wp*(1.0_wp-x(3))
          obj_grad(4) = 180.0_wp*(x(4)-x(3)**2) + 20.2_wp*(x(4)-1.0_wp) + &
           19.8_wp*(x(2)-1.0_wp)
        END IF
      END SUBROUTINE obj_fun

    END MODULE nlp_ex05_mod

    PROGRAM nag_nlp_ex05

      ! Example Program Text for nag_nlp
      ! NAG fl90, Release 4. NAG Copyright 2000.

      ! .. Use Statements ..
      USE nag_examples_io, ONLY : nag_std_out
      USE nag_nlp, ONLY : nag_nlp_sol
      USE nlp_ex05_mod, ONLY : obj_fun, wp
      ! .. Implicit None Statement ..
      IMPLICIT NONE
      ! .. Parameters ..
      INTEGER, PARAMETER :: n = 4
      ! .. Local Scalars ..
      REAL (wp) :: obj_f
      ! .. Local Arrays ..
      REAL (wp) :: x(n)
      ! .. Executable Statements ..
      WRITE (nag_std_out,*) 'Example Program Results for nag_nlp_ex05'

      x = (/ -3.0_wp, -1.0_wp, -3.0_wp, -1.0_wp/)

      ! Solve the problem

      CALL nag_nlp_sol(obj_fun,x,obj_f)

    END PROGRAM nag_nlp_ex05
