Improvements to the code

Reduce the number of global variables and put most of them as function
parameters.
Removed Global variables and passed them as parameters.