module tomo_eps_mod
use sep
use adj_mod
use sep3d_struct_mod
implicit none
real, private, save,  pointer :: wts(:)
integer, private,save :: ndomain,nrange

contains

logical function load_eps_op(slow_s)
type(sep3d) :: slow_s,wt_s
integer, external :: auxin,sreed
real :: eps

load_eps_op=.false.
ndomain=product(slow_s%n(1:sep3d_ndims(slow_s)))
if(-1==auxin("eps_file")) then
 allocate(wts(product(slow_s%n(1:sep3d_ndims(slow_s)))))
 wts=1
else
 call init_sep3d("eps_file",wt_s,"INPUT")
 if(product(slow_s%n) /= product(wt_s%n)) then
    write(0,*) "size of eps must be the same as the size of the slowness space"
    return
 end if
 allocate(wts(product(wt_s%n(1:sep3d_ndims(wt_s)))))
 if(4*size(wts)/=sreed("eps_file",wts,size(wts)*4)) then
   write(0,*)"trouble loading wt_op"
   return
 end if
end if
call from_param("eps",eps,1.)
wts=wts/(sum(wts)/size(wts))
wts=wts*eps
write(0,*) "EWTS",minval(wts),maxval(wts)
nrange=size(wts)
load_eps_op=.true.
end function

integer function eps_range()
 eps_range=nrange
end function

integer function eps_domain()
 eps_domain=ndomain
end function

integer function eps_op(adj,add,model,data)
logical,intent(in) :: adj,add
real    :: model(:),data(:)

call adjnull(adj,add,model,data)
if(.not. adj) then
  data(1:size(wts))=data(1:size(wts))+model(1:size(wts))*wts
else 
  model(1:size(wts))=model(1:size(wts))+data(1:size(wts))*wts
end if
!write(0,*) "XXX",maxval(abs(wts)),maxval(abs(model)),maxval(abs(data)),model(2),data(2),wts(2)
eps_op=0

end function


end module
