You first script/sed problem is too spread out for me to grok here. Can you summarize it in one post: inputs, and expected output? I believe it can be much simpler than even Julf's one-liner.

Cheers