module OW_pspi1

use OW_type
use OW_parms
use OW_wei

implicit none

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

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

contains

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

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

isp=isp_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(:,:,:)!,tfld(:)
complex, allocatable			:: GG(:,:,:,:),rwr(:,:),rws(:,:,:)

integer, external			:: omp_get_thread_num

allocate(GG(img%z%n,img%sh%n,rec%h%n,node))!rec%w%n))

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

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

        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," / SHOT # ",ixs, &
					" FROM NODE: ",inode,maxval(cabs(GG(:,1,floor(rec%h%n/2.),inode)))

end do
! $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,A10,i3,A12,i3,f20.5)

end subroutine owpspi
end module
