Some refactoring

Killed the globals, changed the code to use more functional programming things.