Some refactoring and slight mods