code reorganization and minor improvements