Improve code comments, add tests, refactor a bit