module wei_cps
  !! Complexified Phase-Screen a.k.a. complexified Local Born Fourier
  !! limit the denominator to some small positive number
  !!
  !!
  !!           1                  1
  !! -------------------- = ------------- for x < cps
  !!      ---------------    sqrt(1- x^2)
  !!     /     |  k  |2
  !!    /  1 - | --- |
  !!  \/       | w s |
  !!
  !!

  use wei_util
  use wei_pro
  !---------------
  implicit none

  real, private :: cps

contains
  !----------------------------------------------------------------
  subroutine weicps_init()
    integer :: mpierr
#ifdef DEBUG
    character(len=128), parameter :: unit='weicps_init'
    if(wpro%dbg>0) call in(unit)
#endif

    if(wpar%impi==0) call from_param("cps",cps,.999)
    if(wpar%nmpi >0) call MPI_BCAST(cps,1,MPI_REAL,0,MPI_COMM_WORLD,mpierr)

#ifdef DEBUG
    if(wpro%dbg>0) call out(unit)
#endif
  end subroutine weicps_init
  !----------------------------------------------------------------
  subroutine weicps(dwfld,ith,kk,ko)
    complex, dimension(:,:,:,:,:), pointer :: dwfld
    integer, intent(in)                    :: ith
    real,    dimension(:,:,:,:),   pointer :: kk
    real,    intent(in)                    :: ko
    
#ifdef DEBUG
    character(len=128), parameter :: unit='weicps'
    if(wpro%dbg>9) call in(unit)
#endif

    where (kk/ko <cps) 
       dwfld(:,:,:,:,ith) = &
       dwfld(:,:,:,:,ith) / sqrt(1- (kk/ko)**2)
    end where

#ifdef DEBUG
    if(wpro%dbg>9) call out(unit)
#endif
  end subroutine weicps
  !----------------------------------------------------------------  
end module wei_cps
