Reduce critical section protected by global lock

This tries to reduce the amount of operations done while holding the global lock. Also addresses bug #184.