Sorry, I still do not really understand the problem. Yes, I understand that your script does not work and is trading haywire, but I do not see why it is so difficult to fix it. It's only a few lines.

Can you show, as a first step, in the log what the problem is?