Replacing  an ugly loop with a less ugly loop