Code cleanup.

Global variables made more explicit with `global_` prefix.
Other misc refactoring.