A: 

It appears that this works, after all.

I'm not sure what I was doing wrong, but after Ryan's response I rewrote the code, using the above pseudo code as a starting point. Now it seems to work.