Changed for loop to properlyt exit