Cleaned up loop, moved code to functions