program OWmig2d_areal

use sep 
use OW_type
use OW_grabvel_areal
use OW_exec_time
use OW_parms_areal
use OW_taper_areal
use OW_wei_areal

implicit none

real						:: start, finish, start1, finish1, o3,a
integer						:: ixs,ino,ni,i,st,idip
real, allocatable					:: velint(:,:),taper(:)
real, allocatable					:: R_image(:,:,:)
real, allocatable					:: vel(:,:),vref(:,:,:)
complex, allocatable				:: recv(:,:),source(:,:)
real,allocatable					:: deltaI(:,:,:)

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
 call sep_init()
 call sep_begin_prog()

 start=0.;finish=0.
 call owexec_time(start)

 call owparam()

 allocate(source(sou%h%n,sou%w%n))
 allocate(recv(rec%h%n,rec%w%n))
 allocate(R_image(nz,img%sh%n,img%xm%n));R_image=0.
 allocate(deltaI(nz,img%sh%n,img%xm%n));deltaI=0.
 allocate(taper(img%xm%n))
 call owtaper(tapertr,taper)

 allocate(velint(v%z%n,v%xm%n),vel(v%z%n,img%xm%n))
 call sreed("vel",velint,v%z%n*v%xm%n*4)
 if (exist_file("vref")) then
   allocate(vref(nref,2,v%z%n))
   call sreed("vref",vref,v%z%n*2*nref*4)
 end if
 call owgrab_vel(velint,vel,ni)

 deallocate(velint)
 call owexec_time(finish)
 write(0,'(8x,a,f10.2,a)')' Init.phase - Total elapsed time:', (finish - start),' (sec)'

! Computing bkg.image

       do idip=1,rec%xd%n
          start=0.;finish=0. 
          call owexec_time(start)
          recv=0;source=0;deltaI=0
          call sreed("sou",source,8*sou%h%n*sou%w%n)
          call sreed("in",recv,8*rec%h%n*rec%w%n)
          if (exist_file("vref")) then
             call owwei(taper,recv,source,vel,deltaI,vref)
          else
             call owwei(taper,recv,source,vel,deltaI)
          end if
          R_image=R_image+deltaI
          call owexec_time(finish)
          write(0,111) "EXTRAPOLATED WAVEFIELDS = ",idip," OUT OF ",rec%xd%n," IN ",(finish-start)/60," min"
       end do

       call srite("out",R_image(:,:,tapertr+padtraces+1:img%xm%n-tapertr+padtraces), &
                    4*nz*img%sh%n*(img%xm%n-2*(tapertr+padtraces)))

 111 format(a26,i4,a8,i4,a4,f6.2,a4)


 deallocate(source)
 deallocate(recv)
 deallocate(R_image,deltaI)
 deallocate(taper)
 deallocate(vel)
 if (exist_file("vref")) then
    deallocate(vref)
 end if
 call sep_end_prog()

end program OWmig2d_areal
