Refactor state machine