!******************************************************************************
! 2003/07/25
!******************************************************************************
!
! If this subroutine finish correctly, ios = 0. 
!
!******************************************************************************
! Example:
!
!      interface 
!         subroutine findfu( fn, ios, fu, mode )
!           use vtype_module
!           implicit none
!           character(len=*), intent(in )           :: fn
!           integer(i4b)    , intent(out)           :: ios, fu
!           character(len=*), intent(in ), optional :: mode
!         end subroutine findfu
!      end interface
!
!
!      use vtype
!      character(len=stdstr) :: fn
!      integer(i4b)          :: ios, fu
!      character(len=stdstr) :: mode
!
!      fn = "file"
!      call findfu( fn, ios, un, mode )
!      if( ios /= 0 ) then
!         write( 6, * ) 'STOP in parse_ctl: ', ios
!         stop
!      end if
!      open( unit = un, file = fn, status = "unknown", iostat = ios )
!
!******************************************************************************

  subroutine findfu( fn, ios, fu, mode )

    use vtype_module

    implicit none

    character(len=*), intent(in )           :: fn
    integer(i4b)    , intent(out)           :: ios, fu
    character(len=*), intent(in ), optional :: mode


    ! Local variables
    logical            :: od, ex
    integer, parameter :: fus = 11, fue = 99


    if( present( mode ) ) then
       if( mode .ne. "read" ) then
          write( 6, * ) 'Now, mode of "', trim( mode ), '" is not supported.'
          stop
       end if
    end if


    inquire( file = fn, opened = od, exist = ex )

    if( present( mode ) ) then
       if( ( mode .eq. "read" ) .and. ( .not. ex ) ) go to 903
    end if

    if( od ) goto 901


    do fu = fus, fue
       inquire( unit = fu, opened = od, iostat = ios )
       if( .not. od ) goto 101
    end do
    goto 902
101 continue

    ios = 0

    return


901 continue
    write( 6, * ) 'ERROR: In findfu: File ', trim( fn ), ' is open.'
    ios = 901
    fu = -1
    return

902 continue
    write( 6, * ) 'ERROR: In findfu: Unable to find a file unit.'
    ios = 902
    fu = -1
    return

903 continue
    write( 6, * ) 'ERROR: In findfu: File ', trim( fn ), ' does not exist.'
    ios = 903
    fu = -1
    return

  end subroutine findfu
