Refactoring a little and adding tests