refactor (only) of doswitch()

Removed a lot of duplication, accumulated cruft, and shrank variable ranges.