State machine refactoring.