Refactored the state machine