Fix loop off-by-ones found by Moonlightning