Near-complete rewrite using state machine; much cleaner.  Still needs to handle unittest cases.