Better locking and refactoring