General cleanup and refactoring