Improving code clarity

Splitting up functions, better function names, organizing functions,
moving invariants into outer scope to function calls, splitting up giant
if statements, adding explanatory comments, etc.