First working implementation of the state machine