Also, rework this logic a little to make it simpler. The length of the result slice is now computed in one place.