! Module to manage file unit
module MW_fileunit
   implicit none
   private

   public :: get_new_unit

   integer, parameter :: min_unit = 10

contains

   ! Look for a valid unit to be used in an open statement
   subroutine get_new_unit(newunit)
      use MW_errors, only: MW_errors_runtime_error => runtime_error
      implicit none
      integer, intent(out) :: newunit  ! a valid unit number

      logical :: lexist, lopen

      newunit = min_unit
      inquire(unit=newunit, exist=lexist)
      do while (lexist)
         inquire(unit=newunit, opened=lopen)
         if (.not. lopen) exit
         newunit = newunit + 1
         inquire(unit=newunit, exist=lexist)
      end do

      if (.not. lexist) then
         call MW_errors_runtime_error('MW_fileunit_getNewUnit', 'fileunit.f90', &
               "All valid file units have been exhausted...")
      end if

   end subroutine get_new_unit

end module MW_fileunit
