Refactoring, tests and cleanup