refactored to create a state machine