Add more tests and some small refactoring