Did you consider using recursion for this specific purpose??