First working version of the state machine