Some refactoring to remove globals