# 1 "<stdin>"
# 1 "<built-in>"
# 1 "<command line>"
# 1 "<stdin>"
module grad2_wt
! 2-D gradient with adjoint, r= grad( p)
  use adj_mod
  implicit none
  integer,private :: n1,n2
  real,private :: d21
  real, pointer , private ::wt(:,:)
  contains
  subroutine grad2_wt_init (n1_in,n2_in, d21_in,wt_in)
    integer :: n1_in,n2_in
    real :: d21_in
    real, pointer :: wt_in(:,:)
    n1=n1_in
    n2=n2_in
    d21=d21_in
    wt=>wt_in
  end subroutine
  integer function grad2_wt_lop(adj,add,model,data)
    logical,intent(in) :: adj,add
    real :: model (:),data(:)
    call adjnull(adj,add,model,data)
    call grad2_wt_lop2(adj,model,data)
    grad2_wt_lop=0
  end function
  subroutine grad2_wt_lop2(adj,p,r)
    logical :: adj
    real :: p(n1,n2), r(n1,n2,2),val
    integer i,j
    do i= 1, n1-1
      do j= 1, n2-1
        val=sum(wt(i:i+1,j:j+1))
        if ( adj) then
          p(i+1,j ) = p(i+1,j ) + r(i,j,1) *val
          p(i ,j ) = p(i ,j ) - r(i,j,1) *val
          p(i ,j+1) = p(i ,j+1) + r(i,j,2) * d21 &
            &*val
          p(i ,j ) = p(i ,j ) - r(i,j,2) * d21&
            &*val
        else
          r(i,j,1) = r(i,j,1) + ( p(i+1,j) - p(i,j)) *val
          r(i,j,2) = r(i,j,2) + ( p(i,j+1) - p(i,j))&
            & * d21 *val
        end if
      end do
    end do
  end subroutine
end module
