fixed various loop related bugs