Initial refactoring, passing tests