add locking to allow concurrent instances and other cleanups and changes