this is the completed state machine code.