This more or less works, and has some of the state machine sorted out.