module OW_pspi_

use OWvel
use OW_type
use OW_image
use OW_fftw
use wei_myfft_mod
use OW_grabvel
use OW_parms
use OW_imageIO

implicit none

public						:: owpspi_init, owpspi
private						:: isp,ixs

integer						:: isp,ixs
real						:: wb

contains

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

integer						:: isp_in,ixs_in
real						:: wb_in

isp=isp_in
ixs=ixs_in
wb=wb_in

end subroutine


!---------------------------------------------------------
subroutine owpspi(recv,source,vel,image,vref1) 

real,optional					:: vref1(:,:,:)
integer						:: iw,iz,ikx,iref,iref1,ixw,ish,ino,i,j,iv,ipath
integer						:: nv,ihso,nwb,inode,stat,nrefvel
integer						:: indref(1)
real						:: sign, sqa,a,dwb
real						:: minv, maxv,vw,vpath
real, allocatable					:: f(:),g(:),GG(:,:,:,:),vref(:)
complex, allocatable				:: ws(:,:),wr(:,:),gs0(:,:),gr0(:,:),as(:,:),ar(:,:)
complex,allocatable					:: tflds(:,:),tfldr(:,:),gs(:,:),gr(:,:)
complex						:: recv(:,:),source(:,:),phase
real						:: image(:,:,:),vel(:,:)
integer, external 					:: omp_get_thread_num,omp_get_num_threads

if (node.eq.9999) then
  !$OMP PARALLEL
  node = omp_get_num_threads()
  !$OMP END PARALLEL
write(0,*) " NUM.THREADS = ",node
end if

allocate(GG(kxm%n,img%sh%n,img%z%n,node))
allocate(ws(kxm%n,node)); ws=0.
allocate(wr(kxm%n,node)); wr=0.
allocate(gs0(kxm%n,node));gs0=0
allocate(gr0(kxm%n,node));gr0=0
allocate(f(node));f=0
allocate(g(node));g=0

!--------------------------------------------------
nwb=floor(wb/img%z%d)+1
dwb=nwb*img%z%d
if (nwb.ne.1) then
   vw=minval(vel(nwb-1,:))
   write(0,*) "DATUMING WITH VELOCITY = ",vw
end if
!--------------------------------------------------
! Setting FFTW plans
allocate(tflds(kxm%n,node));tflds=0
call owfftws(tflds,node)

allocate(tfldr(kxm%n,node));tfldr=0
call owfftwr(tfldr,node)

!$OMP parallel do private (inode,&
                             iw,&
                             iv,&
                             iz,&
                            ikx,&
                           iref,&
                          iref1,&
                            ish,&
                           ihso,&
                         indref,&
                            ixw,&
                          ipath,&
                          vpath,&
                            sqa,&
                           minv,&
                           vref,&
                             gr,&
                             gs,&
                             ar,&
                             as,&
                        nrefvel,&
                           maxv,&
                           phase) schedule(dynamic,1) num_threads(node)

omega:do iw = 1,rec%w%n-subf

        inode=omp_get_thread_num()+1; 
        ws(:,inode)=0;wr(:,inode)=0.
        ws(:,inode)=source(:,iw)
        wr(:,inode)=recv(:,iw) 


        if (nwb.ne.1) then

           tflds(:,inode)=ws(:,inode)
           call owfftexes(tflds(:,inode),inode)
           ws(:,inode)=tflds(:,inode)/sqrt(1.*kxm%n)

           tfldr(:,inode)=wr(:,inode)
           call owfftexer(tfldr(:,inode),inode)
           wr(:,inode)=tfldr(:,inode)/sqrt(1.*kxm%n)

           do ikx = 1,kxm%n
              sqa = rec%w%all(iw)**2 / vw**2 - kxm%all(ikx)**2
              if (sqa > 0) then
                 wr(ikx,inode)=wr(ikx,inode)*exp(cmplx(0,dwb*sqrt(sqa)))
                 ws(ikx,inode)=ws(ikx,inode)*exp(cmplx(0,-dwb*sqrt(sqa)))
              else
                 wr(ikx,inode)=wr(ikx,inode)*exp(-sqrt(-sqa)*dwb)
                 ws(ikx,inode)=ws(ikx,inode)*exp(-sqrt(-sqa)*dwb)
              end if
           end do

           tflds(:,inode)=ws(:,inode)
           call owifftexes(tflds(:,inode),inode)
           ws(:,inode)=tflds(:,inode)/sqrt(1.*kxm%n)

           tfldr(:,inode)=wr(:,inode)
           call owifftexer(tfldr(:,inode),inode)
           wr(:,inode)=tfldr(:,inode)/sqrt(1.*kxm%n)

