# 1 "<stdin>"
# 1 "<built-in>"
# 1 "<command line>"
# 1 "<stdin>"
!THIS WAS SERGEYS SMOOTH
module slope_dir_bob_mod
  use divide
  use grad2_wt
  use allpass
  use allder
  use sep3d_struct_mod
  use sep
  implicit none
  integer, private, save :: n12,niter_slope,nl_iter_slope,nd(2)
  real, private, save :: d21,dd(2)
  real, dimension (:), pointer :: u1, u2, dp
  real, dimension(:), pointer :: wt_me
  real,private,save :: eps,eps2
  logical, private, save :: verb,fast
  contains
  subroutine slope_init(n,d,verb3,wt_it)
    logical :: verb3
    integer :: n(2)
    real :: d(2)
    real , pointer :: wt_it(:,:)
    nd=n
    dd=d
    n12=n(1)*n(2)
    d21=d(1)/d(2)
    call from_param("niter_slopes",niter_slope,40)
    call from_param("nl_iter_slope",nl_iter_slope,5)
    call from_param("eps_slope",eps,.25)
    call from_param("eps_slope2",eps2,.25)
    call from_param("fast_slope",fast,.true.)
    allocate (u1 (n12), u2 (n12), dp(n12),wt_me(n12))
    wt_me=reshape(wt_it,(/size(wt_it)/))
    call grad2_wt_init (n(1),n(2),d21,wt_it)
    if (fast) then
      eps=eps**2
      eps2=eps2**2
    end if
  end subroutine
  subroutine slope_clean()
    deallocate(u1,u2,dp)
  end subroutine
  subroutine slope_dir(field,p,res)
    real, dimension (:), pointer :: p,res
    real:: field(:)
    logical :: first
    integer :: nltr,ntr,stat1,stat2,iter
    real :: mean
    ntr=niter_slope
    nltr=nl_iter_slope
! p=0;
    p=p*wt_me
    call allpass_init (nd(1),nd(2),p)
    call allder_init (nd(1),nd(2),p)
    do iter =1, nltr
      stat1 = allpass_lop (.false.,.false.,field,u2)
      stat2 = allder_lop (.false.,.false.,field,u1)
      mean = sqrt (sum (u1*u1))
      u1 = u1/mean
      u2 = u2/mean
      if (fast) then
        call divide_apply_tri(nd(1),nd(2),u2,u1,dp,eps,eps2)
! write(0,*) "CHECK DP",minval(field),maxval(field),minval(u1),maxval(u2),minval(u2),maxval(u1);
      else
! call divide_apply (.false., n12, u2, u1, dp, eps, ntr,
! grad2_wt_lop, 2*n12,res,wt_me)
        call divide_apply_cg (.false., n12, u2, u1, dp, eps, ntr, &
          & grad2_wt_lop, 2*n12,res)
      end if
      p = p + dp
    end do
  end subroutine
end module
