This gets you very close:
Specifically this which I added recently which may do exactly as you require already.
Fork and expand as required.