!           wr(:,inode)=wr(:,inode)*taper
!           ws(:,inode)=ws(:,inode)*taper
        end if

        depth:do iz=nwb+1,img%z%n

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
! Compute vref
!
            if (present(vref1)) then
               nrefvel=count(mask = vref1(:,1,iz).ne.-1)
               if (allocated(vref)) deallocate(vref); allocate(vref(nrefvel))
               if (allocated(gs)) deallocate(gs); allocate(gs(kxm%n,nrefvel));
               if (allocated(gr)) deallocate(gr); allocate(gr(kxm%n,nrefvel));
               vref=1/vref1(:,1,iz); gs(:,:)=0; gr(:,:)=0
            else
               if (path) then
                  if (allocated(as)) deallocate(as); allocate(as(kxm%n,npath));
                  if (allocated(ar)) deallocate(ar); allocate(ar(kxm%n,npath));
                  as=0;ar=0
                  if (maxval(vel(iz,:)).ge.vsal) then
                     nrefvel=nref+npath
                     if (allocated(vref)) deallocate(vref); allocate(vref(nrefvel))
                     if (allocated(gs)) deallocate(gs); allocate(gs(kxm%n,nrefvel));
                     if (allocated(gr)) deallocate(gr); allocate(gr(kxm%n,nrefvel));
                     vref=0; gs(:,:)=0; gr(:,:)=0
                     call owvref(nref,vel(iz,:),vref(int(npath/2)+1:nref+int(npath/2)),minv,maxv)
                     if (npath .gt. 1) then
                     do iv=1,int(npath/2)
                        vref(iv)=minv*(1+(iv-int(npath/2)-1)*vrange/int(npath/2))
                        vref(nref+int(npath/2)+iv)=maxv*(1+(iv*vrange/int(npath/2)))
                     end do
                     end if
                     vref(nrefvel)=maxval(vel(iz,:))
                  else
                     nrefvel=nref+npath-1
                     if (allocated(vref)) deallocate(vref); allocate(vref(nrefvel))
                     if (allocated(gs)) deallocate(gs); allocate(gs(kxm%n,nrefvel));
                     if (allocated(gr)) deallocate(gr); allocate(gr(kxm%n,nrefvel));
                     vref=0; gs(:,:)=0; gr(:,:)=0
                     call owvref(nref,vel(iz,:),vref(int(npath/2)+1:nref+int(npath/2)),minv,maxv)
                     if (npath .gt. 1) then
                     do iv=1,int(npath/2)
                        vref(iv)=minv*(1+(iv-int(npath/2)-1)*vrange/int(npath/2))
                        vref(nref+int(npath/2)+iv)=maxv*(1+(iv*vrange/int(npath/2)))
                     end do
                     end if
                  end if
               else
                  if (maxval(vel(iz,:)).ge.vsal) then
                     nrefvel=nref+1
                     if (allocated(vref)) deallocate(vref); allocate(vref(nref+1))
                     if (allocated(gs)) deallocate(gs); allocate(gs(kxm%n,nref+1));
                     if (allocated(gr)) deallocate(gr); allocate(gr(kxm%n,nref+1));
                     vref=0; gs(:,:)=0; gr(:,:)=0
                     call owvref(nref,vel(iz,:),vref(1:nref),minv,maxv)
                     vref(nref+1)=maxval(vel(iz,:))
                  else 
                     nrefvel=nref
                     if (allocated(vref)) deallocate(vref); allocate(vref(nref))
                     if (allocated(gs)) deallocate(gs); allocate(gs(kxm%n,nref));
                     if (allocated(gr)) deallocate(gr); allocate(gr(kxm%n,nref));
                     vref=0; gs(:,:)=0; gr(:,:)=0
                     call owvref(nref,vel(iz,:),vref,minv,maxv)
                  end if
               end if
            end if
!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!  
            tflds(:,inode)=ws(:,inode)
            call owfftexes(tflds(:,inode),inode)
            ws(:,inode)=tflds(:,inode)/sqrt(1.*kxm%n)

            tfldr(:,inode)=wr(:,inode)
            call owfftexer(tfldr(:,inode),inode)
            wr(:,inode)=tfldr(:,inode)/sqrt(1.*kxm%n)
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
!      Propagate wavefields when velocity is constant 
!
          if ((minv .eq. maxv .and. maxv.eq.vref(size(vref))).or. &
              (path.and.minv .eq. maxv .and. maxv.eq.vref(size(vref)-int(npath/2)))) then
               gs0(:,inode)=ws(:,inode)
               gr0(:,inode)=wr(:,inode)
