Refactor and adding unit tests