Why don't you show us samples of the two versions of the text? Start with a very short first text file containing a few words and new lines, then process that to produce the broken version. We can make lots of guesses about how the text files might be wrong and waste our time and yours doing so. Showing us a small sample of what you are actually dealing with will save everyone time and get you a much better answer.
Why do you read the first line into $in then do nothing with it? Could that be related to your problem?
Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond