module wei_work_mod
  use sep
  use wei_step_mod
  implicit none
  



  contains


  
  subroutine initial_work(wave,iws,izs)
    type(wspace)  :: wave
    integer, pointer  :: iws(:,:),izs(:,:)

#ifdef DEBUG
    write(0,*) "IN INITIAL WORK"
#endif

    call from_param("finished",wave%finished,0)
    allocate(iws(wave%nth,wave%nth),izs(wave%nzb,wave%nth))

#ifdef DEBUG
    write(0,*) "OUT INITIAL WORK"
#endif

  end subroutine


  logical function grab_next_ws_mig(step,iws,nwb)
    type(westep)      :: step
    integer, pointer  :: iws(:,:)
    integer           :: iwdone,i,nwb

#ifdef DEBUG
    write(0,*) "IN GRAB NEXT WS MIG"
#endif

    iwdone=(step%wave%finished/size(step%wave%dz))/step%wave%nth
    if(size(step%wave%dz) *size(step%wave%ws) <= step%wave%finished) then
      grab_next_ws_mig=.false.
    else
      grab_next_ws_mig=.true.
      nwb=min(size(step%wave%ws)-iwdone*step%wave%nth,step%wave%nth)
      do i=1,nwb
        iws(i,step%ithread)=i+iwdone*step%wave%nth
      end do
    end if
    
#ifdef DEBUG
    write(0,*) "OUT GRAB NEXT WS MIG"
#endif

  end function



  logical function grab_next_dzs_mig(step,izs,nzb)
    type(westep)      :: step
    integer, pointer  :: izs(:,:)
    integer           :: iwdone,izdone,nzb,i

#ifdef DEBUG
    write(0,*) "IN GRAB NEXT DZS MIG"
#endif

    iwdone=(step%wave%finished/size(step%wave%dz))/step%wave%nth
    izdone=(step%wave%finished-iwdone*step%wave%nth*size(step%wave%dz))/step%wave%nth
    

    grab_next_dzs_mig=.true.
    nzb=min(size(step%wave%dz)-izdone,step%wave%nzb)
    do i=1,nzb
      izs(i,step%ithread)=i+izdone
    end do
  
#ifdef DEBUG
    write(0,*) "OUT GRAB NEXT DZS MIG"
#endif

  end function



  subroutine update_finished(space,nblock,tag)
    type(wspace)      :: space
    integer           :: nblock
    character(len=*)  :: tag

    space%finished=space%finished+nblock
    call to_history("finished",space%finished,tag)
      
  end subroutine












end module
