Tidied up code (apart from legacy.py, which got messed up), updated docs.