Fixed various bugs, added locks