Brings in lost changes from #5c6cfa9759c1590003ef29e65f57825de9493da8 and fixes off-by-1 error