Refactored state machine