moved function back into loop