Code reorganization and cleanup