!+ Subroutine to get a free unit for I/O
!
! Purpose:
!   The obtains the next free unit beyond the number supplied:
!   the routine then cycles to the lowest available number if
!   higher numbers are not free, but returns an error if no
!   free units can be found.
!
! Method:
!   The INQUIRE statement is used.
!
! Current Owner of Code: J. M. Edwards
!
! History:
!       Version         Date                    Comment
!       1.0             12-04-95                First Version under RCS
!                                               (J. M. Edwards)
!
! Description of Code:
!   FORTRAN 77  with extensions listed in documentation.
!
!- ---------------------------------------------------------------------
      SUBROUTINE Get_free_unit(ierr, iunit_start, iunit_free)
!
!
!
      IMPLICIT NONE
!
!
!     Include Modules setting parameters.
      INCLUDE 'incl/def_std_io.icf
!
!
!     Dummy arguments
      INTEGER	!, INTENT(OUT)
     &     ierr
!             Error Flag
      INTEGER	!, INTENT(IN)
     &     iunit_start
!             The unit number at which to begin searching.
      INTEGER	!, INTENT(OUT)
     &     iunit_free
!             The free unit number.
!
!
!     Local Variables
      LOGICAL l_open
!        Flag set to .TRUE. if a unit is open.
      LOGICAL l_cycle
!        Flag set to .TRUE. once re-cycling begins
      LOGICAL l_exhausted
!        FLag set to .TRUE. if all unit numbers are exhausted
      INTEGER iunit_in
!        Number of unit supplied.

!
!
!
!     Record the initial unit for checking.
      iunit_in=iunit
!
!     Initialize to check the unit supplied, excluding reserved units
!     with low numbers.
      l_open=.TRUE.
      l_cycle=.FALSE.
      l_exhausted=.FALSE.
      iunit=MAX(iunit, IP_UNIT_USER_LOW)
      iunit=iunit-1
!
!
      DO WHILE ( l_open.AND.(.NOT.l_exhausted) )
!
         IF (iunit.LT.IP_UNIT_USER_HIGH) THEN
            iunit=iunit+1
         ELSE
!           Cycle to bottom of range of allowed units.
            l_cycle=.TRUE.
            iunit=IP_UNIT_USER_LOW
         ENDIF
!
         IF ( l_cycle.AND.(iunit.EQ.iunit_in) ) THEN
!           All unit numbers have been exhausted, since the routine
!           is about to recheck the first unit supplied.
            l_exhausted=.TRUE.
            WRITE(IU_ERR, '(/A)') 
     &         '*** Error: There is no remaining free unit.'
            IERR=I_ERR_IO
         ELSE
            INQUIRE(UNIT=iunit, OPEN=l_open)
         ENDIF
!
      ENDDO
!
!
!
      RETURN
      END
