Found out a great recursive solution.