module OW_xcorr_phase

use lint1
use OW_type
use OW_parms_areal
use OW_ctrillwei
use OW_rndseed

implicit none

integer,private					:: node,isp2

contains

!---------------------------------------------------------
subroutine owctrl_init(isp2_in,node_in)
integer						:: isp2_in
integer						:: node_in

isp2=isp2_in
node=node_in

end subroutine
!---------------------------------------------------------
subroutine owxcorr1(taper,source,recset,souset,vsal,vel,GGR,GGS)

integer					:: iw,inode,i
real					:: vel(:,:),taper(:),vsal,start,finish
real, allocatable				:: rand1(:),rand2(:)
real					:: recset(:,:),souset(:,:),source(:)
complex					:: GGR(:,:),GGS(:,:)
complex,allocatable				:: wwr(:,:,:),wws(:,:,:)

integer, external				:: omp_get_thread_num

source=sqrt(source)

!--------------------------------------------------------
if(encode) then
   if(encw) then
      allocate(rand1(sou%w%n))
      do ixs=1,sog%xm%n
         call init_random_seed(isp2,sou%w%n,rand1)
         

         end do
         deallocate(rand1)
      end do
   else if (encz) then
      do ixs=1,sog%xm%n
         do iw = 1,sou%w%n
            allocate(rand2(sog%z%n))
            call init_random_seed(isp2,sog%z%n,rand2)!,iw)

         end do
      end do
!      deallocate(rand2)
   end if

if (exist_file("wwr")) then
   call srite("wwr",wwr,8*sou%w%n*nx*sog%z%n)
   call srite("wws",wws,8*sou%w%n*nx*sog%z%n)
   deallocate(wwr,wws)
end if
   
end subroutine

!-------------------------------------------------------------------------------------------------

subroutine owctrlHD(taper,source,recset,souset,vsal,vel,GGR,GGS,HD)

complex					:: HD(:,:)
real,allocatable				:: HD1(:),HD2(:)
integer					:: iw,inode,i
real					:: vel(:,:),taper(:),vsal,start,finish
real, allocatable				:: rand1(:),rand2(:)
real					:: recset(:,:),souset(:,:),source(:)
complex					:: GGR(:,:,:),GGS(:,:,:)

integer, external				:: omp_get_thread_num

source=sqrt(source)

allocate(HD1(sog%z%n),HD2(sog%z%n))
do iw = 1,sou%w%n
!   HD1=HD(iw,:)
!   HD2=HD(iw+sou%w%n,:)
   HD1=atan(imag(HD(iw,:))*real(HD(iw,:))/(real(HD(iw,:))*real(HD(iw,:))+tiny(1.)))
   HD2=atan(imag(HD(iw+sou%w%n,:))*real(HD(iw+sou%w%n,:))/(real(HD(iw+sou%w%n,:))*real(HD(iw+sou%w%n,:))+tiny(1.)))
   HD1=HD1/maxval(HD1)
   HD2=HD2/maxval(HD2)
!   HD1=cmplx(1,0)
!   HD2=cmplx(1,0)
   call owctrlwei_init(iw,isp2)
   call owctrlweiHD(taper,vsal,vel,recset,souset,GGR(iw,:,:),GGS(iw,:,:),HD1,HD2)
end do
deallocate(HD1,HD2)
end subroutine

end module
