Replacing some manual iterations with standard algorithms. No functional changes intended.