Add tests. Refactor code