module OW_pspi_areal

use OW_type
use OW_parms_areal
use OW_wei_areal
use OW_image_areal

implicit none

!public						:: owpspi_init, owpspi
private						:: ni,ixs,nwb,node,vsal

integer						:: ni,ixs,nwb,node
real						:: wb

contains

!---------------------------------------------------------
subroutine owpspi_init(ni_in,ixs_in,wb_in,node_in)

integer						:: ni_in,ixs_in,node_in
real						:: wb_in

ni=ni_in
ixs=ixs_in
node=node_in
wb=wb_in
wb=floor(wb/img%z%d)*img%z%d
nwb=floor(wb/img%z%d)+1

end subroutine
!---------------------------------------------------------
subroutine owpspi(taper,recv,source,vsal,vel,G1)

integer					:: iw,inode,ino,i1,nout
real					:: vel(:,:),vsal,taper(:)
complex					:: recv(:,:),source(:,:,:),G1(:,:,:)
complex, allocatable			:: GG(:,:,:,:),GGr(:,:),GGs(:,:),GG1(:,:),GG2(:,:)

integer, external			:: omp_get_thread_num

allocate(GG(img%z%n,img%sh%n,img%xm%n,node))
if (allocated(GG1)) deallocate(GG1); allocate(GG1(img%z%n,img%xm%n)); GG1=0
if (allocated(GG2)) deallocate(GG2); allocate(GG2(img%z%n,img%xm%n)); GG2=0

!write(0,*) size(GG,4)

!if (exist_file("wr")) then
!   if (allocated(rwr)) deallocate(rwr);allocate(rwr(img%z%n,rec%h%n));		rwr=0
!   if (allocated(rws)) deallocate(rws);allocate(rws(rec%w%n,img%z%n,rec%h%n));		rws=0
!   write(0,*) "rwr and rws allocated"
!end if

! $OMP parallel default(shared) private(inode) ! num_threads(8)

       inode=omp_get_thread_num()+1;

! $OMP do private(iw)
do iw = 1,rec%w%n
        if (allocated(GGr)) deallocate(GGr); allocate(GGr(img%z%n,img%xm%n)); GGr=0
        if (allocated(GGs)) deallocate(GGs); allocate(GGs(img%z%n,img%xm%n)); GGs=0

        call owwei_init(ni,iw,wb,nwb,node,inode)
!        call owwei(taper,recv,source,vsal,vel,GG(:,:,:,inode),rwr)
        call owwei(taper,recv,source,vsal,vel,GGr,GGs)

        GG1=GG1+GGr
        GG2=GG2+GGs

!         if (exist_file("wr")) then
!           rws(iw,:,:)=rws(iw,:,:)+rwr
!        end if

! $OMP critical
!        G1(:,:,:)=G1(:,:,:)+GG(:,:,:,inode)
! $OMP end critical   
        if (mod(iw,10)==1) write(0,5) " FREQUENCY # ",iw," OUT OF ",rec%w%n," / SYNTH.FCT. # ",rec%x%n, &

					" FROM NODE: ",inode
end do

if (exist_file("wr")) call srite("wr",GG1,4*img%z%n*img%xm%n)
if (exist_file("ws")) call srite("ws",GG2,4*img%z%n*img%xm%n)


call owimage1(GG1,GG2,G1)

! $OMP End do
! $OMP end parallel

!if (exist_file("wr")) then
!   nout=8*rec%h%n*img%z%n*rec%w%n
!   write(0,*) "writing rws" 
!    call srite("wr",rws,nout)
!end if

5 format(A13,i3,A8,i3,A14,i3,A12,i3)

end subroutine owpspi
end module
