This turns a hard-to-understand nested if{} chain into a simple switch statement, and pulls some code out in to utility functions. This is strictly a code-organization change, and should contain no functional changes.