moving function out of loop