Refactored code, added some docstrings.