def generateDoc(thisDoc, parentDoc, visitedDocNames):
    if (thisDoc.name in visitedDocNames):
        modelXbrl.error('loadFromExcel:circularDependency', 'Generation order dependency is circular: %(circularDependency)s', modelXbrl=modelXbrl, circularDependency=((','.join(visitedDocNames) + ', ') + thisDoc.name))
        return
    visitedDocNames.append(thisDoc.name)
    if (XbrlConst.xsd not in thisDoc.importXmlns.values()):
        eltName = 'schema xmlns="{}"'.format(XbrlConst.xsd)
    else:
        for (k, v) in thisDoc.importXmlns.items():
            if (v == XbrlConst.xsd):
                eltName = '{}:schema'.format(k)
                break
    doc = createModelDocument(modelXbrl, Type.SCHEMA, thisDoc.extensionSchemaFilename, isEntry=(parentDoc is None), documentEncoding='utf-8', base='', initialXml='\n        <{eltName}\n            targetNamespace="{targetNamespace}" \n            attributeFormDefault="unqualified" \n            elementFormDefault="qualified" \n            xmlns:xs="http://www.w3.org/2001/XMLSchema" \n            xmlns:{extensionPrefix}="{targetNamespace}"\n            {importXmlns} \n            xmlns:nonnum="http://www.xbrl.org/dtr/type/non-numeric" \n            xmlns:link="http://www.xbrl.org/2003/linkbase" \n            xmlns:xbrli="http://www.xbrl.org/2003/instance" \n            xmlns:xlink="http://www.w3.org/1999/xlink" \n            xmlns:xbrldt="http://xbrl.org/2005/xbrldt" \n            {schemaVersion}{xmlLang} />\n        '.format(eltName=eltName, targetNamespace=thisDoc.extensionSchemaNamespaceURI, extensionPrefix=thisDoc.extensionSchemaPrefix, importXmlns=''.join(('xmlns:{0}="{1}"\n'.format(prefix, namespaceURI) for (prefix, namespaceURI) in thisDoc.importXmlns.items())), schemaVersion=('version="{}" '.format(thisDoc.extensionSchemaVersion) if thisDoc.extensionSchemaVersion else ''), xmlLang=('\n xml:lang="{}"'.format(saveXmlLang) if saveXmlLang else '')), initialComment=thisDoc.initialComment)
    if (parentDoc is None):
        modelXbrl.modelDocument = doc
    thisDoc.generated = True
    doc.loadedFromExcel = True
    doc.inDTS = True
    doc.targetNamespace = thisDoc.extensionSchemaNamespaceURI
    schemaElt = doc.xmlRootElement
    annotationElt = XmlUtil.addChild(schemaElt, XbrlConst.xsd, 'annotation')
    if thisDoc.schemaDocumentation:
        XmlUtil.addChild(annotationElt, XbrlConst.xsd, 'documentation', text=thisDoc.schemaDocumentation)
    appinfoElt = XmlUtil.addChild(annotationElt, XbrlConst.xsd, 'appinfo')
    appinfoElt = XmlUtil.descendant(schemaElt, XbrlConst.xsd, 'appinfo')
    for filename in thisDoc.includes:
        XmlUtil.addChild(schemaElt, XbrlConst.xsd, 'include', attributes=(('schemaLocation', filename),))
    for (importPrefix, importAttributes) in sorted(thisDoc.imports.items(), key=(lambda item: item[1])):
        XmlUtil.addChild(schemaElt, XbrlConst.xsd, 'import', attributes=importAttributes)
        if ((importPrefix in genDocs) and (not genDocs[importPrefix].generated)):
            generateDoc(genDocs[importPrefix], doc, visitedDocNames)
    if any(((roleURI in thisDoc.extensionRoleLabels) for roleURI in thisDoc.extensionRoles.keys())):
        for importAttributes in ((('namespace', XbrlConst.gen), ('schemaLocation', 'http://www.xbrl.org/2008/generic-link.xsd')), (('namespace', XbrlConst.genLabel), ('schemaLocation', 'http://www.xbrl.org/2008/generic-label.xsd'))):
            XmlUtil.addChild(schemaElt, XbrlConst.xsd, 'import', attributes=importAttributes)
    _enumNum = [1]

    def addFacets(thisDoc, restrElt, facets):
        if facets:
            excludedEnumeration = facets.get('excludedEnumeration')
            if ((annotateEnumerationsDocumentation and (excludedEnumeration == 'X')) or (excludedEnumeration == 'D')):
                for (facet, facetValue) in facets.items():
                    if (facet == 'enumeration'):
                        enumerationsDocumentation = []
                        for valLbl in facetValue.split('\n'):
                            (val, _sep, _label) = valLbl.partition('=')
                            val = val.strip()
                            if len(val):
                                if (val == '(empty)'):
                                    val = ''
                                _label = _label.strip()
                                enumerationsDocumentation.append(('{}: {}'.format(val, _label) if _label else val))
                        XmlUtil.addChild(XmlUtil.addChild(restrElt, XbrlConst.xsd, 'annotation'), XbrlConst.xsd, 'documentation', text=' \n'.join(enumerationsDocumentation))
            for (facet, facetValue) in sorted(facets.items(), key=(lambda i: facetSortOrder.get(i[0], i[0]))):
                if (facet == 'enumeration'):
                    if ((not annotateEnumerationsDocumentation) and (not excludedEnumeration)):
                        for valLbl in facetValue.split('\n'):
                            (val, _sep, _label) = valLbl.partition('=')
                            val = val.strip()
                            _label = _label.strip()
                            if len(val):
                                if (val == '(empty)'):
                                    val = ''
                                _attributes = {'value': val}
                                if _label:
                                    _labelsByLang = None
                                    if (_label.startswith('{') and _label.endswith('}')):
                                        try:
                                            _labelsByLang = json.loads(_label)
                                        except json.decoder.JSONDecodeError:
                                            _labelsByLang = None
                                    _name = 'enum{}'.format(_enumNum[0])
                                    _attributes['id'] = ((thisDoc.extensionSchemaPrefix + '_') + _name)
                                    _enumNum[0] += 1
                                    if _labelsByLang:
                                        for (_lang, _langLabel) in _labelsByLang.items():
                                            thisDoc.extensionLabels[(thisDoc.extensionSchemaPrefix, _name, _lang, XbrlConst.genStandardLabel)] = _langLabel
                                    else:
                                        thisDoc.extensionLabels[(thisDoc.extensionSchemaPrefix, _name, defaultLabelLang, XbrlConst.genStandardLabel)] = _label
                                enumElt = XmlUtil.addChild(restrElt, XbrlConst.xsd, facet, attributes=_attributes)
                                if (thisDoc.hasEnumerationDocumentation and _label):
                                    if _labelsByLang:
                                        annotationElt = XmlUtil.addChild(enumElt, XbrlConst.xsd, 'annotation')
                                        for (_lang, _langLabel) in _labelsByLang.items():
                                            thisDoc.extensionLabels[(thisDoc.extensionSchemaPrefix, _name, _lang, XbrlConst.genStandardLabel)] = _langLabel
                                            XmlUtil.addChild(annotationElt, XbrlConst.xsd, 'documentation', text=_langLabel, attributes={'{http://www.w3.org/XML/1998/namespace}lang': _lang})
                                    else:
                                        XmlUtil.addChild(XmlUtil.addChild(enumElt, XbrlConst.xsd, 'annotation'), XbrlConst.xsd, 'documentation', text=_label)
                elif (facet != 'excludedEnumeration'):
                    XmlUtil.addChild(restrElt, XbrlConst.xsd, facet, attributes={'value': str(facetValue)})
    for (eltName, eltDef) in sorted(thisDoc.extensionElements.items(), key=(lambda item: item[0])):
        (eltAttrs, eltFacets) = eltDef
        if (eltFacets and ('type' in eltAttrs)):
            eltType = eltAttrs['type']
            del eltAttrs['type']
        if any(((':' in attrname) for attrname in eltAttrs.keys())):
            for (attrname, attrvalue) in eltAttrs.copy().items():
                if ((not attrname.startswith('{')) and (':' in attrname)):
                    del eltAttrs[attrname]
                    eltAttrs[schemaElt.prefixedNameQname(attrname).clarkNotation] = attrvalue
        isConcept = (eltAttrs.get('substitutionGroup') in ('xbrli:item', 'xbrli:tuple', 'xbrldt:hypercubeItem', 'xbrldt:dimensionItem'))
        elt = XmlUtil.addChild(schemaElt, XbrlConst.xsd, 'element', attributes=eltAttrs)
        if annotateElementDocumentation:
            for labelRole in (XbrlConst.documentationLabel, XbrlConst.genDocumentationLabel):
                labelKey = (thisDoc.extensionSchemaPrefix, eltAttrs['name'], defaultLabelLang, labelRole)
                if (labelKey in thisDoc.extensionLabels):
                    XmlUtil.addChild(XmlUtil.addChild(elt, XbrlConst.xsd, 'annotation'), XbrlConst.xsd, 'documentation', text=thisDoc.extensionLabels[labelKey])
                    break
        if ((elt is not None) and eltFacets and isConcept):
            cmplxType = XmlUtil.addChild(elt, XbrlConst.xsd, 'complexType')
            cmplxCont = XmlUtil.addChild(cmplxType, XbrlConst.xsd, 'simpleContent')
            restrElt = XmlUtil.addChild(cmplxCont, XbrlConst.xsd, 'restriction', attributes={'base': eltType})
            addFacets(thisDoc, restrElt, eltFacets)
            del eltType
    for (roleURI, (roleDefinition, usedOnRoles)) in sorted(thisDoc.extensionRoles.items(), key=(lambda rd: rd[1])):
        roleElt = XmlUtil.addChild(appinfoElt, XbrlConst.link, 'roleType', attributes=(('roleURI', roleURI), ('id', ('roleType_' + roleURI.rpartition('/')[2]))))
        if roleDefinition:
            XmlUtil.addChild(roleElt, XbrlConst.link, 'definition', text=roleDefinition)
        if usedOnRoles:
            for usedOnRole in usedOnRoles.split():
                XmlUtil.addChild(roleElt, XbrlConst.link, 'usedOn', text=usedOnRole)
        else:
            if (hasPreLB and any(((e.childStruct and e.isELR and ((e.role == roleURI) or (e.name == roleDefinition))) for e in preLB))):
                XmlUtil.addChild(roleElt, XbrlConst.link, 'usedOn', text='link:presentationLink')
            if (hasDefLB and any(((e.childStruct and e.isELR and ((e.role == roleURI) or (e.name == roleDefinition))) for e in defLB))):
                XmlUtil.addChild(roleElt, XbrlConst.link, 'usedOn', text='link:definitionLink')
            if (hasCalLB and any(((e.childStruct and e.isELR and ((e.role == roleURI) or (e.name == roleDefinition))) for e in calLB))):
                XmlUtil.addChild(roleElt, XbrlConst.link, 'usedOn', text='link:calculationLink')
            if (hasGenLB and any(((e.childStruct and e.isELR and ((e.role == roleURI) or (e.name == roleDefinition))) for e in genLB))):
                XmlUtil.addChild(roleElt, XbrlConst.link, 'usedOn', text=qname('{http://xbrl.org/2008/generic}genlink:link'))
    if any(((roleURI in thisDoc.extensionRoleLabels) for roleURI in thisDoc.extensionRoles.keys())):
        genLabLB = XmlUtil.addChild(appinfoElt, XbrlConst.link, 'linkbase')
        XmlUtil.addChild(genLabLB, XbrlConst.link, 'roleRef', attributes=(('roleURI', XbrlConst.genStandardLabel), ('{http://www.w3.org/1999/xlink}href', 'http://www.xbrl.org/2008/generic-label.xsd#standard-label'), ('{http://www.w3.org/1999/xlink}type', 'simple')))
        XmlUtil.addChild(genLabLB, XbrlConst.link, 'arcroleRef', attributes=(('arcroleURI', elementLabel), ('{http://www.w3.org/1999/xlink}href', 'http://www.xbrl.org/2008/generic-label.xsd#element-label'), ('{http://www.w3.org/1999/xlink}type', 'simple')))
        linkElt = XmlUtil.addChild(genLabLB, qname('{http://xbrl.org/2008/generic}genlink:link'), attributes=(('{http://www.w3.org/1999/xlink}type', 'extended'), ('{http://www.w3.org/1999/xlink}role', defaultLinkRole)))
        for (roleURI, _defLabel) in sorted(thisDoc.extensionRoles.items(), key=(lambda rd: rd[0])):
            if (roleURI in thisDoc.extensionRoleLabels):
                xlLabel = roleURI.rpartition('/')[2]
                XmlUtil.addChild(linkElt, XbrlConst.link, 'loc', attributes=(('{http://www.w3.org/1999/xlink}type', 'locator'), ('{http://www.w3.org/1999/xlink}href', ('#roleType_' + xlLabel)), ('{http://www.w3.org/1999/xlink}label', ('loc_' + xlLabel))))
                XmlUtil.addChild(linkElt, XbrlConst.qnGenArc, attributes=(('{http://www.w3.org/1999/xlink}type', 'arc'), ('{http://www.w3.org/1999/xlink}arcrole', elementLabel), ('{http://www.w3.org/1999/xlink}from', ('loc_' + xlLabel)), ('{http://www.w3.org/1999/xlink}to', ('label_' + xlLabel))))
                for (text, lang) in thisDoc.extensionRoleLabels[roleURI]:
                    XmlUtil.addChild(linkElt, qname('{http://xbrl.org/2008/label}genlabel:label'), attributes=(('{http://www.w3.org/1999/xlink}type', 'resource'), ('{http://www.w3.org/1999/xlink}label', ('label_' + xlLabel)), ('{http://www.w3.org/1999/xlink}role', XbrlConst.genStandardLabel), ('{http://www.w3.org/XML/1998/namespace}lang', lang)), text=text)

    def addLinkbaseRef(lbType, lbFilename, lbDoc):
        role = 'http://www.xbrl.org/2003/role/{0}LinkbaseRef'.format(lbType)
        lbRefElt = XmlUtil.addChild(appinfoElt, XbrlConst.link, 'linkbaseRef', attributes=((('{http://www.w3.org/1999/xlink}type', 'simple'), ('{http://www.w3.org/1999/xlink}href', docRelpath(lbFilename, thisDoc.extensionSchemaRelDirname)), ('{http://www.w3.org/1999/xlink}arcrole', 'http://www.w3.org/1999/xlink/properties/linkbase')) + (() if lbType.startswith('generic') else (('{http://www.w3.org/1999/xlink}role', role),))))
        if lbDoc:
            doc.referencesDocument[lbDoc] = ModelDocumentReference('href', lbRefElt)
    for (lbRefType, filename, generate) in thisDoc.linkbaseRefs:
        if (not generate):
            for otherGenDoc in genDocs.values():
                if ((not otherGenDoc.generated) and any((((_otherLbRefType == lbRefType) and (_otherFilename == filename) and _otherGenerate) for (_otherLbRefType, _otherFilename, _otherGenerate) in otherGenDoc.linkbaseRefs))):
                    generateDoc(otherGenDoc, doc, visitedDocNames)
            addLinkbaseRef(lbRefType, filename, None)
    doc.schemaDiscover(schemaElt, False, thisDoc.extensionSchemaNamespaceURI)
    for (typeName, typeDef) in sorted(thisDoc.extensionTypes.items(), key=(lambda item: item[0])):
        if (qname(thisDoc.extensionSchemaNamespaceURI, typeName) in modelXbrl.qnameTypes):
            continue
        (typeAttrs, typeFacets) = typeDef
        if (typeName.endswith('ItemType') or typeAttrs.get('base', '').endswith('ItemType')):
            cmplxType = XmlUtil.addChild(schemaElt, XbrlConst.xsd, 'complexType', attributes={'name': typeAttrs['name']})
            contElt = XmlUtil.addChild(cmplxType, XbrlConst.xsd, 'simpleContent')
        else:
            contElt = XmlUtil.addChild(schemaElt, XbrlConst.xsd, 'simpleType', attributes={'name': typeAttrs['name']})
        restrElt = XmlUtil.addChild(contElt, XbrlConst.xsd, 'restriction', attributes={'base': typeAttrs['base']})
        baseQn = qname(schemaElt, typeAttrs.get('base'))
        if typeFacets:
            if (baseQn and (baseQn.namespaceURI not in (XbrlConst.xsd, XbrlConst.xbrli)) and (baseQn in modelXbrl.qnameTypes)):
                baseTypeFacets = (modelXbrl.qnameTypes[baseQn].facets or ())
                typeFacets = dict(((facet, value) for (facet, value) in typeFacets.items() if ((facet not in baseTypeFacets) or (str(baseTypeFacets[facet]) != value))))
            addFacets(thisDoc, restrElt, typeFacets)
    extLabelRoles = {}
    extReferenceRoles = {}
    extReferenceParts = {}
    extReferenceSchemaDocs = {}
    extUnrecognizedRoles = set()
    relationshipArcroles = {}
    relationshipArcqnames = {}

    def setExtRefPart(partLocalName):
        if (partLocalName not in extReferenceParts):
            for partConcept in modelXbrl.nameConcepts.get(partLocalName, ()):
                if ((partConcept is not None) and (partConcept.subGroupHeadQname == qnLinkPart)):
                    extReferenceParts[partLocalName] = partConcept.qname
                    extReferenceSchemaDocs[partConcept.qname.namespaceURI] = (partConcept.modelDocument.uri if partConcept.modelDocument.uri.startswith('http://') else partConcept.modelDocument.basename)
                    break
    for _headerColKey in headerColsAllElrs:
        if (isinstance(_headerColKey, tuple) and (len(_headerColKey) >= 3) and (not _headerColKey[1].startswith('http://'))):
            _resourceType = _headerColKey[0]
            _resourceRole = _headerColKey[1]
            _resourceLangOrPart = _headerColKey[2]
        elif (isinstance(_headerColKey, str) and ('!reference' in _headerColKey)):
            m = resourceParsePattern.match(_headerColKey.partition('!')[2])
            _resourceType = m.group(1)
            _resourceRole = ('/' + m.group(2))
            _resourceLangOrPart = m.group(4)
        else:
            continue
        (_resourceQName, _standardRoles) = {'label': (qnLinkLabel, standardLabelRoles), 'labels': (qnLinkLabel, standardLabelRoles), 'reference': (qnLinkReference, standardReferenceRoles), 'references': (qnLinkReference, standardReferenceRoles)}.get(_resourceType, (None, ()))
        _resourceRoleURI = None
        for _roleURI in _standardRoles:
            if _roleURI.endswith(_resourceRole):
                _resourceRoleURI = _roleURI
                _resourceRoleMatchPart = _resourceRole
                break
        if (_resourceRoleURI is None):
            _resourceRoleMatchPart = _resourceRole.partition('#')[0]
            for _roleURI in modelXbrl.roleTypes:
                if _roleURI.endswith(_resourceRoleMatchPart):
                    for _roleType in modelXbrl.roleTypes[_roleURI]:
                        if (_resourceQName in _roleType.usedOns):
                            _resourceRoleURI = _roleURI
                            break
        if (_resourceType in ('label', 'labels')):
            if _resourceRoleURI:
                extLabelRoles[_resourceRoleMatchPart] = _resourceRoleURI
            elif any(((_resourceRoleMatchPart == k[2]) for k in thisDoc.extensionLabels.keys())):
                modelXbrl.error('loadFromExcel:labelResourceRole', 'Label resource role not found: %(role)s', modelXbrl=modelXbrl, role=_resourceRoleMatchPart, filename=thisDoc.extensionSchemaNamespaceURI)
        elif (_resourceType in ('reference', 'references')):
            if _resourceRoleURI:
                extReferenceRoles[_resourceRoleMatchPart] = _resourceRoleURI
                setExtRefPart(_resourceLangOrPart)
            elif any(((_resourceRoleMatchPart == k[2]) for k in thisDoc.extensionReferences.keys())):
                modelXbrl.error('loadFromExcel:referenceResourceRole', 'Reference resource role not found: %(role)s', modelXbrl=modelXbrl, role=_resourceRoleMatchPart, filename=thisDoc.extensionSchemaNamespaceURI)
        elif (_resourceType == 'relationship to'):
            for _arcroleURI in modelXbrl.arcroleTypes:
                if _arcroleURI.endswith(_resourceRoleMatchPart):
                    for _arcroleType in modelXbrl.arcroleTypes[_arcroleURI]:
                        for _resourceQName in _arcroleType.usedOns:
                            break
                    break
            if (_resourceQName is None):
                modelXbrl.error('loadFromExcel:relationshipArcrole', 'Relationship arcrole not found: %(arcrole)s', modelXbrl=modelXbrl, arcrole=_resourceRoleMatchPart, filename=thisDoc.extensionSchemaNamespaceURI)
            else:
                relationshipArcroles[_resourceRoleMatchPart] = _arcroleURI
                relationshipArcqnames[_arcroleURI] = _resourceQName
    for (lbType, lang, filename) in thisDoc.labelLinkbases:
        thisDoc.thisLBdir = posixpath.dirname(filename)
        langPattern = re.compile((lang or '.*'))
        _isGeneric = lbType.startswith('generic')
        if (_isGeneric and ('http://xbrl.org/2008/label' not in modelXbrl.namespaceDocs)):
            ModelDocument.load(modelXbrl, 'http://www.xbrl.org/2008/generic-link.xsd', isDiscovered=True)
            ModelDocument.load(modelXbrl, 'http://www.xbrl.org/2008/generic-label.xsd', isDiscovered=True)
        lbDoc = ModelDocument.create(modelXbrl, ModelDocument.Type.LINKBASE, filename, base='', initialXml='\n            <linkbase \n                xmlns="http://www.xbrl.org/2003/linkbase" \n                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" \n                xmlns:xlink="http://www.w3.org/1999/xlink" \n                xmlns:xbrli="http://www.xbrl.org/2003/instance"\n                {}\n                xsi:schemaLocation="http://www.xbrl.org/2003/linkbase \n                http://www.xbrl.org/2003/xbrl-linkbase-2003-12-31.xsd{}" \n                {}>{}</linkbase>\n            '.format(('\n                xmlns:genlink="http://xbrl.org/2008/generic"\n                xmlns:genlabel="http://xbrl.org/2008/label"\n                ' if _isGeneric else ''), ('\n                http://xbrl.org/2008/generic  http://www.xbrl.org/2008/generic-link.xsd\n                http://xbrl.org/2008/label  http://www.xbrl.org/2008/generic-label.xsd\n                ' if _isGeneric else ''), ('\n xml:lang="{}"'.format(saveXmlLang) if saveXmlLang else ''), ('\n                <arcroleRef arcroleURI="http://xbrl.org/arcrole/2008/element-label" xlink:href="http://www.xbrl.org/2008/generic-label.xsd#element-label" xlink:type="simple"/>\n                ' if _isGeneric else '')), initialComment=thisDoc.initialComment)
        lbDoc.inDTS = True
        lbDoc.loadedFromExcel = True
        if isGenerateAndImport:
            addLinkbaseRef(lbType, filename, lbDoc)
        lbElt = lbDoc.xmlRootElement
        linkElt = XmlUtil.addChild(lbElt, (gen if _isGeneric else link), ('link' if _isGeneric else 'labelLink'), attributes=(('{http://www.w3.org/1999/xlink}type', 'extended'), ('{http://www.w3.org/1999/xlink}role', defaultLinkRole)))
        firstLinkElt = linkElt
        locs = set()
        roleRefs = set()
        for (labelKey, text) in thisDoc.extensionLabels.items():
            (prefix, name, labelLang, role) = labelKey
            labelLang = (labelLang or defaultLabelLang)
            role = role.partition('#')[0]
            role = extLabelRoles.get(role, role)
            if (langPattern.match(labelLang) and (_isGeneric == (role in (XbrlConst.genStandardLabel, XbrlConst.genDocumentationLabel)))):
                locLabel = ((prefix + '_') + name)
                if (locLabel not in locs):
                    locs.add(locLabel)
                    XmlUtil.addChild(linkElt, XbrlConst.link, 'loc', attributes=(('{http://www.w3.org/1999/xlink}type', 'locator'), ('{http://www.w3.org/1999/xlink}href', LBHref(thisDoc, prefix, name)), ('{http://www.w3.org/1999/xlink}label', locLabel)))
                    XmlUtil.addChild(linkElt, (gen if _isGeneric else link), ('arc' if _isGeneric else 'labelArc'), attributes=(('{http://www.w3.org/1999/xlink}type', 'arc'), ('{http://www.w3.org/1999/xlink}arcrole', (elementLabel if _isGeneric else conceptLabel)), ('{http://www.w3.org/1999/xlink}from', locLabel), ('{http://www.w3.org/1999/xlink}to', ('label_' + locLabel)), ('order', 1.0)))
                XmlUtil.addChild(linkElt, (XbrlConst.genLabel if _isGeneric else XbrlConst.link), 'label', attributes=((('{http://www.w3.org/1999/xlink}type', 'resource'), ('{http://www.w3.org/1999/xlink}label', ('label_' + locLabel)), ('{http://www.w3.org/1999/xlink}role', role)) + ((('{http://www.w3.org/XML/1998/namespace}lang', labelLang),) if (True or (lang != saveXmlLang)) else ())), text=text)
                if role:
                    if (role in XbrlConst.standardLabelRoles):
                        pass
                    elif (role in modelXbrl.roleTypes):
                        roleType = modelXbrl.roleTypes[role][0]
                        roleRefs.add(('roleRef', role, ((roleType.modelDocument.uri + '#') + roleType.id)))
                    elif role.startswith('http://www.xbrl.org/2009/role/negated'):
                        roleRefs.add(('roleRef', role, ('http://www.xbrl.org/lrr/role/negated-2009-12-16.xsd#' + role.rpartition('/')[2])))
                    else:
                        extUnrecognizedRoles.add(role)
        for (roleref, roleURI, href) in roleRefs:
            XmlUtil.addChild(lbElt, XbrlConst.link, roleref, attributes=((('arcroleURI' if (roleref == 'arcroleRef') else 'roleURI'), roleURI), ('{http://www.w3.org/1999/xlink}type', 'simple'), ('{http://www.w3.org/1999/xlink}href', href)), beforeSibling=firstLinkElt)
        lbDoc.linkbaseDiscover(lbElt)
        if extUnrecognizedRoles:
            modelXbrl.error('loadFromExcel:undefinedLabelRole', 'Label roles not defined: %(undefinedRoles)s', modelXbrl=modelXbrl, undefinedRoles=','.join(sorted(extUnrecognizedRoles)))
            extUnrecognizedRoles.clear()
    for (lbType, referenceRole, filename) in thisDoc.referenceLinkbases:
        thisDoc.thisLBdir = posixpath.dirname(filename)
        _isGeneric = lbType.startswith('generic')
        lbDoc = ModelDocument.create(modelXbrl, ModelDocument.Type.LINKBASE, filename, base='', initialXml='\n            <linkbase \n                xmlns="http://www.xbrl.org/2003/linkbase" \n                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" \n                xmlns:xlink="http://www.w3.org/1999/xlink" \n                xmlns:xbrli="http://www.xbrl.org/2003/instance"\n                {}\n                xsi:schemaLocation="http://www.xbrl.org/2003/linkbase \n                http://www.xbrl.org/2003/xbrl-linkbase-2003-12-31.xsd{}{}" \n                {}>{}</linkbase>\n            '.format(('\n                xmlns:genlink="http://xbrl.org/2008/generic"\n                xmlns:genreference="http://xbrl.org/2008/rerference"\n                ' if _isGeneric else ''), ''.join([' {} {}'.format(_ns, _uri) for (_ns, _uri) in extReferenceSchemaDocs.items()]), ('\n                http://xbrl.org/2008/generic  http://www.xbrl.org/2008/generic-link.xsd\n                http://xbrl.org/2008/reference  http://www.xbrl.org/2008/generic-reference.xsd\n                ' if _isGeneric else ''), ('\n xml:lang="{}"'.format(saveXmlLang) if saveXmlLang else ''), ('\n                <roleRef roleURI="http://www.xbrl.org/2008/role/label" xlink:href="http://www.xbrl.org/2008/generic-label.xsd#standard-label" xlink:type="simple"/>\n                <arcroleRef arcroleURI="http://xbrl.org/arcrole/2008/element-reference" xlink:href="http://xbrl.org/2008/generic-reference.xsd#element-reference" xlink:type="simple"/>\n                ' if _isGeneric else '')), initialComment=thisDoc.initialComment)
        lbDoc.inDTS = True
        lbDoc.loadedFromExcel = True
        if isGenerateAndImport:
            addLinkbaseRef(lbType, filename, lbDoc)
        lbElt = lbDoc.xmlRootElement
        linkElt = XmlUtil.addChild(lbElt, (XbrlConst.gen if _isGeneric else XbrlConst.link), ('link' if _isGeneric else 'referenceLink'), attributes=(('{http://www.w3.org/1999/xlink}type', 'extended'), ('{http://www.w3.org/1999/xlink}role', defaultLinkRole)))
        firstLinkElt = linkElt
        locs = set()
        roleRefs = set()
        undefinedReferenceParts = set()
        for (referenceKey, references) in thisDoc.extensionReferences.items():
            (prefix, name, role) = referenceKey
            role = role.partition('#')[0]
            role = extReferenceRoles.get(role, role)
            if fnmatch(role, referenceRole):
                locLabel = ((prefix + '_') + name)
                if (locLabel not in locs):
                    locs.add(locLabel)
                    order = 1
                else:
                    for order in range(2, 1000):
                        _locLabel = '{}_{}'.format(locLabel, order)
                        if (_locLabel not in locs):
                            locLabel = _locLabel
                            locs.add(locLabel)
                            break
                    if (order > 999):
                        print('resource order de-duplicate failure, too many reference parts')
                XmlUtil.addChild(linkElt, XbrlConst.link, 'loc', attributes=(('{http://www.w3.org/1999/xlink}type', 'locator'), ('{http://www.w3.org/1999/xlink}href', LBHref(thisDoc, prefix, name)), ('{http://www.w3.org/1999/xlink}label', locLabel)))
                XmlUtil.addChild(linkElt, XbrlConst.link, 'referenceArc', attributes=(('{http://www.w3.org/1999/xlink}type', 'arc'), ('{http://www.w3.org/1999/xlink}arcrole', conceptReference), ('{http://www.w3.org/1999/xlink}from', locLabel), ('{http://www.w3.org/1999/xlink}to', ('label_' + locLabel)), ('order', order)))
                referenceResource = XmlUtil.addChild(linkElt, (XbrlConst.genReference if _isGeneric else XbrlConst.link), 'reference', attributes=(('{http://www.w3.org/1999/xlink}type', 'resource'), ('{http://www.w3.org/1999/xlink}label', ('label_' + locLabel)), ('{http://www.w3.org/1999/xlink}role', role)))
                for (part, text) in references:
                    setExtRefPart(part)
                    if (part in extReferenceParts):
                        partQn = extReferenceParts.get(part, part)
                        XmlUtil.addChild(referenceResource, partQn, text=text)
                    else:
                        undefinedReferenceParts.add(part)
                if role:
                    if (role in XbrlConst.standardLabelRoles):
                        pass
                    elif (role in modelXbrl.roleTypes):
                        roleType = modelXbrl.roleTypes[role][0]
                        roleRefs.add(('roleRef', role, ((roleType.modelDocument.uri + '#') + roleType.id)))
                    elif role.startswith('http://www.xbrl.org/2009/role/negated'):
                        roleRefs.add(('roleRef', role, ('http://www.xbrl.org/lrr/role/negated-2009-12-16.xsd#' + role.rpartition('/')[2])))
                    else:
                        extUnrecognizedRoles.add(role)
        for part in sorted(undefinedReferenceParts):
            print('reference part not defined: {}'.format(part))
        for (roleref, roleURI, href) in roleRefs:
            XmlUtil.addChild(lbElt, XbrlConst.link, roleref, attributes=((('arcroleURI' if (roleref == 'arcroleRef') else 'roleURI'), roleURI), ('{http://www.w3.org/1999/xlink}type', 'simple'), ('{http://www.w3.org/1999/xlink}href', href)), beforeSibling=firstLinkElt)
        lbDoc.linkbaseDiscover(lbElt)
        if extUnrecognizedRoles:
            modelXbrl.error('loadFromExcel:undefinedReferenceRole', 'Reference roles not defined: %(undefinedRoles)s', modelXbrl=modelXbrl, undefinedRoles=','.join(sorted(extUnrecognizedRoles)))
            extUnrecognizedRoles.clear()
    prefixedNamespaces = modelXbrl.prefixedNamespaces

    def hrefConcept(prefix, name):
        qn = qname(prefixedNamespaces[prefix], name)
        if (qn in modelXbrl.qnameConcepts):
            return modelXbrl.qnameConcepts[qn]
        elif (name in modelXbrl.nameConcepts):
            return modelXbrl.nameConcepts[name][0]
        if (prefix not in prefixedNamespaces):
            modelXbrl.error('loadFromExcel:undefinedRelationshipElementPrefix', 'Prefix not defined: %(prefix)s', modelXbrl=modelXbrl, prefix=prefix)
            return None
        modelXbrl.error('loadFromExcel:undefinedRelationshipElement', 'QName not defined: %(prefix)s:%(localName)s', modelXbrl=modelXbrl, prefix=prefix, localName=name)
        return None

    def prefixedNameQName(prefixedName):
        if (':' not in prefixedName):
            return prefixedName
        (prefix, _sep, name) = prefixedName.rpartition(':')
        if (prefix not in prefixedNamespaces):
            modelXbrl.error('loadFromExcel:undefinedRelationshipAttributePrefix', 'Prefix not defined: %(prefix)s', modelXbrl=modelXbrl, prefix=prefix)
            return prefixedName
        return QName(prefix, prefixedNamespaces[prefix], name)

    def lbTreeWalk(lbType, parentElt, lbStruct, roleRefs, dimDef=False, locs=None, arcsFromTo=None, fromPrefix=None, fromName=None):
        order = 1.0
        for lbEntry in lbStruct:
            if lbEntry.isELR:
                if (not lbEntry.childStruct):
                    continue
                role = 'unspecified'
                if (lbEntry.role and lbEntry.role.startswith('http://')):
                    role = lbEntry.role
                elif lbEntry.name:
                    for (linkroleUri, modelRoleTypes) in modelXbrl.roleTypes.items():
                        definition = modelRoleTypes[0].definition
                        if ((lbEntry.name == definition) and (linkroleUri in thisDoc.extensionRoles)):
                            role = linkroleUri
                            break
                if (role == 'unspecified'):
                    continue
                if (role not in thisDoc.extensionRoles):
                    continue
                if (role == XbrlConst.defaultLinkRole):
                    pass
                elif (role in thisDoc.extensionRoles):
                    roleRefs.add(('roleRef', role, ((doc.uri + '#roleType_') + role.rpartition('/')[2])))
                elif (role in modelXbrl.roleTypes):
                    roleType = modelRoleTypes[0]
                    roleRefs.add(('roleRef', role, ((roleType.modelDocument.uri + '#') + roleType.id)))
                else:
                    extUnrecognizedRoles.add(role)
                linkElt = XmlUtil.addChild(parentElt, (XbrlConst.gen if (lbType == 'generic') else XbrlConst.link), ('link' if (lbType == 'generic') else (lbType + 'Link')), attributes=(('{http://www.w3.org/1999/xlink}type', 'extended'), ('{http://www.w3.org/1999/xlink}role', role)))
                locs = set()
                arcsFromTo = set()
                lbTreeWalk(lbType, linkElt, lbEntry.childStruct, roleRefs, dimDef, locs, arcsFromTo)
            else:
                toPrefix = lbEntry.prefix
                toName = lbEntry.name
                toHref = LBHref(thisDoc, toPrefix, toName)
                if (toHref is None):
                    modelXbrl.error('loadFromExcel:invalidQName', "%(linkbase)s relationship element with prefix '%(prefix)s' localName '%(localName)s' not found", modelXbrl=modelXbrl, linkbase=lbType, prefix=lbEntry.prefix, localName=lbEntry.name)
                    continue
                if ((not toPrefix) and (toName in modelXbrl.nameConcepts)):
                    toPrefix = modelXbrl.nameConcepts[toName][0].qname.prefix
                toLabel = '{}_{}'.format(toPrefix, toName)
                toLabelAlt = None
                if (not lbEntry.isRoot):
                    if ((not fromPrefix) and (fromName in modelXbrl.nameConcepts)):
                        fromPrefix = modelXbrl.nameConcepts[fromName][0].qname.prefix
                    fromLabel = '{}_{}'.format(fromPrefix, fromName)
                    if ((fromLabel, toLabel) in arcsFromTo):
                        for i in range(1, 1000):
                            toLabelAlt = '{}_{}'.format(toLabel, i)
                            if ((fromLabel, toLabelAlt) not in arcsFromTo):
                                toLabel = toLabelAlt
                                break
                if (((toHref not in locs) or toLabelAlt) and (not dimDef)):
                    XmlUtil.addChild(parentElt, XbrlConst.link, 'loc', attributes=(('{http://www.w3.org/1999/xlink}type', 'locator'), ('{http://www.w3.org/1999/xlink}href', toHref), ('{http://www.w3.org/1999/xlink}label', toLabel)))
                    locs.add(toHref)
                if (not lbEntry.isRoot):
                    arcsFromTo.add((fromLabel, toLabel))
                    if ((lbType == 'calculation') and (lbEntry.weight is not None)):
                        otherAttrs = (('weight', lbEntry.weight),)
                    elif ((lbType == 'presentation') and lbEntry.role):
                        if (not lbEntry.role.startswith('http://')):
                            _labelRoleMatchPart = ('/' + lbEntry.role)
                            for _roleURI in modelXbrl.roleTypes:
                                if _roleURI.endswith(_labelRoleMatchPart):
                                    for _roleType in modelXbrl.roleTypes[_roleURI]:
                                        if (XbrlConst.qnLinkLabel in _roleType.usedOns):
                                            lbEntry.role = _roleURI
                                            break
                        if (not lbEntry.role.startswith('http://')):
                            lbEntry.role = ('http://www.xbrl.org/2003/role/' + lbEntry.role)
                        otherAttrs = (('preferredLabel', lbEntry.role),)
                        if (lbEntry.role and (lbEntry.role not in XbrlConst.standardLabelRoles)):
                            if (lbEntry.role in modelXbrl.roleTypes):
                                roleType = modelXbrl.roleTypes[lbEntry.role][0]
                                roleRefs.add(('roleRef', lbEntry.role, ((roleType.modelDocument.uri + '#') + roleType.id)))
                            else:
                                extUnrecognizedRoles.add(lbEntry.role)
                    elif ((lbType == 'generic') and lbEntry.arcrole):
                        if (not lbEntry.arcrole.startswith('http://')):
                            for _arcroleURI in modelXbrl.arcroleTypes:
                                if _arcroleURI.endswith(lbEntry.arcrole):
                                    lbEntry.arcrole = _arcroleURI
                                    break
                        otherAttrs = tuple(((prefixedNameQName(_key), _value) for (_key, _value) in (lbEntry.relAttrs.items() if (lbEntry.relAttrs is not None) else ())))
                    else:
                        otherAttrs = ()
                    if (lbEntry.arcrole == '_dimensions_'):
                        fromConcept = hrefConcept(fromPrefix, fromName)
                        toConcept = hrefConcept(toPrefix, toName)
                        if dimDef:
                            if ((lbEntry.role != '_dimensionDefault_') and (not lbTreeHasDimDefault(lbEntry.childStruct))):
                                continue
                            if ((toConcept is not None) and (toConcept.isDimensionItem or (lbEntry.role == '_dimensionDefault_'))):
                                if ((toHref not in locs) or toLabelAlt):
                                    XmlUtil.addChild(parentElt, XbrlConst.link, 'loc', attributes=(('{http://www.w3.org/1999/xlink}type', 'locator'), ('{http://www.w3.org/1999/xlink}href', toHref), ('{http://www.w3.org/1999/xlink}label', toLabel)))
                                    locs.add(toHref)
                                if (lbEntry.role != '_dimensionDefault_'):
                                    lbTreeWalk(lbType, parentElt, lbEntry.childStruct, roleRefs, dimDef, locs, arcsFromTo, toPrefix, toName)
                                else:
                                    XmlUtil.addChild(parentElt, XbrlConst.link, 'definitionArc', attributes=((('{http://www.w3.org/1999/xlink}type', 'arc'), ('{http://www.w3.org/1999/xlink}arcrole', XbrlConst.dimensionDefault), ('{http://www.w3.org/1999/xlink}from', fromLabel), ('{http://www.w3.org/1999/xlink}to', toLabel), ('order', order)) + otherAttrs))
                                    order += 1.0
                            else:
                                lbTreeWalk(lbType, parentElt, lbEntry.childStruct, roleRefs, dimDef, locs, arcsFromTo, fromPrefix, fromName)
                            continue
                        elif ((toConcept is not None) and toConcept.isHypercubeItem):
                            arcrole = XbrlConst.all
                            otherAttrs += ((XbrlConst.qnXbrldtContextElement, 'segment'), (qnXbrldtClosed, 'true'))
                        elif ((toConcept is not None) and toConcept.isDimensionItem):
                            arcrole = XbrlConst.hypercubeDimension
                        elif ((fromConcept is not None) and fromConcept.isDimensionItem):
                            arcrole = XbrlConst.dimensionDomain
                        else:
                            arcrole = XbrlConst.domainMember
                    else:
                        arcrole = lbEntry.arcrole
                    if (arcrole in relationshipArcqnames):
                        arcqname = relationshipArcqnames[arcrole]
                        arcNS = arcqname.namespaceURI
                        arcLocalname = arcqname.localName
                    elif (lbType == 'generic'):
                        arcNS = XbrlConst.gen
                        arcLocalname = 'arc'
                    else:
                        arcNS = XbrlConst.link
                        arcLocalname = (lbType + 'Arc')
                    XmlUtil.addChild(parentElt, arcNS, arcLocalname, attributes=((('{http://www.w3.org/1999/xlink}type', 'arc'), ('{http://www.w3.org/1999/xlink}arcrole', arcrole), ('{http://www.w3.org/1999/xlink}from', fromLabel), ('{http://www.w3.org/1999/xlink}to', toLabel), ('order', order)) + otherAttrs))
                    order += 1.0
                if ((lbType != 'calculation') or lbEntry.isRoot):
                    lbTreeWalk(lbType, parentElt, lbEntry.childStruct, roleRefs, dimDef, locs, arcsFromTo, toPrefix, toName)

    def lbTreeHasDimDefault(lbStruct):
        for lbEntry in lbStruct:
            if lbEntry.isELR:
                if (not lbEntry.childStruct):
                    continue
                if lbTreeHasDimDefault(lbEntry.childStruct):
                    return True
            else:
                if ((not lbEntry.isRoot) and ((lbEntry.arcrole == '_dimensions_') and (lbEntry.role == '_dimensionDefault_'))):
                    return True
                if lbTreeHasDimDefault(lbEntry.childStruct):
                    return True
        return False
    for (hasLB, lbType, lbLB) in (((hasPreLB and thisDoc.hasPreLB), 'presentation', preLB), ((hasDefLB and thisDoc.hasDefLB), 'definition', defLB), ((hasCalLB and thisDoc.hasCalLB), 'calculation', calLB), ((hasGenLB and thisDoc.hasGenLB), 'generic', genLB)):
        if hasLB:
            for (lbRefType, filename, generate) in thisDoc.linkbaseRefs:
                thisDoc.thisLBdir = posixpath.dirname(filename)
                if (generate and (lbType == lbRefType)):
                    lbDoc = ModelDocument.create(modelXbrl, ModelDocument.Type.LINKBASE, filename, base='', initialXml='\n                        <linkbase \n                            xmlns="http://www.xbrl.org/2003/linkbase" \n                            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" \n                            xmlns:xlink="http://www.w3.org/1999/xlink" \n                            xmlns:xbrli="http://www.xbrl.org/2003/instance"{}\n                            xsi:schemaLocation="http://www.xbrl.org/2003/linkbase \n                            http://www.xbrl.org/2003/xbrl-linkbase-2003-12-31.xsd{}" \n                            />\n                        '.format(('\n                        xmlns:generic="http://xbrl.org/2008/generic"\n                        ' if (lbType == 'generic') else ''), ('\n                        http://xbrl.org/2008/generic  http://www.xbrl.org/2008/generic-link.xsd\n                        ' if (lbType == 'generic') else '')), initialComment=thisDoc.initialComment)
                    lbDoc.inDTS = True
                    lbDoc.loadedFromExcel = True
                    addLinkbaseRef(lbRefType, filename, lbDoc)
                    lbElt = lbDoc.xmlRootElement
                    roleRefs = set()
                    if (lbType == 'definition'):
                        roleRefs.update((('arcroleRef', XbrlConst.all, 'http://www.xbrl.org/2005/xbrldt-2005.xsd#all'), ('arcroleRef', XbrlConst.dimensionDefault, 'http://www.xbrl.org/2005/xbrldt-2005.xsd#dimension-default'), ('arcroleRef', XbrlConst.dimensionDomain, 'http://www.xbrl.org/2005/xbrldt-2005.xsd#dimension-domain'), ('arcroleRef', XbrlConst.domainMember, 'http://www.xbrl.org/2005/xbrldt-2005.xsd#domain-member'), ('arcroleRef', XbrlConst.hypercubeDimension, 'http://www.xbrl.org/2005/xbrldt-2005.xsd#hypercube-dimension')))
                    elif (lbType == 'generic'):
                        for _arcroleURI in relationshipArcroles.values():
                            for _arcroleType in modelXbrl.arcroleTypes[_arcroleURI]:
                                roleRefs.add(('arcroleRef', _arcroleURI, ((_arcroleType.modelDocument.uri + '#') + _arcroleType.id)))
                                break
                    lbTreeWalk(lbType, lbElt, lbLB, roleRefs)
                    if ((lbType == 'definition') and lbTreeHasDimDefault(lbLB)):
                        lbTreeWalk(lbType, lbElt, lbLB, roleRefs, dimDef=True)
                    firstLinkElt = None
                    for firstLinkElt in lbElt.iterchildren():
                        break
                    for (roleref, roleURI, href) in roleRefs:
                        XmlUtil.addChild(lbElt, link, roleref, attributes=((('arcroleURI' if (roleref == 'arcroleRef') else 'roleURI'), roleURI), ('{http://www.w3.org/1999/xlink}type', 'simple'), ('{http://www.w3.org/1999/xlink}href', docRelpath(href, thisDoc.thisLBdir))), beforeSibling=firstLinkElt)
                    lbDoc.linkbaseDiscover(lbElt)
                    break
            if extUnrecognizedRoles:
                modelXbrl.error('loadFromExcel:undefinedRole', '%(lbType)s linkbase roles not defined: %(undefinedRoles)s', modelXbrl=modelXbrl, lbType=lbType, undefinedRoles=','.join(sorted(extUnrecognizedRoles)))
                extUnrecognizedRoles.clear()
    visitedDocNames.pop()
