Refactor while loops in favour of for range