Some refactoring and better docstrings.