code cleanup and better locking