Refactor and add tests