subroutine subtract_mean(mg, iv, include_ghostcells)
use mpi
type(mg_t), intent(inout) :: mg
integer, intent(in) :: iv
logical, intent(in) :: include_ghostcells
integer :: i, id, lvl, nc, ierr
real(dp) :: sum_iv, mean_iv, volume
nc = mg%box_size
sum_iv = get_sum(mg, iv)
call mpi_allreduce(sum_iv, mean_iv, 1, mpi_double, mpi_sum, mg%comm, ierr)
! Divide by total grid volume to get mean
volume = nc**2 * product(mg%dr(:, 1)) * size(mg%lvls(1)%ids)
mean_iv = mean_iv / volume
do lvl = mg%lowest_lvl, mg%highest_lvl
nc = mg%box_size_lvl(lvl)
do i = 1, size(mg%lvls(lvl)%my_ids)
id = mg%lvls(lvl)%my_ids(i)
if (include_ghostcells) then
mg%boxes(id)%cc(:, :, iv) = mg%boxes(id)%cc(:, :, iv) - mean_iv
else
mg%boxes(id)%cc(1:nc, 1:nc, iv) = mg%boxes(id)%cc(1:nc, 1:nc,&
iv) - mean_iv
end if
end do
end do
end subroutine subtract_mean