System Delay to MIDI Beat Clock offset

Package published on October 18, 2020 by Ewan Pearson
Despite it being 2020 as I write MIDI delay compensation in Pro Tools is still woeful. Though Midi Beat Clock can be switched on and offset for any MIDI device or physical output, but there is no automatic adjustment of that clock in relation to the overall sytem delay.
If you want to sync external sequencers, drum machines and modular synths to Pro Tools and you don't own a dedicated hardware solution like an ERM Multiclock this can be a huge pain, especially as any time you instantiate or remove a plug-in in your session the overall system delay will change.
My very first script in Soundflow was a key command to open 'Session' window, wait 10ms and then open the 'MIDI/MIDI Beat Clock...' window as well so I could read the overall system delay and write it manually into the particular MIDI output offset slot.
My first ever question in the Soundflow forum was whether Soundflow could read a value from a window like 'Session' so that this could be automated further. Both Christian Scheuer and Chris Hayes kindly jumped in to help and came up with scripts. Combining both of their answers here's a script that opens 'Session', reads 'System Delay', copies this value to the clipboard, opens the MIDI Beat Clock menu and tabs to the offset slot of the first device in the list. All you have to do is choose which device(s) to paste the delay value into.
You may still have to use this multiple times in a session until you've committed an external part to audio, but this makes that much less of a pain.
Thanks so much to Christian and Chris for being superstars and coming up with this script! I am now trying to learn Javascript so I can do more of the next one myself....!

ATTENTION!
I am using Pro Tools Ultimate 2020.9.1 on an HD Native (Thunderbolt) system. You might have to tinker with the script if you're using a non-HD native system and the 'Session' window layout is different.
The MIDI Beat Clock WON'T open if Pro Tools is playing back, so make sure you've stopped before you run this script.