module weight_md_mod

  use adj_mod
  implicit none

  real, dimension(:), allocatable, private :: wm,wd
  real, dimension(:), allocatable, private :: mask

contains

  subroutine weight_m_init(w)
    real, dimension(:) :: w

    allocate(wm(size(w)))
    wm=w
  end subroutine weight_m_init
 
  subroutine weight_d_init(w)
    real, dimension(:) :: w

    allocate(wd(size(w)))
    wd=w
  end subroutine weight_d_init

  subroutine mask_m_init(m)
    real, dimension(:) :: m

    allocate(mask(size(m)))
    mask=m
  end subroutine mask_m_init

  integer function mask_m_lop(adj,add,model,data)
    logical,intent(in) ::     adj,add
    real, dimension(:) ::             model,data
    call adjnull (adj,add,model,data)
    if (adj) then       
       model = model + data*mask  
    else       
       data  = data + model*mask     
    end if
    mask_m_lop = 0
  end function mask_m_lop

  integer function datw_lop(adj,add,model,data)
    logical,intent(in) ::   adj,add
    real, dimension(:) ::           model,data
    call adjnull (adj,add,model,data)

    if (adj) then      
       model = model + data*wd   
    else       
       data  = data + model*wd     
    end if
    datw_lop=0   

  end function datw_lop

  integer function modw_lop(adj,add,model,data)
    logical,intent(in) ::   adj,add
    real, dimension(:) ::           model,data
    call adjnull (adj,add,model,data)

    if (adj) then      
       model = model + data*wm  
    else       
       data  = data + model*wm    
    end if
    modw_lop=0   

  end function modw_lop
  
  subroutine weight_md_close()
    if (allocated(mask)) deallocate(mask)
    if (allocated(wm)) deallocate(wm)
    if (allocated(wd)) deallocate(wd)
  end subroutine weight_md_close

end module weight_md_mod
