In case this helps anyone else (I stumbled across this when trying solve a very similar scenario).. Here's some code I wrote that does the same thing, not 100% tested across every conceivable case so I've added a 'limiter' to prevent any strange infinite loops which can probably be removed...