cleanup code replace while loop by for loop