I must have overlooked something. I did some further testing, and
it appears that if I don't close the files that I've opened then
the data does not get fully written to them. I should have known this...
but in the original script from the Apache source it didn't do this -
probably because it only had one routine to do and then the script
ended, closing all the files automatically.
Thanks to all for the help!