module wei_int_mod

  implicit none
  integer, private :: nref

contains


  integer function wei_int_init(nref_in) result(stat)
    integer :: nref_in
    nref = nref_in
    stat = 0
  end function


  integer function wei_int_oper(adj, add, vref_slice, vmod_slice, wfld_slice, wfld_cube) result(stat)
    logical                            :: adj
    logical                            :: add
    real   , dimension(:)    , pointer :: vref_slice
    real   , dimension(:,:)  , pointer :: vmod_slice
    complex, dimension(:,:)  , pointer :: wfld_slice
    complex, dimension(:,:,:), pointer :: wfld_cube

    real                               :: vmin, vmax, dv
    integer                            :: ix, iy, ref_index

    if(.not.add) then
       if(adj) then
         wfld_slice = 0.
       else
         wfld_cube = 0.
       end if
    end if

    if(nref .eq. 1) then
       if(adj) then
          wfld_slice = wfld_slice + wfld_cube(:,:,1)
       else
          wfld_cube(:,:,1) = wfld_cube(:,:,1) + wfld_slice
       end if
    else
       vmin = minval(vref_slice)  
       vmax = maxval(vref_slice)
       dv   = (vmax - vmin) / (nref - 1)

       do iy=1, size(wfld_slice, 2)
          do ix=1, size(wfld_slice, 1)
             ref_index = max(1, min(nref, int((vmod_slice(ix, iy)-vmin)/dv+1.5)))
             if (adj) then
                wfld_slice(ix, iy) = wfld_slice(ix, iy) + wfld_cube(ix, iy, ref_index)
             else
                wfld_cube(ix, iy, ref_index) = wfld_cube(ix, iy, ref_index) + wfld_slice(ix, iy)
             end if
          end do
       end do

    end if
    stat = 0
  end function
!================================================================
  subroutine wei_int2d_nearest()
  end subroutine
!================================================================
  subroutine wei_int2d_linear()
  end subroutine
!================================================================
  subroutine wei_int2d_spline()
  end subroutine
!================================================================
  integer function wei_int_clos() result(stat)
    nref = 0
    stat = 0
  end function

end module
