Add a load of docstrings, and some other cleanups I couldn't resist doing.