    MODULE nlin_sys_ex02_mod

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

    CONTAINS

      SUBROUTINE fun(x,finish,f_vec,f_jac)

        ! .. Implicit None Statement ..
        IMPLICIT NONE
        ! .. Intrinsic Functions ..
        INTRINSIC PRESENT, SIZE
        ! .. Scalar Arguments ..
        LOGICAL, INTENT (INOUT) :: finish
        ! .. Array Arguments ..
        REAL (wp), OPTIONAL, INTENT (OUT) :: f_jac(:,:)
        REAL (wp), INTENT (OUT) :: f_vec(:)
        REAL (wp), INTENT (IN) :: x(:)
        ! .. Local Scalars ..
        INTEGER :: i, n
        ! .. Executable Statements ..
        n = SIZE(x)

        f_vec = (3.0_wp-2.0_wp*x)*x + 1.0_wp
        f_vec(2:n) = f_vec(2:n) - x(1:n-1)
        f_vec(1:n-1) = f_vec(1:n-1) - 2.0_wp*x(2:n)

        IF (PRESENT(f_jac)) THEN
          f_jac = 0.0_wp
          DO i = 1, n
            f_jac(i,i) = 3.0_wp - 4.0_wp*x(i)
            IF (i>1) f_jac(i,i-1) = -1.0_wp
            IF (i<n) f_jac(i,i+1) = -2.0_wp
          END DO
        END IF

      END SUBROUTINE fun

    END MODULE nlin_sys_ex02_mod

    PROGRAM nag_nlin_sys_ex02

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

      ! .. Use Statements ..
      USE nag_examples_io, ONLY : nag_std_out
      USE nag_nlin_sys, ONLY : nag_nlin_sys_sol
      USE nlin_sys_ex02_mod, ONLY : fun, wp
      ! .. Implicit None Statement ..
      IMPLICIT NONE
      ! .. Parameters ..
      INTEGER, PARAMETER :: n = 9
      CHARACTER (*), PARAMETER :: fmt1 = '(/,1X,A,/,3(/,3F12.4))'
      CHARACTER (*), PARAMETER :: fmt2 = '(/,1X,A,I4)'
      ! .. Local Scalars ..
      INTEGER :: num_fun_eval, num_jac_eval
      ! .. Local Arrays ..
      REAL (wp) :: jac_check(n), x(n)
      ! .. Executable Statements ..
      WRITE (nag_std_out,*) 'Example Program Results for nag_nlin_sys_ex02'

      ! Starting values for the initial approximate solution
      x = -0.1_wp

      ! Solve the system of non-linear equations: Include the optional
      ! argument jac_check to measure the consistency of the function
      ! and the Jacobian

      CALL nag_nlin_sys_sol(fun,x,num_fun_eval=num_fun_eval, &
       num_jac_eval=num_jac_eval,jac_check=jac_check)

      WRITE (nag_std_out,fmt1) 'Final approximate solution', x
      WRITE (nag_std_out,fmt1) 'Jacobian consistency errors', jac_check
      WRITE (nag_std_out,fmt2) 'Number of function evaluations =', &
       num_fun_eval
      WRITE (nag_std_out,fmt2) 'Number of Jacobian evaluations =', &
       num_jac_eval

    END PROGRAM nag_nlin_sys_ex02
