Finally
There are much more elegant ways to do some of this.
For systems logging, read this.
There is a specific library for writing CSV files.
I wanted to do all this the hard way!
I have code in navigation systems, survey equipment, satellite tracking systems, instrumentation systems, etc. that has used similar, very simple scripts to that which I showed here.
I have a rule with systems which run 24x7 remotely……simplicity!