Add locking, fix few bugs