Some refactoring and logic cleanup