I think with some adjustment this script could get the job done if I understand correctly what you want.
This is what it looks like for me