At a lot of places global variables were used. Scoped them.
Merge from master