# 1 "<stdin>"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "<stdin>"

module binpull1
! From each bin on model mesh, pull nearest data value.
  use adj_mod
  implicit none
  integer ,private, dimension (:), allocatable :: jd
  integer, private :: m1
  contains
  subroutine binpull1_init ( o1,d1,coordinate,m1_in )
    integer :: m1_in
    integer im, id
    real x, near, dist, o1,d1,coordinate(:)
    m1 = m1_in
    if (.not. allocated(jd)) then
      allocate(jd ( m1))
    end if
    do im= 1, m1
      x = o1 + (im-1)*d1
      near = 1.e30
      do id= 1, size(coordinate)
        dist = abs( x -coordinate(id))
        if ( dist < near) then
          jd(im) = id
          near = dist
        end if
      end do
    end do
  end subroutine
  function binpull1_lop ( adj, add, mm, dd) result(stat)
    integer :: stat
    logical,intent(in) :: adj,add
    real,dimension(:) :: mm,dd
    call adjnull (adj,add,mm,dd )
    call binpull1_lop2(adj,add,mm,dd )
    stat=0
  end function
  subroutine binpull1_lop2(adj,add,mm,dd)
    logical,intent(in) :: adj,add
    real, dimension (:) :: mm
    real, dimension (:) :: dd
    integer im,id
    do im= 1, m1
      id = jd(im)
      if ( adj) then
        mm(im) = mm(im) + dd(id)
      else
        dd(id) = dd(id) + mm(im)
      end if
    end do
  end subroutine
  subroutine binpull1_close()
    deallocate( jd )
  end subroutine
end module
