This is a refactor which will make writing tests easier.
Depends on D9467
Run tests to make sure everything still works
rebase