Rewrite functions to use global variables.
More function optimization
Adjust scripts to new functions