Code reorganization and minimal fixes