(mostly) finished implementing the state machine