!------------------------------------------------------------------------------
!
!  Program name:
!
!    opt_par
!
!  Purpose:
!
!    This program calls a function to sum all of the integers
!    between min and max. Set min and max to be optional keyword
!    arguments which default to 1 and 10 respectively.
!
!------------------------------------------------------------------------------

Program opt_par

  IMPLICIT NONE
  INTEGER :: result

  ! Version 1: min and max not specified, so use default values.
  result = isum()
  WRITE (*,*) 'Result for min = 1 and max = 10 is ', result

  ! Version 2: min not specified.
  result = isum(max=5)
  WRITE (*,*) 'Result for min = 1 and max = 5  is ', result

  ! Version 3: max not specified.
  result = isum(min=5)
  WRITE (*,*) 'Result for min = 5 and max = 10 is ', result

  ! Version 4: both specified.
  result = isum(max=7,min=5)
  WRITE (*,*) 'Result for min = 5 and max = 7  is ', result

CONTAINS

  INTEGER FUNCTION isum(min, max)   ! A funtion to sum all of the integer
                                    ! between min and max.
    INTEGER, INTENT(IN), OPTIONAL :: min, max   ! Set min and max to be 
                                                ! optional keyword

    INTEGER :: i, tmin, tmax
  
    ! If min or max not set, set to default:

    IF (PRESENT(min)) THEN
      tmin=min
    ELSE
      tmin=1
    ENDIF

    IF (PRESENT(max)) THEN
      tmax=max
    ELSE
      tmax=10
    ENDIF


    isum = 0                        ! preset isum as zero

    DO i = tmin, tmax
      isum = isum + i               ! sum between min and max
    END DO

  END FUNCTION isum

END PROGRAM opt_par

