This updated rotary encoder routine (borrowed from FlashFloppy by Kier Fraser) should provide much more reliable encoder tracking across a variety of encoder types, even when the encoder quality is poor or state transitions are quite noisy.