module wei_ref
  !! WEI reference slowness selector

  use wei_util
  use wei_pro
  use wei_par
  use wei_tag

  use wei_S
  use wei_xmap
  !---------------
  implicit none

  type(weslow), private :: SS,SR
contains
  !----------------------------------------------------------------
  subroutine weiref_init(SLin)
    integer            :: st
#ifdef DEBUG
    character(len=128), parameter :: unit='weiref_init'
#endif
    interface !!-------------------------
       integer function  SLin() result(st)
       end function SLin
    end interface !!---------------------
#ifdef DEBUG
    if(wpro%dbg>0) call in(unit)
#endif

    SS%tag=wtag%S; call weiS_init(SS)
    SR%tag="RefS"; call weiS_scr_init(SR)

    call weixmap_init()   !! for weiS_push

    !! allocate slowness arrays for FK/FX ops
    call weiS_fkfx_allocate()

    st=SLin()     !! SL op init

#ifdef DEBUG
    if(wpro%dbg>0) call out(unit)
#endif
  end subroutine weiref_init
  !----------------------------------------------------------------
  integer function weiref(SLop)
    integer :: izb
    integer :: st
    interface !!----------------------------------------------
       integer function SLop(X) result(st)
         use wei_type
         type(weslow), intent(inout) :: X
       end function SLop
    end interface !!------------------------------------------
    integer :: ifk,izs
    integer :: imx,imy
    real    :: ds,dso

    zbA: do izb=1,wpro%nzb       
       write(0,*) izb,wpro%nzb
       call weiS_read(SS,izb)      !! read  a slowness block
       st = SLop(SS)               !! setup sS, sR, s(z)
       
       do izs=1,wpro%nzs
          do imx=1,SR%amx%n
             do imy=1,SR%amy%n
                SR%bin(imx,imy,izs) = slo%rs_s(izs,1)
                dso = abs(real(SS%bin(imx,imy,izs))-slo%rs_s(izs,1))
                do ifk=1,slo%nr_s(izs)
                   ds=abs(real(SS%bin(imx,imy,izs))-slo%rs_s(izs,ifk))
                   if(ds < dso) then
                      SR%bin(imx,imy,izs) = slo%rs_s(izs,ifk)
                      dso=ds
                   end if
                end do
             end do
          end do
       end do

       call weiS_write(SR,izb)     !! write a slowness block
    end do zbA
    
    weiref=weiOK
  end function weiref
  !----------------------------------------------------------
end module wei_ref

