rewrote as a state machine