Added thread safety + minor fixes.