Code cleanups and refactoring (first part)