Some refactoring and unit tests