! By H.X. Chen 6 March 2014 at HKUST
! subroutine to read the inflow hydrograph file
subroutine inflow_read(ulog,uinflow)
use input_file_defs;use inflow_vars
implicit none
integer i,j,linct,nopulse
integer,intent(in)::ulog,uinflow
logical ans

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

write (ulog,*) 'inflow hydrograph file -->',inflowfil
write (ulog,*) '-- LISTING OF INFLOW HYDROGRAPH FILE --'	

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

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 (inflowcell(noinflow))
allocate (inflowht(noinflow,nopulse),inflowhq(noinflow,nopulse),inflowhcv(noinflow,nopulse))

do i=1,noinflow
    read (uinflow,*,err=520) inflowcell(i);linct=linct+1
    write (ulog,*)  inflowcell(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 inflow hydrograph successfully!'
close (uinflow)
return
301	continue
	write (*,*) '*** Error opening inflow hydrograph file *** 301'
	write (*,*) '--> ',trim(inflowfil)
	write (*,*) 'Check file location and name'
     	write (ulog,*) '*** Error opening inflow hydrograph file ***'
     	write (ulog,*) '--> ',trim(inflowfil)
     	write (ulog,*) 'Check file location and name'
	pause 'Press RETURN to exit'
	stop '301'
520	continue
  	write (*,*) 'Error reading inflow hydrograph file 520'
	write (*,*) '--> ',trim(inflowfil), 'at line ',linct
	write (*,*) 'Check file contents and organization'
  	write (ulog,*) 'Error reading inflow hydrograph file'
	write (ulog,*) '--> ',trim(inflowfil), 'at line ',linct
	write (ulog,*) 'Check file contents and organization'
	pause 'Press RETURN to exit'
	stop '520'
end