Rewrite of state machine