After a lot of experimenting I’ve come up with a function that seems to work fine so far, posted above. Thanks again.