(r.length - 2) / 2 + 1 is actually r.length / 2, right?
Besides, r.length is unsigned, so it will be buggy for lengths 1 and 0 - can it happen?