Refactoring: Less hacks, fewer static vars, more re-usable code