According to your description, I am thinking the problem might be the other script you have, the one to add text to the end of the file, can you share that with us? As you said, if you edit the file manually it is fine. I think this script should be fine, at least serves your purpose.