Refactoring, adds unit tests