Infinite loop replaced by flag