Archer30, I don't know how to avoid ERM errors in this case, but I do know how to speed up the loop with UN:O and UN:I.
You need to use UN:O with 5 parameters and UN:I with 9 parameters, where the last parameter 0 means no redraw:
Redraw is on by default and slows down the script a lot in this case.
After the cycle ends, you can redraw the screen once.