module OW_shaper

 use OW_type
 use OW_parms_areal

implicit none
complex, private, allocatable  :: souin(:)
contains

!-------------
subroutine send_sou(sou_in)
complex               :: sou_in(:)
allocate(souin(sou%w%n))
souin=sou_in
end subroutine
!-------------
subroutine clos_sou()
deallocate(souin)
end subroutine


!===============================================
subroutine owshaper(GGS,sign)
 integer			:: i,j,sign
 complex			:: GGS(:,:),temp(sou%w%n), temp1(sou%w%n), phase(sou%w%n)

temp=0
if (decon) then
   do i=padtraces+tapertr+1,kxm%n-(padtraces+tapertr)
      do j=1,sou%w%n
         temp(j)=temp(j)+sum(abs(GGS(i,max(1,j-10):min(j+10,sou%w%n))))/(min(j+10,sou%w%n)-max(1,j-10)+1)
      end do
   end do
   temp=temp/kxm%n
else
   temp=1
end if
phase = cmplx(cos(pi/4.), sin(pi/4.)) * sqrt(sou%w%all)
!do i=padtraces+tapertr+1,kxm%n-(padtraces+tapertr)
!   GGS(i,:)=GGS(i,:)*phase*sou%w%all**2
!end do
do i=padtraces+tapertr+1,kxm%n-(padtraces+tapertr)
   if (sum(abs(temp)**2+white*maxval(abs(temp))) > 0) then
      GGS(i,:)=GGS(i,:)*abs(souin)*abs(temp)/(abs(temp)**2+white*maxval(abs(temp)))!*sign
   end if
end do
if (bandpass) then
   temp1=0
   do j=1,sou%w%n/2
      temp1(j)=temp(2*j)
   end do
   do i=padtraces+tapertr+1,kxm%n-(padtraces+tapertr)
      GGS(i,:)=GGS(i,:)*temp1
   end do
end if
end subroutine
!==================================================

subroutine owpeak(x,kk)
real                    :: x(:)
real                    :: tmp
integer                 :: j,kk

tmp=0
do j=-3,3
   tmp=tmp+x(kk+j)
end do
if (tmp < 0) x=-x

end subroutine

end module
