Remove duplicated code.
Add tests.