Code reorganization and bug fixes