Some refactoring and cleaning up