Updated code to scope local vars and should perform better on batch actions