Moved code out of loop