I'd use tailrec instead of flag and while