module OWmig_mod

use sep
use OW_grabvel2_areal
use OW_exec_time
use OW_parms_areal
use OW_taper_areal
use OW_wei_areal
use lloyd_vel
use base_spline_mod
use OW_mpi

implicit none
integer, public, save                  :: iter,realz
real, private, allocatable             :: taper(:,:)

contains 
!---------------------------------------------------------------------
subroutine steep_mpi_init()
integer                  :: i, i_r

    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    ! Set up the taper
    allocate(taper(kxm%n,kym%n));taper=0.
    call owtaper(taper)

end subroutine
!---------------------------------------------------------------------
subroutine steep_mpi_close()
  if (allocated(taper)) deallocate(taper)
end subroutine
!---------------------------------------------------------------------
subroutine fgeval_init(iter_in)
 integer                     :: iter_in
 iter=iter_in

 if (nreal.ne.1) then
    realz=mod(iter,nreal)
 else
    realz=1
 end if

end subroutine

!---------------------------------------------------------------------
subroutine init_files()
integer            :: i,j,k
real,allocatable   :: a(:)

allocate(a(kxm%n*kym%n*nsecdimx*nsecdimy)); a=0
do i=1,img%z%n
   call srite("bkgimg",a,4*kxm%n*kym%n*nsecdimx*nsecdimy)
end do
deallocate(a)
end subroutine
!---------------------------------------------------------------------
subroutine fgeval(vel0,riteD,wsave)

logical                            :: riteD,wsave
real                               :: vel0(:)
!---
integer                            :: idip
real                               :: start2,finish2

    do idip=1,shtblk
       call feval_exe(idip,vel0,riteD,wsave)
    end do

end subroutine
!---------------------------------------------------------------------
subroutine feval_exe(idip,vel0,riteD,wsave)

real                                          :: start, finish, start1, finish1, vel0(:)
integer                                       :: idip,ireal
real, allocatable                             :: vref(:,:,:)
logical                                       :: riteD,wsave
integer                                       :: izb,i_r,status,ierr

       if (wpar%i_mpi > 0) then
          if (extrap(1:4).eq."pspi") then
             if (lloyd) then 
               allocate(vref(nref,2,img%z%n))
               call lloyd_vel1(vel0,vref)
             end if
          end if
       end if
       !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
       ! Computing bkg.image
       call owexec_time(start)
       call owwei_init(idip,1)
       if (lloyd) then
          call owwei(taper=taper,vel=vel0,sref=vref,wsave=wsave)
       else
          call owwei(taper=taper,vel=vel0,wsave=wsave)
       end if

       call owexec_time(finish)
       write(3,112) "COMPUTED BACKGROUND IMAGE IN ",(finish-start)/60," min"

 111 format(a7,i4,a8,i4,a4,f6.2,a4)
 112 format(a29,f10.2,a4)
end subroutine
!---------------------------------------------------------------------
end module
