Some refactoring, added tests