Refactor main into helper routines.
Fix some typos and documentation.