Add tests, more refactoring