Added some tests and a bit of refactoring