Modified for better synchronization and some optimizations.
Changes for optimizations.