move loop out of function