! By H.X. Chen 6 March 2014 at HKUST
! Edited by P. Shen 11 Dec 2015 at HKUST
! subroutine to read the outflow cell number
subroutine outflow_read(ulog,uoutflow)
use input_file_defs;use outflow_vars
implicit none
integer i,j,linct
integer,intent(in)::ulog,uoutflow
logical ans

outflowfil='outflow.txt'
inquire (file=trim(outflowfil),exist=ans)
if(ans) then
    open (uoutflow,file=trim(outflowfil),status='old',err=301)
    write (*,*) 'Opening default outflow cell file'
else
    write (*,*) 'Cannot locate default outflow cell file, <outflow.txt>'
    write (*,*) 'Type name of outflow cell file and'
    write (*,*) 'press RETURN to continue'
    read (*,'(a)') outflowfil
    open (uoutflow,file=trim(outflowfil),status='old',err=301)
end if

write (ulog,*) 'outflow cell file -->',outflowfil
write (ulog,*) '-- LISTING OF OUTFLOW CELL FILE --'	

!! write copy of data to log file
!linct=1
!read (uoutflow,'(a)',err=520) heading;linct=linct+1
!read (uoutflow,*,err=520) otout;linct=linct+1
!write (ulog,*) heading
!write (ulog,*) otout

read (uoutflow,'(a)',err=520) heading;linct=linct+1
read (uoutflow,*,err=520) nooutflow;linct=linct+1
write (ulog,*) heading
write (ulog,*) nooutflow

!read (uinflow,'(a)',err=520) heading;linct=linct+1
!read (uinflow,*,err=520) inflowperiod,inflowdt;linct=linct+1
!write (ulog,*) heading
!write (ulog,*) inflowperiod,inflowdt
!nopulse=int(inflowperiod/inflowdt)+1
!write (ulog,*) 'The number of inflow pulse is',nopulse

allocate (outflowcell(nooutflow))
!allocate (inflowht(noinflow,nopulse),inflowhq(noinflow,nopulse),inflowhcv(noinflow,nopulse))

do i=1,nooutflow
    read (uoutflow,*,err=520) outflowcell(i);linct=linct+1
    write (ulog,*)  outflowcell(i)

!    do j=1,nopulse
!        read (uinflow,*,err=520) inflowht(i,j),inflowhq(i,j),inflowhcv(i,j);linct=linct+1
!        write (ulog,*)  inflowht(i,j),inflowhq(i,j),inflowhcv(i,j)
!    end do
!
!    ! report if error occurs
!    if (inflowht(i,nopulse)/=inflowperiod) then
!    write (*,*) 'The period of the inflow hydrograph of cell',inflowcell(i),'is not equal to the specified inflow period'
!    pause 'Please check!'
!    stop
!    end if
    
end do

write (ulog,*) 'Read the outflow cell successfully!'
close (uoutflow)
return
301	continue
	write (*,*) '*** Error opening outflow cell file *** 301'
	write (*,*) '--> ',trim(outflowfil)
	write (*,*) 'Check file location and name'
     	write (ulog,*) '*** Error opening outflow cell file ***'
     	write (ulog,*) '--> ',trim(outflowfil)
     	write (ulog,*) 'Check file location and name'
	pause 'Press RETURN to exit'
	stop '301'
520	continue
  	write (*,*) 'Error reading outflow cell file 520'
	write (*,*) '--> ',trim(outflowfil), 'at line ',linct
	write (*,*) 'Check file contents and organization'
  	write (ulog,*) 'Error reading outflow cell file'
	write (ulog,*) '--> ',trim(outflowfil), 'at line ',linct
	write (ulog,*) 'Check file contents and organization'
	pause 'Press RETURN to exit'
	stop '520'
end