Reorder the logic to make it more readable

This could be significantly nicer in modules, but I think the current comments help a lot.