Tidy up and add some docstrings