! Copyright 2022, Francois BOUCHUT, Anne MANGENEY, Marc PERUZZETTO, Antoine LUCAS,  Jacques SAINTE-MARIE
! This program is distributed under the terms of the Lesser GPL v3
! This file is part of SHALTOP-2D.


module loop

  use parameters
  use states
  use topography
  use flux
  use write

  implicit double precision (a-h,o-z)

  integer :: l
  
  
contains
  
  subroutine loop_time_step(nim)
    integer, intent(in) :: nim !index of next image records

    !nn = min(n1, n2)
    vmax=maxval((/((absvp(i,j)*max(thet(i,j),thet(i+1,j))&
         & ,i=0,nx),j=1,ny)/))
    vymax=maxval((/((aybsvp(i,j)*max(thet(i,j),thet(i,j+1))&
         & ,i=1,nx),j=0,ny)/))
    delt=min(cflhyp*delx/vmax,cflhyp*dely/vymax,deltmax)

    !Limit time step at beginning of simulation if input discharge is used
    if ((temps.lt.temps_init).and.(i_rho_source.gt.0)) then
       delt=min(delt,deltmax_init)
    end if

    !Limit time step not to overrun tmax
    if (temps+delt.gt.tmax) delt=tmax-temps

    !Limit time step to get simulation outputs at equal time intervals
    delt_im = tmax*nim/nbim-temps
    delt = min(delt_im, delt)
    write_im_bool = ((delt_im-delt).lt.1.d-15)
    
    sig=delt/delx
    sigy=delt/dely
    
  end subroutine loop_time_step
  
end module loop
