replace loop by function