Some more refactoring and fixed tests.