module s2p_mod

  use SEP

  implicit none

contains

  subroutine shottoplane1p(out,in,ox,dx,nx,px,ow,dw,nw,ohx,dhx,nhx,osx,dsx,nsx)
    integer :: nx,nw,nhx,nsx,plane_nsx,iw,ix,ihx,isx,id
    real    :: ox,dx,px,dw,ow,ohx,ohy,osx,dsx,w,sx,tx,plane_osx,plane_dsx
    real    :: xdt,hx,rx,dhx
    complex :: out(:,:),in(:,:,:)
    complex, allocatable :: tout(:,:,:)

    !! For OMP
    integer, external :: omp_get_num_threads,omp_get_thread_num
    integer :: nth,ith

    !$OMP PARALLEL
    nth = omp_get_num_threads()
    !$OMP END PARALLEL

    allocate( tout(nx,nw,nth) )
    
    !$OMP PARALLEL DO PRIVATE(ith,iw,ix)
    do ith=1,nth
       do iw=1,nw
          do ix=1,nx
             tout(ix,iw,ith) = 0.
          end do
       end do
    end do
    !$OMP END PARALLEL DO

    do iw=1,nw
       do ix=1,nx
          out(ix,iw) = 0.
       end do
    end do

    plane_osx = osx  
    plane_dsx = dsx  
    plane_nsx = nsx

    xdt = plane_dsx*px

   !$OMP PARALLEL DO SCHEDULE(DYNAMIC) PRIVATE (id,isx,iw,sx,tx,w,ihx,hx,rx,ix)
    do isx = 1,nsx
       id = omp_get_thread_num()+1

       !! . . Source position
       sx = (isx-1.)*dsx+osx
       
       !! . . Relative source position x px
       tx = (isx-1.)*xdt
       do iw=1,nw
          w = (iw-1.)*dw+ow
          do ihx=1,nhx
             
             !! . . inline relative offset position
             hx=(ihx-1.)*dhx+ohx

             !! . . inline absolute offset position
             rx=sx+hx
             ix = (rx-ox)/dx + 1.5

             if (ix .lt. 1 .or. ix .gt. nx) cycle

             !! . . encode data set
             tout(ix,iw,id) = tout(ix,iw,id)+in(ihx,iw,isx)*cmplx(cos(w*tx),sin(w*tx))
          end do 
       end do
    end do
    !$OMP END PARALLEL DO


    do ith=1,nth
       !$OMP PARALLEL DO SCHEDULE(DYNAMIC) PRIVATE(iw,ix)
       do iw=1,nw
          do ix=1,nx
             out(ix,iw) = out(ix,iw)+tout(ix,iw,ith)
          end do
       end do
       !$OMP END PARALLEL DO
    end do
    
    deallocate(tout)

  end subroutine shottoplane1p

end module s2p_mod
