Refactoring - clean up globals, tidy up events