program newunitbug
	implicit none
	integer :: i, j, k
	integer :: fileUnit1, fileUnit2
	integer :: istat
	integer :: val
	logical :: isopen
	character(len=64) :: fileName
	real :: start, finish
	
	do i = 1, 100
		open(newunit=fileUnit1,file='ExistingFile.txt', status='old', action='read', iostat=istat)
		write(*,*) 'fileUnit1=',fileUnit1
		if (istat .ne. 0) then
			write(*,*) 'failed to open on iter i=',i
			write(*,*) 'iostat=',istat
			write(*,*) 'open files:'
			do k = -1, -32000, -1
				inquire(unit=k, opened=isopen, name=fileName)
				if (isopen) write(*,*) k,fileName
			end do
			stop
		end if
		
		call cpu_time(start)
		do j = 1, 1000
			call OpenNonExistantFileNoClose()
			!call OpenNonExistantFileWithClose()
			!call OpenExistantFileWithClose()
		end do
		call cpu_time(finish)
		
		write(*,'(A,F10.3)') 'inner loop time (s):',finish-start
		close(fileUnit1)
	end do
	write(*,*) 'program finished'
	
contains

	subroutine OpenNonExistantFileNoClose()
		integer :: istat, fileUnit2
		open(newunit=fileUnit2,file='WontExist.txt', status='old', action='read', iostat=istat)
		if (istat .ne. 0) return
		close(fileUnit2)
	end subroutine OpenNonExistantFileNoClose
	
	subroutine OpenNonExistantFileWithClose()
		integer :: istat, fileUnit2
		open(newunit=fileUnit2,file='WontExist.txt', status='old', action='read', iostat=istat)
		close(fileUnit2)
	end subroutine OpenNonExistantFileWithClose
	
	subroutine OpenExistantFileWithClose()
		integer :: istat, fileUnit2
		open(newunit=fileUnit2,file='ExistingFile.txt', status='old', action='read', iostat=istat)
		close(fileUnit2)
	end subroutine OpenExistantFileWithClose
end program newunitbug