Refactor code and tests