Refactoring/get rid of globals

This pull request contains pretty mechanical conversion of global variables (both function-level statics and true globals) into constants where applicable.