refactoring into more of an FSM