!
!      Operations in the wavenumber domain
!      phase shift
                do ikx = 1,kxm%n
                   sqa = rec%w%all(iw)**2 / minv**2 - kxm%all(ikx)**2

                   evanescent1:if (sqa > 0) then
                       gs0(ikx,inode)=gs0(ikx,inode)*exp(cmplx(0,v%z%d*sqrt(sqa)))
                       gr0(ikx,inode)=gr0(ikx,inode)*exp(cmplx(0,-v%z%d*sqrt(sqa)))
                   else
                       gs0(ikx,inode)=gs0(ikx,inode)*exp(-sqrt(-sqa)*v%z%d)
                       gr0(ikx,inode)=gr0(ikx,inode)*exp(-sqrt(-sqa)*v%z%d)
                   end if evanescent1
                end do

                tflds(:,inode)=gs0(:,inode)
                call owifftexes(tflds(:,inode),inode)
                ws(:,inode)=tflds(:,inode)/sqrt(1.*kxm%n)

                tfldr(:,inode)=gr0(:,inode)
                call owifftexer(tfldr(:,inode),inode)
                wr(:,inode)=tfldr(:,inode)/sqrt(1.*kxm%n)

            else
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!      Propagate wavefields with reference velocities
!
                 do iref=1,nrefvel

                    gs(:,iref)=ws(:,inode)
                    gr(:,iref)=wr(:,inode)

                    do ikx = 1,kxm%n
!      phase shift
                        sqa = rec%w%all(iw)**2 / vref(iref)**2 - kxm%all(ikx)**2
                        if (sqa > 0) then
                            gs(ikx,iref)=gs(ikx,iref)*exp(cmplx(0,v%z%d*sqrt(sqa)))
                            gr(ikx,iref)=gr(ikx,iref)*exp(cmplx(0,-v%z%d*sqrt(sqa)))
                        else
                            gs(ikx,iref)=gs(ikx,iref)*exp(-sqrt(-sqa)*v%z%d)
                            gr(ikx,iref)=gr(ikx,iref)*exp(-sqrt(-sqa)*v%z%d)
                        end if
                    end do

! Operations in x            

                    tflds(:,inode)=gs(:,iref)
                    call owifftexes(tflds(:,inode),inode)
                    gs(:,iref)=tflds(:,inode)/sqrt(1.*kxm%n)

                    tfldr(:,inode)=gr(:,iref)
                    call owifftexer(tfldr(:,inode),inode)
                    gr(:,iref)=tfldr(:,inode)/sqrt(1.*kxm%n)

!      split step
                    gs(:,iref) = gs(:,iref) * exp(cmplx(0,v%z%d*rec%w%all(iw))*(1./vel(iz,:)-1./vref(iref)));
                    gr(:,iref) = gr(:,iref) * exp(cmplx(0,-v%z%d*rec%w%all(iw))*(1./vel(iz,:)-1./vref(iref)));
                 end do
!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
!       Interpolate between wavefields
!
             if (present(vref1)) then
!
!              linear interpolation 
                if (linint) then
                   do ikx=1,kxm%n
                      indref=0
                      indref=maxloc(vref, mask = int(vref).le.int(vel(iz,ikx))) 
                      if(indref(1).eq.0) indref(1)=size(vref)
                      if (indref(1).gt.1.and.indref(1).lt.size(vref)) then
                         f(inode)=(vel(iz,ikx) - vref(indref(1)))/vel(iz,ikx)
                         g(inode)=1-f(inode)
                         ws(ikx,inode)=g(inode)*gs(ikx,indref(1))+f(inode)*gs(ikx,indref(1)+1)
                         wr(ikx,inode)=g(inode)*gr(ikx,indref(1))+f(inode)*gr(ikx,indref(1)+1)
                      else
                         ws(ikx,inode)=gs(ikx,indref(1))
                         wr(ikx,inode)=gr(ikx,indref(1))
                      end if
                   end do
!
!               nearest neighbor
                else
                   do iref1=2,nrefvel
                      where (vel(iz,:) >= 1/vref1(iref1,2,iz) .and. vel(iz,:) < 1/vref1(iref1-1,2,iz))
                         ws(:,inode)=gs(:,iref1)
                         wr(:,inode)=gr(:,iref1)
                      end where
                   end do
                   where (vel(iz,:) > 1/vref1(1,2,iz))
                      ws(:,inode)=gs(:,1)
                      wr(:,inode)=gr(:,1)
                   end where
                end if
             else
