clean up and fix some problems with global variables