Start code cleanup. Reorder some functions and add docstrings.