changed state switching code. Added a state-machine. Now the code is much simpler to read and understand