Add tests and refactor code