refactor state machine