module OW_image_areal
!
! Imaging Condition -- crosscorrelation
!

use OW_type
use OW_parms_areal
use OW_fftw_areal
use OW_exec_time

implicit none

contains
!=====================================================================================
subroutine owimage0(iw,ws,wr,GG) 

integer					:: ish, ihso, ixw,iw,iz
complex					:: wr(:),ws(:),phase
real					:: GG(:,:)

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,rec%h%n
      if (ixw-ihso > 1 .and. ixw-ihso < rec%h%n .and. ixw+ihso > 1 .and. ixw+ihso < rec%h%n) then
          GG(ish,ixw)=GG(ish,ixw)+real(conjg(ws(ixw-ihso))*(wr(ixw+ihso)))*phase
      end if
   end do
end do

end subroutine
!=====================================================================================
subroutine owimage(adj,ssou,iw,ws,wr,image)

logical					:: adj,ssou
integer					:: ish, ihso, ixw,iw,sign
complex					:: wr(:),ws(:),phase
!real					:: image(:,:)
complex					:: image(:,:)

phase = cmplx(cos(pi/4.), -sin(pi/4.)) / sqrt(rec%w%all(iw))

if (adj) then
   do ixw=1,kxm%n
      do ish=1,img%sh%n
         ihso=nint(((ish-1)*img%sh%d+img%sh%o)/(img%xm%d))
         if (ixw-ihso >= 1 .and. ixw-ihso <= kxm%n .and. ixw+ihso >= 1 .and. ixw+ihso <= kxm%n) then
            if (ssou) then
               ws(ixw-ihso)=ws(ixw-ihso)+wr(ixw+ihso)*image(ish,ixw)*phase
            else
               wr(ixw+ihso)=wr(ixw+ihso)+ws(ixw-ihso)*image(ish,ixw)*conjg(phase)
            end if
         end if
      end do
   end do
else
   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
            image(ish,ixw)=image(ish,ixw)+conjg(ws(ixw-ihso))*wr(ixw+ihso)*phase
         end if
      end do
   end do

end if

end subroutine

!=====================================================================================
subroutine owimage2(ws,wr,GG) 

integer					:: ish, ihso, ixw
real					:: GG(:,:),wr(:),ws(:)

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 < rec%h%n .and. ixw+ihso > 1 .and. ixw+ihso < rec%h%n) then
         GG(ish,ixw)=GG(ish,ixw)+ws(ixw-ihso)*wr(ixw+ihso)
      end if
   end do
end do

end subroutine
!----------------------------------------------------------
end module
