ranges R;
endpoints E;
startpoints S;
for x in ranges:
append x.endpoint + 1 TO E;
append x.startpoint TO S;
vector<int> starts;
init_start = null;
int total = 0;
for x, is-S in [SORTED!!] S, E:
if is-S:
append x to starts
if init_start == null:
init_start = x
else:
if len(starts) == 1: # not yet popped
total += loc(x) - init_start
init_start = null
pop starts