Refactor code, add tests