There are two related scripts, maybe they can be used as a base to implement all that you are asking for: