Finished refactoring. TODO: fix broken tests