Reafactoring and add tests