Decided to go with a recursive solution, much more elegant.