Lot of refactoring and added tests