Refactoring plus added some tests