I made stupid mistakes when using references together with foreach. This fixes it.