Line merging algorithm

Try with this: