Reorganizing segment points to generate correct geometry

You may also want to take a look at this post if you want to clean up your lines after.