Improve documentation

This commit adds docstrings and comments to explain some non-obvious
behavior.