Some refactoring and add tests