Just for the record, I'd like to take a whack at this one.
Someone can correct me if I am wrong (which might be rare looking at the activity in this forum) but there are 2 errors in my opinion:
1.) You are using a local variable 'x' without adding the local variable first using addlocalvariable() function.
2.) $r is not available to code added using insertBefore() function. Switching insertBefore() call to insertAfter() call should resolve this bug.
correction: it turns out that one can declare local variables directly via calls to insertBefore/insertAfter although it should be available only within that code block