Some more refactoring and tests.