Thanks for the suggestions. I tried a slightly different tack, and now it works a lot better…
The code I posted here wasn’t exactly descriptive of the progress I’d made, and would probably crash if you tried to run it.