First step at fixing main loop to state machine