move logic out of state machine loop