Thank you Simon! Below is the fixed version of the minimal (still reduced from the original post) problem. Your fix also worked on my original code, so all in all this is resolved.
https://pastebin.com/fFu4fkAY 62