module base_grad2d_mod
  use  base_adjnul_mod
  implicit none


  integer, private :: n1, n2

contains


  integer function base_grad2d_init(n1_in, n2_in) result(stat)
    integer :: n1_in, n2_in
    n1 = n1_in
    n2 = n2_in
    stat = 0
  end function

  integer function base_grad2d_oper(adj, add, modl, data) result(stat)
    logical            :: adj, add
    real, dimension(:) :: modl, data
    call base_adjnul_real(adj, add, modl, data) 
    call base_grad2d(adj, modl, data)
    stat = 0
  end function

  integer function base_grad2d_clos() result(stat)
    n1 = 0
    n2 = 0
    stat = 0
  end function


  subroutine base_grad2d(adj, modl, data)
    logical                  :: adj
    real, dimension(n1,n2)   :: modl
    real, dimension(n1,n2,2) :: data

    integer                  :: i, j

    do j=1, n2-1
    do i=1, n1-1
       if (adj) then
          modl(i+1,j) = modl(i+1,j) + data(i,j,1)
          modl(i  ,j) = modl(i  ,j) - data(i,j,1)
          modl(i,j+1) = modl(i,j+1) + data(i,j,2)
          modl(i,j  ) = modl(i,j  ) - data(i,j,2)
       else
          data(i,j,1) = data(i,j,1) + modl(i+1,j) - modl(i,j)
          data(i,j,2) = data(i,j,2) + modl(i,j+1) - modl(i,j) 
       end if
    end do
    end do

  end subroutine


end module
