move function out of loop