Changed for loops to foreach