I was going to then I saw @xfpd has already mentioned the FSM concept and linked to one of dozens of explainers in #6 above.
arduino FSM
if that doesn't make sense right away, many ppl have published what they believe to be the best examples and code.
One or more will work for you and your life will change.
Well at least the way you program things like this will.
a7