Lots of code reorganization and fixes (too much to incrementally commit)