Extracted function creation out of for loop

Also added comments.