Reorder the logic to make it more readable

This could be significantly nicer in modules, but I think the current comments help a lot.
Merge pull request #5 from lachlanp/patch-1

Reorder the logic to make it more readable