I used bits of script from an action by Tim Nahumck, who also helped clean the code up in the original action.

Jimmy Reekes III @jmreekes