Program not working as intended

very classical case for a software-tecnique called state-machine

a fixed sequence of actions where starting the next action is initiated by one or multiple conditions
best regards Stefan