I've seen this loop done already above. You might want to factorize those 2 into a helper function