Updated state machine and scanning code