Hi AndrewAMD,

Thank you for your reply. You are correct.

Here are three versions of the script, just in case someone else runs into the same issue.
The optimize() call is placed at three different positions. One can clearly see what works and what doesn't.
Thanks to Petra and AndrewAMD, I think I get it now

Attached Files before_lookback.PNGoptimize after vars.PNGoptimize before usage.PNG