Converted foreach loops to regular for loops