Fix logic for circular buffer access