My script very nearly worked properly. I'm hoping that one final tweak will be enough