move functions out of loop and better labeling