refactor and add unit test