This re-applies e32b1eee, which was reverted in 20675d8f due to broken unit tests. This patch includes fixes for the tests.