improved scanning code