Some refactoring and trivial fixes