Add some tests and refactor a bit