Rewrite the state machine to improve performance