Some logic fixes and refactors