refactoring to state machines