more robust algorithm to calculate gap size