Thread safe

Various small fixes, and changed the lock granularity to threads.