module OW_pspi_areal

use OW_type
use OW_parms_areal
use OW_wei_areal
use OW_image_areal
use OW_exec_time

implicit none

private						:: ni,ixs
integer						:: ni,ixs

contains

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

integer						:: ni_in,ixs_in

ni=ni_in
ixs=ixs_in

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

integer					:: iw,inode,ino,i1,i2,nout,iwind
real					:: vel(:,:),vsal,taper(:),deltaS(:,:)
complex					:: recv(:,:),source(:,:)
complex, allocatable			:: GG(:,:,:,:),GGr(:,:,:),GGs(:,:,:)
real, allocatable				:: G2(:,:,:),G1(:,:,:)
real					:: start, finish

integer, external				:: omp_get_thread_num

!allocate(GG(img%z%n,img%sh%n,img%xm%n,node))

allocate(G2(img%z%n,img%sh%n,img%xm%n));G2=0.

! $OMP parallel default(shared) private(inode) ! num_threads(8)
       inode=omp_get_thread_num()+1;
! $OMP do private(iw)

   if (exist_file("ws")) then
      allocate(GGr(img%z%n,img%xm%n,rec%w%n)); GGr=0
      allocate(GGs(img%z%n,img%xm%n,rec%w%n)); GGs=0
   end if

   call owexec_time(start)
   do iw = 1,rec%w%n
      call owwei_init(ni,iw)
      if (exist_file("ws")) then
         call owwei(taper,recv(:,iw),source(:,iw),vsal,vel,deltaS,G2,GGr(:,:,iw),GGs(:,:,iw))
      else 
         call owwei(taper,recv(:,iw),source(:,iw),vsal,vel,deltaS,G2)
      end if
      G1=G1+G2

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

   call owexec_time(finish)

   if (exist_file("wr") .and. ixs.eq.1) call srite("wr",GGr,8*img%z%n*img%xm%n*rec%w%n)
   if (exist_file("ws") .and. ixs.eq.1) call srite("ws",GGs,8*img%z%n*img%xm%n*rec%w%n)

   if (exist_file("ws")) then
      deallocate(GGr,GGs)
   end if

! $OMP End do
! $OMP end parallel

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

end subroutine owpspi
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
end module
