Cleanup code and add docstrings