Moved some code out of a loop that doesn't need to execute on each iteration.