Avoid signed overflow in some xrange calculations, and extend