change from foreach to for loop to try to reduce memory