moved flag def outside for loop