Thank you both, Saq and Eric. My actual case is much more intricate so I've tried your solutions but they don't work there, unfortunately. I am, no surprise perhaps, working on EditorMagic and I'm about to make a public status update and had hoped to have this bit solved but it's just too complicated. So I'll post the update and if anyone is willing to take a look I'd be most happy.
Again thank you. The solution you did propose is still very good to know about. I had not properly looked at then+else before so this was valuable.
<:-)