I’ve written this, it might do what you are looking for or maybe take control and copy some of the code.