Fix global variable leaks

At the moment this library has loads of global variable leaks and they're breaking my unit tests.  This change declares all the variables that are used.  I haven't attempted to fix the leaks in `dist` files as I assume those will get fixed automatically when you rebuild.