module tomo_chain_shape_mod
use tomo_wt_mod
use tomo_eps_mod
use dottest
use tomo_mask_mod
use tomo_op_mod
use tomo_reg_prec_mod
use tomo_eps_mod
use tomo_reg_prec_mod
implicit none
integer, private, save :: nfit,nstyle1,nbound
logical, private, save :: prec,lbfgs
real, pointer, private, save :: tempm(:),temp1(:),nobound(:)
real, private, save :: eps_dampen,esmall

contains

logical function init_chains(gam0,dat0,s0,slow)
  type(sep3d) :: slow
  real, pointer :: gam0(:),dat0(:),junk(:),s0(:),tt(:,:)
  integer :: ierr,i
  integer :: nm 
  init_chains=.false.


  nfit=wt_range()
  allocate(dat0(nfit+size(s0)))
  dat0=0
  allocate(temp1( size(gam0)))
  allocate(nobound( size(s0)))
write(0,*) "AAA ",size(gam0)
  allocate(tt(slow%n(1),slow%n(2)))
  call from_param("bound",nbound,10)
write(0,*) "AAA ",nbound,size(tt,1),size(tt,2)
  tt=1
  do i=1,nbound
    tt(i,:)=0 
    tt(size(tt,1)-i+1,:)=0 
    tt(:,i)=0 
    tt(:,size(tt,2)-i+1)=0 
  end do
write(0,*) "AAx "
  nobound=reshape(tt,(/size(nobound)/))
  call from_param("esmall",esmall,9.)
  ierr=wt_op(.false.,.false.,gam0,dat0(1:nfit))
  nobound=reshape(tt,(/size(nobound)/))
write(0,*) "haab",size(s0),size(nobound)
  dat0(nfit+1:)=s0*esmall*nobound
write(0,*) "haa2"
  deallocate(tt)
  init_chains=.true.
end function

integer function i_op(adj,add,model,data)

logical,intent(in) :: adj,add
real               :: model(:),data(:)
i_op=0
write(0,*) "haa3"
call adjnull(adj,add,model,data)
write(0,*) "AA2 "
if(.not. adj) data=data+model*esmall*nobound
write(0,*) "AA3 "
if( adj)      model=model+data*esmall*nobound
write(0,*) "AA4 "
end function


integer function data_op(adj,add,model,data)
logical,intent(in) :: adj,add
real               :: model(:),data(:)
data_op=0
call chain(wt_op,tomo_op,adj,add,model,data,temp1)
end function

integer function op(adj,add,model,data)
logical,intent(in) :: adj,add
real               :: model(:),data(:)
op=0
call array(data_op,i_op,adj,add,model,data(1:nfit),data(nfit+1:))
end function
end module
