Refactored code into logical sub-scripts and removed all global variables.