simplify code in while loop