Added locking to prevent race conditions, API fixes and reduced warnings