Made rescan logic more sensible with margin and max safe gap.