For an excellent example of how to cope with this - using a State Machine approach - see:
NB: “State Machine” is also known as “Finite State Machine” - or “FSM”, for short.