This is a demo-code that shows the principle of a state-machine.
This example has not exact your functionality. After looking at this example ask as many questions as you like. I'm interested in improving the explanation to become easier to understand.