Refactor code and add tests