More tests and refactoring