Changed range creation code

Handle ranges that are out of bounds correctly
use MIN macro to use limit of docIds count for range creation