Refactored duplicate code in state machine