Cleaned up the code

Removed global declarations, replaced with return functions. Simplified
variable names within functions.