Fix bug in state machine