Refactoring code and add more tests