!
!            linear interpolation
                if (path) then
                    do ikx=1,kxm%n
                       if (vel(iz,ikx).lt.vsal) then
                          do ipath=1,npath
                             if (npath .gt. 1) then
                                vpath=vel(iz,ikx)*(1+(ipath-int(npath/2)-1)*vrange/int(npath/2))
                             else 
                                vpath=vel(iz,ikx)
                             end if
                             indref=0
                             indref=maxloc(vref, mask = int(vref).lt.int(vpath)) 
                             if (indref(1).gt.0.and.indref(1).lt.nrefvel) then
                                f(inode)=(vpath - vref(indref(1)))/vpath
                                g(inode)=1-f(inode)
                                as(ikx,ipath)=(g(inode)*gs(ikx,indref(1))+f(inode)*gs(ikx,indref(1)+1))*weight(ipath)
                                ar(ikx,ipath)=(g(inode)*gr(ikx,indref(1))+f(inode)*gr(ikx,indref(1)+1))*weight(ipath)
                             else if (indref(1).eq.0) then
                                as(ikx,ipath)=gs(ikx,indref(1)+1)
                                ar(ikx,ipath)=gr(ikx,indref(1)+1)
                             else if (indref(1).ge.nrefvel) then
                                as(ikx,ipath)=gs(ikx,indref(1))
                                ar(ikx,ipath)=gr(ikx,indref(1))
                             end if
                         end do
                         ws(ikx,inode)=sum(as(ikx,:))
                         wr(ikx,inode)=sum(ar(ikx,:))
if (inode==1) write(0,*) iz,iw,sum(abs(ws(:,inode))),sum(abs(wr(:,inode)))
                      else
if (inode==1) write(0,*) iz,iw,sum(abs(gs(:,nrefvel))),sum(abs(gr(:,nrefvel)))
                         ws(ikx,inode)=gs(ikx,nrefvel)
                         wr(ikx,inode)=gr(ikx,nrefvel)
                      end if
                   end do
                else
                   do ikx=1,kxm%n
                       indref=0
                       indref=maxloc(vref, mask = int(vref).lt.int(vel(iz,ikx))) 
                       if (indref(1).ne.0.and.indref(1).ne.size(vref)-1) then
                          f(inode)=(vel(iz,ikx) - vref(indref(1)))/vel(iz,ikx)
                          g(inode)=1-f(inode)
                          ws(ikx,inode)=g(inode)*gs(ikx,indref(1))+f(inode)*gs(ikx,indref(1)+1)
                          wr(ikx,inode)=g(inode)*gr(ikx,indref(1))+f(inode)*gr(ikx,indref(1)+1)
                       else
                          ws(ikx,inode)=gs(ikx,indref(1)+1)
                          wr(ikx,inode)=gr(ikx,indref(1)+1)
                       end if
                   end do
                end if
             end if
          end if
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
! Imaging Condition by crosscorrelation
!
           phase = cmplx(cos(pi/4.), -sin(pi/4.)) / sqrt(rec%w%all(iw))
           do ish=1,img%sh%n
               ihso=nint(((ish-1)*img%sh%d+img%sh%o)/(img%xm%d))
               do ixw=1,kxm%n
                   if (ixw-ihso >= 1 .and. ixw-ihso <= kxm%n .and. ixw+ihso >= 1 .and. ixw+ihso <= kxm%n) then
                       GG(ixw,ish,iz,inode)=GG(ixw,ish,iz,inode)+real(conjg(ws(ixw-ihso,inode))*(wr(ixw+ihso,inode))*phase)
                   end if
               end do
           end do

        end do depth

        if (mod(iw,20)==1) write(0,5)  "DONE FREQUENCY # ",iw," OUT OF ",rec%w%n-subf," / SHOT # ",ixs
5       format(A17,i5,2(A8,i5))
end do omega
!$OMP END PARALLEL DO

call owfftdestroy()
deallocate(tfldr,tflds)

   do i=1,node
      !$OMP parallel do private (ixw,iz,ish)
      do iz=1,img%z%n
         do ish=1,img%sh%n
            do ixw=1,kxm%n
               image(ixw,ish,iz)=image(ixw,ish,iz)+GG(ixw,ish,iz,i)
            end do
         end do
      end do
      !$OMP END PARALLEL DO
   end do

deallocate(GG,ws,wr,gs0,gr0)

end subroutine
end module

