program OWmig2d_par

use sep 
use OW_pspi
use OW_fftw
use OW_type
use OW_exec_time
use OW_parms
use OW_sumimg


implicit none

real						:: start_time, finish_time
integer						:: ixs,ino,ni,isp,inode,node
real, allocatable				:: velint(:,:)
complex 					:: ws(:),wr(:)
complex, allocatable				:: recv(:,:),source(:,:,:),image(:,:,:),GG(:,:,:,:)

integer, external 				:: omp_get_thread_num,omp_get_num_threads,omp_get_num_procs

 call sep_init()
 call sep_begin_prog()

node=omp_get_num_threads()
write(0,*) 'node = ',node

start_time=0.;finish_time=0.
call owexec_time(start_time)
!---------------------------------------
! IO
!
 call owparam()

allocate(recv(rec%h%n,rec%w%n),source(sou%h%n,sou%w%n,sou%x%n),velint(v%z%n,v%xm%n))
allocate(image(img%z%n,img%sh%n,img%xm%n),GG(v%z%n,rec%x%n,rec%h%n,node))

!--------------------------------------------------
! Setting FFTW plans
!
call owfftw()

!--------------------------------------------------
! Reading source fctn and velocity
 call sreed("sou",source,sou%h%n*sou%w%n*sou%x%n*8)
 call sreed("vel",velint,v%z%n*v%xm%n*4)

call owexec_time(finish_time)
write(0,'(8x,a,f10.2,a)')' Init.phase - Total elapsed time:', (finish_time - start_time),' (sec)'

!--------------------------------------------------
!
!
write(0,*) "DOWNWARD CONTINUES SOURCES AND RECEIVERS"
write(0,*) "========================================"

!--------------------------------------------------
! shot position in the acq.geom.
isp = abs(floor(rec%h%o/rec%h%d)) + 1

!--------------------------------------------------
! Migrating
!
!-----------------------------------------------------------------------------------------------      
!$OMP parallel do default(shared) private(inode,ixs,start,finish,start,vel,ni,recv,ws,wr,GG,image,finish)   
shot:do ixs=1,rec%x%n

    inode=omp_get_thread_num();
    GG=0.

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

    call owgrab_vel(ixs,velint,vel,ni)

    call sreed("in",recv,8*rec%h%n*rec%w%n)

    call owpspi (isp,ni,recv,source,vel,ws,wr)
    call owimage(ws,wr,image,GG) 
    call owsum_img(ni,node,GG,image)

    call owexec_time(finish)
    write(0,*) " DONE SHOT # ",ixs," OUT OF ",rec%x%n," in ", (finish - start)/60./60.," (hrs)"

end do shot
!$OMP end parallel do

call srite("out",real(image),4*img%z%n*img%sh%n*img%xm%n)

call sep_end_prog()
end program OWmig2d_par
