PROGRAM Optional_Keyword_Argument_Demo
!-----------------------------------------------------------------------
! Program to demonstrate the use of optional arguments and keyword
! arguments.
!
! Input:  None
! Output: Values of function Polynomial for various arguments
!-----------------------------------------------------------------------

  IMPLICIT NONE

  PRINT *, "Ordinary function references:"
  PRINT *, "============================="
  PRINT *, "Polynomial(2.5, 1.5, 2.0, 3.0, -1.0, 7.2) =", &
           Polynomial(2.5, 1.5, 2.0, 3.0, -1.0, 7.2)
  PRINT *, "Polynomial(2.5, 1.0, 2.0, 0.0, 0.0, 0.0) =", &
           Polynomial(2.5, 1.0, 2.0, 0.0, 0.0, 0.0)

  PRINT *
  PRINT *, "References with missing arguments:"
  PRINT *, "=================================="
  PRINT *, "Polynomial(2.5, 1.0, 2.0) =", &
           Polynomial(2.5, 1.0, 2.0)
  PRINT *, "Polynomial(2.5, 1.0) =", &
           Polynomial(2.5, 1.0)

  PRINT *
  PRINT *, "References with keyword arguments:"
  PRINT *, "================================="
  PRINT *, "Polynomial(X = 2.5, A = 2.0, E = 1.0) =", &
           Polynomial(X = 2.5, A = 2.0, E = 1.0)
  PRINT *, "Polynomial(E = 1.0, A = 2.0, X = 2.5) =", &
           Polynomial(E = 1.0, A = 2.0, X = 2.5)
  PRINT *, "Polynomial(2.5, 2.0, E = 1.0) =", &
           Polynomial(2.5, 2.0, E = 1.0)

CONTAINS

  !--Polynomial---------------------------------------------------------
  ! Function to evaluate any polynomial of degree <= 4:
  !                      2     3     4
  !           A + BX + CX  + DX  + EX
  !
  ! Accepts:  X value, and coefficients A, B, C, D, E;  B, C, D, and E
  !             are optional.
  ! Returns:  Value of Polynomial at X
  !---------------------------------------------------------------------

  FUNCTION Polynomial(X, A, B, C, D, E)

    REAL :: Polynomial
    REAL, INTENT(IN) :: X, A
    REAL, INTENT(IN), OPTIONAL :: B, C, D, E

    Polynomial = A
    IF (PRESENT(B)) Polynomial = Polynomial + B*X
    IF (PRESENT(C)) Polynomial = Polynomial + C*X**2
    IF (PRESENT(D)) Polynomial = Polynomial + D*X**3
    IF (PRESENT(E)) Polynomial = Polynomial + E*X**4

  END FUNCTION Polynomial

END PROGRAM Optional_Keyword_Argument_Demo
