I tried your improved script and found that it stopped in the middle at line with tail -1. I had to changed it in order to make the script run. Please find attached diff file.
BTW many thanks for letting me know about option -t that changed. It did not notice that !