Refactor out foreach loops