! Program Example from "Essential Fortran 90 & 95" by Loren P. Meissner
! Copyright 1996. Copying for sale requires permission from the author.
! Otherwise, distribution is permitted if these three lines are included.

  module F18M
    implicit none
    public :: Find
  contains
    subroutine Find( Vec, E, L_Size )
      real, dimension (:), intent (in out) :: Vec  ! List
      real, intent (in) :: E  ! Element to find or insert in list
      integer, intent (in out) :: L_Size  ! Current list size
      integer, dimension(1) :: Loc  ! To hold result from MinLoc
  ! start subroutine Find
      if (any( Vec(: L_Size - 1) == E )) then
        Loc = minloc( Vec(: L_Size - 1), Vec(: L_Size - 1) == E ) ! Find an element that matches E.
        write (unit = *, fmt = *) " Found: ", E, " at ", Loc(1), " of ", L_Size
      else  ! No matching element; insert E.
        if (L_Size >= size( Vec )) then
          write (unit = *, fmt = *) " Array is full "
          stop
        end if
        L_Size = L_Size + 1  ! Adjust current size.
        if (any( Vec(: L_Size - 1) > E )) then  ! If any elements > E...
          Loc = minloc( Vec(: L_Size - 1), Vec(: L_Size - 1) > E )  ! find the smallest.
          ! Move all elements beyond Loc(1) to make space.
          Vec(Loc(1) + 1: L_Size) =  Vec(Loc(1): L_Size - 1)
        else
          Loc(1) = L_Size  ! Append at end of list.
        end if
        Vec(Loc(1)) = E  ! Insert at Loc(1).
        write (unit = *, fmt = *) " Inserted: ", E, " at ", Loc(1), " of ", L_Size
      end if
      return
    end subroutine Find
  end module F18M

