further refactoring..
more variable renaming and replacement of global variables.