module OW_sll
  !! Lloyds Algorithm slowness operator
  !! for FK-FX downward continuation
  !! includes salt logic ??

  use type_mod
  use util_mod
  use S_mod
  use lloyd_mod
  !---------------
  implicit none

  real, dimension(:,:), pointer, private :: sx
  real, dimension(:), pointer, private :: bound,ref_slow,s_slice

contains
  !----------------------------------------------------------------
  !! N reference slownesses
  integer function sll_init() result(st)
    integer :: er
    real::a

    allocate(bound(nref),ref_slow(nref))
    allocate(s_slice(rec%h%n))
    allocate(sx(rec%h%n),stat=er)

    call init_lloyd()
    st=OK
  end function sll_init


  !----------------------------------------------------------------  
  !! N reference slownesses
  integer function sll() result(st)
    integer :: izs,ifk
    real    :: ds, so, sz
    real    :: sl,su
    real    :: smin,smax
    integer :: imx, imy, i1,i2
    real    :: ssalt_true
    real    :: ssalt_mean,ssalt_sum
    real    :: slocal
    integer :: ins,ndo,ierr

    call sellect_slow_comp(.true.)

    do izs=1,img%z%n
       slo%nrs(izs) = nref
       do i1=1,rec%h%n
          sx(i1) =S%bin(i1,izs)
       end do
       s_slice=sx
       call lloyd_setup(izs)
    end do

    slo%nrs_r=>slo%nrs_s
    slo%sz_r =>slo%sz_s
    slo%si_r =>slo%si_s
    slo%bound_r=>slo%bound_s

   st=OK
  end function sll
  !----------------------------------------------------------------
  subroutine lloyd_setup(izs)
    integer :: i1,i2,izs

    slo%nrs(izs)=lloyd_go(s_slice,ref_slow,nref,bound)
    slo%sz(izs,1:nref) =ref_slow
    slo%bound(izs,1:nref)= bound

    do  i1=1,rec%h%n
       slo%si(i1,izs)=1
       do while(sx(i1) > bound(slo%si(i1,izs)))
          slo%si(i1,izs)=slo%si(i1,izs)+1
       end do
    end do
  end subroutine lloyd_setup
!----------------------------------------------------------------
end module sll_mod
