flatten while loop correction