def generateDoc(thisDoc, parentDoc, visitedDocNames):
    if (thisDoc.name in visitedDocNames):
        modelXbrl.error('loadFromExcel:circularDependency', 'Generation order dependency is circular: %(circularDependency)s', modelXbrl=modelXbrl, circularDependency=((','.join(visitedDocNames) + ', ') + thisDoc.name))
        return
    visitedDocNames.append(thisDoc.name)
    if (XbrlConst.xsd not in thisDoc.importXmlns.values()):
        eltName = 'schema xmlns="{}"'.format(XbrlConst.xsd)
    else:
        for (k, v) in thisDoc.importXmlns.items():
            if (v == XbrlConst.xsd):
                eltName = '{}:schema'.format(k)
                break
    doc = createModelDocument(modelXbrl, Type.SCHEMA, thisDoc.extensionSchemaFilename, isEntry=(parentDoc is None), documentEncoding='utf-8', base=, initialXml='\n        <{eltName}\n            targetNamespace="{targetNamespace}" \n            attributeFormDefault="unqualified" \n            elementFormDefault="qualified" \n            xmlns:xs="http://www.w3.org/2001/XMLSchema" \n            xmlns:{extensionPrefix}="{targetNamespace}"\n            {importXmlns} \n            xmlns:nonnum="http://www.xbrl.org/dtr/type/non-numeric" \n            xmlns:link="http://www.xbrl.org/2003/linkbase" \n            xmlns:xbrli="http://www.xbrl.org/2003/instance" \n            xmlns:xlink="http://www.w3.org/1999/xlink" \n            xmlns:xbrldt="http://xbrl.org/2005/xbrldt" \n            {schemaVersion}{xmlLang} />\n        '.format(eltName=eltName, targetNamespace=thisDoc.extensionSchemaNamespaceURI, extensionPrefix=thisDoc.extensionSchemaPrefix, importXmlns=.join(('xmlns:{0}="{1}"\n'.format(prefix, namespaceURI) for (prefix, namespaceURI) in thisDoc.importXmlns.items())), schemaVersion=('version="{}" '.format(thisDoc.extensionSchemaVersion) if thisDoc.extensionSchemaVersion else ), xmlLang=('\n xml:lang="{}"'.format(saveXmlLang) if saveXmlLang else )), initialComment=thisDoc.initialComment)
    if (parentDoc is None):
        modelXbrl.modelDocument = doc
    thisDoc.generated = True
    doc.loadedFromExcel = True
    doc.inDTS = True
    doc.targetNamespace = thisDoc.extensionSchemaNamespaceURI
    schemaElt = doc.xmlRootElement
    annotationElt = XmlUtil.addChild(schemaElt, XbrlConst.xsd, 'annotation')
    if thisDoc.schemaDocumentation:
        XmlUtil.addChild(annotationElt, XbrlConst.xsd, 'documentation', text=thisDoc.schemaDocumentation)
    appinfoElt = XmlUtil.addChild(annotationElt, XbrlConst.xsd, 'appinfo')
    appinfoElt = XmlUtil.descendant(schemaElt, XbrlConst.xsd, 'appinfo')
    for filename in thisDoc.includes:
        XmlUtil.addChild(schemaElt, XbrlConst.xsd, 'include', attributes=(('schemaLocation', filename),))
    for (importPrefix, importAttributes) in sorted(thisDoc.imports.items(), key=(lambda item: item[1])):
        XmlUtil.addChild(schemaElt, XbrlConst.xsd, 'import', attributes=importAttributes)
        if ((importPrefix in genDocs) and (not genDocs[importPrefix].generated)):
            generateDoc(genDocs[importPrefix], doc, visitedDocNames)
    if any(((roleURI in thisDoc.extensionRoleLabels) for roleURI in thisDoc.extensionRoles.keys())):
        for importAttributes in ((('namespace', XbrlConst.gen), ('schemaLocation', 'http://www.xbrl.org/2008/generic-link.xsd')), (('namespace', XbrlConst.genLabel), ('schemaLocation', 'http://www.xbrl.org/2008/generic-label.xsd'))):
            XmlUtil.addChild(schemaElt, XbrlConst.xsd, 'import', attributes=importAttributes)
    _enumNum = [1]

    def addFacets(thisDoc, restrElt, facets):
        if facets:
            excludedEnumeration = facets.get('excludedEnumeration')
            if ((annotateEnumerationsDocumentation and (excludedEnumeration == 'X')) or (excludedEnumeration == 'D')):
                for (facet, facetValue) in facets.items():
                    if (facet == 'enumeration'):
                        enumerationsDocumentation = []
                        for valLbl in facetValue.split('\n'):
                            (val, _sep, _label) = valLbl.partition('=')
                            val = val.strip()
                            if len(val):
                                if (val == '(empty)'):
                                    val = 
                                _label = _label.strip()
                                enumerationsDocumentation.append(('{}: {}'.format(val, _label) if _label else val))
                        XmlUtil.addChild(XmlUtil.addChild(restrElt, XbrlConst.xsd, 'annotation'), XbrlConst.xsd, 'documentation', text=' \n'.join(enumerationsDocumentation))
            for (facet, facetValue) in sorted(facets.items(), key=(lambda i: facetSortOrder.get(i[0], i[0]))):
                if (facet == 'enumeration'):
                    if ((not annotateEnumerationsDocumentation) and (not excludedEnumeration)):
                        for valLbl in facetValue.split('\n'):
                            (val, _sep, _label) = valLbl.partition('=')
                            val = val.strip()
                            _label = _label.strip()
                            if len(val):
                                if (val == '(empty)'):
                                    val = 
                                _attributes = {'value': val}
                                if _label:
                                    _labelsByLang = None
                                    if (_label.startswith('{') and _label.endswith('}')):
                                        try:
                                            _labelsByLang = json.loads(_label)
                                        except json.decoder.JSONDecodeError:
                                            _labelsByLang = None
                                    _name = 'enum{}'.format(_enumNum[0])
                                    _attributes['id'] = ((thisDoc.extensionSchemaPrefix + '_') + _name)
                                    _enumNum[0] += 1
                                    if _labelsByLang:
                                        for (_lang, _langLabel) in _labelsByLang.items():
                                            thisDoc.extensionLabels[(thisDoc.extensionSchemaPrefix, _name, _lang, XbrlConst.genStandardLabel)] = _langLabel
                                    else:
                                        thisDoc.extensionLabels[(thisDoc.extensionSchemaPrefix, _name, defaultLabelLang, XbrlConst.genStandardLabel)] = _label
                                enumElt = XmlUtil.addChild(restrElt, XbrlConst.xsd, facet, attributes=_attributes)
                                if (thisDoc.hasEnumerationDocumentation and _label):
                                    if _labelsByLang:
                                        annotationElt = XmlUtil.addChild(enumElt, XbrlConst.xsd, 'annotation')
                                        for (_lang, _langLabel) in _labelsByLang.items():
                                            thisDoc.extensionLabels[(thisDoc.extensionSchemaPrefix, _name, _lang, XbrlConst.genStandardLabel)] = _langLabel
                                            XmlUtil.addChild(annotationElt, XbrlConst.xsd, 'documentation', text=_langLabel, attributes={'{http://www.w3.org/XML/1998/namespace}lang': _lang})
                                    else:
                                        XmlUtil.addChild(XmlUtil.addChild(enumElt, XbrlConst.xsd, 'annotation'), XbrlConst.xsd, 'documentation', text=_label)
                elif (facet != 'excludedEnumeration'):
                    XmlUtil.addChild(restrElt, XbrlConst.xsd, facet, attributes={'value': str(facetValue)})
    for (eltName, eltDef) in sorted(thisDoc.extensionElements.items(), key=(lambda item: item[0])):
        (eltAttrs, eltFacets) = eltDef
        if (eltFacets and ('type' in eltAttrs)):
            eltType = eltAttrs['type']
            del eltAttrs['type']
        if any(((':' in attrname) for attrname in eltAttrs.keys())):
            for (attrname, attrvalue) in eltAttrs.copy().items():
                if ((not attrname.startswith('{')) and (':' in attrname)):
                    del eltAttrs[attrname]
                    eltAttrs[schemaElt.prefixedNameQname(attrname).clarkNotation] = attrvalue
        isConcept = (eltAttrs.get('substitutionGroup') in ('xbrli:item', 'xbrli:tuple', 'xbrldt:hypercubeItem', 'xbrldt:dimensionItem'))
        elt = XmlUtil.addChild(schemaElt, XbrlConst.xsd, 'element', attributes=eltAttrs)
        if annotateElementDocumentation:
            for labelRole in (XbrlConst.documentationLabel, XbrlConst.genDocumentationLabel):
                labelKey = (thisDoc.extensionSchemaPrefix, eltAttrs['name'], defaultLabelLang, labelRole)
                if (labelKey in thisDoc.extensionLabels):
                    XmlUtil.addChild(XmlUtil.addChild(elt, XbrlConst.xsd, 'annotation'), XbrlConst.xsd, 'documentation', text=thisDoc.extensionLabels[labelKey])
                    break
        if ((elt is not None) and eltFacets and isConcept):
            cmplxType = XmlUtil.addChild(elt, XbrlConst.xsd, 'complexType')
            cmplxCont = XmlUtil.addChild(cmplxType, XbrlConst.xsd, 'simpleContent')
            restrElt = XmlUtil.addChild(cmplxCont, XbrlConst.xsd, 'restriction', attributes={'base': eltType})
            addFacets(thisDoc, restrElt, eltFacets)
            del eltType
    for (roleURI, (roleDefinition, usedOnRoles)) in sorted(thisDoc.extensionRoles.items(), key=(lambda rd: rd[1])):
        roleElt = XmlUtil.addChild(appinfoElt, XbrlConst.link, 'roleType', attributes=(('roleURI', roleURI), ('id', ('roleType_' + roleURI.rpartition('/')[2]))))
        if roleDefinition:
            XmlUtil.addChild(roleElt, XbrlConst.link, 'definition', text=roleDefinition)
        if usedOnRoles:
            for usedOnRole in usedOnRoles.split():
                XmlUtil.addChild(roleElt, XbrlConst.link, 'usedOn', text=usedOnRole)
        else:
            if (hasPreLB and any(((e.childStruct and e.isELR and ((e.role == roleURI) or (e.name == roleDefinition))) for e in preLB))):
                XmlUtil.addChild(roleElt, XbrlConst.link, 'usedOn', text='link:presentationLink')
            if (hasDefLB and any(((e.childStruct and e.isELR and ((e.role == roleURI) or (e.name == roleDefinition))) for e in defLB))):
                XmlUtil.addChild(roleElt, XbrlConst.link, 'usedOn', text='link:definitionLink')
            if (hasCalLB and any(((e.childStruct and e.isELR and ((e.role == roleURI) or (e.name == roleDefinition))) for e in calLB))):
                XmlUtil.addChild(roleElt, XbrlConst.link, 'usedOn', text='link:calculationLink')
            if (hasGenLB and any(((e.childStruct and e.isELR and ((e.role == roleURI) or (e.name == roleDefinition))) for e in genLB))):
                XmlUtil.addChild(roleElt, XbrlConst.link, 'usedOn', text=qname('{http://xbrl.org/2008/generic}genlink:link'))
    if any(((roleURI in thisDoc.extensionRoleLabels) for roleURI in thisDoc.extensionRoles.keys())):
        genLabLB = XmlUtil.addChild(appinfoElt, XbrlConst.link, 'linkbase')
        XmlUtil.addChild(genLabLB, XbrlConst.link, 'roleRef', attributes=(('roleURI', XbrlConst.genStandardLabel), ('{http://www.w3.org/1999/xlink}href', 'http://www.xbrl.org/2008/generic-label.xsd#standard-label'), ('{http://www.w3.org/1999/xlink}type', 'simple')))
        XmlUtil.addChild(genLabLB, XbrlConst.link, 'arcroleRef', attributes=(('arcroleURI', elementLabel), ('{http://www.w3.org/1999/xlink}href', 'http://www.xbrl.org/2008/generic-label.xsd#element-label'), ('{http://www.w3.org/1999/xlink}type', 'simple')))
        linkElt = XmlUtil.addChild(genLabLB, qname('{http://xbrl.org/2008/generic}genlink:link'), attributes=(('{http://www.w3.org/1999/xlink}type', 'extended'), ('{http://www.w3.org/1999/xlink}role', defaultLinkRole)))
        for (roleURI, _defLabel) in sorted(thisDoc.extensionRoles.items(), key=(lambda rd: rd[0])):
            if (roleURI in thisDoc.extensionRoleLabels):
                xlLabel = roleURI.rpartition('/')[2]
                XmlUtil.addChild(linkElt, XbrlConst.link, 'loc', attributes=(('{http://www.w3.org/1999/xlink}type', 'locator'), ('{http://www.w3.org/1999/xlink}href', ('#roleType_' + xlLabel)), ('{http://www.w3.org/1999/xlink}label', ('loc_' + xlLabel))))
                XmlUtil.addChild(linkElt, XbrlConst.qnGenArc, attributes=(('{http://www.w3.org/1999/xlink}type', 'arc'), ('{http://www.w3.org/1999/xlink}arcrole', elementLabel), ('{http://www.w3.org/1999/xlink}from', ('loc_' + xlLabel)), ('{http://www.w3.org/1999/xlink}to', ('label_' + xlLabel))))
                for (text, lang) in thisDoc.extensionRoleLabels[roleURI]:
                    XmlUtil.addChild(linkElt, qname('{http://xbrl.org/2008/label}genlabel:label'), attributes=(('{http://www.w3.org/1999/xlink}type', 'resource'), ('{http://www.w3.org/1999/xlink}label', ('label_' + xlLabel)), ('{http://www.w3.org/1999/xlink}role', XbrlConst.genStandardLabel), ('{http://www.w3.org/XML/1998/namespace}lang', lang)), text=text)

    def addLinkbaseRef(lbType, lbFilename, lbDoc):
        role = 'http://www.xbrl.org/2003/role/{0}LinkbaseRef'.format(lbType)
        lbRefElt = XmlUtil.addChild(appinfoElt, XbrlConst.link, 'linkbaseRef', attributes=((('{http://www.w3.org/1999/xlink}type', 'simple'), ('{http://www.w3.org/1999/xlink}href', docRelpath(lbFilename, thisDoc.extensionSchemaRelDirname)), ('{http://www.w3.org/1999/xlink}arcrole', 'http://www.w3.org/1999/xlink/properties/linkbase')) + (() if lbType.startswith('generic') else (('{http://www.w3.org/1999/xlink}role', role),))))
        if lbDoc:
            doc.referencesDocument[lbDoc] = ModelDocumentReference('href', lbRefElt)
    for (lbRefType, filename, generate) in thisDoc.linkbaseRefs:
        if (not generate):
            for otherGenDoc in genDocs.values():
                if ((not otherGenDoc.generated) and any((((_otherLbRefType == lbRefType) and (_otherFilename == filename) and _otherGenerate) for (_otherLbRefType, _otherFilename, _otherGenerate) in otherGenDoc.linkbaseRefs))):
                    generateDoc(otherGenDoc, doc, visitedDocNames)
            addLinkbaseRef(lbRefType, filename, None)
    doc.schemaDiscover(schemaElt, False, thisDoc.extensionSchemaNamespaceURI)
    for (typeName, typeDef) in sorted(thisDoc.extensionTypes.items(), key=(lambda item: item[0])):
        if (qname(thisDoc.extensionSchemaNamespaceURI, typeName) in modelXbrl.qnameTypes):
            continue
        (typeAttrs, typeFacets) = typeDef
        if (typeName.endswith('ItemType') or typeAttrs.get('base', ).endswith('ItemType')):
            cmplxType = XmlUtil.addChild(schemaElt, XbrlConst.xsd, 'complexType', attributes={'name': typeAttrs['name']})
            contElt = XmlUtil.addChild(cmplxType, XbrlConst.xsd, 'simpleContent')
        else:
            contElt = XmlUtil.addChild(schemaElt, XbrlConst.xsd, 'simpleType', attributes={'name': typeAttrs['name']})
        restrElt = XmlUtil.addChild(contElt, XbrlConst.xsd, 'restriction', attributes={'base': typeAttrs['base']})
        baseQn = qname(schemaElt, typeAttrs.get('base'))
        if typeFacets:
            if (baseQn and (baseQn.namespaceURI not in (XbrlConst.xsd, XbrlConst.xbrli)) and (baseQn in modelXbrl.qnameTypes)):
                baseTypeFacets = (modelXbrl.qnameTypes[baseQn].facets or ())
                typeFacets = dict(((facet, value) for (facet, value) in typeFacets.items() if ((facet not in baseTypeFacets) or (str(baseTypeFacets[facet]) != value))))
            addFacets(thisDoc, restrElt, typeFacets)
    extLabelRoles = {}
    extReferenceRoles = {}
    extReferenceParts = {}
    extReferenceSchemaDocs = {}
    extUnrecognizedRoles = set()
    relationshipArcroles = {}
    relationshipArcqnames = {}

    def setExtRefPart(partLocalName):
        if (partLocalName not in extReferenceParts):
            for partConcept in modelXbrl.nameConcepts.get(partLocalName, ()):
                if ((partConcept is not None) and (partConcept.subGroupHeadQname == qnLinkPart)):
                    extReferenceParts[partLocalName] = partConcept.qname
                    extReferenceSchemaDocs[partConcept.qname.namespaceURI] = (partConcept.modelDocument.uri if partConcept.modelDocument.uri.startswith('http://') else partConcept.modelDocument.basename)
                    break
    for _headerColKey in headerColsAllElrs:
        if (isinstance(_headerColKey, tuple) and (len(_headerColKey) >= 3) and (not _headerColKey[1].startswith('http://'))):
            _resourceType = _headerColKey[0]
            _resourceRole = _headerColKey[1]
            _resourceLangOrPart = _headerColKey[2]
        elif (isinstance(_headerColKey, str) and ('!reference' in _headerColKey)):
            m = resourceParsePattern.match(_headerColKey.partition('!')[2])
            _resourceType = m.group(1)
            _resourceRole = ('/' + m.group(2))
            _resourceLangOrPart = m.group(4)
        else:
            continue
        (_resourceQName, _standardRoles) = {'label': (qnLinkLabel, standardLabelRoles), 'labels': (qnLinkLabel, standardLabelRoles), 'reference': (qnLinkReference, standardReferenceRoles), 'references': (qnLinkReference, standardReferenceRoles)}.get(_resourceType, (None, ()))
        _resourceRoleURI = None
        for _roleURI in _standardRoles:
            if _roleURI.endswith(_resourceRole):
                _resourceRoleURI = _roleURI
                _resourceRoleMatchPart = _resourceRole
                break
        if (_resourceRoleURI is None):
            _resourceRoleMatchPart = _resourceRole.partition('#')[0]
            for _roleURI in modelXbrl.roleTypes:
                if _roleURI.endswith(_resourceRoleMatchPart):
                    for _roleType in modelXbrl.roleTypes[_roleURI]:
                        if (_resourceQName in _roleType.usedOns):
                            _resourceRoleURI = _roleURI
                            break
        if (_resourceType in ('label', 'labels')):
            if _resourceRoleURI:
                extLabelRoles[_resourceRoleMatchPart] = _resourceRoleURI
            elif any(((_resourceRoleMatchPart == k[2]) for k in thisDoc.extensionLabels.keys())):
                modelXbrl.error('loadFromExcel:labelResourceRole', 'Label resource role not found: %(role)s', modelXbrl=modelXbrl, role=_resourceRoleMatchPart, filename=thisDoc.extensionSchemaNamespaceURI)
        elif (_resourceType in ('reference', 'references')):
            if _resourceRoleURI:
                extReferenceRoles[_resourceRoleMatchPart] = _resourceRoleURI
                setExtRefPart(_resourceLangOrPart)
            elif any(((_resourceRoleMatchPart == k[2]) for k in thisDoc.extensionReferences.keys())):
                modelXbrl.error('loadFromExcel:referenceResourceRole', 'Reference resource role not found: %(role)s', modelXbrl=modelXbrl, role=_resourceRoleMatchPart, filename=thisDoc.extensionSchemaNamespaceURI)
        elif (_resourceType == 'relationship to'):
            for _arcroleURI in modelXbrl.arcroleTypes:
                if _arcroleURI.endswith(_resourceRoleMatchPart):
                    for _arcroleType in modelXbrl.arcroleTypes[_arcroleURI]:
                        for _resourceQName in _arcroleType.usedOns:
                            break
                    break
            if (_resourceQName is None):
                modelXbrl.error('loadFromExcel:relationshipArcrole', 'Relationship arcrole not found: %(arcrole)s', modelXbrl=modelXbrl, arcrole=_resourceRoleMatchPart, filename=thisDoc.extensionSchemaNamespaceURI)
            else:
                relationshipArcroles[_resourceRoleMatchPart] = _arcroleURI
                relationshipArcqnames[_arcroleURI] = _resourceQName
    for (lbType, lang, filename) in thisDoc.labelLinkbases:
        thisDoc.thisLBdir = posixpath.dirname(filename)
        langPattern = re.compile((lang or '.*'))
        _isGeneric = lbType.startswith('generic')
        if (_isGeneric and ('http://xbrl.org/2008/label' not in modelXbrl.namespaceDocs)):
            ModelDocument.load(modelXbrl, 'http://www.xbrl.org/2008/generic-link.xsd', isDiscovered=True)
            ModelDocument.load(modelXbrl, 'http://www.xbrl.org/2008/generic-label.xsd', isDiscovered=True)
        lbDoc = ModelDocument.create(modelXbrl, ModelDocument.Type.LINKBASE, filename, base=, initialXml='\n            <linkbase \n                xmlns="http://www.xbrl.org/2003/linkbase" \n                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" \n                xmlns:xlink="http://www.w3.org/1999/xlink" \n                xmlns:xbrli="http://www.xbrl.org/2003/instance"\n                {}\n                xsi:schemaLocation="http://www.xbrl.org/2003/linkbase \n                http://www.xbrl.org/2003/xbrl-linkbase-2003-12-31.xsd{}" \n                {}>{}</linkbase>\n            '.format(('\n                xmlns:genlink="http://xbrl.org/2008/generic"\n                xmlns:genlabel="http://xbrl.org/2008/label"\n                ' if _isGeneric else ), ('\n                http://xbrl.org/2008/generic  http://www.xbrl.org/2008/generic-link.xsd\n                http://xbrl.org/2008/label  http://www.xbrl.org/2008/generic-label.xsd\n                ' if _isGeneric else ), ('\n xml:lang="{}"'.format(saveXmlLang) if saveXmlLang else ), ('\n                <arcroleRef arcroleURI="http://xbrl.org/arcrole/2008/element-label" xlink:href="http://www.xbrl.org/2008/generic-label.xsd#element-label" xlink:type="simple"/>\n                ' if _isGeneric else )), initialComment=thisDoc.initialComment)
        lbDoc.inDTS = True
        lbDoc.loadedFromExcel = True
        if isGenerateAndImport:
            addLinkbaseRef(lbType, filename, lbDoc)
        lbElt = lbDoc.xmlRootElement
        linkElt = XmlUtil.addChild(lbElt, (gen if _isGeneric else link), ('link' if _isGeneric else 'labelLink'), attributes=(('{http://www.w3.org/1999/xlink}type', 'extended'), ('{http://www.w3.org/1999/xlink}role', defaultLinkRole)))
        firstLinkElt = linkElt
        locs = set()
        roleRefs = set()
        for (labelKey, text) in thisDoc.extensionLabels.items():
            (prefix, name, labelLang, role) = labelKey
            labelLang = (labelLang or defaultLabelLang)
            role = role.partition('#')[0]
            role = extLabelRoles.get(role, role)
            if (langPattern.match(labelLang) and (_isGeneric == (role in (XbrlConst.genStandardLabel, XbrlConst.genDocumentationLabel)))):
                locLabel = ((prefix + '_') + name)
                if (locLabel not in locs):
                    locs.add(locLabel)
                    XmlUtil.addChild(linkElt, XbrlConst.link, 'loc', attributes=(('{http://www.w3.org/1999/xlink}type', 'locator'), ('{http://www.w3.org/1999/xlink}href', LBHref(thisDoc, prefix, name)), ('{http://www.w3.org/1999/xlink}label', locLabel)))
                    XmlUtil.addChild(linkElt, (gen if _isGeneric else link), ('arc' if _isGeneric else 'labelArc'), attributes=(('{http://www.w3.org/1999/xlink}type', 'arc'), ('{http://www.w3.org/1999/xlink}arcrole', (elementLabel if _isGeneric else conceptLabel)), ('{http://www.w3.org/1999/xlink}from', locLabel), ('{http://www.w3.org/1999/xlink}to', ('label_' + locLabel)), ('order', 1.0)))
                XmlUtil.addChild(linkElt, (XbrlConst.genLabel if _isGeneric else XbrlConst.link), 'label', attributes=((('{http://www.w3.org/1999/xlink}type', 'resource'), ('{http://www.w3.org/1999/xlink}label', ('label_' + locLabel)), ('{http://www.w3.org/1999/xlink}role', role)) + ((('{http://www.w3.org/XML/1998/namespace}lang', labelLang),) if (True or (lang != saveXmlLang)) else ())), text=text)
                if role:
                    if (role in XbrlConst.standardLabelRoles):
                        pass
                    elif (role in modelXbrl.roleTypes):
                        roleType = modelXbrl.roleTypes[role][0]
                        roleRefs.add(('roleRef', role, ((roleType.modelDocument.uri + '#') + roleType.id)))
                    elif role.startswith('http://www.xbrl.org/2009/role/negated'):
                        roleRefs.add(('roleRef', role, ('http://www.xbrl.org/lrr/role/negated-2009-12-16.xsd#' + role.rpartition('/')[2])))
                    else:
                        extUnrecognizedRoles.add(role)
        for (roleref, roleURI, href) in roleRefs:
            XmlUtil.addChild(lbElt, XbrlConst.link, roleref, attributes=((('arcroleURI' if (roleref == 'arcroleRef') else 'roleURI'), roleURI), ('{http://www.w3.org/1999/xlink}type', 'simple'), ('{http://www.w3.org/1999/xlink}href', href)), beforeSibling=firstLinkElt)
        lbDoc.linkbaseDiscover(lbElt)
        if extUnrecognizedRoles:
            modelXbrl.error('loadFromExcel:undefinedLabelRole', 'Label roles not defined: %(undefinedRoles)s', modelXbrl=modelXbrl, undefinedRoles=','.join(sorted(extUnrecognizedRoles)))
            extUnrecognizedRoles.clear()
    for (lbType, referenceRole, filename) in thisDoc.referenceLinkbases:
        thisDoc.thisLBdir = posixpath.dirname(filename)
        _isGeneric = lbType.startswith('generic')
        lbDoc = ModelDocument.create(modelXbrl, ModelDocument.Type.LINKBASE, filename, base=, initialXml='\n            <linkbase \n                xmlns="http://www.xbrl.org/2003/linkbase" \n                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" \n                xmlns:xlink="http://www.w3.org/1999/xlink" \n                xmlns:xbrli="http://www.xbrl.org/2003/instance"\n                {}\n                xsi:schemaLocation="http://www.xbrl.org/2003/linkbase \n                http://www.xbrl.org/2003/xbrl-linkbase-2003-12-31.xsd{}{}" \n                {}>{}</linkbase>\n            '.format(('\n                xmlns:genlink="http://xbrl.org/2008/generic"\n                xmlns:genreference="http://xbrl.org/2008/rerference"\n                ' if _isGeneric else ), .join([' {} {}'.format(_ns, _uri) for (_ns, _uri) in extReferenceSchemaDocs.items()]), ('\n                http://xbrl.org/2008/generic  http://www.xbrl.org/2008/generic-link.xsd\n                http://xbrl.org/2008/reference  http://www.xbrl.org/2008/generic-reference.xsd\n                ' if _isGeneric else ), ('\n xml:lang="{}"'.format(saveXmlLang) if saveXmlLang else ), ('\n                <roleRef roleURI="http://www.xbrl.org/2008/role/label" xlink:href="http://www.xbrl.org/2008/generic-label.xsd#standard-label" xlink:type="simple"/>\n                <arcroleRef arcroleURI="http://xbrl.org/arcrole/2008/element-reference" xlink:href="http://xbrl.org/2008/generic-reference.xsd#element-reference" xlink:type="simple"/>\n                ' if _isGeneric else )), initialComment=thisDoc.initialComment)
        lbDoc.inDTS = True
        lbDoc.loadedFromExcel = True
        if isGenerateAndImport:
            addLinkbaseRef(lbType, filename, lbDoc)
        lbElt = lbDoc.xmlRootElement
        linkElt = XmlUtil.addChild(lbElt, (XbrlConst.gen if _isGeneric else XbrlConst.link), ('link' if _isGeneric else 'referenceLink'), attributes=(('{http://www.w3.org/1999/xlink}type', 'extended'), ('{http://www.w3.org/1999/xlink}role', defaultLinkRole)))
        firstLinkElt = linkElt
        locs = set()
        roleRefs = set()
        undefinedReferenceParts = set()
        for (referenceKey, references) in thisDoc.extensionReferences.items():
            (prefix, name, role) = referenceKey
            role = role.partition('#')[0]
            role = extReferenceRoles.get(role, role)
            if fnmatch(role, referenceRole):
                locLabel = ((prefix + '_') + name)
                if (locLabel not in locs):
                    locs.add(locLabel)
                    order = 1
                else:
                    for order in range(2, 1000):
                        _locLabel = '{}_{}'.format(locLabel, order)
                        if (_locLabel not in locs):
                            locLabel = _locLabel
                            locs.add(locLabel)
                            break
                    if (order > 999):
                        print('resource order de-duplicate failure, too many reference parts')
                XmlUtil.addChild(linkElt, XbrlConst.link, 'loc', attributes=(('{http://www.w3.org/1999/xlink}type', 'locator'), ('{http://www.w3.org/1999/xlink}href', LBHref(thisDoc, prefix, name)), ('{http://www.w3.org/1999/xlink}label', locLabel)))
                XmlUtil.addChild(linkElt, XbrlConst.link, 'referenceArc', attributes=(('{http://www.w3.org/1999/xlink}type', 'arc'), ('{http://www.w3.org/1999/xlink}arcrole', conceptReference), ('{http://www.w3.org/1999/xlink}from', locLabel), ('{http://www.w3.org/1999/xlink}to', ('label_' + locLabel)), ('order', order)))
                referenceResource = XmlUtil.addChild(linkElt, (XbrlConst.genReference if _isGeneric else XbrlConst.link), 'reference', attributes=(('{http://www.w3.org/1999/xlink}type', 'resource'), ('{http://www.w3.org/1999/xlink}label', ('label_' + locLabel)), ('{http://www.w3.org/1999/xlink}role', role)))
                for (part, text) in references:
                    setExtRefPart(part)
                    if (part in extReferenceParts):
                        partQn = extReferenceParts.get(part, part)
                        XmlUtil.addChild(referenceResource, partQn, text=text)
                    else:
                        undefinedReferenceParts.add(part)
                if role:
                    if (role in XbrlConst.standardLabelRoles):
                        pass
                    elif (role in modelXbrl.roleTypes):
                        roleType = modelXbrl.roleTypes[role][0]
                        roleRefs.add(('roleRef', role, ((roleType.modelDocument.uri + '#') + roleType.id)))
                    elif role.startswith('http://www.xbrl.org/2009/role/negated'):
                        roleRefs.add(('roleRef', role, ('http://www.xbrl.org/lrr/role/negated-2009-12-16.xsd#' + role.rpartition('/')[2])))
                    else:
                        extUnrecognizedRoles.add(role)
        for part in sorted(undefinedReferenceParts):
            print('reference part not defined: {}'.format(part))
        for (roleref, roleURI, href) in roleRefs:
            XmlUtil.addChild(lbElt, XbrlConst.link, roleref, attributes=((('arcroleURI' if (roleref == 'arcroleRef') else 'roleURI'), roleURI), ('{http://www.w3.org/1999/xlink}type', 'simple'), ('{http://www.w3.org/1999/xlink}href', href)), beforeSibling=firstLinkElt)
        lbDoc.linkbaseDiscover(lbElt)
        if extUnrecognizedRoles:
            modelXbrl.error('loadFromExcel:undefinedReferenceRole', 'Reference roles not defined: %(undefinedRoles)s', modelXbrl=modelXbrl, undefinedRoles=','.join(sorted(extUnrecognizedRoles)))
            extUnrecognizedRoles.clear()
    prefixedNamespaces = modelXbrl.prefixedNamespaces

    def hrefConcept(prefix, name):
        qn = qname(prefixedNamespaces[prefix], name)
        if (qn in modelXbrl.qnameConcepts):
            return modelXbrl.qnameConcepts[qn]
        elif (name in modelXbrl.nameConcepts):
            return modelXbrl.nameConcepts[name][0]
        if (prefix not in prefixedNamespaces):
            modelXbrl.error('loadFromExcel:undefinedRelationshipElementPrefix', 'Prefix not defined: %(prefix)s', modelXbrl=modelXbrl, prefix=prefix)
            return None
        modelXbrl.error('loadFromExcel:undefinedRelationshipElement', 'QName not defined: %(prefix)s:%(localName)s', modelXbrl=modelXbrl, prefix=prefix, localName=name)
        return None

    def prefixedNameQName(prefixedName):
        if (':' not in prefixedName):
            return prefixedName
        (prefix, _sep, name) = prefixedName.rpartition(':')
        if (prefix not in prefixedNamespaces):
            modelXbrl.error('loadFromExcel:undefinedRelationshipAttributePrefix', 'Prefix not defined: %(prefix)s', modelXbrl=modelXbrl, prefix=prefix)
            return prefixedName
        return QName(prefix, prefixedNamespaces[prefix], name)

    def lbTreeWalk(lbType, parentElt, lbStruct, roleRefs, dimDef=False, locs=None, arcsFromTo=None, fromPrefix=None, fromName=None):
        order = 1.0
        for lbEntry in lbStruct:
            if lbEntry.isELR:
                if (not lbEntry.childStruct):
                    continue
                role = 'unspecified'
                if (lbEntry.role and lbEntry.role.startswith('http://')):
                    role = lbEntry.role
                elif lbEntry.name:
                    for (linkroleUri, modelRoleTypes) in modelXbrl.roleTypes.items():
                        definition = modelRoleTypes[0].definition
                        if ((lbEntry.name == definition) and (linkroleUri in thisDoc.extensionRoles)):
                            role = linkroleUri
                            break
                if (role == 'unspecified'):
                    continue
                if (role not in thisDoc.extensionRoles):
                    continue
                if (role == XbrlConst.defaultLinkRole):
                    pass
                elif (role in thisDoc.extensionRoles):
                    roleRefs.add(('roleRef', role, ((doc.uri + '#roleType_') + role.rpartition('/')[2])))
                elif (role in modelXbrl.roleTypes):
                    roleType = modelRoleTypes[0]
                    roleRefs.add(('roleRef', role, ((roleType.modelDocument.uri + '#') + roleType.id)))
                else:
                    extUnrecognizedRoles.add(role)
                linkElt = XmlUtil.addChild(parentElt, (XbrlConst.gen if (lbType == 'generic') else XbrlConst.link), ('link' if (lbType == 'generic') else (lbType + 'Link')), attributes=(('{http://www.w3.org/1999/xlink}type', 'extended'), ('{http://www.w3.org/1999/xlink}role', role)))
                locs = set()
                arcsFromTo = set()
                lbTreeWalk(lbType, linkElt, lbEntry.childStruct, roleRefs, dimDef, locs, arcsFromTo)
            else:
                toPrefix = lbEntry.prefix
                toName = lbEntry.name
                toHref = LBHref(thisDoc, toPrefix, toName)
                if (toHref is None):
                    modelXbrl.error('loadFromExcel:invalidQName', "%(linkbase)s relationship element with prefix '%(prefix)s' localName '%(localName)s' not found", modelXbrl=modelXbrl, linkbase=lbType, prefix=lbEntry.prefix, localName=lbEntry.name)
                    continue
                if ((not toPrefix) and (toName in modelXbrl.nameConcepts)):
                    toPrefix = modelXbrl.nameConcepts[toName][0].qname.prefix
                toLabel = '{}_{}'.format(toPrefix, toName)
                toLabelAlt = None
                if (not lbEntry.isRoot):
                    if ((not fromPrefix) and (fromName in modelXbrl.nameConcepts)):
                        fromPrefix = modelXbrl.nameConcepts[fromName][0].qname.prefix
                    fromLabel = '{}_{}'.format(fromPrefix, fromName)
                    if ((fromLabel, toLabel) in arcsFromTo):
                        for i in range(1, 1000):
                            toLabelAlt = '{}_{}'.format(toLabel, i)
                            if ((fromLabel, toLabelAlt) not in arcsFromTo):
                                toLabel = toLabelAlt
                                break
                if (((toHref not in locs) or toLabelAlt) and (not dimDef)):
                    XmlUtil.addChild(parentElt, XbrlConst.link, 'loc', attributes=(('{http://www.w3.org/1999/xlink}type', 'locator'), ('{http://www.w3.org/1999/xlink}href', toHref), ('{http://www.w3.org/1999/xlink}label', toLabel)))
                    locs.add(toHref)
                if (not lbEntry.isRoot):
                    arcsFromTo.add((fromLabel, toLabel))
                    if ((lbType == 'calculation') and (lbEntry.weight is not None)):
                        otherAttrs = (('weight', lbEntry.weight),)
                    elif ((lbType == 'presentation') and lbEntry.role):
                        if (not lbEntry.role.startswith('http://')):
                            _labelRoleMatchPart = ('/' + lbEntry.role)
                            for _roleURI in modelXbrl.roleTypes:
                                if _roleURI.endswith(_labelRoleMatchPart):
                                    for _roleType in modelXbrl.roleTypes[_roleURI]:
                                        if (XbrlConst.qnLinkLabel in _roleType.usedOns):
                                            lbEntry.role = _roleURI
                                            break
                        if (not lbEntry.role.startswith('http://')):
                            lbEntry.role = ('http://www.xbrl.org/2003/role/' + lbEntry.role)
                        otherAttrs = (('preferredLabel', lbEntry.role),)
                        if (lbEntry.role and (lbEntry.role not in XbrlConst.standardLabelRoles)):
                            if (lbEntry.role in modelXbrl.roleTypes):
                                roleType = modelXbrl.roleTypes[lbEntry.role][0]
                                roleRefs.add(('roleRef', lbEntry.role, ((roleType.modelDocument.uri + '#') + roleType.id)))
                            else:
                                extUnrecognizedRoles.add(lbEntry.role)
                    elif ((lbType == 'generic') and lbEntry.arcrole):
                        if (not lbEntry.arcrole.startswith('http://')):
                            for _arcroleURI in modelXbrl.arcroleTypes:
                                if _arcroleURI.endswith(lbEntry.arcrole):
                                    lbEntry.arcrole = _arcroleURI
                                    break
                        otherAttrs = tuple(((prefixedNameQName(_key), _value) for (_key, _value) in (lbEntry.relAttrs.items() if (lbEntry.relAttrs is not None) else ())))
                    else:
                        otherAttrs = ()
                    if (lbEntry.arcrole == '_dimensions_'):
                        fromConcept = hrefConcept(fromPrefix, fromName)
                        toConcept = hrefConcept(toPrefix, toName)
                        if dimDef:
                            if ((lbEntry.role != '_dimensionDefault_') and (not lbTreeHasDimDefault(lbEntry.childStruct))):
                                continue
                            if ((toConcept is not None) and (toConcept.isDimensionItem or (lbEntry.role == '_dimensionDefault_'))):
                                if ((toHref not in locs) or toLabelAlt):
                                    XmlUtil.addChild(parentElt, XbrlConst.link, 'loc', attributes=(('{http://www.w3.org/1999/xlink}type', 'locator'), ('{http://www.w3.org/1999/xlink}href', toHref), ('{http://www.w3.org/1999/xlink}label', toLabel)))
                                    locs.add(toHref)
                                if (lbEntry.role != '_dimensionDefault_'):
                                    lbTreeWalk(lbType, parentElt, lbEntry.childStruct, roleRefs, dimDef, locs, arcsFromTo, toPrefix, toName)
                                else:
                                    XmlUtil.addChild(parentElt, XbrlConst.link, 'definitionArc', attributes=((('{http://www.w3.org/1999/xlink}type', 'arc'), ('{http://www.w3.org/1999/xlink}arcrole', XbrlConst.dimensionDefault), ('{http://www.w3.org/1999/xlink}from', fromLabel), ('{http://www.w3.org/1999/xlink}to', toLabel), ('order', order)) + otherAttrs))
                                    order += 1.0
                            else:
                                lbTreeWalk(lbType, parentElt, lbEntry.childStruct, roleRefs, dimDef, locs, arcsFromTo, fromPrefix, fromName)
                            continue
                        elif ((toConcept is not None) and toConcept.isHypercubeItem):
                            arcrole = XbrlConst.all
                            otherAttrs += ((XbrlConst.qnXbrldtContextElement, 'segment'), (qnXbrldtClosed, 'true'))
                        elif ((toConcept is not None) and toConcept.isDimensionItem):
                            arcrole = XbrlConst.hypercubeDimension
                        elif ((fromConcept is not None) and fromConcept.isDimensionItem):
                            arcrole = XbrlConst.dimensionDomain
                        else:
                            arcrole = XbrlConst.domainMember
                    else:
                        arcrole = lbEntry.arcrole
                    if (arcrole in relationshipArcqnames):
                        arcqname = relationshipArcqnames[arcrole]
                        arcNS = arcqname.namespaceURI
                        arcLocalname = arcqname.localName
                    elif (lbType == 'generic'):
                        arcNS = XbrlConst.gen
                        arcLocalname = 'arc'
                    else:
                        arcNS = XbrlConst.link
                        arcLocalname = (lbType + 'Arc')
                    XmlUtil.addChild(parentElt, arcNS, arcLocalname, attributes=((('{http://www.w3.org/1999/xlink}type', 'arc'), ('{http://www.w3.org/1999/xlink}arcrole', arcrole), ('{http://www.w3.org/1999/xlink}from', fromLabel), ('{http://www.w3.org/1999/xlink}to', toLabel), ('order', order)) + otherAttrs))
                    order += 1.0
                if ((lbType != 'calculation') or lbEntry.isRoot):
                    lbTreeWalk(lbType, parentElt, lbEntry.childStruct, roleRefs, dimDef, locs, arcsFromTo, toPrefix, toName)

    def lbTreeHasDimDefault(lbStruct):
        for lbEntry in lbStruct:
            if lbEntry.isELR:
                if (not lbEntry.childStruct):
                    continue
                if lbTreeHasDimDefault(lbEntry.childStruct):
                    return True
            else:
                if ((not lbEntry.isRoot) and ((lbEntry.arcrole == '_dimensions_') and (lbEntry.role == '_dimensionDefault_'))):
                    return True
                if lbTreeHasDimDefault(lbEntry.childStruct):
                    return True
        return False
    for (hasLB, lbType, lbLB) in (((hasPreLB and thisDoc.hasPreLB), 'presentation', preLB), ((hasDefLB and thisDoc.hasDefLB), 'definition', defLB), ((hasCalLB and thisDoc.hasCalLB), 'calculation', calLB), ((hasGenLB and thisDoc.hasGenLB), 'generic', genLB)):
        if hasLB:
            for (lbRefType, filename, generate) in thisDoc.linkbaseRefs:
                thisDoc.thisLBdir = posixpath.dirname(filename)
                if (generate and (lbType == lbRefType)):
                    lbDoc = ModelDocument.create(modelXbrl, ModelDocument.Type.LINKBASE, filename, base=, initialXml='\n                        <linkbase \n                            xmlns="http://www.xbrl.org/2003/linkbase" \n                            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" \n                            xmlns:xlink="http://www.w3.org/1999/xlink" \n                            xmlns:xbrli="http://www.xbrl.org/2003/instance"{}\n                            xsi:schemaLocation="http://www.xbrl.org/2003/linkbase \n                            http://www.xbrl.org/2003/xbrl-linkbase-2003-12-31.xsd{}" \n                            />\n                        '.format(('\n                        xmlns:generic="http://xbrl.org/2008/generic"\n                        ' if (lbType == 'generic') else ), ('\n                        http://xbrl.org/2008/generic  http://www.xbrl.org/2008/generic-link.xsd\n                        ' if (lbType == 'generic') else )), initialComment=thisDoc.initialComment)
                    lbDoc.inDTS = True
                    lbDoc.loadedFromExcel = True
                    addLinkbaseRef(lbRefType, filename, lbDoc)
                    lbElt = lbDoc.xmlRootElement
                    roleRefs = set()
                    if (lbType == 'definition'):
                        roleRefs.update((('arcroleRef', XbrlConst.all, 'http://www.xbrl.org/2005/xbrldt-2005.xsd#all'), ('arcroleRef', XbrlConst.dimensionDefault, 'http://www.xbrl.org/2005/xbrldt-2005.xsd#dimension-default'), ('arcroleRef', XbrlConst.dimensionDomain, 'http://www.xbrl.org/2005/xbrldt-2005.xsd#dimension-domain'), ('arcroleRef', XbrlConst.domainMember, 'http://www.xbrl.org/2005/xbrldt-2005.xsd#domain-member'), ('arcroleRef', XbrlConst.hypercubeDimension, 'http://www.xbrl.org/2005/xbrldt-2005.xsd#hypercube-dimension')))
                    elif (lbType == 'generic'):
                        for _arcroleURI in relationshipArcroles.values():
                            for _arcroleType in modelXbrl.arcroleTypes[_arcroleURI]:
                                roleRefs.add(('arcroleRef', _arcroleURI, ((_arcroleType.modelDocument.uri + '#') + _arcroleType.id)))
                                break
                    lbTreeWalk(lbType, lbElt, lbLB, roleRefs)
                    if ((lbType == 'definition') and lbTreeHasDimDefault(lbLB)):
                        lbTreeWalk(lbType, lbElt, lbLB, roleRefs, dimDef=True)
                    firstLinkElt = None
                    for firstLinkElt in lbElt.iterchildren():
                        break
                    for (roleref, roleURI, href) in roleRefs:
                        XmlUtil.addChild(lbElt, link, roleref, attributes=((('arcroleURI' if (roleref == 'arcroleRef') else 'roleURI'), roleURI), ('{http://www.w3.org/1999/xlink}type', 'simple'), ('{http://www.w3.org/1999/xlink}href', docRelpath(href, thisDoc.thisLBdir))), beforeSibling=firstLinkElt)
                    lbDoc.linkbaseDiscover(lbElt)
                    break
            if extUnrecognizedRoles:
                modelXbrl.error('loadFromExcel:undefinedRole', '%(lbType)s linkbase roles not defined: %(undefinedRoles)s', modelXbrl=modelXbrl, lbType=lbType, undefinedRoles=','.join(sorted(extUnrecognizedRoles)))
                extUnrecognizedRoles.clear()
    visitedDocNames.pop()