Refactor while loops into recursions