updated line merging to be more robust