subroutine avgpatch(patch,patchnum,u,u_avg)
! computes the averaged value of a variable (at the wall) over a patch
! and assigns it to an nx X ny array

! sc: 
! note: this is inefficient: should calculate directly to u_avg
! --no maybe its good
use types,only:rprec
use param,only:ld,nx,ny
use bottombc,only:ptypes
implicit none
real(kind=rprec),dimension(nx,ny),intent(inout)::u_avg
integer,dimension(ptypes),intent(in)::patchnum
integer,dimension(nx,ny),intent(in)::patch
integer::i,j,k
real(kind=rprec),dimension(ptypes)::temp
real(kind=rprec),dimension(ld,ny,1),intent(in)::u

temp=0._rprec
do j=1,ny
do i=1,nx
do k=1,ptypes
   if (patch(i,j).eq.k) then
      temp(patch(i,j))=temp(patch(i,j))+u(i,j,1)/real(patchnum(patch(i,j)))
   end if
end do
end do
end do

do j=1,ny
do i=1,nx
do k=1,ptypes
   if (patch(i,j).eq.k) then
      u_avg(i,j)=real(temp(k))
   end if
end do
end do
end do
end subroutine avgpatch
