Remove the terrible, awful $x global var, and fix some bugs in the process