    MODULE nlp_ex04_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 = x(1)**2 + 0.5_wp*x(2)**2 + x(3)**2 + 0.5_wp*x(4)**2 - &
         x(1)*x(3) + x(3)*x(4) - x(1) - 3.0_wp*x(2) + x(3) - x(4)

        IF (PRESENT(obj_grad)) THEN
          obj_grad(1) = 2.0_wp*x(1) - x(3) - 1.0_wp
          obj_grad(2) = x(2) - 3.0_wp
          obj_grad(3) = 2.0_wp*x(3) - x(1) + x(4) + 1.0_wp
          obj_grad(4) = x(4) + x(3) - 1.0_wp
        END IF
      END SUBROUTINE obj_fun

    END MODULE nlp_ex04_mod

    PROGRAM nag_nlp_ex04

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

      ! .. Use Statements ..
      USE nag_examples_io, ONLY : nag_std_in, nag_std_out
      USE nag_nlp, ONLY : nag_nlp_sol, nag_nlp_cntrl_init, &
       nag_nlp_cntrl_wp => nag_nlp_cntrl_dp
      USE nlp_ex04_mod, ONLY : obj_fun, wp
      ! .. Implicit None Statement ..
      IMPLICIT NONE
      ! .. Parameters ..
      INTEGER, PARAMETER :: m = 3, n = 4
      ! .. Local Scalars ..
      INTEGER :: i
      REAL (wp) :: obj_f
      TYPE (nag_nlp_cntrl_wp) :: control
      ! .. Local Arrays ..
      REAL (wp) :: a(m,n), lin_upper(m), x(n), x_lower(n)
      ! .. Executable Statements ..
      WRITE (nag_std_out,*) 'Example Program Results for nag_nlp_ex04'

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

      ! Read in problem data
      READ (nag_std_in,*) (a(i,:),i=1,m)
      READ (nag_std_in,*) lin_upper
      x_lower = 0.0_wp
      x = 0.5_wp

      ! Initialize control structure and set required control parameters

      CALL nag_nlp_cntrl_init(control)

      control%crash_tol = 0.1_wp
      control%linesearch_tol = 0.5_wp

      ! Solve the problem

      CALL nag_nlp_sol(obj_fun,x,obj_f,x_lower=x_lower,lin_upper=lin_upper, &
       a=a,control=control)

    END PROGRAM nag_nlp_ex04
