/* eslint-disable */
/*
 * GENERATED FILE - DO NOT EDIT DIRECTLY.
 *
 * Regenerate with:
 *   node scripts/build-embedded-template-runtime.js
 */
(function () {
  'use strict';

  const MODULE_SOURCES = {
  "citeproc": "/*\nCopyright (c) 2009-2019 Frank Bennett\n\n\tThis program is free software: you can redistribute it and/or\n\tmodify it under EITHER\n\n      * the terms of the Common Public Attribution License (CPAL) as\n\t    published by the Open Source Initiative, either version 1 of\n\t    the CPAL, or (at your option) any later version; OR\n\n      * the terms of the GNU Affero General Public License (AGPL)\n        as published by the Free Software Foundation, either version\n        3 of the AGPL, or (at your option) any later version.\n\n\tThis program is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n\tAffero General Public License for more details.\n\n\tYou should have received copies of the Common Public Attribution\n    License and of the GNU Affero General Public License along with\n    this program.  If not, see <https://opensource.org/licenses/> or\n    <http://www.gnu.org/licenses/> respectively.\n*/\n/*global CSL: true */\n\n/**\n * A Javascript implementation of the CSL citation formatting language.\n *\n * <p>A configured instance of the process is built in two stages,\n * using {@link CSL.Core.Build} and {@link CSL.Core.Configure}.\n * The former sets up hash-accessible locale data and imports the CSL format file\n * to be applied to the citations,\n * transforming it into a one-dimensional token list, and\n * registering functions and parameters on each token as appropriate.\n * The latter sets jump-point information\n * on tokens that constitute potential branch\n * points, in a single back-to-front scan of the token list.\n * This\n * yields a token list that can be executed front-to-back by\n * body methods available on the\n * {@link CSL.Engine} class.</p>\n *\n * <p>This top-level {@link CSL} object itself carries\n * constants that are needed during processing.</p>\n * @namespace A CSL citation formatter.\n */\n\n// IE6 does not implement Array.indexOf().\n// IE7 neither, according to rumour.\n\n\n// Potential skip words:\n// under; along; out; between; among; outside; inside; amid; amidst; against; toward; towards.\n// See https://forums.zotero.org/discussion/30484/?Focus=159613#Comment_159613\n\n'use strict';\n\n\nvar CSL = {\n\n    PROCESSOR_VERSION: \"1.4.61\",\n\n    error: function(str) { // default error function\n        if (\"undefined\" === typeof Error) {\n            throw new Error(\"citeproc-js error: \" + str);\n        } else {\n            throw \"citeproc-js error: \" + str;\n        }\n    },\n    debug: function(str) { // default debug function\n        if (\"undefined\" === typeof console) {\n            dump(\"CSL: \" + str + \"\\n\");\n        } else {\n            console.log(\"citeproc-js warning: \" + str);\n        }\n    },\n\n    toLocaleUpperCase(str) {\n        var arr = this.tmp.lang_array;\n        try {\n            str = str.toLocaleUpperCase(arr);\n        } catch (e) {\n            str = str.toUpperCase();\n        }\n        return str;\n    },\n\n    toLocaleLowerCase(str) {\n        var arr = this.tmp.lang_array;\n        try {\n            str = str.toLocaleLowerCase(arr);\n        } catch (e) {\n            str = str.toLowerCase();\n        }\n        return str;\n    },\n\n    LOCATOR_LABELS_REGEXP: new RegExp(\"^((vrs|sv|subpara|op|subch|add|amend|annot|app|art|bibliog|bk|ch|cl|col|cmt|dec|dept|div|ex|fig|fld|fol|n|hypo|illus|intro|l|no|p|pp|para|pt|pmbl|princ|pub|r|rn|sched|sec|ser|subdiv|subsec|supp|tbl|tit|vol)\\\\.)\\\\s+(.*)\"),\n\n    STATUTE_SUBDIV_PLAIN_REGEX: /(?:(?:^| )(?:vrs|sv|subpara|op|subch|add|amend|annot|app|art|bibliog|bk|ch|cl|col|cmt|dec|dept|div|ex|fig|fld|fol|n|hypo|illus|intro|l|no|p|pp|para|pt|pmbl|princ|pub|r|rn|sched|sec|ser|subdiv|subsec|supp|tbl|tit|vol)\\. *)/,\n    STATUTE_SUBDIV_PLAIN_REGEX_FRONT: /(?:^\\s*[.,;]*\\s*(?:vrs|sv|subpara|op|subch|add|amend|annot|app|art|bibliog|bk|ch|cl|col|cmt|dec|dept|div|ex|fig|fld|fol|n|hypo|illus|intro|l|no|p|pp|para|pt|pmbl|princ|pub|r|rn|sched|sec|ser|subdiv|subsec|supp|tbl|tit|vol)\\. *)/,\n \n    STATUTE_SUBDIV_STRINGS: {\n        \"vrs.\": \"verse\",\n\t\t\"sv.\": \"sub-verbo\",\n        \"subpara.\": \"subparagraph\",\n        \"op.\": \"opus\",\n        \"subch.\": \"subchapter\",\n        \"add.\": \"addendum\",\n        \"amend.\": \"amendment\",\n        \"annot.\": \"annotation\",\n        \"app.\": \"appendix\",\n        \"art.\": \"article\",\n        \"bibliog.\": \"bibliography\",\n        \"bk.\": \"book\",\n        \"ch.\": \"chapter\",\n        \"cl.\": \"clause\",\n        \"col.\": \"column\",\n        \"cmt.\": \"comment\",\n        \"dec.\": \"decision\",\n        \"dept.\": \"department\",\n        \"ex.\": \"example\",\n        \"fig.\": \"figure\",\n        \"fld.\": \"field\",\n        \"fol.\": \"folio\",\n        \"n.\": \"note\",\n        \"hypo.\": \"hypothetical\",\n        \"illus.\": \"illustration\",\n        \"intro.\": \"introduction\",\n        \"l.\": \"line\",\n        \"no.\": \"issue\",\n        \"p.\": \"page\",\n        \"pp.\": \"page\",\n        \"para.\": \"paragraph\",\n        \"pt.\": \"part\",\n        \"pmbl.\": \"preamble\",\n        \"princ.\": \"principle\",\n        \"pub.\": \"publication\",\n        \"r.\": \"rule\",\n        \"rn.\": \"randnummer\",\n        \"sched.\": \"schedule\",\n        \"sec.\": \"section\",\n        \"ser.\": \"series,\",\n        \"subdiv.\": \"subdivision\",\n        \"subsec.\": \"subsection\",\n        \"supp.\": \"supplement\",\n        \"tbl.\": \"table\",\n        \"tit.\": \"title\",\n        \"vol.\": \"volume\"\n    },\n    STATUTE_SUBDIV_STRINGS_REVERSE: {\n        \"verse\": \"vrs.\",\n\t\t\"sub-verbo\": \"sv.\",\n        \"sub verbo\": \"sv.\",\n        \"subparagraph\": \"subpara.\",\n        \"opus\": \"op.\",\n        \"subchapter\": \"subch.\",\n        \"addendum\": \"add.\",\n        \"amendment\": \"amend.\",\n        \"annotation\": \"annot.\",\n        \"appendix\": \"app.\",\n        \"article\": \"art.\",\n        \"bibliography\": \"bibliog.\",\n        \"book\": \"bk.\",\n        \"chapter\": \"ch.\",\n        \"clause\": \"cl.\",\n        \"column\": \"col.\",\n        \"comment\": \"cmt.\",\n        \"decision\": \"dec.\",\n        \"department\": \"dept.\",\n        \"example\": \"ex.\",\n        \"figure\": \"fig.\",\n        \"field\": \"fld.\",\n        \"folio\": \"fol.\",\n        \"note\": \"n.\",\n        \"hypothetical\": \"hypo.\",\n        \"illustration\": \"illus.\",\n        \"introduction\": \"intro.\",\n        \"line\": \"l.\",\n        \"issue\": \"no.\",\n        \"page\": \"p.\",\n        \"paragraph\": \"para.\",\n        \"part\": \"pt.\",\n        \"preamble\": \"pmbl.\",\n        \"principle\": \"princ.\",\n        \"publication\": \"pub.\",\n        \"rule\": \"r.\",\n        \"randnummer\": \"rn.\",\n        \"schedule\": \"sched.\",\n        \"section\": \"sec.\",\n        \"series,\": \"ser.\",\n        \"subdivision\": \"subdiv.\",\n        \"subsection\": \"subsec.\",\n        \"supplement\": \"supp.\",\n        \"table\": \"tbl.\",\n        \"title\": \"tit.\",\n        \"volume\": \"vol.\"\n    },\n\n    LOCATOR_LABELS_MAP: {\n        \"vrs\": \"verse\",\n\t\t\"sv\": \"sub-verbo\",\n        \"subpara\": \"subparagraph\",\n        \"op\": \"opus\",\n        \"subch\": \"subchapter\",\n        \"add\": \"addendum\",\n        \"amend\": \"amendment\",\n        \"annot\": \"annotation\",\n        \"app\": \"appendix\",\n        \"art\": \"article\",\n        \"bibliog\": \"bibliography\",\n        \"bk\": \"book\",\n        \"ch\": \"chapter\",\n        \"cl\": \"clause\",\n        \"col\": \"column\",\n        \"cmt\": \"comment\",\n        \"dec\": \"decision\",\n        \"dept\": \"department\",\n        \"ex\": \"example\",\n        \"fig\": \"figure\",\n        \"fld\": \"field\",\n        \"fol\": \"folio\",\n        \"n\": \"note\",\n        \"hypo\": \"hypothetical\",\n        \"illus\": \"illustration\",\n        \"intro\": \"introduction\",\n        \"l\": \"line\",\n        \"no\": \"issue\",\n        \"p\": \"page\",\n        \"pp\": \"page\",\n        \"para\": \"paragraph\",\n        \"pt\": \"part\",\n        \"pmbl\": \"preamble\",\n        \"princ\": \"principle\",\n        \"pub\": \"publication\",\n        \"r\": \"rule\",\n        \"rn\": \"randnummer\",\n        \"sched\": \"schedule\",\n        \"sec\": \"section\",\n        \"ser\": \"series,\",\n        \"subdiv\": \"subdivision\",\n        \"subsec\": \"subsection\",\n        \"supp\": \"supplement\",\n        \"tbl\": \"table\",\n        \"tit\": \"title\",\n        \"vol\": \"volume\"\n    },\n    MODULE_MACROS: {\n        \"juris-pretitle\": true,\n        \"juris-title\": true,\n        \"juris-pretitle-short\": true,\n        \"juris-title-short\": true,\n        \"juris-main\": true,\n        \"juris-main-short\": true,\n        \"juris-tail\": true,\n        \"juris-tail-short\": true,\n        \"juris-locator\": true\n    },\n    MODULE_TYPES: {\n        \"legal_case\": true,\n        \"legislation\": true,\n        \"bill\": true,\n        \"hearing\": true,\n        \"gazette\": true,\n        \"report\": true,\n        \"regulation\": true,\n        \"standard\": true,\n        \"patent\": true,\n        \"locator\": true\n    },\n    checkNestedBrace: function(state) {\n        if (state.opt.xclass === \"note\") {\n            this.depth = 0;\n            this.update = function(str) {\n                \n                // Receives affix string, returns with flipped parens.\n                \n                var str = str ? str : \"\";\n                var lst = str.split(/([\\(\\)])/);\n                for (var i=1,ilen=lst.length;i<ilen;i += 2) {\n                    if (lst[i] === \"(\") {\n                        if (1 === (this.depth % 2)) {\n                            lst[i] = \"[\";\n                        }\n                        this.depth += 1;\n                    } else if (lst[i] === \")\") {\n                        if (0 === (this.depth % 2)) {\n                            lst[i] = \"]\";\n                        }\n                        this.depth -= 1;\n                    }\n                }\n                var ret = lst.join(\"\");\n                return ret;\n            };\n        } else {\n            this.update = function(str) {\n                return str;\n            };\n        }\n    },\n\n    MULTI_FIELDS: [\"event\", \"publisher\", \"publisher-place\", \"event-place\", \"title\", \"container-title\", \"collection-title\", \"authority\",\"genre\",\"title-short\",\"medium\",\"country\",\"jurisdiction\",\"archive\",\"archive-place\"],\n\n    LangPrefsMap: {\n        \"title\":\"titles\",\n        \"title-short\":\"titles\",\n        \"event\":\"titles\",\n        \"genre\":\"titles\",\n        \"medium\":\"titles\",\n        \"container-title\":\"journals\",\n        \"collection-title\":\"titles\",\n        \"archive\":\"journals\",\n        \"publisher\":\"publishers\",\n        \"authority\":\"publishers\",\n        \"publisher-place\": \"places\",\n        \"event-place\": \"places\",\n        \"archive-place\": \"places\",\n        \"jurisdiction\": \"places\",\n        \"number\": \"places\",\n        \"edition\":\"places\",\n        \"issue\":\"places\",\n        \"volume\":\"places\"\n    },\n\n    AbbreviationSegments: function () {\n        this[\"container-title\"] = {};\n        this[\"collection-title\"] = {};\n        this[\"institution-entire\"] = {};\n        this[\"institution-part\"] = {};\n        this.nickname = {};\n        this.number = {};\n        this.title = {};\n        this.place = {};\n        this.hereinafter = {};\n        this.classic = {};\n        this[\"container-phrase\"] = {};\n        this[\"title-phrase\"] = {};\n    },\n\n    getAbbrevsDomain: function (state, country, lang) {\n\t\tvar domain = null;\n        if (state.opt.availableAbbrevDomains && country && country !== \"default\") {\n\t        var globalDomainPreference = state.locale[state.opt.lang].opts[\"jurisdiction-preference\"];\n\t\t    var itemDomainPreference = null;\n\t\t    if (state.locale[lang]) {\n\t\t\t    itemDomainPreference = state.locale[lang].opts[\"jurisdiction-preference\"];\n\t\t    }\n\t\t    if (itemDomainPreference) {\n\t\t\t    for (var j=itemDomainPreference.length-1; j > -1; j--) {\n\t\t\t\t    if (state.opt.availableAbbrevDomains[country].indexOf(itemDomainPreference[j]) > -1) {\n\t\t\t\t\t    domain = itemDomainPreference[j];\n\t\t\t\t\t    break;\n\t\t\t\t    }\n\t\t\t    }\n\t\t    }\n\t\t    if (!domain && globalDomainPreference) {\n\t\t\t    for (var j=globalDomainPreference.length-1; j > -1; j--) {\n\t\t\t\t    if (state.opt.availableAbbrevDomains[country].indexOf(globalDomainPreference[j]) > -1) {\n\t\t\t\t\t    domain = globalDomainPreference[j];\n\t\t\t\t\t    break;\n\t\t\t\t    }\n\t\t\t    }\n\t\t    }\n        }\n        return domain;\n    },\n    \n    FIELD_CATEGORY_REMAP: {\n        \"title\": \"title\",\n        \"container-title\": \"container-title\",\n        \"collection-title\": \"collection-title\",\n        \"country\": \"place\",\n        \"number\": \"number\",\n        \"place\": \"place\",\n        \"archive\": \"container-title\",\n        \"title-short\": \"title\",\n        \"genre\": \"title\",\n        \"event\": \"title\",\n        \"medium\": \"title\",\n\t\t\"archive-place\": \"place\",\n\t\t\"publisher-place\": \"place\",\n\t\t\"event-place\": \"place\",\n\t\t\"jurisdiction\": \"place\",\n\t\t\"language-name\": \"place\",\n\t\t\"language-name-original\": \"place\",\n        \"call-number\": \"number\",\n        \"chapter-number\": \"number\",\n        \"collection-number\": \"number\",\n        \"edition\": \"number\",\n        \"page\": \"number\",\n        \"issue\": \"number\",\n        \"locator\": \"number\",\n        \"locator-extra\": \"number\",\n        \"number-of-pages\": \"number\",\n        \"number-of-volumes\": \"number\",\n        \"volume\": \"number\",\n        \"citation-number\": \"number\",\n        \"publisher\": \"institution-part\"\n    },\n    \n    parseLocator: function(item) {\n        if (this.opt.development_extensions.locator_date_and_revision) {\n            // Break out locator elements if necessary\n            if (item.locator) {\n                item.locator = \"\" + item.locator;\n                var idx = item.locator.indexOf(\"|\");\n                if (idx > -1) {\n                    var raw_locator = item.locator;\n                    item.locator = raw_locator.slice(0, idx);\n                    raw_locator = raw_locator.slice(idx + 1);\n                    var m = raw_locator.match(/^([0-9]{4}-[0-9]{2}-[0-9]{2}).*/);\n                    if (m) {\n                        item[\"locator-date\"] = this.fun.dateparser.parseDateToObject(m[1]);\n                        raw_locator = raw_locator.slice(m[1].length);\n                    }\n                    item[\"locator-extra\"] = raw_locator.replace(/^\\s+/, \"\").replace(/\\s+$/, \"\");\n                }\n            }\n        }\n        if (item.locator) {\n            item.locator = (\"\" + item.locator).replace(/\\s+$/, '');\n        }\n        return item;\n    },\n\n    normalizeLocaleStr: function(str) {\n        if (!str) {\n            return;\n        }\n        var lst = str.split('-');\n        lst[0] = lst[0].toLowerCase();\n        if (lst[1]) {\n            lst[1] = lst[1].toUpperCase();\n        }\n        return lst.join(\"-\");\n    },\n\n    parseNoteFieldHacks: function(Item, validFieldsForType, allowDateOverride) {\n        if (\"string\" !== typeof Item.note) {\n            return;\n        }\n        var elems = [];\n        var lines = Item.note.split('\\n');\n        // Normalize entries\n        for (var i=0, ilen=lines.length; i<ilen; i++) {\n            var line = lines[i];\n            var elems = [];\n            var m = line.match(CSL.NOTE_FIELDS_REGEXP);\n            if (m) {\n                var splt = line.split(CSL.NOTE_FIELDS_REGEXP);\n                for (var j=0,jlen=(splt.length-1);j<jlen;j++) {\n                    elems.push(splt[j]);\n                    elems.push(m[j]);\n                }\n                elems.push(splt[splt.length-1]);\n                for (var j=1,jlen=elems.length;j<jlen;j += 2) {\n                    // Abort conversions if preceded by unparseable text\n                    if (elems[j-1].trim() && (i>0 || j>1) && !elems[j-1].match(CSL.NOTE_FIELD_REGEXP)) {\n                        break;\n                    } else {\n                        elems[j] = '\\n' + elems[j].slice(2,-1).trim() + '\\n';\n                    }\n                }\n                lines[i] = elems.join('');\n            }\n        }\n        // Resplit\n        lines = lines.join('\\n').split('\\n');\n        var offset = 0;\n        var names = {};\n        for (var i=0,ilen=lines.length;i<ilen;i++) {\n            var line = lines[i];\n            var mm = line.match(CSL.NOTE_FIELD_REGEXP);\n            if (!line.trim()) {\n                continue;\n            } else if (!mm) {\n                if (i === 0) {\n                    continue;\n                } else {\n                    offset = i;\n                    break;\n                }\n            }\n            var key = mm[1];\n            var val = mm[2].replace(/^\\s+/, \"\").replace(/\\s+$/, \"\");\n            if (key === \"type\") {\n                Item.type = val;\n                lines[i] = \"\";\n            } else if (CSL.DATE_VARIABLES.indexOf(key.replace(/^alt-/, \"\")) > -1) {\n                if (!Item[key] || allowDateOverride) {\n                    Item[key] = CSL.DateParser.parseDateToArray(val);\n                    if (!validFieldsForType || (validFieldsForType[key] && this.isDateString(val))) {\n                        lines[i] = \"\";\n                    }\n                }\n            } else if (!Item[key]) {\n                if (CSL.NAME_VARIABLES.indexOf(key.replace(/^alt-/, \"\")) > -1) {\n                    if (!names[key]) {\n                        names[key] = [];\n                    }\n                    var lst = val.split(/\\s*\\|\\|\\s*/);\n                    if (lst.length === 1) {\n                        names[key].push({literal:lst[0]});\n                    } else if (lst.length === 2) {\n                        var name = {family:lst[0],given:lst[1]};\n                        CSL.parseParticles(name);\n                        names[key].push(name);\n                    }\n                } else {\n                    Item[key] = val;\n                }\n                if (!validFieldsForType || validFieldsForType[key]) {\n                    lines[i] = \"\";\n                }\n            }\n        }\n        for (var key in names) {\n            Item[key] = names[key];\n        }\n        // Final cleanup for validCslFields only: eliminate blank lines, add blank line to text\n        if (validFieldsForType) {\n            if (lines[offset].trim()) {\n                lines[offset] = '\\n' + lines[offset];\n            }\n            for (var i=offset-1;i>-1;i--) {\n                if (!lines[i].trim()) {\n                    lines = lines.slice(0, i).concat(lines.slice(i + 1));\n                }\n            }\n        }\n        Item.note = lines.join(\"\\n\").trim();\n    },\n\n    checkPrefixSpaceAppend: function (state, prefix) {\n        if (!prefix) {\n            prefix = \"\";\n        }\n        var sp = \"\";\n        // We need the raw string, without decorations\n        // of any kind. Markup scheme is known, though, so\n        // markup can be safely stripped at string level.\n        //\n        // U+201d = right double quotation mark\n        // U+2019 = right single quotation mark\n        // U+00bb = right double angle bracket (guillemet)\n        // U+202f = non-breaking thin space\n        // U+00a0 = non-breaking space\n        var test_prefix = prefix.replace(/<[^>]+>/g, \"\").replace(/[\"'\\u201d\\u2019\\u00bb\\u202f\\u00a0 ]+$/g,\"\");\n        var test_char = test_prefix.slice(-1);\n        if (test_prefix.match(CSL.ENDSWITH_ROMANESQUE_REGEXP)) {\n            sp = \" \";\n        } else if (CSL.TERMINAL_PUNCTUATION.slice(0,-1).indexOf(test_char) > -1) {\n            sp = \" \";\n        } else if (test_char.match(/[\\)\\],0-9]/)) {\n            sp = \" \";\n        }\n        // Protect against double spaces, which would trigger an extra,\n        // explicit, non-breaking space.\n        var prefix = (prefix + sp).replace(/\\s+/g, \" \");\n        return prefix;\n    },\n\n    checkIgnorePredecessor: function(state, prefix) {\n        var ignorePredecessor = false;\n        var test_prefix = prefix.replace(/<[^>]+>/g, \"\").replace(/[\"'\\u201d\\u2019\\u00bb\\u202f\\u00a0 ]+$/g,\"\");\n        var test_char = test_prefix.slice(-1);\n        if (CSL.TERMINAL_PUNCTUATION.slice(0,-1).indexOf(test_char) > -1 && prefix.trim().indexOf(\" \") > -1) {\n            state.tmp.term_predecessor = false;\n            return true;\n        }\n        return false;\n    },\n\n    checkSuffixSpacePrepend: function(state, suffix) {\n        if (!suffix) {\n            return \"\";\n        }\n        if (suffix.match(CSL.STARTSWITH_ROMANESQUE_REGEXP) || ['[','('].indexOf(suffix.slice(0,1)) > -1) {\n            suffix = \" \" + suffix;\n        }\n        return suffix;\n    },\n    \n    GENDERS: [\"masculine\", \"feminine\"],\n    \n    ERROR_NO_RENDERED_FORM: 1,\n\n    PREVIEW: \"Just for laughs.\",\n    ASSUME_ALL_ITEMS_REGISTERED: 2,\n\n    START: 0,\n    END: 1,\n    SINGLETON: 2,\n\n    SEEN: 6,\n    SUCCESSOR: 3,\n    SUCCESSOR_OF_SUCCESSOR: 4,\n    SUPPRESS: 5,\n\n    SINGULAR: 0,\n    PLURAL: 1,\n\n    LITERAL: true,\n\n    BEFORE: 1,\n    AFTER: 2,\n\n    DESCENDING: 1,\n    ASCENDING: 2,\n\n    PRIMARY: 1,\n    SECONDARY: 2,\n    \n    POSITION_FIRST: 0,\n    POSITION_SUBSEQUENT: 1,\n    POSITION_IBID: 2,\n    POSITION_IBID_WITH_LOCATOR: 3,\n    POSITION_CONTAINER_SUBSEQUENT: 4,\n\n    POSITION_MAP: {\n        \"0\": 0,\n        \"4\": 1,\n        \"1\": 2,\n        \"2\": 3,\n        \"3\": 4\n    },\n    \n    POSITION_TEST_VARS: [\"position\", \"first-reference-note-number\", \"near-note\"],\n\n    AREAS: [\"citation\", \"citation_sort\", \"bibliography\", \"bibliography_sort\", \"intext\"],\n\n    CITE_FIELDS: [\"first-reference-note-number\", \"first-container-reference-note-number\", \"locator\", \"locator-extra\"],\n\n    SWAPPING_PUNCTUATION: [\".\", \"!\", \"?\", \":\", \",\"],\n    TERMINAL_PUNCTUATION: [\":\", \".\", \";\", \"!\", \"?\", \" \"],\n\n    // update modes\n    NONE: 0,\n    NUMERIC: 1,\n    POSITION: 2,\n    TRIGRAPH: 3,\n\n    DATE_PARTS: [\"year\", \"month\", \"day\"],\n    DATE_PARTS_ALL: [\"year\", \"month\", \"day\", \"season\"],\n    DATE_PARTS_INTERNAL: [\"year\", \"month\", \"day\", \"year_end\", \"month_end\", \"day_end\"],\n\n    NAME_PARTS: [\"non-dropping-particle\", \"family\", \"given\", \"dropping-particle\", \"suffix\", \"literal\"],\n\n    DISAMBIGUATE_OPTIONS: [\n        \"disambiguate-add-names\",\n        \"disambiguate-add-givenname\",\n        \"disambiguate-add-year-suffix\"\n    ],\n\n    GIVENNAME_DISAMBIGUATION_RULES: [\n        \"all-names\",\n        \"all-names-with-initials\",\n        \"primary-name\",\n        \"primary-name-with-initials\",\n        \"by-cite\"\n    ],\n\n    NAME_ATTRIBUTES: [\n        \"and\",\n        \"delimiter-precedes-last\",\n        \"delimiter-precedes-et-al\",\n        \"initialize-with\",\n        \"initialize\",\n        \"name-as-sort-order\",\n        \"sort-separator\",\n        \"et-al-min\",\n        \"et-al-use-first\",\n        \"et-al-subsequent-min\",\n        \"et-al-subsequent-use-first\",\n        \"form\",\n        \"prefix\",\n        \"suffix\",\n        \"delimiter\"\n    ],\n\n    LOOSE: 0,\n    STRICT: 1,\n    TOLERANT: 2,\n\n    PREFIX_PUNCTUATION: /[.;:]\\s*$/,\n    SUFFIX_PUNCTUATION: /^\\s*[.;:,\\(\\)]/,\n\n    NUMBER_REGEXP: /(?:^\\d+|\\d+$)/,\n    //\n    // \\u0400-\\u042f are cyrillic and extended cyrillic capitals\n    // this is not fully smart yet.  can't do what this was trying to do\n    // with regexps, actually; we want to identify strings with a leading\n    // capital letter, and any subsequent capital letters.  Have to compare\n    // locale caps version with existing version, character by character.\n    // hard stuff, but if it breaks, that's what to do.\n    // \\u0600-\\u06ff is Arabic/Persian\n    // \\u200c-\\u200e and \\u202a-\\u202e are special spaces and left-right \n    // control characters\n\n\n\n    NAME_INITIAL_REGEXP: /^([A-Z\\u0e01-\\u0e5b\\u00c0-\\u017f\\u0400-\\u042f\\u0590-\\u05d4\\u05d6-\\u05ff\\u0600-\\u06ff\\u0370\\u0372\\u0376\\u0386\\u0388-\\u03ab\\u03e2\\u03e4\\u03e6\\u03e8\\u03ea\\u03ec\\u03ee\\u03f4\\u03f7\\u03fd-\\u03ff])([a-zA-Z\\u0e01-\\u0e5b\\u00c0-\\u017f\\u0400-\\u052f\\u0600-\\u06ff\\u0370-\\u03ff\\u1f00-\\u1fff]*|)(\\.)*/,\n    ROMANESQUE_REGEXP: /[-0-9a-zA-Z\\u0e01-\\u0e5b\\u00c0-\\u017f\\u0370-\\u03ff\\u0400-\\u052f\\u0590-\\u05d4\\u05d6-\\u05ff\\u1f00-\\u1fff\\u0600-\\u06ff\\u200c\\u200d\\u200e\\u0218\\u0219\\u021a\\u021b\\u202a-\\u202e]/,\n    ROMANESQUE_NOT_REGEXP: /[^a-zA-Z\\u0e01-\\u0e5b\\u00c0-\\u017f\\u0370-\\u03ff\\u0400-\\u052f\\u0590-\\u05d4\\u05d6-\\u05ff\\u1f00-\\u1fff\\u0600-\\u06ff\\u200c\\u200d\\u200e\\u0218\\u0219\\u021a\\u021b\\u202a-\\u202e]/g,\n    STARTSWITH_ROMANESQUE_REGEXP: /^[&a-zA-Z\\u0e01-\\u0e5b\\u00c0-\\u017f\\u0370-\\u03ff\\u0400-\\u052f\\u0590-\\u05d4\\u05d6-\\u05ff\\u1f00-\\u1fff\\u0600-\\u06ff\\u200c\\u200d\\u200e\\u0218\\u0219\\u021a\\u021b\\u202a-\\u202e]/,\n    ENDSWITH_ROMANESQUE_REGEXP: /[.;:&a-zA-Z\\u0e01-\\u0e5b\\u00c0-\\u017f\\u0370-\\u03ff\\u0400-\\u052f\\u0590-\\u05d4\\u05d6-\\u05ff\\u1f00-\\u1fff\\u0600-\\u06ff\\u200c\\u200d\\u200e\\u0218\\u0219\\u021a\\u021b\\u202a-\\u202e]$/,\n    ALL_ROMANESQUE_REGEXP: /^[a-zA-Z\\u0e01-\\u0e5b\\u00c0-\\u017f\\u0370-\\u03ff\\u0400-\\u052f\\u0590-\\u05d4\\u05d6-\\u05ff\\u1f00-\\u1fff\\u0600-\\u06ff\\u200c\\u200d\\u200e\\u0218\\u0219\\u021a\\u021b\\u202a-\\u202e]+$/,\n\n    VIETNAMESE_SPECIALS: /[\\u00c0-\\u00c3\\u00c8-\\u00ca\\u00cc\\u00cd\\u00d2-\\u00d5\\u00d9\\u00da\\u00dd\\u00e0-\\u00e3\\u00e8-\\u00ea\\u00ec\\u00ed\\u00f2-\\u00f5\\u00f9\\u00fa\\u00fd\\u0101\\u0103\\u0110\\u0111\\u0128\\u0129\\u0168\\u0169\\u01a0\\u01a1\\u01af\\u01b0\\u1ea0-\\u1ef9]/,\n\n    VIETNAMESE_NAMES: /^(?:(?:[.AaBbCcDdEeGgHhIiKkLlMmNnOoPpQqRrSsTtUuVvXxYy \\u00c0-\\u00c3\\u00c8-\\u00ca\\u00cc\\u00cd\\u00d2-\\u00d5\\u00d9\\u00da\\u00dd\\u00e0-\\u00e3\\u00e8-\\u00ea\\u00ec\\u00ed\\u00f2-\\u00f5\\u00f9\\u00fa\\u00fd\\u0101\\u0103\\u0110\\u0111\\u0128\\u0129\\u0168\\u0169\\u01a0\\u01a1\\u01af\\u01b0\\u1ea0-\\u1ef9]{2,6})(\\s+|$))+$/,\n\n    NOTE_FIELDS_REGEXP: /\\{:(?:[\\-_a-z]+|[A-Z]+):[^\\}]+\\}/g,\n    NOTE_FIELD_REGEXP: /^([\\-_a-z]+|[A-Z]+):\\s*([^\\}]+)$/,\n\n\tPARTICLE_GIVEN_REGEXP: /^([^ ]+(?:\\u02bb |\\u2019 | |\\' ) *)(.+)$/,\n\tPARTICLE_FAMILY_REGEXP: /^([^ ]+(?:\\-|\\u02bb|\\u2019| |\\') *)(.+)$/,\n\n    DISPLAY_CLASSES: [\"block\", \"left-margin\", \"right-inline\", \"indent\"],\n\n    NAME_VARIABLES: [\n        \"author\",\n        \"chair\",\n        \"collection-editor\",\n        \"compiler\",\n        \"composer\",\n        \"container-author\",\n        \"contributor\",\n        \"curator\",\n        \"director\",\n        \"editor\",\n        \"editor-translator\", \n        \"editorial-director\",\n        \"executive-producer\",\n        \"guest\",\n        \"host\",\n        \"illustrator\",\n        \"interviewer\",\n        \"narrator\", \n        \"organizer\",\n        \"original-author\",\n        \"performer\",\n        \"producer\",\n        \"recipient\",\n        \"reviewed-author\",\n        \"script-writer\",\n        \"series-creator\",\n        \"translator\",\n        \"commenter\"\n    ],\n    CREATORS: [\n        \"author\",\n        \"chair\",\n        \"collection-editor\",\n        \"compiler\",\n        \"composer\",\n        \"container-author\",\n        \"contributor\",\n        \"curator\",\n        \"director\",\n        \"editor\",\n        \"editor-translator\", \n        \"editorial-director\",\n        \"executive-producer\",\n        \"guest\",\n        \"host\",\n        \"illustrator\",\n        \"interviewer\",\n        \"narrator\", \n        \"organizer\",\n        \"original-author\",\n        \"performer\",\n        \"producer\",\n        \"recipient\",\n        \"reviewed-author\",\n        \"script-writer\",\n        \"series-creator\",\n        \"translator\",\n        \"commenter\"\n    ],\n    NUMERIC_VARIABLES: [\n        \"call-number\",\n        \"chapter-number\",\n        \"collection-number\",\n        \"division\",\n        \"edition\",\n        \"page\",\n        \"issue\",\n        \"locator\",\n        \"locator-extra\",\n        \"number\",\n        \"number-of-pages\",\n        \"number-of-volumes\",\n        \"part-number\",\n        \"printing-number\",\n        \"section\",\n        \"supplement-number\",\n        \"version\",\n        \"volume\",\n        \"supplement\", // maybe deprecated this? supplement-number should serve this purpose in standard CSL.\n        \"citation-number\"\n    ],\n    //var x = new Array();\n    //x = x.concat([\"title\",\"container-title\",\"issued\",\"page\"]);\n    //x = x.concat([\"locator\",\"collection-number\",\"original-date\"]);\n    //x = x.concat([\"reporting-date\",\"decision-date\",\"filing-date\"]);\n    //x = x.concat([\"revision-date\"]);\n    //NUMERIC_VARIABLES = x.slice();\n    DATE_VARIABLES: [\n        \"locator-date\", \n        \"issued\", \n        \"event-date\", \n        \"accessed\", \n        \"original-date\",\n        \"publication-date\",\n        \"available-date\",\n        \"submitted\",\n        \"alt-issued\",\n        \"alt-event\"\n    ],\n    VARIABLES_WITH_SHORT_FORM: [\n        \"title\",\n        \"container-title\"\n    ],\n    TITLE_FIELD_SPLITS: function(seg) {\n        var keys = [\"title\", \"short\", \"main\", \"sub\", \"subjoin\"];\n        var ret = {};\n        for (var i=0,ilen=keys.length;i<ilen;i++) {\n            ret[keys[i]] = seg + \"title\" + (keys[i] === \"title\" ? \"\" : \"-\" + keys[i]);\n        }\n        return ret;\n    },\n    \n    demoteNoiseWords: function (state, fld, drop_or_demote) {\n        var SKIP_WORDS = state.locale[state.opt.lang].opts[\"leading-noise-words\"];\n        if (fld && drop_or_demote) {\n            fld = fld.split(/\\s+/);\n            fld.reverse();\n            var toEnd = [];\n            for (var j  = fld.length - 1; j > -1; j += -1) {\n                if (SKIP_WORDS.indexOf(fld[j].toLowerCase()) > -1) {\n                    toEnd.push(fld.pop());\n                } else {\n                    break;\n                }\n            }\n            fld.reverse();\n            var start = fld.join(\" \");\n            var end = toEnd.join(\" \");\n            if (\"drop\" === drop_or_demote || !end) {\n                fld = start;\n            } else if (\"demote\" === drop_or_demote) {\n                fld = [start, end].join(\", \");\n            }\n        }\n        return fld;\n    },\n\n    extractTitleAndSubtitle: function (Item, narrowSpaceLocale) {\n        var narrowSpace = narrowSpaceLocale ? \"\\u202f\" : \"\";\n        // XXX In this function, split on split-char, but prefer exact match\n        // XXX of subtitle to a split-char in title if found.\n        var segments = [\"\"];\n        if (this.opt.development_extensions.split_container_title) {\n            segments.push(\"container-\");\n        }\n        for (var i=0,ilen=segments.length;i<ilen;i++) {\n            var seg = segments[i];\n            var title = CSL.TITLE_FIELD_SPLITS(seg);\n            var langs = [false];\n            if (Item.multi) {\n                for (var lang in Item.multi._keys[title.short]) {\n                    langs.push(lang);\n                }\n            }\n            for (var j=0,jlen=langs.length;j<jlen;j++) {\n                var lang = langs[j];\n                var vals = {};\n                if (lang) {\n                    if (Item.multi._keys[title.title]) {\n                        vals[title.title] = Item.multi._keys[title.title][lang];\n                    }\n                    if (Item.multi._keys[title[\"short\"]]) {\n                        vals[title[\"short\"]] = Item.multi._keys[title[\"short\"]][lang];\n                    }\n                } else {\n                    vals[title.title] = Item[title.title];\n                    vals[title[\"short\"]] = Item[title[\"short\"]];\n                }\n                vals[title.main] = vals[title.title];\n                vals[title.sub] = false;\n                var shortTitle = vals[title[\"short\"]];\n                if (vals[title.title]) {\n                    // Rules\n                    // TITLE_SPLIT eliminates split-points of period-space preceded by a capital letter.\n                    // If short title exists and matches exactly to a split-point, use that split-point only.\n                    // Otherwise if there is just one split-point, use that as main/sub split.\n                    // Otherwise use all split-points ... which is handled in titleCaseSentenceOrNormal, not here.\n                    if (shortTitle && shortTitle.toLowerCase() === vals[title.title].toLowerCase()) {\n                        vals[title.main] = vals[title.title];\n                        vals[title.subjoin] = \"\";\n                        vals[title.sub] = \"\";\n                    } else if (shortTitle) {\n                        // check for valid match to shortTitle\n                        var tail = vals[title.title].slice(shortTitle.replace(/[\\?\\!]+$/, \"\").length);\n                        var top = vals[title.title].replace(tail.replace(/^[\\?\\!]+/, \"\"), \"\").trim();\n                        var m = CSL.TITLE_SPLIT_REGEXP.matchfirst.exec(tail);\n                        if (m && top.toLowerCase() === shortTitle.toLowerCase()) {\n                            vals[title.main] = top;\n                            vals[title.subjoin] = m[1].replace(/[\\?\\!]+(\\s*)$/, \"$1\");\n                            vals[title.sub] = tail.replace(CSL.TITLE_SPLIT_REGEXP.matchfirst, \"\");\n                            if (this.opt.development_extensions.force_short_title_casing_alignment) {\n                                vals[title[\"short\"]] = vals[title.main];\n                            }\n                        } else {\n                            var splitTitle = CSL.TITLE_SPLIT(vals[title.title]);\n                            if (splitTitle.length == 3) {\n                                vals[title.main] = splitTitle[0];\n                                vals[title.subjoin] = splitTitle[1];\n                                vals[title.sub] = splitTitle[2];\n                            } else {\n                                vals[title.main] = vals[title.title];\n                                vals[title.subjoin] = \"\";\n                                vals[title.sub] = \"\";\n                            }\n                        }\n                    } else {\n                        var splitTitle = CSL.TITLE_SPLIT(vals[title.title]);\n                        if (splitTitle.length == 3) {\n                            vals[title.main] = splitTitle[0];\n                            vals[title.subjoin] = splitTitle[1];\n                            vals[title.sub] = splitTitle[2];\n                            if (this.opt.development_extensions.implicit_short_title && Item.type !== \"legal_case\") {\n                                if (!Item[title.short] && !vals[title.main].match(/^[\\-\\.[0-9]+$/)) {\n                                    var punct = vals[title.subjoin].trim();\n                                    if ([\"?\", \"!\"].indexOf(punct) === -1) {\n                                        punct = \"\";\n                                    }\n                                    vals[title.short] = vals[title.main] + punct;\n                                }\n                            }\n                        } else {\n                            vals[title.main] = vals[title.title];\n                            vals[title.subjoin] = \"\";\n                            vals[title.sub] = \"\";\n                        }\n                    }\n                    if (vals[title.subjoin]) {\n                        if (vals[title.subjoin].match(/([\\?\\!])/)) {\n                            var m = vals[title.subjoin].match(/(\\s*)$/)\n                            vals[title.main] = vals[title.main] + narrowSpace +vals[title.subjoin].trim();\n                            vals[title.subjoin] = m[1];\n                        }\n                    }\n                }\n                if (vals[title.subjoin]) {\n                    if (vals[title.subjoin].indexOf(\":\") > -1) {\n                        vals[title.subjoin] = narrowSpace + \": \";\n                    }\n                    if (vals[title.subjoin].indexOf(\"-\") > -1 || vals[title.subjoin].indexOf(\"—\") > -1) {\n                        vals[title.subjoin] = \"—\";\n                    }\n                }\n                if (lang) {\n                    for (var key in vals) {\n                        if (!Item.multi._keys[key]) {\n                            Item.multi._keys[key] = {};\n                        }\n                        Item.multi._keys[key][lang] = vals[key];\n                    }\n                } else {\n                    for (var key in vals) {\n                        Item[key] = vals[key];\n                    }\n                }\n            }\n        }\n    },\n\n    titlecaseSentenceOrNormal: function(state, Item, seg, lang, sentenceCase) {\n        // Hold on here.\n        // What is seg here?\n        // It's ... either \"\" or \"container-\". Which is ugly, but works.\n        // But this ALWAYS returns the full title, never short.\n        // So sentence-casing cannot be applied to short.\n        // Goes unnoticed because forced sentence-casing almost never appears in styles.\n        var title = CSL.TITLE_FIELD_SPLITS(seg);\n        var vals = {};\n        if (lang && Item.multi) {\n            if (Item.multi._keys[title.title]) {\n                vals[title.title] = Item.multi._keys[title.title][lang];\n            }\n            if (Item.multi._keys[title.main]) {\n                vals[title.main] = Item.multi._keys[title.main][lang];\n            }\n            if (Item.multi._keys[title.sub]) {\n                vals[title.sub] = Item.multi._keys[title.sub][lang];\n            }\n            if (Item.multi._keys[title.subjoin]) {\n                vals[title.subjoin] = Item.multi._keys[title.subjoin][lang];\n            }\n        } else {\n            vals[title.title] = Item[title.title];\n            vals[title.main] = Item[title.main];\n            vals[title.sub] = Item[title.sub];\n            vals[title.subjoin] = Item[title.subjoin];\n        }\n        if (vals[title.main] && vals[title.sub]) {\n            var mainTitle = vals[title.main];\n            var subJoin = vals[title.subjoin];\n            var subTitle = vals[title.sub];\n            if (sentenceCase) {\n                mainTitle = CSL.Output.Formatters.sentence(state, mainTitle);\n                subTitle = CSL.Output.Formatters.sentence(state, subTitle);\n            } else if (state.opt.development_extensions.uppercase_subtitles) {\n                subTitle = CSL.Output.Formatters[\"capitalize-first\"](state, subTitle);\n            }\n            return [mainTitle, subJoin, subTitle].join(\"\");\n        } else if (vals[title.title]) {\n            if (sentenceCase) {\n                return CSL.Output.Formatters.sentence(state, vals[title.title]);\n            } else if (state.opt.development_extensions.uppercase_subtitles) {\n                // Split and apply everywhere.\n                var splits = CSL.TITLE_SPLIT(vals[title.title]);\n                for (var i=0,ilen=splits.length; i<ilen; i += 2) {\n                    splits[i] = CSL.Output.Formatters[\"capitalize-first\"](state, splits[i]);\n                }\n                for (var i=1, ilen=splits.length-1; i < ilen; i += 2) {\n                    var m = splits[i].match(/([:\\?\\!] )/);\n                    if (m) {\n                        var narrowSpace = state.opt[\"default-locale\"][0].slice(0, 2).toLowerCase() === \"fr\" ? \"\\u202f\" : \"\";\n                        splits[i] = narrowSpace + m[1];\n                    }\n                    if (splits[i].indexOf(\"-\") > -1 || splits[i].indexOf(\"—\") > -1) {\n                        splits[i] = \"—\";\n                    }\n                }\n                vals[title.title] = splits.join(\"\");\n                return vals[title.title];\n            } else {\n                return vals[title.title];\n            }\n        } else {\n            return \"\";\n        }\n    },\n\n    getSafeEscape: function(state) {\n        if ([\"bibliography\", \"citation\"].indexOf(state.tmp.area) > -1) {\n            // Callback to apply thin space hack\n            // Callback to force LTR/RTL on parens and braces\n            // XXX Is this really necessary?\n            var callbacks = [];\n            if (state.opt.development_extensions.thin_non_breaking_space_html_hack && state.opt.mode === \"html\") {\n                callbacks.push(function (txt) {\n                    return txt.replace(/\\u202f/g, '<span style=\"white-space:nowrap\">&thinsp;</span>');\n                });\n            }\n            if (callbacks.length) {\n                return function (txt) {\n                    for (var i = 0, ilen = callbacks.length; i < ilen; i += 1) {\n                        txt = callbacks[i](txt);\n                    }\n                    return CSL.Output.Formats[state.opt.mode].text_escape(txt);\n                };\n            } else {\n                return CSL.Output.Formats[state.opt.mode].text_escape;\n            }\n        } else {\n            return function (txt) { return txt; };\n        }\n    },\n\n    SKIP_WORDS: [\"about\",\"above\",\"across\",\"afore\",\"after\",\"against\",\"al\", \"along\",\"alongside\",\"amid\",\"amidst\",\"among\",\"amongst\",\"anenst\",\"apropos\",\"apud\",\"around\",\"as\",\"aside\",\"astride\",\"at\",\"athwart\",\"atop\",\"barring\",\"before\",\"behind\",\"below\",\"beneath\",\"beside\",\"besides\",\"between\",\"beyond\",\"but\",\"by\",\"circa\",\"despite\",\"down\",\"during\",\"et\", \"except\",\"for\",\"forenenst\",\"from\",\"given\",\"in\",\"inside\",\"into\",\"lest\",\"like\",\"modulo\",\"near\",\"next\",\"notwithstanding\",\"of\",\"off\",\"on\",\"onto\",\"out\",\"over\",\"per\",\"plus\",\"pro\",\"qua\",\"sans\",\"since\",\"than\",\"through\",\" thru\",\"throughout\",\"thruout\",\"till\",\"to\",\"toward\",\"towards\",\"under\",\"underneath\",\"until\",\"unto\",\"up\",\"upon\",\"versus\",\"vs.\",\"v.\",\"vs\",\"v\",\"via\",\"vis-à-vis\",\"with\",\"within\",\"without\",\"according to\",\"ahead of\",\"apart from\",\"as for\",\"as of\",\"as per\",\"as regards\",\"aside from\",\"back to\",\"because of\",\"close to\",\"due to\",\"except for\",\"far from\",\"inside of\",\"instead of\",\"near to\",\"next to\",\"on to\",\"out from\",\"out of\",\"outside of\",\"prior to\",\"pursuant to\",\"rather than\",\"regardless of\",\"such as\",\"that of\",\"up to\",\"where as\",\"or\", \"yet\", \"so\", \"for\", \"and\", \"nor\", \"a\", \"an\", \"the\", \"de\", \"d'\", \"von\", \"van\", \"c\", \"ca\"],\n\n    FORMAT_KEY_SEQUENCE: [\n        \"@strip-periods\",\n        \"@font-style\",\n        \"@font-variant\",\n        \"@font-weight\",\n        \"@text-decoration\",\n        \"@vertical-align\",\n        \"@quotes\"\n    ],\n\n    INSTITUTION_KEYS: [\n        \"font-style\",\n        \"font-variant\",\n        \"font-weight\",\n        \"text-decoration\",\n        \"text-case\"\n    ],\n\n    SUFFIX_CHARS: \"a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z\",\n    ROMAN_NUMERALS: [\n        [ \"\", \"i\", \"ii\", \"iii\", \"iv\", \"v\", \"vi\", \"vii\", \"viii\", \"ix\" ],\n        [ \"\", \"x\", \"xx\", \"xxx\", \"xl\", \"l\", \"lx\", \"lxx\", \"lxxx\", \"xc\" ],\n        [ \"\", \"c\", \"cc\", \"ccc\", \"cd\", \"d\", \"dc\", \"dcc\", \"dccc\", \"cm\" ],\n        [ \"\", \"m\", \"mm\", \"mmm\", \"mmmm\", \"mmmmm\"]\n    ],\n\n    LANGS: {\n        \"af-ZA\":\"Afrikaans\",\n        \"ar\":\"Arabic\",\n        \"bg-BG\":\"Bulgarian\",\n        \"ca-AD\":\"Catalan\",\n        \"cs-CZ\":\"Czech\",\n        \"da-DK\":\"Danish\",\n        \"de-AT\":\"Austrian\",\n        \"de-CH\":\"German (CH)\",\n        \"de-DE\":\"German (DE)\",\n        \"el-GR\":\"Greek\",\n        \"en-GB\":\"English (GB)\",\n        \"en-US\":\"English (US)\",\n        \"es-ES\":\"Spanish\",\n        \"et-EE\":\"Estonian\",\n        \"eu\":\"European\",\n        \"fa-IR\":\"Persian\",\n        \"fi-FI\":\"Finnish\",\n        \"fr-CA\":\"French (CA)\",\n        \"fr-FR\":\"French (FR)\",\n        \"he-IL\":\"Hebrew\",\n        \"hr-HR\":\"Croatian\",\n        \"hu-HU\":\"Hungarian\",\n        \"is-IS\":\"Icelandic\",\n        \"it-IT\":\"Italian\",\n        \"ja-JP\":\"Japanese\",\n        \"km-KH\":\"Khmer\",\n        \"ko-KR\":\"Korean\",\n        \"lt-LT\":\"Lithuanian\",\n        \"lv-LV\":\"Latvian\",\n        \"mn-MN\":\"Mongolian\",\n        \"nb-NO\":\"Norwegian (Bokmål)\",\n        \"nl-NL\":\"Dutch\",\n        \"nn-NO\":\"Norwegian (Nynorsk)\",\n        \"pl-PL\":\"Polish\",\n        \"pt-BR\":\"Portuguese (BR)\",\n        \"pt-PT\":\"Portuguese (PT)\",\n        \"ro-RO\":\"Romanian\",\n        \"ru-RU\":\"Russian\",\n        \"sk-SK\":\"Slovak\",\n        \"sl-SI\":\"Slovenian\",\n        \"sr-RS\":\"Serbian\",\n        \"sv-SE\":\"Swedish\",\n        \"th-TH\":\"Thai\",\n        \"tr-TR\":\"Turkish\",\n        \"uk-UA\":\"Ukrainian\",\n        \"vi-VN\":\"Vietnamese\",\n        \"zh-CN\":\"Chinese (CN)\",\n        \"zh-TW\":\"Chinese (TW)\"\n    },\n\n    LANG_BASES: {\n        af: \"af_ZA\",\n        ar: \"ar\",\n        bg: \"bg_BG\",\n        ca: \"ca_AD\",\n        cs: \"cs_CZ\",\n        da: \"da_DK\",\n        de: \"de_DE\",\n        el: \"el_GR\",\n        en: \"en_US\",\n        es: \"es_ES\",\n        et: \"et_EE\",\n        eu: \"eu\",\n        fa: \"fa_IR\",\n        fi: \"fi_FI\",\n        fr: \"fr_FR\",\n        he: \"he_IL\",\n        hr: \"hr-HR\",\n        hu: \"hu_HU\",\n        is: \"is_IS\",\n        it: \"it_IT\",\n        ja: \"ja_JP\",\n        km: \"km_KH\",\n        ko: \"ko_KR\",\n        lt: \"lt_LT\",\n        lv: \"lv-LV\",\n        mn: \"mn_MN\",\n        nb: \"nb_NO\",\n        nl: \"nl_NL\",\n        nn: \"nn-NO\",\n        pl: \"pl_PL\",\n        pt: \"pt_PT\",\n        ro: \"ro_RO\",\n        ru: \"ru_RU\",\n        sk: \"sk_SK\",\n        sl: \"sl_SI\",\n        sr: \"sr_RS\",\n        sv: \"sv_SE\",\n        th: \"th_TH\",\n        tr: \"tr_TR\",\n        uk: \"uk_UA\",\n        vi: \"vi_VN\",\n        zh: \"zh_CN\"\n    },\n\n    SUPERSCRIPTS: {\n        \"\\u00AA\": \"\\u0061\",\n        \"\\u00B2\": \"\\u0032\",\n        \"\\u00B3\": \"\\u0033\",\n        \"\\u00B9\": \"\\u0031\",\n        \"\\u00BA\": \"\\u006F\",\n        \"\\u02B0\": \"\\u0068\",\n        \"\\u02B1\": \"\\u0266\",\n        \"\\u02B2\": \"\\u006A\",\n        \"\\u02B3\": \"\\u0072\",\n        \"\\u02B4\": \"\\u0279\",\n        \"\\u02B5\": \"\\u027B\",\n        \"\\u02B6\": \"\\u0281\",\n        \"\\u02B7\": \"\\u0077\",\n        \"\\u02B8\": \"\\u0079\",\n        \"\\u02E0\": \"\\u0263\",\n        \"\\u02E1\": \"\\u006C\",\n        \"\\u02E2\": \"\\u0073\",\n        \"\\u02E3\": \"\\u0078\",\n        \"\\u02E4\": \"\\u0295\",\n        \"\\u1D2C\": \"\\u0041\",\n        \"\\u1D2D\": \"\\u00C6\",\n        \"\\u1D2E\": \"\\u0042\",\n        \"\\u1D30\": \"\\u0044\",\n        \"\\u1D31\": \"\\u0045\",\n        \"\\u1D32\": \"\\u018E\",\n        \"\\u1D33\": \"\\u0047\",\n        \"\\u1D34\": \"\\u0048\",\n        \"\\u1D35\": \"\\u0049\",\n        \"\\u1D36\": \"\\u004A\",\n        \"\\u1D37\": \"\\u004B\",\n        \"\\u1D38\": \"\\u004C\",\n        \"\\u1D39\": \"\\u004D\",\n        \"\\u1D3A\": \"\\u004E\",\n        \"\\u1D3C\": \"\\u004F\",\n        \"\\u1D3D\": \"\\u0222\",\n        \"\\u1D3E\": \"\\u0050\",\n        \"\\u1D3F\": \"\\u0052\",\n        \"\\u1D40\": \"\\u0054\",\n        \"\\u1D41\": \"\\u0055\",\n        \"\\u1D42\": \"\\u0057\",\n        \"\\u1D43\": \"\\u0061\",\n        \"\\u1D44\": \"\\u0250\",\n        \"\\u1D45\": \"\\u0251\",\n        \"\\u1D46\": \"\\u1D02\",\n        \"\\u1D47\": \"\\u0062\",\n        \"\\u1D48\": \"\\u0064\",\n        \"\\u1D49\": \"\\u0065\",\n        \"\\u1D4A\": \"\\u0259\",\n        \"\\u1D4B\": \"\\u025B\",\n        \"\\u1D4C\": \"\\u025C\",\n        \"\\u1D4D\": \"\\u0067\",\n        \"\\u1D4F\": \"\\u006B\",\n        \"\\u1D50\": \"\\u006D\",\n        \"\\u1D51\": \"\\u014B\",\n        \"\\u1D52\": \"\\u006F\",\n        \"\\u1D53\": \"\\u0254\",\n        \"\\u1D54\": \"\\u1D16\",\n        \"\\u1D55\": \"\\u1D17\",\n        \"\\u1D56\": \"\\u0070\",\n        \"\\u1D57\": \"\\u0074\",\n        \"\\u1D58\": \"\\u0075\",\n        \"\\u1D59\": \"\\u1D1D\",\n        \"\\u1D5A\": \"\\u026F\",\n        \"\\u1D5B\": \"\\u0076\",\n        \"\\u1D5C\": \"\\u1D25\",\n        \"\\u1D5D\": \"\\u03B2\",\n        \"\\u1D5E\": \"\\u03B3\",\n        \"\\u1D5F\": \"\\u03B4\",\n        \"\\u1D60\": \"\\u03C6\",\n        \"\\u1D61\": \"\\u03C7\",\n        \"\\u2070\": \"\\u0030\",\n        \"\\u2071\": \"\\u0069\",\n        \"\\u2074\": \"\\u0034\",\n        \"\\u2075\": \"\\u0035\",\n        \"\\u2076\": \"\\u0036\",\n        \"\\u2077\": \"\\u0037\",\n        \"\\u2078\": \"\\u0038\",\n        \"\\u2079\": \"\\u0039\",\n        \"\\u207A\": \"\\u002B\",\n        \"\\u207B\": \"\\u2212\",\n        \"\\u207C\": \"\\u003D\",\n        \"\\u207D\": \"\\u0028\",\n        \"\\u207E\": \"\\u0029\",\n        \"\\u207F\": \"\\u006E\",\n        \"\\u2120\": \"\\u0053\\u004D\",\n        \"\\u2122\": \"\\u0054\\u004D\",\n        \"\\u3192\": \"\\u4E00\",\n        \"\\u3193\": \"\\u4E8C\",\n        \"\\u3194\": \"\\u4E09\",\n        \"\\u3195\": \"\\u56DB\",\n        \"\\u3196\": \"\\u4E0A\",\n        \"\\u3197\": \"\\u4E2D\",\n        \"\\u3198\": \"\\u4E0B\",\n        \"\\u3199\": \"\\u7532\",\n        \"\\u319A\": \"\\u4E59\",\n        \"\\u319B\": \"\\u4E19\",\n        \"\\u319C\": \"\\u4E01\",\n        \"\\u319D\": \"\\u5929\",\n        \"\\u319E\": \"\\u5730\",\n        \"\\u319F\": \"\\u4EBA\",\n        \"\\u02C0\": \"\\u0294\",\n        \"\\u02C1\": \"\\u0295\",\n        \"\\u06E5\": \"\\u0648\",\n        \"\\u06E6\": \"\\u064A\"\n    },\n    SUPERSCRIPTS_REGEXP: new RegExp(\"[\\u00AA\\u00B2\\u00B3\\u00B9\\u00BA\\u02B0\\u02B1\\u02B2\\u02B3\\u02B4\\u02B5\\u02B6\\u02B7\\u02B8\\u02E0\\u02E1\\u02E2\\u02E3\\u02E4\\u1D2C\\u1D2D\\u1D2E\\u1D30\\u1D31\\u1D32\\u1D33\\u1D34\\u1D35\\u1D36\\u1D37\\u1D38\\u1D39\\u1D3A\\u1D3C\\u1D3D\\u1D3E\\u1D3F\\u1D40\\u1D41\\u1D42\\u1D43\\u1D44\\u1D45\\u1D46\\u1D47\\u1D48\\u1D49\\u1D4A\\u1D4B\\u1D4C\\u1D4D\\u1D4F\\u1D50\\u1D51\\u1D52\\u1D53\\u1D54\\u1D55\\u1D56\\u1D57\\u1D58\\u1D59\\u1D5A\\u1D5B\\u1D5C\\u1D5D\\u1D5E\\u1D5F\\u1D60\\u1D61\\u2070\\u2071\\u2074\\u2075\\u2076\\u2077\\u2078\\u2079\\u207A\\u207B\\u207C\\u207D\\u207E\\u207F\\u2120\\u2122\\u3192\\u3193\\u3194\\u3195\\u3196\\u3197\\u3198\\u3199\\u319A\\u319B\\u319C\\u319D\\u319E\\u319F\\u02C0\\u02C1\\u06E5\\u06E6]\", \"g\"),\n\n    // I think we need to have separate args for prefix and term,\n    // since they have different effects between comma-safe and comma-safe-numbers-only.\n    // Either that, or -- oh, we could just bang the two together for the test where\n    // necessary.\n    \n    UPDATE_GROUP_CONTEXT_CONDITION: function (state, str, valueTerm, token, value) {\n        if (!state.opt.use_context_condition) return;\n        var flags = state.tmp.group_context.tip;\n        if (flags.condition) {\n            if (!flags.condition.termtxt) {\n                flags.condition.termtxt = str;\n                flags.condition.valueTerm = valueTerm;\n            }\n            if (!flags.value_seen && flags.condition.test === \"comma-safe-numbers-only\") {\n                if (value) {\n                    flags.value_seen = true;\n                    if (!value.match(/^[0-9]/)) {\n                        state.tmp.just_did_number = false;\n                    }\n                }\n            }\n        } else {\n            // If not inside a conditional group, raise numeric flag\n            // if and only if the current term string ends in a number.\n            if (token && token.decorations.filter(o => o[0] === \"@vertical-align\").length > 0) {\n                state.tmp.just_did_number = false;\n            } else if (token && token.strings.suffix) {\n                state.tmp.just_did_number = false;\n            } else if (str) {\n                if (str.match(/[0-9]$/)) {\n                    state.tmp.just_did_number = true;\n                } else {\n                    state.tmp.just_did_number = false;\n                }\n            }\n        }\n    },\n\n    EVALUATE_GROUP_CONDITION: function(state, flags) {\n        if (!state.opt.use_context_condition) return;\n        var testres;\n        var numbersOnly = flags.condition.test === \"comma-safe-numbers-only\";\n        if (flags.condition.test === \"empty-label\") {\n            testres = !flags.condition.termtxt;\n        } else if (flags.condition.test === \"empty-label-no-decor\") {\n            testres = !flags.condition.termtxt || flags.condition.termtxt.indexOf(\"%s\") > -1;\n        } else if ([\"comma-safe\", \"comma-safe-numbers-only\"].indexOf(flags.condition.test) > -1) {\n            var locale_term = flags.condition.termtxt;\n            var termStartAlpha = false;\n            if (flags.condition.termtxt) {\n                termStartAlpha = flags.condition.termtxt.slice(0,1).match(CSL.ALL_ROMANESQUE_REGEXP);\n            }\n            var num = state.tmp.just_did_number;\n            if (num) {\n                if (flags.condition.valueTerm) {\n                    testres = numbersOnly ? false : true;\n                } else if (!locale_term) {\n                    testres = true;\n                } else if (termStartAlpha) {\n                    testres = numbersOnly ? false : true;\n                } else if ([\"always\", \"after-number\"].indexOf(state.opt.require_comma_on_symbol) > -1) {\n                    testres = true;\n                } else {\n                    testres = false;\n                }\n            } else {\n                if (flags.condition.valueTerm) {\n                    testres = false;\n                } else if (!locale_term) {\n                    testres = false;\n                } else if (termStartAlpha) {\n                    testres = numbersOnly ? false : true;\n                } else if (state.opt.require_comma_on_symbol === \"always\") {\n                    testres = true;\n                } else {\n                    testres = false;\n                }\n            }\n        }\n        if (testres) {\n            var force_suppress = false;\n        } else {\n            var force_suppress = true;\n        }\n        if (flags.condition.not) {\n            force_suppress = !force_suppress;\n        }\n        return force_suppress;\n    },\n    \n    SYS_OPTIONS: [\n        \"prioritize_disambiguate_condition\",\n        \"csl_reverse_lookup_support\",\n        \"main_title_from_short_title\",\n        \"uppercase_subtitles\",\n        \"force_short_title_casing_alignment\",\n        \"implicit_short_title\",\n        \"split_container_title\"\n    ],\n\n    TITLE_SPLIT_REGEXP: (function() {\n        var splits = [\n            \"\\\\.\\\\s+\",\n            \"\\\\!\\\\s+\",\n            \"\\\\?\\\\s+\",\n            \"\\\\s*::*\\\\s+\",\n            \"\\\\s*—\\\\s*\",\n            \"\\\\s+\\\\-\\\\s+\",\n            \"\\\\s*\\\\-\\\\-\\\\-*\\\\s*\"\n        ]\n        return {\n            match: new RegExp(\"(\" + splits.join(\"|\") + \")\", \"g\"),\n            matchfirst: new RegExp(\"^(\" + splits.join(\"|\") + \")\"),\n            split: new RegExp(\"(?:\" + splits.join(\"|\") + \")\")\n        }\n    })(),\n\n    TITLE_SPLIT: function(str) {\n        if (!str) {\n            return str;\n        }\n        var m = str.match(CSL.TITLE_SPLIT_REGEXP.match);\n        var lst = str.split(CSL.TITLE_SPLIT_REGEXP.split);\n        for (var i=lst.length-2; i>-1; i--) {\n            lst[i] = lst[i].trim();\n            if (lst[i] && lst[i].slice(-1).toLowerCase() !== lst[i].slice(-1)) {\n                // recombine\n                lst[i] = lst[i] + m[i] + lst[i+1];\n                lst = lst.slice(0, i+1).concat(lst.slice(i+2))\n            } else {\n                // merge\n                lst = lst.slice(0, i+1).concat([m[i]]).concat(lst.slice(i+1))\n            }\n        }\n        return lst;\n    },\n    \n    GET_COURT_CLASS: function(state, Item, sortKey){\n        // Get authority as a string\n        var cls = \"\";\n        var authority = null;\n        var country = Item.jurisdiction ? Item.jurisdiction.split(\":\")[0] : null;\n        // inStyle versus in module\n        var classType = \"court_condition_classes\";\n        if (sortKey) {\n            classType = \"court_key_classes\";\n        }\n        if (country && Item.authority) {\n            if (\"string\" === typeof Item.authority) {\n                authority = Item.authority;\n            } else {\n                if (Item.authority[0] && Item.authority[0].literal) {\n                    authority = Item.authority[0].literal;\n                }\n            }\n        }\n        if (authority) {\n            if (this.lang && state.locale[this.lang].opts[classType] && state.locale[this.lang].opts[classType][country] && state.locale[this.lang].opts[classType][country][authority]) {\n                cls = state.locale[this.lang].opts[classType][country][authority];\n            } else if (state.locale[state.opt[\"default-locale\"][0]].opts[classType] && state.locale[state.opt[\"default-locale\"][0]].opts[classType][country] && state.locale[state.opt[\"default-locale\"][0]].opts[classType][country][authority]) {\n                cls = state.locale[state.opt[\"default-locale\"][0]].opts[classType][country][authority]\n            }\n        }\n        return cls;\n    },\n\n    SET_COURT_CLASSES: function(state, lang, myxml, dataObj) {\n        var nodes = myxml.getNodesByName(dataObj, 'court-class');\n        for (var pos = 0, len = myxml.numberofnodes(nodes); pos < len; pos += 1) {\n            var courtclass = nodes[pos];\n            var attributes = myxml.attributes(courtclass);\n            var cls = attributes[\"@name\"];\n            var country = attributes[\"@country\"];\n            var courts = attributes[\"@courts\"];\n            \n            // Okay, this is a hack.\n            // If state.registry IS NOT yet defined, this is an in-style declaration.\n            // If state.registry IS defined, this is an in-module declaration.\n            var classType = \"court_key_classes\";\n            if (state.registry) {\n                classType = \"court_condition_classes\";\n            }\n            \n            if (cls && country && courts) {\n                courts = courts.trim().split(/\\s+/);\n                if (!state.locale[lang].opts[classType]) {\n                    state.locale[lang].opts[classType] = {};\n                }\n                if (!state.locale[lang].opts[classType][country]) {\n                    state.locale[lang].opts[classType][country] = {};\n                }\n                for (var i=0,ilen=courts.length;i<ilen;i++) {\n                    state.locale[lang].opts[classType][country][courts[i]] = cls;\n                }\n            }\n        }\n    },\n\n    INIT_JURISDICTION_MACROS: function (state, Item, item, macroName) {\n        if (Item[\"best-jurisdiction\"]) {\n            return true;\n        }\n        if (!state.sys.retrieveStyleModule || !CSL.MODULE_MACROS[macroName] || !Item.jurisdiction) {\n            return false;\n        }\n        var jurisdictionList = state.getJurisdictionList(Item.jurisdiction);\n        // Set up a list of jurisdictions here, we will reuse it\n        if (!state.opt.jurisdictions_seen[jurisdictionList[0]]) {\n            var res = state.retrieveAllStyleModules(jurisdictionList);\n            // Okay. We have code for each of the novel modules in the\n            // hierarchy. Load them all into the processor.\n            for (var jurisdiction in res) {\n                var fallback = state.loadStyleModule(jurisdiction, res[jurisdiction]);\n                if (fallback) {\n                    if (!res[fallback]) {\n                        Object.assign(res, state.retrieveAllStyleModules([fallback]));\n                        state.loadStyleModule(fallback, res[fallback], true);\n                    }\n                }\n            }\n        }\n        var jurisdictionList = state.getJurisdictionList(Item.jurisdiction);\n        if (state.opt.parallel.enable) {\n            if (!state.parallel) {\n                state.parallel = new CSL.Parallel(state);\n            }\n        }\n        // Identify the best jurisdiction for the item and return true, otherwise return false\n        for (var i=0,ilen=jurisdictionList.length;i<ilen;i++) {\n            var jurisdiction = jurisdictionList[i];\n            if (item) {\n                if (state.juris[jurisdiction] && !item[\"best-jurisdiction\"] && state.juris[jurisdiction].types.locator) {\n                    Item[\"best-jurisdiction\"] = jurisdiction;\n                }\n            }\n            if(state.juris[jurisdiction] && state.juris[jurisdiction].types[Item.type]) {\n                Item[\"best-jurisdiction\"] = jurisdiction;\n                return true;\n            }\n        }\n        return false;\n    }\n};\n\n/**\n * Functions for parsing an XML object converted to JSON.\n */\n\n/*\n  Style and locale JSON should be formatted as follows. Note that\n  an empty literal should be set as an explicit empty strings within\n  children:[]\n  \n  {\n    name:\"term\",\n    children:[\n      \"\"\n    ],\n    attrs:{\n      name:\"author\"\n    }\n  }\n\n  The following script will generate correctly formatted JSON\n  from a CSL style or locale file:\n*/\n\nCSL.XmlJSON = function (dataObj) {\n    this.dataObj = dataObj;\n    this.institution = {\n        name:\"institution\",\n        attrs:{\n            \"institution-parts\":\"long\",\n            \"delimiter\":\", \"\n        },\n        children:[\n            {\n                name:\"institution-part\",\n                attrs:{\n                    name:\"long\"\n                },\n                children:[]\n            }\n        ]\n    };\n};\n\n/**\n * No need for cleaning with native JSON.\n */\nCSL.XmlJSON.prototype.clean = function (json) {\n    return json;\n};\n\n\n/**\n * Methods to call on a node.\n */\nCSL.XmlJSON.prototype.getStyleId = function (myjson, styleName) {\n    var tagName = 'id';\n    if (styleName) {\n        tagName = 'title';\n    }\n    var ret = \"\";\n    var children = myjson.children;\n    for (var i=0,ilen=children.length;i<ilen;i++) {\n        if (children[i].name === 'info') {\n            var grandkids = children[i].children;\n            for (var j=0,jlen=grandkids.length;j<jlen;j++) {\n                if (grandkids[j].name === tagName) {\n                    ret = grandkids[j].children[0];\n                }\n            }\n        }\n    }\n    return ret;\n};\n\nCSL.XmlJSON.prototype.children = function (myjson) {\n    //print(\"children()\");\n    if (myjson && myjson.children.length) {\n        return myjson.children.slice();\n    } else {\n        return false;\n    }\n};\n\nCSL.XmlJSON.prototype.nodename = function (myjson) {\n    //print(\"nodename()\");\n    return myjson ? myjson.name : null;\n};\n\nCSL.XmlJSON.prototype.attributes = function (myjson) {\n    //print(\"attributes()\");\n    var ret = {};\n    for (var attrname in myjson.attrs) {\n        ret[\"@\"+attrname] = myjson.attrs[attrname];\n    }\n    return ret;\n};\n\n\nCSL.XmlJSON.prototype.content = function (myjson) {\n    //print(\"content()\");\n    // xmldom.js and xmle4x.js have \"undefined\" as default\n    var ret = \"\";\n    // This only catches content at first level, but that is good enough\n    // for us.\n    if (!myjson || !myjson.children) {\n        return ret;\n    }\n    for (var i=0, ilen=myjson.children.length; i < ilen; i += 1) {\n        if (\"string\" === typeof myjson.children[i]) {\n            ret += myjson.children[i];\n        }\n    }\n    return ret;\n};\n\n\nCSL.XmlJSON.prototype.namespace = {}\n\nCSL.XmlJSON.prototype.numberofnodes = function (myjson) {\n    //print(\"numberofnodes()\");\n    if (myjson && \"number\" == typeof myjson.length) {\n        return myjson.length;\n    } else {\n        return 0;\n    }\n};\n\n// getAttributeName() removed. Looks like it was not being used.\n\nCSL.XmlJSON.prototype.getAttributeValue = function (myjson,name,namespace) {\n    //print(\"getAttributeValue()\");\n    var ret = \"\";\n    if (namespace) {\n        name = namespace+\":\"+name;\n    }\n    if (myjson) {\n        if (myjson.attrs) {\n            if (myjson.attrs[name]) {\n                ret = myjson.attrs[name];\n            } else {\n                ret = \"\";\n            }\n        }\n    }\n    return ret;\n}\n\nCSL.XmlJSON.prototype.getNodeValue = function (myjson,name) {\n    //print(\"getNodeValue()\");\n    var ret = \"\";\n    if (name){\n        for (var i=0, ilen=myjson.children.length; i < ilen; i += 1) {\n            if (myjson.children[i].name === name) {\n                // This will always be Object() unless empty\n                if (myjson.children[i].children.length) {\n                    ret = myjson.children[i];\n                } else {\n                    ret = \"\";\n                }\n            }\n        }\n    } else if (myjson) {\n        ret = myjson;\n    }\n    // Just being careful here, following the former DOM code. The JSON object we receive \n    // for this should be fully normalized.\n    if (ret && ret.children && ret.children.length == 1 && \"string\" === typeof ret.children[0]) {\n        ret = ret.children[0];\n    }\n    return ret;\n}\n\nCSL.XmlJSON.prototype.setAttributeOnNodeIdentifiedByNameAttribute = function (myjson,nodename,partname,attrname,val) {\n    //print(\"setAttributeOnNodeIdentifiedByNameAttribute()\");\n    var pos, len, xml, nodes, node;\n    if (attrname.slice(0,1) === '@'){\n        attrname = attrname.slice(1);\n    }\n    // In the one place this is used in citeproc-js code, it doesn't need to recurse.\n    for (var i=0,ilen=myjson.children.length; i<ilen; i += 1) {\n        if (myjson.children[i].name === nodename && myjson.children[i].attrs.name === partname) {\n            myjson.children[i].attrs[attrname] = val;\n        }\n    }\n}\n\nCSL.XmlJSON.prototype.deleteNodeByNameAttribute = function (myjson,val) {\n    //print(\"deleteNodeByNameAttribute()\");\n    var i, ilen;\n    for (i = 0, ilen = myjson.children.length; i < ilen; i += 1) {\n        if (!myjson.children[i] || \"string\" === typeof myjson.children[i]) {\n            continue;\n        }\n        if (myjson.children[i].attrs.name == val) {\n            myjson.children = myjson.children.slice(0,i).concat(myjson.children.slice(i+1));\n        }\n    }\n}\n\nCSL.XmlJSON.prototype.deleteAttribute = function (myjson,attrname) {\n    //print(\"deleteAttribute()\");\n    var i, ilen;\n    if (\"undefined\" !== typeof myjson.attrs[attrname]) {\n        myjson.attrs.pop(attrname);\n    }\n}\n\nCSL.XmlJSON.prototype.setAttribute = function (myjson,attr,val) {\n    //print(\"setAttribute()\");\n    myjson.attrs[attr] = val;\n    return false;\n}\n\nCSL.XmlJSON.prototype.nodeCopy = function (myjson,clone) {\n    //print(\"nodeCopy()\");\n    if (!clone) {\n        var clone = {};\n    }\n    if (\"object\" === typeof clone && \"undefined\" === typeof clone.length) {\n        // myjson is an object\n        for (var key in myjson) {\n            if (\"string\" === typeof myjson[key]) {\n                clone[key] = myjson[key];\n            } else if (\"object\" === typeof myjson[key]) {\n                if (\"undefined\" === typeof myjson[key].length) {\n                    clone[key] = this.nodeCopy(myjson[key],{});\n                } else {\n                    clone[key] = this.nodeCopy(myjson[key],[]);\n                }\n            }\n        }\n    } else {\n        // myjson is an array\n        for (var i=0,ilen=myjson.length;i<ilen; i += 1) {\n            if (\"string\" === typeof myjson[i]) {\n                clone[i] = myjson[i];\n            } else {\n                // If it's at the first level of an array, it's an object.\n                clone[i] = this.nodeCopy(myjson[i],{});\n            }\n        }\n    }\n    return clone;\n}\n\nCSL.XmlJSON.prototype.getNodesByName = function (myjson,name,nameattrval,ret) {\n    //print(\"getNodesByName()\");\n    var nodes, node, pos, len;\n    if (!ret) {\n        var ret = [];\n    }\n    if (!myjson || !myjson.children) {\n        return ret;\n    }\n    if (name === myjson.name) {\n        if (nameattrval) {\n            if (nameattrval === myjson.attrs.name) {\n                ret.push(myjson);\n            }\n        } else {\n            ret.push(myjson);\n        }\n    }\n    for (var i=0,ilen=myjson.children.length;i<ilen;i+=1){\n        if (\"object\" !== typeof myjson.children[i]) {\n            continue;\n        }\n        this.getNodesByName(myjson.children[i],name,nameattrval,ret);\n    }\n    return ret;\n}\n\nCSL.XmlJSON.prototype.nodeNameIs = function (myjson,name) {\n    //print(\"nodeNameIs()\");\n    if (typeof myjson === \"undefined\") {\n        return false;\n    }\n    if (name == myjson.name) {\n        return true;\n    }\n    return false;\n}\n\nCSL.XmlJSON.prototype.makeXml = function (myjson) {\n    //print(\"makeXml()\");\n    if (\"string\" === typeof myjson) {\n        if (myjson.slice(0, 1) === \"<\") {\n            myjson = this.jsonStringWalker.walkToObject(myjson);\n        } else {\n            myjson = JSON.parse(myjson);\n        }\n    }\n    return myjson;\n};\n\nCSL.XmlJSON.prototype.insertChildNodeAfter = function (parent,node,pos,datejson) {\n    //print(\"insertChildNodeAfter()\");\n    // Function is misnamed: this replaces the node\n    for (var i=0,ilen=parent.children.length;i<ilen;i+=1) {\n        if (node === parent.children[i]) {\n            parent.children = parent.children.slice(0,i).concat([datejson]).concat(parent.children.slice(i+1));\n            break;\n        }\n    }\n    return parent;\n};\n\n\nCSL.XmlJSON.prototype.insertPublisherAndPlace = function(myjson) {\n    if (myjson.name === \"group\") {\n        var useme = true;\n        var mustHaves = [\"publisher\",\"publisher-place\"];\n        for (var i=0,ilen=myjson.children.length;i<ilen;i+=1) {\n            var haveVarname = mustHaves.indexOf(myjson.children[i].attrs.variable);\n            var isText = myjson.children[i].name === \"text\";\n            if (isText && haveVarname > -1 && !myjson.children[i].attrs.prefix && !myjson.children[i].attrs.suffix) {\n                mustHaves = mustHaves.slice(0,haveVarname).concat(mustHaves.slice(haveVarname+1));\n            } else {\n                useme = false;\n                break;\n            }\n        }\n        if (useme && !mustHaves.length) {\n            myjson.attrs[\"has-publisher-and-publisher-place\"] = true;\n       }\n    }\n    for (var i=0,ilen=myjson.children.length;i<ilen;i+=1) {\n        if (\"object\" === typeof myjson.children[i]) {\n            this.insertPublisherAndPlace(myjson.children[i]);\n        }\n    }    \n}\n/*\nCSL.XmlJSON.prototype.insertPublisherAndPlace = function(myxml) {\n    var group = myxml.getElementsByTagName(\"group\");\n    for (var i = 0, ilen = group.length; i < ilen; i += 1) {\n        var node = group.item(i);\n        var skippers = [];\n        for (var j = 0, jlen = node.childNodes.length; j < jlen; j += 1) {\n            if (node.childNodes.item(j).nodeType !== 1) {\n                skippers.push(j);\n            }\n        }\n        if (node.childNodes.length - skippers.length === 2) {\n            var twovars = [];\n            for (var j = 0, jlen = 2; j < jlen; j += 1) {\n                if (skippers.indexOf(j) > -1) {\n                    continue;\n                }\n                var child = node.childNodes.item(j);                    \n                var subskippers = [];\n                for (var k = 0, klen = child.childNodes.length; k < klen; k += 1) {\n                    if (child.childNodes.item(k).nodeType !== 1) {\n                        subskippers.push(k);\n                    }\n                }\n                if (child.childNodes.length - subskippers.length === 0) {\n                    twovars.push(child.getAttribute('variable'));\n                    if (child.getAttribute('suffix')\n                        || child.getAttribute('prefix')) {\n                        twovars = [];\n                        break;\n                    }\n                }\n            }\n            if (twovars.indexOf(\"publisher\") > -1 && twovars.indexOf(\"publisher-place\") > -1) {\n                node.setAttribute('has-publisher-and-publisher-place', true);\n            }\n        }\n    }\n};\n*/\n\nCSL.XmlJSON.prototype.isChildOfSubstitute = function(parents) {\n    if (parents.length > 0) {\n        var myparents = parents.slice();\n        var parent = myparents.pop();\n        if (parent === \"substitute\") {\n            return true;\n        } else {\n            return this.isChildOfSubstitute(myparents);\n        }\n    }\n    return false;\n};\n\nCSL.XmlJSON.prototype.addMissingNameNodes = function(myjson,parents) {\n    if (!parents) {\n        parents = [];\n    }\n    if (myjson.name === \"names\") {\n        // Trawl through children to decide whether a name node is needed here\n        if (!this.isChildOfSubstitute(parents)) {\n            var addName = true;\n            for (var i=0,ilen=myjson.children.length;i<ilen;i++) {\n                if (myjson.children[i].name === \"name\") {\n                    addName = false;\n                    break;\n                }\n            }\n            if (addName) {\n                myjson.children = [{name:\"name\",attrs:{},children:[]}].concat(myjson.children);\n            }\n        }\n    }\n    parents.push(myjson.name);\n    for (var i=0,ilen=myjson.children.length;i<ilen;i+=1) {\n        if (\"object\" === typeof myjson.children[i]) {\n            this.addMissingNameNodes(myjson.children[i],parents);\n        }\n    }\n    parents.pop();\n}\n\n\nCSL.XmlJSON.prototype.addInstitutionNodes = function(myjson) {\n    //print(\"addInstitutionNodes()\");\n    var names, thenames, institution, theinstitution, name, thename, xml, pos, len;\n    // The idea here is to map relevant attributes from name and nampart=family\n    // to the \"long\" institution-part node, when and only when forcing insert\n    // of the default node.\n    if (myjson.name === \"names\") {\n        // do stuff\n        var attributes = {};\n        var insertPos = -1;\n        for (var i=0,ilen=myjson.children.length;i<ilen;i+=1) {\n            if (myjson.children[i].name == \"name\") {\n                for (var key in myjson.children[i].attrs) {\n                    attributes[key] = myjson.children[i].attrs[key];\n                }\n                attributes.delimiter = myjson.children[i].attrs.delimiter;\n                attributes.and = myjson.children[i].attrs.and;\n                insertPos = i;\n                for (var k=0,klen=myjson.children[i].children.length;k<klen;k+=1) {\n                    if (myjson.children[i].children[k].attrs.name !== 'family') {\n                        continue;\n                    }\n                    for (var key in myjson.children[i].children[k].attrs) {\n                        attributes[key] = myjson.children[i].children[k].attrs[key];\n                    }\n                }\n            }\n            if (myjson.children[i].name == \"institution\") {\n                insertPos = -1;\n                break;\n            }\n        }\n        if (insertPos > -1) {\n            var institution = this.nodeCopy(this.institution);\n            for (var i=0,ilen = CSL.INSTITUTION_KEYS.length;i<ilen;i+=1) {\n                var attrname = CSL.INSTITUTION_KEYS[i];\n                if (\"undefined\" !== typeof attributes[attrname]) {\n                    institution.children[0].attrs[attrname] = attributes[attrname];\n                }\n                if (attributes.delimiter) {\n                    institution.attrs.delimiter = attributes.delimiter;\n                }\n                if (attributes.and) {\n                    institution.attrs.and = attributes.and;\n                }\n            }\n            myjson.children = myjson.children.slice(0,insertPos+1).concat([institution]).concat(myjson.children.slice(insertPos+1));\n        }\n    }\n    for (var i=0,ilen=myjson.children.length;i<ilen;i+=1) {\n        if (\"string\" === typeof myjson.children[i]) {\n            continue;\n        }\n        // Recurse\n        this.addInstitutionNodes(myjson.children[i]);\n    }\n}\nCSL.XmlJSON.prototype.flagDateMacros = function(myjson) {\n    // print(\"flagDateMacros()\");\n    for (var i=0,ilen=myjson.children.length;i<ilen;i+=1) {\n        if (myjson.children[i].name === \"macro\") {\n            if (this.inspectDateMacros(myjson.children[i])) {\n                myjson.children[i].attrs[\"macro-has-date\"] = \"true\";\n            }\n        }\n    }\n}\nCSL.XmlJSON.prototype.inspectDateMacros = function(myjson) {\n    //print(\"inspectDateMacros()\");\n    if (!myjson || !myjson.children) {\n        return false;\n    }\n    if (myjson.name === \"date\") {\n        return true;\n    } else {\n        for (var i=0,ilen=myjson.children.length;i<ilen;i+=1) {\n            if (this.inspectDateMacros(myjson.children[i])) {\n                return true;\n            }\n        }\n    }\n    return false;\n}\n\n/*\n * Clean serialized XML\n */\nCSL.stripXmlProcessingInstruction = function (xml) {\n    if (!xml) {\n        return xml;\n    }\n    xml = xml.replace(/^<\\?[^?]+\\?>/, \"\");\n    xml = xml.replace(/<!--[^>]+-->/g, \"\");\n    xml = xml.replace(/^\\s+/g, \"\");\n    xml = xml.replace(/\\s+$/g, \"\");\n    return xml;\n};\n\n\n/*\n * String parser for XML inputs\n */\nCSL.parseXml = function(str) {\n\n    var _pos = 0;\n    var _obj = {children:[]};\n    var _stack = [_obj.children];\n\n    function _listifyString(str) {\n        str = str.split(/(?:\\r\\n|\\n|\\r)/).join(\" \").replace(/>[\t ]+</g, \"><\").replace(/<\\!--.*?-->/g, \"\");\n        var lst = str.split(\"><\");\n        var stylePos = null;\n        for (var i=0,ilen=lst.length;i<ilen;i++) {\n            if (i > 0) {\n                lst[i] = \"<\" + lst[i];\n            }\n            if (i < (lst.length-1)) {\n                lst[i] = lst[i] + \">\";\n            }\n            if (\"number\" != typeof stylePos) {\n                if (lst[i].slice(0, 7) === \"<style \" || lst[i].slice(0, 8) == \"<locale \") {\n                    stylePos = i;\n                }\n            }\n        }\n        lst = lst.slice(stylePos);\n        // Combine open/close elements for empty terms,\n        // so that they will be passed through correctly\n        // as empty strings.\n        for (var i=lst.length-2;i>-1;i--) {\n            if (lst[i].slice(1).indexOf(\"<\") === -1) {\n                var stub = lst[i].slice(0, 5);\n                if (lst[i].slice(-2) !== \"/>\") {\n                    if (stub === \"<term\") {\n                        if (lst[i+1].slice(0, 6) === \"</term\") {\n                            lst[i] = lst[i] + lst[i+1];\n                            lst = lst.slice(0, i+1).concat(lst.slice(i+2));\n                        }\n                    } else if ([\"<sing\", \"<mult\"].indexOf(stub) > -1) {\n                        if (lst[i].slice(-2) !== \"/>\" && lst[i+1].slice(0, 1) === \"<\") {\n                            lst[i] = lst[i] + lst[i+1];\n                            lst = lst.slice(0, i+1).concat(lst.slice(i+2));\n                        }\n                    }\n                }\n            }\n        }\n        return lst;\n    }\n\n    function _decodeHtmlEntities(str) {\n        return str\n            .split(\"&amp;\").join(\"&\")\n            .split(\"&quot;\").join(\"\\\"\")\n            .split(\"&gt;\").join(\">\").split(\"&lt;\").join(\"<\")\n            .replace(/&#([0-9]{1,6});/gi, function(match, numStr) {\n                var num = parseInt(numStr, 10); // read num as normal number\n                return String.fromCharCode(num);\n            })\n            .replace(/&#x([a-f0-9]{1,6});/gi, function(match, numStr){\n                var num = parseInt(numStr, 16); // read num as hex\n                return String.fromCharCode(num);\n            });\n    }\n\n    function _getAttributes(elem) {\n        var m = elem.match(/([^\\'\\\"=\t ]+)=(?:\\\"[^\\\"]*\\\"|\\'[^\\']*\\')/g);\n        if (m) {\n            for (var i=0,ilen=m.length;i<ilen;i++) {\n                m[i] = m[i].replace(/=.*/, \"\");\n            }\n        }\n        return m;\n    }\n\n    function _getAttribute(elem, attr) {\n        var rex = RegExp('^.*[\t ]+' + attr + '=(\\\"(?:[^\\\"]*)\\\"|\\'(?:[^\\']*)\\').*$');\n        var m = elem.match(rex);\n        return m ? m[1].slice(1, -1) : null;\n    }\n\n    function _getTagName(elem) {\n        var rex = RegExp(\"^<([^\t />]+)\");\n        var m = elem.match(rex);\n        return m ? m[1] : null;\n    }\n    \n\n    function _castObjectFromOpeningTag(elem) {\n        var obj = {};\n        obj.name = _getTagName(elem);\n        obj.attrs = {};\n        var attributes = _getAttributes(elem);\n        if (attributes) {\n            for (var i=0,ilen=attributes.length;i<ilen;i++) {\n                var attr = {\n                    name: attributes[i],\n                    value: _getAttribute(elem, attributes[i])\n                }\n                obj.attrs[attr.name] = _decodeHtmlEntities(attr.value);\n            }\n        }\n        obj.children = [];\n        return obj;\n    }\n\n    function _extractTextFromCompositeElement(elem) {\n        var m = elem.match(/^.*>([^<]*)<.*$/);\n        return _decodeHtmlEntities(m[1]);\n    }\n\n    function _appendToChildren(obj) {\n        _stack.slice(-1)[0].push(obj);\n    }\n\n    function _extendStackWithNewChildren(obj) {\n        _stack.push(obj.children);\n    }\n\n    function processElement(elem) {\n        var obj;\n        if (elem.slice(1).indexOf('<') > -1) {\n            // withtext\n            var tag = elem.slice(0, elem.indexOf('>')+1);\n            obj = _castObjectFromOpeningTag(tag);\n            obj.children = [_extractTextFromCompositeElement(elem)];\n            _appendToChildren(obj);\n        } else if (elem.slice(-2) === '/>') {\n            // singleton\n            obj = _castObjectFromOpeningTag(elem);\n            // Empty term as singleton\n            if (_getTagName(elem) === 'term') {\n                obj.children.push('');\n            }\n            _appendToChildren(obj);\n        } else if (elem.slice(0, 2) === '</') {\n            // close\n            _stack.pop();\n        } else {\n            // open\n            obj = _castObjectFromOpeningTag(elem);\n            _appendToChildren(obj)\n            _extendStackWithNewChildren(obj);\n        }\n    }\n\n    var lst = _listifyString(str);\n\n    for (var i=0,ilen=lst.length;i<ilen;i++) {\n        var elem = lst[i];\n        processElement(elem);\n    }\n    return _obj.children[0];\n}\n\n/**\n * Functions for parsing an XML object using E4X.\n */\n\nCSL.XmlDOM = function (dataObj) {\n    this.dataObj = dataObj;\n    if (\"undefined\" == typeof DOMParser) {\n        DOMParser = function() {};\n        DOMParser.prototype.parseFromString = function(str, contentType) {\n            if (\"undefined\" != typeof ActiveXObject) {\n                var xmldata = new ActiveXObject('MSXML.DomDocument');\n                xmldata.async = false;\n                xmldata.loadXML(str);\n                return xmldata;\n            } else if (\"undefined\" != typeof XMLHttpRequest) {\n                var xmldata = new XMLHttpRequest;\n                if (!contentType) {\n                    contentType = 'text/xml';\n                }\n                xmldata.open('GET', 'data:' + contentType + ';charset=utf-8,' + encodeURIComponent(str), false);\n                if(xmldata.overrideMimeType) {\n                    xmldata.overrideMimeType(contentType);\n                }\n                xmldata.send(null);\n                return xmldata.responseXML;\n            } else if (\"undefined\" != typeof marknote) {\n                var parser = new marknote.Parser();\n                return parser.parse(str);\n            }\n        };\n        this.hasAttributes = function (node) {\n            var ret;\n            if (node.attributes && node.attributes.length) {\n                ret = true;\n            } else {\n                ret = false;\n            }\n            return ret;\n        };\n    } else {\n        /*\n        this.hasAttributes = function (node) {\n            return node[\"hasAttributes\"]();\n        };\n        */\n        this.hasAttributes = function (node) {\n            var ret;\n            if (node.attributes && node.attributes.length) {\n                ret = true;\n            } else {\n                ret = false;\n            }\n            return ret;\n        };\n    }\n    this.importNode = function (doc, srcElement) {\n        var ret;\n        if (\"undefined\" == typeof doc.importNode) {\n            ret = this._importNode(doc, srcElement, true);\n        } else {\n            ret = doc.importNode(srcElement, true);\n        }\n        return ret;\n    };\n    // In case importNode is not available.\n    // Thx + hat tip to Anthony T. Holdener III\n    // http://www.alistapart.com/articles/crossbrowserscripting\n    // cases 3, 4, 8 = text, cdata, comment\n    this._importNode = function(doc, node, allChildren) {\n        switch (node.nodeType) {\n            // element node\n            case 1:\n                var newNode = doc.createElement(node.nodeName);\n                if (node.attributes && node.attributes.length > 0)\n                    for (var i = 0, il = node.attributes.length; i < il;)\n                        newNode.setAttribute(node.attributes[i].nodeName, node.getAttribute(node.attributes[i++].nodeName));\n                    if (allChildren && node.childNodes && node.childNodes.length > 0)\n                        for (var i = 0, il = node.childNodes.length; i < il;)\n                            newNode.appendChild(this._importNode(doc, node.childNodes[i++], allChildren));\n                return newNode;\n                break;\n            case 3:\n            case 4:\n            case 8:\n                // Drop comments on the floor as well.\n                //return doc.createTextNode(node.nodeValue);\n                //break;\n        }\n    };\n    this.parser = new DOMParser();\n\n    // This seems horribly tormented, but there might be a reason for it.\n    // Perhaps this was the only way I found to get namespacing to work ... ?\n    var str = \"<docco><institution institution-parts=\\\"long\\\" delimiter=\\\", \\\" substitute-use-first=\\\"1\\\" use-last=\\\"1\\\"><institution-part name=\\\"long\\\"/></institution></docco>\";\n    var inst_doc = this.parser.parseFromString(str, \"text/xml\");\n    var inst_node = inst_doc.getElementsByTagName(\"institution\");\n    this.institution = inst_node.item(0);\n    var inst_part_node = inst_doc.getElementsByTagName(\"institution-part\");\n    this.institutionpart = inst_part_node.item(0);\n    this.ns = \"http://purl.org/net/xbiblio/csl\";\n};\n\n/**\n * No need for cleaning with the DOM, I think.  This will probably just be a noop.\n * But first, let's get XML mode switching up and running.\n */\nCSL.XmlDOM.prototype.clean = function (xml) {\n    xml = xml.replace(/<\\?[^?]+\\?>/g, \"\");\n    xml = xml.replace(/<![^>]+>/g, \"\");\n    xml = xml.replace(/^\\s+/, \"\");\n    xml = xml.replace(/\\s+$/, \"\");\n    xml = xml.replace(/^\\n*/, \"\");\n    return xml;\n};\n\n\n/**\n * Methods to call on a node.\n */\nCSL.XmlDOM.prototype.getStyleId = function (myxml, styleName) {\n    var text = \"\";\n    var tagName = \"id\";\n    if (styleName) {\n        tagName = \"title\";\n    }\n    var node = myxml.getElementsByTagName(tagName);\n    if (node && node.length) {\n        node = node.item(0);\n    }\n    if (node) {\n        // W3C conformant browsers\n        text = node.textContent;\n    }\n    if (!text) {\n        // Opera, IE 6 & 7\n        text = node.innerText;\n    }\n    if (!text) {\n        // Safari\n        text = node.innerHTML;\n    }\n    return text;\n};\n\nCSL.XmlDOM.prototype.children = function (myxml) {\n    var children, pos, len, ret;\n    if (myxml) {\n        ret = [];\n        children = myxml.childNodes;\n        for (pos = 0, len = children.length; pos < len; pos += 1) {\n            if (children[pos].nodeName != \"#text\") {\n                ret.push(children[pos]);\n            }\n        }\n        return ret;\n    } else {\n        return [];\n    }\n};\n\nCSL.XmlDOM.prototype.nodename = function (myxml) {\n    var ret = myxml.nodeName;\n    return ret;\n};\n\nCSL.XmlDOM.prototype.attributes = function (myxml) {\n    var ret, attrs, attr, key, xml, pos, len;\n    ret = new Object();\n    if (myxml && this.hasAttributes(myxml)) {\n        attrs = myxml.attributes;\n        for (pos = 0, len=attrs.length; pos < len; pos += 1) {\n            attr = attrs[pos];\n            ret[\"@\" + attr.name] = attr.value;\n        }\n    }\n    return ret;\n};\n\n\nCSL.XmlDOM.prototype.content = function (myxml) {\n    var ret;\n    if (\"undefined\" != typeof myxml.textContent) {\n        ret = myxml.textContent;\n    } else if (\"undefined\" != typeof myxml.innerText) {\n        ret = myxml.innerText;\n    } else {\n        ret = myxml.txt;\n    }\n    return ret;\n};\n\n\nCSL.XmlDOM.prototype.namespace = {\n    \"xml\":\"http://www.w3.org/XML/1998/namespace\"\n}\n\nCSL.XmlDOM.prototype.numberofnodes = function (myxml) {\n    if (myxml) {\n        return myxml.length;\n    } else {\n        return 0;\n    }\n};\n\nCSL.XmlDOM.prototype.getAttributeName = function (attr) {\n    var ret = attr.name;\n    return ret;\n}\n\nCSL.XmlDOM.prototype.getAttributeValue = function (myxml,name,namespace) {\n    var ret = \"\";\n    if (namespace) {\n        name = namespace+\":\"+name;\n    }\n    if (myxml && this.hasAttributes(myxml) && myxml.getAttribute(name)) {\n        ret = myxml.getAttribute(name);\n    }\n    return ret;\n}\n\n//\n// Can't this be, you know ... simplified?\n//\nCSL.XmlDOM.prototype.getNodeValue = function (myxml,name) {\n    var ret = null;\n    if (name){\n        var vals = myxml.getElementsByTagName(name);\n        if (vals.length > 0) {\n            if (\"undefined\" != typeof vals[0].textContent) {\n                ret = vals[0].textContent;\n            } else if (\"undefined\" != typeof vals[0].innerText) {\n                ret = vals[0].innerText;\n            } else {\n                ret = vals[0].text;\n            }\n        }\n    }\n    if (ret === null && myxml && myxml.childNodes && (myxml.childNodes.length == 0 || (myxml.childNodes.length == 1 && myxml.firstChild.nodeName == \"#text\"))) {\n        if (\"undefined\" != typeof myxml.textContent) {\n            ret = myxml.textContent;\n        } else if (\"undefined\" != typeof myxml.innerText) {\n            ret = myxml.innerText;\n        } else {\n            ret = myxml.text;\n        }\n    }\n    if (ret === null) {\n        ret = myxml;\n    }\n    return ret;\n}\n\nCSL.XmlDOM.prototype.setAttributeOnNodeIdentifiedByNameAttribute = function (myxml,nodename,partname,attrname,val) {\n    var pos, len, xml, nodes, node;\n    if (attrname.slice(0,1) === '@'){\n        attrname = attrname.slice(1);\n    }\n    nodes = myxml.getElementsByTagName(nodename);\n    for (pos = 0, len = nodes.length; pos < len; pos += 1) {\n        node = nodes[pos];\n        if (node.getAttribute(\"name\") != partname) {\n            continue;\n        }\n        node.setAttribute(attrname, val);\n    }\n}\n\nCSL.XmlDOM.prototype.deleteNodeByNameAttribute = function (myxml,val) {\n    var pos, len, node, nodes;\n    nodes = myxml.childNodes;\n    for (pos = 0, len = nodes.length; pos < len; pos += 1) {\n        node = nodes[pos];\n        if (!node || node.nodeType == node.TEXT_NODE) {\n            continue;\n        }\n        if (this.hasAttributes(node) && node.getAttribute(\"name\") == val) {\n            myxml.removeChild(nodes[pos]);\n        }\n    }\n}\n\nCSL.XmlDOM.prototype.deleteAttribute = function (myxml,attr) {\n    myxml.removeAttribute(attr);\n}\n\nCSL.XmlDOM.prototype.setAttribute = function (myxml,attr,val) {\n    if (!myxml.ownerDocument) {\n        myxml = myxml.firstChild;\n    }\n    // \"unknown\" to satisfy IE8, which crashes when setAttribute\n    // is checked directly as a property, and report its type as\n    // \"unknown\".\n    // Many thanks to Phil Lord for tracing the cause of the fault.\n    if ([\"function\", \"unknown\"].indexOf(typeof myxml.setAttribute) > -1) {\n        myxml.setAttribute(attr, val);\n    }\n    return false;\n}\n\nCSL.XmlDOM.prototype.nodeCopy = function (myxml) {\n    var cloned_node = myxml.cloneNode(true);\n    return cloned_node;\n}\n\nCSL.XmlDOM.prototype.getNodesByName = function (myxml,name,nameattrval) {\n    var ret, nodes, node, pos, len;\n    ret = [];\n    nodes = myxml.getElementsByTagName(name);\n    for (pos = 0, len = nodes.length; pos < len; pos += 1) {\n        node = nodes.item(pos);\n        if (nameattrval && !(this.hasAttributes(node) && node.getAttribute(\"name\") == nameattrval)) {\n//        if (nameattrval && !(this.attributes && node.attributes.name && node.attributes.name.value == nameattrval)) {\n            continue;\n        }\n        ret.push(node);\n    }\n    return ret;\n}\n\nCSL.XmlDOM.prototype.nodeNameIs = function (myxml,name) {\n    if (name == myxml.nodeName) {\n        return true;\n    }\n    return false;\n}\n\nCSL.XmlDOM.prototype.makeXml = function (myxml) {\n    var ret, topnode;\n    if (!myxml) {\n        myxml = \"<docco><bogus/></docco>\";\n    }\n    myxml = myxml.replace(/\\s*<\\?[^>]*\\?>\\s*\\n*/g, \"\");\n    var nodetree = this.parser.parseFromString(myxml, \"application/xml\");\n    return nodetree.firstChild;\n};\n\nCSL.XmlDOM.prototype.insertChildNodeAfter = function (parent,node,pos,datexml) {\n    var myxml, xml;\n    myxml = this.importNode(node.ownerDocument, datexml);\n    parent.replaceChild(myxml, node);\n     return parent;\n};\n\nCSL.XmlDOM.prototype.insertPublisherAndPlace = function(myxml) {\n    var group = myxml.getElementsByTagName(\"group\");\n    for (var i = 0, ilen = group.length; i < ilen; i += 1) {\n        var node = group.item(i);\n        var skippers = [];\n        for (var j = 0, jlen = node.childNodes.length; j < jlen; j += 1) {\n            if (node.childNodes.item(j).nodeType !== 1) {\n                skippers.push(j);\n            }\n        }\n        if (node.childNodes.length - skippers.length === 2) {\n            var twovars = [];\n            for (var j = 0, jlen = 2; j < jlen; j += 1) {\n                if (skippers.indexOf(j) > -1) {\n                    continue;\n                }\n                var child = node.childNodes.item(j);                    \n                var subskippers = [];\n                for (var k = 0, klen = child.childNodes.length; k < klen; k += 1) {\n                    if (child.childNodes.item(k).nodeType !== 1) {\n                        subskippers.push(k);\n                    }\n                }\n                if (child.childNodes.length - subskippers.length === 0) {\n                    twovars.push(child.getAttribute('variable'));\n                    if (child.getAttribute('suffix')\n                        || child.getAttribute('prefix')) {\n                        twovars = [];\n                        break;\n                    }\n                }\n            }\n            if (twovars.indexOf(\"publisher\") > -1 && twovars.indexOf(\"publisher-place\") > -1) {\n                node.setAttribute('has-publisher-and-publisher-place', true);\n            }\n        }\n    }\n};\n\nCSL.XmlDOM.prototype.isChildOfSubstitute = function(node) {\n    if (node.parentNode) {\n        if (node.parentNode.tagName.toLowerCase() === \"substitute\") {\n            return true;\n        } else {\n            return this.isChildOfSubstitute(node.parentNode);\n        }\n    }\n    return false;\n};\n\nCSL.XmlDOM.prototype.addMissingNameNodes = function(myxml) {\n    var nameslist = myxml.getElementsByTagName(\"names\");\n    for (var i = 0, ilen = nameslist.length; i < ilen; i += 1) {\n        var names = nameslist.item(i);\n        var namelist = names.getElementsByTagName(\"name\");\n        if ((!namelist || namelist.length === 0)\n            && !this.isChildOfSubstitute(names)) {\n            \n            var doc = names.ownerDocument;\n            var name = doc.createElement(\"name\");\n            names.appendChild(name);\n        }\n    }\n};\n\n\nCSL.XmlDOM.prototype.addInstitutionNodes = function(myxml) {\n    var names, thenames, institution, theinstitution, theinstitutionpart, name, thename, xml, pos, len;\n    names = myxml.getElementsByTagName(\"names\");\n    for (pos = 0, len = names.length; pos < len; pos += 1) {\n        thenames = names.item(pos);\n        name = thenames.getElementsByTagName(\"name\");\n        if (name.length == 0) {\n            continue;\n        }\n        institution = thenames.getElementsByTagName(\"institution\");\n        if (institution.length == 0) {\n            theinstitution = this.importNode(myxml.ownerDocument, this.institution);\n            theinstitutionpart = theinstitution.getElementsByTagName(\"institution-part\").item(0);\n            thename = name.item(0);\n            thenames.insertBefore(theinstitution, thename.nextSibling);\n            for (var j = 0, jlen = CSL.INSTITUTION_KEYS.length; j < jlen; j += 1) {\n                var attrname = CSL.INSTITUTION_KEYS[j];\n                var attrval = thename.getAttribute(attrname);\n                if (attrval) {\n                    theinstitutionpart.setAttribute(attrname, attrval);\n                }\n            }\n            var nameparts = thename.getElementsByTagName(\"name-part\");\n            for (var j = 0, jlen = nameparts.length; j < jlen; j += 1) {\n                if ('family' === nameparts[j].getAttribute('name')) {\n                    for (var k = 0, klen = CSL.INSTITUTION_KEYS.length; k < klen; k += 1) {\n                        var attrname = CSL.INSTITUTION_KEYS[k];\n                        var attrval = nameparts[j].getAttribute(attrname);\n                        if (attrval) {\n                            theinstitutionpart.setAttribute(attrname, attrval);\n                        }\n                    }\n                }\n            }\n        }\n    }\n};\n\n\nCSL.XmlDOM.prototype.flagDateMacros = function(myxml) {\n    var pos, len, thenode, thedate;\n    var nodes = myxml.getElementsByTagName(\"macro\");\n    for (pos = 0, len = nodes.length; pos < len; pos += 1) {\n        thenode = nodes.item(pos);\n        thedate = thenode.getElementsByTagName(\"date\");\n        if (thedate.length) {\n            thenode.setAttribute('macro-has-date', 'true');\n        }\n    }\n};\n\n\n/*global CSL: true */\n\nCSL.setupXml = function(xmlObject) {\n    var dataObj = {};\n    var parser = null;\n    if (\"undefined\" !== typeof xmlObject) {\n        if (\"string\" === typeof xmlObject) {\n            xmlObject = xmlObject.replace(\"^\\uFEFF\", \"\")\n                .replace(/^\\s+/, \"\");\n            if (xmlObject.slice(0, 1) === \"<\") {\n                // Assume serialized XML\n                dataObj = CSL.parseXml(xmlObject);\n            } else {\n                // Assume serialized JSON\n                dataObj = JSON.parse(xmlObject);\n            }\n            parser = new CSL.XmlJSON(dataObj);\n        } else if (\"undefined\" !== typeof xmlObject.getAttribute) {\n            // Assume DOM instance\n            parser = new CSL.XmlDOM(xmlObject);\n        } else if (\"undefined\" !== typeof xmlObject.toXMLString) {\n            // Assume E4X object\n            parser = new CSL.XmlE4X(xmlObject);\n        } else {\n            // Assume JS object\n            parser = new CSL.XmlJSON(xmlObject);\n        }\n    } else {\n        CSL.error(\"unable to parse XML input\");\n    }\n    if (!parser) {\n        CSL.error(\"citeproc-js error: unable to parse CSL style or locale object\");\n    }\n    return parser;\n};\n\n/*global CSL: true */\n\nCSL.getSortCompare = function (default_locale) {\n    if (CSL.stringCompare) {\n        return CSL.stringCompare;\n    }\n    var me = this;\n    var strcmp;\n    var strcmp_opts = {\n        sensitivity:\"base\",\n        ignorePunctuation:true,\n        numeric:true\n    };\n    // In order, attempt the following:\n    //   (1) Set locale collation from processor language\n    //   (2) Use localeCompare()\n    if (!default_locale) {\n        default_locale = \"en-US\";\n    }\n    strcmp = function (a, b) {\n        return CSL.toLocaleLowerCase.call(me, a).localeCompare(CSL.toLocaleLowerCase.call(me, b),default_locale,strcmp_opts);\n    };\n    var stripPunct = function (str) {\n        return str.replace(/^[\\[\\]\\'\\\"]*/g, \"\");\n    };\n    var getBracketPreSort = function () {\n        if (!strcmp(\"[x\",\"x\")) {\n            return false;\n        } else {\n            return function (a, b) {\n                return strcmp(stripPunct(a), stripPunct(b));\n            };\n        }\n    };\n    var bracketPreSort = getBracketPreSort();\n    var sortCompare = function (a, b) {\n        if (bracketPreSort) {\n            return bracketPreSort(a, b);\n        } else {\n            return strcmp(a, b);\n        }\n    };\n    return sortCompare;\n};\n\n/*global CSL: true */\n\nCSL.ambigConfigDiff = function(a, b) {\n    var pos, len, ppos, llen;\n    // return of true means the ambig configs differ\n    if (a.names.length !== b.names.length) {\n        //print(\"   (1)\");\n        return 1;\n    } else {\n        for (pos = 0, len = a.names.length; pos < len; pos += 1) {\n            if (a.names[pos] !== b.names[pos]) {\n        //print(\"   (2) \"+a.names[pos]+\" \"+b.names[pos]);\n                return 1;\n            } else {\n                for (ppos = 0, llen = a.givens[pos]; ppos < llen; ppos += 1) {\n                    if (a.givens[pos][ppos] !== b.givens[pos][ppos]) {\n        //print(\"   (3): \"+a.givens[pos][ppos]+\" \"+b.givens[pos][ppos]+\" \"+pos+\"/\"+ppos+\" \"+b.givens[pos]);\n                        return 1;\n                    }\n                }\n            }\n        }\n    }\n    if (a.disambiguate != b.disambiguate) {\n        //print(\"   (4) \"+a.disambiguate+\" \"+b.disambiguate);\n        return 1;\n    }\n    if (a.year_suffix !== b.year_suffix) {\n        //print(\"   (5) \"+a.year_suffix+\" \"+b.year_suffix);\n        return 1;\n    }\n    return 0;\n};\n\nCSL.cloneAmbigConfig = function (config, oldconfig) {\n    var i, ilen, j, jlen, param;\n    var ret = {};\n    ret.names = [];\n    ret.givens = [];\n    ret.year_suffix = false;\n    ret.disambiguate = false;\n    for (i = 0, ilen = config.names.length; i < ilen; i += 1) {\n        param = config.names[i];\n        // Fixes update bug affecting plugins, without impacting\n        // efficiency with update of large numbers of year-suffixed\n        // items.\n        ret.names[i] = param;\n    }\n    for (i  = 0, ilen = config.givens.length; i < ilen; i += 1) {\n        param = [];\n        for (j = 0, jlen = config.givens[i].length; j < jlen; j += 1) {\n            // condition at line 312 of disambiguate.js protects against negative\n            // values of j\n            param.push(config.givens[i][j]);\n        }\n        ret.givens.push(param);\n    }\n    // XXXX Is this necessary at all?\n    if (oldconfig) {\n        ret.year_suffix = oldconfig.year_suffix;\n        ret.disambiguate = oldconfig.disambiguate;\n    } else {\n        ret.year_suffix = config.year_suffix;\n        ret.disambiguate = config.disambiguate;\n    }\n    return ret;\n};\n\n/**\n * Return current base configuration for disambiguation\n */\nCSL.getAmbigConfig = function () {\n    var config, ret;\n    config = this.tmp.disambig_request;\n    if (!config) {\n        config = this.tmp.disambig_settings;\n    }\n    var ret = CSL.cloneAmbigConfig(config);\n    return ret;\n};\n\n/**\n * Return max values for disambiguation\n */\nCSL.getMaxVals = function () {\n    return this.tmp.names_max.mystack.slice();\n};\n\n/**\n * Return min value for disambiguation\n */\nCSL.getMinVal = function () {\n    return this.tmp[\"et-al-min\"];\n};\n\n/*global CSL: true */\n\n/* For node execution pretty-printing (see below) */\n\n/*\nvar INDENT = \"\";\n*/\n\nCSL.tokenExec = function (token, Item, item) {\n    // Called on state object\n    var next, maybenext, exec, debug;\n    debug = false;\n    next = token.next;\n    maybenext = false;\n\n    /* Pretty-print node executions */\n\n    /*\n    if ([\"if\", \"else-if\", \"else\"].indexOf(token.name) === -1) {\n        if (token.tokentype == 1) {\n            INDENT = INDENT.slice(0, -2);\n        }\n    }\n    this.sys.print(INDENT + \"---> Token: \" + token.name + \" (\" + token.tokentype + \") in \" + this.tmp.area + \", \" + this.output.current.mystack.length);\n    if ([\"if\", \"else-if\", \"else\"].indexOf(token.name) === -1) {\n        if (token.tokentype == 0) {\n            INDENT += \"  \";\n        }\n    }\n    */\n\n    var record = function (result) {\n        if (result) {\n            this.tmp.jump.replace(\"succeed\");\n            return token.succeed;\n        } else {\n            this.tmp.jump.replace(\"fail\");\n            return token.fail;\n        }\n    };\n    if (token.test) {\n        next = record.call(this,token.test(Item, item));\n    }\n    for (var i=0,ilen=token.execs.length;i<ilen;i++) {\n        exec = token.execs[i];\n        maybenext = exec.call(token, this, Item, item);\n        if (maybenext) {\n            next = maybenext;\n        }\n    }\n    //SNIP-START\n    if (debug) {\n        CSL.debug(token.name + \" (\" + token.tokentype + \") ---> done\");\n    }\n    //SNIP-END\n    return next;\n};\n\n/**\n * Macro expander.\n * <p>Called on the state object.</p>\n */\nCSL.expandMacro = function (macro_key_token, target) {\n    var mkey, macro_nodes, end_of_macro, func;\n\n    mkey = macro_key_token.postponed_macro;\n\n    var sort_direction = macro_key_token.strings.sort_direction;\n    \n    // Decorations and affixes are in wrapper applied in cs:text\n    macro_key_token = new CSL.Token(\"group\", CSL.START);\n    \n    var hasDate = false;\n    var macroid = false;\n    macro_nodes = this.cslXml.getNodesByName(this.cslXml.dataObj, 'macro', mkey);\n    if (macro_nodes.length) {\n        macroid = this.cslXml.getAttributeValue(macro_nodes[0],'cslid');\n        hasDate = this.cslXml.getAttributeValue(macro_nodes[0], \"macro-has-date\");\n    }\n    if (hasDate) {\n        mkey = mkey + \"@\" + this.build.current_default_locale;\n        func = function (state) {\n            if (state.tmp.extension) {\n                state.tmp[\"doing-macro-with-date\"] = true;\n            }\n        };\n        macro_key_token.execs.push(func);\n    }\n\n    if (this.build.macro_stack.indexOf(mkey) > -1) {\n        CSL.error(\"CSL processor error: call to macro \\\"\" + mkey + \"\\\" would cause an infinite loop\");\n    } else {\n        this.build.macro_stack.push(mkey);\n    }\n\n    macro_key_token.cslid = macroid;\n\n    if (CSL.MODULE_MACROS[mkey]) {\n        macro_key_token.juris = mkey;\n        this.opt.update_mode = CSL.POSITION;\n    }\n    // Macro group is treated as a real node in the style\n    CSL.Node.group.build.call(macro_key_token, this, target, true);\n\n    // Node does not exist in the CSL\n    if (!this.cslXml.getNodeValue(macro_nodes)) {\n        CSL.error(\"CSL style error: undefined macro \\\"\" + mkey + \"\\\"\");\n    }\n\n    // Let's macro\n    var mytarget = CSL.getMacroTarget.call(this, mkey);\n    if (mytarget) {\n        CSL.buildMacro.call(this, mytarget, macro_nodes);\n        CSL.configureMacro.call(this, mytarget);\n    }\n    if (!this.build.extension) {\n        var func = (function(macro_name) {\n            return function (state, Item, item) {\n                var next = 0;\n                while (next < state.macros[macro_name].length) {\n                    next = CSL.tokenExec.call(state, state.macros[macro_name][next], Item, item);\n                }\n            };\n        }(mkey));\n        var text_node = new CSL.Token(\"text\", CSL.SINGLETON);\n        text_node.execs.push(func);\n        target.push(text_node);\n    }\n\n    // Decorations and affixes are in wrapper applied in cs:text\n    end_of_macro = new CSL.Token(\"group\", CSL.END);\n    end_of_macro.strings.sort_direction = sort_direction;\n    \n    if (hasDate) {\n        func = function (state) {\n            if (state.tmp.extension) {\n                state.tmp[\"doing-macro-with-date\"] = false;\n            }\n        };\n        end_of_macro.execs.push(func);\n    }\n    if (macro_key_token.juris) {\n        end_of_macro.juris = mkey;\n     }\n    // Macro group is treated as a real node in the style\n    CSL.Node.group.build.call(end_of_macro, this, target, true);\n\n    this.build.macro_stack.pop();\n};\n\nCSL.getMacroTarget = function (mkey) {\n    var mytarget = false;\n    if (this.build.extension) {\n        mytarget = this[this.build.root + this.build.extension].tokens;\n    } else if (!this.macros[mkey]) {\n        mytarget = [];\n        this.macros[mkey] = mytarget;\n    }\n    return mytarget;\n};\n\nCSL.buildMacro = function (mytarget, macro_nodes) {\n    var builder = CSL.makeBuilder(this, mytarget);\n    var mynode;\n    if (\"undefined\" === typeof macro_nodes.length) {\n        mynode = macro_nodes;\n    } else {\n        mynode = macro_nodes[0];\n    }\n    builder(mynode);\n};\n\nCSL.configureMacro = function (mytarget) {\n    if (!this.build.extension) {\n        this.configureTokenList(mytarget);\n    }\n};\n\n\n/**\n * Convert XML node to token.\n * <p>This is called on an XML node.  After extracting the name and attribute\n * information from the node, it performs three operations.  Attribute information\n * relating to output formatting is stored on the node as an array of tuples,\n * which fixes the sequence of execution of output functions to be invoked\n * in the next phase of processing.  Other attribute information is reduced\n * to functions, and is pushed into an array on the token in no particular\n * order, for later execution.  The element name is used as a key to\n * invoke the relevant <code>build</code> method of the target element.\n * Element methods are defined in {@link CSL.Node}.</p>\n * @param {Object} state  The state object returned by {@link CSL.Engine}.\n * @param {Int} tokentype  A CSL namespace constant (<code>CSL.START</code>,\n * <code>CSL.END</code> or <code>CSL.SINGLETON</code>.\n */\nCSL.XmlToToken = function (state, tokentype, explicitTarget, var_stack) {\n    var name, txt, attrfuncs, attributes, decorations, token, key, target;\n    name = state.cslXml.nodename(this);\n    //CSL.debug(tokentype + \" : \" + name);\n    if (state.build.skip && state.build.skip !== name) {\n        return;\n    }\n    if (!name) {\n        txt = state.cslXml.content(this);\n        if (txt) {\n            state.build.text = txt;\n        }\n        return;\n    }\n    if (!CSL.Node[state.cslXml.nodename(this)]) {\n        CSL.error(\"Undefined node name \\\"\" + name + \"\\\".\");\n    }\n    attrfuncs = [];\n    attributes = state.cslXml.attributes(this);\n    decorations = CSL.setDecorations.call(this, state, attributes);\n    token = new CSL.Token(name, tokentype);\n    if (tokentype !== CSL.END || name === \"if\" || name === \"else-if\" || name === \"layout\") {\n        //\n        // xml: more xml stuff\n        //\n        for (var key in attributes) {\n            if (attributes.hasOwnProperty(key)) {\n                if (tokentype === CSL.END && key !== \"@language\" && key !== \"@locale\") {\n                    continue;\n                }\n                if (attributes.hasOwnProperty(key)) {\n                    if (CSL.Attributes[key]) {\n                        try {\n                            CSL.Attributes[key].call(token, state, \"\" + attributes[key]);\n                        } catch (e) {\n                            CSL.error(key + \" attribute: \" + e);\n                        }\n                    } else {\n                        CSL.debug(\"warning: undefined attribute \\\"\"+key+\"\\\" in style\");\n                    }\n                }\n            }\n        }\n        token.decorations = decorations;\n        if (CSL.DATE_VARIABLES.indexOf(attributes['@variable']) > -1) {\n            var_stack.push(token.variables);\n        }\n    } else if (tokentype === CSL.END && attributes['@variable']) {\n        token.hasVariable = true;\n        if (CSL.DATE_VARIABLES.indexOf(attributes['@variable']) > -1) {\n            token.variables = var_stack.pop();\n        }\n    }\n    //\n    // !!!!!: eliminate diversion of tokens to separate\n    // token list (formerly used for reading in macros\n    // and terms).\n    //\n    if (explicitTarget) {\n        target = explicitTarget;\n    } else {\n        target = state[state.build.area].tokens;\n    }\n    // True flags real nodes in the style\n    CSL.Node[name].build.call(token, state, target, true);\n};\n\n\n\n/*global CSL: true */\n\n\nCSL.DateParser = function () {\n\n    /*\n     * Fixed values\n     */\n\n    // jse imperial years\n    var epochPairs = [\n        [\"\\u660E\\u6CBB\", 1867],\n        [\"\\u5927\\u6B63\", 1911],\n        [\"\\u662D\\u548C\", 1925],\n        [\"\\u5E73\\u6210\", 1988]\n    ];\n\n    // years by jse imperial epoch\n    var epochYearByName = {};\n    for (var i=0,ilen=epochPairs.length; i<ilen; i++) {\n        var key = epochPairs[i][0];\n        var val = epochPairs[i][1];\n        epochYearByName[key] = val;\n    }\n    \n    var epochMatchStrings = [];\n    var epochMap = {};\n    for (var i=0,ilen=epochPairs.length; i<ilen; i++) {\n        var pair = epochPairs[i];\n        var val = pair[0];\n        epochMatchStrings.push(val);\n        epochMap[pair[0]] = pair[1];\n    }\n    var epochMatchString = epochMatchStrings.join(\"|\");\n\n    // regular expression to trap year name and year\n    // (splitter and matcher, to cope with ancient JS implementations)\n    var epochSplitter = new RegExp(\"(?:\" + epochMatchString + \")(?:[0-9]+)\");\n    var epochMatcher = new RegExp(\"(?:\" + epochMatchString + \")(?:[0-9]+)\", \"g\");\n\n    // regular expression for month or day kanji label\n    var kanjiMonthDay = /(\\u6708|\\u5E74)/g;\n\n    // regular expression for year kanji label\n    var kanjiYear = /\\u65E5/g;\n\n    // regular expression for double-width Japanese range marker\n    var kanjiRange = /\\u301c/g;\n\n    // parsing regexps for normalized strings\n    //   raw materials\n    var yearLast = \"(?:[?0-9]{1,2}%%NUMD%%){0,2}[?0-9]{4}(?![0-9])\";\n    var yearFirst = \"[?0-9]{4}(?:%%NUMD%%[?0-9]{1,2}){0,2}(?![0-9])\";\n    var numberVal = \"[?0-9]{1,3}\";\n    var rangeSeparator = \"[%%DATED%%]\";\n    var fuzzyChar = \"[?~]\";\n    var chars = \"[^\\-\\/\\~\\?0-9]+\";\n    var rexString = \"(\" + yearFirst + \"|\" + yearLast + \"|\" + numberVal + \"|\" + rangeSeparator + \"|\" + fuzzyChar + \"|\" + chars + \")\";\n    //   composed regexps\n    var rexDash = new RegExp(rexString.replace(/%%NUMD%%/g, \"-\").replace(/%%DATED%%/g, \"-\"));\n    var rexDashSlash = new RegExp(rexString.replace(/%%NUMD%%/g, \"-\").replace(/%%DATED%%/g, \"\\/\"));\n    var rexSlashDash = new RegExp(rexString.replace(/%%NUMD%%/g, \"\\/\").replace(/%%DATED%%/g, \"-\"));\n\n    /*\n     * Mutable values\n     */\n\n    // months\n    var monthString = \"january february march april may june july august september october november december spring summer fall winter spring summer\";\n    this.monthStrings = monthString.split(\" \");\n\n    /*\n     * Configuration functions\n     */\n\n    this.setOrderDayMonth = function() {\n        // preferred ordering for numeric dates\n        this.monthGuess = 1;\n        this.dayGuess = 0;\n    };\n\n    this.setOrderMonthDay = function() {\n        // preferred ordering for numeric dates\n        this.monthGuess = 0;\n        this.dayGuess = 1;\n    };\n\n    this.resetDateParserMonths = function() {\n        // Function to reset months to default.\n        this.monthSets = [];\n        for (var i=0,ilen=this.monthStrings.length; i<ilen; i++) {\n            this.monthSets.push([this.monthStrings[i]]);\n        }\n        this.monthAbbrevs = [];\n        for (var i=0,ilen=this.monthSets.length; i<ilen; i++) {\n            this.monthAbbrevs.push([]);\n            for (var j=0,jlen=this.monthSets[i].length; j<jlen; j++) {\n                this.monthAbbrevs[i].push(this.monthSets[i][0].slice(0, 3));\n            }\n        }\n        this.monthRexes = [];\n        for (var i=0,ilen=this.monthAbbrevs.length; i<ilen; i++) {\n            this.monthRexes.push(new RegExp(\"(?:\" + this.monthAbbrevs[i].join(\"|\") + \")\"));\n        }\n    };\n\n    this.addDateParserMonths = function(lst) {\n        // Extend list of months with an additional set of month abbreviations,\n        // extending strings as required to resolve ambiguities.\n\n        // Normalize string to list\n        if (\"string\" === typeof lst) {\n            lst = lst.split(/\\s+/);\n        }\n\n        // Check that there are twelve (or sixteen) to add\n        if (lst.length !== 12 && lst.length !== 16) {\n            CSL.debug(\"month [+season] list of \"+lst.length+\", expected 12 or 16. Ignoring.\");\n            return;\n        }\n\n        // Extend as necessary to resolve ambiguities\n        // For each new month string ...\n        for (var i=0,ilen=lst.length; i<ilen; i++) {\n            var abbrevLength = null;\n            var skip = false;\n            var insert = 3;\n            var extendedSets = {};\n            for (var j=0,jlen=this.monthAbbrevs.length; j<jlen; j++) {\n                extendedSets[j] = {};\n                if (j === i) {\n                    // Mark for skipping if same as an existing abbreviation of same month\n                    for (var k=0,klen=this.monthAbbrevs[i].length; k<klen; k++) {\n                        if (this.monthAbbrevs[i][k] === lst[i].slice(0, this.monthAbbrevs[i][k].length)) {\n                            skip = true;\n                            break;\n                        }\n                    }\n                } else {\n                    // Mark for extending if same as existing abbreviation of any expression of another month\n                    for (var k=0,klen=this.monthAbbrevs[j].length; k<klen; k++) {\n                        abbrevLength = this.monthAbbrevs[j][k].length;\n                        if (this.monthAbbrevs[j][k] === lst[i].slice(0, abbrevLength)) {\n                            while (this.monthSets[j][k].slice(0, abbrevLength) === lst[i].slice(0, abbrevLength)) {\n                                // Abort when full length is hit, otherwise extend\n                                if (abbrevLength > lst[i].length || abbrevLength > this.monthSets[j][k].length) {\n                                    CSL.debug(\"unable to disambiguate month string in date parser: \"+lst[i]);\n                                    break;\n                                } else {\n                                    // Mark both new entry and existing abbrev for extension\n                                    abbrevLength += 1;\n                                }\n                            }\n                            insert = abbrevLength;\n                            extendedSets[j][k] = abbrevLength;\n                        }\n                    }\n                }\n                for (var jKey in extendedSets) {\n                    for (var kKey in extendedSets[jKey]) {\n                        abbrevLength = extendedSets[jKey][kKey];\n                        jKey = parseInt(jKey, 10);\n                        kKey = parseInt(kKey, 10);\n                        this.monthAbbrevs[jKey][kKey] = this.monthSets[jKey][kKey].slice(0, abbrevLength);\n                    }\n                }\n            }\n            // Insert here\n            if (!skip) {\n                this.monthSets[i].push(lst[i]);\n                this.monthAbbrevs[i].push(lst[i].slice(0, insert));\n            }\n        }\n\n        // Compose\n        this.monthRexes = [];\n        this.monthRexStrs = [];\n        for (var i=0,ilen=this.monthAbbrevs.length; i<ilen; i++) {\n            this.monthRexes.push(new RegExp(\"^(?:\" + this.monthAbbrevs[i].join(\"|\") + \")\"));\n            this.monthRexStrs.push(\"^(?:\" + this.monthAbbrevs[i].join(\"|\") + \")\");\n        }\n        if (this.monthAbbrevs.length === 18) {\n            for (var i=12,ilen=14; i<ilen; i++) {\n                this.monthRexes[i+4] = new RegExp(\"^(?:\" + this.monthAbbrevs[i].join(\"|\") + \")\");\n                this.monthRexStrs[i+4] = \"^(?:\" + this.monthAbbrevs[i].join(\"|\") + \")\";\n            }\n        }\n    };\n\n    /*\n     * Conversion functions\n     */\n\n    this.convertDateObjectToArray = function (thedate) {\n        // Converts object in place and returns object\n        thedate[\"date-parts\"] = [];\n        thedate[\"date-parts\"].push([]);\n        var slicelen = 0;\n        var part;\n        for (var i=0,ilen=3; i<ilen; i++) {\n            part = [\"year\", \"month\", \"day\"][i];\n            if (!thedate[part]) {\n                break;\n            }\n            slicelen += 1;\n            thedate[\"date-parts\"][0].push(thedate[part]);\n            delete thedate[part];\n        }\n        thedate[\"date-parts\"].push([]);\n        for (var i=0, ilen=slicelen; i<ilen; i++) {\n            part = [\"year_end\", \"month_end\", \"day_end\"][i];\n            if (!thedate[part]) {\n                break;\n            }\n            thedate[\"date-parts\"][1].push(thedate[part]);\n            delete thedate[part];\n        }\n        if (thedate[\"date-parts\"][0].length !== thedate[\"date-parts\"][1].length) {\n            thedate[\"date-parts\"].pop();\n        }\n        return thedate;\n    };\n\n    // XXXX String output is currently unable to represent ranges\n    this.convertDateObjectToString = function(thedate) {\n        // Returns string\n        var ret = [];\n        for (var i = 0, ilen = 3; i < ilen; i += 1) {\n            if (thedate[CSL.DATE_PARTS_ALL[i]]) {\n                ret.push(thedate[CSL.DATE_PARTS_ALL[i]]);\n            } else {\n                break;\n            }\n        }\n        return ret.join(\"-\");\n    };\n\n    /*\n     * Utility function\n     */\n\n    this._parseNumericDate = function (ret, delim, suff, txt) {\n        if (!suff) {\n            suff = \"\";\n        }\n        var lst = txt.split(delim);\n        \n        for (var i=0, ilen=lst.length; i<ilen; i++) {\n            if (lst[i].length === 4) {\n                ret[(\"year\" + suff)] = lst[i].replace(/^0*/, \"\");\n                if (!i) {\n                    lst = lst.slice(1);\n                } else {\n                    lst = lst.slice(0, i);\n                }\n                break;\n            }\n        }\n        for (var i=0,ilen=lst.length; i<ilen; i++) {\n            lst[i] = parseInt(lst[i], 10);\n        }\n        if (lst.length === 1 || (lst.length === 2 && !lst[1])) {\n            var month = lst[0];\n            if (month) {\n                ret[(\"month\" + suff)] = \"\" + lst[0];\n            }\n        } else if (lst.length === 2) {\n            if (lst[this.monthGuess] > 12) {\n                var month = lst[this.dayGuess];\n                var day = lst[this.monthGuess];\n                if (month) {\n                    ret[(\"month\" + suff)] = \"\" + month;\n                    if (day) {\n                        ret[(\"day\" + suff)] = \"\" + day;\n                    }\n                }\n            } else {\n                var month = lst[this.monthGuess];\n                var day = lst[this.dayGuess];\n                if (month) {\n                    ret[(\"month\" + suff)] = \"\" + month;\n                    if (day) {\n                        ret[(\"day\" + suff)] = \"\" + day;\n                    }\n                }\n            }\n        }\n    };\n\n    /*\n     * Parsing functions\n     */\n\n    this.parseDateToObject = function (txt) {\n        //\n        // Normalize the format and the year if it's a Japanese date\n        //\n        var orig = txt;\n        var slashPos = -1;\n        var dashPos = -1;\n        var yearIsNegative = false;\n        var lst;\n        if (txt) {\n            txt = txt.replace(/^(.*[0-9])T[0-9].*/, \"$1\");\n            // If string leads with a minus sign, strip and memo it.\n            if (txt.slice(0, 1) === \"-\") {\n                yearIsNegative = true;\n                txt = txt.slice(1);\n            }\n            \n            // If string is a number of 1 to 3 characters only, treat as year.\n            if (txt.match(/^[0-9]{1,3}$/)) {\n                while (txt.length < 4) {\n                    txt = \"0\" + txt;\n                }\n            }\n            \n            // Normalize to string\n            txt = \"\" + txt;\n            // Remove things that look like times\n            txt = txt.replace(/\\s*[0-9]{2}:[0-9]{2}(?::[0-9]+)/,\"\");\n            var m = txt.match(kanjiMonthDay);\n            if (m) {\n                txt = txt.replace(/\\s+/g, \"\");\n                txt = txt.replace(kanjiYear, \"\");\n                txt = txt.replace(kanjiMonthDay, \"-\");\n                txt = txt.replace(kanjiRange, \"/\");\n                txt = txt.replace(/\\-\\//g, \"/\");\n                txt = txt.replace(/-$/g,\"\");\n\n                // Tortuous workaround for IE6\n                var slst = txt.split(epochSplitter);\n                lst = [];\n                var mm = txt.match(epochMatcher);\n                if (mm) {\n                    var mmx = [];\n                    for (var i=0,ilen=mm.length; i<ilen; i++) {\n                        mmx = mmx.concat(mm[i].match(/([^0-9]+)([0-9]+)/).slice(1));\n                    }\n                    for (var i=0,ilen=slst.length; i<ilen; i++) {\n                        lst.push(slst[i]);\n                        if (i !== (ilen - 1)) {\n                            // pos is undeclared, and multiplying by 2 here is insane.\n                            var mmpos = (i * 2);\n                            lst.push(mmx[mmpos]);\n                            lst.push(mmx[mmpos + 1]);\n                        }\n                    }\n                } else {\n                    lst = slst;\n                }\n                // workaround duly applied, this now works\n                for (var i=1,ilen=lst.length; i<ilen; i+=3) {\n                    lst[i + 1] = epochMap[lst[i]] + parseInt(lst[i + 1], 10);\n                    lst[i] = \"\";\n                }\n                txt = lst.join(\"\");\n                txt = txt.replace(/\\s*-\\s*$/, \"\").replace(/\\s*-\\s*\\//, \"/\");\n                //\n                // normalize date and identify delimiters\n                //\n                txt = txt.replace(/\\.\\s*$/, \"\");\n\n                // not sure what this is meant to do\n                txt = txt.replace(/\\.(?! )/, \"\");\n\n                slashPos = txt.indexOf(\"/\");\n                dashPos = txt.indexOf(\"-\");\n            }\n        }\n        // drop punctuation from a.d., b.c.\n        txt = txt.replace(/([A-Za-z])\\./g, \"$1\");\n\n        var number = \"\";\n        var note = \"\";\n        var thedate = {};\n        var rangeDelim;\n        var dateDelim;\n        if (txt.slice(0, 1) === \"\\\"\" && txt.slice(-1) === \"\\\"\") {\n            thedate.literal = txt.slice(1, -1);\n            return thedate;\n        }\n        if (slashPos > -1 && dashPos > -1) {\n            var slashCount = txt.split(\"/\");\n            if (slashCount.length > 3) {\n                rangeDelim = \"-\";\n                txt = txt.replace(/\\_/g, \"-\");\n                dateDelim = \"/\";\n                lst = txt.split(rexSlashDash);\n            } else {\n                rangeDelim = \"/\";\n                txt = txt.replace(/\\_/g, \"/\");\n                dateDelim = \"-\";\n                lst = txt.split(rexDashSlash);\n            }\n        } else {\n            txt = txt.replace(/\\//g, \"-\");\n            txt = txt.replace(/\\_/g, \"-\");\n            rangeDelim = \"-\";\n            dateDelim = \"-\";\n            lst = txt.split(rexDash);\n        }\n        var ret = [];\n        for (var i=0,ilen=lst.length; i<ilen; i++) {\n            var m = lst[i].match(/^\\s*([\\-\\/]|[^\\-\\/\\~\\?0-9]+|[\\-~?0-9]+)\\s*$/);\n            if (m) {\n                ret.push(m[1]);\n            }\n        }\n        //\n        // Phase 2\n        //\n        var delimPos = ret.indexOf(rangeDelim);\n        var delims = [];\n        var isRange = false;\n        if (delimPos > -1) {\n            delims.push([0, delimPos]);\n            delims.push([(delimPos + 1), ret.length]);\n            isRange = true;\n        } else {\n            delims.push([0, ret.length]);\n        }\n        //\n        // For each side of a range divide ...\n        //\n        var suff = \"\";\n        \n        for (var i=0,ilen=delims.length; i<ilen; i++) {\n            var delim = delims[i];\n            //\n            // Process each element ...\n            //\n            var date = ret.slice(delim[0], delim[1]);\n            outer: \n            for (var j=0,jlen=date.length; j<jlen; j++) {\n                var element = date[j];\n                //\n                // If it's a numeric date, process it.\n                //\n                if (element.indexOf(dateDelim) > -1) {\n                    this._parseNumericDate(thedate, dateDelim, suff, element);\n                    continue;\n                }\n                //\n                // If it's an obvious year, record it.\n                //\n                if (element.match(/[0-9]{4}/)) {\n                    thedate[(\"year\" + suff)] = element.replace(/^0*/, \"\");\n                    continue;\n                }\n                //\n                // If it's a fuzzy marker, record it.\n                //\n                if (element === \"~\" || element === \"?\" || element === \"c\" || element.match(/^cir/)) {\n                    thedate.circa = true;\n                }\n                //\n                // If it's a month, record it.\n                //\n                for (var k=0,klen=this.monthRexes.length; k<klen; k++) {\n                    if (element.toLocaleLowerCase().match(this.monthRexes[k])) {\n                        thedate[(\"month\" + suff)] = \"\" + (parseInt(k, 10) + 1);\n                        continue outer;\n                    }\n                }\n                //\n                // If it's a number, make a note of it\n                //\n                if (element.match(/^[0-9]+$/)) {\n                    number = element;\n                }\n                //\n                // If it's a BC or AD marker, make a year of\n                // any note.  Separate, reverse the sign of the year\n                // if it's BC.\n                //\n                if (element.toLocaleLowerCase().match(/^bc/) && number) {\n                    thedate[(\"year\" + suff)] = \"\" + (number * -1);\n                    number = \"\";\n                    continue;\n                }\n                if (element.toLocaleLowerCase().match(/^ad/) && number) {\n                    thedate[(\"year\" + suff)] = \"\" + number;\n                    number = \"\";\n                    continue;\n                }\n                //\n                // If it's cruft, make a note of it\n                //\n                if (element.toLocaleLowerCase().match(/(?:mic|tri|hil|eas)/) && !thedate[(\"season\" + suff)]) {\n                    note = element;\n                    continue;\n                }\n            }\n            //\n            // If at the end of the string there's still a note\n            // hanging around, make a day of it.\n            //\n            if (number) {\n                thedate[(\"day\" + suff)] = number;\n                number = \"\";\n            }\n            //\n            // If at the end of the string there's cruft lying\n            // around, and the season field is empty, put the\n            // cruft there.\n            //\n            if (note && !thedate[(\"season\" + suff)]) {\n                thedate[(\"season\" + suff)] = note.trim();\n                note = \"\";\n            }\n            suff = \"_end\";\n        }\n        //\n        // update any missing elements on each side of the divide\n        // from the other\n        //\n        if (isRange) {\n            for (var j=0,jlen=CSL.DATE_PARTS_ALL.length; j<jlen; j++) {\n                var item = CSL.DATE_PARTS_ALL[j];\n                if (thedate[item] && !thedate[(item + \"_end\")]) {\n                    thedate[(item + \"_end\")] = thedate[item];\n                } else if (!thedate[item] && thedate[(item + \"_end\")]) {\n                    thedate[item] = thedate[(item + \"_end\")];\n                }\n            }\n        }\n        //\n        // If there's no year, or if there only a year and a day, it's a failure; pass through the literal\n        //\n        if (!thedate.year || (thedate.year && thedate.day && !thedate.month)) {\n            thedate = { \"literal\": orig };\n        }\n        var parts = [\"year\", \"month\", \"day\", \"year_end\", \"month_end\", \"day_end\"];\n        for (var i=0,ilen=parts.length; i<ilen; i++) {\n            var part = parts[i];\n            if (\"string\" === typeof thedate[part] && thedate[part].match(/^[0-9]+$/)) {\n                thedate[part] = parseInt(thedate[part], 10);\n            }\n            \n        }\n        if (yearIsNegative && Object.keys(thedate).indexOf(\"year\") > -1) {\n            thedate.year = (thedate.year * -1);\n        }\n        return thedate;\n    };\n\n    this.parseDateToArray = function(txt) {\n        return this.convertDateObjectToArray(this.parseDateToObject(txt));            \n    };\n\n    this.parseDateToString = function(txt) {\n        return this.convertDateObjectToString(this.parseDateToObject(txt));\n    };\n    \n    this.parse = function(txt) {\n        return this.parseDateToObject(txt);\n    };\n    \n    /*\n\n     * Setup\n     */\n\n    this.setOrderMonthDay();\n    this.resetDateParserMonths();\n};\nCSL.DateParser = new CSL.DateParser();\n\n/*global CSL: true */\n\nCSL.Engine = function (sys, style, lang, forceLang) {\n    var attrs, langspec;\n    this.processor_version = CSL.PROCESSOR_VERSION;\n    this.csl_version = \"1.0\";\n    this.sys = sys;\n    \n    if (typeof Object.assign != 'function') {\n        // Must be writable: true, enumerable: false, configurable: true\n        Object.defineProperty(Object, \"assign\", {\n            value: function assign(target) { // .length of function is 2\n                'use strict';\n                if (target == null) { // TypeError if undefined or null\n                    throw new TypeError('Cannot convert undefined or null to object');\n                }\n\n                var to = Object(target);\n\n                for (var index = 1; index < arguments.length; index++) {\n                    var nextSource = arguments[index];\n\n                    if (nextSource != null) { // Skip over if undefined or null\n                        for (var nextKey in nextSource) {\n                            // Avoid bugs when hasOwnProperty is shadowed\n                            if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {\n                                to[nextKey] = nextSource[nextKey];\n                            }\n                        }\n                    }\n                }\n                return to;\n            },\n            writable: true,\n            configurable: true\n        });\n    }\n\n    // XXX This may be excess code. Given the normalization performed on\n    // XXX the output queue before variableWrapper() is run, a single\n    // XXX space should be the most cruft that we ever see before a variable.\n    if (sys.variableWrapper) {\n        CSL.VARIABLE_WRAPPER_PREPUNCT_REX = new RegExp('^([' + [\" \"].concat(CSL.SWAPPING_PUNCTUATION).join(\"\") + ']*)(.*)');\n    }\n    // XXXX This should be restored -- temporarily suspended for testing of JSON style support.\n    if (CSL.retrieveStyleModule) {\n        this.sys.retrieveStyleModule = CSL.retrieveStyleModule;\n    }\n    if (CSL.getAbbreviation) {\n        this.sys.getAbbreviation = CSL.getAbbreviation;\n    }\n    if (this.sys.stringCompare) {\n        CSL.stringCompare = this.sys.stringCompare;\n    }\n    this.sys.AbbreviationSegments = CSL.AbbreviationSegments;\n\n    this.transform = new CSL.Transform(this);\n    // true or false\n    this.setParseNames = function (val) {\n        this.opt['parse-names'] = val;\n    };\n    \n    this.opt = new CSL.Engine.Opt();\n    this.tmp = new CSL.Engine.Tmp();\n    this.build = new CSL.Engine.Build();\n    this.fun = new CSL.Engine.Fun(this);\n\n    this.configure = new CSL.Engine.Configure();\n    // Build citation before citation_sort in order to pick up\n    // state.opt.update_mode, needed it determine whether\n    // a grouped sort should be performed.\n    this.citation_sort = new CSL.Engine.CitationSort();\n    this.bibliography_sort = new CSL.Engine.BibliographySort();\n    this.citation = new CSL.Engine.Citation(this);\n    this.bibliography = new CSL.Engine.Bibliography();\n    this.intext = new CSL.Engine.InText();\n\n    this.output = new CSL.Output.Queue(this);\n\n    //this.render = new CSL.Render(this);\n    //\n    // This latter queue is used for formatting date chunks\n    // before they are folded back into the main queue.\n    //\n    this.dateput = new CSL.Output.Queue(this);\n\n    this.cslXml = CSL.setupXml(style);\n\n    for (var i in CSL.SYS_OPTIONS) {\n        var option = CSL.SYS_OPTIONS[i];\n        if (\"boolean\" === typeof this.sys[option]) {\n            this.opt.development_extensions[option] = this.sys[option];\n        }\n        \n    }\n    if (this.opt.development_extensions.uppercase_subtitles || this.opt.development_extensions.implicit_short_title) {\n        this.opt.development_extensions.main_title_from_short_title = true;\n    }\n    if (this.opt.development_extensions.csl_reverse_lookup_support) {\n        this.build.cslNodeId = 0;\n        this.setCslNodeIds = function(myxml, nodename) {\n            var children = this.cslXml.children(myxml);\n            this.cslXml.setAttribute(myxml, 'cslid', this.build.cslNodeId);\n            this.opt.nodenames.push(nodename);\n            this.build.cslNodeId += 1;\n            for (var i = 0, ilen = this.cslXml.numberofnodes(children); i < ilen; i += 1) {\n                nodename = this.cslXml.nodename(children[i]);\n                if (nodename) {\n                    this.setCslNodeIds(children[i], nodename);\n                }\n            }\n        };\n        this.setCslNodeIds(this.cslXml.dataObj, \"style\");\n    }\n    // Preprocessing ops for the XML input\n    this.cslXml.addMissingNameNodes(this.cslXml.dataObj);\n    this.cslXml.addInstitutionNodes(this.cslXml.dataObj);\n    this.cslXml.insertPublisherAndPlace(this.cslXml.dataObj);\n    this.cslXml.flagDateMacros(this.cslXml.dataObj);\n    attrs = this.cslXml.attributes(this.cslXml.dataObj);\n    if (\"undefined\" === typeof attrs[\"@sort-separator\"]) {\n        this.cslXml.setAttribute(this.cslXml.dataObj, \"sort-separator\", \", \");\n    }\n    // This setting does the right thing and seems not to be side-effects\n    this.opt[\"initialize-with-hyphen\"] = true;\n\n    // Locale resolution\n    //\n    // (1) Get three locale strings \n    //     -- default-locale (stripped)\n    //     -- processor-locale\n    //     -- en_US\n    \n    this.setStyleAttributes();\n\n    this.opt.xclass = this.cslXml.getAttributeValue(this.cslXml.dataObj, \"class\");\n    this.opt[\"class\"] = this.opt.xclass;\n    this.opt.styleID = this.cslXml.getStyleId(this.cslXml.dataObj);\n    this.opt.styleName = this.cslXml.getStyleId(this.cslXml.dataObj, true);\n\n    if (this.opt.version.slice(0,4) === \"1.1m\") {\n        this.opt.development_extensions.consolidate_legal_items = true;\n        this.opt.development_extensions.consolidate_container_items = true;\n        this.opt.development_extensions.main_title_from_short_title = true;\n        this.opt.development_extensions.expect_and_symbol_form = true;\n        this.opt.development_extensions.require_explicit_legal_case_title_short = true;\n        this.opt.development_extensions.force_jurisdiction = true;\n        this.opt.development_extensions.force_title_abbrev_fallback = true;\n    }\n    // We seem to have two language specs flying around:\n    //   this.opt[\"default-locale\"], and this.opt.lang\n    // Keeping them aligned for safety's sake, pending\n    // eventual cleanup.\n    if (lang) {\n        lang = lang.replace(\"_\", \"-\");\n        lang = CSL.normalizeLocaleStr(lang);\n    }\n    if (this.opt[\"default-locale\"][0]) {\n        this.opt[\"default-locale\"][0] = this.opt[\"default-locale\"][0].replace(\"_\", \"-\");\n        this.opt[\"default-locale\"][0] = CSL.normalizeLocaleStr(this.opt[\"default-locale\"][0]);\n    }\n    if (lang && forceLang) {\n        this.opt[\"default-locale\"] = [lang];\n    }\n    if (lang && !forceLang && this.opt[\"default-locale\"][0]) {\n        lang = this.opt[\"default-locale\"][0];\n    }\n    if (this.opt[\"default-locale\"].length === 0) {\n        if (!lang) {\n            lang = \"en-US\";\n        }\n        this.opt[\"default-locale\"].push(\"en-US\");\n    }\n    if (!lang) {\n        lang = this.opt[\"default-locale\"][0];\n    }\n    langspec = CSL.localeResolve(lang);\n    this.opt.lang = langspec.best;\n    this.opt[\"default-locale\"][0] = langspec.best;\n    this.locale = {};\n    if (!this.opt[\"default-locale-sort\"]) {\n        this.opt[\"default-locale-sort\"] = this.opt[\"default-locale\"][0];\n    }\n    // Test processor against JS engine locale mess to find a field separator that works\n    if ('dale|'.localeCompare('daleb', this.opt[\"default-locale-sort\"]) > -1) {\n        this.opt.sort_sep = \"@\";\n    } else {\n        this.opt.sort_sep = \"|\";\n    }\n    this.localeConfigure(langspec);\n\n    // Build skip-word regexp\n    function makeRegExp(lst) {\n        var lst = lst.slice();\n        var ret = new RegExp( \"(?:(?:[?!:]*\\\\s+|-|^)(?:\" + lst.join(\"|\") + \")(?=[!?:]*\\\\s+|-|$))\", \"g\");\n        return ret;\n    }\n    this.locale[this.opt.lang].opts[\"skip-words-regexp\"] = makeRegExp(this.locale[this.opt.lang].opts[\"skip-words\"]);\n\n    this.output.adjust = new CSL.Output.Queue.adjust(this.getOpt('punctuation-in-quote'));\n\n    this.registry = new CSL.Registry(this);\n\n    // XXX For modular jurisdiction support, parameterize buildTokenLists().\n    // XXX Feed as arguments:\n    // XXX * actual node to be walked (cslXml)\n    // XXX * actual target array\n\n    this.macros = {};\n\n    this.build.area = \"citation\";\n    var area_nodes = this.cslXml.getNodesByName(this.cslXml.dataObj, this.build.area);\n    this.buildTokenLists(area_nodes, this[this.build.area].tokens);\n\n    this.build.area = \"bibliography\";\n    var area_nodes = this.cslXml.getNodesByName(this.cslXml.dataObj, this.build.area);\n    this.buildTokenLists(area_nodes, this[this.build.area].tokens);\n\n    this.build.area = \"intext\";\n    var area_nodes = this.cslXml.getNodesByName(this.cslXml.dataObj, this.build.area);\n    this.buildTokenLists(area_nodes, this[this.build.area].tokens);\n\n    if (this.opt.parallel.enable) {\n        this.parallel = new CSL.Parallel(this);\n    }\n\n    this.juris = {};\n\n    this.configureTokenLists();\n\n    this.disambiguate = new CSL.Disambiguation(this);\n\n    this.splice_delimiter = false;\n\n    //\n    // date parser\n    //\n    this.fun.dateparser = CSL.DateParser;\n    //\n    // flip-flopper for inline markup\n    //\n    this.fun.flipflopper = new CSL.Util.FlipFlopper(this);\n    //\n    // utility functions for quotes\n    //\n    this.setCloseQuotesArray();\n    //\n    // configure ordinal numbers generator\n    //\n    this.fun.ordinalizer.init(this);\n    //\n    // configure long ordinal numbers generator\n    //\n    this.fun.long_ordinalizer.init(this);\n    //\n    // set up page mangler\n    //\n    this.fun.page_mangler = CSL.Util.PageRangeMangler.getFunction(this, \"page\");\n    this.fun.year_mangler = CSL.Util.PageRangeMangler.getFunction(this, \"year\");\n\n    this.setOutputFormat(\"html\");\n};\n\nCSL.Engine.prototype.setCloseQuotesArray = function () {\n    var ret;\n    ret = [];\n    ret.push(this.getTerm(\"close-quote\"));\n    ret.push(this.getTerm(\"close-inner-quote\"));\n    ret.push('\"');\n    ret.push(\"'\");\n    this.opt.close_quotes_array = ret;\n};\n\n// Walker for preparsed XML input\nCSL.makeBuilder = function (me, target) {\n    var var_stack = [];\n    var node_stack = [];\n    function runStart (node) {\n        node_stack.push(node);\n        CSL.XmlToToken.call(node, me, CSL.START, target, var_stack);\n    }\n    function runEnd () {\n        var node = node_stack.pop();\n        CSL.XmlToToken.call(node, me, CSL.END, target, var_stack);\n    }\n    function runSingle (node) {\n        CSL.XmlToToken.call(node, me, CSL.SINGLETON, target, var_stack);\n    }\n    function buildStyle (nodes, parent, node_stack) {\n        if (!node_stack) {\n            node_stack = [];\n        }\n        if (!nodes) {\n            nodes = [];\n        }\n        if (\"undefined\" === typeof nodes.length) {\n            nodes = [nodes];\n        }\n        for (var i=0; i<nodes.length; i++) {\n            var node = nodes[i];\n            if (me.cslXml.nodename(node) === null) {\n                continue;\n            }\n            if (parent && me.cslXml.nodename(node) === \"date\") {\n                CSL.Util.fixDateNode.call(me, parent, i, node);\n                node = me.cslXml.children(parent)[i];\n            }\n            if (me.cslXml.numberofnodes(me.cslXml.children(node))) {\n                runStart(node);\n                buildStyle(me.cslXml.children(node), node, node_stack);\n                runEnd();\n            } else {\n                runSingle(node);\n            }\n        }\n    }\n    return buildStyle;\n};\n\n\nCSL.Engine.prototype.buildTokenLists = function (area_nodes, target) {\n    if (!this.cslXml.getNodeValue(area_nodes)) {\n        return;\n    }\n    var builder = CSL.makeBuilder(this, target);\n    var mynode;\n    if (\"undefined\" === typeof area_nodes.length) {\n        mynode = area_nodes;\n    } else {\n        mynode = area_nodes[0];\n    }\n    builder(mynode);\n};\n\n\nCSL.Engine.prototype.setStyleAttributes = function () {\n    var dummy, attributes, attrname;\n    // Protect against DOM engines that deliver a top-level document\n    // (needed for createElement) that does not contain our top-level node.\n    // \n    // The string coercion on this.cslXml.tagName addresses a bizarre\n    // condition on the top-level node in jsdom running under node.js, in which:\n    //   (1) typeof this.cslXml.tagName === \"undefined\"; and\n    //   (2) !this.cslXml.tagName === false\n    // Coerced, it becomes an empty string.\n    var dummy = {};\n    dummy.name = this.cslXml.nodename(this.cslXml.dataObj);\n    attributes = this.cslXml.attributes(this.cslXml.dataObj);\n    for (attrname in attributes) {\n        if (attributes.hasOwnProperty(attrname)) {\n            // attr = attributes[key];\n            CSL.Attributes[attrname].call(dummy, this, attributes[attrname]);\n        }\n    }\n};\n\nCSL.Engine.prototype.getTerm = function (term, form, plural, gender, mode, forceDefaultLocale) {\n    if (term && term.match(/[A-Z]/) && term === term.toUpperCase()) {\n        CSL.debug(\"Warning: term key is in uppercase form: \"+term);\n        term = term.toLowerCase();\n    }\n    var lang;\n    if (forceDefaultLocale) {\n        lang = this.opt[\"default-locale\"][0];\n    } else {\n        lang = this.opt.lang;\n    }\n    var ret = CSL.Engine.getField(CSL.LOOSE, this.locale[lang].terms, term, form, plural, gender);\n    // XXXXX Temporary, until locale term is deployed in CSL.\n    if (!ret && term === \"range-delimiter\") {\n        ret = \"\\u2013\";\n    }\n    // XXXXX Not so good if mode is neither strict nor tolerant ...\n    if (typeof ret === \"undefined\") {\n        if (mode === CSL.STRICT) {\n            CSL.error(\"Error in getTerm: term \\\"\" + term + \"\\\" does not exist.\");\n        } else if (mode === CSL.TOLERANT) {\n            ret = \"\";\n        }\n    }\n    if (ret) {\n        this.tmp.cite_renders_content = true;\n    }\n    return ret;\n};\n\nCSL.Engine.prototype.getDate = function (form, forceDefaultLocale) {\n    var lang;\n    if (forceDefaultLocale) {\n        lang = this.opt[\"default-locale\"];\n    } else {\n        lang = this.opt.lang;\n    }\n    if (this.locale[lang].dates[form]) {\n        return this.locale[lang].dates[form];\n    } else {\n        return false;\n    }\n};\n\nCSL.Engine.prototype.getOpt = function (arg) {\n    if (\"undefined\" !== typeof this.locale[this.opt.lang].opts[arg]) {\n        return this.locale[this.opt.lang].opts[arg];\n    } else {\n        return false;\n    }\n};\n\n\n\nCSL.Engine.prototype.getVariable = function (Item, varname, form, plural) {\n    return CSL.Engine.getField(CSL.LOOSE, Item, varname, form, plural);\n};\n\nCSL.Engine.prototype.getDateNum = function (ItemField, partname) {\n    if (\"undefined\" === typeof ItemField) {\n        return 0;\n    } else {\n        return ItemField[partname];\n    }\n};\n\nCSL.Engine.getField = function (mode, hash, term, form, plural, gender) {\n    var ret, forms, f, pos, len, hashterm;\n    ret = \"\";\n    if (\"undefined\" === typeof hash[term]) {\n        if (mode === CSL.STRICT) {\n            CSL.error(\"Error in getField: term \\\"\" + term + \"\\\" does not exist.\");\n        } else {\n            return undefined;\n        }\n    }\n    if (gender && hash[term][gender]) {\n        hashterm = hash[term][gender];\n    } else {\n        hashterm = hash[term];\n    }\n    forms = [];\n    if (form === \"symbol\") {\n        forms = [\"symbol\", \"short\"];\n    } else if (form === \"verb-short\") {\n        forms = [\"verb-short\", \"verb\"];\n    } else if (form !== \"long\") {\n        forms = [form];\n    }\n    forms = forms.concat([\"long\"]);\n    len = forms.length;\n    for (pos = 0; pos < len; pos += 1) {\n        f = forms[pos];\n        if (\"string\" === typeof hashterm || \"number\" === typeof hashterm) {\n            ret = hashterm;\n        } else if (\"undefined\" !== typeof hashterm[f]) {\n            if (\"string\" === typeof hashterm[f] || \"number\" === typeof hashterm[f]) {\n                ret = hashterm[f];\n            } else {\n                if (\"number\" === typeof plural) {\n                    ret = hashterm[f][plural];\n                } else {\n                    ret = hashterm[f][0];\n                }\n            }\n            break;\n        }\n    }\n    return ret;\n};\n\nCSL.Engine.prototype.configureTokenLists = function () {\n    var area, pos, len;\n    //for each (var area in [\"citation\", \"citation_sort\", \"bibliography\",\"bibliography_sort\"]) {\n    len = CSL.AREAS.length;\n    for (pos = 0; pos < len; pos += 1) {\n        //var ret = [];\n        area = CSL.AREAS[pos];\n        var tokens = this[area].tokens;\n        this.configureTokenList(tokens);\n    }\n    this.version = CSL.version;\n    return this.state;\n};\n\nCSL.Engine.prototype.configureTokenList = function (tokens) {\n    var dateparts_master, token, dateparts, part, ppos, pppos, llen, lllen;\n    dateparts_master = [\"year\", \"month\", \"day\"];\n    llen = tokens.length - 1;\n    for (ppos = llen; ppos > -1; ppos += -1) {\n        token = tokens[ppos];\n        //token.pos = ppos;\n        //ret.push(token);\n        if (\"date\" === token.name && CSL.END === token.tokentype) {\n            dateparts = [];\n        }\n        if (\"date-part\" === token.name && token.strings.name) {\n            lllen = dateparts_master.length;\n            for (pppos = 0; pppos < lllen; pppos += 1) {\n                part = dateparts_master[pppos];\n                if (part === token.strings.name) {\n                    dateparts.push(token.strings.name);\n                }\n            }\n        }\n        if (\"date\" === token.name && CSL.START === token.tokentype) {\n            dateparts.reverse();\n            token.dateparts = dateparts;\n        }\n        token.next = (ppos + 1);\n        if (token.name && CSL.Node[token.name].configure) {\n            CSL.Node[token.name].configure.call(token, this, ppos);\n        }\n    }\n};\n\nCSL.Engine.prototype.refetchItems = function (ids) {\n    var ret = [];\n    for (var i = 0, ilen = ids.length; i < ilen; i += 1) {\n        ret.push(this.refetchItem(\"\" + ids[i]));\n    }\n    return ret;\n};\n\nCSL.ITERATION = 0;\n\n// Wrapper for sys.retrieveItem supplied by calling application.\n// Adds experimental fields embedded in the note field for\n// style development trial and testing purposes.\nCSL.Engine.prototype.retrieveItem = function (id) {\n    var Item, m, i;\n\n    if (!this.tmp.loadedItemIDs[id]) {\n        this.tmp.loadedItemIDs[id] = true;\n    } else {\n        return this.registry.refhash[id];\n    }\n\n    if (this.opt.development_extensions.normalize_lang_keys_to_lowercase &&\n        \"boolean\" === typeof this.opt.development_extensions.normalize_lang_keys_to_lowercase) {\n        // This is a hack. Should properly be configured by a processor method after build.\n        for (var i=0,ilen=this.opt[\"default-locale\"].length; i<ilen; i+=1) {\n            this.opt[\"default-locale\"][i] = this.opt[\"default-locale\"][i].toLowerCase();\n        }\n        for (var i=0,ilen=this.opt[\"locale-translit\"].length; i<ilen; i+=1) {\n            this.opt[\"locale-translit\"][i] = this.opt[\"locale-translit\"][i].toLowerCase();\n        }\n        for (var i=0,ilen=this.opt[\"locale-translat\"].length; i<ilen; i+=1) {\n            this.opt[\"locale-translat\"][i] = this.opt[\"locale-translat\"][i].toLowerCase();\n        }\n        this.opt.development_extensions.normalize_lang_keys_to_lowercase = 100;\n    }\n\n    //Zotero.debug(\"XXX === ITERATION \" + CSL.ITERATION + \" \"+ id +\" ===\");\n    CSL.ITERATION += 1;\n\n    Item = JSON.parse(JSON.stringify(this.sys.retrieveItem(\"\" + id)));\n\n    // Optionally normalize keys to lowercase()\n    if (this.opt.development_extensions.normalize_lang_keys_to_lowercase) {\n        if (Item.multi) {\n            if (Item.multi._keys) {\n                for (var field in Item.multi._keys) {\n                    for (var key in Item.multi._keys[field]) {\n                        if (key !== key.toLowerCase()) {\n                            Item.multi._keys[field][key.toLowerCase()] = Item.multi._keys[field][key];\n                            delete Item.multi._keys[field][key];\n                        }\n                    }\n                }\n            }\n            if (Item.multi.main) {\n                for (var field in Item.multi.main) {\n                    Item.multi.main[field] = Item.multi.main[field].toLowerCase();\n                }\n            }\n        }\n        for (var i=0, ilen=CSL.NAME_VARIABLES.length; i>ilen; i+=1) {\n            var ctype = CSL.NAME_VARIABLES[i];\n            if (Item[ctype] && Item[ctype].multi) {\n                for (var j=0, jlen=Item[ctype].length; j<jlen; j+=1) {\n                    var creator = Item[ctype][j];\n                    if (creator.multi) {\n                        if (creator.multi._key) {\n                            for (var key in creator.multi._key) {\n                                if (key !== key.toLowerCase()) {\n                                    creator.multi._key[key.toLowerCase()] = creator.multi._key[key];\n                                    delete creator.multi._key[key];\n                                }\n                            }\n                        }\n                        if (creator.multi.main) {\n                            creator.multi.main = creator.multi.main.toLowerCase();\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    // Normalize language field into \"language\" and \"language-original\"\n    if (Item.language && Item.language.match(/[><]/)) {\n        // Attempt to split field in two\n        var m = Item.language.match(/(.*?)([<>])(.*)/);\n        if (m[2] === \"<\") {\n            Item[\"language-name\"] = m[1];\n            Item[\"language-name-original\"] = m[3];\n        } else {\n            Item[\"language-name\"] = m[3];\n            Item[\"language-name-original\"] = m[1];\n        }\n        if (this.opt.multi_layout) {\n            if (Item[\"language-name-original\"]) {\n                Item.language = Item[\"language-name-original\"];\n            }\n        } else {\n            if (Item[\"language-name\"]) {\n                Item.language = Item[\"language-name\"];\n            }\n        }\n    }\n\n    if (Item.page) {\n        Item[\"page-first\"] = Item.page;\n        var num = \"\" + Item.page;\n        var m = num.split(/\\s*(?:&|, |-|\\u2013)\\s*/);\n        if (m[0].slice(-1) !== \"\\\\\") {\n            Item[\"page-first\"] = m[0];\n        }\n    }\n    // Optional development extensions\n    if (this.opt.development_extensions.field_hack && Item.note) {\n        // false is for validFieldsForType (all conforming entries scrubbed when false)\n        CSL.parseNoteFieldHacks(Item, false, this.opt.development_extensions.allow_field_hack_date_override);\n    }\n    // not including locator-date\n    for (var key in Item) {\n        if (CSL.DATE_VARIABLES.indexOf(key.replace(/^alt-/, \"\")) > -1) {\n            var dateobj = Item[key];\n            if (dateobj) {\n                // raw date parsing is harmless, but can be disabled if desired\n                if (this.opt.development_extensions.raw_date_parsing) {\n                    if (dateobj.raw && (!dateobj[\"date-parts\"] || dateobj[\"date-parts\"].length === 0)) {\n                        dateobj = this.fun.dateparser.parseDateToObject(dateobj.raw);\n                    }\n                }\n                Item[key] = this.dateParseArray(dateobj);\n            }\n        }\n    }\n    if (this.opt.development_extensions.consolidate_legal_items) {\n        if (Item.type && [\"bill\",\"gazette\",\"legislation\",\"regulation\",\"treaty\"].indexOf(Item.type) > -1) {\n            var varname;\n            var elements = [\"type\", \"title\", \"jurisdiction\", \"genre\", \"volume\", \"container-title\"];\n            var legislation_id = [];\n            for (var i = 0, ilen = elements.length; i < ilen; i += 1) {\n                varname = elements[i];\n\t\t\t\tif (Item[varname]) {\n\t\t\t\t\tlegislation_id.push(Item[varname]);\n\t\t\t\t}\n\t\t\t}\n            elements = [\"original-date\", \"issued\"];\n\t\t\tfor (var i = 0, ilen=elements.length; i < ilen; i += 1) {\n                varname = elements[i];\n\t\t\t\tif (Item[varname] && Item[varname].year) {\n\t\t\t\t\tvar value = Item[varname].year;\n\t\t\t\t\tlegislation_id.push(value);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tItem.legislation_id = legislation_id.join(\"::\");\n        }\n    }\n    if (this.bibliography.opt.track_container_items) {\n        if (this.bibliography.opt.track_container_items.indexOf(Item.type) > -1) {\n            var varname;\n            var elements = [\"type\", \"container-title\", \"publisher\", \"edition\"];\n            var container_id = [];\n            for (var i = 0, ilen = elements.length; i < ilen; i += 1) {\n                varname = elements[i];\n\t\t\t\tif (Item[varname]) {\n\t\t\t\t\tcontainer_id.push(Item[varname]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tItem.container_id = container_id.join(\"::\");\n        }\n    }\n    // For authority to name shape in legal styles\n    if (this.opt.development_extensions.force_jurisdiction) {\n        if (\"string\" === typeof Item.authority) {\n            Item.authority = [\n                {\n                    literal: Item.authority,\n                    multi: {\n                        _key: {}\n                    }\n                }\n            ];\n            if (Item.multi && Item.multi._keys && Item.multi._keys.authority) {\n                Item.authority[0].multi._key = {};\n                for (var key in Item.multi._keys.authority) {\n                    Item.authority[0].multi._key[key] = {\n                        literal: Item.multi._keys.authority[key]\n                    };\n                }\n            }\n        }\n    }\n    // Add getAbbreviation() call for title-short and container-title-short\n    if (!Item[\"title-short\"]) {\n        Item[\"title-short\"] = Item.shortTitle;\n    }\n    // Add support for main_title_from_short_title\n    if (this.opt.development_extensions.main_title_from_short_title) {\n        var narrowSpaceLocale = this.opt[\"default-locale\"][0].slice(0, 2).toLowerCase() === \"fr\";\n        CSL.extractTitleAndSubtitle.call(this, Item, narrowSpaceLocale);\n    }\n    var isLegalType = [\"bill\",\"legal_case\",\"legislation\",\"gazette\",\"regulation\"].indexOf(Item.type) > -1;\n    if (this.opt.development_extensions.force_jurisdiction && isLegalType) {\n        if (!Item.jurisdiction) {\n            Item.jurisdiction = \"us\";\n        }\n    }\n    var normalizedKey;\n    if (!isLegalType && Item.title && this.sys.getAbbreviation) {\n        var noHints = false;\n        if (!Item.jurisdiction) {\n            noHints = true;\n        }\n        if (this.sys.normalizeAbbrevsKey) {\n             normalizedKey = this.sys.normalizeAbbrevsKey(\"title\", Item.title);\n        } else {\n            normalizedKey = Item.title;\n        }\n        var jurisdiction = this.transform.loadAbbreviation(Item.jurisdiction, \"title\", normalizedKey, Item.language);\n        if (this.transform.abbrevs[jurisdiction].title) {\n            if (this.transform.abbrevs[jurisdiction].title[normalizedKey]) {\n                Item[\"title-short\"] = this.transform.abbrevs[jurisdiction].title[normalizedKey];\n            }\n        }\n    }\n    if (!Item[\"container-title-short\"]) {\n        Item[\"container-title-short\"] = Item.journalAbbreviation;\n    }\n    if (Item[\"container-title\"] && this.sys.getAbbreviation) {\n        if (this.sys.normalizeAbbrevsKey) {\n            normalizedKey = this.sys.normalizeAbbrevsKey(Item[\"container-title\"]);\n        } else {\n            normalizedKey = Item[\"container-title\"];\n        }\n        var jurisdiction = this.transform.loadAbbreviation(Item.jurisdiction, \"container-title\", normalizedKey, Item.language);\n        if (this.transform.abbrevs[jurisdiction][\"container-title\"]) {\n            if (this.transform.abbrevs[jurisdiction][\"container-title\"][normalizedKey]) {\n                Item[\"container-title-short\"] = this.transform.abbrevs[jurisdiction][\"container-title\"][normalizedKey];\n            }\n        }\n    }\n    if (Item.jurisdiction) {\n        Item.country = Item.jurisdiction.split(\":\")[0];\n    }\n    if (this.registry.refhash[id]) {\n        if (JSON.stringify(this.registry.refhash[id]) != JSON.stringify(Item)) {\n            for (var key in this.registry.refhash[id]) {\n                delete this.registry.refhash[id][key];\n            }\n            this.tmp.taintedItemIDs[Item.id] = true;\n            Object.assign(this.registry.refhash[id], Item);\n        }\n    } else {\n        this.registry.refhash[id] = Item;\n    }\n    return this.registry.refhash[id];\n};\n\nCSL.Engine.prototype.refetchItem = function (id) {\n    return this.registry.refhash[id];\n};\n\n// Executed during style build\nCSL.Engine.prototype.setOpt = function (token, name, value) {\n    if (token.name === \"style\" || token.name === \"cslstyle\") {\n        this.opt.inheritedAttributes[name] = value;\n        this.citation.opt.inheritedAttributes[name] = value;\n        this.bibliography.opt.inheritedAttributes[name] = value;\n    } else if ([\"citation\", \"bibliography\"].indexOf(token.name) > -1) {\n        this[token.name].opt.inheritedAttributes[name] = value;\n    } else {\n        token.strings[name] = value;\n    }\n};\n\n// Executed at runtime, since macros can occur in the context of citation or bibliography\nCSL.Engine.prototype.inheritOpt = function (token, attrname, parentname, defaultValue) {\n    if (\"undefined\" !== typeof token.strings[attrname]) {\n        return token.strings[attrname];\n    } else {\n        var parentValue = this[this.tmp.root].opt.inheritedAttributes[parentname ? parentname : attrname];\n        if (\"undefined\" !== typeof parentValue) {\n            return parentValue;\n        } else {\n            return defaultValue;\n        }\n    }\n};\n\nCSL.Engine.prototype.remapSectionVariable = function (inputList) {\n    // We have items with a value in the section field (on Item) that must\n    // be mapped to the locator field (on item). We simply prepend it as\n    // a string here, and handle all parsing of the resulting string\n    // in processNumber(). Plurals and numeric are set in processNumber().\n    \n    // Because the target is in the citation item (lowercase), the\n    // remapping cannot take place when the Item data is received.\n    // Citation provides a list of Item/item pairs, hence the iteration\n    // used here.\n    for (var i = 0, ilen = inputList.length; i < ilen; i += 1) {\n        var Item = inputList[i][0];\n        var item = inputList[i][1];\n\n        if ([\"bill\",\"gazette\",\"legislation\",\"regulation\",\"treaty\"].indexOf(Item.type) > -1) {\n             // If a locator value exists, then\n            //   (a) Leave be an overriding label at the start of the locator field, defaulting to label value\n            if (item.locator) {\n                item.locator = item.locator.trim();\n                var m = item.locator.match(CSL.STATUTE_SUBDIV_PLAIN_REGEX_FRONT);\n                if (!m) {\n                    if (item.label) {\n                        item.locator = CSL.STATUTE_SUBDIV_STRINGS_REVERSE[item.label] + \" \" + item.locator;\n                    } else {\n                        item.locator = \"p. \" + item.locator;\n                    }\n                }\n            }\n            // If a section value exists, then\n            //   (a) Apply an overriding label at the start of the section field, defaulting to sec.\n            var sectionMasterLabel = null;\n            if (Item.section) {\n                Item.section = Item.section.trim();\n                var m = Item.section.match(CSL.STATUTE_SUBDIV_PLAIN_REGEX_FRONT);\n                if (!m) {\n                    Item.section = \"sec. \" + Item.section;\n                    sectionMasterLabel = \"sec.\";\n                } else {\n                    sectionMasterLabel = m[0].trim();\n                }\n            }\n            // If section is nil, then\n            //   (a) Do nothing\n            if (Item.section) {\n            // If section exists and locator is nil\n            //   (a) Set section string in locator field\n                if (!item.locator) {\n                    item.locator = Item.section;\n                } else {\n            // If both section and locator exist, then\n            //   (a) If locator starts with p., remove p., merge with space or no-space, and set in locator field\n            //   (b) If locator starts with non-p., prepend section value to locator with space, and set in locator field\n                    var m = item.locator.match(/^([^ ]*)\\s*(.*)/);\n                    var space = \" \";\n                    if (m) {\n                        if (m[1] === \"p.\" && sectionMasterLabel !== \"p.\") {\n                            item.locator = m[2];\n                        }\n                        if ([\"[\", \"(\", \".\", \",\", \";\", \":\", \"?\"].indexOf(item.locator.slice(0, 1)) > -1) {\n                            space = \"\";\n                        }\n                    } else {\n                       space = \"\"; \n                    }\n                    item.locator = Item.section + space + item.locator;\n                }\n                //Item.section = \"\";\n            }\n            item.label = \"\";\n            // And that's it. Pre-parse complete.\n        }\n    }\n};\n\n\nCSL.Engine.prototype.setNumberLabels = function (Item) {\n     if (Item.number\n        && [\"bill\", \"gazette\", \"legislation\",\"regulation\",\"treaty\"].indexOf(Item.type) > -1\n        && this.opt.development_extensions.consolidate_legal_items\n        && !this.tmp.shadow_numbers[\"number\"]) {\n\n        this.tmp.shadow_numbers[\"number\"] = {};\n        this.tmp.shadow_numbers[\"number\"].values = [];\n        this.tmp.shadow_numbers[\"number\"].plural = 0;\n        this.tmp.shadow_numbers[\"number\"].numeric = false;\n        this.tmp.shadow_numbers[\"number\"].label = false;\n        \n        // Labels embedded in number variable\n        var value = \"\" + Item.number;\n        value = value.split(\"\\\\\").join(\"\");\n        // Get first word, parse out labels only if it parses\n        var firstword = value.split(/\\s+/)[0];\n        var firstlabel = CSL.STATUTE_SUBDIV_STRINGS[firstword];\n        if (firstlabel) {\n            // Get list and match\n            var splt = value.split(CSL.STATUTE_SUBDIV_PLAIN_REGEX);\n            if (splt.length > 1) {\n                // Convert matches to localized form\n                var lst = [];\n                for (var j=1, jlen=splt.length; j < jlen; j += 1) {\n                    lst.push(splt[j].replace(/\\s*$/, \"\").replace(/^\\s*/, \"\"));\n                }\n                // Preemptively save to shadow_numbers\n                value = lst.join(\" \");\n            } else {\n                value = splt[0];\n            }\n            this.tmp.shadow_numbers[\"number\"].label = firstlabel;\n            this.tmp.shadow_numbers[\"number\"].values.push([\"Blob\", value, false]);\n            this.tmp.shadow_numbers[\"number\"].numeric = false;\n        } else {\n            this.tmp.shadow_numbers[\"number\"].values.push([\"Blob\", value, false]);\n            this.tmp.shadow_numbers[\"number\"].numeric = true;\n        }\n    }\n};\n\n/*global CSL: true */\n\nCSL.substituteOne = function (template) {\n    return function (state, list) {\n        if (!list) {\n            return \"\";\n        } else {\n            // (\"string\" === typeof list)\n            return template.replace(\"%%STRING%%\", list);\n        }\n    };\n};\n\n\n/**\n * Two-tiered substitutions gadget.\n * <p>This is used for\n * options like (now defunct) \"font-family\", where the option value\n * cannot be determined until the attribute is processed.\n * Need for this function might be reviewed at some point ...</p>\n * @param {String} template A template containing\n * <code>%%STRING%%</code> and <code>%%PARAM%%</code>\n * placeholders.  See {@link CSL.Output.Formats.html} for\n * examples.\n */\nCSL.substituteTwo = function (template) {\n    return function (param) {\n        var template2 = template.replace(\"%%PARAM%%\", param);\n        return function (state, list) {\n            if (!list) {\n                return \"\";\n            } else {\n                //(\"string\" === typeof list){\n                return template2.replace(\"%%STRING%%\", list);\n            }\n        };\n    };\n};\n\n/**\n * Generate string functions for designated output mode.\n * <p>Only \"html\" (the default) is supported at present.</p>\n * @param {String} mode Either \"html\" or \"rtf\", eventually.\n */\nCSL.Mode = function (mode) {\n    var decorations, params, param, func, val, args;\n    decorations = {};\n    params = CSL.Output.Formats[mode];\n    for (param in params) {\n        if (true) {\n\n            if (\"@\" !== param.slice(0, 1)) {\n                decorations[param] = params[param];\n                continue;\n            }\n            func = false;\n            val = params[param];\n            args = param.split('/');\n\n            if (typeof val === \"string\" && val.indexOf(\"%%STRING%%\") > -1)  {\n                if (val.indexOf(\"%%PARAM%%\") > -1) {\n                    func = CSL.substituteTwo(val);\n                } else {\n                    func = CSL.substituteOne(val);\n                }\n            } else if (typeof val === \"boolean\" && !val) {\n                func = CSL.Output.Formatters.passthrough;\n            } else if (typeof val === \"function\") {\n                func = val;\n            } else {\n                CSL.error(\"Bad \" + mode + \" config entry for \" + param + \": \" + val);\n            }\n\n            if (args.length === 1) {\n                decorations[args[0]] = func;\n            } else if (args.length === 2) {\n                if (!decorations[args[0]]) {\n                    decorations[args[0]] = {};\n                }\n                decorations[args[0]][args[1]] = func;\n            }\n        }\n    }\n    return decorations;\n};\n\n\n/**\n * Generate a separate list of formatting attributes.\n * <p>This generates a list of tuples containing attribute\n * information relevant to output formatting, in the order\n * fixed in the constant {@link CSL.FORMAT_KEY_SEQUENCE}.\n * This function is called during {@link CSL.Core.Build}.\n * Formatting hints are distilled to functions\n * later, in the second compilation pass ({@link CSL.Core.Configure}).</p>\n * @param {Object} state The state object returned by\n * {@link CSL.Engine}.\n * @param {Object} attributes The hash object containing\n * the attributes and values extracted from an XML node.\n */\nCSL.setDecorations = function (state, attributes) {\n    var ret, key, pos;\n    // This applies a fixed processing sequence\n    ret = [];\n    for (pos in CSL.FORMAT_KEY_SEQUENCE) {\n        if (true) {\n            var key = CSL.FORMAT_KEY_SEQUENCE[pos];\n            if (attributes[key]) {\n                ret.push([key, attributes[key]]);\n                delete attributes[key];\n            }\n        }\n    }\n    return ret;\n};\n\nCSL.Doppeler = function(rexStr, stringMangler) {\n    var matchRex = new RegExp(\"(\" + rexStr + \")\", \"g\");\n    var splitRex = new RegExp(rexStr, \"g\");\n    this.split = function (str) {\n        // Normalize markup\n        if (stringMangler) {\n            str = stringMangler(str);\n        }\n        var match = str.match(matchRex);\n        if (!match) {\n            return {\n                tags: [],\n                strings: [str]\n            };\n        }\n        var split = str.split(splitRex);\n        for (var i=match.length-1; i> -1; i--) {\n            if (typeof match[i] === \"number\") {\n                match[i] = \"\";\n            }\n            var tag = match[i];\n            if (tag === \"\\'\" && split[i+1].length > 0) {\n                // Fixes https://forums.zotero.org/discussion/comment/294317\n                split[i+1] = match[i] + split[i+1];\n                match[i] = \"\";\n            }\n        }\n        return {\n            tags: match,\n            strings: split,\n            origStrings: split.slice()\n        };\n    };\n    this.join = function (obj) {\n        var lst = obj.strings.slice(-1);\n        for (var i=obj.tags.length-1; i>-1; i--) {\n            lst.push(obj.tags[i]);\n            lst.push(obj.strings[i]);\n        }\n        lst.reverse();\n        return lst.join(\"\");\n    };\n};\n\nCSL.Engine.prototype.normalDecorIsOrphan = function (blob, params) {\n    //print(\"params: \"+JSON.stringify(params));\n    if (params[1] === \"normal\") {\n        var use_param = false;\n        var all_the_decor;\n        if (this.tmp.area === \"citation\") {\n            all_the_decor = [this.citation.opt.layout_decorations].concat(blob.alldecor);\n        } else {\n            all_the_decor = blob.alldecor;\n        }\n        for (var k = all_the_decor.length - 1; k > -1; k += -1) {\n            //print(\"  all decor: \"+JSON.stringify(all_the_decor[k]));\n            for (var n = all_the_decor[k].length - 1; n > -1; n += -1) {\n                //print(\"  superior param\"+n+\": \"+all_the_decor[k][n][0]);\n                if (all_the_decor[k][n][0] === params[0]) {\n                    //print(\"  HIT!\");\n                    if (all_the_decor[k][n][1] !== \"normal\") {\n                        use_param = true;\n                    }\n                }\n            }\n        }\n        if (!use_param) {\n            return true;\n        }\n    }\n    return false;\n};\n\n/*global CSL: true */\n\n\nCSL.Engine.prototype.getCitationLabel = function (Item) {\n    var label = \"\";\n    var params = this.getTrigraphParams();\n    var config = params[0];\n    var myname = this.getTerm(\"reference\", \"short\", 0);\n    if (\"undefined\" === typeof myname) {\n        myname = \"reference\";\n    }\n    myname = myname.replace(\".\", \"\");\n    myname = myname.slice(0, 1).toUpperCase() + myname.slice(1);\n    for (var i = 0, ilen = CSL.NAME_VARIABLES.length; i < ilen; i += 1) {\n        var n = CSL.NAME_VARIABLES[i];\n        if (Item[n]) {\n            var names = Item[n];\n            if (names.length > params.length) {\n                config = params[params.length - 1];\n            } else {\n                config = params[names.length - 1];\n            }\n            for (var j = 0, jlen = names.length; j < jlen; j += 1) {\n                if (j === config.authors.length) {\n                    break;\n                }\n                var res = this.nameOutput.getName(names[j], \"locale-translit\", true);\n                var name = res.name;\n                if (name && name.family) {\n                    myname = name.family;\n                    myname = myname.replace(/^([ \\'\\u2019a-z]+\\s+)/, \"\");\n\n                } else if (name && name.literal) {\n                    myname = name.literal;\n                }\n                var m = myname.toLowerCase().match(/^(a\\s+|the\\s+|an\\s+)/);\n                if (m) {\n                    myname = myname.slice(m[1].length);\n                }\n                myname = myname.replace(CSL.ROMANESQUE_NOT_REGEXP, \"\");\n                if (!myname) {\n                    break;\n                }\n                myname = myname.slice(0, config.authors[j]);\n                if (myname.length > 1) {\n                    myname = myname.slice(0, 1).toUpperCase() + myname.slice(1).toLowerCase();\n                } else if (myname.length === 1) {\n                    myname = myname.toUpperCase();\n                }\n                label += myname;\n            }\n            break;\n        }\n    }\n    if (!label) {\n        // Try for something using title\n        if (Item.title) {\n            var skipWords = this.locale[this.opt.lang].opts[\"skip-words\"];\n            var lst = Item.title.split(/\\s+/);\n            for (var i = lst.length - 1; i > -1; i--) {\n                if (skipWords.indexOf(lst[i]) > -1) {\n                    lst = lst.slice(0, i).concat(lst.slice(i + 1));\n                }\n            }\n            var str = lst.join('');\n            str = str.slice(0, params[0].authors[0]);\n            if (str.length > 1) {\n                str = str.slice(0, 1).toUpperCase() + str.slice(1).toLowerCase();\n            } else if (str.length === 1) {\n                str = str.toUpperCase();\n            }\n            label = str;\n        }\n    }\n    var year = \"0000\";\n    if (Item.issued) {\n        if (Item.issued.year) {\n            year = \"\" + Item.issued.year;\n        }\n    }\n    year = year.slice((config.year * -1));\n    label = label + year;\n    return label;\n};\n\nCSL.Engine.prototype.getTrigraphParams = function () {\n    var params = [];\n    var ilst = this.opt.trigraph.split(\":\");\n    if (!this.opt.trigraph || this.opt.trigraph.slice(0,1) !== \"A\") {\n        CSL.error(\"Bad trigraph definition: \"+this.opt.trigraph);\n    }\n    for (var i = 0, ilen = ilst.length; i < ilen; i += 1) {\n        var str = ilst[i];\n        var config = {authors:[], year:0};\n        for (var j = 0, jlen = str.length; j < jlen; j += 1) {\n            switch (str.slice(j,j+1)) {\n            case \"A\":\n                config.authors.push(1);\n                break;\n            case \"a\":\n                config.authors[config.authors.length - 1] += 1;\n                break;\n            case \"0\":\n                config.year += 1;\n                break;\n            default:\n                CSL.error(\"Invalid character in trigraph definition: \"+this.opt.trigraph);\n            }\n        }\n        params.push(config);\n    }\n    return params;\n};\n\n/*global CSL: true */\n\nCSL.Engine.prototype.setOutputFormat = function (mode) {\n    this.opt.mode = mode;\n    this.fun.decorate = CSL.Mode(mode);\n    if (!this.output[mode]) {\n        this.output[mode] = {};\n        this.output[mode].tmp = {};\n    }\n};\n\nCSL.Engine.prototype.getSortFunc = function () {\n    return function (a,b) {\n        a = a.split(\"-\");\n        b = b.split(\"-\");\n        if (a.length < b.length) {\n            return 1;\n        } else if (a.length > b.length) {\n            return -1;\n        } else {\n            a = a.slice(-1)[0];\n            b = b.slice(-1)[0];\n            if (a.length < b.length) {\n                return 1;\n            } else if (a.length > b.length) {\n                return -1;\n            } else {\n                return 0;\n            }\n        }\n    };\n};\n\nCSL.Engine.prototype.setLangTagsForCslSort = function (tags) {\n    var i, ilen;\n    if (tags) {\n        this.opt['locale-sort'] = [];\n        for (i = 0, ilen = tags.length; i < ilen; i += 1) {\n            this.opt['locale-sort'].push(tags[i]);\n        }\n    }\n    this.opt['locale-sort'].sort(this.getSortFunc());\n};\n    \nCSL.Engine.prototype.setLangTagsForCslTransliteration = function (tags) {\n    var i, ilen;\n    this.opt['locale-translit'] = [];\n    if (tags) {\n        for (i = 0, ilen = tags.length; i < ilen; i += 1) {\n            this.opt['locale-translit'].push(tags[i]);\n        }\n    }\n    this.opt['locale-translit'].sort(this.getSortFunc());\n};\n    \nCSL.Engine.prototype.setLangTagsForCslTranslation = function (tags) {\n    var i, ilen;\n    this.opt['locale-translat'] = [];\n    if (tags) {\n        for (i = 0, ilen = tags.length; i < ilen; i += 1) {\n            this.opt['locale-translat'].push(tags[i]);\n        }\n    }\n    this.opt['locale-translat'].sort(this.getSortFunc());\n};\n\nCSL.Engine.prototype.setLangPrefsForCites = function (obj, conv) {\n    var opt = this.opt['cite-lang-prefs'];\n    if (!conv) {\n        conv = function (key) {\n            return key.toLowerCase();\n        };\n    }\n    var segments = ['Persons', 'Institutions', 'Titles', 'Journals', 'Publishers', 'Places'];\n    // Set values in place\n    for (var i = 0, ilen = segments.length; i < ilen; i += 1) {\n        var clientSegment = conv(segments[i]);\n        var citeprocSegment = segments[i].toLowerCase();\n        if (!obj[clientSegment]) {\n            continue;\n        }\n        //\n        // Normalize the sequence of secondary and tertiary\n        // in the provided obj segment list.\n        //\n        var supplements = [];\n        while (obj[clientSegment].length > 1) {\n            supplements.push(obj[clientSegment].pop());\n        }\n        var sortval = {orig:1,translit:2,translat:3};\n        if (supplements.length === 2 && sortval[supplements[0]] < sortval[supplements[1]]) {\n            supplements.reverse();\n        }\n        while (supplements.length) {\n            obj[clientSegment].push(supplements.pop());\n        }\n        //\n        // normalization done.\n        //\n        var lst = opt[citeprocSegment];\n        while (lst.length) {\n            lst.pop();\n        }\n        for (var j = 0, jlen = obj[clientSegment].length; j < jlen; j += 1) {\n            lst.push(obj[clientSegment][j]);\n        }\n    }\n};\n\nCSL.Engine.prototype.setLangPrefsForCiteAffixes = function (affixList) {\n    if (affixList && affixList.length === 48) {\n        var affixes = this.opt.citeAffixes;\n        var count = 0;\n        var settings = [\"persons\", \"institutions\", \"titles\", \"journals\", \"publishers\", \"places\"];\n        var forms = [\"translit\", \"orig\", \"translit\", \"translat\"];\n        var value;\n        for (var i = 0, ilen = settings.length; i < ilen; i += 1) {\n            for (var j = 0, jlen = forms.length; j < jlen; j += 1) {\n                value = \"\";\n                if ((count % 8) === 4) {\n                    if (!affixes[settings[i]][\"locale-\"+forms[j]].prefix\n                        && !affixes[settings[i]][\"locale-\"+forms[j]].suffix) {\n\n                        value = affixList[count] ? affixList[count] : \"\";\n                        affixes[settings[i]][\"locale-\" + forms[j]].prefix = value;\n                        value = affixList[count] ? affixList[count + 1] : \"\";\n                        affixes[settings[i]][\"locale-\" + forms[j]].suffix = value;\n                    }\n                } else {\n                    value = affixList[count] ? affixList[count] : \"\";\n                    affixes[settings[i]][\"locale-\" + forms[j]].prefix = value;\n                    value = affixList[count] ? affixList[count + 1] : \"\";\n                    affixes[settings[i]][\"locale-\" + forms[j]].suffix = value;\n                }\n                count += 2;\n            }\n        }\n        this.opt.citeAffixes = affixes;\n    }\n};\n\nCSL.Engine.prototype.setAutoVietnameseNamesOption = function (arg) {\n    if (arg) {\n        this.opt[\"auto-vietnamese-names\"] = true;\n    } else {\n        this.opt[\"auto-vietnamese-names\"] = false;\n    }\n};\n\nCSL.Engine.prototype.setAbbreviations = function (arg) {\n    if (this.sys.setAbbreviations) {\n        this.sys.setAbbreviations(arg);\n    }\n};\n\nCSL.Engine.prototype.setSuppressTrailingPunctuation = function (arg) {\n    this.citation.opt.suppressTrailingPunctuation = !!arg;\n};\n\n/*global CSL: true */\n\nCSL.Output = {};\n/**\n * Output queue object.\n * @class\n */\nCSL.Output.Queue = function (state) {\n    this.levelname = [\"top\"];\n    this.state = state;\n    this.queue = [];\n    this.empty = new CSL.Token(\"empty\");\n    var tokenstore = {};\n    tokenstore.empty = this.empty;\n    this.formats = new CSL.Stack(tokenstore);\n    this.current = new CSL.Stack(this.queue);\n};\n\n// XXX This works, but causes a mismatch in api_cite\n// Could insert a placeholder\n// Better to have a function that spits out an independent blob.\n// Is that possible though?\n// Okay. Use queue.append() with fake_queue instead.\nCSL.Output.Queue.prototype.pop = function () {\n    // For some reason, state.output.current.value() here can be an array, \n    // not a blob ... ?\n    var drip = this.current.value();\n    if (drip.length) {\n        return drip.pop();\n    } else {\n        return drip.blobs.pop();\n    }\n};\n\nCSL.Output.Queue.prototype.getToken = function (name) {\n    var ret = this.formats.value()[name];\n    return ret;\n};\n\nCSL.Output.Queue.prototype.mergeTokenStrings = function (base, modifier) {\n    var base_token, modifier_token, ret, key;\n    base_token = this.formats.value()[base];\n    modifier_token = this.formats.value()[modifier];\n    ret = base_token;\n    if (modifier_token) {\n        if (!base_token) {\n            base_token = new CSL.Token(base, CSL.SINGLETON);\n            base_token.decorations = [];\n        }\n        ret = new CSL.Token(base, CSL.SINGLETON);\n        var key = \"\";\n        for (var key in base_token.strings) {\n            if (base_token.strings.hasOwnProperty(key)) {\n                ret.strings[key] = base_token.strings[key];\n            }\n        }\n        for (var key in modifier_token.strings) {\n            if (modifier_token.strings.hasOwnProperty(key)) {\n                ret.strings[key] = modifier_token.strings[key];\n            }\n        }\n        ret.decorations = base_token.decorations.concat(modifier_token.decorations);\n    }\n    return ret;\n};\n\n// Store a new output format token based on another\nCSL.Output.Queue.prototype.addToken = function (name, modifier, token) {\n    var newtok, attr;\n    newtok = new CSL.Token(\"output\");\n    if (\"string\" === typeof token) {\n        token = this.formats.value()[token];\n    }\n    if (token && token.strings) {\n        for (attr in token.strings) {\n            if (token.strings.hasOwnProperty(attr)) {\n                newtok.strings[attr] = token.strings[attr];\n            }\n        }\n        newtok.decorations = token.decorations;\n\n    }\n    if (\"string\" === typeof modifier) {\n        newtok.strings.delimiter = modifier;\n    }\n    this.formats.value()[name] = newtok;\n};\n\n//\n// newFormat adds a new bundle of formatting tokens to\n// the queue's internal stack of such bundles\nCSL.Output.Queue.prototype.pushFormats = function (tokenstore) {\n    if (!tokenstore) {\n        tokenstore = {};\n    }\n    tokenstore.empty = this.empty;\n    this.formats.push(tokenstore);\n};\n\n\nCSL.Output.Queue.prototype.popFormats = function () {\n    this.formats.pop();\n};\n\nCSL.Output.Queue.prototype.startTag = function (name, token) {\n    var tokenstore = {};\n    if (this.state.tmp[\"doing-macro-with-date\"] && this.state.tmp.extension) {\n        token = this.empty;\n        name = \"empty\";\n    }\n    tokenstore[name] = token;\n    this.pushFormats(tokenstore);\n    this.openLevel(name);\n};\n\nCSL.Output.Queue.prototype.endTag = function (name) {\n    this.closeLevel(name);\n    this.popFormats();\n};\n\n//\n// newlevel adds a new blob object to the end of the current\n// list, and adjusts the current pointer so that subsequent\n// appends are made to blob list of the new object.\n\nCSL.Output.Queue.prototype.openLevel = function (token) {\n    var blob, curr;\n    if (\"object\" === typeof token) {\n        // delimiter, prefix, suffix, decorations from token\n        blob = new CSL.Blob(undefined, token);\n    } else if (\"undefined\" === typeof token) {\n        blob = new CSL.Blob(undefined, this.formats.value().empty, \"empty\");\n    } else {\n        if (!this.formats.value() || !this.formats.value()[token]) {\n            CSL.error(\"CSL processor error: call to nonexistent format token \\\"\" + token + \"\\\"\");\n        }\n        // delimiter, prefix, suffix, decorations from token\n        blob = new CSL.Blob(undefined, this.formats.value()[token], token);\n    }\n    curr = this.current.value();\n    if (!this.state.tmp.just_looking && this.checkNestedBrace) {\n        blob.strings.prefix = this.checkNestedBrace.update(blob.strings.prefix);\n    }\n    curr.push(blob);\n    this.current.push(blob);\n};\n\n/**\n * \"merge\" used to be real complicated, now it's real simple.\n */\nCSL.Output.Queue.prototype.closeLevel = function (name) {\n    // CLEANUP: Okay, so this.current.value() holds the blob at the\n    // end of the current list.  This is wrong.  It should\n    // be the parent, so that we have  the choice of reading\n    // the affixes and decorations, or appending to its\n    // content.  The code that manipulates blobs will be\n    // much simpler that way.\n    if (name && name !== this.current.value().levelname) {\n        CSL.error(\"Level mismatch error:  wanted \" + name + \" but found \" + this.current.value().levelname);\n    }\n    var blob = this.current.pop();\n    if (!this.state.tmp.just_looking && this.checkNestedBrace) {\n        blob.strings.suffix = this.checkNestedBrace.update(blob.strings.suffix);\n    }\n};\n\n//\n// append does the same thing as newlevel, except\n// that the blob it pushes has text content,\n// and the current pointer is not moved after the push.\n\nCSL.Output.Queue.prototype.append = function (str, tokname, notSerious, ignorePredecessor, noStripPeriods) {\n    var token, blob, curr;\n    var useblob = true;\n    if (notSerious) {\n        ignorePredecessor = true;\n    }\n    // XXXXX Nasty workaround, but still an improvement\n    // over the reverse calls to the cs:date node build\n    // function that we had before.\n    if (this.state.tmp[\"doing-macro-with-date\"] && !notSerious) {\n        if (tokname !== \"macro-with-date\") {\n            return false;\n        }\n        if (tokname === \"macro-with-date\") {\n            tokname = \"empty\";\n        }\n    }\n    if (\"undefined\" === typeof str) {\n        return false;\n    }\n    if (\"number\" === typeof str) {\n        str = \"\" + str;\n    }\n    if (!notSerious \n        && this.state.tmp.element_trace \n        && this.state.tmp.element_trace.value() === \"suppress-me\") {\n        \n        return false;\n    }\n    blob = false;\n    if (!tokname) {\n        token = this.formats.value().empty;\n    } else if (tokname === \"literal\") {\n        token = true;\n        useblob = false;\n    } else if (\"string\" === typeof tokname) {\n        token = this.formats.value()[tokname];\n    } else {\n        token = tokname;\n    }\n    if (!token) {\n        CSL.error(\"CSL processor error: unknown format token name: \" + tokname);\n    }\n    // Unset delimiters must be left undefined until they reach the queue\n    // in order to discriminate unset from explicitly empty delimiters\n    // when inheriting a default value from a superior node. [??? really ???]\n    if (token.strings && \"undefined\" === typeof token.strings.delimiter) {\n        token.strings.delimiter = \"\";\n    }\n    if (\"string\" === typeof str && str.length) {\n\n        // Source (;?!»«): http://en.wikipedia.org/wiki/Space_(punctuation)#Breaking_and_non-breaking_spaces\n        // Source (:): http://forums.zotero.org/discussion/4933/localized-quotes/#Comment_88384\n        str = str.replace(/ ([:;?!\\u00bb])/g, \"\\u202f$1\").replace(/\\u00ab /g, \"\\u00ab\\u202f\");\n\n        this.last_char_rendered = str.slice(-1);\n        // This, and not the str argument below on flipflop, is the\n        // source of the flipflopper string source.\n        str = str.replace(/\\s+'/g, \" \\'\");\n        if (!notSerious) {\n            // this condition for sort_LeadingApostropheOnNameParticle\n            str = str.replace(/^'/g, \" \\'\");\n        }\n\n        // signal whether we end with terminal punctuation?\n        if (!ignorePredecessor) {\n            this.state.tmp.term_predecessor = true;\n            this.state.tmp.in_cite_predecessor = true;\n        } else if (notSerious) {\n            this.state.tmp.term_predecessor_name = true;\n        }\n    }\n    blob = new CSL.Blob(str, token);\n    curr = this.current.value();\n    if (\"undefined\" === typeof curr && this.current.mystack.length === 0) {\n        // XXXX An operation like this is missing somewhere, this should NOT be necessary.\n        // Addresses error triggered in multi-layouts.\n        this.current.mystack.push([]);\n        curr = this.current.value();\n    }\n    if (\"string\" === typeof blob.blobs) {\n        if (!ignorePredecessor) {\n            this.state.tmp.term_predecessor = true;\n            this.state.tmp.in_cite_predecessor = true;\n        } else if (notSerious) {\n            this.state.tmp.term_predecessor_name = true;\n        }\n    }\n    //\n    // Caution: The parallel detection machinery will blow up if tracking\n    // variables are not properly initialized elsewhere.\n    //\n    if (\"string\" === typeof str) {\n        if (\"string\" === typeof blob.blobs) {\n            if (blob.blobs.slice(0, 1) !== \" \") {\n                var blobPrefix = \"\";\n                var blobBlobs = blob.blobs;\n                while (CSL.TERMINAL_PUNCTUATION.indexOf(blobBlobs.slice(0, 1)) > -1) {\n                    blobPrefix = blobPrefix + blobBlobs.slice(0, 1);\n                    blobBlobs = blobBlobs.slice(1);\n                }\n                if (blobBlobs && blobPrefix) {\n                    blob.strings.prefix = blob.strings.prefix + blobPrefix;\n                    blob.blobs = blobBlobs;\n                }\n            }\n        }\n        if (blob.strings[\"text-case\"]) {\n            //\n            // This one is _particularly_ hard to follow.  It's not obvious,\n            // but the blob already contains the input string at this\n            // point, as blob.blobs -- it's a terminal node, as it were.\n            // The str variable also contains the input string, but\n            // that copy is not used for onward processing.  We have to\n            // apply our changes to the blob copy.\n            //\n            blob.blobs = CSL.Output.Formatters[blob.strings[\"text-case\"]](this.state, str);\n        }\n        if (this.state.tmp.strip_periods && !noStripPeriods) {\n            blob.blobs = blob.blobs.replace(/\\.([^a-z]|$)/g, \"$1\");\n        }\n        for (var i = blob.decorations.length - 1; i > -1; i += -1) {\n            if (blob.decorations[i][0] === \"@quotes\" && blob.decorations[i][1] !== \"false\") {\n                blob.punctuation_in_quote = this.state.getOpt(\"punctuation-in-quote\");\n            }\n            if (!blob.blobs.match(CSL.ROMANESQUE_REGEXP)) {\n                if (blob.decorations[i][0] === \"@font-style\") {\n                    blob.decorations = blob.decorations.slice(0, i).concat(blob.decorations.slice(i + 1));\n                }\n            }\n        }\n        //\n        // XXX: Beware superfluous code in your code.  str in this\n        // case is not the source of the final rendered string.\n        // See note above.\n        //\n        curr.push(blob);\n        this.state.fun.flipflopper.processTags(blob);\n    } else if (useblob) {\n        curr.push(blob);\n    } else {\n        curr.push(str);\n    }\n    return true;\n};\n\nCSL.Output.Queue.prototype.string = function (state, myblobs, blob) {\n    var i, ilen, j, jlen, b;\n    //if (blob && blob.strings.delimiter) {\n    //    print(\"DELIMITER: \"+blob.strings.delimiter+\" on \"+[x.blobs[0].num for each (x in myblobs)]);\n    //}\n    //var blobs, ret, blob_delimiter, i, params, blobjr, last_str, last_char, b, use_suffix, qres, addtoret, span_split, j, res, blobs_start, blobs_end, key, pos, len, ppos, llen, ttype, ltype, terminal, leading, delimiters, use_prefix, txt_esc;\n    var txt_esc = CSL.getSafeEscape(this.state);\n    var blobs = myblobs.slice();\n    var ret = [];\n    \n    if (blobs.length === 0) {\n        return ret;\n    }\n\n    var blob_delimiter = \"\";\n    if (blob) {\n        blob_delimiter = blob.strings.delimiter;\n    } else {\n        //print(\"=== Setting false to start ===\");\n        state.tmp.count_offset_characters = false;\n        state.tmp.offset_characters = 0;\n    }\n\n    if (blob && blob.new_locale) {\n        blob.old_locale = state.opt.lang;\n        state.opt.lang = blob.new_locale;\n    }\n\n    var blobjr, use_suffix, use_prefix, params;\n    for (var i = 0, ilen = blobs.length; i < ilen; i += 1) {\n        blobjr = blobs[i];\n\n        if (blobjr.strings.first_blob) {\n            // Being the Item.id of the the entry being rendered.\n            //print(\"  -- turning on counting\");\n            state.tmp.count_offset_characters = blobjr.strings.first_blob;\n        }\n\n        if (\"string\" === typeof blobjr.blobs) {\n            if (\"number\" === typeof blobjr.num) {\n                ret.push(blobjr);\n            } else if (blobjr.blobs) {\n                if (blobjr.particle) {\n                    blobjr.blobs = blobjr.particle + blobjr.blobs;\n                    blobjr.particle = \"\";\n                }\n                // (skips empty strings)\n                //b = txt_esc(blobjr.blobs);\n                b = txt_esc(blobjr.blobs);\n                var blen = b.length;\n\n                if (!state.tmp.suppress_decorations) {\n                    for (j = 0, jlen = blobjr.decorations.length; j < jlen; j += 1) {\n                        params = blobjr.decorations[j];\n                        if (params[0] === \"@showid\") {\n                            continue;\n                        }\n                        if (state.normalDecorIsOrphan(blobjr, params)) {\n                            continue;\n                        }\n                        b = state.fun.decorate[params[0]][params[1]].call(blobjr, state, b, params[2]);\n                    }\n                }\n                //\n                // because we will rip out portions of the output\n                // queue before rendering, group wrappers need\n                // to produce no output if they are found to be\n                // empty.\n                if (b && b.length) {\n                    b = txt_esc(blobjr.strings.prefix) + b + txt_esc(blobjr.strings.suffix);\n                    if (state.opt.development_extensions.csl_reverse_lookup_support && !state.tmp.suppress_decorations) {\n                        for (j = 0, jlen = blobjr.decorations.length; j < jlen; j += 1) {\n                            params = blobjr.decorations[j];\n\n                            if (params[0] === \"@showid\") {\n                                b = state.fun.decorate[params[0]][params[1]].call(blobjr, state, b, params[2]);\n                            }\n                        }\n                    }\n                    ret.push(b);\n                    if (state.tmp.count_offset_characters) {\n                        state.tmp.offset_characters += (blen + blobjr.strings.suffix.length + blobjr.strings.prefix.length);\n                    }\n                }\n            }\n        } else if (blobjr.blobs.length) {\n            var addtoret = state.output.string(state, blobjr.blobs, blobjr);\n            if (blob) {\n                // Patch up world-class weird bug in the ill-constructed code of mine.\n                if (\"string\" !== addtoret && addtoret.length > 1 && blobjr.strings.delimiter) {\n                    var numberSeen = false;\n                    for (var j=0,jlen=addtoret.length;j<jlen;j++) {\n                        if (\"string\" !== typeof addtoret[j]) {\n                            numberSeen = true;\n                        } else if (numberSeen) {\n                            addtoret[j] = (blobjr.strings.delimiter + addtoret[j]);\n                        }\n                    }\n                }\n            }\n            ret = ret.concat(addtoret);\n        }\n        if (blobjr.strings.first_blob && state.registry.registry[blobjr.strings.first_blob]) {\n            // The Item.id of the entry being rendered.\n            state.registry.registry[blobjr.strings.first_blob].offset = state.tmp.offset_characters;\n            state.tmp.count_offset_characters = false;\n        }\n    }\n\n    // Provide delimiters on adjacent numeric blobs\n    for (i=0,ilen=ret.length - 1;i<ilen;i+=1) {\n        if (\"number\" === typeof ret[i].num && \"number\" === typeof ret[i+1].num && !ret[i+1].UGLY_DELIMITER_SUPPRESS_HACK) {\n            // XXX watch this\n            ret[i].strings.suffix = ret[i].strings.suffix + (blob_delimiter ? blob_delimiter : \"\");\n            ret[i+1].successor_prefix = \"\";\n            ret[i+1].UGLY_DELIMITER_SUPPRESS_HACK = true;\n        }\n    }\n\n    var span_split = 0;\n    for (var i = 0, ilen = ret.length; i < ilen; i += 1) {\n        if (\"string\" === typeof ret[i]) {\n            span_split = (parseInt(i, 10) + 1);\n            if (i < ret.length - 1  && \"object\" === typeof ret[i + 1]) {\n                if (blob_delimiter && !ret[i + 1].UGLY_DELIMITER_SUPPRESS_HACK) {\n                    ret[i] += txt_esc(blob_delimiter);\n                }\n                // One bite of the apple\n                ret[i + 1].UGLY_DELIMITER_SUPPRESS_HACK = true;\n            }\n            //span_split = ret.length;\n            //print(\"XXX ret: \"+ret+\" -- \"+blob_delimiter);\n        }\n    }\n/*\n    if (blob && (blob.decorations.length || blob.strings.suffix || blob.strings.prefix)) {\n        span_split = ret.length;\n    }\n*/\n    if (blob && (blob.decorations.length || blob.strings.suffix)) {\n        span_split = ret.length;\n    } else if (blob && blob.strings.prefix) {\n        for (var i=0,ilen=ret.length;i<ilen;i++) {\n            if (\"undefined\" !== typeof ret[i].num) {\n                span_split = i;\n                if (i === 0) {\n                    ret[i].strings.prefix = blob.strings.prefix + ret[i].strings.prefix;\n                }\n                break;\n            }\n        }\n    }\n\n    var blobs_start = state.output.renderBlobs(ret.slice(0, span_split), blob_delimiter, false, blob);\n    if (blobs_start && blob && (blob.decorations.length || blob.strings.suffix || blob.strings.prefix)) {\n        if (!state.tmp.suppress_decorations) {\n            for (var i = 0, ilen = blob.decorations.length; i < ilen; i += 1) {\n                params = blob.decorations[i];\n                if ([\"@cite\",\"@bibliography\", \"@display\", \"@showid\"].indexOf(params[0]) > -1) {\n                    continue;\n                }\n                if (state.normalDecorIsOrphan(blobjr, params)) {\n                    continue;\n                }\n                if (!params[0]) continue;\n                if (\"string\" === typeof blobs_start) {\n                    blobs_start = state.fun.decorate[params[0]][params[1]].call(blob, state, blobs_start, params[2]);\n                }\n            }\n        }\n        //\n        // XXXX: cut-and-paste warning.  same as a code block above.\n        //\n        b = blobs_start;\n        use_suffix = blob.strings.suffix;\n        if (b && b.length) {\n            use_prefix = blob.strings.prefix;\n            b = txt_esc(use_prefix) + b + txt_esc(use_suffix);\n            if (state.tmp.count_offset_characters) {\n                state.tmp.offset_characters += (use_prefix.length + use_suffix.length);\n            }\n        }\n        blobs_start = b;\n        if (!state.tmp.suppress_decorations) {\n            for (var i = 0, ilen = blob.decorations.length; i < ilen; i += 1) {\n                params = blob.decorations[i];\n                if ([\"@cite\",\"@bibliography\", \"@display\", \"@showid\"].indexOf(params[0]) === -1) {\n                    continue;\n                }\n                if (\"string\" === typeof blobs_start) {\n                    blobs_start = state.fun.decorate[params[0]][params[1]].call(blob, state, blobs_start, params[2]);\n                }\n            }\n        }\n    }\n\n    var blobs_end = ret.slice(span_split, ret.length);\n    if (!blobs_end.length && blobs_start) {\n        ret = [blobs_start];\n    } else if (blobs_end.length && !blobs_start) {\n        ret = blobs_end;\n    } else if (blobs_start && blobs_end.length) {\n        ret = [blobs_start].concat(blobs_end);\n    }\n    //\n    // Blobs is now definitely a string with\n    // trailing blobs.  Return it.\n    if (\"undefined\" === typeof blob) {\n        this.queue = [];\n        this.current.mystack = [];\n        this.current.mystack.push(this.queue);\n        if (state.tmp.suppress_decorations) {\n            ret = state.output.renderBlobs(ret, undefined, false);\n        }\n    } else if (\"boolean\" === typeof blob) {\n        ret = state.output.renderBlobs(ret, undefined, true);\n    }\n\n    if (blob && blob.new_locale) {\n        state.opt.lang = blob.old_locale;\n    }\n    //if (!blob && !state.tmp.just_looking) {\n    //  print(\"QUEUE (\"+ state.tmp.just_looking +\"): \"+JSON.stringify(state.output.queue, [\"num\", \"strings\", \"decorations\", \"blobs\", \"prefix\", \"suffix\", \"delimiter\"], 2));\n    //}\n    return ret;\n};\n\nCSL.Output.Queue.prototype.clearlevel = function () {\n    var blob, pos, len;\n    blob = this.current.value();\n    len = blob.blobs.length;\n    for (pos = 0; pos < len; pos += 1) {\n        blob.blobs.pop();\n    }\n};\n\nCSL.Output.Queue.prototype.renderBlobs = function (blobs, delim, in_cite, parent) {\n    var state, ret, ret_last_char, use_delim, blob, pos, len, ppos, llen, str, params, txt_esc;\n    txt_esc = CSL.getSafeEscape(this.state);\n    if (!delim) {\n        delim = \"\";\n    }\n    state = this.state;\n    ret = \"\";\n    ret_last_char = [];\n    use_delim = \"\";\n    len = blobs.length;\n    if (this.state.tmp.area === \"citation\" && !this.state.tmp.just_looking && len === 1 && typeof blobs[0] === \"object\" && parent) {\n        blobs[0].strings.prefix = parent.strings.prefix + blobs[0].strings.prefix;\n        blobs[0].strings.suffix = blobs[0].strings.suffix + parent.strings.suffix;\n        blobs[0].decorations = blobs[0].decorations.concat(parent.decorations);\n        blobs[0].params = parent.params;\n        return blobs[0];\n    }\n    var start = true;\n    for (pos = 0; pos < len; pos += 1) {\n        if (blobs[pos].checkNext) {\n            blobs[pos].checkNext(blobs[pos + 1],start);\n            start = false;\n        } else if (blobs[pos+1] && blobs[pos+1].splice_prefix) {\n            start = false;\n            //blobs[pos+1].checkNext(blobs[pos + 1],start);\n        } else {\n            start = true;\n        }\n    }\n    \n    // print(\"LEN=\"+len+\" \"+JSON.stringify(blobs, null, 2));\n    // Fix last non-range join\n    var doit = true;\n    for (pos = blobs.length - 1; pos > 0; pos += -1) {\n        if (blobs[pos].checkLast) {\n            if (doit && blobs[pos].checkLast(blobs[pos - 1])) {\n                doit = false;\n            }\n        } else {\n            doit = true;\n        }\n    }\n    len = blobs.length;\n    for (pos = 0; pos < len; pos += 1) {\n        blob = blobs[pos];\n        if (ret) {\n            use_delim = delim;\n        }\n        if (\"string\" === typeof blob) {\n            ret += txt_esc(use_delim);\n            // XXX Blob should be run through flipflop and flattened here.\n            // (I think it must be a fragment of text around a numeric\n            // variable)\n            ret += blob;\n            if (state.tmp.count_offset_characters) {\n                //state.tmp.offset_characters += (use_delim.length + blob.length);\n                state.tmp.offset_characters += (use_delim.length);\n            }\n        } else if (in_cite) {\n            // pass\n            // Okay, so this does it -- but we're now not able to return a string!\n            if (ret) {\n                ret = [ret, blob];\n            } else {\n                ret = [blob];\n            }\n        } else if (blob.status !== CSL.SUPPRESS) {\n            if (blob.particle) {\n                str = blob.particle + blob.num;\n            } else {\n                str = blob.formatter.format(blob.num, blob.gender);\n            }\n            // Workaround to get a more or less accurate value.\n            var strlen = str.replace(/<[^>]*>/g, \"\").length;\n            // notSerious\n            this.append(str, \"empty\", true);\n            var str_blob = this.pop();\n            var count_offset_characters = state.tmp.count_offset_characters;\n            str = this.string(state, [str_blob], false);\n            state.tmp.count_offset_characters = count_offset_characters;\n            if (blob.strings[\"text-case\"]) {\n                str = CSL.Output.Formatters[blob.strings[\"text-case\"]](this.state, str);\n            }\n            if (str && this.state.tmp.strip_periods) {\n                str = str.replace(/\\.([^a-z]|$)/g, \"$1\");\n            }\n            if (!state.tmp.suppress_decorations) {\n                llen = blob.decorations.length;\n                for (ppos = 0; ppos < llen; ppos += 1) {\n                    params = blob.decorations[ppos];\n                    if (state.normalDecorIsOrphan(blob, params)) {\n                        continue;\n                    }\n                    str = state.fun.decorate[params[0]][params[1]].call(blob, state, str, params[2]);\n                }\n            }\n            str = txt_esc(blob.strings.prefix) + str + txt_esc(blob.strings.suffix);\n            var addme = \"\";\n            if (blob.status === CSL.END) {\n                //print(\"  CSL.END\");\n                addme = txt_esc(blob.range_prefix);\n            } else if (blob.status === CSL.SUCCESSOR) {\n                //print(\"  CSL.SUCCESSOR\");\n                addme = txt_esc(blob.successor_prefix);\n            } else if (blob.status === CSL.START) {\n                //print(\"  CSL.START\");\n                if (pos > 0 && !blob.suppress_splice_prefix) {\n                    addme = txt_esc(blob.splice_prefix);\n                } else {\n                    addme = \"\";\n                }\n            } else if (blob.status === CSL.SEEN) {\n                //print(\"  CSL.SEEN\");\n\n                // THIS IS NOT THE PROPER FUNCTION OF CSL.SEEN, IS IT?\n\n                addme = txt_esc(blob.splice_prefix);\n            }\n            ret += addme;\n            ret += str;\n            if (state.tmp.count_offset_characters) {\n                state.tmp.offset_characters += (addme.length + blob.strings.prefix.length + strlen + blob.strings.suffix.length);\n            }\n        }\n    }\n    return ret;\n};\n\nCSL.Output.Queue.purgeEmptyBlobs = function (parent) {\n    //print(\"START1\");\n    if (\"object\" !== typeof parent || \"object\" !== typeof parent.blobs || !parent.blobs.length) {\n        return;\n    }\n    // back-to-front, bottom-first\n    for (var i=parent.blobs.length-1;i>-1;i--) {\n        CSL.Output.Queue.purgeEmptyBlobs(parent.blobs[i]);\n        var child = parent.blobs[i];\n        if (!child || !child.blobs || !child.blobs.length) {\n            var buf = [];\n            while ((parent.blobs.length-1) > i) {\n                buf.push(parent.blobs.pop());\n            }\n            parent.blobs.pop();\n            while (buf.length) {\n                parent.blobs.push(buf.pop());\n            }\n        }\n    }\n    //print(\"   end\");\n};\n\n// Adjustments to be made:\n//\n// * Never migrate beyond a @quotes node\n// * Never migrate into a num node.\n\nCSL.Output.Queue.adjust = function (punctInQuote) {\n\n    var NO_SWAP_IN = {\n        \";\": true,\n        \":\": true\n    };\n\n    var NO_SWAP_OUT = {\n        \".\": true,\n        \"!\": true,\n        \"?\": true\n    };\n\n    var LtoR_MAP = {\n        \"!\": {\n            \".\": \"!\",\n            \"?\": \"!?\",\n            \":\": \"!\",\n            \",\": \"!,\",\n            \";\": \"!;\"\n        },\n        \"?\": {\n            \"!\": \"?!\",\n            \".\": \"?\",\n            \":\": \"?\",\n            \",\": \"?,\",\n            \";\": \"?;\"\n        },\n        \".\": {\n            \"!\": \".!\",\n            \"?\": \".?\",\n            \":\": \".:\",\n            \",\": \".,\",\n            \";\": \".;\"\n        },\n        \":\": {\n            \"!\": \"!\",\n            \"?\": \"?\",\n            \".\": \":\",\n            \",\": \":,\",\n            \";\": \":;\"\n        },\n        \",\": {\n            \"!\": \",!\",\n            \"?\": \",?\",\n            \":\": \",:\",\n            \".\": \",.\",\n            \";\": \",;\"\n        },\n        \";\": {\n            \"!\": \"!\",\n            \"?\": \"?\",\n            \":\": \";\",\n            \",\": \";,\",\n            \".\": \";\"\n        }\n    };\n\n    var SWAP_IN = {};\n    var SWAP_OUT = {};\n    var PUNCT = {};\n    var PUNCT_OR_SPACE = {};\n    for (var key in LtoR_MAP) {\n        PUNCT[key] = true;\n        PUNCT_OR_SPACE[key] = true;\n        if (!NO_SWAP_IN[key]) {\n            SWAP_IN[key] = true;\n        }\n        if (!NO_SWAP_OUT[key]) {\n            SWAP_OUT[key] = true;\n        }\n    }\n    PUNCT_OR_SPACE[\" \"] = true;\n    PUNCT_OR_SPACE[\" \"] = true;\n\n    var RtoL_MAP = {};\n    for (var key in LtoR_MAP) {\n        for (var subkey in LtoR_MAP[key]) {\n            if (!RtoL_MAP[subkey]) {\n                RtoL_MAP[subkey] = {};\n            }\n            RtoL_MAP[subkey][key] = LtoR_MAP[key][subkey];\n        }\n    }\n\n    function blobIsNumber(blob) {\n        return (\"number\" === typeof blob.num || (blob.blobs && blob.blobs.length === 1 && \"number\" === typeof blob.blobs[0].num));\n    }\n\n    function blobEndsInNumber(blob) {\n        if (\"number\" === typeof blob.num) {\n            return true;\n        }\n        if (!blob.blobs || \"object\" !==  typeof blob.blobs) {\n            return false;\n        }\n        if (blobEndsInNumber(blob.blobs[blob.blobs.length-1])) {\n            return true;\n        }\n    }\n    \n    function blobHasDecorations(blob,includeQuotes) {\n        var ret = false;\n        var decorlist = ['@font-style','@font-variant','@font-weight','@text-decoration','@vertical-align'];\n        if (includeQuotes) {\n            decorlist.push('@quotes');\n        }\n        if (blob.decorations) {\n            for (var i=0,ilen=blob.decorations.length;i<ilen;i++) {\n                if (decorlist.indexOf(blob.decorations[i][0]) > -1) {\n                    ret = true;\n                    break;\n                }\n            }\n        }\n        return ret;\n    }\n    \n    function blobHasDescendantQuotes(blob) {\n        if (blob.decorations) {\n            for (var i=0,ilen=blob.decorations.length;i<ilen;i++) {\n                if (blob.decorations[i][0] === '@quotes' && blob.decorations[i][1] !== \"false\") {\n                    return true;\n                }\n            }\n        }\n        if (\"object\" !== typeof blob.blobs) {\n            return false;\n        }\n        return blobHasDescendantQuotes(blob.blobs[blob.blobs.length-1]);\n        //if (blobHasDescendantQuotes(blob.blobs[blob.blobs.length-1])) {\n        //    return true\n        //};\n        //return false;\n    }\n    \n    function blobHasDescendantMergingPunctuation(parentChar,blob) {\n        var childChar = blob.strings.suffix.slice(-1);\n        if (!childChar && \"string\" === typeof blob.blobs) {\n            childChar = blob.blobs.slice(-1);\n        }\n        var mergedChars = RtoL_MAP[parentChar][childChar];\n        if (mergedChars && mergedChars.length === 1) {\n            return true;\n        }\n        if (\"object\" !== typeof blob.blobs) {\n            return false;\n        }\n        if (blobHasDescendantMergingPunctuation(parentChar,blob.blobs[blob.blobs.length-1])) {\n            return true;\n        }\n        return false;\n    }\n    \n    function matchLastChar(blob, chr) {\n        if (!PUNCT[chr]) {\n            return false;\n        }\n        if (\"string\" === typeof blob.blobs) {\n\n            if (blob.blobs.slice(-1) === chr) {\n                return true;\n            } else {\n                return false;\n            }\n        } else {\n            var child = blob.blobs[blob.blobs.length-1];\n            if (child) {\n                var childChar = child.strings.suffix.slice(-1);\n                if (!childChar) {\n                    return matchLastChar(child,chr);\n                } else if (child.strings.suffix.slice(-1) == chr) {\n                    return true;\n                } else {\n                    return false;\n                }\n            } else {\n                return false;\n            }\n        }\n    }\n    \n    function mergeChars (First, first, Second, second, merge_right) {\n        var FirstStrings = \"blobs\" === first ? First : First.strings;\n        var SecondStrings = \"blobs\" === second ? Second: Second.strings;\n        var firstChar = FirstStrings[first].slice(-1);\n        var secondChar = SecondStrings[second].slice(0,1);\n        function cullRight () {\n            SecondStrings[second] = SecondStrings[second].slice(1);\n        }\n        function cullLeft () {\n            FirstStrings[first] = FirstStrings[first].slice(0,-1);\n        }\n        function addRight (chr) {\n            SecondStrings[second] = chr + SecondStrings[second];\n        }\n        function addLeft (chr) {\n            FirstStrings[first] += chr;\n        }\n        var cull = merge_right ? cullLeft : cullRight;\n        function matchOnRight () {\n            return RtoL_MAP[secondChar];\n        }\n        function matchOnLeft () {\n            return LtoR_MAP[firstChar];\n        }\n        var match = merge_right ? matchOnLeft : matchOnRight;\n        function mergeToRight () {\n            var chr = LtoR_MAP[firstChar][secondChar];\n            if (\"string\" === typeof chr) {\n                cullLeft();\n                cullRight();\n                addRight(chr);\n            } else {\n                addRight(firstChar);\n                cullLeft();\n            }\n        }\n        function mergeToLeft () {\n            var chr = RtoL_MAP[secondChar][firstChar];\n            if (\"string\" === typeof chr) {\n                cullLeft();\n                cullRight();\n                addLeft(chr);\n            } else {\n                addLeft(secondChar);\n                cullRight();\n            }\n        }\n        var merge = merge_right ? mergeToRight: mergeToLeft;\n\n        var isDuplicate = firstChar === secondChar;\n        if (isDuplicate) {\n            cull();\n        } else {\n            if (match()) {\n                merge();\n            }\n        }\n    }\n\n    function upward (parent) {\n        //print(\"START2\");\n        // Terminus if no blobs\n        if (parent.blobs && \"string\" == typeof parent.blobs) {\n            if (PUNCT[parent.strings.suffix.slice(0,1)]\n                && parent.strings.suffix.slice(0,1) === parent.blobs.slice(-1)) {\n\n                parent.strings.suffix = parent.strings.suffix.slice(1);\n            }\n            return;\n        } else if (\"object\" !== typeof parent || \"object\" !== typeof parent.blobs || !parent.blobs.length) {\n            return;\n        }\n\n        // back-to-front, bottom-first\n        var parentDecorations = blobHasDecorations(parent,true);\n        for (var i=parent.blobs.length-1;i>-1;i--) {\n            this.upward(parent.blobs[i]);\n            var parentStrings = parent.strings;\n            var childStrings = parent.blobs[i].strings;\n            if (i === 0) {\n                // Remove leading space on first-position child node prefix if there is a trailing space on the node prefix above \n                if (\" \" === parentStrings.prefix.slice(-1) && \" \" === childStrings.prefix.slice(0, 1)) {\n                    childStrings.prefix = childStrings.prefix.slice(1);\n                }\n                // Migrate leading punctuation or space on a first-position prefix upward\n                var childChar = childStrings.prefix.slice(0, 1);\n                if (!parentDecorations && PUNCT_OR_SPACE[childChar] && !parentStrings.prefix) {\n                    parentStrings.prefix += childChar;\n                    childStrings.prefix = childStrings.prefix.slice(1);\n                }\n            }\n            if (i === (parent.blobs.length - 1)) {\n                // Migrate trailing space ONLY on a last-position suffix upward, controlling for duplicates\n                var childChar = childStrings.suffix.slice(-1);\n                // ZZZ Loosened to fix initialized names wrapped in a span and followed by a period\n                if (!parentDecorations && [\" \"].indexOf(childChar) > -1) {\n                    if (parentStrings.suffix.slice(0,1) !== childChar) {\n                        parentStrings.suffix = childChar + parentStrings.suffix;\n                    }\n                    childStrings.suffix = childStrings.suffix.slice(0, -1);\n                }\n            }\n            if (parentStrings.delimiter && i > 0) {\n                // Remove leading space on mid-position child node prefix if there is a trailing space on delimiter above\n                if (PUNCT_OR_SPACE[parentStrings.delimiter.slice(-1)]\n                    && parentStrings.delimiter.slice(-1) === childStrings.prefix.slice(0, 1)) {\n\n                    childStrings.prefix = childStrings.prefix.slice(1);\n                }\n            }\n            // Siblings are handled in adjustNearsideSuffixes()\n        }\n        //print(\"   end\");\n    }\n\n    function leftward (parent) {\n        // Terminus if no blobs\n        if (\"object\" !== typeof parent || \"object\" !== typeof parent.blobs || !parent.blobs.length) {\n            return;\n        }\n\n        for (var i=parent.blobs.length-1;i>-1;i--) {\n            this.leftward(parent.blobs[i]);\n            // This is a delicate one.\n            //\n            // Migrate if:\n            // * there is no umbrella delimiter [ok]\n            // * neither the child nor its sibling is a number [ok]\n            // * decorations exist neither on the child nor on the sibling [ok]\n            // * sibling prefix char is a swapping char [ok]\n            //\n            // Suppress without migration if:\n            // * sibling prefix char matches child suffix char or\n            // * child suffix is empty and sibling prefix char match last field char\n            if ((i < parent.blobs.length -1) && !parent.strings.delimiter) {\n                // If there is a trailing swappable character on a sibling prefix with no intervening delimiter, copy it to suffix,\n                // controlling for duplicates\n                var child = parent.blobs[i];\n                var childChar = child.strings.suffix.slice(-1);\n                var sibling = parent.blobs[i+1];\n                var siblingChar = sibling.strings.prefix.slice(0, 1);\n                var hasDecorations = blobHasDecorations(child) || blobHasDecorations(sibling);\n                var hasNumber = \"number\" === typeof childChar || \"number\" === typeof siblingChar;\n\n                if (!hasDecorations && !hasNumber && PUNCT[siblingChar] && !hasNumber) {\n                    var suffixAndPrefixMatch = siblingChar === child.strings.suffix.slice(-1);\n                    var suffixAndFieldMatch = (!child.strings.suffix && \"string\" === typeof child.blobs && child.blobs.slice(-1) === siblingChar);\n                    if (!suffixAndPrefixMatch && !suffixAndFieldMatch) {\n                        mergeChars(child, 'suffix', sibling, 'prefix');\n                        //child.strings.suffix += siblingChar;\n                    } else {\n                        sibling.strings.prefix = sibling.strings.prefix.slice(1);\n                    }\n                }\n            }\n        }\n    }\n\n    function downward (parent) {\n        //print(\"START3\");\n        // Terminus if no blobs\n        if (parent.blobs && \"string\" == typeof parent.blobs) {\n            if (PUNCT[parent.strings.suffix.slice(0,1)]\n                && parent.strings.suffix.slice(0,1) === parent.blobs.slice(-1)) {\n\n                parent.strings.suffix = parent.strings.suffix.slice(1);\n            }\n            return;\n        } else if (\"object\" !== typeof parent || \"object\" !== typeof parent.blobs || !parent.blobs.length) {\n            return;\n        }\n        //if (top) {\n        //    print(\"JSON \"+JSON.stringify(parent, [\"strings\", \"decorations\", \"blobs\", \"prefix\", \"suffix\", \"delimiter\"], 2));\n        //}\n\n        var parentStrings = parent.strings;\n        // Check for numeric child\n        var someChildrenAreNumbers = false;\n        for (var i=0,ilen=parent.blobs.length;i<ilen;i++) {\n            if (blobIsNumber(parent.blobs[i])) {\n                someChildrenAreNumbers = true;\n                break;\n            }\n        }\n        if (true || !someChildrenAreNumbers) {\n            // If there is a leading swappable character on delimiter, copy it to suffixes IFF none of the targets are numbers\n            if (parentStrings.delimiter && PUNCT[parentStrings.delimiter.slice(0, 1)]) {\n                var delimChar = parentStrings.delimiter.slice(0, 1);\n                for (var i=parent.blobs.length-2;i>-1;i--) {\n                    var childStrings = parent.blobs[i].strings;\n                    if (childStrings.suffix.slice(-1) !== delimChar) {\n                        childStrings.suffix += delimChar;\n                    }\n                }\n                parentStrings.delimiter = parentStrings.delimiter.slice(1);\n            }\n        }\n        // back-to-front, top-first\n        for (var i=parent.blobs.length-1;i>-1;i--) {\n            var child = parent.blobs[i];\n            var childStrings = parent.blobs[i].strings;\n            var childDecorations = blobHasDecorations(child, true);\n            var childIsNumber = blobIsNumber(child);\n\n            if (i === (parent.blobs.length - 1)) {\n\n                //if (blobHasDescendantQuotes(child)) {\n                //    print(\"JSON \"+JSON.stringify(parent, [\"strings\", \"decorations\", \"blobs\", \"prefix\", \"suffix\", \"delimiter\"]));\n                //}\n\n                if (true || !someChildrenAreNumbers) {\n                    // If we have decorations, drill down to see if there are quotes below.\n                    // If so, we allow migration anyway.\n                    // Original discussion is here:\n                    // https://forums.zotero.org/discussion/37091/citeproc-bug-punctuation-in-quotes/\n                    var parentChar = parentStrings.suffix.slice(0, 1);\n\n                    // Hmm.\n                    // Consider writing out the matching child from blobHasDescendant functions.\n                    // It should save some cycles, and produce the same result.\n\n                    var allowMigration = false;\n                    if (PUNCT[parentChar]) {\n                        allowMigration = blobHasDescendantMergingPunctuation(parentChar,child);\n                        if (!allowMigration && punctInQuote) {\n                            allowMigration = blobHasDescendantQuotes(child);\n                        }\n                    }\n                    if (allowMigration) {\n                        if (PUNCT[parentChar]) {\n                            if (!blobEndsInNumber(child)) {\n                                if (\"string\" === typeof child.blobs) {\n                                    mergeChars(child, 'blobs', parent, 'suffix');\n                                } else {\n                                    mergeChars(child, 'suffix', parent, 'suffix');\n                                }\n                                if (parentStrings.suffix.slice(0,1) === \".\") {\n                                    childStrings.suffix += parentStrings.suffix.slice(0,1);\n                                    parentStrings.suffix = parentStrings.suffix.slice(1);\n                                }\n                            }\n                        }\n                    }\n                    if (childStrings.suffix.slice(-1) === \" \" && parentStrings.suffix.slice(0,1) === \" \") {\n                        parentStrings.suffix = parentStrings.suffix.slice(1);\n                    }\n                    // More duplicates control\n                    if (PUNCT_OR_SPACE[childStrings.suffix.slice(0,1)]) {\n                        if (\"string\" === typeof child.blobs && child.blobs.slice(-1) === childStrings.suffix.slice(0,1)) {\n                            // Remove parent punctuation of it duplicates the last character of a field\n                            childStrings.suffix = childStrings.suffix.slice(1);\n                        }\n                        if (childStrings.suffix.slice(-1) === parentStrings.suffix.slice(0, 1)) {\n                            // Remove duplicate punctuation on child suffix\n                            parentStrings.suffix = parentStrings.suffix.slice(0, -1);\n                        }\n                    }\n                }\n                // Squash dupes\n                if (matchLastChar(parent,parent.strings.suffix.slice(0,1))) {\n                    parent.strings.suffix = parent.strings.suffix.slice(1);\n                }\n            } else if (parentStrings.delimiter) {\n                // Remove trailing space on mid-position child node suffix if there is a leading space on delimiter above\n                if (PUNCT_OR_SPACE[parentStrings.delimiter.slice(0,1)]\n                    && parentStrings.delimiter.slice(0, 1) === childStrings.suffix.slice(-1)) {\n\n                    parent.blobs[i].strings.suffix = parent.blobs[i].strings.suffix.slice(0, -1);\n                    \n                }\n            } else {\n                // Otherwise it's a sibling. We don't care about moving spaces here, just suppress a duplicate\n                var siblingStrings = parent.blobs[i+1].strings;\n                if (!blobIsNumber(child) \n                    && !childDecorations\n                    && PUNCT_OR_SPACE[childStrings.suffix.slice(-1)]\n                    && childStrings.suffix.slice(-1) === siblingStrings.prefix.slice(0, 1)) {\n\n                    siblingStrings.prefix = siblingStrings.prefix.slice(1);\n                }\n            }\n            // If field content ends with swappable punctuation, suppress swappable punctuation in style suffix.\n            if (!childIsNumber && !childDecorations && PUNCT[childStrings.suffix.slice(0,1)]\n                && \"string\" === typeof child.blobs) {\n                \n                mergeChars(child, 'blobs', child, 'suffix');\n            }\n            this.downward(parent.blobs[i]);\n        }\n/*\n        if (top) {\n\n            var seen = [];\n            print(JSON.stringify(parent, function(key, val) {\n                if (!val || key === 'alldecor') return;\n                if (typeof val == \"object\") {\n                    if (seen.indexOf(val) >= 0)\n                        return\n                    seen.push(val)\n                }\n                return val\n            },2));\n        }\n*/\n\n        //print(\"  end\");\n    }\n    // Abstract out a couple of utility functions, used in fix() below.\n    function swapToTheLeft (child) {\n        var childChar = child.strings.suffix.slice(0,1);\n        if (\"string\" === typeof child.blobs) {\n            while (SWAP_IN[childChar]) {\n                mergeChars(child, 'blobs', child, 'suffix');\n                childChar = child.strings.suffix.slice(0,1);\n            }                                \n        } else {\n            while (SWAP_IN[childChar]) {\n                mergeChars(child.blobs[child.blobs.length-1], 'suffix', child, 'suffix');\n                childChar = child.strings.suffix.slice(0,1);\n            }\n        }\n    }\n    function swapToTheRight (child) {\n        if (\"string\" === typeof child.blobs) {\n            var childChar = child.blobs.slice(-1);\n            while (SWAP_OUT[childChar]) {\n                mergeChars(child, 'blobs', child, 'suffix', true);\n                childChar = child.blobs.slice(-1);\n            }\n        } else {\n            var childChar = child.blobs[child.blobs.length-1].strings.suffix.slice(-1);\n            while (SWAP_OUT[childChar]) {\n                mergeChars(child.blobs[child.blobs.length-1], 'suffix', child, 'suffix', true);\n                childChar = child.blobs[child.blobs.length-1].strings.suffix.slice(-1);\n            }\n        }\n    }\n\n    function fix (parent) {\n        // Terminus if no blobs\n        if (\"object\" !== typeof parent || \"object\" !== typeof parent.blobs || !parent.blobs.length) {\n            return;\n        }\n        \n        //print(\"START4\");\n        // Do the swap, front-to-back, bottom-first\n        var lastChar;\n\n        // XXX Two things to fix with this:\n        // XXX (1) Stalls after one character\n        // XXX (2) Moves colon and semicolon, both of which SHOULD stall\n\n        for (var i=0,ilen=parent.blobs.length;i<ilen;i++) {\n            var child = parent.blobs[i];\n            var quoteSwap = false;\n            for (var j=0,jlen=child.decorations.length;j<jlen;j++) {\n                var decoration = child.decorations[j];\n                if (decoration[0] === \"@quotes\" && decoration[1] !== \"false\") {\n                    quoteSwap = true;\n                }\n            }\n            if (quoteSwap) {\n                if (punctInQuote) {\n                    swapToTheLeft(child);\n                } else {\n                    swapToTheRight(child);\n                }\n            }\n            lastChar = this.fix(parent.blobs[i]);\n            if (child.blobs && \"string\" === typeof child.blobs) {\n                lastChar = child.blobs.slice(-1);\n            }\n        }\n        return lastChar;\n    }\n    this.upward = upward;\n    this.leftward = leftward;\n    this.downward = downward;\n    this.fix = fix;\n};\n\n/*global CSL: true */\n\nCSL.Engine.Opt = function () {\n    this.parallel = {\n        enable: false,\n    },\n    this.has_disambiguate = false;\n    this.mode = \"html\";\n    this.dates = {};\n    this.jurisdictions_seen = {};\n    this.suppressedJurisdictions = {};\n    this.inheritedAttributes = {};\n    this[\"locale-sort\"] = [];\n    this[\"locale-translit\"] = [];\n    this[\"locale-translat\"] = [];\n    this.citeAffixes = {\n        persons:{\n            \"locale-orig\":{\n                prefix:\"\",\n                suffix:\"\"\n            },\n            \"locale-translit\":{\n                prefix:\"\",\n                suffix:\"\"\n            },\n            \"locale-translat\":{\n                prefix:\"\",\n                suffix:\"\"\n            }\n        },\n        institutions:{\n            \"locale-orig\":{\n                prefix:\"\",\n                suffix:\"\"\n            },\n            \"locale-translit\":{\n                prefix:\"\",\n                suffix:\"\"\n            },\n            \"locale-translat\":{\n                prefix:\"\",\n                suffix:\"\"\n            }\n        },\n        titles:{\n            \"locale-orig\":{\n                prefix:\"\",\n                suffix:\"\"\n            },\n            \"locale-translit\":{\n                prefix:\"\",\n                suffix:\"\"\n            },\n            \"locale-translat\":{\n                prefix:\"\",\n                suffix:\"\"\n            }\n        },\n        journals:{\n            \"locale-orig\":{\n                prefix:\"\",\n                suffix:\"\"\n            },\n            \"locale-translit\":{\n                prefix:\"\",\n                suffix:\"\"\n            },\n            \"locale-translat\":{\n                prefix:\"\",\n                suffix:\"\"\n            }\n        },\n        publishers:{\n            \"locale-orig\":{\n                prefix:\"\",\n                suffix:\"\"\n            },\n            \"locale-translit\":{\n                prefix:\"\",\n                suffix:\"\"\n            },\n            \"locale-translat\":{\n                prefix:\"\",\n                suffix:\"\"\n            }\n        },\n        places:{\n            \"locale-orig\":{\n                prefix:\"\",\n                suffix:\"\"\n            },\n            \"locale-translit\":{\n                prefix:\"\",\n                suffix:\"\"\n            },\n            \"locale-translat\":{\n                prefix:\"\",\n                suffix:\"\"\n            }\n        }\n    };\n    this[\"default-locale\"] = [];\n    this.update_mode = CSL.NONE;\n    this.bib_mode = CSL.NONE;\n    this.sort_citations = false;\n    /*\n     * Default values.\n     * The various et-al values are set globally,\n     * and the appropriate value is set by the names start\n     * tag at runtime, depending on whether the Item is a\n     * first or a subsequent reference.\n     */\n    this[\"et-al-min\"] = 0;\n    this[\"et-al-use-first\"] = 1;\n    this[\"et-al-use-last\"] = false;\n    this[\"et-al-subsequent-min\"] = false;\n    this[\"et-al-subsequent-use-first\"] = false;\n\n    this[\"demote-non-dropping-particle\"] = \"display-and-sort\";\n    // default of true, because none of our consuming\n    // applications so far store the various prefixes and \n    // suffixes we support in separate fields.\n    this[\"parse-names\"] = true;\n    // this[\"auto-vietnamese-names\"] = true;\n\n    this.citation_number_slug = false;\n    this.trigraph = \"Aaaa00:AaAa00:AaAA00:AAAA00\";\n\n    this.nodenames = [];\n\n    this.gender = {};\n    this['cite-lang-prefs'] = {\n        persons:['orig'],\n        institutions:['orig'],\n        titles:['orig'],\n        journals:['orig'],\n        publishers:['orig'],\n        places:['orig'],\n        number:['orig']\n    };\n\n    this.has_layout_locale = false;\n    this.disable_duplicate_year_suppression = [];\n    this.use_context_condition = false;\n\n    this.jurisdiction_fallbacks = {};\n\n    this.development_extensions = {};\n    this.development_extensions.field_hack = true;\n    this.development_extensions.allow_field_hack_date_override = true;\n    this.development_extensions.locator_date_and_revision = true;\n    this.development_extensions.locator_label_parse = true;\n    this.development_extensions.raw_date_parsing = true;\n    this.development_extensions.clean_up_csl_flaws = true;\n    this.development_extensions.consolidate_legal_items = false;\n    this.development_extensions.csl_reverse_lookup_support = false;\n    this.development_extensions.wrap_url_and_doi = false;\n    this.development_extensions.thin_non_breaking_space_html_hack = false;\n    this.development_extensions.apply_citation_wrapper = false;\n    this.development_extensions.main_title_from_short_title = false;\n    this.development_extensions.uppercase_subtitles = false;\n    this.development_extensions.normalize_lang_keys_to_lowercase = false;\n    this.development_extensions.strict_text_case_locales = false;\n    this.development_extensions.expect_and_symbol_form = false;\n    this.development_extensions.require_explicit_legal_case_title_short = false;\n    this.development_extensions.spoof_institutional_affiliations = false;\n    this.development_extensions.force_jurisdiction = false;\n    this.development_extensions.parse_names = true;\n    this.development_extensions.hanging_indent_legacy_number = false;\n    this.development_extensions.throw_on_empty = false;\n    this.development_extensions.strict_inputs = true;\n    this.development_extensions.prioritize_disambiguate_condition = false;\n    this.development_extensions.force_short_title_casing_alignment = true;\n    this.development_extensions.implicit_short_title = false;\n    this.development_extensions.force_title_abbrev_fallback = false;\n    this.development_extensions.split_container_title = false;\n    this.development_extensions.legacy_institution_name_ordering = false;\n    this.development_extensions.etal_min_etal_usefirst_hack = false;\n};\n\nCSL.Engine.Tmp = function () {\n    //\n    // scratch variable to display the total\n    // number of names in all rendered variables\n    // in a cite.  initialized to zero by the\n    // citation element, incremented by each\n    // name variable actually rendered\n    this.names_max = new CSL.Stack();\n    this.names_base = new CSL.Stack();\n    this.givens_base = new CSL.Stack();\n    //\n    // this holds the field values collected by the @value\n    // and @variable attributes, for processing by the\n    // element functions.\n    this.value = [];\n    /**\n     * Object to hold the decorations declared by a name-part\n     * element.\n     */\n    this.namepart_decorations = {};\n    /**\n     * String variable to hold the type of a name-part\n     * element.\n     */\n    this.namepart_type = false;\n    //\n    // scratch variable to flag whether we are processing\n    // a citation or a bibiliography.  this diverts token and\n    // configuration to the appropriateo objects inside\n    // state.  the default is \"citation\".\n    this.area = \"citation\";\n    this.root = \"citation\";\n    this.extension = \"\";\n    //\n    // controls the implicit conditional wrappers applied\n    // to top-level elements inside a names substitute span.\n    // false by default, names start tag pushes a new true level,\n    // names end tag pops it.  Output value check in @variable\n    // function of attributes.js sets level to false.  closing names\n    // tag maps a false value to superior level.\n    this.can_substitute = new CSL.Stack(0, CSL.LITERAL);\n    //\n    // notes whether the formatted elements of a date span\n    // rendered anything.  controls whether literal fallback\n    // is used.\n    this.element_rendered_ok = false;\n    //\n    // element_trace keeps a record of rendered elements.\n    // used to implement author-only.\n    //\n    this.element_trace = new CSL.Stack(\"style\");\n    //\n    // counter for total namesets\n    this.nameset_counter = 0;\n    //\n    /////  this.fun.check_for_output = CSL.check_for_output;\n    //\n    // stack flag used for term handling.  Set to true\n    // if at least one variable has tried to render, and\n    // no variables had content.\n    this.group_context = new CSL.Stack({\n        term_intended: false,\n        variable_attempt: false,\n        variable_success: false,\n        output_tip: undefined,\n        label_form:  undefined,\n        parallel_first: undefined,\n        parallel_last: undefined,\n        parallel_delimiter_override: undefined,\n        condition: false,\n        force_suppress: false,\n        done_vars: []\n    });\n    //\n    // boolean flag used to control first-letter capitalization\n    // of terms.  Set to true if any item preceding the term\n    // being handled has rendered successfully, otherwise\n    // false.\n    this.term_predecessor = false;\n    //\n    // boolean flag to control use of layout delimiter\n    // immediately before numbers. This hack is needed for\n    // some numeric styles.\n    this.in_cite_predecessor = false;\n    //\n    // stack flag used to control jumps in the closing\n    // token of a conditional.\n    this.jump = new CSL.Stack(0, CSL.LITERAL);\n    //\n    // holds string parameters for group formatting, between\n    // the start of a group and the closing token.\n    this.decorations = new CSL.Stack();\n    //\n    // token store stack.\n    this.tokenstore_stack = new CSL.Stack();\n\n    // for collapsing\n    this.last_suffix_used = \"\";\n    this.last_names_used = [];\n    this.last_years_used = [];\n    this.years_used = [];\n    this.names_used = [];\n\n    this.taintedItemIDs = {};\n    this.taintedCitationIDs = {};\n    //\n    // scratch stack containing initialize-with strings or null values\n    this.initialize_with = new CSL.Stack();\n    //\n    // this is used to set a requested set of\n    // disambiguation parameters in the output.\n    // for the array elements, the base array\n    // (either zero for each nameset, or full-up\n    // if givens are already used) is set\n    // during names processing, if no value\n    // is set in the processor before a rendering\n    // run.  to simplify things for the calling\n    // function, these are just bog-standard arrays,\n    // and can be safely overwritten.\n    this.disambig_request = false;\n    //\n    // scratch variable to toggle an attempt to set a\n    // name in sort order rather than display\n    // order.\n    this[\"name-as-sort-order\"] = false;\n    //\n    // suppress decorations (used for generating\n    // sort keys and disambiguation keys)\n    this.suppress_decorations = false;\n    //\n    // empty settings array, used to report settings used\n    // if disambig_request is not set at runtime\n    this.disambig_settings = new CSL.AmbigConfig();\n    //\n    // sort key array\n    this.bib_sort_keys = [];\n    //\n    // holds the prefix between the start of a group\n    // and the closing token.\n    this.prefix = new CSL.Stack(\"\", CSL.LITERAL);\n    //\n    // holds the suffix between the start of a group\n    // and the closing token.\n    this.suffix = new CSL.Stack(\"\", CSL.LITERAL);\n    //\n    // holds the group delimiter between the start of a group\n    // and the closing token.\n    this.delimiter = new CSL.Stack(\"\", CSL.LITERAL);\n    //\n    // Used for conditional locale switching.\n    this.cite_locales = [];\n    this.cite_affixes = {\n        citation: false, \n        bibliography: false,\n        citation_sort: false, \n        bibliography_sort: false\n    };\n    this.strip_periods = 0;\n    this.shadow_numbers = {};\n    this.authority_stop_last = 0;\n    this.loadedItemIDs = {};\n    //\n    // Push/pop array for set/unset of opt.lang setting, used\n    // in if locale=\"XX\" to force terms to language of item.\n    // @locale tests track their nesting level in a counter,\n    // and push the current value of state.opt.lang to one array,\n    // and the counter value to another. On the way back up,\n    // closing node decrements the counter, compares its value\n    // with the trailing value on the array, and pops both\n    // arrays, resetting state.opt.lang to the previous value.\n    // A hack to solve a surprisingly difficult problem caused\n    // by the use of an execution stack for the nested structure.\n    this.condition_counter = 0; //incremented/decremented on ALL conditions\n    this.condition_lang_val_arr = [];\n    this.condition_lang_counter_arr = [];\n};\n\n\nCSL.Engine.Fun = function (state) {\n    //\n    // matcher\n    this.match = new CSL.Util.Match();\n    //\n    // utility to get standard suffixes for disambiguation\n    this.suffixator = new CSL.Util.Suffixator(CSL.SUFFIX_CHARS);\n    //\n    // utility to romanize a numeric value\n    this.romanizer = new CSL.Util.Romanizer();\n    //\n    // utility to make an ordinal form of a number\n    this.ordinalizer = new CSL.Util.Ordinalizer(state);\n    //\n    // utility to make the long ordinal form of a number, if possible\n    this.long_ordinalizer = new CSL.Util.LongOrdinalizer();\n};\n\n\nCSL.Engine.Build = function () {\n    // Alternate et-al term\n    // Holds the localization key of the alternative term\n    // to be used for et-al in a names environment.  Reduced\n    // to a term object when the element tag is processed during\n    // Build.\n    this[\"alternate-term\"] = false;\n    //\n    // flags that we are in the bibliography area.\n    // used by sort.\n    this.in_bibliography = false;\n    //\n    // scratch variable to alter behaviour when processing\n    // locale files\n    this.in_style = false;\n    //\n    // used to ignore info\n    this.skip = false;\n    //\n    // the macro ATTRIBUTE stores a macro name on this\n    // scratch variable anywhere outside the layout area\n    // during build.  The macro name is picked up when\n    // the token is encountered inside the layout area,\n    // either through a direct call, or as part of a nested\n    // macro expansion, and the macro content is exploded\n    // into the token list.\n    this.postponed_macro = false;\n    //\n    // used especially for controlling macro expansion\n    // during Build.\n    this.layout_flag = false;\n    //\n    // (was buffer_name)\n    // scratch variable to hold the name of a macro\n    // or a term until its children have been collected.\n    this.name = false;\n    this.names_variables = [[]];\n    this.name_label = [{}];\n    //\n    // scratch variable to hold the value of a form\n    // attribute until other attributes needed for\n    // processing have been collected.\n    this.form = false;\n    this.term = false;\n    //\n    // the macros themselves are discarded after Build\n    this.macro = {};\n    //\n    // the macro build stack.  used to raise an error\n    // when macros would attempt to call themselves.\n    this.macro_stack = [];\n    //\n    // stores the content of an XML text node during processing\n    this.text = false;\n    //\n    // this is a scratch variable for holding an attribute\n    // value during processing\n    this.lang = false;\n    //\n    // should be able to run uninitialized; may attract some\n    // cruft this way.\n    this.area = \"citation\";\n    this.root = \"citation\";\n    this.extension = \"\";\n    //\n    // controls the application of implicit conditional wrappers\n    // to top-level elements inside a names substitute span.\n    // zero by default, build of names tag pushes a\n    // new level with value 1.  group start tag increments by 1,\n    // group end tag decrements by 1.  conditional wrappers are\n    // only applied if value is exactly 1.\n    this.substitute_level = new CSL.Stack(0, CSL.LITERAL);\n    this.names_level = 0;\n    this.render_nesting_level = 0;\n    this.render_seen = false;\n    this.bibliography_key_pos = 0;\n};\n\n\nCSL.Engine.Configure = function () {\n    //\n    // the fail and succeed arrays are used for stack\n    // processing during configure.\n    this.tests = [];\n    this.fail = [];\n    this.succeed = [];\n};\n\n\nCSL.Engine.Citation = function (state) {\n     // Citation options area.\n     // Holds a mixture of persistent and ephemeral\n     // options and scratch data used during processing of\n     // a citation.</p>\n    this.opt = {\n        inheritedAttributes: {}\n    };\n\n    this.tokens = [];\n    // Placeholder function\n    this.srt = new CSL.Registry.Comparifier(state, \"citation_sort\");\n    //\n    // configuration array to hold the collapse\n    // options, if any.\n    this.opt.collapse = [];\n    //\n    // disambiguate options\n    this.opt[\"disambiguate-add-names\"] = false;\n    this.opt[\"disambiguate-add-givenname\"] = false;\n    this.opt[\"disambiguate-add-year-suffix\"] = false;\n    this.opt[\"givenname-disambiguation-rule\"] = \"by-cite\";\n    this.opt[\"near-note-distance\"] = 5;\n\n    this.opt.topdecor = [];\n    this.opt.layout_decorations = [];\n    this.opt.layout_prefix = \"\";\n    this.opt.layout_suffix = \"\";\n    this.opt.layout_delimiter = \"\";\n    //\n    // sorting\n    this.opt.sort_locales = [];\n    this.opt.max_number_of_names = 0;\n    this.root = \"citation\";\n};\n\n\nCSL.Engine.Bibliography = function () {\n    this.opt = {\n        inheritedAttributes: {}\n    };\n    this.tokens = [];\n\n    this.opt.collapse = [];\n\n    this.opt.topdecor = [];\n    this.opt.layout_decorations = [];\n    this.opt.layout_prefix = \"\";\n    this.opt.layout_suffix = \"\";\n    this.opt.layout_delimiter = \"\";\n    this.opt[\"line-spacing\"] = 1;\n    this.opt[\"entry-spacing\"] = 1;\n    //\n    // sorting\n    this.opt.sort_locales = [];\n    this.opt.max_number_of_names = 0;\n    this.root = \"bibliography\";\n};\n\n\nCSL.Engine.BibliographySort = function () {\n    this.tokens = [];\n    this.opt = {};\n    this.opt.sort_directions = [];\n    this.opt.topdecor = [];\n    // Holds the final citation-number sort direction, for use\n    // in applying numbers in cs:citation and cs:bibliography.\n    // Value is exclusively controlled by cs:key in bibliography_sort\n    this.opt.citation_number_sort_direction = CSL.ASCENDING;\n    this.opt.citation_number_secondary = false;\n    this.tmp = {};\n    this.keys = [];\n    this.root = \"bibliography\";\n};\n\n\nCSL.Engine.CitationSort = function () {\n    this.tokens = [];\n    this.opt = {};\n    this.opt.sort_directions = [];\n    this.keys = [];\n    this.opt.topdecor = [];\n    this.root = \"citation\";\n};\n\nCSL.Engine.InText = function () {\n     // InText options area.\n     // Holds a mixture of persistent and ephemeral\n     // options and scratch data used during processing of\n     // a citation.</p>\n    this.opt = {\n        inheritedAttributes: {}\n    };\n\n    this.tokens = [];\n    // Placeholder function\n    //this.srt = new CSL.Registry.Comparifier(state, \"citation_sort\");\n    //\n    // configuration array to hold the collapse\n    // options, if any.\n    this.opt.collapse = [];\n    //\n    // disambiguate options\n    this.opt[\"disambiguate-add-names\"] = false;\n    this.opt[\"disambiguate-add-givenname\"] = false;\n    this.opt[\"disambiguate-add-year-suffix\"] = false;\n    this.opt[\"givenname-disambiguation-rule\"] = \"by-cite\";\n    this.opt[\"near-note-distance\"] = 5;\n\n    this.opt.topdecor = [];\n    this.opt.layout_decorations = [];\n    this.opt.layout_prefix = \"\";\n    this.opt.layout_suffix = \"\";\n    this.opt.layout_delimiter = \"\";\n    //\n    // sorting\n    this.opt.sort_locales = [];\n    this.opt.max_number_of_names = 0;\n    this.root = \"intext\";\n};\n\n/*global CSL: true */\n\nCSL.Engine.prototype.previewCitationCluster = function (citation, citationsPre, citationsPost, newMode) {\n    // Generate output for a hypothetical citation at the current position,\n    // Leave the registry in the same state in which it was found.\n    //print(\"################### previewCitationCluster() #################\");\n    var oldMode = this.opt.mode;\n    this.setOutputFormat(newMode);\n    // Avoids generating unwanted ibids, if the citationID already exists in document\n\tif (citation.citationID) {\n\t\tdelete citation.citationID;\n\t}\n    var ret = this.processCitationCluster(citation, citationsPre, citationsPost, CSL.PREVIEW);\n\n    this.setOutputFormat(oldMode);\n    return ret[1];\n};\n\nCSL.Engine.prototype.appendCitationCluster = function (citation) {\n    var citationsPre = [];\n    var len = this.registry.citationreg.citationByIndex.length;\n    for (var pos = 0; pos < len; pos += 1) {\n        var c = this.registry.citationreg.citationByIndex[pos];\n        citationsPre.push([\"\" + c.citationID, c.properties.noteIndex]);\n    }\n    // Drop the data segment to return a list of pos/string pairs.\n    return this.processCitationCluster(citation, citationsPre, [])[1];\n};\n\n\nCSL.Engine.prototype.processCitationCluster = function (citation, citationsPre, citationsPost, flag) {\n    var c, preCitation, postCitation, i, ilen, j, jlen, k, klen, n, nlen, key, Item, item, noteCitations, textCitations, m, citationsInNote;\n    this.debug = false;\n    this.tmp.loadedItemIDs = {};\n\n    // Revert citation dereference from 2ffc4664ae\n    //citation = JSON.parse(JSON.stringify(citation));\n    \n    //print(\"################### processCitationCluster() #################\");\n    this.tmp.citation_errors = [];\n    this.registry.return_data = {\"bibchange\": false};\n\n    // make sure this citation has a unique ID, and register it in citationById.\n    this.setCitationId(citation);\n\n    var oldCitationList;\n    var oldItemList;\n    var oldAmbigs;\n    if (flag === CSL.PREVIEW) {\n        //SNIP-START\n        if (this.debug) {\n            CSL.debug(\"****** start state save *********\");\n        }\n        //SNIP-END\n        //\n        // Simplify.\n\n        // Take a slice of existing citations.\n        oldCitationList = this.registry.citationreg.citationByIndex.slice();\n\n        // Take a slice of current items, for later use with update.\n        oldItemList = this.registry.reflist.slice();\n\n        // Make a list of preview citation ref objects. Omit the current\n        // citation, because it will not exist in registry if: (a) this is\n        // a new citation; or (b) the calling application is assigning\n        // new citationIDs for every transaction.\n        var newCitationList = citationsPre.concat(citationsPost);\n\n        // Make a full list of desired ids, for use in preview update,\n        // and a hash list of same while we're at it.\n        // First step through known citations, then step through\n        // the items in the citation for preview.\n        var newItemIds = {};\n        var newItemIdsList = [];\n        for (var i = 0, ilen = newCitationList.length; i < ilen; i += 1) {\n            c = this.registry.citationreg.citationById[newCitationList[i][0]];\n            for (j = 0, jlen = c.citationItems.length; j < jlen; j += 1) {\n                newItemIds[c.citationItems[j].id] = true;\n                newItemIdsList.push(\"\" + c.citationItems[j].id);\n            }\n        }\n        for (j = 0, jlen = citation.citationItems.length; j < jlen; j += 1) {\n            newItemIds[citation.citationItems[j].id] = true;\n            newItemIdsList.push(\"\" + citation.citationItems[j].id);\n        }\n\n        // Clone and save off disambigs of items that will be lost.\n        oldAmbigs = {};\n        for (var i = 0, ilen = oldItemList.length; i < ilen; i += 1) {\n            if (!newItemIds[oldItemList[i].id]) {\n                var oldAkey = this.registry.registry[oldItemList[i].id].ambig;\n                var ids = this.registry.ambigcites[oldAkey];\n                if (ids) {\n                    for (j = 0, jlen = ids.length; j < jlen; j += 1) {\n                        oldAmbigs[ids[j]] = CSL.cloneAmbigConfig(this.registry.registry[ids[j]].disambig);\n                    }\n                }\n            }\n        }\n\n        // Update items.  This will produce the base name data and sort things.\n        // Possibly unnecessary?\n        //this.updateItems(this.registry.mylist.concat(tmpItems));\n\n        //SNIP-START\n        if (this.debug) {\n            CSL.debug(\"****** end state save *********\");\n        }\n        //SNIP-END\n    }\n\n    this.tmp.taintedCitationIDs = {};\n    var sortedItems = [];\n\n    // Styles that use note backreferencing with a by-cite\n    // givenname disambiguation rule include the note number\n    // in the cite for disambiguation purposes. Correct resolution\n    // of disambiguate=\"true\" conditions on first-reference cites \n    // in certain editing scenarios (e.g. where a cite is moved across\n    // notes) requires that disambiguation be rerun on cites\n    // affected by the edit.\n    var rerunAkeys = {};\n\n    // retrieve item data and compose items for use in rendering\n    // attach pointer to item data to shared copy for good measure\n    for (var i = 0, ilen = citation.citationItems.length; i < ilen; i += 1) {\n        // Protect against caller-side overwrites to locator strings etc\n        item = {};\n        for (var key in citation.citationItems[i]) {\n            item[key] = citation.citationItems[i][key];\n        }\n        Item = this.retrieveItem(\"\" + item.id);\n        if (Item.id) {\n            this.transform.loadAbbreviation(\"default\", \"hereinafter\", Item.id, Item.language);\n        }\n        item = CSL.parseLocator.call(this, item);\n        if (this.opt.development_extensions.consolidate_legal_items) {\n            this.remapSectionVariable([[Item,item]]);\n        }\n        if (this.opt.development_extensions.locator_label_parse) {\n            if (item.locator && [\"bill\",\"gazette\",\"legislation\",\"regulation\",\"treaty\"].indexOf(Item.type) === -1 && (!item.label || item.label === 'page')) {\n                var m = CSL.LOCATOR_LABELS_REGEXP.exec(item.locator);\n                if (m) {\n                    var tryLabel = CSL.LOCATOR_LABELS_MAP[m[2]];\n                    if (this.getTerm(tryLabel)) {\n                        item.label = tryLabel;\n                        item.locator = m[3];\n                    }\n                }\n            }\n        }\n        var newitem = [Item, item];\n        sortedItems.push(newitem);\n        citation.citationItems[i].item = Item;\n    }\n\n    // ZZZ sort stuff moved from here.\n\n    // attach the sorted list to the citation item\n    citation.sortedItems = sortedItems;\n\n    // build reconstituted citations list in current document order\n    var citationByIndex = [];\n    var citationById = {};\n    var lastNotePos;\n    for (i=0, ilen=citationsPre.length; i<ilen; i += 1) {\n        preCitation = citationsPre[i];\n        if (this.opt.development_extensions.strict_inputs) {\n            if (citationById[preCitation[0]]) {\n                CSL.error(\"Previously referenced citationID \" + preCitation[0] + \" encountered in citationsPre\");\n            }\n            if (preCitation[1]) {\n                if (lastNotePos > preCitation[1]) {\n                    CSL.debug(\"Note index sequence is not sane at citationsPre[\" + i + \"]\");\n                }\n                lastNotePos = preCitation[1];\n            }\n        }\n        this.registry.citationreg.citationById[preCitation[0]].properties.noteIndex = preCitation[1];\n        citationByIndex.push(this.registry.citationreg.citationById[preCitation[0]]);\n        citationById[preCitation[0]] = this.registry.citationreg.citationById[preCitation[0]];\n    }\n    if (!citation.properties) {\n        citation.properties = {\n            noteIndex: 0\n        };\n    }\n    if (this.opt.development_extensions.strict_inputs) {\n        if (citationById[citation.citationID]) {\n            CSL.error(\"Citation with previously referenced citationID \" + citation.citationID);\n        }\n        if (citation.properties.noteIndex) {\n            if (lastNotePos > citation.properties.noteIndex) {\n                CSL.debug(\"Note index sequence is not sane for citation \" + citation.citationID);\n            }\n            lastNotePos = citation.properties.noteIndex;\n        }\n    }\n    citationByIndex.push(citation);\n    citationById[citation.citationID] = citation;\n    for (i=0, ilen=citationsPost.length; i<ilen; i += 1) {\n        postCitation = citationsPost[i];\n        if (this.opt.development_extensions.strict_inputs) {\n            if (citationById[postCitation[0]]) {\n                CSL.error(\"Previously referenced citationID \" + postCitation[0] + \" encountered in citationsPost\");\n            }\n            if (postCitation[1]) {\n                if (lastNotePos > postCitation[1]) {\n                    CSL.debug(\"Note index sequence is not sane at postCitation[\" + i + \"]\");\n                }\n                lastNotePos = postCitation[1];\n            }\n        }\n        this.registry.citationreg.citationById[postCitation[0]].properties.noteIndex = postCitation[1];\n        citationByIndex.push(this.registry.citationreg.citationById[postCitation[0]]);\n        citationById[postCitation[0]] = this.registry.citationreg.citationById[postCitation[0]];\n    }\n    this.registry.citationreg.citationByIndex = citationByIndex;\n    this.registry.citationreg.citationById = citationById;\n\n    //\n    // The processor provides three facilities to support\n    // updates following position reevaluation.\n    //\n    // (1) The updateItems() function reports tainted ItemIDs\n    // to state.tmp.taintedItemIDs.\n    //\n    // (2) The processor memos the type of style referencing as\n    // CSL.NONE, CSL.NUMERIC or CSL.POSITION in state.opt.update_mode.\n    //\n    // XXXX: NO LONGER\n    // (3) For citations containing cites with backreference note numbers,\n    // a string image of the rendered citation is held in\n    // citation.properties.backref_citation, and a list of\n    // ItemIDs to be used to update the backreference note numbers\n    // is memoed at citation.properties.backref_index.  When such\n    // citations change position, they can be updated with a\n    // series of simple find and replace operations, without\n    // need for rerendering.\n    //\n\n    //\n    // Position evaluation!\n    //\n    // set positions in reconstituted list, noting taints\n    this.registry.citationreg.citationsByItemId = {};\n    if (this.opt.update_mode === CSL.POSITION) {\n        textCitations = [];\n        noteCitations = [];\n        citationsInNote = {};\n    }\n    var update_items = [];\n    for (var i = 0, ilen = citationByIndex.length; i < ilen; i += 1) {\n        citationByIndex[i].properties.index = i;\n        for (j = 0, jlen = citationByIndex[i].sortedItems.length; j < jlen; j += 1) {\n            item = citationByIndex[i].sortedItems[j];\n            if (!this.registry.citationreg.citationsByItemId[item[1].id]) {\n                this.registry.citationreg.citationsByItemId[item[1].id] = [];\n                update_items.push(\"\" + item[1].id);\n            }\n            if (this.registry.citationreg.citationsByItemId[item[1].id].indexOf(citationByIndex[i]) === -1) {\n                this.registry.citationreg.citationsByItemId[item[1].id].push(citationByIndex[i]);\n            }\n        }\n        if (this.opt.update_mode === CSL.POSITION) {\n            if (citationByIndex[i].properties.noteIndex) {\n                noteCitations.push(citationByIndex[i]);\n            } else {\n                citationByIndex[i].properties.noteIndex = 0;\n                textCitations.push(citationByIndex[i]);\n            }\n        }\n    }\n    //\n    // update bibliography items here\n    //\n    if (flag !== CSL.ASSUME_ALL_ITEMS_REGISTERED) {\n        //SNIP-START\n        if (this.debug) {\n            CSL.debug(\"****** start update items *********\");\n        }\n        //SNIP-END\n        // true signals implicit updateItems (will not rerun sys.retrieveItem())\n        this.updateItems(update_items, null, null, true);\n        //SNIP-START\n        if (this.debug) {\n            CSL.debug(\"****** endo update items *********\");\n        }\n        //SNIP-END\n    }\n\n    if (!this.opt.citation_number_sort && sortedItems && sortedItems.length > 1 && this.citation_sort.tokens.length > 0) {\n        for (var i = 0, ilen = sortedItems.length; i < ilen; i += 1) {\n            sortedItems[i][1].sortkeys = CSL.getSortKeys.call(this, sortedItems[i][0], \"citation_sort\");\n        }\n\n        /* \n         * Grouped sort stuff (start)\n         */\n\n        if (this.opt.grouped_sort &&  !citation.properties.unsorted) {\n            // Insert authorstring as key.\n            for (var i = 0, ilen = sortedItems.length; i < ilen; i += 1) {\n                var sortkeys = sortedItems[i][1].sortkeys;\n                this.tmp.authorstring_request = true;\n                // Run getAmbiguousCite() with the current disambig\n                // parameters, and pick up authorstring from the registry.\n                var mydisambig = this.registry.registry[sortedItems[i][0].id].disambig;\n                \n                this.tmp.authorstring_request = true;\n                CSL.getAmbiguousCite.call(this, sortedItems[i][0], mydisambig);\n                var authorstring = this.registry.authorstrings[sortedItems[i][0].id];\n                this.tmp.authorstring_request = false;\n\n                sortedItems[i][1].sortkeys = [authorstring].concat(sortkeys);\n            }\n\n            sortedItems.sort(this.citation.srt.compareCompositeKeys);\n            // Replace authorstring key in items with same (authorstring) with the \n            // keystring of first normal key. This forces grouped sorts,\n            // as discussed here:\n            // https://github.com/citation-style-language/schema/issues/40\n            var lastauthor = false;\n            var thiskey = false;\n            var thisauthor = false;\n            for (var i = 0, ilen = sortedItems.length; i < ilen; i += 1) {\n                if (sortedItems[i][1].sortkeys[0] !== lastauthor) {\n                    thisauthor = sortedItems[i][1].sortkeys[0];\n                    thiskey =  sortedItems[i][1].sortkeys[1];\n                }\n                sortedItems[i][1].sortkeys[0] = \"\" + thiskey + i;\n                lastauthor = thisauthor;\n            }\n        }\n        /*\n         * Grouped sort stuff (end)\n         */\n\n        if (!citation.properties.unsorted) {\n            sortedItems.sort(this.citation.srt.compareCompositeKeys);\n        }\n    }\n\n    // evaluate parallels\n\n    if (this.opt.parallel.enable) {\n        this.parallel.StartCitation(citation.sortedItems);\n    }\n\n    var citations;\n    if (this.opt.update_mode === CSL.POSITION) {\n        for (var i = 0; i < 2; i += 1) {\n            var first_ref = {};\n            var last_ref = {};\n            var first_container_ref = {};\n            citations = [textCitations, noteCitations][i];\n            for (j = 0, jlen = citations.length; j < jlen; j += 1) {\n                var onecitation = citations[j];\n                if (!citations[j].properties.noteIndex) {\n                    citations[j].properties.noteIndex = 0;\n                }\n                citations[j].properties.noteIndex = parseInt(citations[j].properties.noteIndex, 10);\n                if (j > 0 && onecitation.properties.noteIndex && citations[j - 1].properties.noteIndex > onecitation.properties.noteIndex) {\n                    citationsInNote = {};\n                    first_ref = {};\n                    last_ref = {};\n                    first_container_ref = {};\n                }\n                for (k = 0, klen = onecitation.sortedItems.length; k < klen; k += 1) {\n                    if (onecitation.sortedItems[k][1].parallel && onecitation.sortedItems[k][1].parallel !== \"first\") {\n                        continue;\n                    }\n                    if (!citationsInNote[onecitation.properties.noteIndex]) {\n                        citationsInNote[onecitation.properties.noteIndex] = 1;\n                    } else {\n                        citationsInNote[onecitation.properties.noteIndex] += 1;\n                    }\n                }\n                // Set the following:\n                //\n                // (1) position as required (as per current Zotero)\n                // (2) first-reference-note-number as required (on onecitation item)\n                // (3) near-note as required (on onecitation item, according to\n                //     state.opt[\"near-note-distance\"] parameter)\n                // (4) state.registry.citationreg.citationsByItemId.\n                //\n                // Any state changes caused by unsetting or resetting should\n                // trigger a single entry for the citations in\n                // state.tmp.taintedCitationIDs (can block on presence of\n                // state.registry.citationreg.citationsByItemId).\n                //\n                for (k = 0, klen = citations[j].sortedItems.length; k < klen; k += 1) {\n                    item = citations[j].sortedItems[k];\n                    // Okay ...\n                    // We set up three IDs for use in position evaluation.\n                    // item_id is the real Item.id\n                    // first_id is the legislation_id or Item.id (so statutes backref to first in set, chapters to specific chapter)\n                    // last_id is the legislation_id or container_id (so statute AND chapter distance is from any ref in set)\n                    // (replaces myid)\n                    var item_id = item[0].id;\n                    var first_id = item[0].legislation_id ? item[0].legislation_id : item[0].id;\n                    var last_id = item[0].legislation_id ? item[0].legislation_id : item[0].container_id ? item[0].container_id : item[0].id;\n                    var myxloc = item[1][\"locator-extra\"];\n                    var mylocator = item[1].locator;\n                    var mylabel = item[1].label;\n                    var incitationid;\n                    var incitationxloc;\n                    if (k > 0) {\n                        // incitationid is only reached in the else branch\n                        // following \"undefined\" === typeof first_ref[myid]\n                        // below\n                        if (onecitation.sortedItems[k - 1][0].legislation_id) {\n                            incitationid = onecitation.sortedItems[k - 1][0].legislation_id;\n                        } else {\n                            incitationid = onecitation.sortedItems[k - 1][1].id;\n                            incitationxloc = onecitation.sortedItems[k - 1][1][\"locator-extra\"];\n                            //if (onecitation.sortedItems[k-1][1].parallel === \"last\") {\n                                for (var l=k-2; l>-1; l--) {\n                                    if (onecitation.sortedItems[l][1].parallel === \"first\") {\n                                        incitationid = onecitation.sortedItems[l][1].id;\n                                        incitationxloc = onecitation.sortedItems[l][1][\"locator-extra\"];\n                                    }\n                                }\n                            //}\n                        }\n                    }\n                    // Don't touch item data of other cites when previewing\n                    if (flag === CSL.PREVIEW) {\n                        if (onecitation.citationID != citation.citationID) {\n                            if (\"undefined\" === typeof first_ref[item[1].id]) {\n                                first_ref[first_id] = onecitation.properties.noteIndex;\n                                last_ref[last_id] = onecitation.properties.noteIndex;\n                            } else {\n                                last_ref[last_id] = onecitation.properties.noteIndex;\n                            }\n                            continue;\n                        }\n                    }\n                    var oldvalue = {};\n                    oldvalue.position = item[1].position;\n                    oldvalue[\"first-reference-note-number\"] = item[1][\"first-reference-note-number\"];\n                    oldvalue[\"first-container-reference-note-number\"] = item[1][\"first-container-reference-note-number\"];\n                    oldvalue[\"near-note\"] = item[1][\"near-note\"];\n                    item[1][\"first-reference-note-number\"] = 0;\n                    item[1][\"first-container-reference-note-number\"] = 0;\n                    item[1][\"near-note\"] = false;\n                    if (this.registry.citationreg.citationsByItemId[item_id]) {\n                        if (this.opt.xclass === 'note' && this.opt.has_disambiguate) {\n                            var oldCount = this.registry.registry[item[0].id][\"citation-count\"];\n                            var newCount = this.registry.citationreg.citationsByItemId[item_id].length;\n                            this.registry.registry[item[0].id][\"citation-count\"] = this.registry.citationreg.citationsByItemId[item_id].length;\n                            if (\"number\" === typeof oldCount) {\n                                var oldCountCheck = (oldCount < 2);\n                                var newCountCheck = (newCount < 2);\n                                if (oldCountCheck !== newCountCheck) {\n                                    for (var l=0,llen=this.registry.citationreg.citationsByItemId[item_id].length;l<llen;l++) {\n                                        rerunAkeys[this.registry.registry[item[0].id].ambig] = true;\n                                        this.tmp.taintedCitationIDs[this.registry.citationreg.citationsByItemId[item_id][l].citationID] = true;\n                                    }\n                                }\n                            } else {\n                                for (var l=0,llen=this.registry.citationreg.citationsByItemId[item_id].length;l<llen;l++) {\n                                    rerunAkeys[this.registry.registry[item[0].id].ambig] = true;\n                                    this.tmp.taintedCitationIDs[this.registry.citationreg.citationsByItemId[item_id][l].citationID] = true;\n                                }\n                            }\n                        }\n                    }\n                    var oldlastid;\n                    var oldlastxloc;\n                    \n                    // Okay, chill.\n                    // The first test needs to be for presence of last_ref[last_id]. Everything\n                    // after in subsequent evaluation depends on that.\n\n                    // HOWEVER, despite starting with this test, we need to catch every member\n                    // of the set, and set its first-container-reference-note-number to point at the\n                    // first.\n\n                    // ALSO, despite starting with this test, we need to set first-reference-note-number\n                    // on every item.\n                    \n                    // So ... we run an independent test on first_ref[first_id]], and let this ride.\n                    \n                    if (\"undefined\" === typeof last_ref[last_id] && onecitation.properties.mode !== \"author-only\") {\n                        first_ref[first_id] = onecitation.properties.noteIndex;\n                        last_ref[last_id] = onecitation.properties.noteIndex;\n                        first_container_ref[last_id] = onecitation.properties.noteIndex;\n                        item[1].position = CSL.POSITION_FIRST;\n                    } else {\n                        //\n                        // backward-looking position evaluation happens here.\n                        //\n                        //\n                        //\n                        var ibidme = false;\n                        var suprame = false;\n                        var prevCitation = null;\n                        if (j > 0) {\n                            var prevCitation = citations[j-1];\n                        }\n                        var thisCitation = citations[j];\n                        // XXX Ugly, but This is used in the second else-if branch condition below.\n                        if (j > 0) {\n                            var old_last_id_offset = 1;\n                            if (prevCitation.properties.mode === \"author-only\" && j > 1) {\n                                old_last_id_offset = 2;\n                            }\n                            var adjusted_offset = (j - old_last_id_offset);\n                            if (citations[adjusted_offset].sortedItems.length) {\n                                oldlastid =  citations[adjusted_offset].sortedItems.slice(-1)[0][1].id;\n                                oldlastxloc =  citations[j - old_last_id_offset].sortedItems.slice(-1)[0][1][\"locator-extra\"];\n                            }\n                            if (prevCitation.sortedItems.length) {\n                                if (prevCitation.sortedItems[0].slice(-1)[0].legislation_id) {\n                                    oldlastid = prevCitation.sortedItems[0].slice(-1)[0].legislation_id;\n                                }\n                            }\n                        }\n                        if (j > 0 && k === 0 && prevCitation.properties.noteIndex !== thisCitation.properties.noteIndex) {\n                            // Case 1: source in previous onecitation\n                            // (1) Threshold conditions\n                            //     (a) there must be a previous onecitation with one item\n                            //     (b) this item must be the first in this onecitation\n                            //     (c) the previous onecitation must contain a reference\n                            //         to the same item ...\n                            //     (d) the note numbers must be the same or consecutive.\n                            // (this has some jiggery-pokery in it for parallels)\n                            var useme = false;\n                            // XXX Can oldid be equated with oldlastid, I wonder ...\n                            var oldid = prevCitation.sortedItems[0][0].id;\n                            if (prevCitation.sortedItems[0][0].legislation_id) {\n                                oldid = prevCitation.sortedItems[0][0].legislation_id;\n                            }\n                            if ((oldid  == first_id && prevCitation.properties.noteIndex >= (thisCitation.properties.noteIndex - 1))) {\n                                var prevxloc = prevCitation.sortedItems[0][1][\"locator-extra\"];\n                                var thisxloc = thisCitation.sortedItems[0][1][\"locator-extra\"];\n                                if ((citationsInNote[prevCitation.properties.noteIndex] === 1 || prevCitation.properties.noteIndex === 0) && prevxloc === thisxloc) {\n                                    useme = true;\n                                }\n                            }\n                            if (useme) {\n                                ibidme = true;\n                            } else {\n                                suprame = true;\n                            }\n                        } else if (k > 0 && incitationid == first_id && incitationxloc == myxloc) {\n                            // Case 2: immediately preceding source in this onecitation\n                            // (1) Threshold conditions\n                            //     (a) there must be an imediately preceding reference to  the\n                            //         same item in this onecitation; and\n                            ibidme = true;\n                        } else if (k === 0 && j > 0 && prevCitation.properties.noteIndex == thisCitation.properties.noteIndex\n                                   && prevCitation.sortedItems.length \n                                   && oldlastid == first_id && oldlastxloc == myxloc) {\n                            // ... in case there are separate citations in the same note ...\n                            // Case 2 [take 2]: immediately preceding source in this onecitation\n                            // (1) Threshold conditions\n                            //     (a) there must be an imediately preceding reference to  the\n                            //         same item in this onecitation; and\n                            ibidme = true;\n                        } else {\n                            // everything else is definitely subsequent\n                            suprame = true;\n                        }\n                        // conditions\n                        var prev, prev_locator, prev_label, curr_locator, curr_label;\n                        if (ibidme) {\n                            if (k > 0) {\n                                prev = onecitation.sortedItems[(k - 1)][1];\n                            } else {\n                                prev = citations[(j - 1)].sortedItems[0][1];\n                            }\n                            if (prev.locator) {\n                                if (prev.label) {\n                                    prev_label = prev.label;\n                                } else {\n                                    prev_label = \"\";\n                                }\n                                prev_locator = \"\" + prev.locator + prev_label;\n                            } else {\n                                prev_locator = prev.locator;\n                            }\n                            if (mylocator) {\n                                if (mylabel) {\n                                    curr_label = mylabel;\n                                } else {\n                                    curr_label = \"\";\n                                }\n                                curr_locator = \"\" + mylocator + curr_label;\n                            } else {\n                                curr_locator = mylocator;\n                            }\n                        }\n                        // triage\n                        if (ibidme && prev_locator && !curr_locator) {\n                            ibidme = false;\n                            suprame = true;\n\n                        }\n                        if (ibidme) {\n                            if (!prev_locator && curr_locator) {\n                                //     (a) if the previous onecitation had no locator\n                                //         and this onecitation has one, use ibid+pages\n                                item[1].position = CSL.POSITION_IBID_WITH_LOCATOR;\n                            } else if (!prev_locator && !curr_locator) {\n                                //     (b) if the previous onecitation had no locator\n                                //         and this onecitation also has none, use ibid\n                                item[1].position = CSL.POSITION_IBID;\n                                //print(\"setting ibid in cmd_cite()\");\n                            } else if (prev_locator && curr_locator === prev_locator) {\n                                //     (c) if the previous onecitation had a locator\n                                //         (page number, etc.) and this onecitation has\n                                //         a locator that is identical, use ibid\n\n                                item[1].position = CSL.POSITION_IBID;\n                                //print(\"setting ibid in cmd_cite() [2]\");\n                            } else if (prev_locator && curr_locator && curr_locator !== prev_locator) {\n                                //     (d) if the previous onecitation had a locator,\n                                //         and this onecitation has one that differs,\n                                //         use ibid+pages\n                                item[1].position = CSL.POSITION_IBID_WITH_LOCATOR;\n                            } else {\n                                //     (e) if the previous onecitation had a locator\n                                //         and this onecitation has none, use subsequent\n                                //\n                                //     ... and everything else would be subsequent also\n                                ibidme = false; // just to be clear\n                                suprame = true;\n                            }\n                        }\n                        if (suprame) {\n                            item[1].position = CSL.POSITION_CONTAINER_SUBSEQUENT;\n                            if (\"undefined\" === typeof first_ref[first_id]) {\n                                first_ref[first_id] = onecitation.properties.noteIndex;\n                            } else {\n                                item[1].position = CSL.POSITION_SUBSEQUENT;\n                            }\n                        }\n                        if (suprame || ibidme) {\n                            if (onecitation.properties.mode === \"author-only\") {\n                                item[1].position = CSL.POSITION_FIRST;\n                            }\n                            if (first_container_ref[last_id] != onecitation.properties.noteIndex) {\n                                item[1]['first-container-reference-note-number'] = first_container_ref[last_id];\n                                if (this.registry.registry[item[0].id]) {\n                                    this.registry.registry[item[0].id]['first-container-reference-note-number'] = first_container_ref[last_id];\n                                }\n                            }\n                            if (first_ref[first_id] != onecitation.properties.noteIndex) {\n                                item[1][\"first-reference-note-number\"] = first_ref[first_id];\n                                if (this.registry.registry[item[0].id]) {\n                                    // This is either the earliest recorded number, or the number of the current citation, whichever is smaller.\n                                    /*\n                                    var oldFirst = this.registry.citationreg.citationsByItemId[item_id][0].properties.noteIndex;\n                                    var newFirst = onecitation.properties.noteIndex;\n                                    this.registry.registry[item[0].id]['first-reference-note-number'] = newFirst < oldFirst ? newFirst: oldFirst;\n                                     */\n                                    // Try this instead?\n                                    this.registry.registry[item[0].id]['first-reference-note-number'] = first_ref[first_id];\n                                }\n                            }\n                        }\n                    }\n                    if (onecitation.properties.noteIndex) {\n                        var note_distance = parseInt(onecitation.properties.noteIndex, 10) - parseInt(last_ref[last_id], 10);\n                        if (item[1].position !== CSL.POSITION_FIRST \n                            && note_distance <= this.citation.opt[\"near-note-distance\"]) {\n                            item[1][\"near-note\"] = true;\n                        }\n                        last_ref[last_id] = onecitation.properties.noteIndex;\n                    } else if (item[1].position !== CSL.POSITION_FIRST) {\n                        item[1][\"near-note\"] = true;\n                    }\n                    if (onecitation.citationID != citation.citationID) {\n                        for (n = 0, nlen = CSL.POSITION_TEST_VARS.length; n < nlen; n += 1) {\n                            var param = CSL.POSITION_TEST_VARS[n];\n                            if (item[1][param] !== oldvalue[param]) {\n                                if (this.registry.registry[item[0].id]) {\n                                    if (param === 'first-reference-note-number') {\n                                        rerunAkeys[this.registry.registry[item[0].id].ambig] = true;\n                                        this.tmp.taintedItemIDs[item[0].id] = true;\n                                    }\n                                }\n                                this.tmp.taintedCitationIDs[onecitation.citationID] = true;\n                            }\n                        }\n                    }\n                    if (this.sys.variableWrapper) {\n                        item[1].index = onecitation.properties.index;\n                        item[1].noteIndex = onecitation.properties.noteIndex;\n                    }\n                }\n            }\n        }\n    }\n    if (this.opt.citation_number_sort && sortedItems && sortedItems.length > 1 && this.citation_sort.tokens.length > 0) {\n        if (!citation.properties.unsorted) {\n            for (var i = 0, ilen = sortedItems.length; i < ilen; i += 1) {\n                sortedItems[i][1].sortkeys = CSL.getSortKeys.call(this, sortedItems[i][0], \"citation_sort\");\n            }\n            sortedItems.sort(this.citation.srt.compareCompositeKeys);\n        }\n    }\n    for (var key in this.tmp.taintedItemIDs) {\n        if (this.tmp.taintedItemIDs.hasOwnProperty(key)) {\n            citations = this.registry.citationreg.citationsByItemId[key];\n            // Current citation may be tainted but will not exist\n            // during previewing.\n            if (citations) {\n                for (var i = 0, ilen = citations.length; i < ilen; i += 1) {\n                    this.tmp.taintedCitationIDs[citations[i].citationID] = true;\n                }\n            }\n        }\n    }\n\n    var ret = [];\n    if (flag === CSL.PREVIEW) {\n        // If previewing, return only a rendered string\n        //SNIP-START\n        if (this.debug) {\n            CSL.debug(\"****** start run processor *********\");\n        }\n        //SNIP-END\n        try {\n            ret = this.process_CitationCluster.call(this, citation.sortedItems, citation);\n        } catch (e) {\n            CSL.error(\"Error running CSL processor for preview: \"+e);\n        }\n            \n        //SNIP-START\n        if (this.debug) {\n            CSL.debug(\"****** end run processor *********\");\n            CSL.debug(\"****** start state restore *********\");\n        }\n        //SNIP-END\n        // Wind out anything related to new items added for the preview.\n        // This means (1) names, (2) disambig state for affected items,\n        // (3) keys registered in the ambigs pool arrays, and (4) registry\n        // items.\n        //\n\n        // restore sliced citations\n        this.registry.citationreg.citationByIndex = oldCitationList;\n        this.registry.citationreg.citationById = {};\n        for (var i = 0, ilen = oldCitationList.length; i < ilen; i += 1) {\n            this.registry.citationreg.citationById[oldCitationList[i].citationID] = oldCitationList[i];\n        }\n\n        //SNIP-START\n        if (this.debug) {\n            CSL.debug(\"****** start final update *********\");\n        }\n        //SNIP-END\n        var oldItemIds = [];\n        for (var i = 0, ilen = oldItemList.length; i < ilen; i += 1) {\n            oldItemIds.push(\"\" + oldItemList[i].id);\n        }\n        this.updateItems(oldItemIds, null, null, true);\n        //SNIP-START\n        if (this.debug) {\n            CSL.debug(\"****** end final update *********\");\n        }\n        //SNIP-END\n        // Roll back disambig states\n        for (var key in oldAmbigs) {\n            if (oldAmbigs.hasOwnProperty(key)) {\n                this.registry.registry[key].disambig = oldAmbigs[key];\n            }\n        }\n        //SNIP-START\n        if (this.debug) {\n            CSL.debug(\"****** end state restore *********\");\n        }\n        //SNIP-END\n    } else {\n        // Rerun cites that have moved across citations or had a change\n        // in their number of subsequent references, so that disambiguate\n        // and subsequent-reference-count conditions are applied\n        // correctly in output.\n        for (var rerunAkey in rerunAkeys) {\n            this.disambiguate.run(rerunAkey, citation);\n        }\n        // Run taints only if not previewing\n        //\n        // Push taints to the return object\n        //\n        var obj;\n        for (var key in this.tmp.taintedCitationIDs) {\n            if (key == citation.citationID) {\n                continue;\n            }\n            var mycitation = this.registry.citationreg.citationById[key];\n            if (!mycitation.properties.unsorted) {\n                for (var i = 0, ilen = mycitation.sortedItems.length; i < ilen; i += 1) {\n                    mycitation.sortedItems[i][1].sortkeys = CSL.getSortKeys.call(this, mycitation.sortedItems[i][0], \"citation_sort\");\n                }\n                mycitation.sortedItems.sort(this.citation.srt.compareCompositeKeys);\n            }\n            // For error reporting\n            this.tmp.citation_pos = mycitation.properties.index;\n            this.tmp.citation_note_index = mycitation.properties.noteIndex;\n            this.tmp.citation_id = \"\" + mycitation.citationID;\n            obj = [];\n            obj.push(mycitation.properties.index);\n            obj.push(this.process_CitationCluster.call(this, mycitation.sortedItems, mycitation));\n            obj.push(mycitation.citationID);\n            ret.push(obj);\n        }\n        this.tmp.taintedItemIDs = {};\n        this.tmp.taintedCitationIDs = {};\n\n        // For error reporting again\n        this.tmp.citation_pos = citation.properties.index;\n        this.tmp.citation_note_index = citation.properties.noteIndex;\n        this.tmp.citation_id = \"\" + citation.citationID;\n\n        obj = [];\n        obj.push(citationsPre.length);\n        obj.push(this.process_CitationCluster.call(this, sortedItems, citation));\n        obj.push(citation.citationID);\n        ret.push(obj);\n        //\n        // note for posterity: Rhino and Spidermonkey produce different\n        // sort results for items with matching keys.  That discrepancy\n        // turned up a subtle bug in the parallel detection code, trapped\n        // at line 266, above, and in line 94 of util_parallel.js.\n        //\n        ret.sort(function (a, b) {\n            if (a[0] > b[0]) {\n                return 1;\n            } else if (a[0] < b[0]) {\n                return -1;\n            } else {\n                return 0;\n            }\n        });\n        //\n        // In normal rendering, return is a list of two-part arrays, with the first element\n        // a citation index number, and the second the text to be inserted.\n        //\n    }\n    this.registry.return_data.citation_errors = this.tmp.citation_errors.slice();\n    return [this.registry.return_data, ret];\n};\n\nCSL.Engine.prototype.process_CitationCluster = function (sortedItems, citation) {\n    var str = \"\";\n    if (citation && citation.properties && citation.properties.mode === \"composite\") {\n        citation.properties.mode = \"author-only\";\n        var firstChunk = CSL.getCitationCluster.call(this, sortedItems, citation);\n        citation.properties.mode = \"suppress-author\";\n        var secondChunk = \"\";\n        if (citation.properties.infix) {\n            this.output.append(citation.properties.infix);\n            secondChunk = this.output.string(this, this.output.queue);\n            // Had no idea this could return a single-element array! Go figure.\n            if (\"object\" === typeof secondChunk) {\n                secondChunk = secondChunk.join(\"\");\n            }\n        }\n        var thirdChunk = CSL.getCitationCluster.call(this, sortedItems, citation);\n        citation.properties.mode = \"composite\";\n        if (firstChunk && secondChunk && CSL.SWAPPING_PUNCTUATION.concat([\"\\u2019\", \"\\'\"]).indexOf(secondChunk[0]) > -1) {\n            firstChunk += secondChunk;\n            secondChunk = false;\n        }\n        str = [firstChunk, secondChunk, thirdChunk].filter(function(obj) {\n            return obj;\n        }).join(\" \");\n    } else {\n        str = CSL.getCitationCluster.call(this, sortedItems, citation);\n    }\n    return str;\n};\n\nCSL.Engine.prototype.makeCitationCluster = function (rawList) {\n    var inputList, newitem, str, pos, len, item, Item;\n    inputList = [];\n    len = rawList.length;\n    for (pos = 0; pos < len; pos += 1) {\n        item = {};\n        for (var key in rawList[pos]) {\n            item[key] = rawList[pos][key];\n        }\n        Item = this.retrieveItem(\"\" + item.id);\n        // Code block is copied from processCitationCluster() above\n        if (this.opt.development_extensions.locator_label_parse) {\n            if (item.locator && [\"bill\",\"gazette\",\"legislation\",\"regulation\",\"treaty\"].indexOf(Item.type) === -1 && (!item.label || item.label === 'page')) {\n                var m = CSL.LOCATOR_LABELS_REGEXP.exec(item.locator);\n                if (m) {\n                    var tryLabel = CSL.LOCATOR_LABELS_MAP[m[2]];\n                    if (this.getTerm(tryLabel)) {\n                        item.label = tryLabel;\n                        item.locator = m[3];\n                    }\n                }\n            }\n        }\n        if (item.locator) {\n            item.locator = (\"\" + item.locator).replace(/\\s+$/, '');\n        }\n        newitem = [Item, item];\n        inputList.push(newitem);\n    }\n    if (this.opt.development_extensions.consolidate_legal_items) {\n        this.remapSectionVariable(inputList);\n    }\n    if (inputList && inputList.length > 1 && this.citation_sort.tokens.length > 0) {\n        len = inputList.length;\n        for (pos = 0; pos < len; pos += 1) {\n            inputList[pos][1].sortkeys = CSL.getSortKeys.call(this, inputList[pos][0], \"citation_sort\");\n        }\n        inputList.sort(this.citation.srt.compareCompositeKeys);\n    }\n    this.tmp.citation_errors = [];\n    var str = CSL.getCitationCluster.call(this, inputList);\n    return str;\n};\n\n\n/**\n * Get the undisambiguated version of a cite, without decorations\n * <p>This is used internally by the Registry.</p>\n *\n * [object] CSL Item\n * [object] disambiguation parameters\n * [boolean] If true, include first-reference-note-number value in cite\n */\nCSL.getAmbiguousCite = function (Item, disambig, visualForm, item) {\n    var ret;\n    var flags = this.tmp.group_context.tip;\n    var oldTermSiblingLayer = {\n        term_intended: flags.term_intended,\n        variable_attempt: flags.variable_attempt,\n        variable_success: flags.variable_success,\n        output_tip: flags.output_tip,\n        label_form: flags.label_form,\n        non_parallel: flags.non_parallel,\n        parallel_last: flags.parallel_last,\n        parallel_first: flags.parallel_first,\n        parallel_last_override: flags.parallel_last_override,\n        parallel_delimiter_override: flags.parallel_delimiter_override,\n        parallel_delimiter_override_on_suppress: flags.parallel_delimiter_override_on_suppress,\n        condition: flags.condition,\n        force_suppress: flags.force_suppress,\n        done_vars: flags.done_vars.slice()\n    };\n    if (disambig) {\n        this.tmp.disambig_request = disambig;\n    } else {\n        this.tmp.disambig_request = false;\n    }\n    var itemSupp = {\n        position: CSL.POSITION_SUBSEQUENT,\n        \"near-note\": true\n    };\n\n    if (item) {\n        itemSupp.locator = item.locator;\n        itemSupp.label = item.label;\n    }\n\n    if (this.registry.registry[Item.id] \n        && this.registry.citationreg.citationsByItemId\n        && this.registry.citationreg.citationsByItemId[Item.id]\n        && this.registry.citationreg.citationsByItemId[Item.id].length \n        && visualForm) {\n        if (this.citation.opt[\"givenname-disambiguation-rule\"] === \"by-cite\") {\n            itemSupp['first-reference-note-number'] = this.registry.registry[Item.id]['first-reference-note-number'];\n        }\n    }\n    this.tmp.area = \"citation\";\n    this.tmp.root = \"citation\";\n    var origSuppressDecorations = this.tmp.suppress_decorations;\n    this.tmp.suppress_decorations = true;\n    this.tmp.just_looking = true;\n\n    CSL.getCite.call(this, Item, itemSupp, null, false);\n    // !!!\n    for (var i=0,ilen=this.output.queue.length;i<ilen;i+=1) {\n        CSL.Output.Queue.purgeEmptyBlobs(this.output.queue[i]);\n    }\n    if (this.opt.development_extensions.clean_up_csl_flaws) {\n        for (var j=0,jlen=this.output.queue.length;j<jlen;j+=1) {\n            this.output.adjust.upward(this.output.queue[j]);\n            this.output.adjust.leftward(this.output.queue[j]);\n            this.output.adjust.downward(this.output.queue[j]);\n            this.output.adjust.fix(this.output.queue[j]);\n        }\n    }\n    var ret = this.output.string(this, this.output.queue);\n    this.tmp.just_looking = false;\n    this.tmp.suppress_decorations = origSuppressDecorations;\n    // Cache the result.\n    this.tmp.group_context.replace(oldTermSiblingLayer);\n    return ret;\n};\n\n/**\n * Return delimiter for use in join\n * <p>Splice evaluation is done during cite\n * rendering, and this method returns the\n * result.  Evaluation requires three items\n * of information from the preceding cite, if\n * one is present: the names used; the years\n * used; and the suffix appended to the\n * citation.  These details are copied into\n * the state object before processing begins,\n * and are cleared by the processor on\n * completion of the run.</p>\n */\n\nCSL.getSpliceDelimiter = function (last_locator, last_collapsed, pos) {\n    //print(pos +  \" after-collapse-delimiter=\"+this.citation.opt[\"after-collapse-delimiter\"] + \"\\n  cite_group_delimiter=\" + this.tmp.use_cite_group_delimiter + \"\\n  last_collapsed=\" +last_collapsed + \"\\n  have_collapsed=\" +this.tmp.have_collapsed + \"\\n  last_locator=\" + last_locator)\n    if (undefined !== this.citation.opt[\"after-collapse-delimiter\"]) {\n        if (last_locator) {\n            this.tmp.splice_delimiter = this.citation.opt[\"after-collapse-delimiter\"];\n        } else if (last_collapsed && !this.tmp.have_collapsed) {\n            this.tmp.splice_delimiter = this.citation.opt[\"after-collapse-delimiter\"];\n        } else if (!last_collapsed && !this.tmp.have_collapsed && this.citation.opt.collapse !== \"year-suffix\") {\n            this.tmp.splice_delimiter = this.citation.opt[\"after-collapse-delimiter\"];\n        } else {\n            this.tmp.splice_delimiter = this.citation.opt.layout_delimiter;\n        }\n    } else if (this.tmp.use_cite_group_delimiter) {\n        this.tmp.splice_delimiter = this.citation.opt.cite_group_delimiter;\n    } else {\n        if (this.tmp.have_collapsed && this.opt.xclass === \"in-text\" && this.opt.update_mode !== CSL.NUMERIC) {\n            this.tmp.splice_delimiter = \", \";\n        } else if (this.tmp.cite_locales[pos - 1]) {\n            //\n            // Must have a value to take effect.  Use zero width space to force empty delimiter.\n            var alt_affixes = this.tmp.cite_affixes[this.tmp.area][this.tmp.cite_locales[pos - 1]];\n            if (alt_affixes && alt_affixes.delimiter) {\n                this.tmp.splice_delimiter = alt_affixes.delimiter;\n            }\n        } else if (!this.tmp.splice_delimiter) {\n            // This happens when no delimiter is set on cs:layout under cs:citation\n            this.tmp.splice_delimiter = \"\";\n        }\n    }\n\n/*\n    if (last_locator && \"string\" === typeof this.citation.opt[\"after-collapse-delimiter\"]) {\n        this.tmp.splice_delimiter = this.citation.opt[\"after-collapse-delimiter\"];\n    } else if (last_collapsed && !this.tmp.have_collapsed && \"string\" === typeof this.citation.opt[\"after-collapse-delimiter\"]) {\n        this.tmp.splice_delimiter = this.citation.opt[\"after-collapse-delimiter\"];\n    } else if (!last_collapsed && !this.tmp.have_collapsed && \"string\" === typeof this.citation.opt[\"after-collapse-delimiter\"] && !this.citation.opt.collapse === \"year-suffix\") {\n        this.tmp.splice_delimiter = this.citation.opt[\"after-collapse-delimiter\"];\n    } else if (this.tmp.use_cite_group_delimiter) {\n        this.tmp.splice_delimiter = this.citation.opt.cite_group_delimiter;\n    } else if (this.tmp.have_collapsed && this.opt.xclass === \"in-text\" && this.opt.update_mode !== CSL.NUMERIC) {\n        this.tmp.splice_delimiter = \", \";\n    } else if (this.tmp.cite_locales[pos - 1]) {\n        //\n        // Must have a value to take effect.  Use zero width space to force empty delimiter.\n        var alt_affixes = this.tmp.cite_affixes[this.tmp.area][this.tmp.cite_locales[pos - 1]];\n        if (alt_affixes && alt_affixes.delimiter) {\n            this.tmp.splice_delimiter = alt_affixes.delimiter;\n        }\n    } else if (!this.tmp.splice_delimiter) {\n        // This happens when no delimiter is set on cs:layout under cs:citation\n        this.tmp.splice_delimiter = \"\";\n    }\n*/\n    // Paranoia\n    //if (!this.tmp.splice_delimiter) {\n    //    this.tmp.splice_delimiter = \"\";\n    //}\n    return this.tmp.splice_delimiter;\n};\n\n/*\n * Compose individual cites into a single string, with\n * flexible inter-cite splicing.\n */\nCSL.getCitationCluster = function (inputList, citation) {\n    var result, objects, myparams, len, pos, item, last_collapsed, params, empties, composite, compie, myblobs, Item, llen, ppos, obj, preceding_item, txt_esc, error_object, citationID, authorOnly, suppressAuthor;\n    var citation_prefix = \"\";\n    this.output.checkNestedBrace = new CSL.checkNestedBrace(this);\n    if (citation) {\n        citationID = citation.citationID;\n        authorOnly = citation.properties.mode === \"author-only\" ? !!citation.properties.mode : false;\n        if (this.opt.xclass !== \"note\") {\n            suppressAuthor = citation.properties.mode === \"suppress-author\" ? !!citation.properties.mode : false;\n        }\n        if (citation.properties.prefix) {\n            citation_prefix = CSL.checkPrefixSpaceAppend(this, citation.properties.prefix);\n        }\n    }\n    inputList = inputList ? inputList : [];\n    this.tmp.last_primary_names_string = false;\n    txt_esc = CSL.getSafeEscape(this);\n    this.tmp.area = \"citation\";\n    this.tmp.root = \"citation\";\n    result = \"\";\n    objects = [];\n    this.tmp.last_suffix_used = \"\";\n    this.tmp.last_names_used = [];\n    this.tmp.last_years_used = [];\n    this.tmp.backref_index = [];\n    this.tmp.cite_locales = [];\n    if (!this.tmp.just_looking) {\n        this.tmp.abbrev_trimmer = {\n            QUASHES: {}\n        };\n    }\n\n    var use_layout_prefix = this.output.checkNestedBrace.update(this.citation.opt.layout_prefix + citation_prefix);\n    //var use_layout_prefix = this.citation.opt.layout_prefix;\n\n    var suppressTrailingPunctuation = false;\n    if (this.citation.opt.suppressTrailingPunctuation) {\n        suppressTrailingPunctuation = true;\n    }\n    if (citationID) {\n        //this.registry.citationreg.citationById[citationID].properties.backref_index = false;\n        //this.registry.citationreg.citationById[citationID].properties.backref_citation = false;\n        if (this.registry.citationreg.citationById[citationID].properties[\"suppress-trailing-punctuation\"]) {\n            suppressTrailingPunctuation = true;\n        }\n    }\n\n    // Adjust locator positions if that looks like a sensible thing to do.\n    if (this.opt.xclass === \"note\") {\n        var parasets = [];\n        var lastTitle = false;\n        var lastPosition = false;\n        var lastID = false;\n        var lst = [];\n        for (var i=0, ilen = inputList.length; i < ilen; i += 1) {\n            var type = inputList[i][0].type;\n            var title = inputList[i][0].title;\n            var position = inputList[i][1].position;\n            var id = inputList[i][0].id;\n            if (title && type === \"legal_case\" && id !== lastID && position) {\n                // Start a fresh sublist if the item title does not match the last one\n                if (title !== lastTitle || parasets.length === 0) {\n                    lst = [];\n                    parasets.push(lst);\n                }\n                lst.push(inputList[i][1]);\n            }\n            lastTitle = title;\n            lastPosition = position;\n            lastID = id;\n        }\n        // We now have a list of sublists, each w/matching titles\n        for (i=0, ilen=parasets.length; i < ilen; i += 1) {\n            lst = parasets[i];\n            if (lst.length < 2) {\n                continue;\n            }\n            // Get the locator in last position, but only if it's the only one in the set.\n            var locatorInLastPosition = lst.slice(-1)[0].locator;\n            if (locatorInLastPosition) {\n                for (var j=0, jlen=lst.length - 1; j < jlen; j += 1) {\n                    if (lst[j].locator) {\n                        locatorInLastPosition = false;\n                    }\n                }\n            }\n            // move the locator here, if it's called for.\n            if (locatorInLastPosition) {\n                lst[0].locator = locatorInLastPosition;\n                delete lst.slice(-1)[0].locator;\n                lst[0].label = lst.slice(-1)[0].label;\n                if (lst.slice(-1)[0].label) {\n                    delete lst.slice(-1)[0].label;\n                }\n            }\n       }\n    }\n    myparams = [];\n    len = inputList.length;\n    if (inputList[0] && inputList[0][1]) {\n        if (authorOnly) {\n            delete inputList[0][1][\"suppress-author\"];\n            inputList[0][1][\"author-only\"] = true;\n        } else if (suppressAuthor) {\n            delete inputList[0][1][\"author-only\"];\n            inputList[0][1][\"suppress-author\"] = true;\n        }\n    }\n    if (this.opt.parallel.enable) {\n        this.parallel.StartCitation(inputList);\n    }\n    for (pos = 0; pos < len; pos += 1) {\n\n        // Also for parallels only\n        this.tmp.cite_index = pos;\n\n        Item = inputList[pos][0];\n        item = inputList[pos][1];\n        item = CSL.parseLocator.call(this, item);\n        last_collapsed = this.tmp.have_collapsed;\n        var last_locator = false;\n        if (pos > 0 && inputList[pos-1][1]) {\n            last_locator = !!inputList[pos-1][1].locator;\n        }\n        params = {};\n        \n        // Reset shadow_numbers here, suppress reset in getCite()\n        this.tmp.shadow_numbers = {};\n        if (!this.tmp.just_looking && this.opt.hasPlaceholderTerm) {\n            var output = this.output;\n            this.output = new CSL.Output.Queue(this);\n            this.output.adjust = new CSL.Output.Queue.adjust();\n            CSL.getAmbiguousCite.call(this, Item, null, false, item);\n            this.output = output;\n        }\n\n        this.tmp.in_cite_predecessor = false;\n        // true is to block reset of shadow numbers\n        \n        \n        if (pos > 0) {\n            CSL.getCite.call(this, Item, item, \"\" + inputList[(pos - 1)][0].id, true);\n        } else {\n            this.tmp.term_predecessor = false;\n            CSL.getCite.call(this, Item, item, null, true);\n        }\n\n        // Make a note of any errors\n        if (!this.tmp.cite_renders_content) {\n            error_object = {\n                citationID: \"\" + this.tmp.citation_id,\n                index: this.tmp.citation_pos,\n                noteIndex: this.tmp.citation_note_index,\n                itemID: \"\" + Item.id,\n                citationItems_pos: pos,\n                error_code: CSL.ERROR_NO_RENDERED_FORM\n            };\n            this.tmp.citation_errors.push(error_object);\n        }\n        params.splice_delimiter = CSL.getSpliceDelimiter.call(this, last_locator, last_collapsed, pos);\n        // XXX This appears to be superfluous.\n        if (item && item[\"author-only\"]) {\n            this.tmp.suppress_decorations = true;\n        }\n\n        if (pos > 0) {\n            preceding_item = inputList[pos - 1][1];\n\n            // XXX OR if preceding suffix is empty, and the current prefix begins with a full stop.\n\n            var precedingEndsInPeriodOrComma = preceding_item.suffix && [\";\", \".\", \",\"].indexOf(preceding_item.suffix.slice(-1)) > -1;\n            var currentStartsWithPeriodOrComma = !preceding_item.suffix && item.prefix && [\";\", \".\", \",\"].indexOf(item.prefix.slice(0, 1)) > -1;\n            if (precedingEndsInPeriodOrComma || currentStartsWithPeriodOrComma) {\n                var spaceidx = params.splice_delimiter.indexOf(\" \");\n                if (spaceidx > -1 && !currentStartsWithPeriodOrComma) {\n                    params.splice_delimiter = params.splice_delimiter.slice(spaceidx);\n                } else {\n                    params.splice_delimiter = \"\";\n                }\n            }\n        }\n        params.suppress_decorations = this.tmp.suppress_decorations;\n        params.have_collapsed = this.tmp.have_collapsed;\n        //\n        // XXXXX: capture parameters to an array, which\n        // will be of the same length as this.output.queue,\n        // corresponding to each element.\n        //\n        myparams.push(params);\n        if (item[\"author-only\"]) {\n            break;\n        }\n    }\n    //\n    // output.queue is a simple array.  do a slice\n    // of it to get each cite item, setting params from\n    // the array that was built in the preceding loop.\n    //\n    empties = 0;\n    myblobs = this.output.queue.slice();\n\n    var citation_suffix = \"\";\n    if (citation) {\n        citation_suffix = CSL.checkSuffixSpacePrepend(this, citation.properties.suffix);\n    }\n    var suffix = this.citation.opt.layout_suffix;\n    var last_locale = this.tmp.cite_locales[this.tmp.cite_locales.length - 1];\n    //\n    // Must have a value to take effect.  Use zero width space to force empty suffix.\n    if (last_locale && this.tmp.cite_affixes[this.tmp.area][last_locale] && this.tmp.cite_affixes[this.tmp.area][last_locale].suffix) {\n        suffix = this.tmp.cite_affixes[this.tmp.area][last_locale].suffix;\n    }\n    if (CSL.TERMINAL_PUNCTUATION.slice(0, -1).indexOf(suffix.slice(0, 1)) > -1) {\n        suffix = suffix.slice(0, 1);\n    }\n    //print(\"=== FROM CITE ===\");\n    suffix = this.output.checkNestedBrace.update(citation_suffix + suffix);\n\n\n    for (var i=0,ilen=this.output.queue.length;i<ilen;i+=1) {\n        CSL.Output.Queue.purgeEmptyBlobs(this.output.queue[i]);\n    }\n    if (!this.tmp.suppress_decorations && this.output.queue.length) {\n        if (!(this.opt.development_extensions.apply_citation_wrapper\n              && this.sys.wrapCitationEntry\n               && !this.tmp.just_looking\n              && this.tmp.area === \"citation\")) { \n\n            if (!suppressTrailingPunctuation) {\n                this.output.queue[this.output.queue.length - 1].strings.suffix = suffix;\n            }\n            this.output.queue[0].strings.prefix = use_layout_prefix;\n        }\n    }\n    if (this.opt.development_extensions.clean_up_csl_flaws) {\n        for (var j=0,jlen=this.output.queue.length;j<jlen;j+=1) {\n            //print(\"OUTPUT[5]: \"+JSON.stringify(this.output.queue[j],['strings','prefix','suffix','delimiter','blobs','decorations'],2))\n            this.output.adjust.upward(this.output.queue[j]);\n            //print(\"OUTPUT[4]: \"+JSON.stringify(this.output.queue[j],['strings','prefix','suffix','delimiter','blobs','decorations'],2))\n            this.output.adjust.leftward(this.output.queue[j]);\n            //print(\"OUTPUT[3]: \"+JSON.stringify(this.output.queue[j],['strings','prefix','suffix','delimiter','blobs','decorations'],2))\n            this.output.adjust.downward(this.output.queue[j]);\n            //print(\"OUTPUT[2]: \"+JSON.stringify(this.output.queue[j],['strings','prefix','suffix','delimiter','blobs','decorations'],2))\n            this.tmp.last_chr = this.output.adjust.fix(this.output.queue[j]);\n            //print(\"OUTPUT[1]: \"+JSON.stringify(this.output.queue[j],['strings','prefix','suffix','delimiter','blobs','decorations','num'],2))\n        }\n    }\n    //print(\"this.tmp.last_chr=\"+this.tmp.last_chr);\n    for (pos = 0, len = myblobs.length; pos < len; pos += 1) {\n        var buffer = [];\n        this.output.queue = [myblobs[pos]];\n        this.tmp.suppress_decorations = myparams[pos].suppress_decorations;\n        this.tmp.splice_delimiter = myparams[pos].splice_delimiter;\n        //\n        // oh, one last second thought on delimiters ...\n        //\n\n        if (myblobs[pos].parallel_delimiter) {\n            this.tmp.splice_delimiter = myblobs[pos].parallel_delimiter;\n        }\n        this.tmp.have_collapsed = myparams[pos].have_collapsed;\n\n        composite = this.output.string(this, this.output.queue);\n\n        this.tmp.suppress_decorations = false;\n        // meaningless assignment\n        // this.tmp.handle_ranges = false;\n        if (\"string\" === typeof composite) {\n            this.tmp.suppress_decorations = false;\n            if (!composite) {\n                if (this.opt.development_extensions.throw_on_empty) {\n                    CSL.error(\"Citation would render no content\");\n                } else {\n                    composite = \"[NO_PRINTED_FORM]\";\n                }\n            }\n            return composite;\n        }\n        if (\"object\" === typeof composite && composite.length === 0 && !item[\"suppress-author\"]) {\n            if (pos === 0) {\n                var errStr = \"[CSL STYLE ERROR: reference with no printed form.]\";\n                var preStr = pos === 0 ? txt_esc(this.citation.opt.layout_prefix) : \"\";\n                var sufStr = pos === (myblobs.length - 1) ? txt_esc(this.citation.opt.layout_suffix) : \"\";\n                composite.push(preStr + errStr + sufStr);\n            } else if (pos === myblobs.length - 1) {\n                var tmpobj = objects[objects.length - 1];\n                if (typeof tmpobj === \"string\") {\n                    objects[objects.length -1] += (txt_esc(this.citation.opt.layout_suffix));\n                } else if (typeof tmpobj === \"object\") {\n                    tmpobj.strings.suffix += (txt_esc(this.citation.opt.layout_suffix));\n                }\n            }\n        }\n        if (buffer.length && \"string\" === typeof composite[0]) {\n            composite.reverse();\n            var tmpstr = composite.pop();\n            if (tmpstr && tmpstr.slice(0, 1) === \",\") {\n                buffer.push(tmpstr);\n            } else if (\"string\" == typeof buffer.slice(-1)[0] && buffer.slice(-1)[0].slice(-1) === \",\") {\n                buffer.push(\" \" + tmpstr);\n            } else if (tmpstr) {\n                buffer.push(txt_esc(this.tmp.splice_delimiter) + tmpstr);\n            }\n        } else {\n            composite.reverse();\n            compie = composite.pop();\n            if (\"undefined\" !== typeof compie) {\n                if (buffer.length && \"string\" === typeof buffer[buffer.length - 1]) {\n                    buffer[buffer.length - 1] += compie.successor_prefix;\n                }\n                buffer.push(compie);\n            }\n        }\n        // Seems odd, but this was unnecessary and broken.\n        //composite.reverse();\n        llen = composite.length;\n        for (ppos = 0; ppos < llen; ppos += 1) {\n            obj = composite[ppos];\n            if (\"string\" === typeof obj) {\n                buffer.push(txt_esc(this.tmp.splice_delimiter) + obj);\n                continue;\n            }\n            compie = composite.pop();\n            if (\"undefined\" !== typeof compie) {\n                buffer.push(compie);\n            }\n        }\n        if (buffer.length === 0 && !inputList[pos][1][\"suppress-author\"]) {\n            empties += 1;\n        }\n        if (buffer.length > 1 && typeof buffer[0] !== \"string\") {\n            buffer = [this.output.renderBlobs(buffer)];\n        }\n        if (buffer.length) {\n            if (\"string\" === typeof buffer[0]) {\n                if (pos > 0) {\n                    buffer[0] = txt_esc(this.tmp.splice_delimiter) + buffer[0];\n                }\n            } else {\n                if (pos > 0) {\n                    buffer[0].splice_prefix = this.tmp.splice_delimiter;\n                } else {\n                    buffer[0].splice_prefix = \"\";\n                }\n            }\n        }\n        objects = objects.concat(buffer);\n    }\n    // print(\"OBJECTS=\"+objects);\n    result += this.output.renderBlobs(objects);\n\n    if (result) {\n        //if (CSL.TERMINAL_PUNCTUATION.indexOf(this.tmp.last_chr) > -1 \n        //    && this.tmp.last_chr === use_layout_suffix.slice(0, 1)) {\n        //    use_layout_suffix = use_layout_suffix.slice(1);\n        //}\n        if (!this.tmp.suppress_decorations) {\n            len = this.citation.opt.layout_decorations.length;\n            for (pos = 0; pos < len; pos += 1) {\n                params = this.citation.opt.layout_decorations[pos];\n                // The \"normal\" formats in some output modes expect\n                // a superior nested decoration environment, and\n                // so should produce no output here.\n                if (params[1] === \"normal\") {\n                    continue;\n                }\n                if (!item || !item[\"author-only\"]) {\n                    result = this.fun.decorate[params[0]][params[1]](this, result);\n                }\n            }\n        }\n    }\n    this.tmp.suppress_decorations = false;\n    if (!result) {\n        if (this.opt.development_extensions.throw_on_empty) {\n            CSL.error(\"Citation would render no content\");\n        } else {\n            result = \"[NO_PRINTED_FORM]\"\n        }\n    }\n    return result;\n};\n\n/*\n * Render a single cite item.\n *\n * This is called on the state object, with a single\n * Item as input.  It iterates exactly once over the style\n * citation tokens, and leaves the result of rendering in\n * the top-level list in the relevant *.opt.output\n * stack, as a list item consisting of a single string.\n *\n * (This is dual-purposed for generating individual\n * entries in a bibliography.)\n */\nCSL.getCite = function (Item, item, prevItemID, blockShadowNumberReset) {\n    var next, error_object;\n    var areaOrig = this.tmp.area;\n    if (item && item[\"author-only\"] && this.intext && this.intext.tokens.length > 0) {\n            this.tmp.area = \"intext\";\n    }\n    this.tmp.cite_renders_content = false;\n    this.tmp.probably_rendered_something = false;\n    this.tmp.prevItemID = prevItemID;\n\n    CSL.citeStart.call(this, Item, item, blockShadowNumberReset);\n    next = 0;\n    this.tmp.name_node = {};\n    this.nameOutput = new CSL.NameOutput(this, Item, item);\n\n    // rerun?\n    while (next < this[this.tmp.area].tokens.length) {\n        next = CSL.tokenExec.call(this, this[this.tmp.area].tokens[next], Item, item);\n    }\n\n    CSL.citeEnd.call(this, Item, item);\n    // Odd place for this, but it seems to fit here\n    if (!this.tmp.cite_renders_content && !this.tmp.just_looking) {\n        if (this.tmp.area === \"bibliography\") {\n            error_object = {\n                index: this.tmp.bibliography_pos,\n                itemID: \"\" + Item.id,\n                error_code: CSL.ERROR_NO_RENDERED_FORM\n            };\n            this.tmp.bibliography_errors.push(error_object);\n        }\n    }\n    this.tmp.area = areaOrig;\n    return \"\" + Item.id;\n};\n\n\nCSL.citeStart = function (Item, item, blockShadowNumberReset) {\n    this.tmp.lang_array = [];\n    if (Item.language) {\n        // Guard against garbage locales in user input\n        var m = Item.language.match(/^([a-zA-Z]+).*/);\n        if (m) {\n            this.tmp.lang_array.push(m[1].toLowerCase());\n        }\n    }\n    this.tmp.lang_array.push(this.opt.lang);\n    if (!blockShadowNumberReset) {\n        this.tmp.shadow_numbers = {};\n    }\n    \n    this.tmp.disambiguate_count = 0;\n    this.tmp.disambiguate_maxMax = 0;\n    this.tmp.same_author_as_previous_cite = false;\n    if (!this.tmp.suppress_decorations) {\n        this.tmp.subsequent_author_substitute_ok = true;\n    } else {\n        this.tmp.subsequent_author_substitute_ok = false;\n    }\n    this.tmp.lastchr = \"\";\n    if (this.tmp.area === \"citation\" && this.citation.opt.collapse && this.citation.opt.collapse.length) {\n        //this.tmp.have_collapsed = \"year\";\n        this.tmp.have_collapsed = true;\n    } else {\n        this.tmp.have_collapsed = false;\n    }\n    this.tmp.render_seen = false;\n    if (this.tmp.disambig_request  && ! this.tmp.disambig_override) {\n        this.tmp.disambig_settings = this.tmp.disambig_request;\n    } else if (this.registry.registry[Item.id] && ! this.tmp.disambig_override) {\n        this.tmp.disambig_request = this.registry.registry[Item.id].disambig;\n        this.tmp.disambig_settings = this.registry.registry[Item.id].disambig;\n    } else {\n        this.tmp.disambig_settings = new CSL.AmbigConfig();\n    }\n    if (this.tmp.area !== 'citation') {\n        if (!this.registry.registry[Item.id]) {\n            this.tmp.disambig_restore = new CSL.AmbigConfig();\n        } else {\n            this.tmp.disambig_restore = CSL.cloneAmbigConfig(this.registry.registry[Item.id].disambig);\n            if (this.tmp.area === 'bibliography' && this.tmp.disambig_settings && this.tmp.disambig_override) {\n                if (this.opt[\"disambiguate-add-names\"]) {\n                    this.tmp.disambig_settings.names = this.registry.registry[Item.id].disambig.names.slice();\n                    if (this.tmp.disambig_request) {\n                        this.tmp.disambig_request.names = this.registry.registry[Item.id].disambig.names.slice();\n                    }\n                }\n                if (this.opt[\"disambiguate-add-givenname\"]) {\n                    // This is weird and delicate and not fully understood\n                    this.tmp.disambig_request = this.tmp.disambig_settings;\n                    this.tmp.disambig_settings.givens = this.registry.registry[Item.id].disambig.givens.slice();\n                    this.tmp.disambig_request.givens = this.registry.registry[Item.id].disambig.givens.slice();\n                    for (var i=0,ilen=this.tmp.disambig_settings.givens.length;i<ilen;i+=1) {\n                        this.tmp.disambig_settings.givens[i] = this.registry.registry[Item.id].disambig.givens[i].slice();\n                    }\n                    for (var i=0,ilen=this.tmp.disambig_request.givens.length;i<ilen;i+=1) {\n                        this.tmp.disambig_request.givens[i] = this.registry.registry[Item.id].disambig.givens[i].slice();\n                    }\n                }\n            }\n        }\n    }\n\n    this.tmp.names_used = [];\n    this.tmp.nameset_counter = 0;\n    this.tmp.years_used = [];\n    this.tmp.names_max.clear();\n    if (!this.tmp.just_looking) {\n        if (!item || item.parallel === \"first\" || !item.parallel) {\n            this.tmp.abbrev_trimmer = {\n                QUASHES: {}\n            };\n        }\n    }\n\n    this.tmp.splice_delimiter = this[this.tmp.area].opt.layout_delimiter;\n    //this.tmp.splice_delimiter = this[this.tmp.area].opt.delimiter;\n\n    this.bibliography_sort.keys = [];\n    this.citation_sort.keys = [];\n\n    this.tmp.has_done_year_suffix = false;\n    this.tmp.last_cite_locale = false;\n    // SAVE PARAMETERS HERE, IF APPROPRIATE\n    // (promiscuous addition of global parameters => death by a thousand cuts)\n    if (!this.tmp.just_looking && item && !item.position && this.registry.registry[Item.id]) {\n        this.tmp.disambig_restore = CSL.cloneAmbigConfig(this.registry.registry[Item.id].disambig);\n    }\n    // XXX This only applied to the \"number\" variable itself? Huh?\n    //this.setNumberLabels(Item);\n    this.tmp.first_name_string = false;\n    this.tmp.authority_stop_last = 0;\n};\n\nCSL.citeEnd = function (Item, item) {\n    // RESTORE PARAMETERS IF APPROPRIATE\n    if (this.tmp.disambig_restore && this.registry.registry[Item.id]) {\n        this.registry.registry[Item.id].disambig.names = this.tmp.disambig_restore.names.slice();\n        this.registry.registry[Item.id].disambig.givens = this.tmp.disambig_restore.givens.slice();\n        for (var i=0,ilen=this.registry.registry[Item.id].disambig.givens.length;i<ilen;i+=1) {\n            this.registry.registry[Item.id].disambig.givens[i] = this.tmp.disambig_restore.givens[i].slice();\n        }\n    }\n    this.tmp.disambig_restore = false;\n\n    if (item && item.suffix) {\n        //this.tmp.last_suffix_used = this.tmp.suffix.value();\n        this.tmp.last_suffix_used = item.suffix;\n    } else {\n        this.tmp.last_suffix_used = \"\";\n    }\n    this.tmp.last_years_used = this.tmp.years_used.slice();\n    this.tmp.last_names_used = this.tmp.names_used.slice();\n    this.tmp.cut_var = false;\n\n    // This is a hack, in a way; I have lost track of where\n    // the disambig (name rendering) settings used for rendering work their way\n    // into the registry.  This resets defaults to the subsequent form,\n    // when first cites are rendered.\n    //if (this.tmp.disambig_restore && this.registry.registry[Item.id]) {\n    //    this.registry.registry[Item.id].disambig = this.tmp.disambig_restore;\n    //}\n    //this.tmp.disambig_restore = false;\n    this.tmp.disambig_request = false;\n\n    this.tmp.cite_locales.push(this.tmp.last_cite_locale);\n\n    if (this.tmp.issued_date && this.tmp.renders_collection_number) {\n        var buf = [];\n        for (var i = this.tmp.issued_date.list.length - 1; i > this.tmp.issued_date.pos; i += -1) {\n            buf.push(this.tmp.issued_date.list.pop());\n        }\n        // Throw away the unwanted blob\n        this.tmp.issued_date.list.pop();\n        // Put the other stuff back\n        for (i = buf.length - 1; i > -1; i += -1) {\n            this.tmp.issued_date.list.push(buf.pop());\n        }\n    }\n    this.tmp.issued_date = false;\n    this.tmp.renders_collection_number = false;\n\n};\n\n/*global CSL: true */\n\nCSL.Engine.prototype.makeBibliography = function (bibsection) {\n    var debug, ret, params, maxoffset, item, len, pos, tok, tokk, tokkk, entry_ids, entry_strings;\n    debug = false;\n    if (!bibsection && (this.bibliography.opt.exclude_types || this.bibliography.opt.exclude_with_fields)) {\n        bibsection = {\n            exclude: []\n        };\n        if (this.bibliography.opt.exclude_types) {\n            for (var i in this.bibliography.opt.exclude_types) {\n                var val = this.bibliography.opt.exclude_types[i];\n                bibsection.exclude.push({\n                    field: \"type\",\n                    value: val\n                });\n            }\n        }\n        if (this.bibliography.opt.exclude_with_fields) {\n            for (var i in this.bibliography.opt.exclude_with_fields) {\n                var field = this.bibliography.opt.exclude_with_fields[i];\n                bibsection.exclude.push({\n                    field: field, value: true\n                });\n            }\n        }\n    }\n    // API change: added in version 1.0.51\n    if (!this.bibliography.tokens.length) {\n        return false;\n    }\n    if (\"string\" === typeof bibsection) {\n        this.opt.citation_number_slug = bibsection;\n        bibsection = false;\n    }\n    //SNIP-START\n    if (debug) {\n        len = this.bibliography.tokens.length;\n        for (pos = 0; pos < len; pos += 1) {\n            tok = this.bibliography.tokens[pos];\n            CSL.debug(\"bibtok: \" + tok.name);\n        }\n        CSL.debug(\"---\");\n        len = this.citation.tokens.length;\n        for (pos = 0; pos < len; pos += 1) {\n            tokk = this.citation.tokens[pos];\n            CSL.debug(\"cittok: \" + tok.name);\n        }\n        CSL.debug(\"---\");\n        len = this.bibliography_sort.tokens.length;\n        for (pos = 0; pos < len; pos += 1) {\n            tokkk = this.bibliography_sort.tokens[pos];\n            CSL.debug(\"bibsorttok: \" + tok.name);\n        }\n    }\n    //SNIP-END\n\n    // For paged returns\n    ret = CSL.getBibliographyEntries.call(this, bibsection);\n    entry_ids = ret[0];\n    entry_strings = ret[1];\n\n    // For paged returns\n    var done = ret[2];\n\n    params = {\n        \"maxoffset\": 0,\n        \"entryspacing\": this.bibliography.opt[\"entry-spacing\"],\n        \"linespacing\": this.bibliography.opt[\"line-spacing\"],\n        \"second-field-align\": false,\n        \"entry_ids\": entry_ids,\n        \"bibliography_errors\": this.tmp.bibliography_errors.slice(),\n        \"done\": done\n    };\n    if (this.bibliography.opt[\"second-field-align\"]) {\n        params[\"second-field-align\"] = this.bibliography.opt[\"second-field-align\"];\n    }\n    maxoffset = 0;\n    len = this.registry.reflist.length;\n    for (pos = 0; pos < len; pos += 1) {\n        item = this.registry.reflist[pos];\n        if (item.offset > params.maxoffset) {\n            params.maxoffset = item.offset;\n        }\n    }\n    if (this.bibliography.opt.hangingindent) {\n        params.hangingindent = this.bibliography.opt.hangingindent;\n    }\n    params.bibstart = this.fun.decorate.bibstart;\n    params.bibend = this.fun.decorate.bibend;\n\n    this.opt.citation_number_slug = false;\n    return [params, entry_strings];\n};\n\n/*\n * Compose individual cites into a single string.\n */\nCSL.getBibliographyEntries = function (bibsection) {\n    var ret, input, include, anymatch, allmatch, bib_entry, res, item, spec, lllen, pppos, topblobs, entry_item_ids, debug, i, ilen, siblings, skips, sortedItems, eyetem, entry_item_data, j, jlen;\n    ret = [];\n    entry_item_data = [];\n    this.tmp.area = \"bibliography\";\n    this.tmp.root = \"bibliography\";\n    this.tmp.last_rendered_name = false;\n    this.tmp.bibliography_errors = [];\n    this.tmp.bibliography_pos = 0;\n    \n    // For paged returns: disable generated entries and\n    // do not fetch full items as a batch (input variable\n    // consists of ids only in this case)\n    if (bibsection && bibsection.page_start && bibsection.page_length) {\n        input = this.registry.getSortedIds();        \n    } else {\n        input = this.refetchItems(this.registry.getSortedIds());\n    }\n    \n    this.tmp.disambig_override = true;\n    function eval_string(a, b) {\n        if (a === b) {\n            return true;\n        }\n        return false;\n    }\n    function eval_list(a, lst) {\n        lllen = lst.length;\n        for (pppos = 0; pppos < lllen; pppos += 1) {\n            if (eval_string(a, lst[pppos])) {\n                return true;\n            }\n        }\n        return false;\n    }\n    function eval_spec(a, b) {\n        if (\"boolean\" === typeof a || !a) {\n            if (a) {\n                return !!b;\n            } else {\n                return !b;\n            }\n        } else {\n            if (\"string\" === typeof b) {\n                return eval_string(a, b);\n            } else if (!b) {\n                return false;\n            } else {\n                return eval_list(a, b);\n            }\n        }\n    }\n\n    skips = {};\n\n    // For paged returns\n    var page_item_count;\n    if (bibsection && bibsection.page_start && bibsection.page_length) {\n        page_item_count = 0;\n        if (bibsection.page_start !== true) {\n            for (i = 0, ilen = input.length; i < ilen; i += 1) {\n                skips[input[i]] = true;\n                if (bibsection.page_start == input[i]) {\n                    break;\n                }\n            }\n        }\n    }\n\n    var processed_item_ids = [];\n\n    var consolidatedIDs = {};\n    this.tmp.container_item_count = {};\n    input = input.filter(o => {\n        var ret = o;\n        if (o.legislation_id) {\n            if (consolidatedIDs[o.legislation_id]) {\n                ret = false;\n            } else {\n                consolidatedIDs[o.legislation_id] = true;\n            }\n        } else if (o.container_id) {\n            if (!this.tmp.container_item_count[o.container_id]) {\n                this.tmp.container_item_count[o.container_id] = 0;\n            }\n            this.tmp.container_item_count[o.container_id]++;\n            if (this.bibliography.opt.consolidate_containers.indexOf(o.type) > -1) {\n                if (consolidatedIDs[o.container_id]) {\n                    ret = false;\n                } else {\n                    consolidatedIDs[o.container_id] = true;\n                }\n            }\n        }\n        return ret;\n    });\n\n    this.tmp.container_item_pos = {};\n\n    for (i = 0, ilen = input.length; i < ilen; i += 1) {\n        \n        // For paged returns\n        if (bibsection && bibsection.page_start && bibsection.page_length) {\n            if (skips[input[i]]) {\n                continue;\n            }\n            item = this.refetchItem(input[i]);\n            if (page_item_count === bibsection.page_length) {\n                break;\n            }\n        } else {\n            item = input[i];\n            if (skips[item.id]) {\n                continue;\n            }\n        }\n        if (bibsection) {\n            include = true;\n            if (bibsection.include) {\n                //\n                // Opt-in: these are OR-ed.\n                //\n                include = false;\n                for (j = 0, jlen = bibsection.include.length; j < jlen; j += 1) {\n                    spec = bibsection.include[j];\n                    if (eval_spec(spec.value, item[spec.field])) {\n                        include = true;\n                        break;\n                    }\n                }\n            } else if (bibsection.exclude) {\n                //\n                // Opt-out: these are also OR-ed.\n                //\n                anymatch = false;\n                for (j = 0, jlen = bibsection.exclude.length; j < jlen; j += 1) {\n                    spec = bibsection.exclude[j];\n                    if (eval_spec(spec.value, item[spec.field])) {\n                        anymatch = true;\n                        break;\n                    }\n                }\n                if (anymatch) {\n                    include = false;\n                }\n            } else if (bibsection.select) {\n                //\n                // Multiple condition opt-in: these are AND-ed.\n                //\n                include = false;\n                allmatch = true;\n                for (j = 0, jlen = bibsection.select.length; j < jlen; j += 1) {\n                    spec = bibsection.select[j];\n                    if (!eval_spec(spec.value, item[spec.field])) {\n                        allmatch = false;\n                    }\n                }\n                if (allmatch) {\n                    include = true;\n                }\n            }\n            if (bibsection.quash) {\n                //\n                // Stop criteria: These are AND-ed.\n                //\n                allmatch = true;\n                for (j = 0, jlen = bibsection.quash.length; j < jlen; j += 1) {\n                    spec = bibsection.quash[j];\n                    if (!eval_spec(spec.value, item[spec.field])) {\n                        allmatch = false;\n                    }\n                }\n                if (allmatch) {\n                    include = false;\n                }\n            }\n            if (!include) {\n                continue;\n            }\n        }\n        //SNIP-START\n        if (debug) {\n            CSL.debug(\"BIB: \" + item.id);\n        }\n\n        if (item.container_id) {\n            if (!this.tmp.container_item_pos[item.container_id]) {\n                this.tmp.container_item_pos[item.container_id] = 0;\n            }\n            this.tmp.container_item_pos[item.container_id]++;\n        }\n        \n        //SNIP-END\n        bib_entry = new CSL.Token(\"group\", CSL.START);\n        bib_entry.decorations = [[\"@bibliography\", \"entry\"]].concat(this.bibliography.opt.layout_decorations);\n        this.output.startTag(\"bib_entry\", bib_entry);\n        if (item.system_id && this.sys.embedBibliographyEntry) {\n            this.output.current.value().item_id = item.system_id;\n        } else {\n            this.output.current.value().system_id = item.id;\n        }\n\n        // 2019-06-25 Hacked to conform to new parallels evaluation method\n        // 2020-04-25 Revised to work with latest, and final, parallel-first/parallel-last attributes\n        entry_item_ids = [];\n        if (this.registry.registry[item.id].master\n            && !(bibsection && bibsection.page_start && bibsection.page_length)) {\n            // Fetch item content\n            sortedItems = [[item, {id: item.id}]];\n            siblings = this.registry.registry[item.id].siblings;\n            for (var j=0,jlen=siblings.length; j<jlen; j++) {\n               sortedItems.push([this.refetchItem(siblings[j]), {id: siblings[j]}]);\n            }\n            // Adjust parameters\n            this.parallel.StartCitation(sortedItems);\n            if (this.registry.registry[item.id].parallel_delimiter_override) {\n                this.output.queue[0].strings.delimiter = this.registry.registry[item.id].parallel_delimiter_override;\n            } else {\n                this.output.queue[0].strings.delimiter = \", \";\n            }\n            this.tmp.term_predecessor = false;\n            this.tmp.cite_index = 0;\n            // Run cites\n            for (j = 0, jlen = sortedItems.length; j < jlen; j += 1) {\n                if (j < (sortedItems.length - 1)) {\n                    this.tmp.parallel_and_not_last = true;\n                } else {\n                    delete this.tmp.parallel_and_not_last;\n                }\n                entry_item_ids.push(\"\" + CSL.getCite.call(this, sortedItems[j][0], sortedItems[j][1]));\n                this.tmp.cite_index++;\n                skips[sortedItems[j][0].id] = true;\n            }\n        } else if (!this.registry.registry[item.id].siblings) {\n            this.tmp.term_predecessor = false;\n            this.tmp.cite_index = 0;\n            entry_item_ids.push(\"\" + CSL.getCite.call(this, item));\n            if (bibsection && bibsection.page_start && bibsection.page_length) {\n                page_item_count += 1;\n            }\n            //skips[item.id] = true;\n        }\n        // For RDF support\n        entry_item_data.push(\"\");\n\n        this.tmp.bibliography_pos += 1;\n\n        processed_item_ids.push(entry_item_ids);\n        //\n        // XXX: loop to render parallels goes here\n        // XXX: just have to mark them somehow ...\n        //\n        this.output.endTag(\"bib_entry\");\n        //\n        // place layout prefix on first blob of each cite, and suffix\n        // on the last non-empty blob of each cite.  there be dragons\n        // here.\n        //\n        if (this.output.queue[0].blobs.length && this.output.queue[0].blobs[0].blobs.length) {\n            // The output queue stuff needs cleaning up.  the result of\n            // output.current.value() is sometimes a blob, sometimes its list\n            // of blobs.  this inconsistency is a source of confusion, and\n            // should be cleaned up across the code base in the first\n            // instance, before making any other changes to output code.\n            if (!this.output.queue[0].blobs[0].blobs[0].strings) {\n                topblobs = this.output.queue[0].blobs;\n            } else {\n                topblobs = this.output.queue[0].blobs[0].blobs;\n            }\n            topblobs[0].strings.prefix = this.bibliography.opt.layout_prefix + topblobs[0].strings.prefix;\n        }\n        for (j=0,jlen=this.output.queue.length;j<jlen;j+=1) {\n            CSL.Output.Queue.purgeEmptyBlobs(this.output.queue[j]);\n            //print(\"XXX: \"+JSON.stringify(this.output.queue[j],['strings','prefix','suffix','delimiter','blobs','decorations'],2))\n        }\n        for (j=0,jlen=this.output.queue.length;j<jlen;j+=1) {\n            this.output.adjust.upward(this.output.queue[j]);\n            this.output.adjust.leftward(this.output.queue[j]);\n            this.output.adjust.downward(this.output.queue[j],true);\n            this.output.adjust.fix(this.output.queue[j]);\n            //print(\"OUTPUT: \"+JSON.stringify(this.output.queue[j],['strings','prefix','suffix','delimiter','blobs','decorations'],2))\n        }\n\n        //print(\"DUMP \"+JSON.stringify(this.output.queue, [\"strings\", \"decorations\", \"prefix\", \"suffix\", \"delimiter\", \"blobs\"], 2));\n\n        // XXX Need to account for numeric blobs in input.\n        // XXX No idea how this could have worked previously.\n\n        //print(\"BLOBS \"+this.output.queue[0].blobs[0].blobs);\n\n        //print(\"JSON \"+JSON.stringify(this.output.queue[0].blobs, null, 2));\n\n        res = this.output.string(this, this.output.queue)[0];\n        \n        if (!res && this.opt.update_mode === CSL.NUMERIC) {\n            var err = (ret.length + 1) + \". [CSL STYLE ERROR: reference with no printed form.]\";\n            res = CSL.Output.Formats[this.opt.mode][\"@bibliography/entry\"](this, err);\n        }\n        if (res) {\n            ret.push(res);\n        }\n    }\n\n    var done = false;\n    if (bibsection && bibsection.page_start && bibsection.page_length) {\n        var last_expected_id = input.slice(-1)[0];\n        var last_seen_id = processed_item_ids.slice(-1)[0];\n        if (!last_expected_id || !last_seen_id || last_expected_id == last_seen_id) {\n            done = true;\n        }\n    }\n    this.tmp.disambig_override = false;\n\n    // XXX done\n    return [processed_item_ids, ret, done];\n};\n\n/*global CSL: true */\n\n\nCSL.Engine.prototype.setCitationId = function (citation, force) {\n    var ret, id, direction;\n    ret = false;\n    if (!citation.citationID || force) {\n        id = Math.floor(Math.random() * 100000000000000);\n        while (true) {\n            direction = 0;\n            if (!this.registry.citationreg.citationById[id]) {\n                // In case the ID is used as an HTML identifier in the\n                // calling application.\n                //   https://github.com/Juris-M/citeproc-js/issues/22\n                citation.citationID = \"a\" + id.toString(32);\n                break;\n            } else if (!direction && id < 50000000000000) {\n                direction = 1;\n            } else {\n                direction = -1;\n            }\n            if (direction === 1) {\n                id += 1;\n            } else {\n                id += -1;\n            }\n        }\n        ret = \"\" + id;\n    }\n    this.registry.citationreg.citationById[citation.citationID] = citation;\n    return ret;\n};\n\nCSL.Engine.prototype.rebuildProcessorState = function (citations, mode, uncitedItemIDs) {\n    // Rebuilds the processor from scratch, based on a list of citation\n    // objects. In a dynamic application, once the internal state of processor\n    // is established, citations should edited with individual invocations\n    // of processCitationCluster().\n\n    // citations is a list of citation objects in document order.\n    // mode is one of \"html\", \"text\" or \"rtf\".\n    // uncitedItemIDs is a list of itemIDs or a JS object with itemIDs as keys.\n    // Returns a list of [citationID,noteIndex,string] triples in document order.\n    // Set citation.properties.noteIndex to 0 for in-text citations.\n    // It is not necessary to run updateItems() before this function.\n    if (!citations) {\n        citations = [];\n    }\n    if (!mode) {\n        mode = 'html';\n    }\n    var doneIDs = {};\n    var itemIDs = [];\n    for (var i=0,ilen=citations.length;i<ilen;i+=1) {\n        for (var j=0,jlen=citations[i].citationItems.length;j<jlen;j+=1) {\n            var itemID = \"\" + citations[i].citationItems[j].id;\n            if (!doneIDs[itemID]) {\n                itemIDs.push(itemID);\n            }\n            doneIDs[itemID] = true;\n        }\n    }\n    this.updateItems(itemIDs);\n    var pre = [];\n    var post = [];\n    var ret = [];\n    var oldMode = this.opt.mode;\n    this.setOutputFormat(mode);\n    for (var i=0,ilen=citations.length;i<ilen;i+=1) {\n        // res contains a result report and a list of [index,string] pairs\n        // index begins at 0\n        var res = this.processCitationCluster(citations[i],pre,post,CSL.ASSUME_ALL_ITEMS_REGISTERED);\n        pre.push([citations[i].citationID,citations[i].properties.noteIndex]);\n        for (var j=0,jlen=res[1].length;j<jlen;j+=1) {\n            var index = res[1][j][0];\n            ret[index] = [\n                pre[index][0],\n                pre[index][1],\n                res[1][j][1]\n            ];\n        }\n    }\n    this.updateUncitedItems(uncitedItemIDs);\n    this.setOutputFormat(oldMode);\n    return ret;\n};\n\n\nCSL.Engine.prototype.restoreProcessorState = function (citations) {\n    var i, ilen, j, jlen, item, Item, newitem, citationList, itemList, sortedItems;\n    \n    // This function is deprecated.\n    // Use rebuildProcessorState() instead.\n\n    // Quickly restore state from citation details retained by\n    // calling application.\n    //\n    // if citations are provided, position details and sortkeys \n    // on the citation objects are are assumed to be correct.  Item\n    // data is retrieved, and sortedItems arrays are created and\n    // sorted as required by the current style.\n    //\n    // If citations is an empty list or nil, reset processor to\n    // empty state.\n    citationList = [];\n    itemList = [];\n    if (!citations) {\n        citations = [];\n    }\n    // Adjust citationIDs to avoid duplicates, save off index numbers\n    var indexNumbers = [];\n    var citationIds = {};\n    for (i = 0, ilen = citations.length; i < ilen; i += 1) {\n        if (citationIds[citations[i].citationID]) {\n            this.setCitationId(citations[i], true);\n        }\n        citationIds[citations[i].citationID] = true;\n        indexNumbers.push(citations[i].properties.index);\n    }\n    // Slice citations and sort by their declared index positions, if any,\n    // then reassign index and noteIndex numbers.\n    var oldCitations = citations.slice();\n    oldCitations.sort(\n        function (a,b) {\n            if (a.properties.index < b.properties.index) {\n                return -1;\n            } else if (a.properties.index > b.properties.index) {\n                return 1;\n            } else {\n                return 0;\n            }\n        }\n    );\n    for (i = 0, ilen = oldCitations.length; i < ilen; i += 1) {\n        oldCitations[i].properties.index = i;\n    }\n    for (i = 0, ilen = oldCitations.length; i < ilen; i += 1) {\n        sortedItems = [];\n        for (j = 0, jlen = oldCitations[i].citationItems.length; j < jlen; j += 1) {\n            item = oldCitations[i].citationItems[j];\n            if (\"undefined\" === typeof item.sortkeys) {\n                item.sortkeys = [];\n            }\n            Item = this.retrieveItem(\"\" + item.id);\n            newitem = [Item, item];\n            sortedItems.push(newitem);\n            oldCitations[i].citationItems[j].item = Item;\n            itemList.push(\"\" + item.id);\n        }\n        if (!oldCitations[i].properties.unsorted) {\n            sortedItems.sort(this.citation.srt.compareCompositeKeys);\n        }\n        oldCitations[i].sortedItems = sortedItems;\n        // Save citation data in registry\n        this.registry.citationreg.citationById[oldCitations[i].citationID] = oldCitations[i];\n    }\n    // Register Items\n    this.updateItems(itemList);\n\n    // Construct citationList from original copy\n    for (i = 0, ilen = citations.length; i < ilen; i += 1) {\n        citationList.push([\"\" + citations[i].citationID, citations[i].properties.noteIndex]);\n    }\n\n    var ret = [];\n    if (citations && citations.length) {\n        // Rendering one citation restores remainder of processor state.\n        // If citations is empty, rest to empty state.\n        ret = this.processCitationCluster(citations[0], [], citationList.slice(1));\n    } else {\n        this.registry = new CSL.Registry(this);\n        this.tmp = new CSL.Engine.Tmp();\n        this.disambiguate = new CSL.Disambiguation(this);\n    }\n    return ret;\n};\n\n\nCSL.Engine.prototype.updateItems = function (idList, nosort, rerun_ambigs, implicitUpdate) {\n    var debug = false;\n    var oldArea = this.tmp.area;\n    var oldRoot = this.tmp.root;\n    var oldExtension = this.tmp.extension;\n    if (this.bibliography_sort.tokens.length === 0) {\n        nosort = true;\n    }\n    this.tmp.area = \"citation\";\n    this.tmp.root = \"citation\";\n    this.tmp.extension = \"\";\n    if (!implicitUpdate) {\n        this.tmp.loadedItemIDs = {};\n    }\n    //CSL.debug = print\n    //SNIP-START\n    if (debug) {\n        CSL.debug(\"--> init <--\");\n    }\n    //SNIP-END\n    this.registry.init(idList);\n\n\tif (rerun_ambigs) {\n\t\tfor (var ambig in this.registry.ambigcites) {\n\t\t\tthis.registry.ambigsTouched[ambig] = true;\n\t\t}\n\t}\n\n    this.registry.dodeletes(this.registry.myhash);\n    \n    this.registry.doinserts(this.registry.mylist);\n    \n    this.registry.dorefreshes();\n\n    // *** affects reflist\n    this.registry.rebuildlist(nosort);\n    \n    this.registry.setsortkeys();\n\n    // taints always\n    this.registry.setdisambigs();\n\n    // *** affects reflist\n    this.registry.sorttokens(nosort);\n\n    // *** affects reflist\n    // taints if numbered style\n    this.registry.renumber();\n    \n    // taints always\n    //this.registry.yearsuffix();\n\n    this.tmp.extension = oldExtension;\n    this.tmp.area = oldArea;\n    this.tmp.root = oldRoot;\n\n    return this.registry.getSortedIds();\n};\n\nCSL.Engine.prototype.updateUncitedItems = function (idList, nosort) {\n    var idHash;\n    var oldArea = this.tmp.area;\n    var oldRoot = this.tmp.root;\n    var oldExtension = this.tmp.extension;\n    if (this.bibliography_sort.tokens.length === 0) {\n        nosort = true;\n    }\n    this.tmp.area = \"citation\";\n    this.tmp.root = \"citation\";\n    this.tmp.extension = \"\";\n    this.tmp.loadedItemIDs = {};\n    // This should be a utility function\n    if (!idList) {\n        idList = [];\n    }\n    if (\"object\" == typeof idList) {\n        if (\"undefined\" == typeof idList.length) {\n            idHash = idList;\n            idList = [];\n            for (var key in idHash) {\n                idList.push(key);\n            }\n        } else if (\"number\" == typeof idList.length) {\n            idHash = {};\n            for (var i=0,ilen=idList.length;i<ilen;i+=1) {\n                idHash[idList[i]] = true;\n            }\n        }\n    }\n\n    // prepare extended list of items\n    this.registry.init(idList, true);\n\n    // Use purge instead of delete.\n    // this.registry.dodeletes(this.registry.myhash);\n    this.registry.dopurge(idHash);\n\n    // everything else is the same as updateItems()\n    this.registry.doinserts(this.registry.mylist);\n\n    this.registry.dorefreshes();\n\n    this.registry.rebuildlist(nosort);\n\n    this.registry.setsortkeys();\n\n    this.registry.setdisambigs();\n\n    this.registry.sorttokens(nosort);\n\n    this.registry.renumber();\n\n    this.tmp.extension = oldExtension;\n    this.tmp.area = oldArea;\n    this.tmp.root = oldRoot;\n\n    return this.registry.getSortedIds();\n};\n\n/*global CSL: true */\n\nCSL.localeResolve = function (langstr, defaultLocale) {\n    var ret, langlst;\n    if (!defaultLocale) {\n        defaultLocale = \"en-US\";\n    }\n    if (!langstr) {\n        langstr = defaultLocale;\n    }\n    ret = {};\n    //if (\"undefined\" === typeof langstr) {\n    //    langstr = \"en_US\";\n    //}\n    langlst = langstr.split(/[\\-_]/);\n    ret.base = CSL.LANG_BASES[langlst[0]];\n    if (\"undefined\" === typeof ret.base) {\n        //CSL.debug(\"Warning: unknown locale \"+langstr+\", setting fallback to \"+defaultLocale);\n        return {base:defaultLocale, best:langstr, bare:langlst[0]};\n    }\n    if (langlst.length === 1) {\n        ret.generic = true;\n    }\n    if (langlst.length === 1 || langlst[1] === \"x\") {\n        ret.best = ret.base.replace(\"_\", \"-\");\n    } else {\n        ret.best = langlst.slice(0, 2).join(\"-\");\n    }\n    ret.base = ret.base.replace(\"_\", \"-\");\n    ret.bare = langlst[0];\n    return ret;\n};\n\n// Use call to invoke this.\nCSL.Engine.prototype.localeConfigure = function (langspec, beShy) {\n    var localexml;\n    if (beShy && this.locale[langspec.best]) {\n        return;\n    }\n    if (langspec.best === \"en-US\") {\n        localexml = CSL.setupXml(this.sys.retrieveLocale(\"en-US\"));\n        this.localeSet(localexml, \"en-US\", langspec.best);\n    } else if (langspec.best !== \"en-US\") {\n        if (langspec.base !== langspec.best) {\n            localexml = CSL.setupXml(this.sys.retrieveLocale(langspec.base));\n            this.localeSet(localexml, langspec.base, langspec.best);\n        }\n        localexml = CSL.setupXml(this.sys.retrieveLocale(langspec.best));\n        this.localeSet(localexml, langspec.best, langspec.best);        \n    }\n    this.localeSet(this.cslXml, \"\", langspec.best);\n    this.localeSet(this.cslXml, langspec.bare, langspec.best);\n    if (langspec.base !== langspec.best) {\n        this.localeSet(this.cslXml, langspec.base, langspec.best);\n    }\n    this.localeSet(this.cslXml, langspec.best, langspec.best);\n    if (\"undefined\" === typeof this.locale[langspec.best].terms[\"page-range-delimiter\"]) {\n        if ([\"fr\", \"pt\"].indexOf(langspec.best.slice(0, 2).toLowerCase()) > -1) {\n            this.locale[langspec.best].terms[\"page-range-delimiter\"] = \"-\";\n        } else {\n            this.locale[langspec.best].terms[\"page-range-delimiter\"] = \"\\u2013\";\n        }\n    }\n    if (\"undefined\" === typeof this.locale[langspec.best].terms[\"year-range-delimiter\"]) {\n        this.locale[langspec.best].terms[\"year-range-delimiter\"] = \"\\u2013\";\n    }\n    if (\"undefined\" === typeof this.locale[langspec.best].terms[\"citation-range-delimiter\"]) {\n        this.locale[langspec.best].terms[\"citation-range-delimiter\"] = \"\\u2013\";\n    }\n    if (this.opt.development_extensions.normalize_lang_keys_to_lowercase) {\n        var localeLists = [\"default-locale\",\"locale-sort\",\"locale-translit\",\"locale-translat\"];\n        for (var i=0,ilen=localeLists.length;i<ilen;i+=1) {\n            for (var j=0,jlen=this.opt[localeLists[i]].length;j<jlen;j+=1) {\n                this.opt[localeLists[i]][j] = this.opt[localeLists[i]][j].toLowerCase();\n            }\n        }\n        this.opt.lang = this.opt.lang.toLowerCase();\n    }\n};\n    \n//\n// XXXXX: Got it.  The locales objects need to be reorganized,\n// with a top-level local specifier, and terms, opts, dates\n// below.\n//\nCSL.Engine.prototype.localeSet = function (myxml, lang_in, lang_out) {\n    var blob, locale, nodes, attributes, pos, term, form, termname, styleopts, date, attrname, len, genderform, target, i, ilen;\n    lang_in = lang_in.replace(\"_\", \"-\");\n    lang_out = lang_out.replace(\"_\", \"-\");\n\n    if (this.opt.development_extensions.normalize_lang_keys_to_lowercase) {\n        lang_in = lang_in.toLowerCase();\n        lang_out = lang_out.toLowerCase();\n    }\n\n    if (!this.locale[lang_out]) {\n        this.locale[lang_out] = {};\n        this.locale[lang_out].terms = {};\n        this.locale[lang_out].opts = {};\n        // Set default skip words. Can be overridden in locale by attribute on style-options node.\n        this.locale[lang_out].opts[\"skip-words\"] = CSL.SKIP_WORDS;\n        // Initialise leading noise word to false. Actual assignment is below. Empty by default, can be overridden in locale by attribute on style-options node.\n        if (!this.locale[lang_out].opts[\"leading-noise-words\"]) {\n            this.locale[lang_out].opts[\"leading-noise-words\"] = [];\n        }\n        this.locale[lang_out].dates = {};\n        // For ordinals\n        this.locale[lang_out].ord = {'1.0.1':false,keys:{}};\n        this.locale[lang_out][\"noun-genders\"] = {};\n    }\n\n    //\n    // Xml: Test if node is \"locale\" (nb: ns declarations need to be invoked\n    // on every access to the xml object; bundle this with the functions\n    //\n    locale = myxml.makeXml();\n    if (myxml.nodeNameIs(myxml.dataObj, 'locale')) {\n        locale = myxml.dataObj;\n    } else {\n        //\n        // Xml: get a list of all \"locale\" nodes\n        //\n        nodes = myxml.getNodesByName(myxml.dataObj, \"locale\");\n        var foundLocale = false;\n        for (pos = 0, len = myxml.numberofnodes(nodes); pos < len; pos += 1) {\n            blob = nodes[pos];\n            //\n            // Xml: get locale xml:lang\n            //\n            // Iterate over all locales, but for non-matching nodes,\n            // we set jurisdiction_preference only (processing of the\n            // chosen one will process the attribute there,\n            // separately.\n            if (!foundLocale && myxml.getAttributeValue(blob, 'lang', 'xml') === lang_in) {\n                locale = blob;\n                foundLocale = true;\n            } else {\n                var lang = myxml.getAttributeValue(blob, 'lang', 'xml');\n                var style_options = myxml.getNodesByName(blob, 'style-options');\n                if (lang && style_options && style_options.length) {\n                    var jurispref = myxml.getAttributeValue(style_options[0], 'jurisdiction-preference');\n                    if (jurispref) {\n                        if (!this.locale[lang]) {\n                            this.locale[lang] = {\n                                opts: {}\n                            };\n                        }\n                        this.locale[lang].opts[\"jurisdiction-preference\"] = jurispref.split(/\\s+/);\n                    }\n                }\n            }\n        }\n    }\n    //\n    // Xml: get a list of any cs:type nodes within locale\n    //\n    nodes = myxml.getNodesByName(locale, 'type');\n    for (i = 0, ilen = myxml.numberofnodes(nodes); i < ilen; i += 1) {\n        var typenode = nodes[i];\n        var type = myxml.getAttributeValue(typenode, 'name');\n        var gender = myxml.getAttributeValue(typenode, 'gender');\n        this.opt.gender[type] = gender;\n    }\n    //\n    // Xml: get a list of term nodes within locale\n    //\n\n    // If we are setting CSL 1.0.1 ordinals inside a style, wipe the\n    // slate clean and start over.\n    var hasCslOrdinals101 = myxml.getNodesByName(locale, 'term', 'ordinal').length;\n    if (hasCslOrdinals101) {\n        for (var key in this.locale[lang_out].ord.keys) {\n            delete this.locale[lang_out].terms[key];\n        }\n        this.locale[lang_out].ord = {\"1.0.1\":false,keys:{}};\n    }\n\n    nodes = myxml.getNodesByName(locale, 'term');\n    // Collect ordinals info as for 1.0.1, but save only if 1.0.1 toggle triggers\n    var ordinals101 = {\"last-digit\":{},\"last-two-digits\":{},\"whole-number\":{}};\n    var ordinals101_toggle = false;\n    var genderized_terms = {};\n    for (pos = 0, len = myxml.numberofnodes(nodes); pos < len; pos += 1) {\n        term = nodes[pos];\n        //\n        // Xml: get string value of attribute\n        //\n        termname = myxml.getAttributeValue(term, 'name');\n        if (termname === \"sub verbo\") {\n            termname = \"sub-verbo\";\n        }\n        if (termname.slice(0,7) === \"ordinal\") {\n            if (termname === \"ordinal\") {\n                ordinals101_toggle = true;\n            } else {\n                var match = myxml.getAttributeValue(term, 'match');\n                var termstub = termname.slice(8);\n                var genderform = myxml.getAttributeValue(term, 'gender-form');\n                if (!genderform) {\n                    genderform = \"neuter\";\n                }\n                if (!match) {\n                    match = \"last-two-digits\";\n                    if (termstub.slice(0,1) === \"0\") {\n                        match = \"last-digit\";\n                    }\n                }\n                if (termstub.slice(0,1) === \"0\") {\n                    termstub = termstub.slice(1);\n                }\n                if (!ordinals101[match][termstub]) {\n                    ordinals101[match][termstub] = {};\n                }\n                ordinals101[match][termstub][genderform] = termname;\n            }\n            this.locale[lang_out].ord.keys[termname] = true;\n        }\n        if (\"undefined\" === typeof this.locale[lang_out].terms[termname]) {\n            this.locale[lang_out].terms[termname] = {};\n        }\n        form = \"long\";\n        genderform = false;\n        //\n        // Xml: get string value of form attribute, if any\n        //\n        if (myxml.getAttributeValue(term, 'form')) {\n            form = myxml.getAttributeValue(term, 'form');\n        }\n        //\n        // Xml: get string value of gender attribute, if any\n        // \n        if (myxml.getAttributeValue(term, 'gender-form')) {\n            genderform = myxml.getAttributeValue(term, 'gender-form');\n        }\n        //\n        // Xml: set global gender assignment for variable associated\n        // with term name\n        // \n        if (myxml.getAttributeValue(term, 'gender')) {\n            this.locale[lang_out][\"noun-genders\"][termname] = myxml.getAttributeValue(term, 'gender');\n        }\n        // Work on main segment or gender-specific sub-segment as appropriate\n        if (genderform) {\n            this.locale[lang_out].terms[termname][genderform] = {};\n            this.locale[lang_out].terms[termname][genderform][form] = [];\n            target = this.locale[lang_out].terms[termname][genderform];\n            genderized_terms[termname] = true;\n        } else {\n            this.locale[lang_out].terms[termname][form] = [];\n            target = this.locale[lang_out].terms[termname];\n        }\n        //\n        // Xml: test of existence of node\n        //\n        if (myxml.numberofnodes(myxml.getNodesByName(term, 'multiple'))) {\n            //\n            // Xml: get string value of attribute, plus\n            // Xml: get string value of node content\n            //\n            target[form][0] = myxml.getNodeValue(term, 'single');\n            if (target[form][0].indexOf(\"%s\") > -1) {\n                this.opt.hasPlaceholderTerm = true;\n            }\n            //\n            // Xml: get string value of attribute, plus\n            // Xml: get string value of node content\n            //\n            target[form][1] = myxml.getNodeValue(term, 'multiple');\n            if (target[form][1].indexOf(\"%s\") > -1) {\n                this.opt.hasPlaceholderTerm = true;\n            }\n        } else {\n            //\n            // Xml: get string value of attribute, plus\n            // Xml: get string value of node content\n            //\n            target[form] = myxml.getNodeValue(term);\n            if (target[form].indexOf(\"%s\") > -1) {\n                this.opt.hasPlaceholderTerm = true;\n            }\n        }\n    }\n    if (!this.locale[lang_out].terms.supplement) {\n        this.locale[lang_out].terms.supplement = {};\n    }\n    if (!this.locale[lang_out].terms.supplement[\"long\"]) {\n        this.locale[lang_out].terms.supplement[\"long\"] = [\"supplement\", \"supplements\"];\n    }\n    // If locale had a CSL 1.0.1-style ordinal definition, install the logic object\n    // and iterate over gendered terms, filling in default values for use by getTerm.\n    if (ordinals101_toggle) {\n        for (var ikey in genderized_terms) {\n            var gender_segments = {};\n            var form_segments = 0;\n            for (var jkey in this.locale[lang_out].terms[ikey]) {\n                if ([\"masculine\",\"feminine\"].indexOf(jkey) > -1) {\n                    gender_segments[jkey] = this.locale[lang_out].terms[ikey][jkey];\n                } else {\n                    form_segments += 1;\n                }\n            }\n            if (!form_segments) {\n                if (gender_segments.feminine) {\n                    // Link each feminine form segment to default\n                    // (no need to filter, these will not have gender segments mixed in)\n                    for (var jkey in gender_segments.feminine) {\n                        this.locale[lang_out].terms[ikey][jkey] = gender_segments.feminine[jkey];\n                    }\n                } else if (gender_segments.masculine) {\n                    // Otherwise link each masculine form segment to default \n                    for (var jkey in gender_segments.masculine) {\n                        this.locale[lang_out].terms[ikey][jkey] = gender_segments.masculine[jkey];\n                    }\n                }\n            }\n        }\n        this.locale[lang_out].ord['1.0.1'] = ordinals101;\n    }\n\n    // Iterate over main segments, and fill in any holes in gender-specific data\n    // sub-segments\n    for (termname in this.locale[lang_out].terms) {\n        for (i = 0, ilen = 2; i < ilen; i += 1) {\n            genderform = CSL.GENDERS[i];\n            if (this.locale[lang_out].terms[termname][genderform]) {\n                for (form in this.locale[lang_out].terms[termname]) {\n                    if (!this.locale[lang_out].terms[termname][genderform][form]) {\n                        this.locale[lang_out].terms[termname][genderform][form] = this.locale[lang_out].terms[termname][form];\n                    }\n                }\n            }\n        }\n    }\n    //\n    // Xml: get list of nodes by node type\n    //\n    nodes = myxml.getNodesByName(locale, 'style-options');\n    for (pos = 0, len = myxml.numberofnodes(nodes); pos < len; pos += 1) {\n        if (true) {\n            styleopts = nodes[pos];\n            //\n            // Xml: get list of attributes on a node\n            //\n            attributes = myxml.attributes(styleopts);\n            for (attrname in attributes) {\n                if (attributes.hasOwnProperty(attrname)) {\n                    if (attrname === \"@punctuation-in-quote\" || attrname === \"@limit-day-ordinals-to-day-1\") {\n                        if (attributes[attrname] === \"true\") {\n                            // trim off leading @\n                            this.locale[lang_out].opts[attrname.slice(1)] = true;\n                        } else {\n                            // trim off leading @\n                            this.locale[lang_out].opts[attrname.slice(1)] = false;\n                        }\n                    } else if (attrname === \"@jurisdiction-preference\") {\n                        var jurisdiction_preference = attributes[attrname].split(/\\s+/);\n                        this.locale[lang_out].opts[attrname.slice(1)] = jurisdiction_preference;\n                    } else if (attrname === \"@skip-words\") {\n                        var skip_words = attributes[attrname].split(/\\s*,\\s*/);\n                        this.locale[lang_out].opts[attrname.slice(1)] = skip_words;\n                    } else if (attrname === \"@leading-noise-words\") {\n                        var val = attributes[attrname].split(/\\s*,\\s*/);\n                        this.locale[lang_out].opts[\"leading-noise-words\"] = val;\n                    } else if (attrname === \"@name-as-sort-order\") {\n                        // Fallback is okay here.\n                        this.locale[lang_out].opts[\"name-as-sort-order\"] = {};\n                        var lst = attributes[attrname].split(/\\s+/);\n                        for (var i=0,ilen=lst.length;i<ilen;i+=1) {\n                            this.locale[lang_out].opts[\"name-as-sort-order\"][lst[i]] = true;\n                        }\n                    } else if (attrname === \"@name-as-reverse-order\") {\n                        // Fallback is okay here.\n                        this.locale[lang_out].opts[\"name-as-reverse-order\"] = {};\n                        var lst = attributes[attrname].split(/\\s+/);\n                        for (var i=0,ilen=lst.length;i<ilen;i+=1) {\n                            this.locale[lang_out].opts[\"name-as-reverse-order\"][lst[i]] = true;\n                        }\n                    } else if (attrname === \"@name-never-short\") {\n                        // Here too.\n                        this.locale[lang_out].opts[\"name-never-short\"] = {};\n                        var lst = attributes[attrname].split(/\\s+/);\n                        for (var i=0,ilen=lst.length;i<ilen;i+=1) {\n                            this.locale[lang_out].opts[\"name-never-short\"][lst[i]] = true;\n                        }\n                    }\n                }\n            }\n        }\n    }\n    //\n    // Xml: get list of nodes by type\n    //\n    nodes = myxml.getNodesByName(locale, 'date');\n    for (pos = 0, len = myxml.numberofnodes(nodes); pos < len; pos += 1) {\n        if (true) {\n            var date = nodes[pos];\n            //\n            // Xml: get string value of attribute\n            //\n            this.locale[lang_out].dates[myxml.getAttributeValue(date, \"form\")] = date;\n        }\n    }\n    //\n    // Xml: get list of nodes by node type\n    //\n    CSL.SET_COURT_CLASSES(this, lang_out, myxml, locale);\n};\n\n\nCSL.getLocaleNames = function (myxml, preferredLocale) {\n    var stylexml = CSL.setupXml(myxml);\n\n    function extendLocaleList(localeList, locale) {\n        var forms = [\"base\", \"best\"];\n        if (locale) {\n            var normalizedLocale = CSL.localeResolve(locale);\n            for (var i=0,ilen=forms.length;i<ilen;i++) {\n                if (normalizedLocale[forms[i]] && localeList.indexOf(normalizedLocale[forms[i]]) === -1) {\n                    localeList.push(normalizedLocale[forms[i]]);\n                }\n            }\n        }\n    }\n    \n    var localeIDs = [\"en-US\"];\n    \n    function sniffLocaleOnOneNodeName(nodeName) {\n        var nodes = stylexml.getNodesByName(stylexml.dataObj, nodeName);\n        for (var i=0,ilen=nodes.length;i<ilen;i++) {\n            var nodeLocales = stylexml.getAttributeValue(nodes[i], \"locale\");\n            if (nodeLocales) {\n                nodeLocales = nodeLocales.split(/ +/);\n                for (var j=0,jlen=nodeLocales.length;j<jlen;j++) {\n                    this.extendLocaleList(localeIDs, nodeLocales[j]);\n                }\n            }\n        }\n    }\n\n    extendLocaleList(localeIDs, preferredLocale);\n\n    var styleNode = stylexml.getNodesByName(stylexml.dataObj, \"style\")[0];\n    var defaultLocale = stylexml.getAttributeValue(styleNode, \"default-locale\");\n    extendLocaleList(localeIDs, defaultLocale);\n\n    var nodeNames = [\"layout\", \"if\", \"else-if\", \"condition\"];\n    for (var i=0,ilen=nodeNames.length;i<ilen;i++) {\n        sniffLocaleOnOneNodeName(stylexml, localeIDs, nodeNames[i]);\n    }\n    return localeIDs;\n};\n\n/*global CSL: true */\n\nCSL.Node = {};\n\nCSL.Node.bibliography = {\n    build: function (state, target) {\n        if (this.tokentype === CSL.START) {\n\n            state.build.area = \"bibliography\";\n            state.build.root = \"bibliography\";\n            state.build.extension = \"\";\n\n            var func = function(state) {\n                state.tmp.area = \"bibliography\";\n                state.tmp.root = \"bibliography\";\n                state.tmp.extension = \"\";\n            };\n            this.execs.push(func);\n\n        }\n        target.push(this);\n    }\n};\n\n\n/*global CSL: true */\n\nCSL.Node.choose = {\n    build: function (state, target) {\n        var func;\n        if (this.tokentype === CSL.START) {\n            //open condition\n            func = function (state) {\n                state.tmp.jump.push(undefined, CSL.LITERAL);\n            };\n        }\n        if (this.tokentype === CSL.END) {\n            //close condition\n            func = function (state) {\n                state.tmp.jump.pop();\n            };\n        }\n        this.execs.push(func);\n        target.push(this);\n    },\n\n    configure: function (state, pos) {\n        if (this.tokentype === CSL.END) {\n            state.configure.fail.push((pos));\n            state.configure.succeed.push((pos));\n        } else {\n            state.configure.fail.pop();\n            state.configure.succeed.pop();\n        }\n    }\n};\n\n/*global CSL: true */\n\nCSL.Node.citation = {\n    build: function (state, target) {\n        if (this.tokentype === CSL.START) {\n\n            state.build.area = \"citation\";\n            state.build.root = \"citation\";\n            state.build.extension = \"\";\n\n\n            var func = function(state) {\n                state.tmp.area = \"citation\";\n                state.tmp.root = \"citation\";\n                state.tmp.extension = \"\";\n            };\n            this.execs.push(func);\n\n/*\n            state.build.root = \"citation\";\n\n            OK state.fixOpt(this, \"names-delimiter\", \"delimiter\");\n            OK state.fixOpt(this, \"name-delimiter\", \"delimiter\");\n            OK state.fixOpt(this, \"name-form\", \"form\");\n            OK state.fixOpt(this, \"and\", \"and\");\n            OK state.fixOpt(this, \"delimiter-precedes-last\", \"delimiter-precedes-last\");\n            OK state.fixOpt(this, \"delimiter-precedes-et-al\", \"delimiter-precedes-et-al\");\n            OK state.fixOpt(this, \"initialize-with\", \"initialize-with\");\n            OK state.fixOpt(this, \"initialize\", \"initialize\");\n            OK state.fixOpt(this, \"name-as-sort-order\", \"name-as-sort-order\");\n            OK state.fixOpt(this, \"sort-separator\", \"sort-separator\");\n\n            OK state.fixOpt(this, \"et-al-min\", \"et-al-min\");\n            OK state.fixOpt(this, \"et-al-use-first\", \"et-al-use-first\");\n            OK state.fixOpt(this, \"et-al-use-last\", \"et-al-use-last\");\n            state.fixOpt(this, \"et-al-subsequent-min\", \"et-al-subsequent-min\");\n            state.fixOpt(this, \"et-al-subsequent-use-first\", \"et-al-subsequent-use-first\");\n*/\n        }\n        if (this.tokentype === CSL.END) {\n\n            // Open an extra key at first position for use in\n            // grouped sorts.\n            // print(\"in cs:citation END\");\n            state.opt.grouped_sort = state.opt.xclass === \"in-text\" \n                && (state.citation.opt.collapse \n                    && state.citation.opt.collapse.length)\n                || (state.citation.opt.cite_group_delimiter\n                    && state.citation.opt.cite_group_delimiter.length)\n                && state.opt.update_mode !== CSL.POSITION\n                && state.opt.update_mode !== CSL.NUMERIC;\n            \n            if (state.opt.grouped_sort \n                && state.citation_sort.opt.sort_directions.length) {\n                \n                var firstkey = state.citation_sort.opt.sort_directions[0].slice();\n                //print(\"extending sort keys \"+state.citation_sort.opt.sort_directions+\" with \"+firstkey);\n                state.citation_sort.opt.sort_directions = [firstkey].concat(state.citation_sort.opt.sort_directions);\n                // print(\"new key directions in effect: \"+state.citation_sort.opt.sort_directions);\n            }\n            // print(\"creating new comparifier\");\n            state.citation.srt = new CSL.Registry.Comparifier(state, \"citation_sort\");\n        }\n        target.push(this);\n    }\n};\n\n\n/*global CSL: true */\n\nCSL.Node[\"#comment\"] = {\n       // This is a comment in the CSL file.\n       build: function () {\n        // Save some space in the log files -- no need to mention this, really.\n        // CSL.debug(\"CSL processor warning: comment node reached\");\n       }\n};\n\n/*global CSL: true */\n\nCSL.Node.date = {\n    build: function (state, target) {\n        var func, date_obj, len, pos, part, dpx, parts, mypos, start, end;\n        if (this.tokentype === CSL.START || this.tokentype === CSL.SINGLETON) {\n            // used to collect rendered date part names in node_datepart,\n            // for passing through to node_key, for use in dates embedded\n            // in macros\n            state.dateput.string(state, state.dateput.queue);\n            state.tmp.date_token = CSL.Util.cloneToken(this);\n            state.tmp.date_token.strings.prefix = \"\";\n            state.tmp.date_token.strings.suffix = \"\";\n            state.dateput.openLevel(this);\n            state.build.date_parts = [];\n            state.build.date_variables = this.variables;\n            if (!state.build.extension) {\n                CSL.Util.substituteStart.call(this, state, target);\n            }\n            if (state.build.extension) {\n                func = CSL.dateMacroAsSortKey;\n            } else {\n                func = function (state, Item, item) {\n                    var dp;\n                    state.tmp.element_rendered_ok = false;\n                    state.tmp.donesies = [];\n                    state.tmp.dateparts = [];\n                    dp = [];\n                    //if (this.variables.length && Item[this.variables[0]]){\n                    if (this.variables.length\n                        && !(state.tmp.just_looking\n                             && this.variables[0] === \"accessed\")) {\n                        \n                        date_obj = Item[this.variables[0]];\n                        if (\"undefined\" === typeof date_obj) {\n                            date_obj = {\"date-parts\": [[0]] };\n                            if (state.opt.development_extensions.locator_date_and_revision) {\n                                if (item && this.variables[0] === \"locator-date\" && item[\"locator-date\"]) {\n                                    date_obj = item[\"locator-date\"];\n                                }\n                            }\n                        }\n                        state.tmp.date_object = date_obj;\n                        //\n                        // Call a function here to analyze the\n                        // data and set the name of the date-part that\n                        // should collapse for this range, if any.\n                        //\n                        // (1) build a filtered list, in y-m-d order,\n                        // consisting only of items that are (a) in the\n                        // date-parts and (b) in the *_end data.\n                        // (note to self: remember that season is a\n                        // fallback var when month and day are empty)\n                        \n                        //if (\"undefined\" === typeof this.dateparts) {\n                        //    this.dateparts = [\"year\", \"month\", \"day\"];\n                        //}\n                        len = this.dateparts.length;\n                        for (pos = 0; pos < len; pos += 1) {\n                            part = this.dateparts[pos];\n                            if (\"undefined\" !== typeof state.tmp.date_object[(part +  \"_end\")]) {\n                                dp.push(part);\n                            } else if (part === \"month\" && \"undefined\" !== typeof state.tmp.date_object.season_end) {\n                                dp.push(part);\n                            }\n                        }\n                        dpx = [];\n                        parts = [\"year\", \"month\", \"day\"];\n                        len = parts.length;\n                        for (pos = 0; pos < len; pos += 1) {\n                            if (dp.indexOf(parts[pos]) > -1) {\n                                dpx.push(parts[pos]);\n                            }\n                        }\n                        dp = dpx.slice();\n                        //\n                        // (2) Reverse the list and step through in\n                        // reverse order, popping each item if the\n                        // primary and *_end data match.\n                        mypos = 2;\n                        len = dp.length;\n                        for (pos = 0; pos < len; pos += 1) {\n                            part = dp[pos];\n                            start = state.tmp.date_object[part];\n                            end = state.tmp.date_object[(part + \"_end\")];\n                            if (start !== end) {\n                                mypos = pos;\n                                break;\n                            }\n                        }\n                        \n                        //\n                        // (3) When finished, the first item in the\n                        // list, if any, is the date-part where\n                        // the collapse should occur.\n\n                        // XXXXX: was that it?\n                        state.tmp.date_collapse_at = dp.slice(mypos);\n                        //\n                        // The collapse itself will be done by appending\n                        // string output for the date, less suffix,\n                        // placing a delimiter on output, then then\n                        // doing the *_end of the range, dropping only\n                        // the prefix.  That should give us concise expressions\n                        // of ranges.\n                        //\n                        // Numeric dates should not collapse, though,\n                        // and should probably use a slash delimiter.\n                        // Scope for configurability will remain (all over\n                        // the place), but this will do to get this feature\n                        // started.\n                        //\n                    } else {\n                        state.tmp.date_object = false;\n                    }\n                };\n            }\n            this.execs.push(func);\n\n            // newoutput\n            func = function (state, Item) {\n                if (!Item[this.variables[0]]) {\n                    return;\n                }\n                state.output.startTag(\"date\", this);\n                if (this.variables[0] === \"issued\"\n                    && (Item.type === \"legal_case\" || Item.type === \"legislation\")\n                    && state.opt.disable_duplicate_year_suppression.indexOf(Item.country) === -1\n                    && !state.tmp.extension\n                    && \"\" + Item[\"collection-number\"] === \"\" + state.tmp.date_object.year\n                    && this.dateparts.length === 1\n                    && this.dateparts[0] === \"year\") {\n\n                    // Set up to (maybe) suppress the year if we're not sorting, and\n                    // it's the same as the collection-number, and we would render\n                    // only the year, with not month or day, and this is a legal_case item.\n                    // We save a pointer to the blob parent and its position here. The\n                    // blob will be popped from output if at the end of processing for\n                    // this cite we find that we have rendered the collection-number\n                    // variable also.\n                    for (var key in state.tmp.date_object) {\n                        if (state.tmp.date_object.hasOwnProperty(key)) {\n                            if (key.slice(0, 4) === \"year\") {\n                                state.tmp.issued_date = {};\n                                var lst = state.output.current.mystack.slice(-2)[0].blobs;\n                                state.tmp.issued_date.list = lst;\n                                state.tmp.issued_date.pos = lst.length - 1;\n                            }\n                        }\n                    }\n                }\n            };\n            this.execs.push(func);\n        }\n\n        if (!state.build.extension && (this.tokentype === CSL.END || this.tokentype === CSL.SINGLETON)) {\n            // mergeoutput\n            func = function (state, Item) {\n                if (!Item[this.variables[0]]) {\n                    return;\n                }\n                state.output.endTag();\n            };\n            this.execs.push(func);\n        }\n        target.push(this);\n\n        if (this.tokentype === CSL.END || this.tokentype === CSL.SINGLETON) {\n            if (!state.build.extension) {\n                CSL.Util.substituteEnd.call(this, state, target);\n            }\n        }\n    }\n};\n\n/*global CSL: true */\n\nCSL.Node[\"date-part\"] = {\n    build: function (state, target) {\n        var func, pos, len, first_date, value, value_end, real, have_collapsed, invoked, precondition, known_year, bc, ad, bc_end, ad_end, ready, curr, dcurr, number, num, formatter, item, blob;\n        if (!this.strings.form) {\n            this.strings.form = \"long\";\n        }\n        // used in node_date, to send a list of rendering date parts\n        // to node_key, for dates embedded in macros.\n        state.build.date_parts.push(this.strings.name);\n        //\n        // Set delimiter here, if poss.\n        //\n\n        var date_variable = state.build.date_variables[0];\n\n        function formatAndStrip(myform, gender, val) {\n            if (!val) {\n                return val;\n            }\n            val = \"\" + CSL.Util.Dates[this.strings.name][myform](state, val, gender, this.default_locale);\n            if (\"month\" === this.strings.name) {\n                if (state.tmp.strip_periods) {\n                    val = val.replace(/\\./g, \"\");\n                } else {\n                    for (var i = 0, ilen = this.decorations.length; i < ilen; i += 1) {\n                        if (\"@strip-periods\" === this.decorations[i][0] && \"true\" === this.decorations[i][1]) {\n                            val = val.replace(/\\./g, \"\");\n                            break;\n                        }\n                    }\n                }\n            }\n            return val;\n        }\n\n        func = function (state, Item) {\n\n            if (!state.tmp.date_object) {\n                return;\n            } else {\n                state.tmp.probably_rendered_something = true;\n            }\n\n            var last_string_output = \"\";\n\n            first_date = true;\n            value = \"\";\n            value_end = \"\";\n            state.tmp.donesies.push(this.strings.name);\n\n            // Render literal only when year is included in date output\n            if (state.tmp.date_object.literal && \"year\" === this.strings.name) {\n                last_string_output = state.tmp.date_object.literal;\n                state.output.append(state.tmp.date_object.literal, this);\n            }\n\n            if (state.tmp.date_object) {\n                value = state.tmp.date_object[this.strings.name];\n                value_end = state.tmp.date_object[(this.strings.name + \"_end\")];\n            }\n            if (\"year\" === this.strings.name && value === 0 && !state.tmp.suppress_decorations) {\n                value = false;\n            }\n            real = !state.tmp.suppress_decorations;\n            have_collapsed = state.tmp.have_collapsed;\n            invoked = state[state.tmp.area].opt.collapse === \"year-suffix\" || state[state.tmp.area].opt.collapse === \"year-suffix-ranged\";\n            precondition = state.opt[\"disambiguate-add-year-suffix\"];\n            if (real && precondition && invoked) {\n                state.tmp.years_used.push(value);\n                known_year = state.tmp.last_years_used.length >= state.tmp.years_used.length;\n                if (known_year && have_collapsed) {\n                    if (state.tmp.last_years_used[(state.tmp.years_used.length - 1)] === value) {\n                        value = false;\n                    }\n                }\n            }\n            if (\"undefined\" !== typeof value) {\n                bc = false;\n                ad = false;\n                bc_end = false;\n                ad_end = false;\n                if (\"year\" === this.strings.name) {\n                    if (parseInt(value, 10) < 500 && parseInt(value, 10) > 0) {\n                        ad = state.getTerm(\"ad\");\n                    }\n                    if (parseInt(value, 10) < 0) {\n                        bc = state.getTerm(\"bc\");\n                        value = (parseInt(value, 10) * -1);\n                    }\n                    if (value_end) {\n                        if (parseInt(value_end, 10) < 500 && parseInt(value_end, 10) > 0) {\n                            ad_end = state.getTerm(\"ad\");\n                        }\n                        if (parseInt(value_end, 10) < 0) {\n                            bc_end = state.getTerm(\"bc\");\n                            value_end = (parseInt(value_end, 10) * -1);\n                        }\n                    }\n                }\n\n                // For gendered locales\n                var monthnameid = \"\"+state.tmp.date_object.month;\n                while (monthnameid.length < 2) {\n                    monthnameid = \"0\"+monthnameid;\n                }\n                monthnameid = \"month-\"+monthnameid;\n                var gender = state.locale[state.opt.lang][\"noun-genders\"][monthnameid];\n                if (this.strings.form) {\n                    var myform = this.strings.form;\n                    var myform_end = this.strings.form;\n                    if (this.strings.name === \"day\") {\n                        if (myform === \"ordinal\" && state.locale[state.opt.lang].opts[\"limit-day-ordinals-to-day-1\"]) {\n                            if (value != 1) {\n                                myform = \"numeric\";\n                            }\n                            if (value_end != 1) {\n                                myform_end = \"numeric\";\n                            }\n                        }\n                    }\n                    value = formatAndStrip.call(this, myform, gender, value);\n                    value_end = formatAndStrip.call(this, myform_end, gender, value_end);\n                }\n                state.output.openLevel(\"empty\");\n                if (state.tmp.date_collapse_at.length) {\n                    //state.output.startTag(this.strings.name,this);\n                    ready = true;\n                    len = state.tmp.date_collapse_at.length;\n                    for (pos = 0; pos < len; pos += 1) {\n                        item = state.tmp.date_collapse_at[pos];\n                        if (state.tmp.donesies.indexOf(item) === -1) {\n                            ready = false;\n                            break;\n                        }\n                    }\n                    if (ready) {\n                        if (\"\" + value_end !== \"0\") {\n                            if (state.dateput.queue.length === 0) {\n                                first_date = true;\n                            }\n\n                            // OK! So if the actual data has no month, day or season,\n                            // and we reach this block, then we can combine the dates\n                            // to a string, run minimial-two, and output the trailing\n                            // year right here. No impact on other functionality.\n\n                            if (state.opt[\"year-range-format\"]\n                                && state.opt[\"year-range-format\"] !== \"expanded\"\n                                && !state.tmp.date_object.day\n                                && !state.tmp.date_object.month\n                                && !state.tmp.date_object.season\n                                && this.strings.name === \"year\"\n                                && value && value_end) {\n\n                                // second argument adjusts collapse as required for years\n                                // See OSCOLA section 1.3.2\n                                value_end = state.fun.year_mangler(value + \"-\" + value_end, true);\n                                var range_delimiter = state.getTerm(\"year-range-delimiter\");\n                                value_end = value_end.slice(value_end.indexOf(range_delimiter) + 1);\n                            }\n                            last_string_output = value_end;\n                            state.dateput.append(value_end, this);\n                            if (first_date) {\n                                blob = state.dateput.current.value().blobs[0];\n                                if (blob) {\n                                    blob.strings.prefix = \"\";\n                                }\n\n                            }\n                        }\n                        last_string_output = value;\n                        state.output.append(value, this);\n                        curr = state.output.current.value();\n                        blob = curr.blobs[(curr.blobs.length - 1)];\n                        if (blob) {\n                            blob.strings.suffix = \"\";\n                        }\n\n                        if (this.strings[\"range-delimiter\"]) {\n                            state.output.append(this.strings[\"range-delimiter\"]);\n                        } else {\n                            state.output.append(state.getTerm(\"year-range-delimiter\"), \"empty\");\n                        }\n                        state.dateput.closeLevel();\n                        dcurr = state.dateput.current.value();\n                        curr.blobs = curr.blobs.concat(dcurr);\n                        // This may leave the stack pointer on a lower level.\n                        // It's not a problem because the stack will be clobbered\n                        // when the queue is initialized by the next cs:date node.\n                        state.dateput.string(state, state.dateput.queue);\n                        state.dateput.openLevel(state.tmp.date_token);\n                        state.tmp.date_collapse_at = [];\n                    } else {\n                        last_string_output = value;\n                        state.output.append(value, this);\n                        // print(\"collapse_at: \"+state.tmp.date_collapse_at);\n                        if (state.tmp.date_collapse_at.indexOf(this.strings.name) > -1) {\n                            //\n                            // Use ghost dateput queue\n                            //\n                            if (\"\" + value_end !== \"0\") {\n                                //\n                                // XXXXX: It's a workaround.  It's ugly.\n                                // There's another one above.\n                                //\n                                if (state.dateput.queue.length === 0) {\n                                    first_date = true;\n                                }\n                                state.dateput.openLevel(\"empty\");\n                                last_string_output = value_end;\n                                state.dateput.append(value_end, this);\n                                if (first_date) {\n                                    blob = state.dateput.current.value().blobs[0];\n                                    if (blob) {\n                                        blob.strings.prefix = \"\";\n                                    }\n                                }\n                                if (bc) {\n                                    last_string_output = bc;\n                                    state.dateput.append(bc);\n                                }\n                                if (ad) {\n                                    last_string_output = ad;\n                                    state.dateput.append(ad);\n                                }\n                                state.dateput.closeLevel();\n                            }\n                        }\n                    }\n                } else {\n                    last_string_output = value;\n                    state.output.append(value, this);\n                }\n\n                if (bc) {\n                    last_string_output = bc;\n                    state.output.append(bc);\n                }\n                if (ad) {\n                    last_string_output = ad;\n                    state.output.append(ad);\n                }\n                state.output.closeLevel();\n                //state.output.endTag();\n            } else if (\"month\" === this.strings.name) {\n                // XXX The simpler solution here will be to\n                // directly install season and season_end on\n                // month, with a value of 13, 14, 15, 16, or\n                // (to allow correct ranging with Down Under\n                // dates) 17 or 18.  That will allow ranging\n                // to take place in the normal way.  With this\n                // \"approach\", it doesn't.\n                //\n                // No value for this target variable\n                //\n                if (state.tmp.date_object.season) {\n                    value = \"\" + state.tmp.date_object.season;\n                    if (value && value.match(/^[1-4]$/)) {\n                        // XXXXXXXXXXXXXXXXXXX was replace([false, false, true]);\n                        //state.tmp.group_context.replace([false, false, true]);\n                        state.tmp.group_context.tip.variable_success = true;\n                        last_string_output = \"winter\";\n                        state.output.append(state.getTerm((\"season-0\" + value)), this);\n                    } else if (value) {\n                        last_string_output = value;\n                        state.output.append(value, this);\n                    }\n                }\n            }\n            state.tmp.value = [];\n            if (Item[date_variable] && (value || state.tmp.have_collapsed) && !state.opt.has_year_suffix && \"year\" === this.strings.name && !state.tmp.just_looking) {\n                if (state.registry.registry[Item.id] && state.registry.registry[Item.id].disambig.year_suffix !== false && !state.tmp.has_done_year_suffix) {\n                    state.tmp.has_done_year_suffix = true;\n                    last_string_output = \"x\";\n                    num = parseInt(state.registry.registry[Item.id].disambig.year_suffix, 10);\n                    // first argument is for number particle [a-zA-Z], never present on dates\n                    number = new CSL.NumericBlob(state, false, num, this, Item.id);\n                    this.successor_prefix = state[state.build.area].opt.layout_delimiter;\n                    this.splice_prefix = state[state.build.area].opt.layout_delimiter;\n                    formatter = new CSL.Util.Suffixator(CSL.SUFFIX_CHARS);\n                    number.setFormatter(formatter);\n                    if (state[state.tmp.area].opt.collapse === \"year-suffix-ranged\") {\n                        number.range_prefix = state.getTerm(\"citation-range-delimiter\");\n                    }\n                    if (state[state.tmp.area].opt.cite_group_delimiter) {\n                        number.successor_prefix = state[state.tmp.area].opt.cite_group_delimiter;\n                    } else if (state[state.tmp.area].opt[\"year-suffix-delimiter\"]) {\n                        number.successor_prefix = state[state.tmp.area].opt[\"year-suffix-delimiter\"];\n                    } else {\n                        number.successor_prefix = state[state.tmp.area].opt.layout_delimiter;\n                    }\n                    number.UGLY_DELIMITER_SUPPRESS_HACK = true;\n                    state.output.append(number, \"literal\");\n                }\n            }\n            if (last_string_output && !state.tmp.group_context.tip.condition) {\n                state.tmp.just_did_number = last_string_output.match(/[0-9]$/);\n                if (state.output.current.tip.strings.suffix) {\n                    state.tmp.just_did_number = false;\n                }\n            }\n        };\n        this.execs.push(func);\n        target.push(this);\n    }\n};\n\n/*global CSL: true */\n\nCSL.Node[\"else-if\"] = {\n    //\n    // these function are the same as those in if, might just clone\n    build: function (state, target) {\n        CSL.Conditions.TopNode.call(this, state, target);\n        target.push(this);\n    },\n    configure: function (state, pos) {\n        CSL.Conditions.Configure.call(this, state, pos);\n    }\n};\n\n/*global CSL: true */\n\nCSL.Node[\"else\"] = {\n    build: function (state, target) {\n        target.push(this);\n    },\n    configure: function (state, pos) {\n        if (this.tokentype === CSL.START) {\n            state.configure.fail[(state.configure.fail.length - 1)] = pos;\n        }\n    }\n};\n\n\n/*global CSL: true */\n\nCSL.Node[\"et-al\"] = {\n    build: function (state, target) {\n        if (state.build.area === \"citation\" || state.build.area === \"bibliography\") {\n            var func = function (state) {\n                state.tmp.etal_node = this;\n                if (\"string\" === typeof this.strings.term) {\n                    state.tmp.etal_term = this.strings.term;\n                }\n            };\n            this.execs.push(func);\n        }\n        target.push(this);\n    }\n};\n\n/*global CSL: true */\n\nCSL.Node.group = {\n    build: function (state, target, realGroup) {\n        var func, execs;\n        this.realGroup = realGroup;\n        if (this.tokentype === CSL.START) {\n            CSL.Util.substituteStart.call(this, state, target);\n            if (state.build.substitute_level.value()) {\n                state.build.substitute_level.replace((state.build.substitute_level.value() + 1));\n            }\n            if (!this.juris) {\n                target.push(this);\n            }\n\n            // newoutput\n            func = function (state) {\n                state.output.startTag(\"group\", this);\n                \n                if (this.strings.label_form_override) {\n                    if (!state.tmp.group_context.tip.label_form) {\n                        state.tmp.group_context.tip.label_form = this.strings.label_form_override;\n                    }\n                }\n                \n                if (this.strings.label_capitalize_if_first_override) {\n                    if (!state.tmp.group_context.tip.label_capitalize_if_first) {\n                        state.tmp.group_context.tip.label_capitalize_if_first = this.strings.label_capitalize_if_first_override;\n                    }\n                }\n                \n                if (this.realGroup) {\n                    \n                    if (state.tmp.group_context.tip.condition) {\n                        CSL.UPDATE_GROUP_CONTEXT_CONDITION(state, this.strings.prefix, null, this);\n                    }\n                    \n                    var condition = false;\n                    var force_suppress = false;\n\n                    // XXX Can we do something better for length here?\n                    if (state.tmp.group_context.mystack.length) {\n                        state.output.current.value().parent = state.tmp.group_context.tip.output_tip;\n                    }\n                    \n                    // fieldcontextflag\n                    var label_form = state.tmp.group_context.tip.label_form;\n                    if (!label_form) {\n                        label_form = this.strings.label_form_override;\n                    }\n                    \n                    var label_capitalize_if_first = state.tmp.group_context.tip.label_capitalize_if_first;\n                    if (!label_capitalize_if_first) {\n                        label_capitalize_if_first = this.strings.label_capitalize_if_first;\n                    }\n                    if (state.tmp.group_context.tip.condition) {\n                        condition = state.tmp.group_context.tip.condition;\n                        force_suppress = state.tmp.group_context.tip.force_suppress;\n                        //force_suppress: false;\n                    } else if (this.strings.reject) {\n                        condition = {\n                            test: this.strings.reject,\n                            not: true\n                        };\n                    } else if (this.strings.require) {\n                        condition = {\n                            test: this.strings.require,\n                            not: false\n                        };\n                    }\n                    var context = {\n                        old_term_predecessor: state.tmp.term_predecessor,\n                        term_intended: false,\n                        variable_attempt: false,\n                        variable_success: false,\n                        variable_success_parent: state.tmp.group_context.tip.variable_success,\n                        output_tip: state.output.current.tip,\n                        label_form: label_form,\n                        label_static: state.tmp.group_context.tip.label_static,\n                        label_capitalize_if_first: label_capitalize_if_first,\n                        parallel_delimiter_override: this.strings.set_parallel_delimiter_override,\n                        parallel_delimiter_override_on_suppress: this.strings.set_parallel_delimiter_override_on_suppress,\n                        condition: condition,\n                        force_suppress: force_suppress,\n                        done_vars: state.tmp.group_context.tip.done_vars.slice()\n                    };\n                    if(this.non_parallel) {\n                        var non_parallel = state.tmp.group_context.tip.non_parallel;\n                        if (!non_parallel) {\n                            non_parallel = {};\n                        }\n                        Object.assign(non_parallel, this.non_parallel);\n                        context.non_parallel = non_parallel;\n                    }\n                    if(this.parallel_first) {\n                        var parallel_first = state.tmp.group_context.tip.parallel_first;\n                        if (!parallel_first) {\n                            parallel_first = {};\n                        }\n                        Object.assign(parallel_first, this.parallel_first);\n                        context.parallel_first = parallel_first;\n                    }\n                    if(this.parallel_last) {\n                        var parallel_last = state.tmp.group_context.tip.parallel_last;\n                        if (!parallel_last) {\n                            parallel_last = {};\n                        }\n                        Object.assign(parallel_last, this.parallel_last);\n                        context.parallel_last = parallel_last;\n                    }\n                    if (state.tmp.abbrev_trimmer && state.tmp.abbrev_trimmer.LAST_TO_FIRST && context.parallel_last) {\n                        if (!context.parallel_first) {\n                            context.parallel_first = {};\n                        }\n                        for (var varname in state.tmp.abbrev_trimmer.LAST_TO_FIRST) {\n                            if (context.parallel_last[varname]) {\n                                context.parallel_first[varname] = true;\n                                delete context.parallel_last[varname];\n                            }\n                        }\n                    }\n                    \n                    /*\n                    if(this.parallel_last_override) {\n                        var parallel_last_override = state.tmp.group_context.tip.parallel_last_override;\n                        if (!parallel_last_override) {\n                            parallel_last_override = {};\n                        }\n                        Object.assign(parallel_last_override, this.parallel_last_override);\n                        context.parallel_last_override = parallel_last_override;\n                    }\n                     */\n                    state.tmp.group_context.push(context);\n\n                    if (state.tmp.abbrev_trimmer && this.parallel_last_to_first) {\n                        if (!state.tmp.abbrev_trimmer.LAST_TO_FIRST) {\n                            state.tmp.abbrev_trimmer.LAST_TO_FIRST = {};\n                        }\n                        for (var varname in this.parallel_last_to_first) {\n                            state.tmp.abbrev_trimmer.LAST_TO_FIRST[varname] = true;\n                        }\n                    }\n                    \n                    //if (!state.tmp.just_looking) {\n                    //    print(\"       flags=\"+JSON.stringify(state.tmp.group_context.tip, params))\n                    //}\n                }\n            };\n            //\n            // Paranoia.  Assure that this init function is the first executed.\n            execs = [];\n            execs.push(func);\n            this.execs = execs.concat(this.execs);\n\n            // \"Special handling\" for nodes that contain only\n            // publisher and place, with no affixes. For such\n            // nodes only, parallel publisher/place pairs\n            // will be parsed out and properly joined, piggybacking on\n            // join parameters set on cs:citation or cs:bibliography.\n            if (this.strings[\"has-publisher-and-publisher-place\"]) {\n                // Pass variable string values to the closing\n                // tag via a global, iff they conform to expectations.\n                state.build[\"publisher-special\"] = true;\n                if (this.strings[\"subgroup-delimiter\"]) {\n                    // Set the handling function only if name-delimiter\n                    // is set on the parent cs:citation or cs:bibliography\n                    // node.\n                    func = function (state, Item) {\n                        if (Item.publisher && Item[\"publisher-place\"]) {\n                            var publisher_lst = Item.publisher.split(/;\\s*/);\n                            var publisher_place_lst = Item[\"publisher-place\"].split(/;\\s*/);\n                            if (publisher_lst.length > 1\n                                && publisher_lst.length === publisher_place_lst.length) {\n                                state.publisherOutput = new CSL.PublisherOutput(state, this);\n                                state.publisherOutput[\"publisher-list\"] = publisher_lst;\n                                state.publisherOutput[\"publisher-place-list\"] = publisher_place_lst;\n                            }\n                        }\n                    };\n                    this.execs.push(func);\n                }\n            }\n\n            if (this.juris) {\n                // \"Special handling\" for jurisdiction macros\n                // We try to instantiate these as standalone token lists.\n                // If available, the token list is executed,\n                // the result is written directly into output,\n                // and control returns here.\n\n                // So we'll have something like this:\n                // * expandMacro() in util_node.js flags juris- macros\n                //   on build. [DONE]\n                // * Those are picked up here, and\n                //   - A runtime function attempts to fetch and instantiate\n                //     the macros in separate token lists under a segment\n                //     opened for the jurisdiction. We assume that the\n                //     jurisdiction has a full set of macros. That will need\n                //     to be enforced by validation. [DONE HERE, function is TODO]\n                //   - Success or failure is marked in a runtime flag object\n                //     (in citeproc.opt). [DONE]\n                //   - After the instantiation function comes a test, for\n                //     juris- macros only, which either runs diverted code,\n                //     or proceeds as per normal through the token list. [TODO]\n                // I think that's all there is to it.\n                \n                // Code for fetching an instantiating?\n\n                var choose_start = new CSL.Token(\"choose\", CSL.START);\n                CSL.Node.choose.build.call(choose_start, state, target);\n                \n                var if_start = new CSL.Token(\"if\", CSL.START);\n\n                func = (function (macroName) {\n                    return function (Item, item) {\n                        return CSL.INIT_JURISDICTION_MACROS(state, Item, item, macroName);\n                    }\n                }(this.juris));\n                \n                if_start.tests ? {} : if_start.tests = [];\n                if_start.tests.push(func);\n                if_start.test = state.fun.match.any(if_start, state, if_start.tests);\n                target.push(if_start);\n                var text_node = new CSL.Token(\"text\", CSL.SINGLETON);\n                func = function (state, Item, item) {\n                    // This will run the juris- token list.\n                    var itemItem = Item;\n                    if (item && item[\"best-jurisdiction\"] && this.juris === \"juris-locator\") {\n                        itemItem = item;\n                    }\n                    var next = 0;\n                    if (state.juris[itemItem[\"best-jurisdiction\"]][this.juris]) {\n                        while (next < state.juris[itemItem[\"best-jurisdiction\"]][this.juris].length) {\n                            next = CSL.tokenExec.call(state, state.juris[itemItem[\"best-jurisdiction\"]][this.juris][next], Item, item);\n                        }\n                    }\n                };\n                text_node.juris = this.juris;\n                text_node.execs.push(func);\n                target.push(text_node);\n\n                var if_end = new CSL.Token(\"if\", CSL.END);\n                CSL.Node[\"if\"].build.call(if_end, state, target);\n                var else_start = new CSL.Token(\"else\", CSL.START);\n                CSL.Node[\"else\"].build.call(else_start, state, target);\n            }\n        }\n\n        if (this.tokentype === CSL.END) {\n            \n            // Unbundle and print publisher lists\n            // Same constraints on creating the necessary function here\n            // as above. The full content of the group formatting token\n            // is apparently not available on the closing tag here,\n            // hence the global flag on state.build.\n            if (state.build[\"publisher-special\"]) {\n                state.build[\"publisher-special\"] = false;\n                func = function (state) {\n                    if (state.publisherOutput) {\n                        state.publisherOutput.render();\n                        state.publisherOutput = false;\n                    }\n                };\n                this.execs.push(func);\n            }\n            \n            // quashnonfields\n            func = function (state, Item, item) {\n                if (!state.tmp.group_context.tip.condition) {\n                    if (state.output.current.tip.strings.suffix) {\n                        state.tmp.just_did_number = false;\n                    }\n                }\n                state.output.endTag();\n                if (this.realGroup) {\n                    var flags = state.tmp.group_context.pop();\n                    if (flags.parallel_delimiter_override) {\n                        state.tmp.group_context.tip.parallel_delimiter_override = flags.parallel_delimiter_override;\n                        if (!state.tmp.just_looking && state.registry.registry[Item.id].master) {\n                            state.registry.registry[Item.id].parallel_delimiter_override = flags.parallel_delimiter_override;\n                        }\n                    }\n                    if (flags.parallel_delimiter_override_on_suppress) {\n                        state.tmp.group_context.tip.parallel_delimiter_override_on_suppress = flags.parallel_delimiter_override_on_suppress;\n                    }\n                    if (state.tmp.area === \"bibliography_sort\") {\n                        var citationNumberIdx = flags.done_vars.indexOf(\"citation-number\");\n                        if (this.strings.sort_direction && citationNumberIdx > -1 && state.tmp.group_context.length() == 1) {\n                            if (this.strings.sort_direction === CSL.DESCENDING) {\n                                state.bibliography_sort.opt.citation_number_sort_direction = CSL.DESCENDING;\n                            } else {\n                                state.bibliography_sort.opt.citation_number_sort_direction = CSL.ASCENDING;\n                            }\n                            flags.done_vars = flags.done_vars.slice(0, citationNumberIdx).concat(flags.done_vars.slice(citationNumberIdx + 1))\n                        }\n                    }\n                    //var params = [\"condition\", \"variable_success\", \"force_suppress\",\"term_intended\", \"variable_attempt\"]\n                    //if (!state.tmp.just_looking) {\n                    //    print(\"POP parent=\"+JSON.stringify(state.tmp.group_context.tip, params))\n                    //    print(\"    flags=\"+JSON.stringify(flags, params));\n                    //}\n                    if (flags.condition) {\n                        flags.force_suppress = CSL.EVALUATE_GROUP_CONDITION(state, flags);\n                    }\n                    if (state.tmp.group_context.tip.condition) {\n                        state.tmp.group_context.tip.force_suppress = flags.force_suppress;\n                    }\n                            \n                    if (!flags.force_suppress && (flags.variable_success || (flags.term_intended && !flags.variable_attempt))) {\n                        if (!this.isJurisLocatorLabel) {\n                            state.tmp.group_context.tip.variable_success = true;\n                        }\n                        var blobs = state.output.current.value().blobs;\n                        var pos = state.output.current.value().blobs.length - 1;\n\n                        if (!state.tmp.just_looking && (flags.non_parallel || flags.parallel_last || flags.parallel_first || flags.parallel_delimiter_override || flags.parallel_delimiter_override_on_suppress)) {\n                            // flags.parallel_last\n                            // flags.parallel_first\n\n                            // Returns true ONLY if all variables listed on this group are repeats.\n                            var hasRepeat = state.parallel.checkRepeats(flags);\n                            if (hasRepeat) {\n                                if (blobs) {\n                                    blobs.pop();\n                                }\n                            }\n                            if (state.tmp.cite_index > 0 && (hasRepeat || (!flags.parallel_first && !flags.parallel_last && !flags.non_parallel))) {\n                                //state.sys.print(`${state.tmp.cite_index} ${JSON.stringify(state.tmp.suppress_repeats, null, 2)}`)\n                                var info = state.tmp.suppress_repeats[state.tmp.cite_index-1];\n                                if (hasRepeat && flags.parallel_delimiter_override_on_suppress && (info.SIBLING || info.ORPHAN)) {\n                                    state.output.queue.slice(-1)[0].parallel_delimiter = flags.parallel_delimiter_override_on_suppress;\n                                } else if (flags.parallel_delimiter_override && info.SIBLING) {\n                                    state.output.queue.slice(-1)[0].parallel_delimiter = flags.parallel_delimiter_override;\n                                }\n                            }\n                        }\n                    } else {\n                        state.tmp.term_predecessor = flags.old_term_predecessor;\n                        state.tmp.group_context.tip.variable_attempt = flags.variable_attempt;\n                        if (flags.force_suppress && !state.tmp.group_context.tip.condition) {\n                            state.tmp.group_context.tip.variable_attempt = true;\n                            state.tmp.group_context.tip.variable_success = flags.variable_success_parent;\n                        }\n                        if (flags.force_suppress) {\n                            // 2019-04-15\n                            // This is removing variables done within the group we're leaveing from global\n                            // done_vars? How does that make sense?\n                            // Ah. This is a FAILURE. So removing from done_vars allows it to re-render\n                            // later in the cite if desired.\n                            // Currently no tests fail from removing the condition, but leaving it in.\n                            for (var i=0,ilen=flags.done_vars.length;i<ilen;i++) {\n                                var doneVar = flags.done_vars[i];\n                                for (var j=0,jlen=state.tmp.done_vars.length; j<jlen; j++) {\n                                    if (state.tmp.done_vars[j] === doneVar) {\n                                        state.tmp.done_vars = state.tmp.done_vars.slice(0, j).concat(state.tmp.done_vars.slice(j+1));\n                                    }\n                                }\n                            }\n                        }\n                        if (state.output.current.value().blobs) {\n                            state.output.current.value().blobs.pop();\n                        }\n                    }\n                }\n            };\n            this.execs.push(func);\n            \n            if (this.juris) {\n                var else_end = new CSL.Token(\"else\", CSL.END);\n                CSL.Node[\"else\"].build.call(else_end, state, target);\n                var choose_end = new CSL.Token(\"choose\", CSL.END);\n                CSL.Node.choose.build.call(choose_end, state, target);\n            }\n        }\n\n        if (this.tokentype === CSL.END) {\n            if (!this.juris) {\n                target.push(this);\n            }\n            if (state.build.substitute_level.value()) {\n                state.build.substitute_level.replace((state.build.substitute_level.value() - 1));\n            }\n            CSL.Util.substituteEnd.call(this, state, target);\n        }\n    }\n};\n\n/*global CSL: true */\n\nCSL.Node[\"if\"] = {\n    build: function (state, target) {\n        CSL.Conditions.TopNode.call(this, state, target);\n        target.push(this);\n    },\n    configure: function (state, pos) {\n        CSL.Conditions.Configure.call(this, state, pos);\n    }\n};\n\n\nCSL.Node[\"conditions\"] = {\n    build: function (state) {\n        if (this.tokentype === CSL.START) {\n            state.tmp.conditions.addMatch(this.match);\n        }\n        if (this.tokentype === CSL.END) {\n            state.tmp.conditions.matchCombine();\n        }\n    }\n};\n\nCSL.Node[\"condition\"] = {\n    build: function (state) {\n        if (this.tokentype === CSL.SINGLETON) {\n            var test = state.fun.match[this.match](this, state, this.tests);\n            state.tmp.conditions.addTest(test);\n        }\n    }\n};\n\nCSL.Conditions = {};\n\nCSL.Conditions.TopNode = function (state) {\n    var func;\n    if (this.tokentype === CSL.START || this.tokentype === CSL.SINGLETON) {\n        if (this.locale) {\n            state.opt.lang = this.locale;\n        }\n        if (!this.tests || !this.tests.length) {\n            // Set up the condition compiler with our current context\n            state.tmp.conditions = new CSL.Conditions.Engine(state, this);\n        } else {\n            // The usual.\n            this.test = state.fun.match[this.match](this, state, this.tests);\n        }\n        if (state.build.substitute_level.value() === 0) {\n            func = function(state) {\n                state.tmp.condition_counter++;\n            }\n            this.execs.push(func);\n        }\n    }\n    if (this.tokentype === CSL.END || this.tokentype === CSL.SINGLETON) {\n        if (state.build.substitute_level.value() === 0) {\n            func = function (state) {\n                state.tmp.condition_counter--;\n                if (state.tmp.condition_lang_counter_arr.length > 0) {\n                    var counter = state.tmp.condition_lang_counter_arr.slice(-1)[0];\n                    if (counter === state.tmp.condition_counter) {\n                        state.opt.lang = state.tmp.condition_lang_val_arr.pop();\n                        state.tmp.condition_lang_counter_arr.pop();\n                    }\n                }\n                if (this.locale_default) {\n                    // Open output tag with locale marker\n                    state.output.current.value().old_locale = this.locale_default;\n                    state.output.closeLevel(\"empty\");\n                    state.opt.lang = this.locale_default;\n                }\n            };\n            this.execs.push(func);\n        }\n        // closingjump\n        func = function (state) {\n            var next = this[state.tmp.jump.value()];\n            return next;\n        };\n        this.execs.push(func);\n        if (this.locale_default) {\n            state.opt.lang = this.locale_default;\n        }\n    }\n};\n\nCSL.Conditions.Configure = function (state, pos) {\n    if (this.tokentype === CSL.START) {\n        // jump index on failure\n        this.fail = state.configure.fail.slice(-1)[0];\n        this.succeed = this.next;\n        state.configure.fail[(state.configure.fail.length - 1)] = pos;\n    } else if (this.tokentype === CSL.SINGLETON) {\n        // jump index on failure\n        this.fail = this.next;\n        this.succeed = state.configure.succeed.slice(-1)[0];\n        state.configure.fail[(state.configure.fail.length - 1)] = pos;\n    } else {\n        // jump index on success\n        this.succeed = state.configure.succeed.slice(-1)[0];\n        this.fail = this.next;\n    }\n};\n\nCSL.Conditions.Engine = function (state, token) {\n    this.token = token;\n    this.state = state;\n};\n\nCSL.Conditions.Engine.prototype.addTest = function (test) {\n    this.token.tests ? {} : this.token.tests = [];\n    this.token.tests.push(test);\n};\n\nCSL.Conditions.Engine.prototype.addMatch = function (match) {\n    this.token.match = match;\n};\n\nCSL.Conditions.Engine.prototype.matchCombine = function () {\n    this.token.test = this.state.fun.match[this.token.match](this.token, this.state, this.token.tests);\n};\n\n/*global CSL: true */\n\nCSL.Node.info = {\n    build: function (state) {\n        if (this.tokentype === CSL.START) {\n            state.build.skip = \"info\";\n        } else {\n            state.build.skip = false;\n        }\n    }\n};\n\n\n/*global CSL: true */\n\nCSL.Node.institution = {\n    build: function (state, target) {\n        if ([CSL.SINGLETON, CSL.START].indexOf(this.tokentype) > -1) {\n\n            var func = function (state) {\n                if (\"string\" === typeof this.strings.delimiter) {\n                    state.tmp.institution_delimiter = this.strings.delimiter;\n                } else {\n                    state.tmp.institution_delimiter = state.tmp.name_delimiter;\n                }\n\n                // This is the same code for the same result as in node_name.js, \n                // but when cs:institution comes on stream, it may produce\n                // different results.\n                if (\"text\" === state.inheritOpt(this, \"and\")) {\n                    this.and_term = state.getTerm(\"and\", \"long\", 0);\n                } else if (\"symbol\" === state.inheritOpt(this, \"and\")) {\n                    if (state.opt.development_extensions.expect_and_symbol_form) {\n                        this.and_term = state.getTerm(\"and\", \"symbol\", 0);\n                    } else {\n                        this.and_term = \"&\";\n                    }\n                } else if (\"none\" === state.inheritOpt(this, \"and\")) {\n                    this.and_term = state.tmp.institution_delimiter;\n                }\n                if (\"undefined\" === typeof this.and_term && state.tmp.and_term) {\n                    // this.and_term = state.getTerm(\"and\", \"long\", 0);\n                    this.and_term = state.tmp.and_term;\n                }\n                if (CSL.STARTSWITH_ROMANESQUE_REGEXP.test(this.and_term)) {\n                    this.and_prefix_single = \" \";\n                    this.and_prefix_multiple = \", \";\n                    if (\"string\" === typeof state.tmp.institution_delimiter) {\n                        this.and_prefix_multiple = state.tmp.institution_delimiter;\n                    }\n                    this.and_suffix = \" \";\n                } else {\n                    this.and_prefix_single = \"\";\n                    this.and_prefix_multiple = \"\";\n                    this.and_suffix = \"\";\n                }\n                if (state.inheritOpt(this, \"delimiter-precedes-last\") === \"always\") {\n                    this.and_prefix_single = state.tmp.institution_delimiter;\n                } else if (state.inheritOpt(this, \"delimiter-precedes-last\") === \"never\") {\n                    // Slightly fragile: could test for charset here to make\n                    // this more certain.\n                    if (this.and_prefix_multiple) {\n                        this.and_prefix_multiple = \" \";\n                    }\n                }\n                \n                this.and = {};\n                if (\"undefined\" !== typeof this.and_term) {\n                    state.output.append(this.and_term, \"empty\", true);\n                    this.and.single = state.output.pop();\n                    this.and.single.strings.prefix = this.and_prefix_single;\n                    this.and.single.strings.suffix = this.and_suffix;\n                    state.output.append(this.and_term, \"empty\", true);\n                    this.and.multiple = state.output.pop();\n                    this.and.multiple.strings.prefix = this.and_prefix_multiple;\n                    this.and.multiple.strings.suffix = this.and_suffix;\n                } else if (\"undefined\" !== this.strings.delimiter) {\n                    this.and.single = new CSL.Blob(state.tmp.institution_delimiter);\n                    this.and.single.strings.prefix = \"\";\n                    this.and.single.strings.suffix = \"\";\n                    this.and.multiple = new CSL.Blob(state.tmp.institution_delimiter);\n                    this.and.multiple.strings.prefix = \"\";\n                    this.and.multiple.strings.suffix = \"\";\n                }\n                state.nameOutput.institution = this;\n            };\n            this.execs.push(func);\n        }\n        target.push(this);\n    },\n    configure: function (state) {\n        if ([CSL.SINGLETON, CSL.START].indexOf(this.tokentype) > -1) {\n            state.build.has_institution = true;\n        }\n    }\n};\n\n/*global CSL: true */\n\nCSL.Node[\"institution-part\"] = {\n    build: function (state, target) {\n        var func;\n        if (\"long\" === this.strings.name) {\n            if (this.strings[\"if-short\"]) {\n                func = function (state) {\n                    state.nameOutput.institutionpart[\"long-with-short\"] = this;\n                };\n            } else {\n                func = function (state) {\n                    state.nameOutput.institutionpart[\"long\"] = this;\n                };\n            }\n        } else if (\"short\" === this.strings.name) {\n            func = function (state) {\n                state.nameOutput.institutionpart[\"short\"] = this;\n            };\n        }\n        this.execs.push(func);\n        target.push(this);\n    }\n};\n\n/*global CSL: true */\n\nCSL.Node.key = {\n    build: function (state, target) {\n        \n        target = state[state.build.root + \"_sort\"].tokens;\n\n        var func;\n        var debug = false;\n        var start_key = new CSL.Token(\"key\", CSL.START);\n\n        state.tmp.root = state.build.root;\n\n        // The params object for build and runtime (tmp) really shouldn't have been separated.\n        // Oh, well.\n        start_key.strings[\"et-al-min\"] = state.inheritOpt(this, \"et-al-min\");\n        start_key.strings[\"et-al-use-first\"] = state.inheritOpt(this, \"et-al-use-first\");\n        start_key.strings[\"et-al-use-last\"] = state.inheritOpt(this, \"et-al-use-last\");\n\n\n        // initialize done vars\n        func = function (state) {\n            state.tmp.done_vars = [];\n        };\n        start_key.execs.push(func);\n\n        // initialize output queue\n        func = function (state) {\n            state.output.openLevel(\"empty\");\n        };\n        start_key.execs.push(func);\n\n        // sort direction\n        var sort_direction = [];\n        if (this.strings.sort_direction === CSL.DESCENDING) {\n            //print(\"sort: descending on \"+state.tmp.area);\n            sort_direction.push(1);\n            sort_direction.push(-1);\n        } else {\n            //print(\"sort: ascending\");\n            sort_direction.push(-1);\n            sort_direction.push(1);\n        }\n        state[state.build.area].opt.sort_directions.push(sort_direction);\n\n        if (CSL.DATE_VARIABLES.indexOf(this.variables[0]) > -1) {\n            state.build.date_key = true;\n        }\n\n        // et al init\n        func = function (state) {\n            state.tmp.sort_key_flag = true;\n            //print(\"== key node function ==\");\n            if (state.inheritOpt(this, \"et-al-min\")) {\n                state.tmp[\"et-al-min\"] = state.inheritOpt(this, \"et-al-min\");\n            }\n            if (state.inheritOpt(this, \"et-al-use-first\")) {\n                state.tmp[\"et-al-use-first\"] = state.inheritOpt(this, \"et-al-use-first\");\n            }\n            if (\"boolean\" === typeof state.inheritOpt(this, \"et-al-use-last\")) {\n                state.tmp[\"et-al-use-last\"] = state.inheritOpt(this, \"et-al-use-last\");\n                //print(\"  set tmp et-al-use-last: \"+this.strings[\"et-al-use-last\"])\n            }\n        };\n        start_key.execs.push(func);\n        target.push(start_key);\n        \n        //\n        // ops to initialize the key's output structures\n        if (this.variables.length) {\n            var variable = this.variables[0];\n            if (CSL.NAME_VARIABLES.indexOf(variable) > -1) {\n                //\n                // Start tag\n                var names_start_token = new CSL.Token(\"names\", CSL.START);\n                names_start_token.tokentype = CSL.START;\n                names_start_token.variables = this.variables;\n                CSL.Node.names.build.call(names_start_token, state, target);\n                //\n                // Name tag\n                var name_token = new CSL.Token(\"name\", CSL.SINGLETON);\n                name_token.tokentype = CSL.SINGLETON;\n                name_token.strings[\"name-as-sort-order\"] = \"all\";\n                name_token.strings[\"sort-separator\"] = \" \";\n                name_token.strings[\"et-al-use-last\"] = state.inheritOpt(this, \"et-al-use-last\");\n                name_token.strings[\"et-al-min\"] = state.inheritOpt(this, \"et-al-min\");\n                name_token.strings[\"et-al-use-first\"] = state.inheritOpt(this, \"et-al-use-first\");\n                CSL.Node.name.build.call(name_token, state, target);\n                //\n                // Institution tag\n                var institution_token = new CSL.Token(\"institution\", CSL.SINGLETON);\n                institution_token.tokentype = CSL.SINGLETON;\n                CSL.Node.institution.build.call(institution_token, state, target);\n                //\n                // End tag\n                var names_end_token = new CSL.Token(\"names\", CSL.END);\n                names_end_token.tokentype = CSL.END;\n                CSL.Node.names.build.call(names_end_token, state, target);\n            } else {\n                var single_text = new CSL.Token(\"text\", CSL.SINGLETON);\n                single_text.strings.sort_direction = this.strings.sort_direction;\n                single_text.dateparts = this.dateparts;\n                if (CSL.NUMERIC_VARIABLES.indexOf(variable) > -1) {\n                    // citation-number is virtualized. As a sort key it has no effect on registry\n                    // sort order per se, but if set to DESCENDING, it reverses the sequence of numbers representing\n                    // bib entries.\n                    if (variable === \"citation-number\") {\n                        func = function (state, Item) {\n                            if (state.tmp.area === \"bibliography_sort\") {\n                                if (this.strings.sort_direction === CSL.DESCENDING) {\n                                    state.bibliography_sort.opt.citation_number_sort_direction = CSL.DESCENDING;\n                                } else {\n                                    state.bibliography_sort.opt.citation_number_sort_direction = CSL.ASCENDING;\n                                }\n                            }\n                            if (state.tmp.area === \"citation_sort\" && state.bibliography_sort.tmp.citation_number_map) {\n                                var num = state.bibliography_sort.tmp.citation_number_map[state.registry.registry[Item.id].seq];\n                            } else {\n                                var num = state.registry.registry[Item.id].seq;\n                            }\n                            if (num) {\n                                // Code currently in util_number.js\n                                num = CSL.Util.padding(\"\" + num);\n                            }\n                            state.output.append(num, this);\n                        };\n                    } else {\n                        func = function (state, Item) {\n                            var num = false;\n                            num = Item[variable];\n                            // XXX What if this is NaN?\n                            if (num) {\n                                // Code currently in util_number.js\n                                num = CSL.Util.padding(num);\n                            }\n                            state.output.append(num, this);\n                        };\n                    }\n                } else if (variable === \"citation-label\") {\n                    func = function (state, Item) {\n                        var trigraph = state.getCitationLabel(Item);\n                        state.output.append(trigraph, this);\n                    };\n                } else if (CSL.DATE_VARIABLES.indexOf(variable) > -1) {\n                    func = CSL.dateAsSortKey;\n                    single_text.variables = this.variables;\n                } else if (\"title\" === variable) {\n                    var abbrevfam = \"title\";\n                    var abbrfall = false;\n                    var altvar = false;\n                    var transfall = true;\n                    func = state.transform.getOutputFunction(this.variables, abbrevfam, abbrfall, altvar, transfall);\n                } else if (\"court-class\" === variable) {\n                    func = function(state, Item, item) {\n                        CSL.INIT_JURISDICTION_MACROS(state, Item, item, \"juris-main\")\n                        // true is for sortKey mode\n                        var cls = CSL.GET_COURT_CLASS(state, Item, true);\n                        state.output.append(cls, \"empty\");\n                    }\n                } else {\n                    func = function (state, Item) {\n                        var varval = Item[variable];\n                        state.output.append(varval, \"empty\");\n                    };\n                }\n                single_text.execs.push(func);\n                target.push(single_text);\n            }\n        } else { // macro\n            //\n            // if it's not a variable, it's a macro\n            var token = new CSL.Token(\"text\", CSL.SINGLETON);\n            token.strings.sort_direction = this.strings.sort_direction;\n            token.postponed_macro = this.postponed_macro;\n            CSL.expandMacro.call(state, token, target);\n        }\n        //\n        // ops to output the key string result to an array go\n        // on the closing \"key\" tag before it is pushed.\n        // Do not close the level.\n        var end_key = new CSL.Token(\"key\", CSL.END);\n\n        // Eliminated at revision 1.0.159.\n        // Was causing non-fatal error \"wanted empty but found group\".\n        // Possible contributor to weird \"PAGES\" bug?\n        //func = function (state, Item) {\n        //state.output.closeLevel(\"empty\");\n        //};\n        //end_key.execs.push(func);\n        \n        // store key for use\n        func = function (state) {\n            var keystring = state.output.string(state, state.output.queue);\n            if (state.sys.normalizeUnicode) {\n                keystring = state.sys.normalizeUnicode(keystring);\n            }\n            keystring = keystring ? (keystring.split(\" \").join(state.opt.sort_sep) + state.opt.sort_sep) : \"\";\n            //SNIP-START\n            if (debug) {\n                CSL.debug(\"keystring: \" + keystring + \" \" + typeof keystring);\n            }\n            //print(\"keystring: (\" + keystring + \") \" + typeof keystring + \" \" + state.tmp.area);\n            //SNIP-END\n            //state.sys.print(\"keystring: (\" + keystring + \") \" + typeof keystring + \" \" + state.tmp.area);\n            if (\"\" === keystring) {\n                keystring = undefined;\n            }\n            if (\"string\" !== typeof keystring) {\n                keystring = undefined;\n                //state.tmp.empty_date = false;\n            }\n            state[state[state.tmp.area].root + \"_sort\"].keys.push(keystring);\n            state.tmp.value = [];\n        };\n        end_key.execs.push(func);\n\n        // Set year-suffix key on anything that looks like a date\n        if (state.build.date_key) {\n            if (state.build.area === \"citation\" && state.build.extension === \"_sort\") {\n                // ascending sort always\n                state[state.build.area].opt.sort_directions.push([-1,1]);\n                func = function (state, Item) {\n                    // year-suffix Key\n                    var year_suffix = state.registry.registry[Item.id].disambig.year_suffix;\n                    if (!year_suffix) {\n                        year_suffix = 0;\n                    }\n                    var key = CSL.Util.padding(\"\" + year_suffix);\n                    state[state.tmp.area].keys.push(key);\n                };\n                end_key.execs.push(func);\n            }\n            state.build.date_key = false;\n        }\n\n        // reset key params\n        func = function (state) {\n            // state.tmp.name_quash = new Object();\n\n            // XXX This should work, should be necessary, but doesn't and isn't.\n            //state.output.closeLevel(\"empty\");\n\n            state.tmp[\"et-al-min\"] = undefined;\n            state.tmp[\"et-al-use-first\"] = undefined;\n            state.tmp[\"et-al-use-last\"] = undefined;\n            state.tmp.sort_key_flag = false;\n        };\n        end_key.execs.push(func);\n        target.push(end_key);\n    }\n};\n\n/*global CSL: true */\n\nCSL.Node.label = {\n    build: function (state, target) {\n        \n        if (this.strings.term) {\n            // Non-names labels\n            var func = function (state, Item, item) {\n                // Must accomplish this without touching strings\n                // shared with the calling application: \"sub verbo\"\n                // and \"sub-verbo\" must both pass, as they stand.\n                //if (item && item.label === \"sub verbo\") {\n                //    item.label = \"sub-verbo\";\n                //}\n                // This is abstracted away, because the same\n                // logic must be run in cs:names.\n                var termtxt = CSL.evaluateLabel(this, state, Item, item);\n                if (item && this.strings.term === \"locator\") {\n\n                    item.section_form_override = this.strings.form;\n\n                }\n                if (termtxt) {\n                    state.tmp.group_context.tip.term_intended = true;\n                }\n                CSL.UPDATE_GROUP_CONTEXT_CONDITION(state, termtxt, null, this);\n                if (termtxt.indexOf(\"%s\") === -1) {\n                    // ^ Suppress output here if we have an embedded term\n                    if (this.strings.capitalize_if_first) {\n                        if (!state.tmp.term_predecessor && !(state.opt[\"class\"] === \"in-text\" && state.tmp.area === \"citation\")) {\n                            termtxt = CSL.Output.Formatters[\"capitalize-first\"](state, termtxt);\n                        }\n                    }\n                    state.output.append(termtxt, this);\n                }\n            };\n            this.execs.push(func);\n        } else {\n            if (!this.strings.form) {\n                this.strings.form = \"long\";\n            }\n            // Names labels\n            // Picked up in names END\n            var namevars = state.build.names_variables[state.build.names_variables.length-1];\n            var namelabels = state.build.name_label[state.build.name_label.length-1];\n            for (var i = 0, ilen = namevars.length; i < ilen; i += 1) {\n                if (!namelabels[namevars[i]]) {\n                    namelabels[namevars[i]] = {};\n                }\n            }\n            if (!state.build.name_flag) {\n                for (var i = 0, ilen = namevars.length; i < ilen; i += 1) {\n                    namelabels[namevars[i]].before = this;\n                }\n            } else {\n                for (var i = 0, ilen = namevars.length; i < ilen; i += 1) {\n                    namelabels[namevars[i]].after = this;\n                }\n            }\n        }\n        target.push(this);\n    }\n};\n\n/*global CSL: true */\n\nCSL.Node.layout = {\n    build: function (state, target) {\n        var func, prefix_token, suffix_token, tok;\n\n        function setSuffix() {\n            if (state.build.area === \"bibliography\") {\n                suffix_token = new CSL.Token(\"text\", CSL.SINGLETON);\n                func = function(state) {\n                    // Suppress suffix on all but the last item in bibliography parallels\n                    if (!state.tmp.parallel_and_not_last) {\n                        var suffix;\n                        if (state.tmp.cite_affixes[state.tmp.area][state.tmp.last_cite_locale]) {\n                            suffix = state.tmp.cite_affixes[state.tmp.area][state.tmp.last_cite_locale].suffix;\n                        } else {\n                            suffix = state.bibliography.opt.layout_suffix;\n                        }\n\n                        // If @display is used, layout suffix is placed on the last\n                        // immediate child of the layout, which we assume will be a\n                        // @display group node.\n                        var topblob = state.output.current.value();\n                        if (state.opt.using_display) {\n                            topblob.blobs[topblob.blobs.length-1].strings.suffix = suffix;\n                        } else {\n                            topblob.strings.suffix = suffix;\n                        }\n                    }\n                    if (state.bibliography.opt[\"second-field-align\"]) {\n                        // closes bib_other\n                        state.output.endTag(\"bib_other\");\n                    }\n                };\n                suffix_token.execs.push(func);\n                target.push(suffix_token);\n            }\n        }\n\n        if (this.tokentype === CSL.START) {\n\n            if (this.locale_raw) {\n                state.build.current_default_locale = this.locale_raw;\n            } else {\n                state.build.current_default_locale = state.opt[\"default-locale\"];\n            }\n\n            func = function (state, Item, item) {\n                if (state.opt.development_extensions.apply_citation_wrapper\n                    && state.sys.wrapCitationEntry\n                    && !state.tmp.just_looking\n                    && Item.system_id \n                    && state.tmp.area === \"citation\") { \n\n                    var cite_entry = new CSL.Token(\"group\", CSL.START);\n                    cite_entry.decorations = [[\"@cite\", \"entry\"]];\n                    state.output.startTag(\"cite_entry\", cite_entry);\n                    state.output.current.value().item_id = Item.system_id;\n                    if (item) {\n                        state.output.current.value().locator_txt = item.locator_txt;\n                        state.output.current.value().suffix_txt = item.suffix_txt;\n                    }\n                }\n            };\n            this.execs.push(func);\n        }\n\n        // XXX Works, but using state.tmp looks wrong here? We're in the build layer ...\n        if (this.tokentype === CSL.START && !state.tmp.cite_affixes[state.build.area]) {\n            //\n            // done_vars is used to prevent the repeated\n            // rendering of variables\n            //\n            // initalize done vars\n            func = function (state, Item, item) {\n\n                state.tmp.done_vars = [];\n                if (item && item[\"author-only\"]) {\n                    state.tmp.done_vars.push(\"locator\");\n                }\n                if (state.opt.suppressedJurisdictions[Item[\"country\"]]\n                    && Item[\"country\"]\n                    && [\"treaty\", \"patent\"].indexOf(Item.type) === -1) {\n                    \n                    state.tmp.done_vars.push(\"country\");\n                }\n                if (!state.tmp.just_looking && state.registry.registry[Item.id] && state.registry.registry[Item.id].parallel) {\n                    state.tmp.done_vars.push(\"first-reference-note-number\");\n                }\n                // trimmer is not available in getAmbiguousCite\n                if (!state.tmp.just_looking && state.tmp.abbrev_trimmer && Item.jurisdiction) {\n                    for (var field in state.tmp.abbrev_trimmer.QUASHES[Item.jurisdiction]) {\n                        state.tmp.done_vars.push(field);\n                    }\n                }\n\n                //CSL.debug(\" === init rendered_name === \");\n                state.tmp.rendered_name = false;\n            };\n            this.execs.push(func);\n            // set opt delimiter\n            func = function (state) {\n                // just in case\n                state.tmp.sort_key_flag = false;\n            };\n            this.execs.push(func);\n            \n            // reset nameset counter [all nodes]\n            func = function (state) {\n                state.tmp.nameset_counter = 0;\n            };\n            this.execs.push(func);\n\n            func = function (state, Item) {\n                var tok = new CSL.Token();\n                state.output.openLevel(tok);\n            };\n            this.execs.push(func);\n            target.push(this);\n\n            if (state.build.area === \"citation\") {\n                prefix_token = new CSL.Token(\"text\", CSL.SINGLETON);\n                func = function (state, Item, item) {\n                    if (item && item.prefix) {\n                        var prefix = CSL.checkPrefixSpaceAppend(state, item.prefix);\n                        if (!state.tmp.just_looking) {\n                            prefix = state.output.checkNestedBrace.update(prefix);\n                        }\n                        var ignorePredecessor = CSL.checkIgnorePredecessor(state, prefix);\n                        state.output.append(prefix, this, false, ignorePredecessor);\n                    }\n                };\n                prefix_token.execs.push(func);\n                target.push(prefix_token);\n            }\n        }\n\n        // Cast token to be used in one of the configurations below.\n        var my_tok;\n        if (this.locale_raw) {\n            my_tok = new CSL.Token(\"dummy\", CSL.START);\n            my_tok.locale = this.locale_raw;\n            my_tok.strings.delimiter = this.strings.delimiter;\n            my_tok.strings.suffix = this.strings.suffix;\n            if (!state.tmp.cite_affixes[state.build.area]) {\n                state.tmp.cite_affixes[state.build.area] = {};\n            }\n        }\n\n        if (this.tokentype === CSL.START) {\n            state.build.layout_flag = true;\n                            \n            // Only run the following once, to set up the final layout node ...\n            if (!this.locale_raw) {\n                //\n                // save out decorations for flipflop processing [final node only]\n                //\n                state[state.tmp.area].opt.topdecor = [this.decorations];\n                state[(state.tmp.area + \"_sort\")].opt.topdecor = [this.decorations];\n\n                state[state.build.area].opt.layout_prefix = this.strings.prefix;\n                state[state.build.area].opt.layout_suffix = this.strings.suffix;\n                state[state.build.area].opt.layout_delimiter = this.strings.delimiter;\n\n                state[state.build.area].opt.layout_decorations = this.decorations;\n                \n                // Only do this if we're running conditionals\n                if (state.tmp.cite_affixes[state.build.area]) {\n                    // if build_layout_locale_flag is true,\n                    // write cs:else START to the token list.\n                    tok = new CSL.Token(\"else\", CSL.START);\n                    CSL.Node[\"else\"].build.call(tok, state, target);\n                }\n\n            } // !this.locale_raw\n\n            // Conditionals\n            if (this.locale_raw) {\n                if (!state.build.layout_locale_flag) {\n                    // if layout_locale_flag is untrue,\n                    // write cs:choose START and cs:if START\n                    // to the token list.\n                    var choose_tok = new CSL.Token(\"choose\", CSL.START);\n                    CSL.Node.choose.build.call(choose_tok, state, target);\n                    my_tok.name = \"if\";\n                    CSL.Attributes[\"@locale-internal\"].call(my_tok, state, this.locale_raw);\n                    CSL.Node[\"if\"].build.call(my_tok, state, target);\n                } else {\n                    // if build_layout_locale_flag is true,\n                    // write cs:else-if START to the token list.\n                    my_tok.name = \"else-if\";\n                    CSL.Attributes[\"@locale-internal\"].call(my_tok, state, this.locale_raw);\n                    CSL.Node[\"else-if\"].build.call(my_tok, state, target);\n                }\n                // cite_affixes for this node\n                state.tmp.cite_affixes[state.build.area][my_tok.locale] = {};\n                state.tmp.cite_affixes[state.build.area][my_tok.locale].delimiter = this.strings.delimiter;\n                state.tmp.cite_affixes[state.build.area][my_tok.locale].suffix = this.strings.suffix;\n            }\n        }\n        if (this.tokentype === CSL.END) {\n            if (this.locale_raw) {\n                setSuffix();\n                if (!state.build.layout_locale_flag) {\n                    // If layout_locale_flag is untrue, write cs:if END\n                    // to the token list.\n                    my_tok.name = \"if\";\n                    my_tok.tokentype = CSL.END;\n                    CSL.Attributes[\"@locale-internal\"].call(my_tok, state, this.locale_raw);\n                    CSL.Node[\"if\"].build.call(my_tok, state, target);\n                    state.build.layout_locale_flag = true;\n                } else {\n                    // If layout_locale_flag is true, write cs:else-if END\n                    // to the token list.\n                    my_tok.name = \"else-if\";\n                    my_tok.tokentype = CSL.END;\n                    CSL.Attributes[\"@locale-internal\"].call(my_tok, state, this.locale_raw);\n                    CSL.Node[\"else-if\"].build.call(my_tok, state, target);\n                }\n            }\n            if (!this.locale_raw) {\n                setSuffix();\n                // Only add this if we're running conditionals\n                if (state.tmp.cite_affixes[state.build.area]) {\n                    // If layout_locale_flag is true, write cs:else END\n                    // and cs:choose END to the token list.\n                    if (state.build.layout_locale_flag) {\n                        tok = new CSL.Token(\"else\", CSL.END);\n                        CSL.Node[\"else\"].build.call(tok, state, target);\n                        tok = new CSL.Token(\"choose\", CSL.END);\n                        CSL.Node.choose.build.call(tok, state, target);\n                    }\n                }\n                state.build_layout_locale_flag = true;\n                if (state.build.area === \"citation\") {\n                    suffix_token = new CSL.Token(\"text\", CSL.SINGLETON);\n                    func = function (state, Item, item) {\n                        var sp;\n                        if (item && item.suffix) {\n                            var suffix = CSL.checkSuffixSpacePrepend(state, item.suffix);\n                            if (!state.tmp.just_looking) {\n                                suffix = state.output.checkNestedBrace.update(suffix);\n                            }\n                            state.output.append((suffix), this);\n                        }\n                    };\n                    suffix_token.execs.push(func);\n                    target.push(suffix_token);\n                }\n\n                // Closes wrapper token\n                func = function (state) {\n                    state.output.closeLevel();\n                };\n                this.execs.push(func);\n                func = function (state, Item) {\n                    if (state.opt.development_extensions.apply_citation_wrapper\n                        && state.sys.wrapCitationEntry\n                        && !state.tmp.just_looking\n                        && Item.system_id \n                        && state.tmp.area === \"citation\") { \n                        \n                        state.output.endTag(); // closes citation link wrapper\n                    }\n                };\n                this.execs.push(func);\n                target.push(this);\n                state.build.layout_flag = false;\n                state.build.layout_locale_flag = false;\n            } // !this.layout_raw\n        }\n    }\n};\n\n/*global CSL: true */\n\nCSL.Node.macro = {\n    build: function () {}\n};\n\n/*global CSL: true */\n\nCSL.Node.alternative = {\n    build: function (state, target) {\n        if (this.tokentype === CSL.START) {\n\n            var choose_tok = new CSL.Token(\"choose\", CSL.START);\n            CSL.Node[\"choose\"].build.call(choose_tok, state, target);\n\n            var if_tok = new CSL.Token(\"if\", CSL.START);\n            CSL.Attributes[\"@alternative-node-internal\"].call(if_tok, state);\n            CSL.Node[\"if\"].build.call(if_tok, state, target);\n\n            var func = function(state, Item) {\n\n                state.tmp.oldItem = Item;\n                state.tmp.oldLang = state.opt.lang;\n                state.tmp.abort_alternative = true;\n\n                if (Item[\"language-name\"] && Item[\"language-name-original\"]) {\n\n                    var newItem = JSON.parse(JSON.stringify(Item));\n\n                    newItem.language = newItem[\"language-name\"];\n                    var langspec = CSL.localeResolve(newItem.language, state.opt[\"default-locale\"][0]);\n\n                    if (state.opt.multi_layout) {\n                        for (var i in state.opt.multi_layout) {\n                            var locale_list = state.opt.multi_layout[i];\n                            var gotlang = false;\n                            for (var j in locale_list) {\n                                var tryspec = locale_list[j];\n                                if (langspec.best === tryspec.best || langspec.base === tryspec.base || langspec.bare === tryspec.bare) {\n                                    gotlang = locale_list[0].best;\n                                    break;\n                                }\n                            }\n                            if (!gotlang) {\n                                gotlang = state.opt[\"default-locale\"][0];\n                            }\n                            state.opt.lang = gotlang;\n                        }\n                    }\n\n                    for (var key in newItem) {\n                        if ([\"id\", \"type\", \"language\", \"multi\"].indexOf(key) === -1 && key.slice(0, 4) !== \"alt-\") {\n                            if (newItem.multi && newItem.multi._keys[key]) {\n                                var deleteme = true;\n                                for (var lang in newItem.multi._keys[key]) {\n                                    if (langspec.bare === lang.replace(/^([a-zA-Z]+).*/, \"$1\")) {\n                                        deleteme = false;\n                                        break;\n                                    }\n                                }\n                                if (deleteme) {\n                                    delete newItem[key];\n                                }\n                            } else {\n                                delete newItem[key];\n                            }\n                        }\n                    }\n                    for (var key in newItem) {\n                        if (key.slice(0, 4) === \"alt-\") {\n                            newItem[key.slice(4)] = newItem[key];\n                            state.tmp.abort_alternative = false;\n                        } else {\n                            if (newItem.multi && newItem.multi._keys) {\n                                if (!newItem[\"alt-\" + key] && newItem.multi._keys[key]) {\n                                    if (newItem.multi._keys[key][langspec.best]) {\n                                        newItem[key] = newItem.multi._keys[key][langspec.best];\n                                        state.tmp.abort_alternative = false;\n                                    } else if (newItem.multi._keys[key][langspec.base]) {\n                                        newItem[key] = newItem.multi._keys[key][langspec.base];\n                                        state.tmp.abort_alternative = false;\n                                    } else if (newItem.multi._keys[key][langspec.bare]) {\n                                        newItem[key] = newItem.multi._keys[key][langspec.bare];\n                                        state.tmp.abort_alternative = false;\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n\n                state.output.openLevel(this);\n                state.registry.refhash[Item.id] = newItem;\n                state.nameOutput = new CSL.NameOutput(state, newItem);\n            };\n            this.execs.push(func);\n            target.push(this);\n\n            var choose_tok = new CSL.Token(\"choose\", CSL.START);\n            CSL.Node[\"choose\"].build.call(choose_tok, state, target);\n\n            var if_tok = new CSL.Token(\"if\", CSL.START);\n            CSL.Attributes[\"@alternative-node-internal\"].call(if_tok, state);\n            var func = function(state) {\n                state.tmp.abort_alternative = true;\n            }\n            if_tok.execs.push(func);\n            CSL.Node[\"if\"].build.call(if_tok, state, target);\n\n        } else if (this.tokentype === CSL.END) {\n\n            var if_tok = new CSL.Token(\"if\", CSL.END);\n            CSL.Node[\"if\"].build.call(if_tok, state, target);\n\n            var choose_tok = new CSL.Token(\"choose\", CSL.END);\n            CSL.Node[\"choose\"].build.call(choose_tok, state, target);\n\n            var func = function(state, Item) {\n                state.output.closeLevel();\n                state.registry.refhash[Item.id] = state.tmp.oldItem;\n                state.opt.lang = state.tmp.oldLang;\n                state.nameOutput = new CSL.NameOutput(state, state.tmp.oldItem);\n                state.tmp.abort_alternative = false;\n            };\n            this.execs.push(func);\n            target.push(this);\n\n            var if_tok = new CSL.Token(\"if\", CSL.END);\n            CSL.Node[\"if\"].build.call(if_tok, state, target);\n\n            var choose_tok = new CSL.Token(\"choose\", CSL.END);\n            CSL.Node[\"choose\"].build.call(choose_tok, state, target);\n\n        }\n    }\n};\n\nCSL.Node[\"alternative-text\"] = {\n    build: function (state, target) {\n        if (this.tokentype === CSL.SINGLETON) {\n            // do stuff\n            var func = function(state, Item) {\n                var Item = state.refetchItem(Item.id);\n                CSL.getCite.call(state, Item);\n            };\n            this.execs.push(func);\n        }\n        target.push(this);\n    }\n};\n\n\n\n/*global CSL: true */\n\nCSL.NameOutput = function(state, Item, item) {\n    this.debug = false;\n    this.state = state;\n    //SNIP-START\n    if (this.debug) {\n        this.state.sys.print(\"(1)\");\n    }\n    //SNIP-END\n    this.Item = Item;\n    this.item = item;\n    this.nameset_base = 0;\n    this.etal_spec = {};\n    this._first_creator_variable = false;\n    this._please_chop = false;\n};\n\nCSL.NameOutput.prototype.init = function (names) {\n    this.requireMatch = names.requireMatch;\n    if (this.state.tmp.term_predecessor) {\n        this.state.tmp.subsequent_author_substitute_ok = false;\n    }\n    if (this.nameset_offset) {\n        this.nameset_base = this.nameset_base + this.nameset_offset;\n    }\n    this.nameset_offset = 0;\n    this.names = names;\n    this.variables = names.variables;\n\n    this.state.tmp.value = [];\n    this.state.tmp.rendered_name = [];\n    this.state.tmp.label_blob = false;\n    this.state.tmp.etal_node = false;\n    this.state.tmp.etal_term = false;\n    for (var i = 0, ilen = this.variables.length; i < ilen; i += 1) {\n        if (this.Item[this.variables[i]] && this.Item[this.variables[i]].length) {\n            this.state.tmp.value = this.state.tmp.value.concat(this.Item[this.variables[i]]);\n        }\n    }\n    this[\"et-al\"] = undefined;\n    // REMOVE THIS\n    this[\"with\"] = undefined;\n\n    this.name = undefined;\n    // long, long-with-short, short\n    this.institutionpart = {};\n    // family, given\n    //this.namepart = {};\n    // before, after\n    //this.label = {};\n\n    this.state.tmp.group_context.tip.variable_attempt = true;\n\n    this.labelVariable = this.variables[0];\n\n    if (!this.state.tmp.value.length) {\n        return;\n    }\n\n    // Abort and proceed to the next substitution if a match is required,\n    // two variables are called, and they do not match.\n    var checkCommonTerm = this.checkCommonAuthor(this.requireMatch);\n    if (checkCommonTerm) {\n        this.state.tmp.can_substitute.pop();\n        this.state.tmp.can_substitute.push(true);\n        //this.state.tmp.group_context.mystack[this.state.tmp.group_context.mystack.length-1].variable_success = false;\n        for (var i in this.variables) {\n            var idx = this.state.tmp.done_vars.indexOf(this.variables[i]);\n            if (idx > -1) {\n                this.state.tmp.done_vars = this.state.tmp.done_vars.slice(0, idx).concat(this.state.tmp.done_vars.slice(i+1));\n            }\n        }\n        this.state.tmp.common_term_match_fail = true;\n        this.variables = [];\n    }\n};\n\n\nCSL.NameOutput.prototype.reinit = function (names, labelVariable) {\n    this.requireMatch = names.requireMatch;\n    this.labelVariable = labelVariable;\n\n    if (this.state.tmp.can_substitute.value()) {\n        this.nameset_offset = 0;\n        // What-all should be carried across from the subsidiary\n        // names node, and on what conditions? For each attribute,\n        // and decoration, is it an override, or is it additive?\n        this.variables = names.variables;\n        \n        // Not sure why this is necessary. Guards against a memory leak perhaps?\n        var oldval = this.state.tmp.value.slice();\n        this.state.tmp.value = [];\n\n        for (var i = 0, ilen = this.variables.length; i < ilen; i += 1) {\n            if (this.Item[this.variables[i]] && this.Item[this.variables[i]].length) {\n                this.state.tmp.value = this.state.tmp.value.concat(this.Item[this.variables[i]]);\n            }\n        }\n        if (this.state.tmp.value.length) {\n            this.state.tmp.can_substitute.replace(false, CSL.LITERAL);\n        }\n\n        this.state.tmp.value = oldval;\n\n    }\n    // Abort and proceed to the next substitution if a match is required,\n    // two variables are called, and they do not match.\n    var checkCommonTerm = this.checkCommonAuthor(this.requireMatch);\n    if (checkCommonTerm) {\n        this.state.tmp.can_substitute.pop();\n        this.state.tmp.can_substitute.push(true);\n        for (var i in this.variables) {\n            var idx = this.state.tmp.done_vars.indexOf(this.variables[i]);\n            if (idx > -1) {\n                this.state.tmp.done_vars = this.state.tmp.done_vars.slice(0, idx).concat(this.state.tmp.done_vars.slice(i+1));\n            }\n        }\n        this.variables = [];\n    }\n};\n\nCSL.NameOutput.prototype.outputNames = function () {\n    var i, ilen;\n    var variables = this.variables;\n    if (this.institution.and) {\n        if (!this.institution.and.single.blobs || !this.institution.and.single.blobs.length) {\n            this.institution.and.single.blobs = this.name.and.single.blobs;\n        }\n        if (!this.institution.and.multiple.blobs || !this.institution.and.multiple.blobs.length) {\n            this.institution.and.multiple.blobs = this.name.and.multiple.blobs;\n        }\n    }\n\n    this.variable_offset = {};\n    if (this.family) {\n        this.family_decor = CSL.Util.cloneToken(this.family);\n        this.family_decor.strings.prefix = \"\";\n        this.family_decor.strings.suffix = \"\";\n        // Sets text-case value (text-case=\"title\" is suppressed for items\n        // non-English with non-English value in Item.language)\n        for (i = 0, ilen = this.family.execs.length; i < ilen; i += 1) {\n            this.family.execs[i].call(this.family_decor, this.state, this.Item);\n        }\n    } else {\n        this.family_decor = false;\n    }\n\n    if (this.given) {\n        this.given_decor = CSL.Util.cloneToken(this.given);\n        this.given_decor.strings.prefix = \"\";\n        this.given_decor.strings.suffix = \"\";\n        // Sets text-case value (text-case=\"title\" is suppressed for items\n        // non-English with non-English value in Item.language)\n        for (i = 0, ilen = this.given.execs.length; i < ilen; i += 1) {\n            this.given.execs[i].call(this.given_decor, this.state, this.Item);\n        }\n    } else {\n        this.given_decor = false;\n    }\n\n    //SNIP-START\n    if (this.debug) {\n        this.state.sys.print(\"(2)\");\n    }\n    //SNIP-END\n    // util_names_etalconfig.js\n    this.getEtAlConfig();\n    //SNIP-START\n    if (this.debug) {\n        this.state.sys.print(\"(3)\");\n    }\n    //SNIP-END\n    // util_names_divide.js\n    this.divideAndTransliterateNames();\n    //SNIP-START\n    if (this.debug) {\n        this.state.sys.print(\"(4)\");\n    }\n    //SNIP-END\n    // util_names_truncate.js\n\n    this.truncatePersonalNameLists();\n    //SNIP-START\n    if (this.debug) {\n        this.state.sys.print(\"(5)\");\n    }\n    //SNIP-END\n\n    //SNIP-START\n    if (this.debug) {\n        this.state.sys.print(\"(6)\");\n    }\n    //SNIP-END\n    // util_names_disambig.js\n    this.disambigNames();\n\n    // util_names_constraints.js\n    this.constrainNames();\n    //SNIP-START\n    if (this.debug) {\n        this.state.sys.print(\"(7)\");\n    }\n    //SNIP-END\n    // form=\"count\"\n    if (this.name.strings.form === \"count\") {\n        if (this.state.tmp.extension || this.names_count != 0) {\n            this.state.output.append(this.names_count, \"empty\");\n            this.state.tmp.group_context.tip.variable_success = true;\n        }\n        return;\n    }\n\n    //SNIP-START\n    if (this.debug) {\n        this.state.sys.print(\"(8)\");\n    }\n    //SNIP-END\n    this.setEtAlParameters();\n    //SNIP-START\n    if (this.debug) {\n        this.state.sys.print(\"(9)\");\n    }\n    //SNIP-END\n    this.setCommonTerm(this.requireMatch);\n    //SNIP-START\n    if (this.debug) {\n        this.state.sys.print(\"(10)\");\n    }\n    //SNIP-END\n    this.renderAllNames();\n    //SNIP-START\n    if (this.debug) {\n        this.state.sys.print(\"(11)\");\n    }\n    //SNIP-END\n    var blob_list = [];\n    for (i = 0, ilen = variables.length; i < ilen; i += 1) {\n        var v = variables[i];\n        var institution_sets = [];\n        var institutions = false;\n        var varblob = null;\n        if (!this.state.opt.development_extensions.spoof_institutional_affiliations) {\n            varblob = this._join([this.freeters[v]], \"\");\n        } else {\n            //SNIP-START\n            if (this.debug) {\n                this.state.sys.print(\"(11a)\");\n            }\n            //SNIP-END\n            for (var j = 0, jlen = this.institutions[v].length; j < jlen; j += 1) {\n                institution_sets.push(this.joinPersonsAndInstitutions([this.persons[v][j], this.institutions[v][j]]));\n            }\n            //SNIP-START\n            if (this.debug) {\n                this.state.sys.print(\"(11b)\");\n            }\n            //SNIP-END\n            if (this.institutions[v].length) {\n                var pos = this.nameset_base + this.variable_offset[v];\n                if (this.freeters[v].length) {\n                    pos += 1;\n                }\n                institutions = this.joinInstitutionSets(institution_sets, pos);\n            }\n            //SNIP-START\n            if (this.debug) {\n                this.state.sys.print(\"(11c)\");\n            }\n            //SNIP-END\n            var varblob = this.joinFreetersAndInstitutionSets([this.freeters[v], institutions]);\n            //SNIP-START\n            if (this.debug) {\n                this.state.sys.print(\"(11d)\");\n            }\n            //SNIP-END\n        }\n        if (varblob) {\n            // Apply labels, if any\n            if (!this.state.tmp.extension) {\n                varblob = this._applyLabels(varblob, v);\n            }\n            blob_list.push(varblob);\n        }\n        //SNIP-START\n        if (this.debug) {\n            this.state.sys.print(\"(11e)\");\n        }\n        //SNIP-END\n        if (this.common_term) {\n            break;\n        }\n    }\n    //SNIP-START\n    if (this.debug) {\n        this.state.sys.print(\"(12)\");\n    }\n    //SNIP-END\n    this.state.output.openLevel(\"empty\");\n    this.state.output.current.value().strings.delimiter = this.state.inheritOpt(this.names, \"delimiter\", \"names-delimiter\");\n    //SNIP-START\n    if (this.debug) {\n        this.state.sys.print(\"(13)\");\n    }\n    //SNIP-END\n    for (i = 0, ilen = blob_list.length; i < ilen; i += 1) {\n        // notSerious\n        this.state.output.append(blob_list[i], \"literal\", true);\n    }\n    if (!this.state.tmp.just_looking && blob_list.length > 0) {\n        this.state.tmp.probably_rendered_something = true;\n    }\n    //SNIP-START\n    if (this.debug) {\n        this.state.sys.print(\"(14)\");\n    }\n    //SNIP-END\n    this.state.output.closeLevel(\"empty\");\n    //SNIP-START\n    if (this.debug) {\n        this.state.sys.print(\"(15)\");\n    }\n    //SNIP-END\n    var blob = this.state.output.pop();\n    this.state.tmp.name_node.top = blob;\n    //SNIP-START\n    if (this.debug) {\n        this.state.sys.print(\"(16)\");\n    }\n    //SNIP-END\n\n    // Append will drop the names on the floor here if suppress-me is\n    // set on element_trace.\n    // Need to rescue the value for collapse comparison.\n    var namesToken = CSL.Util.cloneToken(this.names);\n    if (this.state.tmp.group_context.tip.condition) {\n        CSL.UPDATE_GROUP_CONTEXT_CONDITION(this.state, this.names.strings.prefix, null, this.names);\n    }\n    this.state.output.append(blob, namesToken);\n    if (this.state.tmp.term_predecessor_name) {\n        this.state.tmp.term_predecessor = true;\n    }\n    //SNIP-START\n    if (this.debug) {\n        this.state.sys.print(\"(17)\");\n    }\n    //SNIP-END\n    // Also used in CSL.Util.substituteEnd (which could do with\n    // some cleanup at this writing).\n    //SNIP-START\n    if (this.debug) {\n        this.state.sys.print(\"(18)\");\n    }\n    //SNIP-END\n    if (variables[0] !== \"authority\") {\n        // Just grab the string values in the name\n        var name_node_string = [];\n        var nameobjs = this.Item[variables[0]];\n        if (nameobjs) {\n            for (var i = 0, ilen = nameobjs.length; i < ilen; i += 1) {\n                var substring = CSL.Util.Names.getRawName(nameobjs[i]);\n                if (substring) {\n                    name_node_string.push(substring);\n                }\n            }\n        }\n        name_node_string = name_node_string.join(\", \");\n        if (name_node_string) {\n            this.state.tmp.name_node.string = name_node_string;\n        }\n    }\n    // for classic support\n    // This may be more convoluted than it needs to be. Or maybe not.\n    //\n    // Check for classic abbreviation\n    //\n    // If found, then (1) suppress title rendering, (2) replace the node\n    // with the abbreviation output [and (3) do not run this._collapseAuthor() ?]\n    if (this.state.tmp.name_node.string && !this.state.tmp.first_name_string) {\n        this.state.tmp.first_name_string = this.state.tmp.name_node.string;\n    }\n    if (\"classic\" === this.Item.type) {\n        if (this.state.tmp.first_name_string) {\n            var author_title = [];\n            author_title.push(this.state.tmp.first_name_string);\n            if (this.Item.title) {\n                author_title.push(this.Item.title);\n            }\n            author_title = author_title.join(\", \");\n            if (author_title && this.state.sys.getAbbreviation) {\n                if (this.state.sys.normalizeAbbrevsKey) {\n                    author_title = this.state.sys.normalizeAbbrevsKey(\"classic\", author_title);\n                }\n                this.state.transform.loadAbbreviation(\"default\", \"classic\", author_title, this.Item.language);\n                if (this.state.transform.abbrevs[\"default\"].classic[author_title]) {\n                    this.state.tmp.done_vars.push(\"title\");\n                    this.state.output.append(this.state.transform.abbrevs[\"default\"].classic[author_title], \"empty\", true);\n                    blob = this.state.output.pop();\n\t\t\t\t    this.state.tmp.name_node.top.blobs.pop();\n                    this.state.tmp.name_node.top.blobs.push(blob);\n                }\n            }\n        }\n    }\n\n    // Let's try something clever here.\n    this._collapseAuthor();\n\n    // For name_SubstituteOnNamesSpanNamesSpanFail\n    this.variables = [];\n    \n    // Reset stop-last after rendering\n    this.state.tmp.authority_stop_last = 0;\n\n    //SNIP-START\n    if (this.debug) {\n        this.state.sys.print(\"(19)\");\n    }\n    //SNIP-END\n};\n\nCSL.NameOutput.prototype._applyLabels = function (blob, v) {\n    var txt;\n    if (!this.label || !this.label[this.labelVariable]) {\n        return blob;\n    }\n    var plural = 0;\n    var num = this.freeters_count[v] + this.institutions_count[v];\n    if (num > 1) {\n        plural = 1;\n    } else {\n        for (var i = 0, ilen = this.persons[v].length; i < ilen; i += 1) {\n            num += this.persons_count[v][i];\n        }\n        if (num > 1) {\n            plural = 1;\n        }\n    }\n    // Some code duplication here, should be factored out.\n    if (this.label[this.labelVariable].before) {\n        if (\"number\" === typeof this.label[this.labelVariable].before.strings.plural) {\n            plural = this.label[this.labelVariable].before.strings.plural;\n        }\n        txt = this._buildLabel(v, plural, \"before\", this.labelVariable);\n        this.state.output.openLevel(\"empty\");\n        this.state.output.append(txt, this.label[this.labelVariable].before, true);\n        this.state.output.append(blob, \"literal\", true);\n        this.state.output.closeLevel(\"empty\");\n        blob = this.state.output.pop();\n    } else if (this.label[this.labelVariable].after) {\n        if (\"number\" === typeof this.label[this.labelVariable].after.strings.plural) {\n            plural = this.label[this.labelVariable].after.strings.plural;\n        }\n        txt = this._buildLabel(v, plural, \"after\", this.labelVariable);\n        this.state.output.openLevel(\"empty\");\n        this.state.output.append(blob, \"literal\", true);\n        this.state.output.append(txt, this.label[this.labelVariable].after, true);\n        this.state.tmp.label_blob = this.state.output.pop();\n        this.state.output.append(this.state.tmp.label_blob,\"literal\",true);\n        this.state.output.closeLevel(\"empty\");\n        blob = this.state.output.pop();\n    }\n    return blob;\n};\n\nCSL.NameOutput.prototype._buildLabel = function (term, plural, position, v) {\n    if (this.common_term) {\n        term = this.common_term;\n    }\n\n    var ret = false;\n    var node = this.label[v][position];\n    if (node) {\n        ret = CSL.castLabel(this.state, node, term, plural, CSL.TOLERANT);\n    }\n    return ret;\n};\n\n\nCSL.NameOutput.prototype._collapseAuthor = function () {\n    var myqueue, mystr, oldchars;\n    // collapse can be undefined, an array of length zero, and probably\n    // other things ... ugh.\n    if (this.state.tmp.name_node.top.blobs.length === 0) {\n        return;\n    }\n    if (this.nameset_base === 0 && this.Item[this.variables[0]] && !this._first_creator_variable) {\n        this._first_creator_variable = this.variables[0];\n    }\n    if ((this.state[this.state.tmp.area].opt.collapse\n            && this.state[this.state.tmp.area].opt.collapse.length)\n        || (this.state[this.state.tmp.area].opt.cite_group_delimiter \n            && this.state[this.state.tmp.area].opt.cite_group_delimiter.length)) {\n\n        if (this.state.tmp.authorstring_request) {\n            // Avoid running this on every call to getAmbiguousCite()?\n            mystr = \"\";\n            myqueue = this.state.tmp.name_node.top.blobs.slice(-1)[0].blobs;\n            oldchars = this.state.tmp.offset_characters;\n            if (myqueue) {\n                mystr = this.state.output.string(this.state, myqueue, false);\n            }\n            // Avoid side-effects on character counting: we're only interested\n            // in the final rendering.\n            this.state.tmp.offset_characters = oldchars;\n            this.state.registry.authorstrings[this.Item.id] = mystr;\n        } else if (!this.state.tmp.just_looking\n                   && !this.state.tmp.suppress_decorations && ((this.state[this.state.tmp.area].opt.collapse && this.state[this.state.tmp.area].opt.collapse.length) || this.state[this.state.tmp.area].opt.cite_group_delimiter && this.state[this.state.tmp.area].opt.cite_group_delimiter)) {\n            // XX1 this.state.sys.print(\"RENDER: \"+this.Item.id);\n            mystr = \"\";\n            myqueue = this.state.tmp.name_node.top.blobs.slice(-1)[0].blobs;\n            oldchars = this.state.tmp.offset_characters;\n            if (myqueue) {\n                mystr = this.state.output.string(this.state, myqueue, false);\n            }\n            if (mystr === this.state.tmp.last_primary_names_string) {\n                if (this.item[\"suppress-author\"] || (this.state[this.state.tmp.area].opt.collapse && this.state[this.state.tmp.area].opt.collapse.length)) {\n                    // XX1 this.state.sys.print(\"    CUT!\");\n                    this.state.tmp.name_node.top.blobs.pop();\n                    this.state.tmp.name_node.children = [];\n                    // If popped, avoid side-effects on character counting: we're only interested\n                    // in things that actually render.\n                    this.state.tmp.offset_characters = oldchars;\n                }\n                // Needed\n                if (this.state[this.state.tmp.area].opt.cite_group_delimiter && this.state[this.state.tmp.area].opt.cite_group_delimiter) {\n                    this.state.tmp.use_cite_group_delimiter = true;\n                }\n            } else {\n                // XX1 this.state.sys.print(\"remembering: \"+mystr);\n                this.state.tmp.last_primary_names_string = mystr;\n                // XXXXX A little more precision would be nice.\n                // This will clobber variable=\"author editor\" as well as variable=\"author\".\n\n                if (this.variables.indexOf(this._first_creator_variable) > -1 && this.item && this.item[\"suppress-author\"] && this.Item.type !== \"legal_case\") {\n                    this.state.tmp.name_node.top.blobs.pop();\n                    this.state.tmp.name_node.children = [];\n                    // If popped, avoid side-effects on character counting: we're only interested\n                    // in things that actually render.\n                    this.state.tmp.offset_characters = oldchars;\n\n                    // A wild guess, but will usually be correct\n                    this.state.tmp.term_predecessor = false;\n                }\n                // Arcane and probably unnecessarily complicated?\n                this.state.tmp.have_collapsed = false;\n                // Needed\n                if (this.state[this.state.tmp.area].opt.cite_group_delimiter && this.state[this.state.tmp.area].opt.cite_group_delimiter) {\n                    this.state.tmp.use_cite_group_delimiter = false;\n                }\n            }\n        }\n    }\n};\n\n/*\nCSL.NameOutput.prototype.suppressNames = function() {\n    suppress_condition = suppress_min && display_names.length >= suppress_min;\n    if (suppress_condition) {\n        continue;\n    }\n}\n*/\n\n/*global CSL: true */\n\nCSL.NameOutput.prototype.isPerson = function (value) {\n    if (value.literal\n        || (!value.given && value.family && value.isInstitution)) {\n        \n        return false;\n    } else {\n        return true;\n    }\n};\n\n/*global CSL: true */\n\nCSL.NameOutput.prototype.truncatePersonalNameLists = function () {\n    var v, i, ilen, j, jlen, chopvar, values;\n    // XXX Before truncation, make a note of the original number\n    // of names, for use in et-al evaluation.\n    this.freeters_count = {};\n    this.persons_count = {};\n    this.institutions_count = {};\n    // By key is okay here, as we don't care about sequence.\n    for (v in this.freeters) {\n        if (this.freeters.hasOwnProperty(v)) {\n            this.freeters_count[v] = this.freeters[v].length;\n            this.freeters[v] = this._truncateNameList(this.freeters, v);\n        }\n    }\n\n    for (v in this.persons) {\n        if (this.persons.hasOwnProperty(v)) {\n            this.institutions_count[v] = this.institutions[v].length;\n            this._truncateNameList(this.institutions, v);\n            this.persons[v] = this.persons[v].slice(0, this.institutions[v].length);\n            this.persons_count[v] = [];\n            for (j = 0, jlen = this.persons[v].length; j < jlen; j += 1) {\n                this.persons_count[v][j] = this.persons[v][j].length;\n                this.persons[v][j] = this._truncateNameList(this.persons, v, j);\n            }\n        }\n    }\n    if (this.state.opt.development_extensions.etal_min_etal_usefirst_hack\n        && this.etal_min === 1 && this.etal_use_first === 1 \n        && !(this.state.tmp.extension\n             || this.state.tmp.just_looking)) {\n        chopvar = v;\n    } else {\n        chopvar = false;\n    }\n    if (chopvar || this._please_chop) {\n        for (i = 0, ilen = this.variables.length; i < ilen; i += 1) {\n            v = this.variables[i];\n            if (this.freeters[v].length) {\n                if (this._please_chop === v) {\n                    this.freeters[v] = this.freeters[v].slice(1);\n                    this.freeters_count[v] += -1;\n                    this._please_chop = false;\n                } else if (chopvar && !this._please_chop) {\n                    this.freeters[v] = this.freeters[v].slice(0, 1);\n                    this.freeters_count[v] = 1;\n                    this.institutions[v] = [];\n                    this.persons[v] = [];\n                    this._please_chop = chopvar;\n                }\n            }\n            for (var j=0,jlen = this.persons[v].length;j<jlen;j++) {\n                if (this.persons[v][j].length) {\n                    if (this._please_chop === v) {\n                        this.persons[v][j] = this.persons[v][j].slice(1);\n                        this.persons_count[v][j] += -1;\n                        this._please_chop = false;\n                        break;\n                    } else if (chopvar && !this._please_chop) {\n                        this.freeters[v] = this.persons[v][j].slice(0, 1);\n                        this.freeters_count[v] = 1;\n                        this.institutions[v] = [];\n                        this.persons[v] = [];\n                        values = [];\n                        this._please_chop = chopvar;\n                        break;\n                    }\n                }\n            }\n            if (this.institutions[v].length) {\n                if (this._please_chop === v) {\n                    this.institutions[v] = this.institutions[v].slice(1);\n                    this.institutions_count[v] += -1;\n                    this._please_chop = false;\n                } else if (chopvar && !this._please_chop) {\n                    this.institutions[v] = this.institutions[v].slice(0, 1);\n                    this.institutions_count[v] = 1;\n                    values = [];\n                    this._please_chop = chopvar;\n                }\n            }\n        }\n    }\n\n    // Transliteration and abbreviation mapping\n\n    // Hmm. This could produce three lists for each nameset:\n    //   - primary (transformed in place)\n    //   - secondary\n    //   - tertiary\n    // with items that produce no result in the secondary and tertiary\n    // transforms set to false. Maybe.\n\n    // Actually that would be insane, so forget it.\n    // What we need is to add suitable parameters to getName(), and merge\n    // the single-name-level operations below into that function. Then the\n    // operation can be applied in util_names_render.js, and the logic\n    // becomes very similar to what we already have running in util_transform.js.\n\n/*\n    for (v in this.freeters) {\n        this._transformNameset(this.freeters[v]);\n    }\n    for (v in this.persons) {\n        for (i = 0, ilen = this.persons[v].length; i < ilen; i += 1) {\n            this._transformNameset(this.persons[v][i]);\n        }\n        this._transformNameset(this.institutions[v]);\n    }\n*/\n\n    // Could also be factored out to a separate function for clarity.\n    // ???? XXX Does this belong?\n    for (i = 0, ilen = this.variables.length; i < ilen; i += 1) {\n        if (this.institutions[v].length) {\n            this.nameset_offset += 1;\n        }\n        for (var j=0,jlen=this.persons[v].length;j<jlen;j++) {\n            if (this.persons[v][j].length) {\n                this.nameset_offset += 1;\n            }\n            // this.institutions[v][i] = this._splitInstitution(this.institutions[v][i], v, i);\n        }\n    }\n};\n\nCSL.NameOutput.prototype._truncateNameList = function (container, variable, index) {\n    var lst;\n    if (\"undefined\" === typeof index) {\n        lst = container[variable];\n    } else {\n        lst = container[variable][index];\n    }\n    if (this.state[this.state[this.state.tmp.area].root].opt.max_number_of_names \n        && lst.length > 50 \n        && lst.length > (this.state[this.state[this.state.tmp.area].root].opt.max_number_of_names + 2)) {\n\n        // Preserve the last name in the list, in case we're rendering with a PI ellipsis (et-al-use-last)\n        var limit = this.state[this.state[this.state.tmp.area].root].opt.max_number_of_names;\n        lst = lst.slice(0, limit+1).concat(lst.slice(-1));\n    }\n    return lst;\n};\n\n\n/*global CSL: true */\n\nCSL.NameOutput.prototype.divideAndTransliterateNames = function () {\n    var i, ilen, j, jlen;\n    var Item = this.Item;\n    var variables = this.variables;\n    this.varnames = variables.slice();\n    this.freeters = {};\n    this.persons = {};\n    this.institutions = {};\n    for (i = 0, ilen = variables.length; i < ilen; i += 1) {\n        var v = variables[i];\n        this.variable_offset[v] = this.nameset_offset;\n        var values = this._normalizeVariableValue(Item, v);\n        if (this.name.strings[\"suppress-min\"] && values.length >= this.name.strings[\"suppress-min\"]) {\n            values = [];\n        }\n        if (this.name.strings[\"suppress-max\"] && values.length <= this.name.strings[\"suppress-max\"]) {\n            values = [];\n        }\n        this._getFreeters(v, values);\n        this._getPersonsAndInstitutions(v, values);\n        if (this.state.opt.development_extensions.spoof_institutional_affiliations) {\n            if (this.name.strings[\"suppress-min\"] === 0) {\n                this.freeters[v] = [];\n                for (j = 0, jlen = this.persons[v].length; j < jlen; j += 1) {\n                    this.persons[v][j] = [];\n                }\n            } else if (this.institution.strings[\"suppress-min\"] === 0) {\n                this.institutions[v] = [];\n                this.freeters[v] = this.freeters[v].concat(this.persons[v]);\n                for (j = 0, jlen = this.persons[v].length; j < jlen; j += 1) {\n                    for (var k = 0, klen = this.persons[v][j].length; k < klen; k += 1) {\n                        this.freeters[v].push(this.persons[v][j][k]);\n                    }\n                }\n                this.persons[v] = [];\n            }\n        }\n    }\n};\n\nCSL.NameOutput.prototype._normalizeVariableValue = function (Item, variable) {\n    var names;\n    if (\"string\" === typeof Item[variable] || \"number\" === typeof Item[variable]) {\n        CSL.debug(\"name variable \\\"\" + variable + \"\\\" is string or number, not array. Attempting to fix.\");\n        names = [{literal: Item[variable] + \"\"}];\n    } else if (!Item[variable]) {\n        names = [];\n    } else if (\"number\" !== typeof Item[variable].length) {\n        CSL.debug(\"name variable \\\"\" + variable + \"\\\" is object, not array. Attempting to fix.\");\n        Item[variable] = [Item[variable]];\n        names = Item[variable].slice();\n    } else {\n        names = Item[variable].slice();\n    }\n    return names;\n};\n\nCSL.NameOutput.prototype._getFreeters = function (v, values) {\n    this.freeters[v] = [];\n    if (this.state.opt.development_extensions.spoof_institutional_affiliations) {\n        for (var i=values.length-1;i>-1;i--) {\n            if (this.isPerson(values[i])) {\n                var value = this._checkNickname(values.pop());\n                if (value) {\n                    this.freeters[v].push(value);\n                }\n            } else {\n                break;\n            }\n        }\n    } else {\n        for (var i=values.length-1;i>-1;i--) {\n            var value = values.pop();\n            if (this.isPerson(value)) {\n                var value = this._checkNickname(value);\n            }\n            this.freeters[v].push(value);\n        }\n    }\n    this.freeters[v].reverse();\n    if (this.freeters[v].length) {\n        this.nameset_offset += 1;\n    }\n};\n\nCSL.NameOutput.prototype._getPersonsAndInstitutions = function (v, values) {\n    this.persons[v] = [];\n    this.institutions[v] = [];\n    if (!this.state.opt.development_extensions.spoof_institutional_affiliations) {\n        return;\n    }\n    var persons = [];\n    var has_affiliates = false;\n    var first = true;\n    for (var i = values.length - 1; i > -1; i += -1) {\n        if (this.isPerson(values[i])) {\n            var value = this._checkNickname(values[i]);\n            if (value) {\n                persons.push(value);\n            }\n        } else {\n            has_affiliates = true;\n            this.institutions[v].push(values[i]);\n            if (!first) {\n                persons.reverse();\n                this.persons[v].push(persons);\n                persons = [];\n            }\n            first = false;\n        }\n    }\n    if (has_affiliates) {\n        persons.reverse();\n        this.persons[v].push(persons);\n        this.persons[v].reverse();\n        this.institutions[v].reverse();\n    }\n};\n\nCSL.NameOutput.prototype._clearValues = function (values) {\n    for (var i = values.length - 1; i > -1; i += -1) {\n        values.pop();\n    }\n};\n\nCSL.NameOutput.prototype._checkNickname = function (name) {\n    if ([\"interview\", \"personal_communication\"].indexOf(this.Item.type) > -1) {\n        var author = \"\";\n        author = CSL.Util.Names.getRawName(name);\n        if (author && this.state.sys.getAbbreviation && !(this.item && this.item[\"suppress-author\"])) {\n            var normalizedKey = author;\n            if (this.state.sys.normalizeAbbrevsKey) {\n                // The first argument does not have to be the exact variable name.\n                normalizedKey = this.state.sys.normalizeAbbrevsKey(\"author\", author);\n            }\n            this.state.transform.loadAbbreviation(\"default\", \"nickname\", normalizedKey, this.Item.language);\n            // XXX Why does this have to happen here?\n            var myLocalName = this.state.transform.abbrevs[\"default\"].nickname[normalizedKey];\n            if (myLocalName) {\n                if (myLocalName === \"!here>>>\") {\n                    name = false;\n                } else {\n                    name = {family:myLocalName,given:''};\n                }\n            }\n        }\n    }\n    return name;\n};\n\n/*global CSL: true */\n\nCSL.NameOutput.prototype._purgeEmptyBlobs = function (blobs) {\n    for (var i = blobs.length - 1; i > -1; i += -1) {\n        if (!blobs[i] || blobs[i].length === 0 || !blobs[i].blobs.length) {\n            blobs = blobs.slice(0, i).concat(blobs.slice(i + 1));\n        }\n    }\n    return blobs;\n};\n\nCSL.NameOutput.prototype.joinPersons = function (blobs, pos, j, tokenname) {\n    var ret;\n    blobs = this._purgeEmptyBlobs(blobs);\n    if (!tokenname) {\n        tokenname = \"name\";\n    }\n    if (\"undefined\" === typeof j) {\n        if (this.etal_spec[pos].freeters === 1) {\n           ret = this._joinEtAl(blobs);\n        } else if (this.etal_spec[pos].freeters === 2) {\n            ret = this._joinEllipsis(blobs);\n        } else if (!this.state.tmp.sort_key_flag) {\n            ret = this._joinAnd(blobs);\n        } else {\n            ret = this._join(blobs, this.state.inheritOpt(this.name, \"delimiter\", \"name-delimiter\", \", \"));\n        }\n    } else {\n        if (this.etal_spec[pos].persons[j] === 1) {\n            ret = this._joinEtAl(blobs);\n        } else if (this.etal_spec[pos].persons[j] === 2) {\n            ret = this._joinEllipsis(blobs);\n        } else if (!this.state.tmp.sort_key_flag) {\n            ret = this._joinAnd(blobs);\n        } else {\n            ret = this._join(blobs, this.state.inheritOpt(this.name, \"delimiter\", \"name-delimiter\", \", \"));\n        }\n    }\n    return ret;\n};\n\n\nCSL.NameOutput.prototype.joinInstitutionSets = function (blobs, pos) {\n    var ret;\n    blobs = this._purgeEmptyBlobs(blobs);\n    if (this.etal_spec[pos].institutions === 1) {\n        ret = this._joinEtAl(blobs, \"institution\");\n    } else if (this.etal_spec[pos].institutions === 2) {\n        ret = this._joinEllipsis(blobs, \"institution\");\n    } else {\n        ret = this._joinAnd(blobs);\n    }\n    return ret;\n};\n\n\nCSL.NameOutput.prototype.joinPersonsAndInstitutions = function (blobs) {\n    //\n    blobs = this._purgeEmptyBlobs(blobs);\n    var ret = this._join(blobs, this.state.tmp.name_delimiter);\n    ret.isInstitution = true;\n    return ret;\n};\n\n// LEGACY\n// This should go away eventually\nCSL.NameOutput.prototype.joinFreetersAndInstitutionSets = function (blobs) {\n    // Nothing, one or two, never more\n    blobs = this._purgeEmptyBlobs(blobs);\n    var ret = this._join(blobs, \"[never here]\", this[\"with\"].single, this[\"with\"].multiple);\n    //var ret = this._join(blobs, \"\");\n    return ret;\n};\n\nCSL.NameOutput.prototype._getAfterInvertedName = function(blobs, delimiter, finalJoin) {\n    if (finalJoin && blobs.length > 1) {\n        if (this.state.inheritOpt(this.name, \"delimiter-precedes-last\") === \"after-inverted-name\") {\n            var prevBlob = blobs[blobs.length - 2];\n            if (prevBlob.blobs.length > 0 && prevBlob.blobs[0].isInverted) {\n                finalJoin.strings.prefix = delimiter;\n            }\n        }\n    }\n    return finalJoin;\n}\n\nCSL.NameOutput.prototype._getAndJoin = function (blobs, delimiter) {\n    var finalJoin = false;\n    if (blobs.length > 1) {\n        var singleOrMultiple = \"single\";\n        if (blobs.length > 2) {\n            singleOrMultiple = \"multiple\";\n        }\n        if (blobs[blobs.length - 1].isInstitution) {\n            finalJoin = this.institution.and[singleOrMultiple];\n        } else {\n            finalJoin = this.name.and[singleOrMultiple];\n        }\n        // finalJoin = new CSL.Blob(finalJoin);\n        finalJoin = JSON.parse(JSON.stringify(finalJoin));\n        finalJoin = this._getAfterInvertedName(blobs, delimiter, finalJoin);\n    }\n    return finalJoin;\n};\n\nCSL.NameOutput.prototype._joinEtAl = function (blobs) {\n    var delimiter = this.state.inheritOpt(this.name, \"delimiter\", \"name-delimiter\", \", \");\n    var blob = this._join(blobs, delimiter);\n    \n    // notSerious\n    this.state.output.openLevel(this._getToken(\"name\"));\n    // Delimiter is applied from separately saved source in this case,\n    // for discriminate application of single and multiple joins.\n    this.state.output.current.value().strings.delimiter = \"\";\n    this.state.output.append(blob, \"literal\", true);\n    if (blobs.length > 1) {\n        this.state.output.append(this[\"et-al\"].multiple, \"literal\", true);\n    } else if (blobs.length === 1) {\n        this.state.output.append(this[\"et-al\"].single, \"literal\", true);\n    }\n    this.state.output.closeLevel();\n    return this.state.output.pop();\n};\n\n\nCSL.NameOutput.prototype._joinEllipsis = function (blobs) {\n    var delimiter = this.state.inheritOpt(this.name, \"delimiter\", \"name-delimiter\", \", \");\n    var finalJoin = false;\n    if (blobs.length > 1) {\n        var singleOrMultiple = \"single\";\n        if (blobs.length > 2) {\n            singleOrMultiple = \"multiple\";\n        }\n        finalJoin = JSON.parse(JSON.stringify(this.name.ellipsis[singleOrMultiple]));\n        finalJoin = this._getAfterInvertedName(blobs, delimiter , finalJoin);\n        \n    }\n    return this._join(blobs, delimiter, finalJoin);\n};\n\nCSL.NameOutput.prototype._joinAnd = function (blobs) {\n    var delimiter = this.state.inheritOpt(this.name, \"delimiter\", \"name-delimiter\", \", \");\n    var finalJoin = this._getAndJoin(blobs, delimiter);\n    return this._join(blobs, delimiter, finalJoin);\n};\n\n\nCSL.NameOutput.prototype._join = function (blobs, delimiter, finalJoin) {\n    var i, ilen;\n    if (!blobs) {\n        return false;\n    }\n    blobs = this._purgeEmptyBlobs(blobs);\n    if (!blobs.length) {\n        return false;\n    }\n    if (blobs.length > 1) {\n        if (blobs.length === 2) {\n            if (!finalJoin) {\n                blobs[0].strings.suffix += delimiter;\n            } else {\n                blobs = [blobs[0], finalJoin, blobs[1]];\n            }\n        } else {\n            var offset;\n            if (finalJoin) {\n                offset = 1;\n            } else {\n                offset = 0;\n            }\n            var blob = blobs.pop();\n            for (var i=0,ilen=blobs.length - offset;i<ilen;i++) {\n                blobs[i].strings.suffix += delimiter;\n            }\n            blobs.push(finalJoin);\n            blobs.push(blob);\n        }\n    }\n\n    //this.state.output.openLevel(this._getToken(tokenname));\n    this.state.output.openLevel();\n\n    //this.state.output.openLevel(this._getToken(\"empty\"));\n    // Delimiter is applied from separately saved source in this case,\n    // for discriminate application of single and multiple joins.\n    for (i = 0, ilen = blobs.length; i < ilen; i += 1) {\n        this.state.output.append(blobs[i], false, true);\n    }\n    this.state.output.closeLevel();\n    return this.state.output.pop();\n};\n\n\nCSL.NameOutput.prototype._getToken = function (tokenname) {\n    var token = this[tokenname];\n    if (tokenname === \"institution\") {\n        var newtoken = new CSL.Token();\n        // Which, hmm, is the same thing as \"empty\"\n        // Oh, well.\n        //newtoken.strings.prefix = token.prefix;\n        //newtoken.strings.suffix = token.suffix;\n        return newtoken;\n    }\n    return token;\n};\n\n/*global CSL: true */\n\nCSL.NameOutput.prototype.checkCommonAuthor = function(requireMatch) {\n    if (!requireMatch) {\n        return false;\n    }\n    var common_term = false;\n    if (this.variables.length === 2) {\n        var variables = this.variables;\n        var varnames = variables.slice();\n        varnames.sort();\n        common_term = varnames.join(\"\");\n    }\n    if (!common_term) {\n        return false;\n    }\n    var has_term = false;\n    if (this.state.locale[this.state.opt.lang].terms[common_term]) {\n        has_term = true;\n    }\n    if (!has_term) {\n        this.state.tmp.done_vars.push(this.variables[0]);\n        this.state.tmp.done_vars.push(this.variables[1]);\n        return false;\n    }\n    var firstSet = this.Item[this.variables[0]];\n    var secondSet = this.Item[this.variables[1]];\n    var perfectMatch = this._compareNamesets(firstSet, secondSet);\n    if (perfectMatch === true) {\n        this.state.tmp.done_vars.push(this.variables[0]);\n        this.state.tmp.done_vars.push(this.variables[1]);\n    }\n    // This may be counter-intuitive.\n    // This check controls whether we will fail on the this attempt at rendering\n    // and proceed with substitution. If the names match exactly (true), then\n    // we do *not* want to abort and continue with substitution.\n    return !perfectMatch;\n};\n\nCSL.NameOutput.prototype.setCommonTerm = function () {\n    var variables = this.variables;\n    var varnames = variables.slice();\n    varnames.sort();\n    this.common_term = varnames.join(\"\");\n    // When no varnames are on offer\n    if (!this.common_term) {\n        return;\n    }\n    var has_term = false;\n    if (this.label && this.label[this.variables[0]]) {\n        if (this.label[this.variables[0]].before) {\n            has_term = this.state.getTerm(this.common_term, this.label[this.variables[0]].before.strings.form, 0);\n        } else if (this.label[this.variables[0]].after) {\n            has_term = this.state.getTerm(this.common_term, this.label[this.variables[0]].after.strings.form, 0);\n        }\n     }\n\n    // When there is no common term\n    if (!this.state.locale[this.state.opt.lang].terms[this.common_term]\n        || !has_term\n        || this.variables.length < 2) {\n        this.common_term = false;\n        return;\n    }\n    var freeters_offset = 0;\n    for (var i = 0, ilen = this.variables.length - 1; i < ilen; i += 1) {\n        var v = this.variables[i];\n        var vv = this.variables[i + 1];\n        if (this.freeters[v].length || this.freeters[vv].length) {\n            if (this.etal_spec[v].freeters !== this.etal_spec[vv].freeters\n                || !this._compareNamesets(this.freeters[v], this.freeters[vv])) {\n                this.common_term = false;\n                return;\n            }\n            freeters_offset += 1;\n        }\n        if (this.persons[v].length !== this.persons[vv].length) {\n            this.common_term = false;\n            return;\n        }\n        for (var j = 0, jlen = this.persons[v].length; j < jlen; j += 1) {\n            if (this.etal_spec[v].persons[j] !== this.etal_spec[vv].persons[j]\n                || !this._compareNamesets(this.persons[v][j], this.persons[vv][j])) {\n                this.common_term = false;\n                return;\n            }\n        }\n    }\n};\n\nCSL.NameOutput.prototype._compareNamesets = function (base_nameset, nameset) {\n    if (!base_nameset || !nameset || base_nameset.length !== nameset.length) {\n        return false;\n    }\n    for (var i = 0, ilen = nameset.length; i < ilen; i += 1) {\n        for (var j = 0, jlen = CSL.NAME_PARTS.length; j < jlen; j += 1) {\n            var part = CSL.NAME_PARTS[j];\n            if (!base_nameset[i] || base_nameset[i][part] != nameset[i][part]) {\n                return false;\n            }\n        }\n    }\n    return true;\n};\n\n/*global CSL: true */\n\nCSL.NameOutput.prototype.constrainNames = function () {\n    // figure out how many names to include, in light of the disambig params\n    //\n    this.names_count = 0;\n    //var pos = 0;\n    var pos;\n    for (var i = 0, ilen = this.variables.length; i < ilen; i += 1) {\n        var v = this.variables[i];\n        pos = this.nameset_base + i;\n        // Constrain independent authors here\n        if (this.freeters[v].length) {\n            this.state.tmp.names_max.push(this.freeters[v].length, \"literal\");\n            this._imposeNameConstraints(this.freeters, this.freeters_count, v, pos);\n            this.names_count += this.freeters[v].length;\n        }\n\n        // Constrain institutions here\n        if (this.institutions[v].length) {\n            this.state.tmp.names_max.push(this.institutions[v].length, \"literal\");\n            this._imposeNameConstraints(this.institutions, this.institutions_count, v, pos);\n            this.persons[v] = this.persons[v].slice(0, this.institutions[v].length);\n            this.names_count += this.institutions[v].length;\n        }\n\n        for (var j = 0, jlen = this.persons[v].length; j < jlen; j += 1) {\n            // Constrain affiliated authors here\n            if (this.persons[v][j].length) {\n                this.state.tmp.names_max.push(this.persons[v][j].length, \"literal\");\n                this._imposeNameConstraints(this.persons[v], this.persons_count[v], j, pos);\n                this.names_count += this.persons[v][j].length;\n            }\n        }\n    }\n};\n\nCSL.NameOutput.prototype._imposeNameConstraints = function (lst, count, key, pos) {\n    // display_names starts as the original length of this list of names.\n    var display_names = lst[key];\n    var discretionary_names_length = this.state.tmp[\"et-al-min\"];\n    \n    // Mappings, to allow existing disambiguation machinery to\n    // remain untouched.\n    if (this.state.tmp.suppress_decorations) {\n        if (this.state.tmp.disambig_request && this.state.tmp.disambig_request.names[pos]) {\n            // Oh. Trouble.\n            // state.tmp.nameset_counter is the number of the nameset\n            // in the disambiguation try-sequence. Ouch.\n            discretionary_names_length = this.state.tmp.disambig_request.names[pos];\n        } else if (count[key] >= this.etal_min) {\n            discretionary_names_length = this.etal_use_first;\n        }\n    } else {\n        if (this.state.tmp.disambig_request \n            && this.state.tmp.disambig_request.names[pos] > this.etal_use_first) {\n\n            if (count[key] < this.etal_min) {\n                discretionary_names_length = count[key];\n            } else {\n                discretionary_names_length = this.state.tmp.disambig_request.names[pos];\n            }\n        } else if (count[key] >= this.etal_min) {\n            //discretionary_names_length = this.state.tmp[\"et-al-use-first\"];\n            discretionary_names_length = this.etal_use_first;\n        }\n        // XXXX: This is a workaround. Under some conditions.\n        // Where namesets disambiguate on one of the two names\n        // dropped here, it is possible for more than one\n        // in-text citation to be close (and indistinguishable)\n        // matches to a single bibliography entry.\n        //\n        // \n        if (this.etal_use_last && discretionary_names_length > (this.etal_min - 2)) {\n            discretionary_names_length = this.etal_min - 2;\n        }\n    }\n    var sane = this.etal_min >= this.etal_use_first;\n    var overlength = count[key] > discretionary_names_length;\n    // This var is used to control contextual join, and\n    // lies about the number of names when forceEtAl is true,\n    // unless normalized.\n    if (discretionary_names_length > count[key]) {\n\n        // Use actual truncated list length, to avoid overrun.\n        discretionary_names_length = display_names.length;\n    }\n    // forceEtAl is relevant when the author list is\n    // truncated to eliminate clutter.\n    if (sane && overlength) {\n        if (this.etal_use_last) {\n            lst[key] = display_names.slice(0, discretionary_names_length).concat(display_names.slice(-1));\n        } else {\n            lst[key] = display_names.slice(0, discretionary_names_length);\n        }\n    }\n    this.state.tmp.disambig_settings.names[pos] = lst[key].length;\n    this.state.disambiguate.padBase(this.state.tmp.disambig_settings);\n    \n\n    // ???\n    //if (!this.state.tmp.disambig_request) {\n    //    this.state.tmp.disambig_settings.givens[pos] = [];\n    //}\n};\n\n// Disambiguate names (the number of names is controlled externally, by successive\n// runs of the processor).\n\n/*global CSL: true */\n\nCSL.NameOutput.prototype.disambigNames = function () {\n    var pos;\n    for (var i = 0, ilen = this.variables.length; i < ilen; i += 1) {\n        var v = this.variables[i];\n        pos = this.nameset_base + i;\n        if (this.freeters[v].length) {\n            this._runDisambigNames(this.freeters[v], pos);\n        }\n        // Is this even necessary???\n        if (this.institutions[v].length) {\n            if (\"undefined\" === typeof this.state.tmp.disambig_settings.givens[pos]) {\n                this.state.tmp.disambig_settings.givens[pos] = [];\n            }\n            for (var j=0,jlen=this.institutions[v].length;j<jlen;j+=1) {\n                if (\"undefined\" === typeof this.state.tmp.disambig_settings.givens[pos][j]) {\n                    this.state.tmp.disambig_settings.givens[pos].push(2);\n                }\n            }\n        }\n        for (var j = 0, jlen = this.persons[v].length; j < jlen; j += 1) {\n            if (this.persons[v][j].length) {\n                this._runDisambigNames(this.persons[v][j], pos);\n            }\n        }\n    }\n};\n\nCSL.NameOutput.prototype._runDisambigNames = function (lst, pos) {\n    var chk, myform, myinitials, param, i, ilen, paramx;\n    //if (this.state.tmp.root === \"bibliography\") {\n    //    return;\n    //}\n    for (i = 0, ilen = lst.length; i < ilen; i += 1) {\n        //\n        // register the name in the global names disambiguation\n        // registry\n\n        if (!lst[i].given && !lst[i].family) {\n            continue;\n        }\n\n        myinitials = this.state.inheritOpt(this.name, \"initialize-with\");\n        this.state.registry.namereg.addname(\"\" + this.Item.id, lst[i], i);\n        chk = this.state.tmp.disambig_settings.givens[pos];\n        if (\"undefined\" === typeof chk) {\n            // Holes can appear in the list, probably due to institutional\n            // names that this doesn't touch. Maybe. This fills them up.\n            for (var j = 0, jlen = pos + 1; j < jlen; j += 1) {\n                if (!this.state.tmp.disambig_settings.givens[j]) {\n                    this.state.tmp.disambig_settings.givens[j] = [];\n                }\n            }\n        }\n        chk = this.state.tmp.disambig_settings.givens[pos][i];\n        //if (\"undefined\" !== typeof chk && this.state.tmp.root === 'citation') {\n            //this.state.tmp.disambig_settings.givens[pos] = [];\n            //chk = undefined;\n        //}\n        if (\"undefined\" === typeof chk) {\n            myform = this.state.inheritOpt(this.name, \"form\", \"name-form\", \"long\");\n            param = this.state.registry.namereg.evalname(\"\" + this.Item.id, lst[i], i, 0, myform, myinitials);\n            this.state.tmp.disambig_settings.givens[pos].push(param);\n        }\n        //\n        // set the display mode default for givennames if required\n        myform = this.state.inheritOpt(this.name, \"form\", \"name-form\", \"long\");\n        paramx = this.state.registry.namereg.evalname(\"\" + this.Item.id, lst[i], i, 0, myform, myinitials);\n        // this.state.registry.namereg.evalname(\"\" + this.Item.id, lst[i], i, 0, myform, myinitials);\n        if (this.state.tmp.disambig_request) {\n            //\n            // fix a request for initials that makes no sense.\n            // can't do this in disambig, because the availability\n            // of initials is not a global parameter.\n            var val = this.state.tmp.disambig_settings.givens[pos][i];\n            // This is limited to by-cite disambiguation.\n            // 2012-09-13: added lst[i].given check to condition\n            if (val === 1 && \n                this.state.citation.opt[\"givenname-disambiguation-rule\"] === \"by-cite\" && \n                (\"undefined\" === typeof this.state.inheritOpt(this.name, \"initialize-with\")\n                 || \"undefined\" === typeof lst[i].given)) {\n                val = 2;\n            }\n            param = val;\n            // 2012-09-13: lst[i].given check protects against personal names\n            // that have no first name element. These were causing an infinite loop,\n            // this prevents that.\n            if (this.state.opt[\"disambiguate-add-givenname\"] && lst[i].given) {\n                param = this.state.registry.namereg.evalname(\"\" + this.Item.id, lst[i], i, param, this.state.inheritOpt(this.name, \"form\", \"name-form\", \"long\"), this.state.inheritOpt(this.name, \"initialize-with\"));\n            }\n        } else {\n            //\n            // it clicks.  here is where we will put the\n            // call to the names register, to get the floor value\n            // for an individual name.\n            //\n            param = paramx;\n        }\n        // Need to save off the settings based on subsequent\n        // form, when first cites are rendered.\n        if (!this.state.tmp.just_looking && this.item && this.item.position === CSL.POSITION_FIRST) {\n            if (paramx > param) {\n                param = paramx;\n            }\n        }\n        if (!this.state.tmp.sort_key_flag) {\n            this.state.tmp.disambig_settings.givens[pos][i] = param;\n            if (\"string\" === typeof myinitials\n                && (\"undefined\" === typeof this.name.strings[\"initialize\"]\n                    || true === this.name.strings[\"initialize\"])) {\n\n                this.state.tmp.disambig_settings.use_initials = true;\n            }\n        }\n    }\n    //this.state.registry.registry[this.Item.id].disambig.givens = this.state.tmp.disambig_settings.givens.slice();\n};\n\n/*global CSL: true */\n\nCSL.NameOutput.prototype.getEtAlConfig = function () {\n    var item = this.item;\n    this[\"et-al\"] = {};\n\n    this.state.output.append(this.etal_term, this.etal_style, true);\n    this[\"et-al\"].single = this.state.output.pop();\n    this[\"et-al\"].single.strings.suffix = this.etal_suffix;\n    this[\"et-al\"].single.strings.prefix = this.etal_prefix_single;\n    \n    this.state.output.append(this.etal_term, this.etal_style, true);\n    this[\"et-al\"].multiple = this.state.output.pop();\n    this[\"et-al\"].multiple.strings.suffix = this.etal_suffix;\n    this[\"et-al\"].multiple.strings.prefix = this.etal_prefix_multiple;\n\n    // Et-al style parameters (may be sidestepped by disambiguation\n    // in util_names_constraints.js)\n    if (\"undefined\" === typeof item) {\n        item = {};\n    }\n    //print(\"== getEtAlConfig() == \"+this.state.tmp.area);\n\n    if (item.position) {\n        if (this.state.inheritOpt(this.name, \"et-al-subsequent-min\")) {\n            // XX\n            this.etal_min = this.state.inheritOpt(this.name, \"et-al-subsequent-min\");\n        } else {\n            // XX\n            this.etal_min = this.state.inheritOpt(this.name, \"et-al-min\");\n        }\n        if (this.state.inheritOpt(this.name, \"et-al-subsequent-use-first\")) {\n            // XX\n            this.etal_use_first = this.state.inheritOpt(this.name, \"et-al-subsequent-use-first\");\n        } else {\n            // XX\n            this.etal_use_first = this.state.inheritOpt(this.name, \"et-al-use-first\");\n        }\n    } else {\n        if (this.state.tmp[\"et-al-min\"]) {\n            this.etal_min = this.state.tmp[\"et-al-min\"];\n        } else {\n            // XX\n            this.etal_min = this.state.inheritOpt(this.name, \"et-al-min\");\n        }\n        if (this.state.tmp[\"et-al-use-first\"]) {\n            this.etal_use_first = this.state.tmp[\"et-al-use-first\"];\n        } else {\n            // XX\n            this.etal_use_first = this.state.inheritOpt(this.name, \"et-al-use-first\");\n        }\n        if (\"boolean\" === typeof this.state.tmp[\"et-al-use-last\"]) {\n            //print(\"  etal_use_last from tmp: \"+this.state.tmp[\"et-al-use-last\"]);\n            this.etal_use_last = this.state.tmp[\"et-al-use-last\"];\n        } else {\n            //print(\"  etal_use_last from name: \"+this.name.strings[\"et-al-use-last\"]);\n            // XX\n            this.etal_use_last = this.state.inheritOpt(this.name, \"et-al-use-last\");\n        }\n        //print(\"  etal_use_last: \"+this.etal_use_last);\n    }\n    // Provided for use as the starting level for disambiguation.\n    if (!this.state.tmp[\"et-al-min\"]) {\n        this.state.tmp[\"et-al-min\"] = this.etal_min;\n    }\n};\n\n/*global CSL: true */\n\nCSL.NameOutput.prototype.setEtAlParameters = function () {\n    var i, ilen, j, jlen;\n    for (i = 0, ilen = this.variables.length; i < ilen; i += 1) {\n        var v = this.variables[i];\n        if (\"undefined\" === typeof this.etal_spec[v]) {\n            this.etal_spec[v] = {freeters:0,institutions:0,persons:[]};\n        }\n        this.etal_spec[this.nameset_base + i] = this.etal_spec[v];\n        if (this.freeters[v].length) {\n            this._setEtAlParameter(\"freeters\", v);\n        }\n        for (j = 0, jlen = this.persons[v].length; j < jlen; j += 1) {\n            if (\"undefined\" === typeof this.etal_spec[v][j]) {\n                this.etal_spec[v].persons[j] = 0;\n            }\n            this._setEtAlParameter(\"persons\", v, j);\n        }\n        if (this.institutions[v].length) {\n            this._setEtAlParameter(\"institutions\", v);\n        }\n    }\n};\n\nCSL.NameOutput.prototype._setEtAlParameter = function (type, v, j) {\n    var lst, count;\n    if (type === \"persons\") {\n        lst = this.persons[v][j];\n        count = this.persons_count[v][j];\n    } else {\n        lst = this[type][v];\n        count = this[type + \"_count\"][v];\n    }\n    if (lst.length < count && !this.state.tmp.sort_key_flag) {\n        if (this.etal_use_last) {\n            if (type === \"persons\") {\n                this.etal_spec[v].persons[j] = 2;\n            } else {\n                this.etal_spec[v][type] = 2;\n            }\n        } else {\n            if (type === \"persons\") {\n                this.etal_spec[v].persons[j] = 1;\n            } else {\n                this.etal_spec[v][type] = 1;\n            }\n        }\n    } else {\n        if (type === \"persons\") {\n            this.etal_spec[v].persons[j] = 0;\n        } else {\n            this.etal_spec[v][type] = 0;\n        }\n    }\n};\n\n/*global CSL: true */\n\nCSL.NameOutput.prototype.renderAllNames = function () {\n    // Note that et-al/ellipsis parameters are set on the basis\n    // of rendering order through the whole cite.\n    var pos;\n    for (var i = 0, ilen = this.variables.length; i < ilen; i += 1) {\n        var v = this.variables[i];\n\n        if (this.freeters[v].length || this.institutions[v].length) {\n            if (!this.state.tmp.group_context.tip.condition) {\n                this.state.tmp.just_did_number = false;\n            }\n        }\n        \n        pos = this.nameset_base + i;\n        if (this.freeters[v].length) {\n            this.freeters[v] = this._renderNames(v, this.freeters[v], pos);\n        }\n        for (var j = 0, jlen = this.institutions[v].length; j < jlen; j += 1) {\n            this.persons[v][j] = this._renderNames(v, this.persons[v][j], pos, j);\n        }\n    }\n    this.renderInstitutionNames();\n};\n\nCSL.NameOutput.prototype.renderInstitutionNames = function () {\n    // Institutions are split to string list as\n    // this.institutions[v][\"long\"] and this.institutions[v][\"short\"]\n    for (var i = 0, ilen = this.variables.length; i < ilen; i += 1) {\n        var v = this.variables[i];\n        for (var j = 0, jlen = this.institutions[v].length; j < jlen; j += 1) {\n            var institution;\n\n            var name = this.institutions[v][j];\n\n            \n\n            // XXX Start here for institutions\n            // Figure out the three segments: primary, secondary, tertiary\n            var j, jlen, localesets;\n            if (this.state.tmp.extension) {\n                localesets = [\"sort\"];\n            } else if (name.isInstitution || name.literal) {\n                // Will never hit this in this function, but preserving\n                // in case we factor this out.\n                localesets = this.state.opt['cite-lang-prefs'].institutions;\n            } else {\n                localesets = this.state.opt['cite-lang-prefs'].persons;\n            }\n\n            var slot = {primary:'locale-orig',secondary:false,tertiary:false};\n\t        if (localesets) {\n\t\t        var slotnames = [\"primary\", \"secondary\", \"tertiary\"];\n\t\t        for (var k = 0, klen = slotnames.length; k < klen; k += 1) {\n\t\t\t        if (localesets.length - 1 <  k) {\n\t\t\t\t        break;\n\t\t\t        }\n                    if (localesets[k]) {\n\t\t\t            slot[slotnames[k]] = 'locale-' + localesets[k];\n                    }\n\t\t        }\n\t        } else {\n\t\t        slot.primary = 'locale-translat';\n\t        }\n\t        if (this.state.tmp.area !== \"bibliography\"\n\t\t        && !(this.state.tmp.area === \"citation\"\n\t\t\t         && this.state.opt.xclass === \"note\"\n\t\t\t         && this.item && !this.item.position)) {\n                \n\t\t        slot.secondary = false;\n\t\t        slot.tertiary = false;\n\t        }\n            // Get normalized name object for a start.\n            // true invokes fallback\n            this.setRenderedName(name);\n\n            // XXXX FROM HERE (instututions)\n            var institution = this._renderInstitutionName(v, name, slot, j);\n\n            //this.institutions[v][j] = this._join(institution, \"\");\n            this.institutions[v][j] = institution;\n        }\n    }\n};\n\nCSL.NameOutput.prototype._renderInstitutionName = function (v, name, slot, j) {\n    var secondary, tertiary, long_style, short_style, institution, institution_short, institution_long;\n    var res = this.getName(name, slot.primary, true);\n    var primary = res.name;\n    var usedOrig = res.usedOrig;\n    if (primary) {\n        //print(\"primary, v, j = \"+primary+\", \"+v+\", \"+j);\n        primary = this.fixupInstitution(primary, v, j);\n    }\n\tsecondary = false;\n\tif (slot.secondary) {\n        res = this.getName(name, slot.secondary, false, usedOrig);\n        var secondary = res.name;\n        usedOrig = res.usedOrig;\n        if (secondary) {\n\t\t\tsecondary = this.fixupInstitution(secondary, v, j);\n        }\n\t}\n    //Zotero.debug(\"XXX [2] secondary: \"+secondary[\"long\"].literal+\", slot.secondary: \"+slot.secondary);\n\ttertiary = false;\n\tif (slot.tertiary) {\n        res = this.getName(name, slot.tertiary, false, usedOrig);\n        tertiary = res.name;\n        if (tertiary) {\n\t\t\ttertiary = this.fixupInstitution(tertiary, v, j);\n        }\n\t}\n    var n = {\n        l: {\n            pri: false,\n            sec: false,\n            ter: false\n        },\n        s: {\n            pri: false,\n            sec: false,\n            ter: false\n        }\n    };\n    if (primary) {\n        n.l.pri = primary[\"long\"];\n        n.s.pri = primary[\"short\"].length ? primary[\"short\"] : primary[\"long\"];\n    }\n    if (secondary) {\n        n.l.sec = secondary[\"long\"];\n        n.s.sec = secondary[\"short\"].length ? secondary[\"short\"] : secondary[\"long\"];\n    }\n    if (tertiary) {\n        n.l.ter = tertiary[\"long\"];\n        n.s.ter = tertiary[\"short\"].length ? tertiary[\"short\"] : tertiary[\"long\"];\n    }\n    switch (this.institution.strings[\"institution-parts\"]) {\n    case \"short\":\n        // No multilingual for pure short form institution names.\n        if (primary[\"short\"].length) {\n            short_style = this._getShortStyle();\n            institution = [this._composeOneInstitutionPart([n.s.pri, n.s.sec, n.s.ter], slot, short_style, v)];\n        } else {\n            // Fail over to long.\n            long_style = this._getLongStyle(primary, v, j);\n            institution = [this._composeOneInstitutionPart([n.l.pri, n.l.sec, n.l.ter], slot, long_style, v)];\n        }\n        break;\n    case \"short-long\":\n        long_style = this._getLongStyle(primary, v, j);\n        short_style = this._getShortStyle();\n        institution_short = this._renderOneInstitutionPart(primary[\"short\"], short_style);\n        // true is to include multilingual supplement\n        institution_long = this._composeOneInstitutionPart([n.l.pri, n.l.sec, n.l.ter], slot, long_style, v);\n        institution = [institution_short, institution_long];\n        break;\n    case \"long-short\":\n        long_style = this._getLongStyle(primary, v, j);\n        short_style = this._getShortStyle();\n        institution_short = this._renderOneInstitutionPart(primary[\"short\"], short_style);\n        // true is to include multilingual supplement\n        institution_long = this._composeOneInstitutionPart([n.l.pri, n.l.sec, n.l.ter], slot, long_style, v);\n        institution = [institution_long, institution_short];\n        break;\n    default:\n        long_style = this._getLongStyle(primary, v, j);\n        // true is to include multilingual supplement\n        institution = [this._composeOneInstitutionPart([n.l.pri, n.l.sec, n.l.ter], slot, long_style, v)];\n        break;\n    }\n    var blob = this._join(institution, \" \");\n    if (blob) {\n        blob.isInstitution = true;\n    }\n    this.state.tmp.name_node.children.push(blob);\n    return blob;\n};\n\nCSL.NameOutput.prototype._composeOneInstitutionPart = function (names, slot, style) {\n    var primary = false, secondary = false, tertiary = false, primary_tok, secondary_tok, tertiary_tok;\n    if (names[0]) {\n        primary_tok = CSL.Util.cloneToken(style);\n        if (this.state.opt.citeAffixes[slot.primary]){\n            if (\"<i>\" === this.state.opt.citeAffixes.institutions[slot.primary].prefix) {\n                var hasItalic = false;\n                for (var i = 0, ilen = primary_tok.decorations.length; i < ilen; i += 1) {\n                    if (style.decorations[i][0] === \"@font-style\"\n                        && primary_tok.decorations[i][1] === \"italic\") {\n                        hasItalic = true;\n                    }\n                }\n                if (!hasItalic) {\n                    primary_tok.decorations.push([\"@font-style\", \"italic\"]);\n                }\n            }\n        }\n        primary = this._renderOneInstitutionPart(names[0], primary_tok);\n     }\n    if (names[1]) {\n        secondary = this._renderOneInstitutionPart(names[1], style);\n    }\n    if (names[2]) {\n        tertiary = this._renderOneInstitutionPart(names[2], style);\n    }\n    // Compose\n    var institutionblob;\n    if (secondary || tertiary) {\n        this.state.output.openLevel(\"empty\");\n\n        this.state.output.append(primary);\n\n        secondary_tok = CSL.Util.cloneToken(style);\n        if (slot.secondary) {\n            secondary_tok.strings.prefix = this.state.opt.citeAffixes.institutions[slot.secondary].prefix;\n            secondary_tok.strings.suffix = this.state.opt.citeAffixes.institutions[slot.secondary].suffix;\n            // Add a space if empty\n            if (!secondary_tok.strings.prefix) {\n                secondary_tok.strings.prefix = \" \";\n            }\n        }\n        var secondary_outer = new CSL.Token();\n        secondary_outer.decorations.push([\"@font-style\", \"normal\"]);\n        secondary_outer.decorations.push([\"@font-weight\", \"normal\"]);\n        this.state.output.openLevel(secondary_outer);\n        this.state.output.append(secondary, secondary_tok);\n        this.state.output.closeLevel();\n\n        tertiary_tok = CSL.Util.cloneToken(style);\n        if (slot.tertiary) {\n            tertiary_tok.strings.prefix = this.state.opt.citeAffixes.institutions[slot.tertiary].prefix;\n            tertiary_tok.strings.suffix = this.state.opt.citeAffixes.institutions[slot.tertiary].suffix;\n            // Add a space if empty\n            if (!tertiary_tok.strings.prefix) {\n                tertiary_tok.strings.prefix = \" \";\n            }\n        }\n        var tertiary_outer = new CSL.Token();\n        tertiary_outer.decorations.push([\"@font-style\", \"normal\"]);\n        tertiary_outer.decorations.push([\"@font-weight\", \"normal\"]);\n        this.state.output.openLevel(tertiary_outer);\n        this.state.output.append(tertiary, tertiary_tok);\n        this.state.output.closeLevel();\n\n        this.state.output.closeLevel();\n\n        institutionblob = this.state.output.pop();\n    } else {\n        institutionblob = primary;\n    }\n    return institutionblob;\n};\n\nCSL.NameOutput.prototype._renderOneInstitutionPart = function (blobs, style) {\n    for (var i = 0, ilen = blobs.length; i < ilen; i += 1) {\n        if (blobs[i]) {\n            var str = blobs[i];\n            // XXXXX Cut-and-paste code in multiple locations. This code block should be\n            // collected in a function.\n            // Tag: strip-periods-block\n            if (this.state.tmp.strip_periods) {\n                str = str.replace(/\\./g, \"\");\n            } else {\n                for (var j = 0, jlen = style.decorations.length; j < jlen; j += 1) {\n                    if (\"@strip-periods\" === style.decorations[j][0] && \"true\" === style.decorations[j][1]) {\n                        str = str.replace(/\\./g, \"\");\n                        break;\n                    }\n                }\n            }\n            //this.state.output.append(blobs[i], style, true);\n            this.state.tmp.group_context.tip.variable_success = true;\n            this.state.tmp.can_substitute.replace(false, CSL.LITERAL);\n            if (str === \"!here>>>\") {\n                blobs[i] = false;\n            } else {\n                this.state.output.append(str, style, true);\n                blobs[i] = this.state.output.pop();\n            }\n        }\n    }\n    if (\"undefined\" === typeof this.institution.strings[\"part-separator\"]) {\n        this.institution.strings[\"part-separator\"] = this.state.tmp.name_delimiter;\n    }\n    return this._join(blobs, this.institution.strings[\"part-separator\"]);\n};\n\nCSL.NameOutput.prototype._renderNames = function (v, values, pos, j) {\n    //\n    var ret = false;\n    if (values.length) {\n        var names = [];\n        for (var i = 0, ilen = values.length; i < ilen; i += 1) {\n            var name = values[i];\n            \n            // XXX We'll start here with attempts.\n            // Figure out the three segments: primary, secondary, tertiary\n            var ret, localesets;\n            \n            if (this.state.tmp.extension) {\n                localesets = [\"sort\"];\n            } else if (name.isInstitution || name.literal) {\n                // Will never hit this in this function, but preserving\n                // in case we factor this out.\n                localesets = this.state.opt['cite-lang-prefs'].institutions;\n            } else {\n                localesets = this.state.opt['cite-lang-prefs'].persons;\n            }\n            var slot = {primary:'locale-orig',secondary:false,tertiary:false};\n\t        if (localesets) {\n\t\t        var slotnames = [\"primary\", \"secondary\", \"tertiary\"];\n\t\t        for (var k = 0, klen = slotnames.length; k < klen; k += 1) {\n\t\t\t        if (localesets.length - 1 <  k) {\n\t\t\t\t        break;\n\t\t\t        }\n\t\t\t        slot[slotnames[k]] = 'locale-' + localesets[k];\n\t\t        }\n\t        } else {\n\t\t        slot.primary = 'locale-translat';\n\t        }\n\t        if (this.state.tmp.sort_key_flag || (this.state.tmp.area !== \"bibliography\"\n\t\t        && !(this.state.tmp.area === \"citation\"\n\t\t\t         && this.state.opt.xclass === \"note\"\n\t\t\t         && this.item && !this.item.position))) {\n                \n\t\t        slot.secondary = false;\n\t\t        slot.tertiary = false;\n\t        }\n\n            // primary\n            // true is for fallback\n            this.setRenderedName(name);\n\n            if (!name.literal && !name.isInstitution) {\n                var nameBlob = this._renderPersonalName(v, name, slot, pos, i, j);\n                var nameToken = CSL.Util.cloneToken(this.name);\n                this.state.output.append(nameBlob, nameToken, true);\n                names.push(this.state.output.pop());\n            } else {\n                names.push(this._renderInstitutionName(v, name, slot, j));\n            }\n        }\n        //ret = this._join(names, \"\");\n        ret = this.joinPersons(names, pos, j);\n    }\n    return ret;\n};\n\n\nCSL.NameOutput.prototype._renderPersonalName = function (v, name, slot, pos, i, j) {\n    // XXXX FROM HERE (persons)\n\n    var res = this.getName(name, slot.primary, true);\n    var primary = this._renderOnePersonalName(res.name, pos, i, j);\n\tvar secondary = false;\n\tif (slot.secondary) {\n        res = this.getName(name, slot.secondary, false, res.usedOrig);\n        if (res.name) {\n\t\t\tsecondary = this._renderOnePersonalName(res.name, pos, i, j);\n        }\n\t}\n\tvar tertiary = false;\n\tif (slot.tertiary) {\n        res = this.getName(name, slot.tertiary, false, res.usedOrig);\n        if (res.name) {\n\t\t\ttertiary = this._renderOnePersonalName(res.name, pos, i, j);\n        }\n\t}\n    // Now compose them to a unit\n    var personblob;\n    if (secondary || tertiary) {\n\n        this.state.output.openLevel(\"empty\");\n\n        this.state.output.append(primary);\n\n        var secondary_tok = new CSL.Token();\n        if (slot.secondary) {\n            secondary_tok.strings.prefix = this.state.opt.citeAffixes.persons[slot.secondary].prefix;\n            secondary_tok.strings.suffix = this.state.opt.citeAffixes.persons[slot.secondary].suffix;\n            // Add a space if empty\n            if (!secondary_tok.strings.prefix) {\n                secondary_tok.strings.prefix = \" \";\n            }\n        }\n        this.state.output.append(secondary, secondary_tok);\n\n        var tertiary_tok = new CSL.Token();\n        if (slot.tertiary) {\n            tertiary_tok.strings.prefix = this.state.opt.citeAffixes.persons[slot.tertiary].prefix;\n            tertiary_tok.strings.suffix = this.state.opt.citeAffixes.persons[slot.tertiary].suffix;\n            // Add a space if empty\n            if (!tertiary_tok.strings.prefix) {\n                tertiary_tok.strings.prefix = \" \";\n            }\n        }\n        this.state.output.append(tertiary, tertiary_tok);\n\n        this.state.output.closeLevel();\n\n        personblob = this.state.output.pop();\n    } else {\n        personblob = primary;\n    }\n    return personblob;\n};\n\nCSL.NameOutput.prototype._isRomanesque = function (name) {\n    // 0 = entirely non-romanesque\n    // 1 = mixed content\n    // 2 = pure romanesque\n    var ret = 2;\n    if (!name.family.replace(/\\\"/g, '').match(CSL.ROMANESQUE_REGEXP)) {\n        ret = 0;\n    }\n    if (!ret && name.given && name.given.match(CSL.STARTSWITH_ROMANESQUE_REGEXP)) {\n        ret = 1;\n    }\n    var top_locale;\n    if (ret == 2) {\n        if (name.multi && name.multi.main) {\n            top_locale = name.multi.main.slice(0, 2);\n        } else if (this.Item.language) {\n            top_locale = this.Item.language.slice(0, 2);\n        }\n        if ([\"ja\", \"zh\"].indexOf(top_locale) > -1) {\n            ret = 1;\n        }\n    }\n    //print(\"name: \"+name.given+\", multi: \"+name.multi+\", ret: \"+ret);\n    return ret;\n};\n\nCSL.NameOutput.prototype._renderOnePersonalName = function (value, pos, i, j) {\n    var name = value;\n    var dropping_particle = this._droppingParticle(name, pos, j);\n    var family = this._familyName(name);\n    var non_dropping_particle = this._nonDroppingParticle(name);\n    var givenInfo = this._givenName(name, pos, i);\n    var given = givenInfo.blob;\n    var suffix = this._nameSuffix(name);\n    if (given === false) {\n        dropping_particle = false;\n        suffix = false;\n    }\n    var sort_sep = this.state.inheritOpt(this.name, \"sort-separator\");\n    if (!sort_sep) {\n        sort_sep = \"\";\n    }\n    var suffix_sep;\n    if (name[\"comma-suffix\"]) {\n        suffix_sep = \", \";\n    } else {\n        suffix_sep = \" \";\n    }\n    var romanesque = this._isRomanesque(name);\n    function hasJoiningPunctuation(blob) {\n        if (!blob) {\n            return false;\n        } else if (\"string\" === typeof blob.blobs) {\n            if ([\"\\u2019\", \"\\'\", \"-\", \" \"].indexOf(blob.blobs.slice(-1)) > -1) {\n                return true;\n            } else {\n                return false;\n            }\n        } else {\n            return hasJoiningPunctuation(blob.blobs[blob.blobs.length-1]);\n        }\n    }\n    \n    var has_hyphenated_non_dropping_particle = hasJoiningPunctuation(non_dropping_particle);\n\n    var nbspace;\n    if ([\"fr\", \"ru\", \"cs\"].indexOf(this.state.opt[\"default-locale\"][0].slice(0, 2)) > -1) {\n        nbspace = \"\\u00a0\";\n    } else {\n        nbspace = \" \";\n    }\n\n    var blob, merged, first, second;\n    if (romanesque === 0) {\n        // XXX handle affixes for given and family\n        blob = this._join([non_dropping_particle, family, given], \"\");\n    } else if (romanesque === 1 || name[\"static-ordering\"]) { // entry likes sort order\n        merged = this._join([non_dropping_particle, family], nbspace);\n        blob = this._join([merged, given], \" \");\n    } else if (name[\"reverse-ordering\"]) { // entry likes reverse order\n        merged = this._join([non_dropping_particle, family], nbspace);\n        blob = this._join([given, merged], \" \");\n    } else if (this.state.tmp.sort_key_flag) {\n        // ok with no affixes here\n        if (this.state.opt[\"demote-non-dropping-particle\"] === \"never\") {\n            merged = this._join([non_dropping_particle, family], nbspace);\n            merged = this._join([merged, dropping_particle], \" \");\n            merged = this._join([merged, given], this.state.opt.sort_sep);\n            blob = this._join([merged, suffix], \" \");\n        } else {\n            second = this._join([given, dropping_particle, non_dropping_particle], \" \");\n            merged = this._join([family, second], this.state.opt.sort_sep);\n            blob = this._join([merged, suffix], \" \");\n        }\n    } else if (this.state.inheritOpt(this.name, \"name-as-sort-order\") === \"all\" || (this.state.inheritOpt(this.name, \"name-as-sort-order\") === \"first\" && i === 0 && (j === 0 || \"undefined\" === typeof j))) {\n        //\n        // Discretionary sort ordering and inversions\n        //\n        if ([\"Lord\", \"Lady\"].indexOf(name.given) > -1) {\n            sort_sep = \", \";\n        }\n\n        // XXX Needs a more robust solution than this\n        // XXX See https://forums.zotero.org/discussion/30974/any-idea-why-an-a-author-comes-last-in-the-bibliography/#Item_30\n\n        //if ([\"always\", \"display-and-sort\"].indexOf(this.state.opt[\"demote-non-dropping-particle\"]) > -1 && !has_hyphenated_non_dropping_particle) {\n        if ([\"always\", \"display-and-sort\"].indexOf(this.state.opt[\"demote-non-dropping-particle\"]) > -1) {\n            // Drop non-dropping particle\n            //second = this._join([given, dropping_particle, non_dropping_particle], \" \");\n            second = this._join([given, dropping_particle], (name[\"comma-dropping-particle\"] + \" \"));\n        \n            // This would be a problem with al-Ghazali. Avoided by has_hyphenated_non_dropping_particle check above.\n            second = this._join([second, non_dropping_particle], \" \");\n            if (second && this.given) {\n                second.strings.prefix = this.given.strings.prefix;\n                second.strings.suffix = this.given.strings.suffix;\n            }\n            if (family && this.family) {\n                family.strings.prefix = this.family.strings.prefix;\n                family.strings.suffix = this.family.strings.suffix;\n            }\n            merged = this._join([family, second], sort_sep);\n            blob = this._join([merged, suffix], sort_sep);\n        } else {\n            // Don't drop particle.\n            // Don't do this\n            //if (this.state.tmp.area === \"bibliography\" && !this.state.tmp.term_predecessor && non_dropping_particle) {\n            //    if (!has_hyphenated_non_dropping_particle) {\n            //        non_dropping_particle.blobs = CSL.Output.Formatters[\"capitalize-first\"](this.state, non_dropping_particle.blobs)\n            //    }\n            //}\n            if (has_hyphenated_non_dropping_particle) {\n                first = this._join([non_dropping_particle, family], \"\");\n            } else {\n                first = this._join([non_dropping_particle, family], nbspace);\n            }\n            if (first && this.family) {\n                first.strings.prefix = this.family.strings.prefix;\n                first.strings.suffix = this.family.strings.suffix;\n            }\n\n            second = this._join([given, dropping_particle], (name[\"comma-dropping-particle\"] + \" \"));\n            //second = this._join([given, dropping_particle], \" \");\n            if (second && this.given) {\n                second.strings.prefix = this.given.strings.prefix;\n                second.strings.suffix = this.given.strings.suffix;\n            }\n\n            merged = this._join([first, second], sort_sep);\n            blob = this._join([merged, suffix], sort_sep);\n        }\n        blob.isInverted = true;\n    } else { // plain vanilla\n        if (name[\"dropping-particle\"] && name.family && !name[\"non-dropping-particle\"]) {\n            var dp = name[\"dropping-particle\"];\n            var apostrophes = [\"'\",\"\\u02bc\",\"\\u2019\",\"-\"];\n            if (apostrophes.indexOf(dp.slice(-1)) > -1 && dp.slice(0, -1) !== \"de\") {\n                family = this._join([dropping_particle, family], \"\");\n                dropping_particle = false;\n            }\n        }\n\n        if (has_hyphenated_non_dropping_particle) {\n            second = this._join([non_dropping_particle, family], \"\");\n            second = this._join([dropping_particle, second], nbspace);\n        } else {\n            second = this._join([dropping_particle, non_dropping_particle, family], nbspace);\n        }\n        second = this._join([second, suffix], suffix_sep);\n        if (second && this.family) {\n            second.strings.prefix = this.family.strings.prefix;\n            second.strings.suffix = this.family.strings.suffix;\n        }\n        if (given && this.given) {\n            given.strings.prefix = this.given.strings.prefix;\n            given.strings.suffix = this.given.strings.suffix;\n        }\n        if (second.strings.prefix) {\n            name[\"comma-dropping-particle\"] = \"\";\n        }\n\n        var space;\n        if (this.state.inheritOpt(this.name, \"initialize-with\")\n            && this.state.inheritOpt(this.name, \"initialize-with\").match(/[\\u00a0\\ufeff]/)\n            && givenInfo.initializationLevel === 1) {\n            \n            space = nbspace;\n        } else {\n            space = \" \";\n        }\n        blob = this._join([given, second], (name[\"comma-dropping-particle\"] + space));\n    }\n    // XXX Just generally assume for the present that personal names render something\n    this.state.tmp.group_context.tip.variable_success = true;\n    this.state.tmp.can_substitute.replace(false, CSL.LITERAL);\n    this.state.tmp.term_predecessor = true;\n    // notSerious\n    //this.state.output.append(blob, \"literal\", true);\n    //var ret = this.state.output.pop();\n    this.state.tmp.name_node.children.push(blob);\n    return blob;\n};\n\n/*\n        // Do not include given name, dropping particle or suffix in strict short form of name\n\n        // initialize if appropriate\n*/\n\n// Input names should be touched by _normalizeNameInput()\n// exactly once: this is not idempotent.\nCSL.NameOutput.prototype._normalizeNameInput = function (value) {\n    var name = {\n        literal:value.literal,\n        family:value.family,\n        isInstitution:value.isInstitution,\n        given:value.given,\n        suffix:value.suffix,\n        \"comma-suffix\":value[\"comma-suffix\"],\n        \"non-dropping-particle\":value[\"non-dropping-particle\"],\n        \"dropping-particle\":value[\"dropping-particle\"],\n        \"static-ordering\":value[\"static-ordering\"],\n        \"static-particles\":value[\"static-particles\"],\n        \"reverse-ordering\":value[\"reverse-ordering\"],\n        \"full-form-always\": value[\"full-form-always\"],\n        \"parse-names\":value[\"parse-names\"],\n        \"comma-dropping-particle\": \"\",\n        block_initialize:value.block_initialize,\n        multi:value.multi\n    };\n    this._parseName(name);\n    return name;\n};\n\n// _transformNameset() replaced with enhanced transform.name().\n\nCSL.NameOutput.prototype._stripPeriods = function (tokname, str) {\n    var decor_tok = this[tokname + \"_decor\"];\n    if (str) {\n        if (this.state.tmp.strip_periods) {\n            str = str.replace(/\\./g, \"\");\n        } else  if (decor_tok) {\n            for (var i = 0, ilen = decor_tok.decorations.length; i < ilen; i += 1) {\n                if (\"@strip-periods\" === decor_tok.decorations[i][0] && \"true\" === decor_tok.decorations[i][1]) {\n                    str = str.replace(/\\./g, \"\");\n                    break;\n                }\n            }\n        }\n    }\n    return str;\n};\n\nCSL.NameOutput.prototype._nonDroppingParticle = function (name) {\n    var ndp = name[\"non-dropping-particle\"];\n    if (ndp && this.state.tmp.sort_key_flag) {\n        ndp = ndp.replace(/[\\'\\u2019]/, \"\");\n    }\n    var str = this._stripPeriods(\"family\", ndp);\n    if (this.state.output.append(str, this.family_decor, true)) {\n        return this.state.output.pop();\n    }\n    return false;\n};\n\nCSL.NameOutput.prototype._droppingParticle = function (name, pos, j) {\n    var dp = name[\"dropping-particle\"];\n    if (dp && this.state.tmp.sort_key_flag) {\n        dp = dp.replace(/[\\'\\u2019]/, \"\");\n    }\n    var str = this._stripPeriods(\"given\", dp);\n    if (name[\"dropping-particle\"] && name[\"dropping-particle\"].match(/^et.?al[^a-z]$/)) {\n        if (this.state.inheritOpt(this.name, \"et-al-use-last\")) {\n            if (\"undefined\" === typeof j) { \n                this.etal_spec[pos].freeters = 2;\n            } else {\n                this.etal_spec[pos].persons = 2;\n            }\n        } else {\n            if (\"undefined\" === typeof j) { \n                this.etal_spec[pos].freeters = 1;\n            } else {\n                this.etal_spec[pos].persons = 1;\n            }\n        }\n        name[\"comma-dropping-particle\"] = \"\";\n    } else if (this.state.output.append(str, this.given_decor, true)) {\n        return this.state.output.pop();\n    }\n    return false;\n};\n\nCSL.NameOutput.prototype._familyName = function (name) {\n    var str = this._stripPeriods(\"family\", name.family);\n    if (this.state.output.append(str, this.family_decor, true)) {\n        return this.state.output.pop();\n    }\n    return false;\n};\n\nCSL.NameOutput.prototype._givenName = function (name, pos, i) {\n    var ret;\n    // citation\n    //   use disambig as-is\n    // biblography\n    //   use disambig only if it boosts over the default\n    //   SO WHAT IS THE DEFAULT?\n    //   A: If \"form\" is short, it's 0.\n    //      If \"form\" is long, initialize-with exists (and initialize is not false) it's 1\n    //      If \"form\" is long, and initialize_with does not exist, it's 2.\n    var formIsShort = this.state.inheritOpt(this.name, \"form\", \"name-form\", \"long\") !== \"long\";\n    var initializeIsTurnedOn = this.state.inheritOpt(this.name, \"initialize\") !== false;\n    var hasInitializeWith = \"string\" === typeof this.state.inheritOpt(this.name, \"initialize-with\") && !name.block_initialize;\n    var defaultLevel;\n    var useLevel;\n    if (name[\"full-form-always\"]) {\n        useLevel = 2;\n    } else {\n        if (formIsShort) {\n            defaultLevel = 0;\n        } else if (hasInitializeWith) {\n            defaultLevel = 1;\n        } else {\n            defaultLevel = 2;\n        }\n        var requestedLevel = this.state.tmp.disambig_settings.givens[pos][i];\n        if (requestedLevel > defaultLevel) {\n            useLevel = requestedLevel;\n        } else {\n            useLevel = defaultLevel;\n        }\n    }\n    var gdropt = this.state.citation.opt[\"givenname-disambiguation-rule\"];\n   if (gdropt && gdropt.slice(-14) === \"-with-initials\") {\n        hasInitializeWith = true;\n    }\n    if (name.family && useLevel === 1) {\n        if (hasInitializeWith) {\n            var initialize_with = this.state.inheritOpt(this.name, \"initialize-with\", false, \"\");\n            name.given = CSL.Util.Names.initializeWith(this.state, name.given, initialize_with, !initializeIsTurnedOn);\n        } else {\n            name.given = CSL.Util.Names.unInitialize(this.state, name.given);\n        }\n    } else if (useLevel === 0) {\n        return {\n            blob: false\n        }\n    } else if (useLevel === 2) {\n        name.given = CSL.Util.Names.unInitialize(this.state, name.given);\n    }\n\n    var str = this._stripPeriods(\"given\", name.given);\n    var rendered = this.state.output.append(str, this.given_decor, true);\n    if (rendered) {\n        ret = this.state.output.pop();\n\t    return {\n            blob: ret,\n            initializationLevel: useLevel\n        };\n    }\n    return {\n        blob: false\n    };\n};\n\nCSL.NameOutput.prototype._nameSuffix = function (name) {\n\n    var str = name.suffix, ret;\n\n    if (str && \"string\" === typeof this.state.inheritOpt(this.name, \"initialize-with\")) {\n        str = CSL.Util.Names.initializeWith(this.state, str, this.state.inheritOpt(this.name, \"initialize-with\"), true);\n    }\n\n    str = this._stripPeriods(\"family\", str);\n    var toSuffix = '';\n    if (str && str.slice(-1) === '.') {\n\tstr = str.slice(0, -1);\n\ttoSuffix = '.';\n    }\n    var rendered = this.state.output.append(str, \"empty\", true);\n    if (rendered) {\n        ret = this.state.output.pop();\n\tret.strings.suffix = toSuffix + ret.strings.suffix;\n\treturn ret;\n    }\n    return false;\n};\n\nCSL.NameOutput.prototype._getLongStyle = function (name) {\n    var long_style;\n    if (name[\"short\"].length) {\n        if (this.institutionpart[\"long-with-short\"]) {\n            long_style = this.institutionpart[\"long-with-short\"];\n        } else {\n            long_style = this.institutionpart[\"long\"];\n        }\n    } else {\n        long_style = this.institutionpart[\"long\"];\n    }\n    if (!long_style) {\n        long_style = new CSL.Token();\n    }\n    return long_style;\n};\n\nCSL.NameOutput.prototype._getShortStyle = function () {\n    var short_style;\n    if (this.institutionpart[\"short\"]) {\n        short_style = this.institutionpart[\"short\"];\n    } else {\n        short_style = new CSL.Token();\n    }\n    return short_style;\n};\n\nCSL.NameOutput.prototype._parseName = function (name) {\n    if (!name[\"parse-names\"] && \"undefined\" !== typeof name[\"parse-names\"]) {\n        return name;\n    }\n    if (name.family && !name.given && name.isInstitution) {\n        name.literal = name.family;\n        name.family = undefined;\n        name.isInstitution = undefined;\n    }\n    var noparse;\n    if (name.family \n        && (name.family.slice(0, 1) === '\"' && name.family.slice(-1) === '\"')\n        || (!name[\"parse-names\"] && \"undefined\" !== typeof name[\"parse-names\"])) {\n\n        name.family = name.family.slice(1, -1);\n        noparse = true;\n        name[\"parse-names\"] = 0;\n    } else {\n        noparse = false;\n    }\n    if (this.state.opt.development_extensions.parse_names) {\n        if (!name[\"non-dropping-particle\"] && name.family && !noparse && name.given) {\n            if (!name[\"static-particles\"]) {\n                CSL.parseParticles(name, true);\n            }\n        }\n    }\n};\n\n/*\n * Return a single name object\n  */\n\n// The interface is a mess, but this should serve.\n\nCSL.NameOutput.prototype.getName = function (name, slotLocaleset, fallback, stopOrig) {\n\n    // Needs to tell us whether we used orig or not.\n    \n    if (stopOrig && slotLocaleset === 'locale-orig') {\n        return {name:false,usedOrig:stopOrig};\n    }\n\n    // Normalize to string\n    if (!name.family) {\n        name.family = \"\";\n    }\n    if (!name.given) {\n        name.given = \"\";\n    }\n\n    // Recognized params are:\n    //  block-initialize\n    //  transliterated\n    //  static-ordering\n    //  full-form-always\n    // All default to false, except for static-ordering, which is initialized\n    // with a sniff.\n    var name_params = {};\n    // Determines the default static-order setting based on the characters\n    // used in the headline field. Will be overridden by locale-based\n    // parameters evaluated against explicit lang tags set on the (sub)field.\n    name_params[\"static-ordering\"] = this.getStaticOrder(name);\n\n    var foundTag = true;\n    var langTag;\n    if (slotLocaleset !== 'locale-orig') {\n        foundTag = false;\n        if (name.multi) {\n            var langTags = this.state.opt[slotLocaleset];\n            for (var i = 0, ilen = langTags.length; i < ilen; i += 1) {\n                langTag = langTags[i];\n                if (name.multi._key[langTag]) {\n                    foundTag = true;\n                    var isInstitution = name.isInstitution;\n                    name = name.multi._key[langTag];\n                    name.isInstitution = isInstitution;\n                    // Set name formatting params\n                    name_params = this.getNameParams(langTag);\n                    name_params.transliterated = true;\n                    break;\n                }\n            }\n        }\n    }\n\n    if (!foundTag) {\n        langTag = false;\n        if (name.multi && name.multi.main) {\n            langTag = name.multi.main;\n        } else if (this.Item.language) {\n            langTag = this.Item.language;\n        }\n        if (langTag) {\n            name_params = this.getNameParams(langTag);\n        }\n    }\n\n    if (!fallback && !foundTag) {\n        return {name:false,usedOrig:stopOrig};\n    }\n    \n    // Normalize to string (again)\n    if (!name.family) {\n        name.family = \"\";\n    }\n    if (!name.given) {\n        name.given = \"\";\n    }\n    if (name.literal) {\n        delete name.family;\n        delete name.given;\n    }\n    // var clone the item before writing into it\n    name = {\n        family:name.family,\n        given:name.given,\n        \"non-dropping-particle\":name[\"non-dropping-particle\"],\n        \"dropping-particle\":name[\"dropping-particle\"],\n        suffix:name.suffix,\n        \"static-ordering\":name_params[\"static-ordering\"],\n        \"static-particles\":name[\"static-particles\"],\n        \"reverse-ordering\":name_params[\"reverse-ordering\"],\n        \"full-form-always\": name_params[\"full-form-always\"],\n        \"parse-names\":name[\"parse-names\"],\n        \"comma-suffix\":name[\"comma-suffix\"],\n        \"comma-dropping-particle\":name[\"comma-dropping-particle\"],\n        transliterated: name_params.transliterated,\n        block_initialize: name_params[\"block-initialize\"],\n        literal:name.literal,\n        isInstitution:name.isInstitution,\n        multi:name.multi\n    };\n    \n    if (!name.literal && (!name.given && name.family && name.isInstitution)) {\n        name.literal = name.family;\n    }\n    if (name.literal) {\n        delete name.family;\n        delete name.given;\n    }\n    name = this._normalizeNameInput(name);\n    var usedOrig;\n    if (stopOrig) {\n        usedOrig = stopOrig;\n    } else {\n        usedOrig = !foundTag;\n    }\n    return {name:name,usedOrig:usedOrig};\n};\n\nCSL.NameOutput.prototype.getNameParams = function (langTag) {\n    var ret = {};\n    var langspec = CSL.localeResolve(this.Item.language, this.state.opt[\"default-locale\"][0]);\n    var try_locale = this.state.locale[langspec.best] ? langspec.best : this.state.opt[\"default-locale\"][0];\n    var name_as_sort_order = this.state.locale[try_locale].opts[\"name-as-sort-order\"];\n    var name_as_reverse_order = this.state.locale[try_locale].opts[\"name-as-reverse-order\"];\n    var name_never_short = this.state.locale[try_locale].opts[\"name-never-short\"];\n    var field_lang_bare = langTag.split(\"-\")[0];\n    if (name_as_sort_order && name_as_sort_order[field_lang_bare]) {\n        ret[\"static-ordering\"] = true;\n        ret[\"reverse-ordering\"] = false;\n    }\n    if (name_as_reverse_order && name_as_reverse_order[field_lang_bare]) {\n        ret[\"reverse-ordering\"] = true;\n        ret[\"static-ordering\"] = false;\n    }\n    if (name_never_short && name_never_short[field_lang_bare]) {\n        ret[\"full-form-always\"] = true;\n    }\n    \n    if (ret[\"static-ordering\"]) {\n        ret[\"block-initialize\"] = true;\n    }\n    return ret;\n};\n\nCSL.NameOutput.prototype.setRenderedName = function (name) {\n    if (this.state.tmp.area === \"bibliography\") {\n        var strname = \"\";\n        for (var j=0,jlen=CSL.NAME_PARTS.length;j<jlen;j+=1) {\n            if (name[CSL.NAME_PARTS[j]]) {\n                strname += name[CSL.NAME_PARTS[j]];\n            }\n        }\n        this.state.tmp.rendered_name.push(strname);\n    }\n};\n\nCSL.NameOutput.prototype.fixupInstitution = function (name, varname, listpos) {\n    if (!name.literal && name.family) {\n        name.literal = name.family;\n        delete name.family;\n    }\n    var longNameStr = name.literal;\n    var shortNameStr = longNameStr;\n    var ret = {\n        \"long\": longNameStr.split(/\\s*\\|\\s*/),\n        \"short\": shortNameStr.split(/\\s*\\|\\s*/),\n    };\n    if (this.state.sys.getAbbreviation) {\n        // Normalize longNameStr and shortNameStr\n        if (this.institution.strings.form === \"short\") {\n            let jurisdiction = this.Item.jurisdiction;\n            jurisdiction = this.state.transform.loadAbbreviation(jurisdiction, \"institution-entire\", longNameStr, this.Item.language);\n            if (this.state.transform.abbrevs[jurisdiction][\"institution-entire\"][longNameStr]) {\n                longNameStr = this.state.transform.abbrevs[jurisdiction][\"institution-entire\"][longNameStr];\n            } else {\n                jurisdiction = this.Item.jurisdiction;\n                jurisdiction = this.state.transform.loadAbbreviation(jurisdiction, \"institution-part\", longNameStr, this.Item.language);\n                if (this.state.transform.abbrevs[jurisdiction][\"institution-part\"][longNameStr]) {\n                    longNameStr = this.state.transform.abbrevs[jurisdiction][\"institution-part\"][longNameStr];\n                }\n            }\n            longNameStr = this._quashChecks(jurisdiction, longNameStr);\n        }\n        if ([\"short\", \"short-long\", \"long-short\"].indexOf(this.institution.strings[\"institution-parts\"]) > -1) {\n            let jurisdiction = this.Item.jurisdiction;\n            jurisdiction = this.state.transform.loadAbbreviation(jurisdiction, \"institution-part\", shortNameStr, this.Item.language);\n            if (this.state.transform.abbrevs[jurisdiction][\"institution-part\"][shortNameStr]) {\n                shortNameStr = this.state.transform.abbrevs[jurisdiction][\"institution-part\"][shortNameStr];\n            }\n            shortNameStr = this._quashChecks(jurisdiction, shortNameStr);\n            if ([\"short-long\", \"long-short\"].indexOf(this.institution.strings[\"institution-parts\"]) > -1) {\n                if (shortNameStr === longNameStr) {\n                    shortNameStr = \"\";\n                }\n            }\n        }\n        // Split abbreviated strings\n        // For pure long, split and we're done.\n        ret[\"long\"] = longNameStr.split(/\\s*\\|\\s*/);\n        // For short, split and then try abbrev with institution-part on each element\n        ret[\"short\"] = shortNameStr.split(/\\s*\\|\\s*/);\n        if ([\"short\", \"short-long\", \"long-short\"].indexOf(this.institution.strings[\"institution-parts\"]) > -1) {\n            for (var j=ret[\"short\"].length-1; j>-1; j--) {\n                let jurisdiction = this.Item.jurisdiction;\n                var abbrevKey = ret[\"short\"][j];\n                jurisdiction = this.state.transform.loadAbbreviation(jurisdiction, \"institution-part\", abbrevKey, this.Item.language);\n                if (this.state.transform.abbrevs[jurisdiction][\"institution-part\"][abbrevKey]) {\n                    ret[\"short\"][j] = this.state.transform.abbrevs[jurisdiction][\"institution-part\"][abbrevKey];\n                }\n                if (ret[\"short\"][j].indexOf(\"|\") > -1) {\n                    let retShort = ret[\"short\"];\n                    let splitShort = retShort[j].split(/\\s*\\|\\s*/);\n                    ret[\"short\"] = retShort.slice(0, j).concat(splitShort).concat(retShort.slice(j+1));\n                }\n            }\n        }\n        if (this.state.opt.development_extensions.legacy_institution_name_ordering) {\n            ret[\"short\"].reverse();\n        }\n        ret[\"short\"] = this._trimInstitution(ret[\"short\"]);\n        if (this.institution.strings[\"reverse-order\"]) {\n            ret[\"short\"].reverse();\n        }\n        // trimmer is not available in getAmbiguousCite\n        if (!this.state.tmp.just_looking) {\n            if (this.Item.jurisdiction) {\n                let jurisdiction = this.Item.jurisdiction;\n                var trimmer = this.state.tmp.abbrev_trimmer;\n                if (trimmer && trimmer[jurisdiction] && trimmer[jurisdiction][varname]) {\n                    for (var i=0,ilen=ret[\"short\"].length;i<ilen;i++) {\n                        var frag = ret[\"short\"][i];\n                        ret[\"short\"][i] = frag.replace(trimmer[jurisdiction][varname], \"\").trim();\n                    }\n                }\n            }\n        }\n    }\n    if (this.state.opt.development_extensions.legacy_institution_name_ordering) {\n        ret[\"long\"].reverse();\n    }\n    ret[\"long\"] = this._trimInstitution(ret[\"long\"]);\n    if (this.institution.strings[\"reverse-order\"]) {\n        ret[\"long\"].reverse();\n    }\n\n    return ret;\n};\n\n\nCSL.NameOutput.prototype.getStaticOrder = function (name, refresh) {\n    var static_ordering_val = false;\n    if (!refresh && name[\"static-ordering\"]) {\n        static_ordering_val = true;\n    } else if (this._isRomanesque(name) === 0) {\n        static_ordering_val = true;\n    } else if ((!name.multi || !name.multi.main) && this.Item.language && ['vi', 'hu'].indexOf(this.Item.language) > -1) {\n        static_ordering_val = true;\n    } else if (name.multi && name.multi.main && ['vi', 'hu'].indexOf(name.multi.main.slice(0,2)) > -1) {\n        static_ordering_val = true;\n    } else {\n        if (this.state.opt['auto-vietnamese-names']\n            && (CSL.VIETNAMESE_NAMES.exec(name.family + \" \" + name.given)\n                && CSL.VIETNAMESE_SPECIALS.exec(name.family + name.given))) {\n            \n            static_ordering_val = true;\n        }\n    }\n    return static_ordering_val;\n};\n\nCSL.NameOutput.prototype._quashChecks = function (jurisdiction, str) {\n    var str = this.state.transform.quashCheck(jurisdiction, str);\n    // If the abbreviation has date cut-offs, find the most recent\n    // abbreviation within scope.\n    var lst = str.split(/>>[0-9]{4}>>/);\n    var m = str.match(/>>([0-9]{4})>>/);\n    str = lst.pop();\n    var date = this.Item[\"original-date\"] ? this.Item[\"original-date\"] : this.Item[\"issued\"];\n    if (date) {\n        date = parseInt(date.year, 10);\n        date = isNaN(date) ? false : date;\n    }\n    if (date) {\n        if (lst.length > 0) {\n            for (var k=m.length-1; k>0; k--) {\n                if (date >= parseInt(m[k], 10)) {\n                    break;\n                }\n                str = lst.pop();\n            }\n        }\n        str = str.replace(/\\s*\\|\\s*/g, \"|\");\n    }\n    return str;\n}\n\nCSL.NameOutput.prototype._trimInstitution = function (subunits) {\n\t// Oh! Good catch in the tests. This happens before abbrevs.\n    // Won't work that way. Need to do abbrev substitute first,\n    // and apply this separately to long and to short.\n    var use_first = false;\n    var stop_last = false;\n    var use_last = false;\n    var stop_first = false;\n    var s = subunits.slice();\n    if (this.institution) {\n        // If use_first, apply stop_last, then apply use_first;\n        // If use_last, apply stop_first, then apply use_last;\n        if (\"undefined\" !== typeof this.institution.strings[\"use-first\"]) {\n            // this.state.sys.print(\"use-first OK\");\n            use_first = this.institution.strings[\"use-first\"];\n        }\n        if (\"undefined\" !== typeof this.institution.strings[\"use-last\"]) {\n            // this.state.sys.print(\"use-last OK\");\n            use_last = this.institution.strings[\"use-last\"];\n        }\n        if (\"undefined\" !== typeof this.institution.strings[\"stop-first\"]) {\n            // this.state.sys.print(\"stop-first OK\");\n            stop_first = this.institution.strings[\"stop-first\"];\n        }\n        if (\"undefined\" !== typeof this.institution.strings[\"stop-last\"]) {\n            stop_last = this.institution.strings[\"stop-last\"];\n        }\n\n        if (use_first) {\n            if (stop_last) {\n                s = s.slice(0, stop_last * -1);\n            }\n            s = s.slice(0, use_first);\n        }\n        \n        if (use_last) {\n            var ss = subunits.slice();\n            if (use_first) {\n                stop_first = use_first;\n            } else {\n                s = [];\n            }\n            if (stop_first) {\n                ss = ss.slice(stop_first);\n            }\n            ss = ss.slice(use_last * -1);\n            s = s.concat(ss);\n        }\n        subunits = s;\n    }\n    return subunits;\n};\n\n/*global CSL: true */\n\nCSL.PublisherOutput = function (state, group_tok) {\n    this.state = state;\n    this.group_tok = group_tok;\n    this.varlist = [];\n};\n\nCSL.PublisherOutput.prototype.render = function () {\n    this.clearVars();\n    this.composeAndBlob();\n    this.composeElements();\n    this.composePublishers();\n    this.joinPublishers();\n};\n\n\n// XXX Figure out how to adapt this to the House of Lords / House of Commons\n// joint committee case\n\n// name_delimiter\n// delimiter_precedes_last\n// and\n\nCSL.PublisherOutput.prototype.composeAndBlob = function () {\n    this.and_blob = {};\n    var and_term = false;\n    if (this.group_tok.strings.and === \"text\") {\n        and_term = this.state.getTerm(\"and\");\n    } else if (this.group_tok.strings.and === \"symbol\") {\n        and_term = \"&\";\n    }\n    var tok = new CSL.Token();\n    tok.strings.suffix = \" \";\n    tok.strings.prefix = \" \";\n    this.state.output.append(and_term, tok, true);\n    var no_delim = this.state.output.pop();\n\n    tok.strings.prefix = this.group_tok.strings[\"subgroup-delimiter\"];\n    this.state.output.append(and_term, tok, true);\n    var with_delim = this.state.output.pop();\n    \n    this.and_blob.single = false;\n    this.and_blob.multiple = false;\n    if (and_term) {\n        if (this.group_tok.strings[\"subgroup-delimiter-precedes-last\"] === \"always\") {\n            this.and_blob.single = with_delim;\n        } else if (this.group_tok.strings[\"subgroup-delimiter-precedes-last\"] === \"never\") {\n            this.and_blob.single = no_delim;\n            this.and_blob.multiple = no_delim;\n        } else {\n            this.and_blob.single = no_delim;\n            this.and_blob.multiple = with_delim;\n        }\n    }\n};\n\n\nCSL.PublisherOutput.prototype.composeElements = function () {\n    for (var i = 0, ilen = 2; i < ilen; i += 1) {\n        var varname = [\"publisher\", \"publisher-place\"][i];\n        for (var j = 0, jlen = this[\"publisher-list\"].length; j < jlen; j += 1) {\n            var str = this[varname + \"-list\"][j];\n            var tok = this[varname + \"-token\"];\n            // notSerious\n            this.state.output.append(str, tok, true);\n            this[varname + \"-list\"][j] = this.state.output.pop();\n        }\n    }\n};\n\n\nCSL.PublisherOutput.prototype.composePublishers = function () {\n    var blobs;\n    for (var i = 0, ilen = this[\"publisher-list\"].length; i < ilen; i += 1) {\n        blobs = [this[this.varlist[0] + \"-list\"][i], this[this.varlist[1] + \"-list\"][i]];\n        this[\"publisher-list\"][i] = this._join(blobs, this.group_tok.strings.delimiter);\n    }\n};\n\n\nCSL.PublisherOutput.prototype.joinPublishers = function () {\n    var blobs = this[\"publisher-list\"];\n    var publishers = this._join(blobs, this.group_tok.strings[\"subgroup-delimiter\"], this.and_blob.single, this.and_blob.multiple, this.group_tok);\n    this.state.output.append(publishers, \"literal\");\n};\n\n\n// blobs, delimiter, single, multiple, tokenname\n// Tokenname is a key at top level of this object.\nCSL.PublisherOutput.prototype._join = CSL.NameOutput.prototype._join;\nCSL.PublisherOutput.prototype._getToken = CSL.NameOutput.prototype._getToken;\n\n\nCSL.PublisherOutput.prototype.clearVars = function () {\n    this.state.tmp[\"publisher-list\"] = false;\n    this.state.tmp[\"publisher-place-list\"] = false;\n    this.state.tmp[\"publisher-group-token\"] = false;\n    this.state.tmp[\"publisher-token\"] = false;\n    this.state.tmp[\"publisher-place-token\"] = false;\n};\n\n/*global CSL: true */\n\nCSL.evaluateLabel = function (node, state, Item, item) {\n    var myterm;\n    if (\"locator\" === node.strings.term) {\n        if (item && item.label) {\n            if (item.label === \"sub verbo\") {\n                myterm = \"sub-verbo\";\n            } else {\n                myterm = item.label;\n            }\n        }\n        if (!myterm) {\n            myterm = \"page\";\n        }\n    } else {\n        myterm = node.strings.term;\n    }\n    \n    // Plurals detection.\n    var plural = node.strings.plural;\n    if (\"number\" !== typeof plural) {\n        // (node, ItemObject, variable, type)\n        var theItem = (item && node.strings.term === \"locator\") ? item : Item;\n        if (theItem[node.strings.term]) {\n            state.processNumber(false, theItem, node.strings.term, Item.type);\n            plural = state.tmp.shadow_numbers[node.strings.term].plural;\n            if (!state.tmp.shadow_numbers[node.strings.term].labelForm\n                && !state.tmp.shadow_numbers[node.strings.term].labelDecorations) {\n                if (node.strings.form) {\n                    state.tmp.shadow_numbers[node.strings.term].labelForm = node.strings.form;\n                } else if (state.tmp.group_context.tip.label_form) {\n                    state.tmp.shadow_numbers[node.strings.term].labelForm = state.tmp.group_context.tip.label_form;\n                }\n                state.tmp.shadow_numbers[node.strings.term].labelCapitalizeIfFirst = node.strings.capitalize_if_first;\n                state.tmp.shadow_numbers[node.strings.term].labelDecorations = node.decorations.slice();\n            }\n            \n            if ([\"locator\", \"number\", \"page\"].indexOf(node.strings.term) > -1 && state.tmp.shadow_numbers[node.strings.term].label) {\n                myterm = state.tmp.shadow_numbers[node.strings.term].label;\n            }\n            if (node.decorations && state.opt.development_extensions.csl_reverse_lookup_support) {\n                node.decorations.reverse();\n                node.decorations.push([\"@showid\",\"true\", node.cslid]);\n                node.decorations.reverse();\n            }\n        }\n    }\n    return CSL.castLabel(state, node, myterm, plural, CSL.TOLERANT);\n};\n\nCSL.castLabel = function (state, node, term, plural, mode) {\n    var label_form = node.strings.form;\n    var label_capitalize_if_first = node.strings.capitalize_if_first;\n    if (state.tmp.group_context.tip.label_form) {\n        if (label_form === \"static\") {\n            state.tmp.group_context.tip.label_static = true;\n        } else {\n            label_form = state.tmp.group_context.tip.label_form;\n        }\n    }\n\n    if (state.tmp.group_context.tip.label_capitalize_if_first) {\n        label_capitalize_if_first = state.tmp.group_context.tip.label_capitalize_if_first;\n    }\n    var ret = state.getTerm(term, label_form, plural, false, mode, node.default_locale);\n    if (label_capitalize_if_first) {\n        ret = CSL.Output.Formatters[\"capitalize-first\"](state, ret);\n    }\n    // XXXXX Cut-and-paste code in multiple locations. This code block should be\n    // collected in a function.\n    // Tag: strip-periods-block\n    if (state.tmp.strip_periods) {\n        ret = ret.replace(/\\./g, \"\");\n    } else {\n        for (var i = 0, ilen = node.decorations.length; i < ilen; i += 1) {\n            if (\"@strip-periods\" === node.decorations[i][0] && \"true\" === node.decorations[i][1]) {\n                ret = ret.replace(/\\./g, \"\");\n                break;\n            }\n        }\n    }\n    return ret;\n};\n\n/*global CSL: true */\n\nCSL.Node.name = {\n    build: function (state, target) {\n        var func;\n        if ([CSL.SINGLETON, CSL.START].indexOf(this.tokentype) > -1) {\n            var oldTmpRoot;\n            if (\"undefined\" === typeof state.tmp.root) {\n                oldTmpRoot = undefined;\n                state.tmp.root = \"citation\";\n            } else {\n                oldTmpRoot = state.tmp.root;\n            }\n            // Many CSL styles set et-al-[min|use-first]\n            // and et-al-subsequent-[min|use-first] to the same\n            // value.\n            // Set state.opt.update_mode = CSL.POSITION if\n            // et-al-subsequent-min or et-al-subsequent-use-first\n            // are set AND their value differs from their plain\n            // counterparts.\n            if (state.inheritOpt(this, \"et-al-subsequent-min\")\n                && (state.inheritOpt(this, \"et-al-subsequent-min\") !== state.inheritOpt(this, \"et-al-min\"))) {\n                \n                state.opt.update_mode = CSL.POSITION;\n            }\n            if (state.inheritOpt(this, \"et-al-subsequent-use-first\")\n                && (state.inheritOpt(this, \"et-al-subsequent-use-first\") !== state.inheritOpt(this, \"et-al-use-first\"))) {\n                \n                state.opt.update_mode = CSL.POSITION;\n            }\n\n            state.tmp.root = oldTmpRoot;\n\n            func = function (state) {\n                // Et-al (onward processing in node_etal.js and node_names.js)\n                // XXXXX Why is this necessary? This is available on this.name, right?\n                state.tmp.etal_term = \"et-al\";\n\n                // Use default delimiter as fallback, in a way that allows explicit\n                // empty strings.\n                state.tmp.name_delimiter = state.inheritOpt(this, \"delimiter\", \"name-delimiter\", \", \");\n                state.tmp[\"delimiter-precedes-et-al\"] = state.inheritOpt(this, \"delimiter-precedes-et-al\");\n                \n                // And\n                if (\"text\" === state.inheritOpt(this, \"and\")) {\n                    this.and_term = state.getTerm(\"and\", \"long\", 0);\n                } else if (\"symbol\" === state.inheritOpt(this, \"and\")) {\n                    if (state.opt.development_extensions.expect_and_symbol_form) {\n                        this.and_term = state.getTerm(\"and\", \"symbol\", 0);\n                    } else {\n                        this.and_term = \"&\";\n                    }\n                }\n                state.tmp.and_term = this.and_term;\n                if (CSL.STARTSWITH_ROMANESQUE_REGEXP.test(this.and_term)) {\n                    this.and_prefix_single = \" \";\n                    this.and_prefix_multiple = \", \";\n                    // Workaround to allow explicit empty string\n                    // on cs:name delimiter.\n                    if (\"string\" === typeof state.tmp.name_delimiter) {\n                        this.and_prefix_multiple = state.tmp.name_delimiter;\n                    }\n                    this.and_suffix = \" \";\n\n                    // Really can't inspect these values in the build phase. Sorry.\n                    //state.build.name_delimiter = this.strings.delimiter;\n\n                } else {\n                    this.and_prefix_single = \"\";\n                    this.and_prefix_multiple = \"\";\n                    this.and_suffix = \"\";\n                }\n                if (state.inheritOpt(this, \"delimiter-precedes-last\") === \"always\") {\n                    this.and_prefix_single = state.tmp.name_delimiter;\n                } else if (state.inheritOpt(this, \"delimiter-precedes-last\") === \"never\") {\n                    // Slightly fragile: could test for charset here to make\n                    // this more certain.\n                    if (this.and_prefix_multiple) {\n                        this.and_prefix_multiple = \" \";\n                    }\n                } else if (state.inheritOpt(this, \"delimiter-precedes-last\") === \"after-inverted-name\") {\n                    if (this.and_prefix_single) {\n                        this.and_prefix_single = state.tmp.name_delimiter;\n                    }\n                    if (this.and_prefix_multiple) {\n                        this.and_prefix_multiple = \" \";\n                    }\n                }\n\n                this.and = {};\n                if (state.inheritOpt(this, \"and\")) {\n                    state.output.append(this.and_term, \"empty\", true);\n                    this.and.single = state.output.pop();\n                    this.and.single.strings.prefix = this.and_prefix_single;\n                    this.and.single.strings.suffix = this.and_suffix;\n                    state.output.append(this.and_term, \"empty\", true);\n                    this.and.multiple = state.output.pop();\n                    this.and.multiple.strings.prefix = this.and_prefix_multiple;\n                    this.and.multiple.strings.suffix = this.and_suffix;\n                } else if (state.tmp.name_delimiter) {\n                    // This is a little weird, but it works.\n                    this.and.single = new CSL.Blob(state.tmp.name_delimiter);\n                    this.and.single.strings.prefix = \"\";\n                    this.and.single.strings.suffix = \"\";\n                    this.and.multiple = new CSL.Blob(state.tmp.name_delimiter);\n                    this.and.multiple.strings.prefix = \"\";\n                    this.and.multiple.strings.suffix = \"\";\n                }\n\n                this.ellipsis = {};\n                if (state.inheritOpt(this, \"et-al-use-last\")) {\n                    // We use the dedicated Unicode ellipsis character because\n                    // it is recommended by some editors, and can be more easily\n                    // identified for find and replace operations.\n                    // Source: http://en.wikipedia.org/wiki/Ellipsis#Computer_representations\n                    //\n                    \n                    // Eventually, this should be localized as a term in CSL, with some\n                    // mechanism for triggering appropriate punctuation handling around\n                    // the ellipsis placeholder (Polish is a particularly tough case for that).\n                    this.ellipsis_term = \"\\u2026\";\n                    // Similar treatment to \"and\", above, will be needed\n                    // here when this becomes a locale term.\n                    this.ellipsis_prefix_single = \" \";\n                    this.ellipsis_prefix_multiple =  state.inheritOpt(this, \"delimiter\", \"name-delimiter\", \", \");\n                    this.ellipsis_suffix = \" \";\n                    this.ellipsis.single = new CSL.Blob(this.ellipsis_term);\n                    this.ellipsis.single.strings.prefix = this.ellipsis_prefix_single;\n                    this.ellipsis.single.strings.suffix = this.ellipsis_suffix;\n                    this.ellipsis.multiple = new CSL.Blob(this.ellipsis_term);\n                    this.ellipsis.multiple.strings.prefix = this.ellipsis_prefix_multiple;\n                    this.ellipsis.multiple.strings.suffix = this.ellipsis_suffix;\n                }\n\n                // et-al parameters are annoyingly incomprehensible\n                // again.\n                //\n                // Explanation probably just adds a further layer of\n                // irritation, but what's INTENDED here is that\n                // the state.tmp et-al variables are set from the\n                // cs:key element when composing sort keys, and a\n                // macro containing a name can be called from cs:key.\n                // So when cs:key sets et-al attributes, they are\n                // set on state.tmp, and when the key is finished\n                // processing, the state.tmp variables are reset to\n                // undefined. IN THEORY the state.tmp et-al variables\n                // will not be used in other contexts. I hope.\n                //\n                // Anyway, the current tests now seem to pass.\n                if (\"undefined\" === typeof state.tmp[\"et-al-min\"]) {\n                    state.tmp[\"et-al-min\"] = state.inheritOpt(this, \"et-al-min\");\n                }\n                if (\"undefined\" === typeof state.tmp[\"et-al-use-first\"]) {\n                    state.tmp[\"et-al-use-first\"] = state.inheritOpt(this, \"et-al-use-first\");\n                }\n                if (\"undefined\" === typeof state.tmp[\"et-al-use-last\"]) {\n                    //print(\"  setting et-al-use-last from name: \"+this.strings[\"et-al-use-last\"]);\n                    state.tmp[\"et-al-use-last\"] = state.inheritOpt(this, \"et-al-use-last\");\n                }\n\n                state.nameOutput.name = this;\n            };\n            \n            state.build.name_flag = true;\n\n            this.execs.push(func);\n        }\n        target.push(this);\n    }\n};\n\n\n\n/*global CSL: true */\n\nCSL.Node[\"name-part\"] = {\n    build: function (state) {\n        state.build[this.strings.name] = this;\n    }\n};\n\n/*global CSL: true */\n\nCSL.Node.names = {\n    build: function (state, target) {\n        var func;\n        // CSL.debug = print;\n\n        if (this.tokentype === CSL.START || this.tokentype === CSL.SINGLETON) {\n            CSL.Util.substituteStart.call(this, state, target);\n            state.build.substitute_level.push(1);\n        }\n        \n        if (this.tokentype === CSL.SINGLETON) {\n            state.build.names_variables[state.build.names_variables.length-1].concat(this.variables);\n            for (var i in this.variables) {\n                var variable = this.variables[i];\n                var name_labels = state.build.name_label[state.build.name_label.length-1];\n                if (Object.keys(name_labels).length) {\n                    name_labels[variable] = name_labels[Object.keys(name_labels)[0]];\n                }\n            }\n            func = function (state) {\n                state.nameOutput.reinit(this, this.variables_real[0]);\n            };\n            this.execs.push(func);\n        }\n\n        if (this.tokentype === CSL.START) {\n\n            state.build.names_flag = true;\n            state.build.name_flag = false;\n            state.build.names_level += 1;\n            state.build.names_variables.push(this.variables);\n            state.build.name_label.push({});\n            // init can substitute\n            // init names\n            func = function (state) {\n                state.tmp.can_substitute.push(true);\n                state.tmp.name_node = {};\n                state.tmp.name_node.children = [];\n                state.nameOutput.init(this);\n            };\n            this.execs.push(func);\n\n        }\n        \n        if (this.tokentype === CSL.END) {\n\n            // Set/reset name blobs if they exist, for processing\n            // by namesOutput()\n            for (var i = 0, ilen = 3; i < ilen; i += 1) {\n                var key = [\"family\", \"given\", \"et-al\"][i];\n                this[key] = state.build[key];\n                if (state.build.names_level === 1) {\n                    state.build[key] = undefined;\n                }\n            }\n            // Labels, if any\n            this.label = state.build.name_label[state.build.name_label.length-1];\n            state.build.names_level += -1;\n            state.build.names_variables.pop();\n            state.build.name_label.pop();\n\n            // The with term. This isn't the right place\n            // for this, but it's all hard-wired at the\n            // moment.\n\n            // \"and\" and \"ellipsis\" are set in node_name.js\n            func = function (state) {\n                // Et-al (strings only)\n                // Blob production has to happen inside nameOutput()\n                // since proper escaping requires access to the output\n                // queue.\n                if (state.tmp.etal_node) {\n                    this.etal_style = state.tmp.etal_node;\n                } else {\n                    this.etal_style = \"empty\";\n                }\n\n                this.etal_term = state.getTerm(state.tmp.etal_term, \"long\", 0);\n                this.etal_prefix_single = \" \";\n                // Should be name delimiter, not hard-wired.\n                this.etal_prefix_multiple = state.tmp.name_delimiter;\n                if (state.tmp[\"delimiter-precedes-et-al\"] === \"always\") {\n                    this.etal_prefix_single = state.tmp.name_delimiter;\n                } else if (state.tmp[\"delimiter-precedes-et-al\"] === \"never\") {\n                    this.etal_prefix_multiple = \" \";\n                } else if (state.tmp[\"delimiter-precedes-et-al\"] === \"after-inverted-name\") {\n                    this.etal_prefix_single = state.tmp.name_delimiter;\n                    this.etal_prefix_multiple = \" \";\n                }\n                this.etal_suffix = \"\";\n                if (!CSL.STARTSWITH_ROMANESQUE_REGEXP.test(this.etal_term)) {\n                    // Not sure what the correct treatment is here, but we should not suppress\n                    // a comma-space.\n                    // https://forums.zotero.org/discussion/76679/delimiter-precedes-et-al-always-dose-not-work-in-locale-zh-cn\n                    if (this.etal_prefix_single === \" \") {\n                        this.etal_prefix_single = \"\";\n                    }\n                    if (this.etal_prefix_multiple === \" \") {\n                        this.etal_prefix_multiple = \"\";\n                    }\n                    if (this.etal_suffix === \" \") {\n                        this.etal_suffix = \"\";\n                    }\n                }\n                // et-al affixes are further adjusted in nameOutput(),\n                // after the term (possibly changed in cs:et-al) is known.\n\n\n                for (var i = 0, ilen = 3; i < ilen; i += 1) {\n                    var key = [\"family\", \"given\"][i];\n                    state.nameOutput[key] = this[key];\n                }\n                state.nameOutput[\"with\"] = this[\"with\"];\n\n                // REMOVE THIS\n                var mywith = \"with\";\n                var with_default_prefix = \"\";\n                var with_suffix = \"\";\n                if (CSL.STARTSWITH_ROMANESQUE_REGEXP.test(mywith)) {\n                    with_default_prefix = \" \";\n                    with_suffix = \" \";\n                }\n                var thewith = {};\n                thewith.single = new CSL.Blob(mywith);\n                thewith.single.strings.suffix = with_suffix;\n                thewith.multiple = new CSL.Blob(mywith);\n                thewith.multiple.strings.suffix = with_suffix;\n                if (state.inheritOpt(state.nameOutput.name, \"delimiter-precedes-last\") === \"always\") {\n                    thewith.single.strings.prefix = state.inheritOpt(this, \"delimiter\", \"names-delimiter\");\n                    thewith.multiple.strings.prefix = state.inheritOpt(this, \"delimiter\", \"names-delimiter\");\n                } else if (state.inheritOpt(state.nameOutput.name, \"delimiter-precedes-last\") === \"contextual\") {\n                    thewith.single.strings.prefix = with_default_prefix;\n                    thewith.multiple.strings.prefix = state.inheritOpt(this, \"delimiter\", \"names-delimiter\");\n                } else if (state.inheritOpt(state.nameOutput.name, \"delimiter-precedes-last\") === \"after-inverted-name\") {\n                    thewith.single.strings.prefix = state.inheritOpt(this, \"delimiter\", \"names-delimiter\");\n                    thewith.multiple.strings.prefix = with_default_prefix;\n                } else {\n                    thewith.single.strings.prefix = with_default_prefix;\n                    thewith.multiple.strings.prefix = with_default_prefix;\n                }\n                state.nameOutput[\"with\"] = thewith;\n\n\n                // XXX label style should be set per variable, since they may differ\n                // XXX with full-form nested names constructs\n                state.nameOutput.label = this.label;\n\n                state.nameOutput.etal_style = this.etal_style;\n                state.nameOutput.etal_term = this.etal_term;\n                state.nameOutput.etal_prefix_single = this.etal_prefix_single;\n                state.nameOutput.etal_prefix_multiple = this.etal_prefix_multiple;\n                state.nameOutput.etal_suffix = this.etal_suffix;\n                state.nameOutput.outputNames();\n                state.tmp[\"et-al-use-first\"] = undefined;\n                state.tmp[\"et-al-min\"] = undefined;\n                state.tmp[\"et-al-use-last\"] = undefined;\n            };\n            this.execs.push(func);\n\n            // unsets\n            func = function (state) {\n                if (!state.tmp.can_substitute.pop()) {\n                    state.tmp.can_substitute.replace(false, CSL.LITERAL);\n                }\n                \n                // For posterity ...\n                //\n                // This was enough to fix the issue reported here:\n                //\n                //   http://forums.zotero.org/discussion/25223/citeproc-bug-substitute-doesnt-work-correctly-for-title-macro/\n                //\n                // The remainder of the changes applied in the same patch\n                // relate to a label assignments, which were found to be\n                // buggy while working on the issue. The test covering\n                // both problems is here:\n                //\n                //   https://bitbucket.org/bdarcus/citeproc-test/src/ab136a6aa8f2/processor-tests/humans/substitute_SuppressOrdinaryVariable.txt\n                if (state.tmp.can_substitute.mystack.length === 1) {\n                    state.tmp.can_block_substitute = false;\n                }\n            };\n            this.execs.push(func);\n\n            state.build.name_flag = false;\n        }\n        target.push(this);\n\n        if (this.tokentype === CSL.END || this.tokentype === CSL.SINGLETON) {\n            state.build.substitute_level.pop();\n            CSL.Util.substituteEnd.call(this, state, target);\n        }\n    }\n};\n\n/*global CSL: true */\n\nCSL.Node.number = {\n    build: function (state, target) {\n        var func;\n        CSL.Util.substituteStart.call(this, state, target);\n        //\n        // This should push a rangeable object to the queue.\n        //\n        if (this.strings.form === \"roman\") {\n            this.formatter = state.fun.romanizer;\n        } else if (this.strings.form === \"ordinal\") {\n            this.formatter = state.fun.ordinalizer;\n        } else if (this.strings.form === \"long-ordinal\") {\n            this.formatter = state.fun.long_ordinalizer;\n        }\n        if (\"undefined\" === typeof this.successor_prefix) {\n            this.successor_prefix = state[state.build.area].opt.layout_delimiter;\n        }\n        if (\"undefined\" === typeof this.splice_prefix) {\n            this.splice_prefix = state[state.build.area].opt.layout_delimiter;\n        }\n        // is this needed?\n        //if (\"undefined\" === typeof this.splice_prefix){\n        //    this.splice_prefix = state[state.tmp.area].opt.layout_delimiter;\n        //}\n        //\n        // Whether we actually stick a number object on\n        // the output queue depends on whether the field\n        // contains a pure number.\n        //\n        // push number or text\n        func = function (state, Item, item) {\n            // NOTE: this works because this is the ONLY function in this node.\n            // If further functions are added, they need to start with the same\n            // abort condition.\n            if (this.variables.length === 0) {\n                return;\n            }\n            var varname;\n            varname = this.variables[0];\n            if (\"undefined\" === typeof item) {\n                var item = {};\n            }\n            if ([\"locator\", \"locator-extra\"].indexOf(varname) > -1) {\n                if (state.tmp.just_looking) {\n                    return;\n                }\n                if (!item[varname]) {\n                    return;\n                }\n            } else {\n                if (!Item[varname]) {\n                    return;\n                }\n            }\n\n            if (varname === 'collection-number' && Item.type === 'legal_case') {\n                state.tmp.renders_collection_number = true;\n            }\n            \n            // For bill or legislation items that have a label-form\n            // attribute set on the cs:number node rendering the locator,\n            // the form and pluralism of locator terms are controlled\n            // separately from those of the initial label. Form is\n            // straightforward: the label uses the value set on\n            // the cs:label node that renders it, and the embedded\n            // labels use the value of label-form set on the cs:number\n            // node. Both default to \"long\".\n            //\n            // Pluralism is more complicated. For embedded labels,\n            // pluralism is evaluated using a simple heuristic that\n            // can be found below (it just looks for comma, ampersand etc).\n            // The item.label rendered independently via cs:label\n            // defaults to singular. It is always singular if embedded\n            // labels exist that (when expanded to their valid CSL\n            // value) do not match the value of item.label. Otherwise,\n            // if one or more matching embedded labels exist, the\n            // cs:label is set to plural.\n            //\n            // The code that does all this is divided between this module,\n            // util_static_locator.js, and util_label.js. It's not easy\n            // to follow, but seems to do the job. Let's home for good\n            // luck out there in the wild.\n            \n            var node = this;\n\n            if (state.tmp.group_context.tip.force_suppress) {\n                return false;\n            }\n\n            if ([\"locator\", \"locator-extra\"].indexOf(varname) > -1) {\n                // amazing that we reach this. should abort sooner if no content?\n                state.processNumber.call(state, node, item, varname, Item.type);\n            } else {\n                if (!state.tmp.group_context.tip.condition && Item[varname]) {\n                    state.tmp.just_did_number = (\"\" + Item[varname]).match(/[0-9]$/);\n                }\n                // UPDATE_GROUP_CONTEXT_CONDITION is run by processNumber\n                state.processNumber.call(state, node, Item, varname, Item.type);\n            }\n\n            if (this.substring) {\n                var val = Item[varname].slice(this.substring);\n                state.output.append(val, node);\n            } else {\n                CSL.Util.outputNumericField(state, varname, Item.id);\n            }\n\n            if ([\"locator\", \"locator-extra\"].indexOf(this.variables_real[0]) > -1\n               && !state.tmp.just_looking) {\n                state.tmp.done_vars.push(this.variables_real[0]);\n                state.tmp.group_context.tip.done_vars.push(this.variables_real[0]);\n            }\n        };\n        this.execs.push(func);\n        target.push(this);\n        \n        CSL.Util.substituteEnd.call(this, state, target);\n    }\n};\n\n/*global CSL: true */\n\n/*\n * Yikes, these functions were running out of scope for yonks.\n * now that they are set in the correct token list,\n * they might be useful for things.\n * FB 2013.11.09\n*/\n\nCSL.Node.sort = {\n    build: function (state, target) {\n        target = state[state.build.root + \"_sort\"].tokens;\n        if (this.tokentype === CSL.START) {\n            if (state.build.area === \"citation\") {\n                state.opt.sort_citations = true;\n            }\n            state.build.area = state.build.root + \"_sort\";\n            state.build.extension = \"_sort\";\n            \n            var func = function (state, Item) {\n                //state.tmp.area = state.tmp.root + \"_sort\";\n                //state.tmp.extension = \"_sort\";\n                if (state.opt.has_layout_locale) {\n                    var langspec = CSL.localeResolve(Item.language, state.opt[\"default-locale\"][0]);\n                    var sort_locales = state[state.tmp.area.slice(0,-5)].opt.sort_locales;\n                    var langForItem;\n                    for (var i=0,ilen=sort_locales.length;i<ilen;i+=1) {\n                        langForItem = sort_locales[i][langspec.bare];\n                        if (!langForItem) {\n                            langForItem = sort_locales[i][langspec.best];\n                        }\n                        if (langForItem) {\n                            break;\n                        }\n                    }\n                    if (!langForItem) {\n                        langForItem = state.opt[\"default-locale\"][0];\n                    }\n                    state.tmp.lang_sort_hold = state.opt.lang;\n                    state.opt.lang = langForItem;\n                }\n            };\n            this.execs.push(func);\n            \n        }\n        if (this.tokentype === CSL.END) {\n            state.build.area = state.build.root;\n            state.build.extension = \"\";\n            var func = function (state) {\n                if (state.opt.has_layout_locale) {\n                    state.opt.lang = state.tmp.lang_sort_hold;\n                    delete state.tmp.lang_sort_hold;\n                }\n                //state.tmp.area = state.tmp.root;\n                //state.tmp.extension = \"\";\n            };\n            this.execs.push(func);\n            /*\n            var func = function (state, Item) {\n                state.tmp.area = state.tmp.root;\n                state.tmp.extension = \"\";\n            }\n            this.execs.push(func);\n            */\n        }\n        target.push(this);\n    }\n};\n\n\n\n/*global CSL: true */\n\nCSL.Node.substitute = {\n    build: function (state, target) {\n        var func;\n        if (this.tokentype === CSL.START) {\n            /* */\n            // set conditional\n            var choose_start = new CSL.Token(\"choose\", CSL.START);\n            CSL.Node.choose.build.call(choose_start, state, target);\n            var if_singleton = new CSL.Token(\"if\", CSL.SINGLETON);\n            func = function() {\n                if (state.tmp.value.length && !state.tmp.common_term_match_fail) {\n                    return true;\n                }\n                return false;\n            }\n            if_singleton.tests = [func];\n            if_singleton.test = state.fun.match.any(if_singleton, state, if_singleton.tests);\n            target.push(if_singleton);\n\n            func = function (state) {\n                state.tmp.can_block_substitute = true;\n                if (state.tmp.value.length && !state.tmp.common_term_match_fail) {\n                    state.tmp.can_substitute.replace(false, CSL.LITERAL);\n                }\n                state.tmp.common_term_match_fail = false;\n            };\n            this.execs.push(func);\n            target.push(this);\n            /* */\n        }\n        if (this.tokentype === CSL.END) {\n            //var if_end = new CSL.Token(\"if\", CSL.END);\n            //CSL.Node[\"if\"].build.call(if_end, state, target);\n            /* */\n            target.push(this);\n            var choose_end = new CSL.Token(\"choose\", CSL.END);\n            CSL.Node.choose.build.call(choose_end, state, target);\n            /* */\n        }\n    }\n};\n\n\n\n/*global CSL: true */\n\nCSL.Node.text = {\n    build: function (state, target) {\n        var func, form, plural, id, num, number, formatter, firstoutput, specialdelimiter, label, suffix, term;\n        if (this.postponed_macro) {\n            var group_start = CSL.Util.cloneToken(this);\n            group_start.name = \"group\";\n            group_start.tokentype = CSL.START;\n            CSL.Node.group.build.call(group_start, state, target);\n\n            CSL.expandMacro.call(state, this, target);\n\n            var group_end = CSL.Util.cloneToken(this);\n            group_end.name = \"group\";\n            group_end.tokentype = CSL.END;\n            if (this.postponed_macro === 'juris-locator-label') {\n                group_end.isJurisLocatorLabel = true;\n            }\n            CSL.Node.group.build.call(group_end, state, target);\n\n        } else {\n            CSL.Util.substituteStart.call(this, state, target);\n            // ...\n            //\n            // Do non-macro stuff\n            \n            // Guess again. this.variables is ephemeral, adjusted by an initial\n            // function set on the node via @variable attribute setup.\n            //variable = this.variables[0];\n            \n            if (!this.variables_real) {\n                this.variables_real = [];\n            }\n            if (!this.variables) {\n                this.variables = [];\n            }\n\n            form = \"long\";\n            plural = 0;\n            if (this.strings.form) {\n                form = this.strings.form;\n            }\n            if (this.strings.plural) {\n                plural = this.strings.plural;\n            }\n            if (\"citation-number\" === this.variables_real[0] || \"year-suffix\" === this.variables_real[0] || \"citation-label\" === this.variables_real[0]) {\n                //\n                // citation-number and year-suffix are super special,\n                // because they are rangeables, and require a completely\n                // different set of formatting parameters on the output\n                // queue.\n                if (this.variables_real[0] === \"citation-number\") {\n\n                    if (state.build.root === \"citation\") {\n                        state.opt.update_mode = CSL.NUMERIC;\n                    }\n                    if (state.build.root === \"bibliography\") {\n                        state.opt.bib_mode = CSL.NUMERIC;\n                    }\n                    //this.strings.is_rangeable = true;\n                    if (\"citation-number\" === state[state.tmp.area].opt.collapse) {\n                        this.range_prefix = state.getTerm(\"citation-range-delimiter\");\n                    }\n                    this.successor_prefix = state[state.build.area].opt.layout_delimiter;\n                    this.splice_prefix = state[state.build.area].opt.layout_delimiter;\n                    func = function (state, Item, item) {\n\n                        id = \"\" + Item.id;\n                        if (!state.tmp.just_looking) {\n                            if (state.tmp.area.slice(-5) === \"_sort\" && this.variables[0] === \"citation-number\") {\n                                if (state.tmp.area === \"bibliography_sort\") {\n                                    state.tmp.group_context.tip.done_vars.push(\"citation-number\");\n                                }\n                                if (state.tmp.area === \"citation_sort\" && state.bibliography_sort.tmp.citation_number_map) {\n                                    var num = state.bibliography_sort.tmp.citation_number_map[state.registry.registry[Item.id].seq];\n                                } else {\n                                    var num = state.registry.registry[Item.id].seq;\n                                }\n                                if (num) {\n                                    // Code currently in util_number.js\n                                    num = CSL.Util.padding(\"\" + num);\n                                }\n                                state.output.append(num, this);\n                                return;\n                            }\n                            if (item && item[\"author-only\"]) {\n                                state.tmp.element_trace.replace(\"suppress-me\");\n                            }\n                            if (state.tmp.area !== \"bibliography_sort\" && state.bibliography_sort.tmp.citation_number_map && state.bibliography_sort.opt.citation_number_sort_direction === CSL.DESCENDING) {\n                                num = state.bibliography_sort.tmp.citation_number_map[state.registry.registry[id].seq];\n                            } else {\n                                num = state.registry.registry[id].seq;\n                            }\n                            if (state.opt.citation_number_slug) {\n                                state.output.append(state.opt.citation_number_slug, this);\n                            } else {\n                                number = new CSL.NumericBlob(state, false, num, this, Item.id);\n                                if (state.tmp.in_cite_predecessor) {\n                                    number.suppress_splice_prefix = true;\n                                }\n                                state.output.append(number, \"literal\");\n                            }\n                        }\n                    };\n                    this.execs.push(func);\n                } else if (this.variables_real[0] === \"year-suffix\") {\n\n                    state.opt.has_year_suffix = true;\n\n                    if (state[state.tmp.area].opt.collapse === \"year-suffix-ranged\") {\n                        //this.range_prefix = \"-\";\n                        this.range_prefix = state.getTerm(\"citation-range-delimiter\");\n                    }\n                    this.successor_prefix = state[state.build.area].opt.layout_delimiter;\n                    if (state[state.tmp.area].opt[\"year-suffix-delimiter\"]) {\n                        this.successor_prefix = state[state.build.area].opt[\"year-suffix-delimiter\"];\n                    }\n                    func = function (state, Item) {\n                        if (state.registry.registry[Item.id] && state.registry.registry[Item.id].disambig.year_suffix !== false && !state.tmp.just_looking) {\n                            //state.output.append(state.registry.registry[Item.id].disambig[2],this);\n                            num = parseInt(state.registry.registry[Item.id].disambig.year_suffix, 10);\n\n                            //if (state[state.tmp.area].opt.collapse === \"year-suffix-ranged\") {\n                            //    //this.range_prefix = \"-\";\n                            //    this.range_prefix = state.getTerm(\"citation-range-delimiter\");\n                            //}\n                            //this.successor_prefix = state[state.tmp.area].opt.layout_delimiter;\n                            if (state[state.tmp.area].opt.cite_group_delimiter) {\n                                this.successor_prefix = state[state.tmp.area].opt.cite_group_delimiter;\n                            }\n                            number = new CSL.NumericBlob(state, false, num, this, Item.id);\n                            formatter = new CSL.Util.Suffixator(CSL.SUFFIX_CHARS);\n                            number.setFormatter(formatter);\n                            state.output.append(number, \"literal\");\n                            firstoutput = false;\n                            // XXX Can we do something better for length here?\n                            for (var i=0,ilen=state.tmp.group_context.mystack.length; i<ilen; i++) {\n                                var flags = state.tmp.group_context.mystack[i];\n                                if (!flags.variable_success && (flags.variable_attempt || (!flags.variable_attempt && !flags.term_intended))) {\n                                    firstoutput = true;\n                                    break;\n                                }\n                            }\n                            specialdelimiter = state[state.tmp.area].opt[\"year-suffix-delimiter\"];\n                            if (firstoutput && specialdelimiter && !state.tmp.sort_key_flag) {\n                                state.tmp.splice_delimiter = state[state.tmp.area].opt[\"year-suffix-delimiter\"];\n                            }\n                        }\n                    };\n                    this.execs.push(func);\n                } else if (this.variables_real[0] === \"citation-label\") {\n                    if (state.build.root === \"bibliography\") {\n                        state.opt.bib_mode = CSL.TRIGRAPH;\n                    }\n                    state.opt.has_year_suffix = true;\n                    func = function (state, Item) {\n                        label = Item[\"citation-label\"];\n                        if (!label) {\n                            label = state.getCitationLabel(Item);\n                        }\n                        if (!state.tmp.just_looking) {\n                            suffix = \"\";\n                            if (state.registry.registry[Item.id] && state.registry.registry[Item.id].disambig.year_suffix !== false) {\n                                num = parseInt(state.registry.registry[Item.id].disambig.year_suffix, 10);\n                                suffix = state.fun.suffixator.format(num);\n                            }\n                            label += suffix;\n                        }\n                        state.output.append(label, this);\n                    };\n                    this.execs.push(func);\n                }\n            } else {\n                if (this.strings.term) {\n                    \n                    // printterm\n                    func = function (state, Item) {\n                        var gender = state.opt.gender[Item.type];\n                        var term = this.strings.term;\n                        term = state.getTerm(term, form, plural, gender, CSL.TOLERANT, this.default_locale);\n                        var myterm;\n                        // if the term is not an empty string, say\n                        // that we rendered a term\n                        if (term !== \"\") {\n                            state.tmp.group_context.tip.term_intended = true;\n                        }\n                        CSL.UPDATE_GROUP_CONTEXT_CONDITION(state, term, null, this);\n                        \n                        // capitalize the first letter of a term, if it is the\n                        // first thing rendered in a citation (or if it is\n                        // being rendered immediately after terminal punctuation,\n                        // I guess, actually).\n                        if (!state.tmp.term_predecessor && !(state.opt[\"class\"] === \"in-text\" && state.tmp.area === \"citation\")) {\n                            myterm = CSL.Output.Formatters[\"capitalize-first\"](state, term);\n                            //CSL.debug(\"Capitalize\");\n                        } else {\n                            myterm = term;\n                        }\n                        \n                        // XXXXX Cut-and-paste code in multiple locations. This code block should be\n                        // collected in a function.\n                        // Tag: strip-periods-block\n                        if (state.tmp.strip_periods) {\n                            myterm = myterm.replace(/\\./g, \"\");\n                        } else {\n                            for (var i = 0, ilen = this.decorations.length; i < ilen; i += 1) {\n                                if (\"@strip-periods\" === this.decorations[i][0] && \"true\" === this.decorations[i][1]) {\n                                    myterm = myterm.replace(/\\./g, \"\");\n                                    break;\n                                }\n                            }\n                        }\n                        state.output.append(myterm, this);\n                        if (state.tmp.can_block_substitute) {\n                            // Black magic here. This causes the cs:substitution condition to pass,\n                            // blocking further rendering within its scope. \n                            state.tmp.can_substitute.replace(false, CSL.LITERAL);\n                        }\n                    };\n                    this.execs.push(func);\n                    state.build.term = false;\n                    state.build.form = false;\n                    state.build.plural = false;\n                } else if (this.variables_real.length) {\n                    func = function (state, Item) {\n\n                        // If some text variable is rendered, we're not collapsing.\n                        if (this.variables_real[0] !== \"locator\") {\n                            state.tmp.have_collapsed = false;\n                        }\n\n                        if (!state.tmp.group_context.tip.condition && Item[this.variables[0]]) {\n                            state.tmp.just_did_number = false;\n                        }\n                        var val = Item[this.variables[0]];\n                        if (val && !state.tmp.group_context.tip.condition) {\n                            if ((\"\" + val).slice(-1).match(/[0-9]/)) {\n                                state.tmp.just_did_number = true;\n                            } else {\n                                state.tmp.just_did_number = false;\n                            }\n                        }\n                    };\n                    this.execs.push(func);\n\n                    // plain string fields\n\n                    // Deal with multi-fields and ordinary fields separately.\n                    if (CSL.MULTI_FIELDS.indexOf(this.variables_real[0]) > -1\n                        || this.variables_real[0].indexOf(\"-main\") > -1\n                        || this.variables_real[0].indexOf(\"-sub\") > -1\n                        || [\"language-name\", \"language-name-original\"].indexOf(this.variables_real[0]) > -1\n                       ) {\n\n                        // multi-fields\n                        // Initialize transform factory according to whether\n                        // abbreviation is desired.\n                        var abbrevfam = this.variables[0];\n                        var abbrfall = false;\n                        var altvar = false;\n                        var transfall = false;\n                        if (form === \"short\") {\n                            if (this.variables_real[0].slice(-6) !== \"-short\") {\n                                altvar = this.variables_real[0] + \"-short\";\n                            }\n                        } else {\n                            abbrevfam = false;\n                        }\n                        if (state.build.extension) {\n                            // multi-fields for sorting get a sort transform,\n                            // (abbreviated if the short form was selected)\n                            transfall = true;\n                        } else {\n                            transfall = true;\n                            abbrfall = true;\n\t\t\t\t\t\t}\n\n                        func = state.transform.getOutputFunction(this.variables, abbrevfam, abbrfall, altvar, transfall);\n                    } else {\n                        // ordinary fields\n                        if (CSL.CITE_FIELDS.indexOf(this.variables_real[0]) > -1) {\n                            // per-cite fields are read from item, rather than Item\n                            func = function (state, Item, item) {\n                                if (item && item[this.variables[0]]) {\n                                    // Code copied to page variable as well; both\n                                    // become cs:number in MLZ extended schema\n                                    \n                                    // If locator, use cs:number. Otherwise, render\n                                    // normally.\n\n                                    // XXX The code below is pretty-much copied from\n                                    // XXX node_number.js. Should be a common function.\n                                    // XXX BEGIN\n                                    state.processNumber(this, item, this.variables[0], Item.type);\n                                    CSL.Util.outputNumericField(state, this.variables[0], Item.id);\n                                    // XXX END\n\n                                    if ([\"locator\", \"locator-extra\"].indexOf(this.variables_real[0]) > -1\n                                       && !state.tmp.just_looking) { \n                                        state.tmp.done_vars.push(this.variables_real[0]);\n                                    }\n                                }\n                            };\n                        } else  if ([\"page\", \"page-first\", \"chapter-number\", \"collection-number\", \"edition\", \"issue\", \"number\", \"number-of-pages\", \"number-of-volumes\", \"volume\"].indexOf(this.variables_real[0]) > -1) {\n                            // page gets mangled with the correct collapsing\n                            // algorithm\n                            func = function(state, Item) {\n                                state.processNumber(this, Item, this.variables[0], Item.type);\n                                CSL.Util.outputNumericField(state, this.variables[0], Item.id);\n                            };\n                        } else if ([\"URL\", \"DOI\"].indexOf(this.variables_real[0]) > -1) {\n                            func = function (state, Item) {\n                                var value;\n                                if (this.variables[0]) {\n                                    value = state.getVariable(Item, this.variables[0], form);\n                                    if (value) {\n                                        if (this.variables[0] === \"URL\" && form === \"short\") {\n                                            value = value.replace(/(.*\\.[^\\/]+)\\/.*/, \"$1\");\n                                            if (value.match(/\\/\\/www\\./)) {\n                                                value = value.replace(/https?:\\/\\//, \"\");\n                                            }\n                                        }\n                                        // true is for non-suppression of periods\n                                        if (state.opt.development_extensions.wrap_url_and_doi) {\n                                            if (!this.decorations.length || this.decorations[0][0] !== \"@\" + this.variables[0]) {\n                                                // Special-casing to fix https://github.com/Juris-M/citeproc-js/issues/57\n                                                // clone current token, to avoid collateral damage\n                                                var clonetoken = CSL.Util.cloneToken(this);\n                                                // cast a group blob\n                                                var groupblob = new CSL.Blob(null, null, \"url-wrapper\");\n                                                // set the DOI decoration on the blob\n                                                groupblob.decorations.push([\"@DOI\", \"true\"]);\n                                                if (this.variables_real[0] === \"DOI\") {\n                                                    // strip a proper DOI prefix\n                                                    var prefix;\n                                                    if (this.strings.prefix && this.strings.prefix.match(/^.*https:\\/\\/doi\\.org\\/$/)) {\n                                                        value = value.replace(/^https?:\\/\\/doi\\.org\\//, \"\");\n                                                        if (value.match(/^https?:\\/\\//)) {\n                                                            // Do not tamper with another protocol + domain if already set in field value\n                                                            prefix = \"\";\n                                                        } else {\n                                                            // Otherwise https + domain\n                                                            prefix = \"https://doi.org/\";\n                                                        }\n                                                        // set any string prefix on the clone\n                                                        clonetoken.strings.prefix = this.strings.prefix.slice(0, clonetoken.strings.prefix.length-16);\n                                                    }\n                                                    // cast a text blob\n                                                    // set the prefix as the content of the blob\n                                                    var prefixblob = new CSL.Blob(prefix);\n                                                    // cast another text blob\n                                                    // set the value as the content of the second blob\n                                                    var valueblob = new CSL.Blob(value);\n                                                    // append new text token and clone to group token\n                                                    groupblob.push(prefixblob);\n                                                    groupblob.push(valueblob);\n                                                    // append group token to output\n                                                    state.output.append(groupblob, clonetoken, false, false, true);\n                                                } else {\n                                                    var valueblob = new CSL.Blob(value);\n                                                    // append new text token and clone to group token\n                                                    groupblob.push(valueblob);\n                                                    // append group token to output\n                                                    //this.decorations = [[\"@\" + this.variables[0], \"true\"]].concat(this.decorations);\n                                                    state.output.append(groupblob, clonetoken, false, false, true);\n                                                }\n                                            } else {\n                                                state.output.append(value, this, false, false, true);\n                                            }\n                                        } else {\n                                            // This is totally unnecessary, isn't it?\n                                            if (this.decorations.length) {\n                                                for (var i=this.decorations.length-1; i>-1; i--) {\n                                                    if (this.decorations[i][0] === \"@\" + this.variables[0]) {\n                                                        this.decorations = this.decorations.slice(0, i).concat(this.decorations.slice(i+1));\n                                                    }\n                                                }\n                                            }\n                                            state.output.append(value, this, false, false, true);\n                                        }\n                                    }\n                                }\n                            };\n                        } else if (this.variables_real[0] === \"section\") {\n                            // Sections for statutes are special. This is an uncommon\n                            // variable, so we save the cost of the runtime check\n                            // unless it's being used.\n                            func = function (state, Item) {\n                                var value;\n                                value = state.getVariable(Item, this.variables[0], form);\n                                if (value) {\n                                    state.output.append(value, this);\n                                }\n                            };\n                        } else if (this.variables_real[0] === \"hereinafter\") {\n                            func = function (state, Item) {\n                                var value = state.transform.abbrevs[\"default\"][\"hereinafter\"][Item.id];\n                                if (value) {\n                                    state.output.append(value, this);\n                                    state.tmp.group_context.tip.variable_success = true;\n                                }\n                            };\n                        } else {\n                            // anything left over just gets output in the normal way.\n                            func = function (state, Item) {\n                                var value;\n                                if (this.variables[0]) {\n                                    value = state.getVariable(Item, this.variables[0], form);\n                                    if (value) {\n                                        value = \"\" + value;\n                                        value = value.split(\"\\\\\").join(\"\");\n                                        state.output.append(value, this);\n                                    }\n                                }\n                            };\n                        }\n                    }\n                    this.execs.push(func);\n                } else if (this.strings.value) {\n                    // for the text value attribute.\n                    func = function (state) {\n                        state.tmp.group_context.tip.term_intended = true;\n                        // true flags that this is a literal-value term\n                        CSL.UPDATE_GROUP_CONTEXT_CONDITION(state, this.strings.value, true, this);\n                        state.output.append(this.strings.value, this);\n                        if (state.tmp.can_block_substitute) {\n                            // Black magic here. This causes the cs:substitution condition to pass,\n                            // blocking further rendering within its scope. \n                            state.tmp.can_substitute.replace(false, CSL.LITERAL);\n                        }\n                    };\n                    this.execs.push(func);\n                    // otherwise no output\n                }\n            }\n            target.push(this);\n            CSL.Util.substituteEnd.call(this, state, target);\n        }\n    }\n};\n\n\n\n/*global CSL: true */\n\nCSL.Node.intext = {\n    build: function (state, target) {\n        if (this.tokentype === CSL.START) {\n\n            state.build.area = \"intext\";\n            state.build.root = \"intext\";\n            state.build.extension = \"\";\n\n            var func = function(state, Item) {\n                state.tmp.area = \"intext\";\n                state.tmp.root = \"intext\";\n                state.tmp.extension = \"\";\n            }\n            this.execs.push(func);\n        }\n        if (this.tokentype === CSL.END) {\n\n            // Do whatever cs:citation does with sorting.\n            state.intext_sort = {\n                opt: {\n                    sort_directions: state.citation_sort.opt.sort_directions\n                }\n            }\n            state.intext.srt = state.citation.srt;\n        }\n        target.push(this);\n    }\n};\n\n\n/*global CSL: true */\n\nCSL.Attributes = {};\n\nCSL.Attributes[\"@disambiguate\"] = function (state, arg) {\n    if (!this.tests) {this.tests = []; };\n    if (arg === \"true\") {\n        state.opt.has_disambiguate = true;\n        var func = function (Item) {\n            if (state.tmp.area === \"bibliography\") {\n                if (state.tmp.disambiguate_count < state.registry.registry[Item.id].disambig.disambiguate) {\n                    state.tmp.disambiguate_count += 1;\n                    return true;\n                }\n            } else {\n                state.tmp.disambiguate_maxMax += 1;\n                if (state.tmp.disambig_settings.disambiguate\n                    && state.tmp.disambiguate_count < state.tmp.disambig_settings.disambiguate) {\n                    state.tmp.disambiguate_count += 1;\n                    return true;\n                }\n            }\n            return false;\n        };\n        this.tests.push(func);\n    } else if (arg === \"check-ambiguity-and-backreference\") {\n        var func = function (Item) {\n            if (state.registry.registry[Item.id].disambig.disambiguate && state.registry.registry[Item.id][\"citation-count\"] > 1) {\n                return true;\n            }\n            return false;\n        };\n        this.tests.push(func);\n    }\n};\n\nCSL.Attributes[\"@is-numeric\"] = function (state, arg) {\n    if (!this.tests) {this.tests = []; };\n    var variables = arg.split(/\\s+/);\n    var maketest = function(variable) {\n        return function (Item, item) {\n            var myitem = Item;\n            if (item && [\"locator\",\"locator-extra\"].indexOf(variable) > -1) {\n                myitem = item;\n            }\n            if (!myitem[variable]) {\n                return false;\n            }\n            if (CSL.NUMERIC_VARIABLES.indexOf(variable) > -1) {\n                if (!state.tmp.shadow_numbers[variable]) {\n                    state.processNumber(false, myitem, variable, Item.type);\n                }\n                if (state.tmp.shadow_numbers[variable].numeric) {\n                    return true;\n                }\n            } else if ([\"title\",\"version\"].indexOf(variable) > -1) {\n                if (myitem[variable].slice(-1) === \"\" + parseInt(myitem[variable].slice(-1), 10)) {\n                    return true;\n                }\n            }\n            return false;\n        };\n    };\n    for (var i=0; i<variables.length; i+=1) {\n        this.tests.push(maketest(variables[i]));\n    }\n};\n\n\nCSL.Attributes[\"@is-uncertain-date\"] = function (state, arg) {\n    if (!this.tests) {this.tests = []; };\n    var variables = arg.split(/\\s+/);\n    // Strip off any boolean prefix.\n    var maketest = function (myvariable) {\n        return function(Item) {\n            if (Item[myvariable] && Item[myvariable].circa) {\n                return true;\n            } else {\n                return false;\n            }\n        };\n    };\n    for (var i=0,ilen=variables.length;i<ilen;i+=1) {\n        this.tests.push(maketest(variables[i]));\n    }\n};\n\n\nCSL.Attributes[\"@locator\"] = function (state, arg) {\n    if (!this.tests) {this.tests = []; };\n    var trylabels = arg.replace(\"sub verbo\", \"sub-verbo\");\n    trylabels = trylabels.split(/\\s+/);\n    // Strip off any boolean prefix.\n    var maketest = function (trylabel) {\n        return function(Item, item) {\n            var label;\n            state.processNumber(false, item, \"locator\");\n            label = state.tmp.shadow_numbers.locator.label;\n            if (label && trylabel === label) {\n                return true;\n            } else {\n                return false;\n            }\n        };\n    };\n    for (var i=0,ilen=trylabels.length;i<ilen;i+=1) {\n        this.tests.push(maketest(trylabels[i]));\n    }\n};\n\n\nCSL.Attributes[\"@position\"] = function (state, arg) {\n    if (!this.tests) {this.tests = []; };\n    var tryposition;\n    state.opt.update_mode = CSL.POSITION;\n    var trypositions = arg.split(/\\s+/);\n    var testSubsequentNear = function (Item, item) {\n        if (item && CSL.POSITION_MAP[item.position] >= CSL.POSITION_MAP[CSL.POSITION_SUBSEQUENT] && item[\"near-note\"]) {\n            return true;\n        }\n        return false;\n    };\n    var testSubsequentNotNear = function (Item, item) {\n        if (item && CSL.POSITION_MAP[item.position] == CSL.POSITION_MAP[CSL.POSITION_SUBSEQUENT] && !item[\"near-note\"]) {\n            return true;\n        }\n        return false;\n    };\n    var maketest = function(tryposition) {\n        return function (Item, item) {\n            if (state.tmp.area === \"bibliography\") {\n                return false;\n            }\n            if (item && \"undefined\" === typeof item.position) {\n                item.position = 0;\n            }\n            if (item && typeof item.position === \"number\") {\n                if (item.position === 0 && tryposition === 0) {\n                    return true;\n                } else if (tryposition > 0 && CSL.POSITION_MAP[item.position] >= CSL.POSITION_MAP[tryposition]) {\n                    return true;\n                }\n            } else if (tryposition === 0) {\n                return true;\n            }\n            return false;\n        };\n    };\n    for (var i=0,ilen=trypositions.length;i<ilen;i+=1) {\n        var tryposition = trypositions[i];\n        if (tryposition === \"first\") {\n            tryposition = CSL.POSITION_FIRST;\n        } else if (tryposition === \"container-subsequent\") {\n            tryposition = CSL.POSITION_CONTAINER_SUBSEQUENT;\n        } else if (tryposition === \"subsequent\") {\n            tryposition = CSL.POSITION_SUBSEQUENT;\n        } else if (tryposition === \"ibid\") {\n            tryposition = CSL.POSITION_IBID;\n        } else if (tryposition === \"ibid-with-locator\") {\n            tryposition = CSL.POSITION_IBID_WITH_LOCATOR;\n        }\n        if (\"near-note\" === tryposition) {\n            this.tests.push(testSubsequentNear);\n        } else if (\"far-note\" === tryposition) {\n            this.tests.push(testSubsequentNotNear);\n        } else {\n            this.tests.push(maketest(tryposition));\n        }\n    }\n};\n\nCSL.Attributes[\"@type\"] = function (state, arg) {\n    if (!this.tests) {this.tests = []; };\n    // XXX This is ALWAYS composed as an \"any\" match\n    var types = arg.split(/\\s+/);\n    // Strip off any boolean prefix.\n    var maketest = function (mytype) {\n        return function(Item) {\n            var ret = (Item.type === mytype);\n            if (ret) {\n                return true;\n            } else {\n                return false;\n            }\n        };\n    };\n    var tests = [];\n    for (var i=0,ilen=types.length;i<ilen;i+=1) {\n        tests.push(maketest(types[i]));\n    }\n    this.tests.push(state.fun.match.any(this, state, tests));\n};\n\nCSL.Attributes[\"@variable\"] = function (state, arg) {\n    if (!this.tests) {this.tests = []; };\n    var func;\n    this.variables = arg.split(/\\s+/);\n    this.variables_real = this.variables.slice();\n\n    // First the non-conditional code.\n    if (\"label\" === this.name && this.variables[0]) {\n        this.strings.term = this.variables[0];\n    } else if ([\"names\", \"date\", \"text\", \"number\"].indexOf(this.name) > -1) {\n        //\n        // An oddity of variable handling is that this.variables\n        // is actually ephemeral; the full list of variables is\n        // held in the variables_real var, and pushed into this.variables\n        // conditionally in order to suppress repeat renderings of\n        // the same item variable.  [STILL FUNCTIONAL? 2010.01.15]\n        //\n        // set variable names\n        func = function (state, Item, item) {\n            // Clear this.variables in place\n            for (var i = this.variables.length - 1; i > -1; i += -1) {\n                this.variables.pop();\n            }\n            for (var i=0,ilen=this.variables_real.length;i<ilen;i++) {\n                // set variable name if not quashed, and if not the title of a legal case w/suppress-author\n                if (state.tmp.done_vars.indexOf(this.variables_real[i]) === -1 \n// This looks nuts. Why suppress a case name if not required by context?\n//                    && !(item && Item.type === \"legal_case\" && item[\"suppress-author\"] && this.variables_real[i] === \"title\")\n                   ) {\n                    this.variables.push(this.variables_real[i]);\n                }\n                if (state.tmp.can_block_substitute) {\n                    state.tmp.done_vars.push(this.variables_real[i]);\n                }\n            }\n        };\n        this.execs.push(func);\n\n        // check for output\n        func = function (state, Item, item) {\n            var output = false;\n            for (var i=0,ilen=this.variables.length;i<ilen;i++) {\n                var variable = this.variables[i];\n                if ([\"authority\", \"committee\"].indexOf(variable) > -1\n                    && \"string\" === typeof Item[variable]\n                    && \"names\" === this.name) {\n\n                    // Great! So for each of these, we split.\n                    // And we only recombine everything if the length\n                    // of all the splits matches.\n                    \n                    // Preflight\n                    var isValid = true;\n                    var rawNames = Item[variable].split(/\\s*;\\s*/);\n                    var rawMultiNames = {};\n                    if (Item.multi && Item.multi._keys[variable]) {\n                        for (var langTag in Item.multi._keys[variable]) {\n                            rawMultiNames[langTag] = Item.multi._keys[variable][langTag].split(/\\s*;\\s*/);\n                            if (rawMultiNames[langTag].length !== rawNames.length) {\n                                isValid = false;\n                                break;\n                            }\n                        }\n                    }\n                    if (!isValid) {\n                        rawNames = [Item[variable]];\n                        rawMultiNames = Item.multi._keys[variable];\n                    }\n                    for (var j = 0, jlen = rawNames.length; j < jlen; j++) {\n                        var creatorParent = {\n                            literal:rawNames[j],\n                            multi:{\n                                _key:{}\n                            }\n                        };\n                        for (var langTag in rawMultiNames) {\n                            var creatorChild = {\n                                literal:rawMultiNames[langTag][j]\n                            };\n                            creatorParent.multi._key[langTag] = creatorChild;\n                        }\n                        rawNames[j] = creatorParent;\n                    }\n                    Item[variable] = rawNames;\n                }\n                if (this.strings.form === \"short\" && !Item[variable]) {\n                    if (variable === \"title\") {\n                        variable = \"title-short\";\n                    } else if (variable === \"container-title\") {\n                        variable = \"container-title-short\";\n                    }\n                }\n                if (variable === \"year-suffix\") {\n                    // year-suffix always signals that it produces output,\n                    // even when it doesn't. This permits it to be used with\n                    // the \"no date\" term inside a group used exclusively\n                    // to control formatting.\n                    output = true;\n                    break;\n                } else if (CSL.DATE_VARIABLES.indexOf(variable) > -1) {\n                    if (state.opt.development_extensions.locator_date_and_revision && \"locator-date\" === variable) {\n                        // If locator-date is set, it's valid.\n                        output = true;\n                        break;\n                    }\n                    if (Item[variable]) {\n                        for (var key in Item[variable]) {\n                            if (this.dateparts.indexOf(key) === -1 && \"literal\" !== key) {\n                                continue;\n                            }\n                            if (Item[variable][key]) {\n                                output = true;\n                                break;\n                            }\n                        }\n                        if (output) {\n                            break;\n                        }\n                    }\n                } else if (\"locator\" === variable) {\n                    if (item && item.locator) {\n                        output = true;\n                    }\n                    break;\n                } else if (\"locator-extra\" === variable) {\n                    if (item && item[\"locator-extra\"]) {\n                        output = true;\n                    }\n                    break;\n                } else if ([\"citation-number\",\"citation-label\"].indexOf(variable) > -1) {\n                    output = true;\n                    break;\n                } else if (\"first-reference-note-number\" === variable) {\n                    if (item && item[\"first-reference-note-number\"]) {\n                        output = true;\n                    }\n                    break;\n                } else if (\"first-container-reference-note-number\" === variable) {\n                    if (item && item[\"first-container-reference-note-number\"]) {\n                        output = true;\n                    }\n                    break;\n                } else if (\"hereinafter\" === variable) {\n                    if (state.transform.abbrevs[\"default\"].hereinafter[Item.id]\n                        && state.sys.getAbbreviation\n                        && Item.id) {\n\t\t\t\t\t\t\n                        output = true;\n                    }\n                    break;\n                } else if (\"object\" === typeof Item[variable]) {\n                    break;\n                } else if (\"string\" === typeof Item[variable] && Item[variable]) {\n                    output = true;\n                    break;\n                } else if (\"number\" === typeof Item[variable]) {\n                    output = true;\n                    break;\n                }\n                if (output) {\n                    break;\n                }\n            }\n            //print(\"-- VAR: \"+variable);\n            //flag = state.tmp.group_context.tip;\n            if (output) {\n                for (var i=0,ilen=this.variables_real.length;i<ilen;i++) {\n                    var variable = this.variables_real[i];\n                    if (variable !== \"citation-number\" || state.tmp.area !== \"bibliography\") {\n                        state.tmp.cite_renders_content = true;\n                    }\n                    //print(\"  setting [2] to true based on: \" + arg);\n                    state.tmp.group_context.tip.variable_success = true;\n                    // For util_substitute.js, subsequent-author-substitute\n                    if (state.tmp.can_substitute.value() \n                        && state.tmp.area === \"bibliography\"\n                        && \"string\" === typeof Item[variable]) {\n\n                        state.tmp.name_node.top = state.output.current.value();\n                        state.tmp.rendered_name.push(Item[variable]);\n                    }\n                }\n                state.tmp.can_substitute.replace(false,  CSL.LITERAL);\n            } else {\n                //print(\"  setting [1] to true based on: \" + arg);\n                state.tmp.group_context.tip.variable_attempt = true;\n            }\n            //state.tmp.group_context.replace(flag);\n        };\n        this.execs.push(func);\n    } else if ([\"if\",  \"else-if\", \"condition\"].indexOf(this.name) > -1) {\n        // Strip off any boolean prefix.\n        // Now the conditionals.\n        var maketest = function (variable) {\n            return function(Item,item){\n                var myitem = Item;\n                if (item && [\"locator\", \"locator-extra\", \"first-reference-note-number\", \"first-container-reference-note-number\", \"locator-date\"].indexOf(variable) > -1) {\n                    myitem = item;\n                }\n                // We don't run loadAbbreviation() here; it is run by the application-supplied\n                // retrieveItem() if hereinafter functionality is to be used, so this key will\n                // always exist in memory, possibly with a nil value.\n                if (variable === \"hereinafter\" && state.sys.getAbbreviation && myitem.id) {\n                    if (state.transform.abbrevs[\"default\"].hereinafter[myitem.id]) {\n                        return true;\n                    }\n                } else if (myitem[variable]) {\n                    if (\"number\" === typeof myitem[variable] || \"string\" === typeof myitem[variable]) {\n                        return true;\n                    } else if (\"object\" === typeof myitem[variable]) {\n                        //\n                        // this will turn true only for hash objects\n                        // that have at least one attribute, or for a\n                        // non-zero-length list\n                        //\n                        for (var key in myitem[variable]) {\n                            if (myitem[variable][key]) {\n                                return true;\n                            }\n                        }\n                    }\n                }\n                return false;\n            };\n        };\n        for (var i=0,ilen=this.variables.length;i<ilen;i+=1) {\n            this.tests.push(maketest(this.variables[i]));\n        }\n    }\n};\n\n\nCSL.Attributes[\"@page\"] = function (state, arg) {\n    if (!this.tests) {this.tests = []; };\n    var trylabels = arg.replace(\"sub verbo\", \"sub-verbo\");\n    trylabels = trylabels.split(/\\s+/);\n    // Strip off any boolean prefix.\n    var maketest = function (trylabel) {\n        return function(Item) {\n            var label;\n            state.processNumber(false, Item, \"page\", Item.type);\n            if (!state.tmp.shadow_numbers.page.label) {\n                label = \"page\";\n            } else if (state.tmp.shadow_numbers.page.label === \"sub verbo\") {\n                label = \"sub-verbo\";\n            } else {\n                label = state.tmp.shadow_numbers.page.label;\n            }\n            if (state.tmp.shadow_numbers.page.values.length > 0) {\n                if (state.tmp.shadow_numbers.page.values[0].gotosleepability) {\n                    state.tmp.shadow_numbers.page.values[0].labelVisibility = false;\n                }\n            }\n            if (trylabel === label) {\n                return true;\n            } else {\n                return false;\n            }\n        };\n    };\n    for (var i=0,ilen=trylabels.length;i<ilen;i+=1) {\n        this.tests.push(maketest(trylabels[i]));\n    }\n};\n\n\n// a near duplicate of code above\nCSL.Attributes[\"@number\"] = function (state, arg) {\n    if (!this.tests) {this.tests = []; };\n    var trylabels = arg.split(/\\s+/);\n    var maketest = function(trylabel) {\n        return function (Item) {\n            var label;\n            state.processNumber(false, Item, \"number\", Item.type);\n            if (!state.tmp.shadow_numbers.number.label) {\n                label = \"number\";\n            } else {\n                label = state.tmp.shadow_numbers.number.label;\n            }\n            if (trylabel === label) {\n                return true;\n            } else {\n                return false;\n            }\n        };\n    };\n    for (var i=0,ilen=trylabels.length;i<ilen;i+=1) {\n        this.tests.push(maketest(trylabels[i]));\n    }\n};\n\nCSL.Attributes[\"@jurisdiction\"] = function (state, arg) {\n    if (!this.tests) {this.tests = []; };\n    var tryjurisdictions = arg.split(/\\s+/);\n    \n    // This forces a match=any method, similar to @type\n    var maketests = function (tryjurisdictions) {\n        return function(Item) {\n            if (!Item.jurisdiction) {\n                return false;\n            }\n            var jurisdiction = Item.jurisdiction;\n            for (var i=0,ilen=tryjurisdictions.length;i<ilen;i++) {\n                if (jurisdiction === tryjurisdictions[i]) {\n                    return true;\n                }\n            }\n            return false;\n        };\n    };\n    this.tests.push(maketests(tryjurisdictions));\n};\n\nCSL.Attributes[\"@country\"] = function (state, arg) {\n    if (!this.tests) {this.tests = []; };\n    var trycountries = arg.split(/\\s+/);\n    \n    // This forces a match=any method, similar to @type\n    var maketests = function (trycountries) {\n        return function(Item) {\n            if (!Item.country) {\n                return false;\n            }\n            var country = Item.country;\n            for (var i=0,ilen=trycountries.length;i<ilen;i++) {\n                if (country === trycountries[i]) {\n                    return true;\n                }\n            }\n            return false;\n        };\n    };\n    this.tests.push(maketests(trycountries));\n};\n\nCSL.Attributes[\"@context\"] = function (state, arg) {\n    if (!this.tests) {this.tests = []; };\n    var func = function () {\n        if ([\"bibliography\", \"citation\"].indexOf(arg) > -1) {\n\t\t    var area = state.tmp.area.slice(0, arg.length);\n\t\t    if (area === arg) {\n\t\t\t    return true;\n\t\t    }\n\t\t    return false;\n        } else if (\"alternative\" === arg) {\n            return !!state.tmp.abort_alternative;\n        }\n    };\n    this.tests.push(func);\n};\n\nCSL.Attributes[\"@has-year-only\"] = function (state, arg) {\n    if (!this.tests) {this.tests = []; };\n    var trydates = arg.split(/\\s+/);\n    var maketest = function (trydate) {\n        return function(Item) {\n            var date = Item[trydate];\n            if (!date || date.month || date.season) {\n                return false;\n            } else {\n                return true;\n            }\n        };\n    };\n    for (var i=0,ilen=trydates.length;i<ilen;i+=1) {\n        this.tests.push(maketest(trydates[i]));\n    }\n};\n\nCSL.Attributes[\"@has-to-month-or-season\"] = function (state, arg) {\n    if (!this.tests) {this.tests = []; };\n    var trydates = arg.split(/\\s+/);\n    var maketest = function (trydate) {\n        return function(Item) {\n            var date = Item[trydate];\n            if (!date || (!date.month && !date.season) || date.day) {\n                return false;\n            } else {\n                return true;\n            }\n        };\n    };\n    for (var i=0,ilen=trydates.length;i<ilen;i+=1) {\n        this.tests.push(maketest(trydates[i]));\n    }\n};\n\nCSL.Attributes[\"@has-day\"] = function (state, arg) {\n    if (!this.tests) {this.tests = []; };\n    var trydates = arg.split(/\\s+/);\n    var maketest = function (trydate) {\n        return function(Item) {\n            var date = Item[trydate];\n            if (!date || !date.day) {\n                return false;\n            } else {\n                return true;\n            }\n        };\n    };\n    for (var i=0,ilen=trydates.length;i<ilen;i+=1) {\n        this.tests.push(maketest(trydates[i]));\n    }\n};\n\nCSL.Attributes[\"@is-plural\"] = function (state, arg) {\n    if (!this.tests) {this.tests = []; };\n    var func = function (Item) {\n        var nameList = Item[arg];\n        if (nameList && nameList.length) {\n            var persons = 0;\n            var institutions = 0;\n            var last_is_person = false;\n            for (var i = 0, ilen = nameList.length; i < ilen; i += 1) {\n                if (state.opt.development_extensions.spoof_institutional_affiliations\n                    && (nameList[i].literal || (nameList[i].isInstitution && nameList[i].family && !nameList[i].given))) {\n                    institutions += 1;\n                    last_is_person = false;\n                } else {\n                    persons += 1;\n                    last_is_person = true;\n                }\n            }\n            if (persons > 1) {\n                return true;\n            } else if (institutions > 1) {\n                return true;\n            } else if (institutions && last_is_person) {\n                return true;\n            }\n        }\n        return false;\n    };\n    this.tests.push(func);\n};\n\nCSL.Attributes[\"@is-multiple\"] = function (state, arg) {\n    if (!this.tests) {this.tests = []; };\n    var func = function (Item) {\n        var val = (\"\" + Item[arg]);\n        var lst = val.split(/(?:,\\s|\\s(?:tot\\sen\\smet|līdz|oraz|and|bis|έως|και|och|až|do|en|et|in|ir|ja|og|sa|to|un|und|és|și|i|u|y|à|e|a|и|-|–)\\s|—|\\&)/);\n        if (lst.length > 1) {\n            return true;\n        }\n        return false;\n    };\n    this.tests.push(func);\n};\n\n\n\n\nCSL.Attributes[\"@locale\"] = function (state, arg) {\n    if (!this.tests) {this.tests = []; };\n    var ret, langspec, lang, lst, i, ilen;\n    // Style default\n    var locale_default = state.opt[\"default-locale\"][0];\n\n    if (this.name === \"layout\") {\n        // For layout\n        this.locale_raw = arg;\n        if (this.tokentype === CSL.START) {\n            if (!state.opt.multi_layout) {\n                state.opt.multi_layout = [];\n            }\n            var locale_data = [];\n            // Register the primary locale in the set, and others that \"map\" to it, \n            // so that they can be used when generating sort keys. See node_sort.js.\n            // Not idempotent. Only do this once.\n            var locales = arg.split(/\\s+/);\n            var sort_locale = {};\n            var localeMaster = CSL.localeResolve(locales[0], locale_default);\n            locale_data.push(localeMaster);\n            if (localeMaster.generic) {\n                sort_locale[localeMaster.generic] = localeMaster.best;\n            } else {\n                sort_locale[localeMaster.best] = localeMaster.best;\n            }\n            for (var i=1,ilen=locales.length;i<ilen;i+=1) {\n                var localeServant = CSL.localeResolve(locales[i], locale_default);\n                locale_data.push(localeServant);\n                if (localeServant.generic) {\n                    sort_locale[localeServant.generic] = localeMaster.best;\n                } else {\n                    sort_locale[localeServant.best] = localeMaster.best;\n                }\n\n            }\n            state[state.build.area].opt.sort_locales.push(sort_locale);\n            state.opt.multi_layout.push(locale_data);\n        }\n        state.opt.has_layout_locale = true;\n    } else {\n        // For if and if-else\n\n        // Split argument\n        lst = arg.split(/\\s+/);\n\n        // Expand each list element\n        var locale_bares = [];\n        for (i = 0, ilen = lst.length; i < ilen; i += 1) {\n            // Parse out language string\n            lang = lst[i];\n        \n            // Analyze the locale\n            langspec = CSL.localeResolve(lang, locale_default);\n            if (lst[i].length === 2) {\n                // For fallback\n                locale_bares.push(langspec.bare);\n            }\n            // Load the locale terms etc.\n            // (second argument causes immediate return if locale already exists)\n            state.localeConfigure(langspec, true);\n            \n            // Replace string with locale spec object\n            lst[i] = langspec;\n        }\n        // Locales to test\n        var locale_list = lst.slice();\n\n        // check for variable value\n        // Closure probably not necessary here.\n        var maketest = function (locale_list, locale_default,locale_bares) {\n            return function (Item) {\n                var res;\n                ret = [];\n                res = false;\n                var langspec = false;\n\n                var lang;\n                if (!Item.language) {\n                    lang = locale_default;\n                } else {\n                    lang = Item.language;\n                }\n                langspec = CSL.localeResolve(lang, locale_default);\n                for (i = 0, ilen = locale_list.length; i < ilen; i += 1) {\n                    if (langspec.best === locale_list[i].best) {\n                        state.tmp.condition_lang_counter_arr.push(state.tmp.condition_counter);\n                        state.tmp.condition_lang_val_arr.push(state.opt.lang);\n                        state.opt.lang = locale_list[0].best;\n                        res = true;\n                        break;\n                    }\n                }\n                if (!res && locale_bares.indexOf(langspec.bare) > -1) {\n                    state.tmp.condition_lang_counter_arr.push(state.tmp.condition_counter);\n                    state.tmp.condition_lang_val_arr.push(state.opt.lang);\n                    state.opt.lang = locale_list[0].best;\n                    res = true;\n                }\n                return res;\n            };\n        };\n        this.tests.push(maketest(locale_list,locale_default,locale_bares));\n    }\n};\n\nCSL.Attributes[\"@alternative-node-internal\"] = function (state) {\n    if (!this.tests) {this.tests = []; };\n    var maketest = function () {\n        return function() {\n            return !state.tmp.abort_alternative;\n        };\n    };\n    var me = this;\n    this.tests.push(maketest(me));\n};\n\nCSL.Attributes[\"@locale-internal\"] = function (state, arg) {\n    if (!this.tests) {this.tests = []; };\n    var langspec, lang, lst, i, ilen;\n        // For if and if-else\n\n        // Split argument\n        lst = arg.split(/\\s+/);\n\n        // Expand each list element\n        this.locale_bares = [];\n        for (i = 0, ilen = lst.length; i < ilen; i += 1) {\n            // Parse out language string\n            lang = lst[i];\n        \n            // Analyze the locale\n            langspec = CSL.localeResolve(lang, state.opt[\"default-locale\"][0]);\n            if (lst[i].length === 2) {\n                // For fallback\n                this.locale_bares.push(langspec.bare);\n            }\n            // Load the locale terms etc.\n            state.localeConfigure(langspec);\n            \n            // Replace string with locale spec object\n            lst[i] = langspec;\n        }\n        // Set locale tag on node\n        this.locale_default = state.opt[\"default-locale\"][0];\n        // The locale to set on node children if match is successful\n        this.locale = lst[0].best;\n        // Locales to test\n        this.locale_list = lst.slice();\n        \n        // check for variable value\n        // Closure probably not necessary here.\n        var maketest = function (me) {\n            return function (Item) {\n                var ret, res;\n                ret = [];\n                res = false;\n                var langspec = false;\n                if (Item.language) {\n                    lang = Item.language;\n                    langspec = CSL.localeResolve(lang, state.opt[\"default-locale\"][0]);\n                    if (langspec.best === state.opt[\"default-locale\"][0]) {\n                        langspec = false;\n                    }\n                }\n                if (langspec) {\n                    // We attempt to match a specific locale from the\n                    // list of parameters.  If that fails, we fall back\n                    // to the base locale of the first element.  The\n                    // locale applied is always the first local \n                    // in the list of parameters (or base locale, for a \n                    // single two-character language code) \n                    for (i = 0, ilen = me.locale_list.length; i < ilen; i += 1) {\n                        if (langspec.best === me.locale_list[i].best) {\n                            state.opt.lang = me.locale;\n                            state.tmp.last_cite_locale = me.locale;\n                            // Set empty group open tag with locale set marker\n                            state.output.openLevel(\"empty\");\n                            state.output.current.value().new_locale = me.locale;\n                            res = true;\n                            break;\n                        }\n                    }\n                    if (!res && me.locale_bares.indexOf(langspec.bare) > -1) {\n                        state.opt.lang = me.locale;\n                        state.tmp.last_cite_locale = me.locale;\n                        // Set empty group open tag with locale set marker\n                        state.output.openLevel(\"empty\");\n                        state.output.current.value().new_locale = me.locale;\n                        res = true;\n                    }\n                }\n                return res;\n            };\n        };\n        var me = this;\n        this.tests.push(maketest(me));\n};\n\n\nCSL.Attributes[\"@court-class\"] = function (state, arg) {\n    if (!this.tests) {this.tests = []; };\n\tvar tryclasses = arg.split(/\\s+/);\n    var maketest = function (tryclass) {\n        return function(Item) {\n            var cls = CSL.GET_COURT_CLASS(state, Item);\n            if (cls === tryclass) {\n                return true;\n            } else {\n                return false;\n            }\n        };\n    };\n    for (var i=0,ilen=tryclasses.length; i<ilen; i++) {\n        this.tests.push(maketest(tryclasses[i]));\n    }\n};\n\nCSL.Attributes[\"@container-multiple\"] = function (state, arg) {\n    if (!this.tests) {this.tests = []; };\n\tvar retval = \"true\" === arg ? true : false;\n    var maketest = function (retval) {\n        return function(Item) {\n            if (!state.tmp.container_item_count[Item.container_id]) {\n                return !retval;\n            } else if (state.tmp.container_item_count[Item.container_id] > 1) {\n                return retval;\n            }\n            return !retval;\n        };\n    };\n    this.tests.push(maketest(retval));\n};\n\nCSL.Attributes[\"@container-subsequent\"] = function (state, arg) {\n    if (!this.tests) {this.tests = []; };\n\tvar retval = \"true\" === arg ? true : false;\n    var maketest = function (retval) {\n        return function(Item) {\n            if (state.tmp.container_item_pos[Item.container_id] > 1) {\n                return retval;\n            }\n            return !retval;\n        };\n    };\n    this.tests.push(maketest(retval));\n};\n\nCSL.Attributes[\"@has-subunit\"] = function (state, arg) {\n    if (!this.tests) {this.tests = []; };\n    var maketest = function(namevar) {\n        return function (Item) {\n            var subunit_count = 0;\n            for (var i in Item[namevar]) {\n                var name = Item[namevar][i];\n                if (!name.given) {\n                    var institution = name.literal ? name.literal : name.family;\n                    var length = institution.split(\"|\").length;\n                    if (subunit_count === 0 || length < subunit_count) {\n                        subunit_count = length;\n                    }\n                }\n            }\n            return (subunit_count > 1);\n        };\n    };\n    this.tests.push(maketest(arg));\n}\n\nCSL.Attributes[\"@cite-form\"] = function (state, arg) {\n    if (!this.tests) {this.tests = []; };\n    var maketest = function(citeForm) {\n        return function (Item) {\n            if (Item[\"cite-form\"] === citeForm) {\n                return true;\n            }\n            return false;\n        };\n    };\n    this.tests.push(maketest(arg));\n}\n\nCSL.Attributes[\"@disable-duplicate-year-suppression\"] = function (state, arg) {\n\tstate.opt.disable_duplicate_year_suppression = arg.split(/\\s+/);\n}\n\nCSL.Attributes[\"@consolidate-containers\"] = function (state, arg) {\n    CSL.Attributes[\"@track-containers\"](state, arg);\n    var args = arg.split(/\\s+/);\n    state.bibliography.opt.consolidate_containers = args;\n}\n\nCSL.Attributes[\"@track-containers\"] = function (state, arg) {\n    var args = arg.split(/\\s+/);\n    if (!state.bibliography.opt.track_container_items) {\n        state.bibliography.opt.track_container_items = [];\n    }\n    if (!state.bibliography.opt.consolidate_containers) {\n        state.bibliography.opt.consolidate_containers = [];\n    }\n    state.bibliography.opt.track_container_items = state.bibliography.opt.track_container_items.concat(args);\n}\n\n// These are not evaluated as conditions immediately: they only\n// set parameters that are picked up during processing.\nCSL.Attributes[\"@parallel-first\"] = function (state, arg) {\n    state.opt.parallel.enable = true;\n    var vars = arg.split(/\\s+/);\n    if (!state.opt.track_repeat) {\n        state.opt.track_repeat = {};\n    }\n    this.parallel_first = {};\n    for (var i in vars) {\n        var v = vars[i];\n        this.parallel_first[v] = true;\n        state.opt.track_repeat[v] = true;\n    }\n};\nCSL.Attributes[\"@parallel-last\"] = function (state, arg) {\n    state.opt.parallel.enable = true;\n    var vars = arg.split(/\\s+/);\n    if (!state.opt.track_repeat) {\n        state.opt.track_repeat = {};\n    }\n    this.parallel_last = {};\n    for (var i in vars) {\n        var v = vars[i];\n        this.parallel_last[v] = true;\n        state.opt.track_repeat[v] = true;\n    }\n};\nCSL.Attributes[\"@parallel-last-to-first\"] = function (state, arg) {\n    state.opt.parallel.enable = true;\n    var vars = arg.split(/\\s+/);\n    this.parallel_last_to_first = {};\n    for (var i=0,ilen=vars.length;i<ilen;i++) {\n        this.parallel_last_to_first[vars[i]] = true;\n    }\n};\nCSL.Attributes[\"@parallel-delimiter-override\"] = function (state, arg) {\n    state.opt.parallel.enable = true;\n    this.strings.set_parallel_delimiter_override = arg;\n};\nCSL.Attributes[\"@parallel-delimiter-override-on-suppress\"] = function (state, arg) {\n    state.opt.parallel.enable = true;\n    this.strings.set_parallel_delimiter_override_on_suppress = arg;\n};\nCSL.Attributes[\"@no-repeat\"] = function (state, arg) {\n    state.opt.parallel.enable = true;\n    var vars = arg.split(/\\s+/);\n    if (!state.opt.track_repeat) {\n        state.opt.track_repeat = {};\n    }\n    this.non_parallel = {};\n    for (var i in vars) {\n        var v = vars[i];\n        this.non_parallel[v] = true;\n        state.opt.track_repeat[v] = true;\n    }\n};\n\nCSL.Attributes[\"@require\"] = function (state, arg) {\n    state.opt.use_context_condition = true;\n    this.strings.require = arg;\n\n    // Introduced to constrain rendering of the group with a\n    // requirement that it either render an alpha term via cs:label or\n    // cs:text at least once, or render without any label. That\n    // behaviour is invoked with \"label-empty-or-alpha\" as arg.\n\n    // This attribute is a complement to @label-form and modular\n    // jurisdiction support, as it makes macros that adapt to shifting\n    // local term definitions possible.\n};\n\nCSL.Attributes[\"@reject\"] = function (state, arg) {\n    state.opt.use_context_condition = true;\n    this.strings.reject = arg;\n\n    // Introduced to constrain rendering of the group with a\n    // requirement that it render some label via cs:label or cs:text,\n    // and that it NOT be alpha. That behaviour is invoked with\n    // \"label-empty-or-alpha\" as arg.\n\n    // This attribute is a complement to @label-form and modular\n    // jurisdiction support, as it makes macros that adapt to shifting\n    // local term definitions possible.\n};\n\nCSL.Attributes[\"@require-comma-on-symbol\"] = function (state, arg) {\n    state.opt.require_comma_on_symbol = arg;\n}\n\nCSL.Attributes[\"@gender\"] = function (state, arg) {\n    this.gender = arg;\n};\n\nCSL.Attributes[\"@cslid\"] = function (state, arg) {\n    // @cslid is a noop\n    // The value set on this attribute is used to\n    // generate reverse lookup wrappers on output when \n    // this.development_extensions.csl_reverse_lookup_support is\n    // set to true in state.js (there is no runtime option,\n    // it must be set in state.js)\n    //\n    // See the @showid method in the html output\n    // section of formats.js for the function that\n    // renders the wrappers.\n    this.cslid = parseInt(arg, 10);\n};\n\nCSL.Attributes[\"@capitalize-if-first\"] = function (state, arg) {\n    this.strings.capitalize_if_first_override = arg;\n};\n\nCSL.Attributes[\"@label-capitalize-if-first\"] = function (state, arg) {\n    this.strings.label_capitalize_if_first_override = arg;\n};\n\nCSL.Attributes[\"@label-form\"] = function (state, arg) {\n    this.strings.label_form_override = arg;\n};\n\nCSL.Attributes[\"@part-separator\"] = function (state, arg) {\n    this.strings[\"part-separator\"] = arg;\n};\n\nCSL.Attributes[\"@leading-noise-words\"] = function (state, arg) {\n    this[\"leading-noise-words\"] = arg;\n};\n\nCSL.Attributes[\"@name-never-short\"] = function (state, arg) {\n    this[\"name-never-short\"] = arg;\n};\n\nCSL.Attributes[\"@class\"] = function (state, arg) {\n    state.opt[\"class\"] = arg;\n};\n\nCSL.Attributes[\"@version\"] = function (state, arg) {\n    state.opt.version = arg;\n};\n\n/**\n * Store the value attribute on the token.\n * @name CSL.Attributes.@value\n * @function\n */\nCSL.Attributes[\"@value\"] = function (state, arg) {\n    this.strings.value = arg;\n};\n\n\n/**\n * Store the name attribute (of a macro or term node)\n * on the state object.\n * <p>For reference when the closing node of a macro\n * or locale definition is encountered.</p>\n * @name CSL.Attributes.@name\n * @function\n */\nCSL.Attributes[\"@name\"] = function (state, arg) {\n    this.strings.name = arg;\n};\n\n/**\n * Store the form attribute (of a term node) on the state object.\n * <p>For reference when the closing node of a macro\n * or locale definition is encountered.</p>\n * @name CSL.Attributes.@form\n * @function\n */\nCSL.Attributes[\"@form\"] = function (state, arg) {\n    this.strings.form = arg;\n};\n\nCSL.Attributes[\"@date-parts\"] = function (state, arg) {\n    this.strings[\"date-parts\"] = arg;\n};\n\nCSL.Attributes[\"@range-delimiter\"] = function (state, arg) {\n    this.strings[\"range-delimiter\"] = arg;\n};\n\n/**\n * Store macro tokens in a buffer on the state object.\n * <p>For reference when the enclosing text token is\n * processed.</p>\n * @name CSL.Attributes.@macro\n * @function\n */\nCSL.Attributes[\"@macro\"] = function (state, arg) {\n    this.postponed_macro = arg;\n};\n\n/*\n * CSL.Attributes[\"@prefer-jurisdiction\"] = function (state, arg) {\n *    this.prefer_jurisdiction = true;\n * };\n */\n\nCSL.Attributes[\"@term\"] = function (state, arg) {\n    if (arg === \"sub verbo\") {\n        this.strings.term = \"sub-verbo\";\n    } else {\n        this.strings.term = arg;\n    }\n};\n\n\n/*\n * Ignore xmlns attribute.\n * <p>This should always be <p>http://purl.org/net/xbiblio/csl</code>\n * anyway.  At least for the present we will blindly assume\n * that it is.</p>\n * @name CSL.Attributes.@xmlns\n * @function\n */\nCSL.Attributes[\"@xmlns\"] = function () {};\n\n\n/*\n * Store language attribute to a buffer field.\n * <p>Will be placed in the appropriate location\n * when the element is processed.</p>\n * @name CSL.Attributes.@lang\n * @function\n */\nCSL.Attributes[\"@lang\"] = function (state, arg) {\n    if (arg) {\n        state.build.lang = arg;\n    }\n};\n\n\n// Used as a flag during dates processing\nCSL.Attributes[\"@lingo\"] = function () {};\n\n// Used as a flag during dates processing\nCSL.Attributes[\"@macro-has-date\"] = function () {\n    this[\"macro-has-date\"] = true;\n};\n\n/*\n * Store suffix string on token.\n * @name CSL.Attributes.@suffix\n * @function\n */\nCSL.Attributes[\"@suffix\"] = function (state, arg) {\n    this.strings.suffix = arg;\n};\n\n\n/*\n * Store prefix string on token.\n * @name CSL.Attributes.@prefix\n * @function\n */\nCSL.Attributes[\"@prefix\"] = function (state, arg) {\n    this.strings.prefix = arg;\n};\n\n\n/*\n * Store delimiter string on token.\n * @name CSL.Attributes.@delimiter\n * @function\n */\nCSL.Attributes[\"@delimiter\"] = function (state, arg) {\n    this.strings.delimiter = arg;\n};\n\n\n/*\n * Store match evaluator on token.\n */\nCSL.Attributes[\"@match\"] = function (state, arg) {\n    this.match = arg;\n};\n\n\nCSL.Attributes[\"@names-min\"] = function (state, arg) {\n    var val = parseInt(arg, 10);\n    if (state[state.build.area].opt.max_number_of_names < val) {\n        state[state.build.area].opt.max_number_of_names = val;\n    }\n    this.strings[\"et-al-min\"] = val;\n};\n\nCSL.Attributes[\"@names-use-first\"] = function (state, arg) {\n    this.strings[\"et-al-use-first\"] = parseInt(arg, 10);\n};\n\nCSL.Attributes[\"@names-use-last\"] = function (state, arg) {\n    if (arg === \"true\") {\n        this.strings[\"et-al-use-last\"] = true;\n    } else {\n        this.strings[\"et-al-use-last\"] = false;\n    }\n};\n\nCSL.Attributes[\"@sort\"] = function (state, arg) {\n    if (arg === \"descending\") {\n        this.strings.sort_direction = CSL.DESCENDING;\n    }\n};\n\nCSL.Attributes[\"@plural\"] = function (state, arg) {\n    // Accepted values of plural attribute differ on cs:text\n    // and cs:label nodes.\n    if (\"always\" === arg || \"true\" === arg) {\n        this.strings.plural = 1;\n    } else if (\"never\" === arg || \"false\" === arg) {\n        this.strings.plural = 0;\n    } else if (\"contextual\" === arg) {\n        this.strings.plural = false;\n    }\n};\n\nCSL.Attributes[\"@has-publisher-and-publisher-place\"] = function () {\n    this.strings[\"has-publisher-and-publisher-place\"] = true;\n};\n\nCSL.Attributes[\"@publisher-delimiter-precedes-last\"] = function (state, arg) {\n    this.strings[\"publisher-delimiter-precedes-last\"] = arg;\n};\n\nCSL.Attributes[\"@publisher-delimiter\"] = function (state, arg) {\n    this.strings[\"publisher-delimiter\"] = arg;\n};\n\nCSL.Attributes[\"@publisher-and\"] = function (state, arg) {\n    this.strings[\"publisher-and\"] = arg;\n};\n\nCSL.Attributes[\"@givenname-disambiguation-rule\"] = function (state, arg) {\n    if (CSL.GIVENNAME_DISAMBIGUATION_RULES.indexOf(arg) > -1) {\n        state.citation.opt[\"givenname-disambiguation-rule\"] = arg;\n    }\n};\n\nCSL.Attributes[\"@collapse\"] = function (state, arg) {\n    // only one collapse value will be honoured.\n    if (arg) {\n        state[this.name].opt.collapse = arg;\n    }\n};\n\nCSL.Attributes[\"@cite-group-delimiter\"] = function (state, arg) {\n    if (arg) {\n        state[state.tmp.area].opt.cite_group_delimiter = arg;\n    }\n};\n\n\n\nCSL.Attributes[\"@names-delimiter\"] = function (state, arg) {\n    state.setOpt(this, \"names-delimiter\", arg);\n};\n\nCSL.Attributes[\"@name-form\"] = function (state, arg) {\n    state.setOpt(this, \"name-form\", arg);\n};\n\nCSL.Attributes[\"@subgroup-delimiter\"] = function (state, arg) {\n    this.strings[\"subgroup-delimiter\"] = arg;\n};\n\nCSL.Attributes[\"@subgroup-delimiter-precedes-last\"] = function (state, arg) {\n    this.strings[\"subgroup-delimiter-precedes-last\"] = arg;\n};\n\n\nCSL.Attributes[\"@name-delimiter\"] = function (state, arg) {\n    state.setOpt(this, \"name-delimiter\", arg);\n};\n\nCSL.Attributes[\"@et-al-min\"] = function (state, arg) {\n    var val = parseInt(arg, 10);\n    if (state[state.build.area].opt.max_number_of_names < val) {\n        state[state.build.area].opt.max_number_of_names = val;\n    }\n    state.setOpt(this, \"et-al-min\", val);\n};\n\nCSL.Attributes[\"@et-al-use-first\"] = function (state, arg) {\n    state.setOpt(this, \"et-al-use-first\", parseInt(arg, 10));\n};\n\nCSL.Attributes[\"@et-al-use-last\"] = function (state, arg) {\n    if (arg === \"true\") {\n        state.setOpt(this, \"et-al-use-last\", true);\n    } else {\n        state.setOpt(this, \"et-al-use-last\", false);\n    }\n};\n\nCSL.Attributes[\"@et-al-subsequent-min\"] = function (state, arg) {\n    var val = parseInt(arg, 10);\n    if (state[state.build.area].opt.max_number_of_names < val) {\n        state[state.build.area].opt.max_number_of_names = val;\n    }\n    state.setOpt(this, \"et-al-subsequent-min\", val);\n};\n\nCSL.Attributes[\"@et-al-subsequent-use-first\"] = function (state, arg) {\n    state.setOpt(this, \"et-al-subsequent-use-first\", parseInt(arg, 10));\n};\n\nCSL.Attributes[\"@suppress-min\"] = function (state, arg) {\n    this.strings[\"suppress-min\"] = parseInt(arg, 10);\n};\n\nCSL.Attributes[\"@suppress-max\"] = function (state, arg) {\n    this.strings[\"suppress-max\"] = parseInt(arg, 10);\n};\n\n\nCSL.Attributes[\"@and\"] = function (state, arg) {\n    state.setOpt(this, \"and\", arg);\n};\n\nCSL.Attributes[\"@delimiter-precedes-last\"] = function (state, arg) {\n    state.setOpt(this, \"delimiter-precedes-last\", arg);\n};\n\nCSL.Attributes[\"@delimiter-precedes-et-al\"] = function (state, arg) {\n    state.setOpt(this, \"delimiter-precedes-et-al\", arg);\n};\n\nCSL.Attributes[\"@initialize-with\"] = function (state, arg) {\n    state.setOpt(this, \"initialize-with\", arg);\n};\n\nCSL.Attributes[\"@initialize\"] = function (state, arg) {\n    if (arg === \"false\") {\n        state.setOpt(this, \"initialize\", false);\n    }\n};\n\nCSL.Attributes[\"@name-as-reverse-order\"] = function (state, arg) {\n    this[\"name-as-reverse-order\"] = arg;\n};\n\nCSL.Attributes[\"@name-as-sort-order\"] = function (state, arg) {\n    if (this.name === \"style-options\") {\n        this[\"name-as-sort-order\"] = arg;\n    } else {\n        state.setOpt(this, \"name-as-sort-order\", arg);\n    }\n};\n\nCSL.Attributes[\"@sort-separator\"] = function (state, arg) {\n    state.setOpt(this, \"sort-separator\", arg);\n};\n\nCSL.Attributes[\"@require-match\"] = function (state, arg) {\n    if (arg === \"true\") {\n        this.requireMatch = true;\n    }\n};\n\nCSL.Attributes[\"@exclude-types\"] = function (state, arg) {\n    state.bibliography.opt.exclude_types = arg.split(/\\s+/);\n};\n\nCSL.Attributes[\"@exclude-with-fields\"] = function (state, arg) {\n    state.bibliography.opt.exclude_with_fields = arg.split(/\\s+/);\n};\n\n\nCSL.Attributes[\"@year-suffix-delimiter\"] = function (state, arg) {\n    state[this.name].opt[\"year-suffix-delimiter\"] = arg;\n};\n\nCSL.Attributes[\"@after-collapse-delimiter\"] = function (state, arg) {\n    state[this.name].opt[\"after-collapse-delimiter\"] = arg;\n};\n\nCSL.Attributes[\"@subsequent-author-substitute\"] = function (state, arg) {\n    state[this.name].opt[\"subsequent-author-substitute\"] = arg;\n};\n\nCSL.Attributes[\"@subsequent-author-substitute-rule\"] = function (state, arg) {\n    state[this.name].opt[\"subsequent-author-substitute-rule\"] = arg;\n};\n\nCSL.Attributes[\"@disambiguate-add-names\"] = function (state, arg) {\n    if (arg === \"true\") {\n        state.opt[\"disambiguate-add-names\"] = true;\n    }\n};\n\nCSL.Attributes[\"@disambiguate-add-givenname\"] = function (state, arg) {\n    if (arg === \"true\") {\n        state.opt[\"disambiguate-add-givenname\"] = true;\n    }\n};\n\nCSL.Attributes[\"@disambiguate-add-year-suffix\"] = function (state, arg) {\n    if (arg === \"true\" && state.opt.xclass !== \"numeric\") {\n        state.opt[\"disambiguate-add-year-suffix\"] = true;\n    }\n};\n\n\nCSL.Attributes[\"@second-field-align\"] = function (state, arg) {\n    if (arg === \"flush\" || arg === \"margin\") {\n        state[this.name].opt[\"second-field-align\"] = arg;\n    }\n};\n\n\nCSL.Attributes[\"@hanging-indent\"] = function (state, arg) {\n    if (arg === \"true\") {\n        if (state.opt.development_extensions.hanging_indent_legacy_number) {\n            state[this.name].opt.hangingindent = 2;\n\t    } else {\n            state[this.name].opt.hangingindent = true;\n\t    }\n    }\n};\n\n\nCSL.Attributes[\"@line-spacing\"] = function (state, arg) {\n    if (arg && arg.match(/^[.0-9]+$/)) {\n        state[this.name].opt[\"line-spacing\"] = parseFloat(arg, 10);\n    }\n};\n\n\nCSL.Attributes[\"@entry-spacing\"] = function (state, arg) {\n    if (arg && arg.match(/^[.0-9]+$/)) {\n        state[this.name].opt[\"entry-spacing\"] = parseFloat(arg, 10);\n    }\n};\n\n\nCSL.Attributes[\"@near-note-distance\"] = function (state, arg) {\n    state[this.name].opt[\"near-note-distance\"] = parseInt(arg, 10);\n};\n\nCSL.Attributes[\"@substring\"] = function (state, arg) {\n    this.substring = parseInt(arg, 10);\n};\n\nCSL.Attributes[\"@text-case\"] = function (state, arg) {\n    var func = function (state, Item) {\n        if (arg === \"normal\") {\n            this.text_case_normal = true;\n        } else {\n            this.strings[\"text-case\"] = arg;\n            if (arg === \"title\") {\n                if (Item.jurisdiction) {\n                    this.strings[\"text-case\"] = \"passthrough\";\n                }\n            }\n        }\n    };\n    this.execs.push(func);\n};\n\n\nCSL.Attributes[\"@page-range-format\"] = function (state, arg) {\n    state.opt[\"page-range-format\"] = arg;\n};\n\n\nCSL.Attributes[\"@year-range-format\"] = function (state, arg) {\n    state.opt[\"year-range-format\"] = arg;\n};\n\n\nCSL.Attributes[\"@default-locale\"] = function (state, arg) {\n    if (this.name === 'style') {\n        var lst, len, pos, m, ret;\n        //\n        // Workaround for Internet Exploder 6 (doesn't recognize\n        // groups in str.split(/something(braced-group)something/)\n        //\n        var m = arg.match(/-x-(sort|translit|translat)-/g);\n        if (m) {\n            for (pos = 0, len = m.length; pos < len; pos += 1) {\n                m[pos] = m[pos].replace(/^-x-/, \"\").replace(/-$/, \"\");\n            }\n        }\n        lst = arg.split(/-x-(?:sort|translit|translat)-/);\n        ret = [lst[0]];\n        for (pos = 1, len = lst.length; pos < len; pos += 1) {\n            ret.push(m[pos - 1]);\n            ret.push(lst[pos]);\n        }\n        lst = ret.slice();\n        len = lst.length;\n        for (pos = 1; pos < len; pos += 2) {\n            state.opt[(\"locale-\" + lst[pos])].push(lst[(pos + 1)].replace(/^\\s*/g, \"\").replace(/\\s*$/g, \"\"));\n        }\n        if (lst.length) {\n            state.opt[\"default-locale\"] = lst.slice(0, 1);\n        } else {\n            state.opt[\"default-locale\"] = [\"en\"];\n        }\n    } else if (arg === \"true\") {\n        this.default_locale = true;\n    }\n};\n\nCSL.Attributes[\"@default-locale-sort\"] = function (state, arg) {\n    state.opt[\"default-locale-sort\"] = arg;\n};\n\nCSL.Attributes[\"@demote-non-dropping-particle\"] = function (state, arg) {\n    state.opt[\"demote-non-dropping-particle\"] = arg;\n};\n\nCSL.Attributes[\"@initialize-with-hyphen\"] = function (state, arg) {\n    if (arg === \"false\") {\n        state.opt[\"initialize-with-hyphen\"] = false;\n    }\n};\n\nCSL.Attributes[\"@institution-parts\"] = function (state, arg) {\n    this.strings[\"institution-parts\"] = arg;\n};\n\nCSL.Attributes[\"@if-short\"] = function (state, arg) {\n    if (arg === \"true\") {\n        this.strings[\"if-short\"] = true;\n    }\n};\n\nCSL.Attributes[\"@substitute-use-first\"] = function (state, arg) {\n    this.strings[\"substitute-use-first\"] = parseInt(arg, 10);\n};\n\nCSL.Attributes[\"@use-first\"] = function (state, arg) {\n    this.strings[\"use-first\"] = parseInt(arg, 10);\n};\n\nCSL.Attributes[\"@use-last\"] = function (state, arg) {\n    this.strings[\"use-last\"] = parseInt(arg, 10);\n};\n\nCSL.Attributes[\"@stop-first\"] = function (state, arg) {\n    this.strings[\"stop-first\"] = parseInt(arg, 10);\n};\n\nCSL.Attributes[\"@stop-last\"] = function (state, arg) {\n    this.strings[\"stop-last\"] = parseInt(arg, 10) * -1;\n};\n\n\nCSL.Attributes[\"@reverse-order\"] = function (state, arg) {\n    if (\"true\" === arg) {\n        this.strings[\"reverse-order\"] = true;\n    }\n};\n\nCSL.Attributes[\"@display\"] = function (state, arg) {\n    if (state.bibliography.tokens.length === 2) {\n        state.opt.using_display = true;\n    }\n    this.strings.cls = arg;\n};\n\n\n/*global CSL: true */\n\n\n/**\n * String stack object.\n * <p>Numerous string stacks are used to track nested\n * parameters at runtime.  This class provides methods\n * that remove some of the aggravation of managing\n * them.</p>\n * @class\n */\nCSL.Stack = function (val, literal) {\n    this.mystack = [];\n    if (literal || val) {\n        this.mystack.push(val);\n    }\n    this.tip = this.mystack[0];\n};\n\n/**\n * Push a value onto the stack.\n * <p>This just does what it says.</p>\n */\nCSL.Stack.prototype.push = function (val, literal) {\n    if (literal || val) {\n        this.mystack.push(val);\n    } else {\n        this.mystack.push(\"\");\n    }\n    this.tip = this.mystack[this.mystack.length - 1];\n};\n\n/**\n * Clear the stack\n */\nCSL.Stack.prototype.clear = function () {\n    this.mystack = [];\n    this.tip = {};\n};\n\n/**\n * Replace the top value on the stack.\n * <p>This removes some ugly syntax from the\n * main code.</p>\n */\nCSL.Stack.prototype.replace = function (val, literal) {\n    //\n    // safety fix after a bug was chased down.  Rhino\n    // JS will process a negative index without error (!).\n    if (this.mystack.length === 0) {\n        CSL.error(\"Internal CSL processor error: attempt to replace nonexistent stack item with \" + val);\n    }\n    if (literal || val) {\n        this.mystack[(this.mystack.length - 1)] = val;\n    } else {\n        this.mystack[(this.mystack.length - 1)] = \"\";\n    }\n    this.tip = this.mystack[this.mystack.length - 1];\n};\n\n\n/**\n * Remove the top value from the stack.\n * <p>Just does what it says.</p>\n */\nCSL.Stack.prototype.pop = function () {\n    var ret = this.mystack.pop();\n    if (this.mystack.length) {\n        this.tip = this.mystack[this.mystack.length - 1];\n    } else {\n        this.tip = {};\n    }\n    return ret;\n};\n\n\n/**\n * Return the top value on the stack.\n * <p>Removes a little hideous complication from\n * the main code.</p>\n */\nCSL.Stack.prototype.value = function () {\n    return this.mystack.slice(-1)[0];\n};\n\n\n/**\n * Return length (depth) of stack.\n * <p>Used to identify if there is content to\n * be handled on the stack</p>\n */\nCSL.Stack.prototype.length = function () {\n    return this.mystack.length;\n};\n\n/*global CSL: true */\n\n/**\n * Initializes the parallel cite tracking arrays\n */\nCSL.Parallel = function (state) {\n    this.state = state;\n};\n\nCSL.Parallel.prototype.StartCitation = function (sortedItems, out) {\n    // This array carries the repeat markers used in rendering the cite.\n    this.state.tmp.suppress_repeats = [];\n    if (sortedItems.length < 2) return;\n    var idxEnd = 0;\n    var parallelMatchList = false;\n    var siblingRanges = [];\n\n    for (var i=0,ilen=sortedItems.length-1;i<ilen;i++) {\n        var currItem = sortedItems[i][0];\n        var nextItem = sortedItems[i+1][0];\n        var freshMatchList = false;\n        var info = {};\n        if (sortedItems[i][0].seeAlso && sortedItems[i][0].seeAlso.length > 0 && !parallelMatchList) {\n            freshMatchList = true;\n            parallelMatchList = [sortedItems[i][0].id].concat(sortedItems[i][0].seeAlso);\n            var tempMatchList = parallelMatchList.slice();\n            var remainder = sortedItems.slice(i);\n            remainder[0][1].parallel = \"first\";\n            for (var j=0,jlen=remainder.length;j<jlen;j++) {\n                var itemID = remainder[j][0].id;\n                var ididx = tempMatchList.indexOf(itemID);\n                idxEnd = false;\n                if (ididx === -1) {\n                    idxEnd = (i+j-1);\n                } else if ((i+j) === (sortedItems.length-1)) {\n                    idxEnd = (i+j);\n                }\n                if (idxEnd) {\n                    siblingRanges.push([i, idxEnd]);\n                    break;\n                } else {\n                    tempMatchList = tempMatchList.slice(0, ididx).concat(tempMatchList.slice(ididx+1));\n                }\n            }\n        }\n        // parallelMatchList/freshMatchList relate only to parallels.\n        // no-repeat non-parallels are handled in a separate block.\n        if (i > 0 && freshMatchList) {\n            this.state.tmp.suppress_repeats[i-1].START = true;\n            freshMatchList = false;\n        }\n        for (var varname in this.state.opt.track_repeat) {\n            if (!currItem[varname] || !nextItem[varname]) {\n                // Go ahead and render any value with an empty partner\n                info[varname] = false;\n            } else if (\"string\" === typeof nextItem[varname] || \"number\" === typeof nextItem[varname]) {\n                // Simple comparison of string values\n                if (varname === \"title\" && currItem[\"title-short\"] && nextItem[\"title-short\"]) {\n                    var currVal = currItem[\"title-short\"];\n                    var nextVal = nextItem[\"title-short\"];\n                } else {\n                    var currVal = currItem[varname];\n                    var nextVal = nextItem[varname];\n                }\n                if (currVal == nextVal) {\n                    info[varname] = true;\n                } else {\n                    info[varname] = false;\n                }\n            } else if (\"undefined\" === typeof currItem[varname].length) {\n                // If a date, use only the year\n                info[varname] = false;\n                var currYear = currItem[varname].year;\n                var nextYear = nextItem[varname].year;\n                if (currYear && nextYear) {\n                    if (currYear == nextYear) {\n                        info[varname] = true;\n                    }\n                }\n            } else {\n                // If a creator value, kludge it\n                var currVal = JSON.stringify(currItem[varname]);\n                var nextVal = JSON.stringify(nextItem[varname]);\n                if (currVal === nextVal) {\n                    info[varname] = true;\n                } else {\n                    info[varname] = false;\n                }\n            }\n        }\n        if (!parallelMatchList) {\n            info.ORPHAN = true;\n        }\n        if (idxEnd === i) {\n            info.END = true;\n            parallelMatchList = false;\n        }\n        this.state.tmp.suppress_repeats.push(info);\n    }\n    \n    // if (!this.state.tmp.just_looking) {\n    //     this.state.sys.print(`${JSON.stringify(this.state.tmp.suppress_repeats, null, 2)}`);\n    // }\n    \n    // Set no-repeat info here?\n    for (var j=0,jlen=siblingRanges.length;j<jlen;j++) {\n        var masterID = sortedItems[siblingRanges[j][0]][0].id;\n        this.state.registry.registry[masterID].master = true;\n        this.state.registry.registry[masterID].siblings = [];\n        var start = siblingRanges[j][0];\n        var end = siblingRanges[j][1];\n        for (var k=start; k<end; k++) {\n            this.state.tmp.suppress_repeats[k].SIBLING = true;\n            var siblingID = sortedItems[k+1][0].id;\n            sortedItems[k+1][1].parallel = \"other\";\n            this.state.registry.registry[masterID].siblings.push(siblingID);\n        }\n    }\n    // this.state.sys.print(JSON.stringify(this.state.tmp.suppress_repeats, null, 2));\n};\n\nCSL.Parallel.prototype.checkRepeats = function(params) {\n    var idx = this.state.tmp.cite_index;\n    if (this.state.tmp.suppress_repeats) {\n        if (params.parallel_first && Object.keys(params.parallel_first).length > 0) {\n            var arr = [{}].concat(this.state.tmp.suppress_repeats);\n            var ret = true;\n            for (var varname in params.parallel_first) {\n                if (!arr[idx][varname] || arr[idx].START) {\n                    // true --> suppress the entry\n                    // Test here evaluates as \"all\", not \"any\"\n                    ret = false;\n                }\n            }\n            return ret;\n        }\n        if (params.parallel_last && Object.keys(params.parallel_last).length > 0) {\n            var arr = this.state.tmp.suppress_repeats.concat([{}]);\n            var ret = Object.keys(params.parallel_last).length > 0 ? true : false;\n            for (var varname in params.parallel_last) {\n                if (!arr[idx][varname] || arr[idx].END) {\n                    // \"all\" match, as above.\n                    ret = false;\n                }\n            }\n            return ret;\n        }\n        if (params.non_parallel && Object.keys(params.non_parallel).length > 0) {\n            var arr = [{}].concat(this.state.tmp.suppress_repeats);\n            var ret = true;\n            for (var varname in params.non_parallel) {\n                if (!arr[idx][varname]) {\n                    ret = false;\n                }\n            }\n            return ret;\n        }\n    }\n    return false;\n};\n\n/*global CSL: true */\n\n\nCSL.Util = {};\n\nCSL.Util.Match = function () {\n\n    this.any = function (token, state, tests) {\n        return function (Item, item) {\n            for (var i=0, ilen=tests.length; i < ilen; i += 1) {\n                var result = tests[i](Item, item);\n                if (result) {\n                    return true;\n                }\n            }\n            return false;\n        };\n    };\n\n    this.none = function (token, state, tests) {\n        return function (Item, item) {\n            for (var i=0,ilen=tests.length;i<ilen;i+=1) {\n                var result = tests[i](Item,item);\n                if (result) {\n                    return false;\n                }\n            }\n            return true;\n        };\n    };\n\n    this.all = function (token, state, tests) {\n        return function (Item, item) {\n            for (var i=0,ilen=tests.length;i<ilen;i+=1) {\n                var result = tests[i](Item,item);\n                if (!result) {\n                    return false;\n                }\n            }\n            return true;\n        };\n    };\n\n    this[undefined] = this.all;\n\n    this.nand = function (token, state, tests) {\n        return function (Item, item) {\n            for (var i=0,ilen=tests.length;i<ilen;i+=1) {\n                var result = tests[i](Item,item);\n                if (!result) {\n                    return true;\n                }\n            }\n            return false;\n        };\n    };\n\n};\n\n/*global CSL: true */\n\n/*\n * Fields can be transformed by translation/transliteration, or by\n * abbreviation.  Transformations are performed in that order.\n *\n * Renderings of original, translated or transliterated content\n * (followed by abbreviation if requested) are placed in the primary\n * output slot or the (implicitly punctuated) secondary and tertiary\n * output slots according to the settings registered in the\n * state.opt['cite-lang-prefs'] arrays. The array has six segments:\n * 'persons', 'institutions', 'titles', 'journals', 'publishers', and\n * 'places'. Each segment always contains at least one item, and may\n * hold values 'orig', 'translit' or 'translat'. The array defaults to\n * a single item 'orig'.\n *\n * All multilingual variables are associated with segments,\n * with the exception of 'edition' and 'genre'. These two\n * exceptions are always rendered with the first matching\n * language form found in state.opt['locale-translit'] or, if\n * composing a sort key, state.opt['locale-sort']. No secondary\n * slot rendering is performed for this two variables.\n *\n * The balance of multilingual variables are rendered with\n * the first matching value in the transform locales spec\n * (no transform, state.opt['locale-translit'], or \n * state.opt['locale-translat']) mapped to the target\n * slot.\n *\n * Full primary+secondary+tertiary rendering is performed only in\n * note-style citations and the bibliography.  In-text citations are\n * rendered in the primary output slot only, following the same spec\n * parameters.\n *\n *   Optional setters:\n *     .setAbbreviationFallback(); fallback flag\n *       (if true, a failed abbreviation will fallback to long)\n *\n *     .setAlternativeVariableName(): alternative variable name in Item,\n *       for use as a fallback abbreviation source\n *\n * Translation/transliteration\n *\n *   Optional setter:\n *     .setTransformFallback():\n *       default flag (if true, the original field value will be used as a fallback)\n *\n * The getTextSubField() method may be used to obtain a string transform\n * of a field, without abbreviation, as needed for setting sort keys\n * (for example).\n *\n */\n\nCSL.Transform = function (state) {\n    // Abbreviation families\n    this.abbrevs = {};\n    this.abbrevs[\"default\"] = new state.sys.AbbreviationSegments();\n\n    function getCountryOrJurisdiction(variable, normalizedKey, quashCountry) {\n        var value = \"\";\n        if (state.sys.getHumanForm) {\n            if (variable === \"country\") {\n                value = state.sys.getHumanForm(normalizedKey.toLowerCase(), false, true);\n                value = value.split(\"|\")[0];\n            } else if (variable === \"jurisdiction\") {\n                value = state.sys.getHumanForm(normalizedKey.toLowerCase(), false, true);\n                if (!quashCountry) {\n                    value = value.split(\"|\").slice(1).join(\", \");\n                } else {\n                    // Bare country name is rendered by \"country\", not \"jurisdiction\"\n                    value = \"\";\n                }\n            }\n\t    }\n\t    return value;\n    }\n    \n    // Internal function\n    function abbreviate(state, tok, Item, altvar, basevalue, family_var, use_field) {\n\n        var value = \"\";\n        var myabbrev_family = CSL.FIELD_CATEGORY_REMAP[family_var];\n        var preferredJurisdiction;\n        if (!myabbrev_family) {\n            return basevalue;\n        }\n\n        var variable = family_var;\n        var normalizedKey = basevalue;\n\n        if (state.sys.normalizeAbbrevsKey) {\n            normalizedKey = state.sys.normalizeAbbrevsKey(family_var, basevalue);\n        }\n        var quashCountry = false;\n        if (variable === \"jurisdiction\" && normalizedKey) {\n            quashCountry = normalizedKey.indexOf(\":\") === -1;\n        }\n        // Fix up jurisdiction codes\n        if ([\"jurisdiction\", \"country\"].indexOf(family_var) > -1 && basevalue === basevalue.toLowerCase()) {\n            normalizedKey = basevalue.toUpperCase();\n        }\n        \n        \n        // Lazy retrieval of abbreviations.\n        if (state.sys.getAbbreviation) {\n\n            if ([\"jurisdiction\", \"country\", \"language-name\", \"language-name-original\"].indexOf(variable) > -1) {\n                preferredJurisdiction = \"default\";\n            } else if (Item.jurisdiction) {\n                preferredJurisdiction = Item.jurisdiction;\n            } else {\n                preferredJurisdiction = \"default\";\n            }\n            var jurisdiction = state.transform.loadAbbreviation(preferredJurisdiction, myabbrev_family, normalizedKey, Item.language);\n\n            // Some rules:\n            // # variable === \"country\"\n            // (1) If an abbreviation is associated with the code, then:\n            //     (a) return the abbreviated form if form=\"short\"\n            // (2) Otherwise:\n            //     (a) return the human-readable country name, or whatever is there if it's not a code\n            // # variable === \"jurisdiction\"\n            // (1) If !!getHumanForm(jurisdictionID, false, false):\n            //     (a) If the code is top-level (i.e. a country):\n            //         (i) return nothing -- this is what the \"country\" variable is for.\n            //     (b) otherwise:\n            //         (i) If an abbreviation is associated with the code, then:\n            //             (A) return the abbreviated form\n            //         (ii) Otherwise\n            //             (A) return the human-readable form, with the country name & code removed from the front\n            // (2) Otherwise:\n            //     (a) abbreviate as per normal.\n            // # other variables\n            // (1) Abbreviate as per normal.\n\n            if (state.transform.abbrevs[jurisdiction][myabbrev_family] && normalizedKey) {\n                // Safe to test presence of abbrev against raw object in this block\n                var abbrev = state.transform.abbrevs[jurisdiction][myabbrev_family][normalizedKey];\n                if (tok.strings.form === \"short\" && abbrev) {\n                    if (quashCountry) {\n                        value = \"\";\n                    } else {\n                        value = abbrev;\n                    }\n                } else {\n\t                value = getCountryOrJurisdiction(variable, normalizedKey, quashCountry);\n                }\n            }\n        }\n        \n        // Was for: \n        if (!value \n            && (!state.opt.development_extensions.require_explicit_legal_case_title_short || Item.type !== 'legal_case') \n            && altvar && Item[altvar] && use_field) {\n            value = Item[altvar];\n        }\n        if (!value && !state.sys.getAbbreviation && state.sys.getHumanForm) {\n\t        value = getCountryOrJurisdiction(variable, normalizedKey, quashCountry);\n\t    }\n        if (!value && !quashCountry && (!state.sys.getHumanForm || variable !== \"jurisdiction\")) {\n            value = basevalue;\n        }\n        if (state.opt.development_extensions.force_title_abbrev_fallback) {\n            if (variable === \"title\" && value === basevalue && Item[\"title-short\"]) {\n                value = Item[\"title-short\"];\n            }\n        }\n        return value;\n    }\n\n    function getFieldLocale(Item,field) {\n        var ret = state.opt[\"default-locale\"][0].slice(0, 2);\n        var localeRex;\n        if (state.opt.development_extensions.strict_text_case_locales) {\n            localeRex = new RegExp(\"^([a-zA-Z]{2})(?:$|-.*| .*)\");\n        } else {\n            localeRex = new RegExp(\"^([a-zA-Z]{2})(?:$|-.*|.*)\");\n        }\n        if (Item.language) {\n            var m = (\"\" + Item.language).match(localeRex);\n            if (m) {\n                ret = m[1];\n            } else {\n                // Set garbage to \"Klingon\".\n                ret = \"tlh\";\n            }\n        }\n        if (Item.multi && Item.multi && Item.multi.main && Item.multi.main[field]) {\n            ret = Item.multi.main[field];\n        }\n        if (!state.opt.development_extensions.strict_text_case_locales\n            || state.opt.development_extensions.normalize_lang_keys_to_lowercase) {\n\n            ret = ret.toLowerCase();\n        }\n        return ret;\n    }\n\n    // Internal functions\n    function getTextSubField (Item, field, locale_type, use_default, stopOrig, family_var) {\n        var opt, o, ret, opts;\n        var usedOrig = stopOrig;\n        var usingOrig = false;\n\n        if (!Item[field]) {\n            return {\n                name:\"\",\n                usedOrig:stopOrig,\n                token: CSL.Util.cloneToken(this)\n            };\n        }\n        // If form=\"short\" is selected (\"family_var\" is a misnomer\n        // here, it means short-form requested), and the variable\n        // has a short-form partner (i.e. it is in array\n        // VARIABLES_WITH_SHORT_FORM), then it is run here as *-short\".\n        var stickyLongForm = false;\n        if (CSL.VARIABLES_WITH_SHORT_FORM.indexOf(field) > -1\n            && family_var) {\n\n            field = field + \"-short\";\n            stickyLongForm = true;\n        }\n        var breakMe = false;\n        var firstValue = null;\n        var fieldsToTry = [];\n        if (field.slice(-6) === \"-short\") {\n            fieldsToTry.push(field);\n            fieldsToTry.push(field.slice(0, -6))\n        } else {\n            fieldsToTry.push(field);\n        }\n\n        for (var h=0,hlen=fieldsToTry.length; h<hlen; h++) {\n            var variantMatch = false;\n            var field = fieldsToTry[h];\n\n            ret = {name:\"\", usedOrig:stopOrig,locale:getFieldLocale(Item,field)};\n\n            opts = state.opt[locale_type] ? state.opt[locale_type].slice() : [];\n            var hasVal = false;\n\n            if (locale_type === 'locale-orig') {\n                if (!stopOrig) {\n                    ret.name = Item[field];\n                    ret.usedOrig = false;\n                }\n                hasVal = true;\n                usingOrig = true;\n            } else if (use_default && (\"undefined\" === typeof opts || opts.length === 0)) {\n                // If we want the original, or if we don't have any specific guidance and we \n                // definitely want output, just return the original value.\n                ret.name = Item[field];\n                ret.usedOrig = true;\n                hasVal = true;\n                usingOrig = true;\n            }\n\n            if (!hasVal) {\n                for (var i = 0, ilen = opts.length; i < ilen; i += 1) {\n                    opt = opts[i];\n                    o = opt.split(/[\\-_]/)[0];\n                    if (opt && Item.multi && Item.multi._keys[field] && Item.multi._keys[field][opt]) {\n                        ret.name = Item.multi._keys[field][opt];\n                        ret.locale = opt;\n                        hasVal = true;\n                        variantMatch = true;\n                        usingOrig = false;\n                        break;\n                    } else if (o && Item.multi && Item.multi._keys[field] && Item.multi._keys[field][o]) {\n                        ret.name = Item.multi._keys[field][o];\n                        ret.locale = o;\n                        hasVal = true;\n                        variantMatch = true;\n                        usingOrig = false;\n                        break;\n                    }\n                }\n                if (!ret.name && use_default) {\n                    ret = {name:Item[field], usedOrig:true, locale:getFieldLocale(Item,field)};\n                    usingOrig = true;\n                }\n            }\n            ret.token = CSL.Util.cloneToken(this);\n            if (h === 0) {\n                if (variantMatch) {\n                    ret.found_variant_ok = true;\n                }\n                firstValue = ret;\n                if (!stickyLongForm && (\"undefined\" === typeof opts || opts.length === 0)) {\n                    breakMe = true;\n                }\n                if (variantMatch) {\n                    breakMe = true;\n                }\n            } else {\n                if (!stickyLongForm && !variantMatch && firstValue) {\n                    ret = firstValue;\n                    field = fieldsToTry[0];\n                } else if (variantMatch) {\n                    ret.found_variant_ok = true;\n                }\n            }\n            if ([\"title\", \"container-title\"].indexOf(field) > -1) {\n                if (!usedOrig\n                    && (!ret.token.strings[\"text-case\"]\n                        || ret.token.strings[\"text-case\"] === \"sentence\"\n                        || ret.token.strings[\"text-case\"] === \"normal\")) {\n                    var locale = state.opt.lang;\n                    var lang;\n                    if (usingOrig) {\n                        lang = false;\n                    } else {\n                        lang = ret.locale;\n                    }\n                    var seg = field.slice(0,-5);\n                    var sentenceCase = ret.token.strings[\"text-case\"] === \"sentence\" ? true : false;\n                    ret.name = CSL.titlecaseSentenceOrNormal(state, Item, seg, lang, sentenceCase);\n                    delete ret.token.strings[\"text-case\"];\n                }\n            }\n            if (breakMe) {\n                break;\n            }\n        }\n        return ret;\n    }\n    this.getTextSubField = getTextSubField;\n    \n    // Setter for abbreviation lists\n    // This initializes a single abbreviation based on known\n    // data.\n    function loadAbbreviation(jurisdiction, category, orig, lang) {\n        if (!jurisdiction) {\n            jurisdiction = \"default\";\n        }\n        var country = jurisdiction.split(\":\")[0];\n        var domain = CSL.getAbbrevsDomain(state, country, lang);\n        if (domain) {\n            jurisdiction += (\"@\" + domain);\n        }\n        if (!orig) {\n            if (!state.transform.abbrevs[jurisdiction]) {\n                state.transform.abbrevs[jurisdiction] = new state.sys.AbbreviationSegments();\n            }\n            if (!state.transform.abbrevs[jurisdiction][category]) {\n                state.transform.abbrevs[jurisdiction][category] = {};\n            }\n            return jurisdiction;\n        }\n        // The getAbbreviation() function should check the\n        // external DB for the content key. If a value exists\n        // in this[category] and no value exists in DB, the entry\n        // in memory is left untouched. If a value does exist in\n        // DB, the memory value is created.\n        //\n        // See testrunner_stdrhino.js for an example.\n        if (state.sys.getAbbreviation) {\n            jurisdiction = state.sys.getAbbreviation(state.opt.styleID, state.transform.abbrevs, jurisdiction, category, orig);\n            if (!jurisdiction) {\n                jurisdiction = \"default\";\n                if (domain) {\n                    jurisdiction += (\"@\" + domain);\n                }\n            }\n        }\n        return jurisdiction;\n    }\n    this.loadAbbreviation = loadAbbreviation;\n\n    function publisherCheck (tok, Item, primary, family_var) {\n        var varname = tok.variables[0];\n        if (state.publisherOutput && primary) {\n            if ([\"publisher\",\"publisher-place\"].indexOf(varname) === -1) {\n                return false;\n            } else {\n                // In this case, the publisher bundle will be rendered\n                // at the close of the group, by the closing group node.\n                state.publisherOutput[varname + \"-token\"] = tok;\n                state.publisherOutput.varlist.push(varname);\n                var lst = primary.split(/;\\s*/);\n                if (lst.length === state.publisherOutput[varname + \"-list\"].length) {\n                    state.publisherOutput[varname + \"-list\"] = lst;\n                }\n                // Abbreviate each of the items in the list here!\n                for (var i = 0, ilen = lst.length; i < ilen; i += 1) {\n                    lst[i] = abbreviate(state, tok, Item, false, lst[i], family_var, true);\n                }\n                state.tmp[varname + \"-token\"] = tok;\n                return true;\n            }\n        }\n        return false;\n    }\n\n    function citeFormCheck(Item, value) {\n        var m = value.match(/^#([0-9]+).*>>>/);\n        if (m && m[1]) {\n            Item[\"cite-form\"] = m[1];\n        }\n    }\n    \n    // The name transform code is placed here to keep similar things\n    // in one place.  Obviously this module could do with a little\n    // tidying up.\n    function quashCheck(jurisdiction, value) {\n        var m = value.match(/^(?:#[0-9]+)*(?:!((?:[-_a-z]+(?:(?:.*)))(?:,(?:[-_a-z]+(?:(?:.*))))*))*>>>/);\n        if (m) {\n            value = value.slice(m[0].length);\n            if (m[1]) {\n                var fields = m[1].split(\",\");\n                for (var i = 0, ilen = fields.length; i < ilen; i += 1) {\n                    var rawField = fields[i];\n                    var mm = rawField.match(/^([-_a-z]+)(?:\\:(.*))*$/);\n                    var field = mm[1];\n                    // trimmer is not available in getAmbiguousCite\n                    var trimmer = state.tmp.abbrev_trimmer;\n                    if (mm[2]) {\n                        if (trimmer && jurisdiction) {\n                            if (!trimmer[jurisdiction]) {\n                                trimmer[jurisdiction] = {};\n                            }\n                            trimmer[jurisdiction][field] = mm[2];\n                        }\n                    } else if (state.tmp.done_vars.indexOf(field) === -1) {\n                        if (trimmer && jurisdiction) {\n                            if (!trimmer.QUASHES[jurisdiction]) {\n                                trimmer.QUASHES[jurisdiction] = {};\n                            }\n                            trimmer.QUASHES[jurisdiction][field] = true;\n                        }\n                        state.tmp.done_vars.push(field);\n                    }\n                }\n            }\n        }\n        return value;\n    }\n    this.quashCheck = quashCheck;\n\n    // Return function appropriate to selected options\n    function getOutputFunction(variables, family_var, abbreviation_fallback, alternative_varname) {\n        // var mytoken;\n\n        // Set the primary_locale and secondary_locale lists appropriately.\n        // No instance helper function for this; everything can be derived\n        // from processor settings and rendering context.\n\n        var localesets;\n        var langPrefs = CSL.LangPrefsMap[variables[0]];\n        if (!langPrefs) {\n            localesets = false;\n        } else {\n            localesets = state.opt['cite-lang-prefs'][langPrefs];\n        }\n\n        return function (state, Item, item) {\n            var primary, primary_locale, secondary, secondary_locale, tertiary, tertiary_locale, primary_tok;\n            if (!variables[0] || (!Item[variables[0]] && !Item[alternative_varname])) {\n                return null;\n            }\n            //\n            // Exploring the edges here.\n            // \"suppress-author\" for string variables (mostly titles).\n            //\n            if (!state.tmp.just_looking && item && item[\"suppress-author\"]) {\n                if (!state.tmp.probably_rendered_something && state.tmp.can_substitute.length() > 1) {\n                    return null;\n                }\n            }\n            var slot = {primary:false, secondary:false, tertiary:false};\n            if (state.tmp.area.slice(-5) === \"_sort\") {\n                slot.primary = 'locale-sort';\n            } else {\n                if (localesets && localesets.length === 1 && localesets[0] === \"locale-orig\") {\n                    slot.primary = \"locale-orig\";\n                    localesets = false;\n                } else if (localesets && !state.tmp.multi_layout) {\n                    var slotnames = [\"primary\", \"secondary\", \"tertiary\"];\n                    for (var i = 0, ilen = slotnames.length; i < ilen; i += 1) {\n                        if (localesets.length - 1 <  i) {\n                            break;\n                        }\n                        if (localesets[i]) {\n                            slot[slotnames[i]] = 'locale-' + localesets[i];\n                        }\n                    }\n                } else {\n                    slot.primary = 'locale-orig';\n                }\n            }\n            \n            if (variables[0] === \"title-short\" \n                || (state.tmp.area !== \"bibliography\"\n                    && !(state.tmp.area === \"citation\"\n                         && state.opt.xclass === \"note\"\n                         && item && !item.position))) {\n                \n                slot.secondary = false;\n                slot.tertiary = false;\n            }\n\n            if (state.tmp.multi_layout) {\n                slot.secondary = false;\n                slot.tertiary = false;\n            }\n            \n            // Problem for multilingual: we really should be\n            // checking for sanity on the basis of the output\n            // strings to be actually used. (also below)\n            if (state.tmp[\"publisher-list\"]) {\n                if (variables[0] === \"publisher\") {\n                    state.tmp[\"publisher-token\"] = this;\n                } else if (variables[0] === \"publisher-place\") {\n                    state.tmp[\"publisher-place-token\"] = this;\n                }\n                return null;\n            }\n            \n            // tmp.lang_array carries the current locale IDs of the style\n            // and the item. Field-level locale IDs are added here, so\n            // we clone it to allow reset.\n            var oldLangArray = state.tmp.lang_array.slice();\n\n            // True is for transform fallback\n            var res = getTextSubField.call(this, Item, variables[0], slot.primary, true, null, family_var);\n            primary = res.name;\n            primary_locale = res.locale;\n            var primary_tok = res.token;\n            var primaryUsedOrig = res.usedOrig;\n            if (family_var && !res.found_variant_ok) {\n                primary = abbreviate(state, primary_tok, Item, alternative_varname, primary, family_var, true);\n                // Suppress subsequent use of another variable if requested by\n                // hack syntax in this abbreviation short form.\n                if (primary) {\n                    // We run quash-check in getAmbiguousCite, to possibly pick up a cite-form value.\n                    citeFormCheck(Item, primary);\n                    if (!state.tmp.just_looking) {\n                        primary = quashCheck(Item.jurisdiction, primary);\n                    }\n                }\n            }\n            if (publisherCheck(this, Item, primary, family_var)) {\n                state.tmp.lang_array = oldLangArray;\n                return null;\n            }\n\n            // No fallback for secondary and tertiary\n            secondary = false;\n            tertiary = false;\n            var secondary_tok;\n            var tertiary_tok;\n            if (slot.secondary) {\n                res = getTextSubField.call(this, Item, variables[0], slot.secondary, false, res.usedOrig, null, family_var);\n                secondary = res.name;\n                secondary_locale = res.locale;\n                secondary_tok = res.token;\n                if (family_var && !res.found_variant_ok) {\n                    if (secondary) {\n                        // The abbreviate() function could use a cleanup, after Zotero correct to use title-short\n                        secondary = abbreviate(state, secondary_tok, Item, false, secondary, family_var, true);\n                    }\n                }\n                //print(\"XXX secondary_locale: \"+secondary_locale);\n            }\n            if (slot.tertiary) {\n                res = getTextSubField.call(this, Item, variables[0], slot.tertiary, false, res.usedOrig, null, family_var);\n                tertiary = res.name;\n                tertiary_locale = res.locale;\n                tertiary_tok = res.token;\n                if (family_var && !res.found_variant_ok) {\n                    if (tertiary) {\n                        // The abbreviate() function could use a cleanup, after Zotero correct to use title-short\n                        tertiary = abbreviate(state, tertiary_tok, Item, false, tertiary, family_var, true);\n                    }\n                }\n                //print(\"XXX tertiary_locale: \"+tertiary_locale);\n            }\n            \n            // Decoration of primary (currently translit only) goes here\n            var primaryPrefix;\n            if (slot.primary === \"locale-translit\") {\n                primaryPrefix = state.opt.citeAffixes[langPrefs][slot.primary].prefix;\n            }                \n            // XXX This should probably protect against italics at higher\n            // levels.\n\n            if (primaryPrefix === \"<i>\" && variables[0] === 'title' && !primaryUsedOrig) {\n                var hasItalic = false;\n                for (var i = 0, ilen = primary_tok.decorations.length; i < ilen; i += 1) {\n                    if (primary_tok.decorations[i][0] === \"@font-style\"\n                        && primary_tok.decorations[i][1] === \"italic\") {\n                        \n                        hasItalic = true;\n                    }\n                }\n                if (!hasItalic) {\n                    primary_tok.decorations.push([\"@font-style\", \"italic\"]);\n                }\n            }\n\n            //print(\"XXX \"+primary_tok.strings[\"text-case\"]);\n            if (primary_locale !== \"en\" && primary_tok.strings[\"text-case\"] === \"title\") {\n                primary_tok.strings[\"text-case\"] = \"passthrough\";\n            }\n            \n            if (\"title\" === variables[0]) {\n                primary = CSL.demoteNoiseWords(state, primary, this[\"leading-noise-words\"]);\n            }\n            if (secondary || tertiary) {\n\n                state.output.openLevel(\"empty\");\n\n                // A little too aggressive maybe.\n                primary_tok.strings.suffix = primary_tok.strings.suffix.replace(/[ .,]+$/,\"\");\n                if (primary_locale) {\n                    state.tmp.lang_array = [primary_locale].concat(oldLangArray);\n                }\n                CSL.UPDATE_GROUP_CONTEXT_CONDITION(state, null, null, primary_tok, primary_tok.strings.prefix + primary);\n                state.output.append(primary, primary_tok);\n                state.tmp.probably_rendered_something = true;\n\n                if (primary === secondary) {\n                    secondary = false;\n                }\n                if (secondary) {\n                    secondary_tok.strings.prefix = state.opt.citeAffixes[langPrefs][slot.secondary].prefix;\n                    secondary_tok.strings.suffix = state.opt.citeAffixes[langPrefs][slot.secondary].suffix;\n                    // Add a space if empty\n                    if (!secondary_tok.strings.prefix) {\n                        secondary_tok.strings.prefix = \" \";\n                    }\n                    // Remove quotes\n                    for (var i = secondary_tok.decorations.length - 1; i > -1; i += -1) {\n                        if (['@quotes/true', '@font-style/italic', '@font-style/oblique', '@font-weight/bold'].indexOf(secondary_tok.decorations[i].join('/')) > -1) {\n                            secondary_tok.decorations = secondary_tok.decorations.slice(0, i).concat(secondary_tok.decorations.slice(i + 1));\n                        }\n                    }\n                    if (secondary_locale !== \"en\" && secondary_tok.strings[\"text-case\"] === \"title\") {\n                        secondary_tok.strings[\"text-case\"] = \"passthrough\";\n                    }\n                    if (secondary_locale) {\n                        state.tmp.lang_array = [secondary_locale].concat(oldLangArray);\n                    }\n                    var secondary_outer = new CSL.Token();\n                    secondary_outer.decorations.push([\"@font-style\", \"normal\"]);\n                    secondary_outer.decorations.push([\"@font-weight\", \"normal\"]);\n                    state.output.openLevel(secondary_outer);\n                    state.output.append(secondary, secondary_tok);\n                    state.output.closeLevel();\n\n                    var blob_obj = state.output.current.value();\n                    var blobs_pos = state.output.current.value().blobs.length - 1;\n                    // Suppress supplementary multilingual info on subsequent\n                    // partners of a parallel cite?\n                }\n                if (primary === tertiary) {\n                    tertiary = false;\n                }\n                \n                if (tertiary) {\n                    tertiary_tok.strings.prefix = state.opt.citeAffixes[langPrefs][slot.tertiary].prefix;\n                    tertiary_tok.strings.suffix = state.opt.citeAffixes[langPrefs][slot.tertiary].suffix;\n                    // Add a space if empty\n                    if (!tertiary_tok.strings.prefix) {\n                        tertiary_tok.strings.prefix = \" \";\n                    }\n                    // Remove quotes\n                    for (var i = tertiary_tok.decorations.length - 1; i > -1; i += -1) {\n                        if (['@quotes/true', '@font-style/italic', '@font-style/oblique', '@font-weight/bold'].indexOf(tertiary_tok.decorations[i].join('/')) > -1) {\n                            tertiary_tok.decorations = tertiary_tok.decorations.slice(0, i).concat(tertiary_tok.decorations.slice(i + 1));\n                        }\n                    }\n                    if (tertiary_locale !== \"en\" && tertiary_tok.strings[\"text-case\"] === \"title\") {\n                        tertiary_tok.strings[\"text-case\"] = \"passthrough\";\n                    }\n                    if (tertiary_locale) {\n                        state.tmp.lang_array = [tertiary_locale].concat(oldLangArray);\n                    }\n                    var tertiary_outer = new CSL.Token();\n                    tertiary_outer.decorations.push([\"@font-style\", \"normal\"]);\n                    tertiary_outer.decorations.push([\"@font-weight\", \"normal\"]);\n                    state.output.openLevel(tertiary_outer);\n                    state.output.append(tertiary, tertiary_tok);\n                    state.output.closeLevel();\n\n                    var blob_obj = state.output.current.value();\n                    var blobs_pos = state.output.current.value().blobs.length - 1;\n                    // Suppress supplementary multilingual info on subsequent\n                    // partners of a parallel cite?\n                    // See note above.\n                }\n\n                state.output.closeLevel();\n            } else {\n                if (primary_locale) {\n                    state.tmp.lang_array = [primary_locale].concat(oldLangArray);\n                }\n                CSL.UPDATE_GROUP_CONTEXT_CONDITION(state, null, null, primary_tok, primary_tok.strings.prefix + primary);\n                state.output.append(primary, primary_tok);\n                state.tmp.probably_rendered_something = true;\n            }\n\n            state.tmp.lang_array = oldLangArray;\n                \n            if (state.tmp.can_block_substitute) {\n                state.tmp.name_node.children.push(state.output.current.value());\n            }\n            return null;\n        };\n    }\n    this.getOutputFunction = getOutputFunction;\n};\n\n/*global CSL: true */\n\n/**\n * Style token.\n * <p>This class provides the tokens that define\n * the runtime version of the style.  The tokens are\n * instantiated by {@link CSL.Core.Build}, but the token list\n * must be post-processed with\n * {@link CSL.Core.Configure} before it can be used to generate\n * citations.</p>\n * @param {String} name The node name represented by this token.\n * @param {Int} tokentype A flag indicating whether this token\n * marks the start of a node, the end of a node, or is a singleton.\n * @class\n */\nCSL.Token = function (name, tokentype, conditional) {\n    /**\n     * Name of the element.\n     * <p>This corresponds to the element name of the\n     * relevant tag in the CSL file.\n     */\n    this.name = name;\n    /**\n     * Strings and other static content specific to the element.\n     */\n    this.strings = {};\n    this.strings.delimiter = undefined;\n    this.strings.prefix = \"\";\n    this.strings.suffix = \"\";\n    /**\n     * Formatting parameters.\n     * <p>This is a placeholder at instantiation.  It is\n     * replaced by the result of {@link CSL.setDecorations}\n     * when the tag is created and configured during {@link CSL.Core.Build}\n     * by {@link CSL.XmlToToken}.  The parameters for particular\n     * formatting attributes are stored as string arrays, which\n     * map to formatting functions at runtime,\n     * when the output format is known.  Note that the order in which\n     * parameters are registered is fixed by the constant\n     * {@link CSL.FORMAT_KEY_SEQUENCE}.\n     */\n    this.decorations = [];\n    this.variables = [];\n    /**\n     * Element functions.\n     * <p>Functions implementing the styling behaviour of the element\n     * are pushed into this array in the {@link CSL.Core.Build} phase.\n     */\n    this.execs = [];\n    /**\n     * Token type.\n     * <p>This is a flag constant indicating whether the token represents\n     * a start tag, an end tag, or is a singleton.</p>\n     */\n    this.tokentype = tokentype;\n\n    // Conditional attributes added to bare tokens at runtime\n    \n    /**\n     * Condition evaluator.\n     * <p>This is a placeholder that receives a single function, and is\n     * only relevant for a conditional branching tag (<code>if</code> or\n     * <code>else-if</code>).  The function implements the argument to\n     * the <code>match=</code> attribute (<code>any</code>, <code>all</code>\n     * or <code>none</code>), by executing the functions registered in the\n     * <code>tests</code> array (see below), and reacting accordingly.  This\n     * function is invoked by the execution wrappers found in\n     * {@link CSL.Engine}.</p>\n     */\n    // this.evaluator = false;\n    /**\n     * Conditions.\n     * <p>Functions that evaluate to true or false, implementing\n     * various posisble attributes to the conditional branching tags,\n     * are registered here during {@link CSL.Core.Build}.\n     * </p>\n     */\n    // this.tests = [];\n    /**\n     * Jump point on success.\n     * <p>This holds the list jump point to be used when the\n     * <code>evaluator</code> function of a conditional tag\n     * returns true (success).  The jump index value is set during the\n     * back-to-front token pass performed during {@link CSL.Core.Configure}.\n     * </p>\n     */\n    // this.succeed = false;\n    /**\n     * Jump point on failure.\n     * <p>This holds the list jump point to be used when the\n     * <code>evaluator</code> function of a conditional tag\n     * returns false (failure).  Jump index values are set during the\n     * back-to-front token pass performed during {@link CSL.Core.Configure}.\n     * </p>\n     */\n    // this.fail = false;\n    /**\n     * Index of next token.\n     * <p>This holds the index of the next token in the\n     * token list, which is the default \"jump-point\" for ordinary\n     * processing.  Jump index values are set during the\n     * back-to-front token pass performed during {@link CSL.Core.Configure}.\n     * </p>\n     */\n    // this.next = false;\n};\n\n// Have needed this for yonks\nCSL.Util.cloneToken = function (token) {\n    var newtok, key, pos, len;\n    if (\"string\" === typeof token) {\n        return token;\n    }\n    newtok = new CSL.Token(token.name, token.tokentype);\n    for (var key in token.strings) {\n        if (token.strings.hasOwnProperty(key)) {\n            newtok.strings[key] = token.strings[key];\n        }\n    }\n    if (token.decorations) {\n        newtok.decorations = [];\n        for (pos = 0, len = token.decorations.length; pos < len; pos += 1) {\n            newtok.decorations.push(token.decorations[pos].slice());\n        }\n    }\n    if (token.variables) {\n        newtok.variables = token.variables.slice();\n    }\n    // Probably overkill; this is only used for cloning formatting\n    // tokens.\n    if (token.execs) {\n        newtok.execs = token.execs.slice();\n        if (token.tests) {\n            newtok.tests = token.tests.slice();\n        }\n    }\n    return newtok;\n};\n\n/*global CSL: true */\n\n/**\n * Ambiguous Cite Configuration Object\n * @class\n */\nCSL.AmbigConfig = function () {\n    this.maxvals = [];\n    this.minval = 1;\n    this.names = [];\n    this.givens = [];\n    this.year_suffix = false;\n    this.disambiguate = 0;\n};\n\n/*global CSL: true */\n\nCSL.Blob = function (str, token, levelname) {\n    var len, pos, key;\n    this.levelname = levelname;\n    //print(levelname);\n    if (token) {\n        this.strings = {\"prefix\":\"\",\"suffix\":\"\"};\n        for (var key in token.strings) {\n            if (token.strings.hasOwnProperty(key)) {\n                this.strings[key] = token.strings[key];\n            }\n        }\n        this.decorations = [];\n        if (token.decorations === undefined) {\n            len = 0;\n        } else {\n            len = token.decorations.length;\n        }\n        for (pos = 0; pos < len; pos += 1) {\n            this.decorations.push(token.decorations[pos].slice());\n        }\n    } else {\n        this.strings = {};\n        this.strings.prefix = \"\";\n        this.strings.suffix = \"\";\n        this.strings.delimiter = \"\";\n        this.decorations = [];\n    }\n    if (\"string\" === typeof str) {\n        this.blobs = str;\n    } else if (str) {\n        this.blobs = [str];\n    } else {\n        this.blobs = [];\n    }\n    this.alldecor = [this.decorations];\n};\n\n\nCSL.Blob.prototype.push = function (blob) {\n    if (\"string\" === typeof this.blobs) {\n        CSL.error(\"Attempt to push blob onto string object\");\n    } else if (false !== blob) {\n        blob.alldecor = blob.alldecor.concat(this.alldecor);\n        this.blobs.push(blob);\n    }\n};\n\n/*global CSL: true */\n\n/**\n * An output instance object representing a number or a range\n *\n * with attributes next and start, and\n * methods isRange(), renderStart(), renderEnd() and renderRange().\n * At render time, the output queue will perform optional\n * collapsing of these objects in the queue, according to\n * configurable options, and apply any decorations registered\n * in the object to the output elements.\n * @namespace Range object and friends.\n */\n\nCSL.NumericBlob = function (state, particle, num, mother_token, id) {\n    // item id is used to assure that prefix delimiter is invoked only\n    // when joining blobs across items\n    this.id = id;\n    this.alldecor = [];\n    this.num = num;\n    this.particle = particle;\n    this.blobs = num.toString();\n    this.status = CSL.START;\n    this.strings = {};\n    if (mother_token) {\n        if (mother_token.strings[\"text-case\"]) {\n            var textCase = mother_token.strings[\"text-case\"];\n            this.particle = CSL.Output.Formatters[textCase](state, this.particle);\n            this.blobs = CSL.Output.Formatters[textCase](state, this.blobs);\n        }\n        this.gender = mother_token.gender;\n        this.decorations = mother_token.decorations;\n        this.strings.prefix = mother_token.strings.prefix;\n        this.strings.suffix = mother_token.strings.suffix;\n        this.strings[\"text-case\"] = mother_token.strings[\"text-case\"];\n        this.successor_prefix = mother_token.successor_prefix;\n        this.range_prefix = mother_token.range_prefix;\n        this.splice_prefix = mother_token.splice_prefix;\n        this.formatter = mother_token.formatter;\n        if (!this.formatter) {\n            this.formatter =  new CSL.Output.DefaultFormatter();\n        }\n        if (this.formatter) {\n            this.type = this.formatter.format(1);\n        }\n    } else {\n        this.decorations = [];\n        this.strings.prefix = \"\";\n        this.strings.suffix = \"\";\n        this.successor_prefix = \"\";\n        this.range_prefix = \"\";\n        this.splice_prefix = \"\";\n        this.formatter = new CSL.Output.DefaultFormatter();\n    }\n};\n\n\nCSL.NumericBlob.prototype.setFormatter = function (formatter) {\n    this.formatter = formatter;\n    this.type = this.formatter.format(1);\n};\n\n\nCSL.Output.DefaultFormatter = function () {};\n\nCSL.Output.DefaultFormatter.prototype.format = function (num) {\n    return num.toString();\n};\n\nCSL.NumericBlob.prototype.checkNext = function (next,start) {\n    if (start) {\n        this.status = CSL.START;\n        if (\"object\" === typeof next) {\n            if (next.num === (this.num + 1)) {\n                next.status = CSL.SUCCESSOR;\n            } else {\n                next.status = CSL.SEEN;\n            }\n        }\n    } else if (! next || !next.num || this.type !== next.type || next.num !== (this.num + 1)) {\n        if (this.status === CSL.SUCCESSOR_OF_SUCCESSOR) {\n            this.status = CSL.END;\n        }\n        if (\"object\" === typeof next) { \n           next.status = CSL.SEEN;\n        }\n    } else { // next number is in the sequence\n        if (this.status === CSL.START || this.status === CSL.SEEN) {\n            next.status = CSL.SUCCESSOR;\n        } else if (this.status === CSL.SUCCESSOR || this.status === CSL.SUCCESSOR_OF_SUCCESSOR) {\n            if (this.range_prefix) {\n                next.status = CSL.SUCCESSOR_OF_SUCCESSOR;\n                this.status = CSL.SUPPRESS;\n            } else {\n                next.status = CSL.SUCCESSOR;\n            }\n        }\n        // wakes up the correct delimiter.\n        //if (this.status === CSL.SEEN) {\n        //    this.status = CSL.SUCCESSOR;\n        //}\n    }\n};\n\n\nCSL.NumericBlob.prototype.checkLast = function (last) {\n    // Used to adjust final non-range join\n    if (this.status === CSL.SEEN \n    || (last.num !== (this.num - 1) && this.status === CSL.SUCCESSOR)) {\n        this.status = CSL.SUCCESSOR;\n        return true;\n    }\n    return false;\n};\n\n/*global CSL: true */\n\nCSL.Util.fixDateNode = function (parent, pos, node) {\n    var form, variable, datexml, subnode, partname, attr, val, prefix, suffix, children, subchildren, display, cslid;\n    \n    var lingo = this.cslXml.getAttributeValue(node, \"lingo\");\n\n    var default_locale = this.cslXml.getAttributeValue(node, \"default-locale\");\n\n    // Raise date flag, used to control inclusion of year-suffix key in sorts\n    // This may be a little reckless: not sure what happens on no-date conditions\n    this.build.date_key = true;\n\n    form = this.cslXml.getAttributeValue(node, \"form\");\n    var lingo;\n    if (default_locale) {\n        lingo = this.opt[\"default-locale\"][0];\n    } else {\n        lingo = this.cslXml.getAttributeValue(node, \"lingo\");\n    }\n\n    if (!this.getDate(form, default_locale)) {\n        return parent;\n    }\n\n    var dateparts = this.cslXml.getAttributeValue(node, \"date-parts\");\n\n    variable = this.cslXml.getAttributeValue(node, \"variable\");\n    prefix = this.cslXml.getAttributeValue(node, \"prefix\");\n    suffix = this.cslXml.getAttributeValue(node, \"suffix\");\n    display = this.cslXml.getAttributeValue(node, \"display\");\n    cslid = this.cslXml.getAttributeValue(node, \"cslid\");\n\n    //\n    // Xml: Copy a node\n    //\n    datexml = this.cslXml.nodeCopy(this.getDate(form, default_locale));\n    this.cslXml.setAttribute(datexml, 'lingo', this.opt.lang);\n    this.cslXml.setAttribute(datexml, 'form', form);\n    this.cslXml.setAttribute(datexml, 'date-parts', dateparts);\n    this.cslXml.setAttribute(datexml, \"cslid\", cslid);\n    //\n    // Xml: Set attribute\n    //\n    this.cslXml.setAttribute(datexml, 'variable', variable);\n    this.cslXml.setAttribute(datexml, 'default-locale', default_locale);\n    //\n    // Xml: Set flag\n    //\n    if (prefix) {\n        //\n        // Xml: Set attribute\n        //\n        this.cslXml.setAttribute(datexml, \"prefix\", prefix);\n    }\n    if (suffix) {\n        //\n        // Xml: Set attribute\n        //\n        this.cslXml.setAttribute(datexml, \"suffix\", suffix);\n    }\n    if (display) {\n        //\n        // Xml: Set attribute\n        //\n        this.cslXml.setAttribute(datexml, \"display\", display);\n    }\n    //\n    // Step through any date-part children of the layout date node,\n    // and lay their attributes onto the corresponding node in the\n    // locale template node copy.\n    //\n    // tests: language_BaseLocale\n    // tests: date_LocalizedTextInStyleLocaleWithTextCase\n    //\n    children = this.cslXml.children(datexml);\n    for (var key in children) {\n        subnode = children[key];\n        if (\"date-part\" === this.cslXml.nodename(subnode)) {\n            partname = this.cslXml.getAttributeValue(subnode, \"name\");\n            if (default_locale) {\n                this.cslXml.setAttributeOnNodeIdentifiedByNameAttribute(datexml, \"date-part\", partname, \"@default-locale\", \"true\");\n            }\n        }\n    }\n\n    children = this.cslXml.children(node);\n    for (var key in children) {\n        subnode = children[key];\n        if (\"date-part\" === this.cslXml.nodename(subnode)) {\n            partname = this.cslXml.getAttributeValue(subnode, \"name\");\n            subchildren = this.cslXml.attributes(subnode);\n            for (attr in subchildren) {\n                if (\"@name\" === attr) {\n                    continue;\n                }\n                if (lingo && lingo !== this.opt.lang) {\n                    if ([\"@suffix\", \"@prefix\", \"@form\"].indexOf(attr) > -1) {\n                        continue;\n                    }\n                }\n                val = subchildren[attr];\n                this.cslXml.setAttributeOnNodeIdentifiedByNameAttribute(datexml, \"date-part\", partname, attr, val);\n            }\n        }\n    }\n    \n    if (\"year\" === this.cslXml.getAttributeValue(node, \"date-parts\")) {\n\n        //\n        // Xml: Find one node by attribute and delete\n        //\n        this.cslXml.deleteNodeByNameAttribute(datexml, 'month');\n        //\n        // Xml: Find one node by attribute and delete\n        //\n        this.cslXml.deleteNodeByNameAttribute(datexml, 'day');\n        \n    } else if (\"year-month\" === this.cslXml.getAttributeValue(node, \"date-parts\")) {\n        //\n        // Xml: Find one node by attribute and delete\n        //\n        this.cslXml.deleteNodeByNameAttribute(datexml, 'day');\n    } else if (\"month-day\" === this.cslXml.getAttributeValue(node, \"date-parts\")) {\n        //\n        // Xml: Get child nodes\n        //\n        var childNodes = this.cslXml.children(datexml);\n        for (var i=1,ilen=this.cslXml.numberofnodes(childNodes);i<ilen;i++) {\n            //\n            // Xml: Get attribute value (for string comparison)\n            //\n            if (this.cslXml.getAttributeValue(childNodes[i], 'name') === \"year\") {\n                //\n                // Xml: Set attribute value\n                //\n                this.cslXml.setAttribute(childNodes[i-1], \"suffix\", \"\");\n                break;\n            }\n        }\n        //\n        // Xml: Find one node by attribute and delete\n        //\n        this.cslXml.deleteNodeByNameAttribute(datexml, 'year');\n    }\n    return this.cslXml.insertChildNodeAfter(parent, node, pos, datexml);\n};\n\n/*global CSL: true */\n\nCSL.dateMacroAsSortKey = function (state, Item) {\n    CSL.dateAsSortKey.call(this, state, Item, true);\n};\n\n\nCSL.dateAsSortKey = function (state, Item, isMacro) {\n    var dp, elem, value, e, yr, prefix, i, ilen;\n    var variable = this.variables[0];\n    var macroFlag = \"empty\";\n    if (isMacro && state.tmp.extension) {\n        macroFlag = \"macro-with-date\";\n    }\n    dp = Item[variable];\n    if (\"undefined\" === typeof dp) {\n        dp = {\"date-parts\": [[0]] };\n    }\n    if (\"undefined\" === typeof this.dateparts) {\n        this.dateparts = [\"year\", \"month\", \"day\"];\n    }\n    if (dp.raw) {\n        dp = state.fun.dateparser.parseDateToArray(dp.raw);\n    } else if (dp[\"date-parts\"]) {\n        dp = state.dateParseArray(dp);\n    }\n    if (\"undefined\" === typeof dp) {\n        dp = {};\n    }\n    if (dp.year) {\n        for (i = 0, ilen = CSL.DATE_PARTS_INTERNAL.length; i < ilen; i += 1) {\n            elem = CSL.DATE_PARTS_INTERNAL[i];\n            value = 0;\n            e = elem;\n            if (e.slice(-4) === \"_end\") {\n                e = e.slice(0, -4);\n            }\n            if (dp[elem] && this.dateparts.indexOf(e) > -1) {\n                value = dp[elem];\n            }\n            if (elem.slice(0, 4) === \"year\") {\n                yr = CSL.Util.Dates[e].numeric(state, value);\n                var prefix = \"1\";\n                if (yr[0] === \"-\") {\n                    prefix = \"0\";\n                    yr = yr.slice(1);\n                    yr = 9999 - parseInt(yr, 10);\n                }\n                state.output.append(CSL.Util.Dates[elem.slice(0, 4)].numeric(state, (prefix + yr)), macroFlag);\n            } else {\n                value = CSL.Util.Dates[e][\"numeric-leading-zeros\"](state, value);\n                // Ugh.\n                if (!value) {\n                    value = \"00\";\n                }\n                state.output.append(value, macroFlag);\n            }\n        }\n    }\n};\n\nCSL.Engine.prototype.dateParseArray = function (date_obj) {\n    var ret, field, dp, exts;\n    ret = {};\n    for (field in date_obj) {\n        if (field === \"date-parts\") {\n            dp = date_obj[\"date-parts\"];\n            if (dp.length > 1) {\n                if (dp[0].length !== dp[1].length) {\n                    CSL.error(\"CSL data error: element mismatch in date range input.\");\n                }\n            }\n            exts = [\"\", \"_end\"];\n            for (var i = 0, ilen = dp.length; i < ilen; i += 1) {\n                for (var j = 0, jlen = CSL.DATE_PARTS.length; j < jlen; j += 1) {\n                    if (isNaN(parseInt(dp[i][j], 10))) {\n                        ret[(CSL.DATE_PARTS[j] + exts[i])] = undefined;\n                    } else {\n                        ret[(CSL.DATE_PARTS[j] + exts[i])] = parseInt(dp[i][j], 10);\n                    }\n                }\n            }\n        } else if (date_obj.hasOwnProperty(field)) {\n\n            // XXXX: temporary workaround\n\n            if (field === \"literal\" && \"object\" === typeof date_obj.literal && \"string\" === typeof date_obj.literal.part) {\n                CSL.debug(\"Warning: fixing up weird literal date value\");\n                ret.literal = date_obj.literal.part;\n            } else {\n                ret[field] = date_obj[field];\n            }\n        }\n    }\n    return ret;\n};\n\n/*global CSL: true */\n\nCSL.Util.Names = {};\n\nCSL.Util.Names.compareNamesets = CSL.NameOutput.prototype._compareNamesets;\n\n/**\n * Un-initialize a name (quash caps after first character)\n */\nCSL.Util.Names.unInitialize = function (state, name) {\n    var i, ilen, namelist, punctlist, ret;\n    if (!name) {\n        return \"\";\n    }\n    namelist = name.split(/(?:\\-|\\s+)/);\n    punctlist = name.match(/(\\-|\\s+)/g);\n    ret = \"\";\n    for (i = 0, ilen = namelist.length; i < ilen; i += 1) {\n        // if (CSL.ALL_ROMANESQUE_REGEXP.exec(namelist[i].slice(0,-1)) \n        //    && namelist[i] \n        //    && namelist[i] !== namelist[i].toUpperCase()) {\n\n            // More or less like this, to address the following fault report:\n            // http://forums.zotero.org/discussion/17610/apsa-problems-with-capitalization-of-mc-mac-etc/\n\n            // Leaving the name string untouched because name capitalization is varied and wonderful.\n            // https://github.com/Juris-M/citeproc-js/issues/43\n            \n            //namelist[i] = namelist[i].slice(0, 1) + namelist[i].slice(1, 2).toLowerCase() + namelist[i].slice(2);\n        // }\n        ret += namelist[i];\n        if (i < ilen - 1) {\n            ret += punctlist[i];\n        }\n    }\n    return ret;\n};\n\n/**\n * Initialize a name.\n */\nCSL.Util.Names.initializeWith = function (state, name, terminator, normalizeOnly) {\n    var i, ilen, mm, lst, ret;\n    if (!name) {\n        return \"\";\n    }\n    if (!terminator) {\n        terminator = \"\";\n    }\n    if ([\"Lord\", \"Lady\"].indexOf(name) > -1\n        || (!name.replace(/^(?:<[^>]+>)*/, \"\").match(CSL.STARTSWITH_ROMANESQUE_REGEXP)\n            && !terminator.match(\"%s\"))) {\n        return name;\n    }\n\n    if (state.opt[\"initialize-with-hyphen\"] === false) {\n        name = name.replace(/\\-/g, \" \");\n    }\n\n    // We need to suss out what is a set of initials or abbreviation,\n    // so that they can be selectively normalized. Steps might be:\n    //   (1) Split the string\n    //   (2) Step through the string, deleting periods and, if initalize=\"false\", then\n    //       (a) note abbreviations and initials (separately).\n    //   (3) If initialize=\"false\" then:\n    //       (a) Do the thing below, but only pushing terminator; or else\n    //       (b) Do the thing below\n\n    name = name.replace(/\\s*\\-\\s*/g, \"-\").replace(/\\s+/g, \" \");\n    name = name.replace(/-([a-z])/g, \"\\u2013$1\");\n\n    for (var i=name.length-2; i>-1; i += -1) {\n        if (name.slice(i, i+1) === \".\" && name.slice(i+1, i+2) !== \" \") {\n            name = name.slice(0, i) + \". \" + name.slice(i+1);\n        }\n    }\n\n    // (1) Split the string\n    var nameSplits = CSL.Output.Formatters.nameDoppel.split(name);\n    var namelist = [];\n    namelist = [nameSplits.strings[0]];\n\n    if (nameSplits.tags.length === 0) {\n        var mmm = namelist[0].match(/[^\\.]+$/);\n        if (mmm && mmm[0].length === 1 && mmm[0] !== mmm[0].toLowerCase()) {\n            namelist[0] += \".\";\n        }\n    }\n\n    for (i = 1, ilen = nameSplits.strings.length; i < ilen; i += 1) {\n        namelist.push(nameSplits.tags[i - 1]);\n        namelist.push(nameSplits.strings[i]);\n    }\n\n    // Use doInitializeName or doNormalizeName, depending on requirements.\n    if (normalizeOnly) {\n        ret = this.doNormalize(state, namelist, terminator);\n    } else {\n        ret = this.doInitialize(state, namelist, terminator);\n    }\n    ret = ret.replace(/\\u2013([a-z])/g, \"-$1\");\n    return ret;\n};\n\nCSL.Util.Names.notag = function(str) {\n    return str.replace(/^(?:<[^>]+>)*/, \"\");\n};\n\nCSL.Util.Names.mergetag = function(state, tagstr, newstr) {\n    var m = tagstr.match(/(?:-*<[^>]+>-*)/g);\n    if (!m) {\n        return newstr;\n    } else {\n        tagstr = m.join(\"\");\n    }\n    m = newstr.match(/^(.*[^\\s])*(\\s+)$/);\n    if (m) {\n        m[1] = m[1] ? m[1] : \"\";\n        newstr = m[1] + tagstr + m[2];\n    } else {\n        newstr = newstr + tagstr;\n    }\n    return newstr;\n};\n\nCSL.Util.Names.tagonly = function(state, str) {\n    var m = str.match(/(?:<[^>]+>)+/);\n    if (!m) {\n        return str;\n    } else {\n        return m.join(\"\");\n    }\n};\n\nCSL.Util.Names.doNormalize = function (state, namelist, terminator) {\n    var i, ilen;\n    // namelist is a flat list of given-name elements and space-like separators between them\n    terminator = terminator ? terminator : \"\";\n    // Flag elements that look like abbreviations\n    var isAbbrev = [];\n    for (i = 0, ilen = namelist.length; i < ilen; i += 1) {\n        if (this.notag(namelist[i]).length > 1 && this.notag(namelist[i]).slice(-1) === \".\") {\n            // namelist[i] = namelist[i].slice(0, -1);\n            namelist[i] = namelist[i].replace(/^(.*)\\.(.*)$/, \"$1$2\");\n            isAbbrev.push(true);\n        } else if (namelist[i].length === 1 && namelist[i].toUpperCase() === namelist[i]) {\n            isAbbrev.push(true);\n        } else {\n            isAbbrev.push(false);\n        }\n    }\n    // Step through the elements of the givenname array\n    for (i = 0, ilen = namelist.length; i < ilen; i += 2) {\n        // If the element is not an abbreviation, leave it and its trailing spaces alone\n        if (isAbbrev[i]) {\n            // For all elements but the last\n            if (i < namelist.length - 2) {\n                // Start from scratch on space-like things following an abbreviation\n                namelist[i + 1] = this.tagonly(state, namelist[i+1]);\n                if (!isAbbrev[i+2]) {\n                    namelist[i + 1] = this.tagonly(state, namelist[i+1]) + \" \";\n                }\n                \n                // Add the terminator to the element\n                // If the following element is not a single-character abbreviation, remove a trailing zero-width non-break space, if present\n                // These ops may leave some duplicate cruft in the elements and separators. This will be cleaned at the end of the function.\n                if (namelist[i + 2].length > 1) {\n                    namelist[i+1] = terminator.replace(/\\ufeff$/, \"\") + namelist[i+1];\n                } else {\n                    namelist[i+1] = this.mergetag(state, namelist[i+1], terminator);\n                }\n            }\n            // For the last element (if it is an abbreviation), just append the terminator\n            if (i === namelist.length - 1) {\n                namelist[i] = namelist[i] + terminator;\n            }\n        }\n    }\n    // Remove trailing cruft and duplicate spaces, and return\n    return namelist.join(\"\").replace(/[\\u0009\\u000a\\u000b\\u000c\\u000d\\u0020\\ufeff\\u00a0]+$/,\"\").replace(/\\s*\\-\\s*/g, \"-\").replace(/[\\u0009\\u000a\\u000b\\u000c\\u000d\\u0020]+/g, \" \");\n};\n\nCSL.Util.Names.doInitialize = function (state, namelist, terminator) {\n    var i, ilen, m, j, jlen, lst, n;\n    for (i = 0, ilen = namelist.length; i < ilen; i += 2) {\n        n = namelist[i];\n        if (!n) {\n            continue;\n        }\n        m = n.match(CSL.NAME_INITIAL_REGEXP);\n        if (!m && (!n.match(CSL.STARTSWITH_ROMANESQUE_REGEXP) && n.length > 1 && terminator.match(\"%s\"))) {\n            m = n.match(/(.)(.*)/);\n        }\n        if (m && m[2] && m[3]) {\n            m[1] = m[1] + m[2];\n            m[2] = \"\";\n        }\n        if (m && m[1].slice(0, 1) === m[1].slice(0, 1).toUpperCase()) {\n            var extra = \"\";\n            if (m[2]) {\n                var s = \"\";\n                lst = m[2].split(\"\");\n                for (j = 0, jlen = lst.length; j < jlen; j += 1) {\n                    var c = lst[j];\n                    if (c === c.toUpperCase()) {\n                        s += c;\n                    } else {\n                        break;\n                    }\n                }\n                if (s.length < m[2].length) {\n                    extra = CSL.toLocaleLowerCase.call(state, s);\n                }\n            }\n            namelist[i] = m[1] + extra;\n            if (i < (ilen - 1)) {\n                if (terminator.match(\"%s\")) {\n                    namelist[i] = terminator.replace(\"%s\", namelist[i]);\n                } else {\n                    if (namelist[i + 1].indexOf(\"-\") > -1) {\n                        namelist[i + 1] = this.mergetag(state, namelist[i+1].replace(\"-\", \"\"), terminator) + \"-\";\n                    } else {\n                        namelist[i + 1] = this.mergetag(state, namelist[i+1], terminator);\n                    }\n                }\n            } else {\n                if (terminator.match(\"%s\")) {\n                    namelist[i] = terminator.replace(\"%s\", namelist[i]);\n                } else {\n                    namelist.push(terminator);\n                }\n            }\n        } else if (n.match(CSL.ROMANESQUE_REGEXP) && (!m || !m[3])) {\n            namelist[i] = \" \" + n;\n        }\n    }\n    var ret = namelist.join(\"\");\n    ret = ret.replace(/[\\u0009\\u000a\\u000b\\u000c\\u000d\\u0020\\ufeff\\u00a0]+$/,\"\").replace(/\\s*\\-\\s*/g, \"-\").replace(/[\\u0009\\u000a\\u000b\\u000c\\u000d\\u0020]+/g, \" \");\n    return ret;\n};\n\nCSL.Util.Names.getRawName = function (name) {\n    var ret = [];\n    if (name.literal) {\n        ret.push(name.literal);\n    } else {\n        if (name.given) {\n            ret.push(name.given);\n        }\n        if (name.family) {\n            ret.push(name.family);\n        }\n    }\n    return ret.join(\" \");\n};\n\n/*global CSL: true */\n\n/**\n * Date mangling functions.\n * @namespace Date construction utilities\n */\nCSL.Util.Dates = {};\n\n/**\n * Year manglers\n * <p>short, long</p>\n */\nCSL.Util.Dates.year = {};\n\n/**\n * Convert year to long form\n * <p>This just passes the number back as a string.</p>\n */\nCSL.Util.Dates.year[\"long\"] = function (state, num) {\n    if (!num) {\n        if (\"boolean\" === typeof num) {\n            num = \"\";\n        } else {\n            num = 0;\n        }\n    }\n    return num.toString();\n};\n\n/**\n * Crudely convert to Japanese Imperial form.\n * <p>Returns the result as a string.</p>\n */\nCSL.Util.Dates.year.imperial = function (state, num, end) {\n    var year = \"\";\n    if (!num) {\n        if (\"boolean\" === typeof num) {\n            num = \"\";\n        } else {\n            num = 0;\n        }\n    }\n    end = end ? \"_end\" : \"\";\n    var month = state.tmp.date_object[\"month\" + end];\n    month = month ? \"\"+month : \"1\";\n    while (month.length < 2) {\n        month = \"0\" + month;\n    }\n    var day = state.tmp.date_object[\"day\" + end];\n    day = day ? \"\"+day : \"1\";\n    while (day.length < 2) {\n        day = \"0\" + day;\n    }\n    var date = parseInt(num + month + day, 10);\n    var label;\n    var offset;\n    if (date >= 18680908 && date < 19120730) {\n        label = '\\u660e\\u6cbb';\n        offset = 1867;\n    } else if (date >= 19120730 && date < 19261225) {\n        label = '\\u5927\\u6b63';\n        offset = 1911;\n    } else if (date >= 19261225 && date < 19890108) {\n        label = '\\u662d\\u548c';\n        offset = 1925;\n    } else if (date >= 19890108) {\n        label = '\\u5e73\\u6210';\n        offset = 1988;\n    }\n    // This entire \"imperial\" code block should be cut. Scraped input\n    // for this will be too ratty to be useful anyway.\n    if (label && offset) {\n        var normalizedKey = label;\n        if (state.sys.normalizeAbbrevsKey) {\n            // The first argument does not need to specify the exact variable\n            // name.\n            normalizedKey = state.sys.normalizeAbbrevsKey(\"number\", label);\n        }\n        if (!state.transform.abbrevs['default']['number'][normalizedKey]) {\n            // loadAbbreviation normally takes an item as fourth argument.\n            // It is not available here, \n            state.transform.loadAbbreviation('default', \"number\", normalizedKey, null);\n        }\n        if (state.transform.abbrevs['default']['number'][normalizedKey]) {\n            label = state.transform.abbrevs['default']['number'][normalizedKey];\n        }\n        year = label + (num - offset);\n    }\n    return year;\n};\n\n/**\n * Convert year to short form\n * <p>Just crops any 4-digit year to the last two digits.</p>\n */\nCSL.Util.Dates.year[\"short\"] = function (state, num) {\n    num = num.toString();\n    if (num && num.length === 4) {\n        return num.substr(2);\n    }\n};\n\n\n/**\n * Convert year to short form\n * <p>Just crops any 4-digit year to the last two digits.</p>\n */\nCSL.Util.Dates.year.numeric = function (state, num) {\n    var m, pre;\n    num = \"\" + num;\n    var m = num.match(/([0-9]*)$/);\n    if (m) {\n        pre = num.slice(0, m[1].length * -1);\n        num = m[1];\n    } else {\n        pre = num;\n        num = \"\";\n    }\n    while (num.length < 4) {\n        num = \"0\" + num;\n    }\n    return (pre + num);\n};\n\n\n/*\n * MONTH manglers\n * normalize\n * long, short, numeric, numeric-leading-zeros\n */\nCSL.Util.Dates.normalizeMonth = function (num, useSeason) {\n    var ret;\n    if (!num) {\n        num = 0;\n    }\n    num = \"\" + num;\n    if (!num.match(/^[0-9]+$/)) {\n        num = 0;\n    }\n    num = parseInt(num, 10);\n    if (useSeason) {\n        var res = {stub: \"month-\", num: num};\n        if (res.num < 1 || res.num > 24) {\n            res.num = 0;\n        } else {\n            while (res.num > 16) {\n                res.num = res.num - 4;\n            }\n            if (res.num > 12) {\n                res.stub = \"season-\";\n                res.num = res.num - 12;\n            }\n        }\n        ret = res;\n    } else {\n        if (num < 1 || num > 12) {\n            num = 0;\n        }\n        ret = num;\n    }\n    return ret;\n};\n\nCSL.Util.Dates.month = {};\n\n/**\n * Convert month to numeric form\n * <p>This just passes the number back as a string.</p>\n */\nCSL.Util.Dates.month.numeric = function (state, num) {\n    var num = CSL.Util.Dates.normalizeMonth(num);\n    if (!num) {\n        num = \"\";\n    }\n    return num;\n};\n\n/**\n * Convert month to numeric-leading-zeros form\n * <p>This just passes the number back as string padded with zeros.</p>\n */\nCSL.Util.Dates.month[\"numeric-leading-zeros\"] = function (state, num) {\n    var num = CSL.Util.Dates.normalizeMonth(num);\n    if (!num) {\n        num = \"\";\n    } else {\n        num = \"\" + num;\n        while (num.length < 2) {\n            num = \"0\" + num;\n        }\n    }\n    return num;\n};\n\n/**\n * Convert month to long form\n * <p>This passes back the month of the locale in long form.</p>\n */\n\n// Gender is not currently used. Is it needed?\n\nCSL.Util.Dates.month[\"long\"] = function (state, num, gender, forceDefaultLocale) {\n    var res = CSL.Util.Dates.normalizeMonth(num, true);\n    var num = res.num;\n    if (!num) {\n        num = \"\";\n    } else {\n        num = \"\" + num;\n        while (num.length < 2) {\n            num = \"0\" + num;\n        }\n        num = state.getTerm(res.stub + num, \"long\", 0, 0, false, forceDefaultLocale);\n    }\n    return num;\n};\n\n/**\n * Convert month to long form\n * <p>This passes back the month of the locale in short form.</p>\n */\n\n// See above.\n\nCSL.Util.Dates.month[\"short\"] = function (state, num, gender, forceDefaultLocale) {\n    var res = CSL.Util.Dates.normalizeMonth(num, true);\n    var num = res.num;\n    if (!num) {\n        num = \"\";\n    } else {\n        num = \"\" + num;\n        while (num.length < 2) {\n            num = \"0\" + num;\n        }\n        num = state.getTerm(res.stub + num, \"short\", 0, 0, false, forceDefaultLocale);\n    }\n    return num;\n};\n\n/*\n * DAY manglers\n * numeric, numeric-leading-zeros, ordinal\n */\nCSL.Util.Dates.day = {};\n\n/**\n * Convert day to numeric form\n * <p>This just passes the number back as a string.</p>\n */\nCSL.Util.Dates.day.numeric = function (state, num) {\n    return num.toString();\n};\n\nCSL.Util.Dates.day[\"long\"] = CSL.Util.Dates.day.numeric;\n\n/**\n * Convert day to numeric-leading-zeros form\n * <p>This just passes the number back as a string padded with zeros.</p>\n */\nCSL.Util.Dates.day[\"numeric-leading-zeros\"] = function (state, num) {\n    if (!num) {\n        num = 0;\n    }\n    num = num.toString();\n    while (num.length < 2) {\n        num = \"0\" + num;\n    }\n    return num.toString();\n};\n\n/**\n * Convert day to ordinal form\n * <p>This will one day pass back the number as a string with the\n * ordinal suffix appropriate to the locale.  For the present,\n * it just does what is most of the time right for English.</p>\n */\nCSL.Util.Dates.day.ordinal = function (state, num, gender) {\n    return state.fun.ordinalizer.format(num, gender);\n};\n\n/*global CSL: true */\n\n/**\n * Helper functions for constructing sort keys.\n * @namespace Sort key utilities\n */\nCSL.Util.Sort = {};\n\n/**\n * Strip prepositions from a string\n * <p>Used when generating sort keys.</p>\n */\nCSL.Util.Sort.strip_prepositions = function (str) {\n    var m;\n    if (\"string\" === typeof str) {\n        m = str.match(/^(([aA]|[aA][nN]|[tT][hH][eE])\\s+)/);\n    }\n    if (m) {\n        str = str.substr(m[1].length);\n    }\n    return str;\n};\n\n/*global CSL: true */\n\nCSL.Util.substituteStart = function (state, target) {\n    var element_trace, display, bib_first, func, choose_start, if_start, nodetypes;\n    func = function (state, Item, item) {\n        for (var i = 0, ilen = this.decorations.length; i < ilen; i += 1) {\n            if (\"@strip-periods\" === this.decorations[i][0] && \"true\" === this.decorations[i][1]) {\n                state.tmp.strip_periods += 1;\n                break;\n            }\n        }\n    };\n    this.execs.push(func);\n    if (this.decorations && state.opt.development_extensions.csl_reverse_lookup_support) {\n        this.decorations.reverse();\n        this.decorations.push([\"@showid\",\"true\", this.cslid]);\n        this.decorations.reverse();\n    }\n    //\n    // Contains body code for both substitute and first-field/remaining-fields\n    // formatting.\n    //\n\n    nodetypes = [\"number\", \"date\", \"names\"];\n    if ((\"text\" === this.name && !this.postponed_macro) || nodetypes.indexOf(this.name) > -1) {\n        element_trace = function (state, Item, item) {\n            if (state.tmp.element_trace.value() === \"author\" || \"names\" === this.name) {\n                if (!state.tmp.just_looking && item && item[\"author-only\"] && state.tmp.area !== \"intext\") {\n                    if (!state.tmp.probably_rendered_something) {\n                    } else {\n                        state.tmp.element_trace.push(\"suppress-me\");\n                    }\n                }\n                if (!state.tmp.just_looking && item && item[\"suppress-author\"]) {\n                    if (!state.tmp.probably_rendered_something) {\n                        state.tmp.element_trace.push(\"suppress-me\");\n                    }\n                }\n            }\n            else if (\"date\" === this.name) {\n                if (!state.tmp.just_looking && item && item[\"author-only\"] && state.tmp.area !== \"intext\") {\n                    if (state.tmp.probably_rendered_something) {\n                        state.tmp.element_trace.push(\"suppress-me\");\n                    }\n                }\n                /*\n                if (!state.tmp.just_looking && item && item[\"suppress-author\"]) {\n                    if (state.tmp.probably_rendered_something) {\n                        //state.tmp.element_trace.push(\"suppress-me\");\n                    }\n                }\n                */\n            } else {\n                if (!state.tmp.just_looking && item && item[\"author-only\"] && state.tmp.area !== \"intext\") {\n                    // XXX can_block_substitute probably is doing nothing here. The value is always true.\n                    if (!state.tmp.probably_rendered_something && state.tmp.can_block_substitute) {\n                    } else {\n                        state.tmp.element_trace.push(\"suppress-me\");\n                    }\n                } else if (item && item[\"suppress-author\"]) {\n                    state.tmp.element_trace.push(\"do-not-suppress-me\");\n                }\n            }\n        };\n        this.execs.push(element_trace);\n    }\n    display = this.strings.cls;\n    this.strings.cls = false;\n    if (state.build.render_nesting_level === 0) {\n        //\n        // The markup formerly known as @bibliography/first\n        //\n        // Separate second-field-align from the generic display logic.\n        // There will be some code replication, but not in the\n        // assembled style.\n        //\n        if (state.build.area === \"bibliography\" && state.bibliography.opt[\"second-field-align\"]) {\n            bib_first = new CSL.Token(\"group\", CSL.START);\n            bib_first.decorations = [[\"@display\", \"left-margin\"]];\n            func = function (state, Item) {\n                if (!state.tmp.render_seen) {\n                    bib_first.strings.first_blob = Item.id;\n                    state.output.startTag(\"bib_first\", bib_first);\n                }\n            };\n            bib_first.execs.push(func);\n            target.push(bib_first);\n        } else if (CSL.DISPLAY_CLASSES.indexOf(display) > -1) {\n            bib_first = new CSL.Token(\"group\", CSL.START);\n            bib_first.decorations = [[\"@display\", display]];\n            func = function (state, Item) {\n                bib_first.strings.first_blob = Item.id;\n                state.output.startTag(\"bib_first\", bib_first);\n            };\n            bib_first.execs.push(func);\n            target.push(bib_first);\n        }\n        state.build.cls = display;\n    }\n    state.build.render_nesting_level += 1;\n    // Should this be render_nesting_level, with the increment\n    // below? ... ?\n    if (state.build.substitute_level.value() === 1) {\n        //\n        // All top-level elements in a substitute environment get\n        // wrapped in conditionals.  The substitute_level variable\n        // is a stack, because spanned names elements (with their\n        // own substitute environments) can be nested inside\n        // a substitute environment.\n        //\n        // (okay, we use conditionals a lot more than that.\n        // we slot them in for author-only as well...)\n        choose_start = new CSL.Token(\"choose\", CSL.START);\n        CSL.Node.choose.build.call(choose_start, state, target);\n        if_start = new CSL.Token(\"if\", CSL.START);\n        //\n        // Set a test of the shadow if token to skip this\n        // macro if we have acquired a name value.\n\n        // check for variable\n        func = function () {\n            if (state.tmp.can_substitute.value()) {\n                return true;\n            }\n            return false;\n        };\n        if_start.tests ? {} : if_start.tests = [];\n        if_start.tests.push(func);\n        if_start.test = state.fun.match.any(this, state, if_start.tests);\n        target.push(if_start);\n    }\n\n    if (state.sys.variableWrapper\n        && this.variables_real\n        && this.variables_real.length) {\n\n        func = function (state, Item, item) {\n            if (!state.tmp.just_looking && !state.tmp.suppress_decorations) {\n                // Attach item data and variable names.\n                // Do with them what you will.\n                var variable_entry = new CSL.Token(\"text\", CSL.START);\n                variable_entry.decorations = [[\"@showid\", \"true\"]];\n                state.output.startTag(\"variable_entry\", variable_entry);\n                var position = null;\n                if (item) {\n                    position = item.position;\n                }\n                if (!position) {\n                    position = 0;\n                }\n                var positionMap = [\n                    \"first\",\n                    \"container-subsequent\",\n                    \"subsequent\",\n                    \"ibid\",\n                    \"ibid-with-locator\"\n                ];\n                var noteNumber = 0;\n                if (item && item.noteIndex) {\n                    noteNumber = item.noteIndex;\n                }\n                var firstReferenceNoteNumber = 0;\n                if (item && item['first-reference-note-number']) {\n                    firstReferenceNoteNumber = item['first-reference-note-number'];\n                }\n                var firstContainerReferenceNoteNumber = 0;\n                if (item && item['first-container-reference-note-number']) {\n                    firstContainerReferenceNoteNumber = item['first-container-reference-note-number'];\n                }\n                var citationNumber = 0;\n                // XXX Will this EVER happen?\n                if (item && item['citation-number']) {\n                    citationNumber = item['citation-number'];\n                }\n                var index = 0;\n                if (item && item.index) {\n                    index = item.index;\n                }\n                var params = {\n                    itemData: Item,\n                    variableNames: this.variables,\n                    context: state.tmp.area,\n                    xclass: state.opt.xclass,\n                    position: positionMap[position],\n                    \"note-number\": noteNumber,\n                    \"first-reference-note-number\": firstReferenceNoteNumber,\n                    \"first-container-reference-note-number\": firstContainerReferenceNoteNumber,\n                    \"citation-number\": citationNumber,\n                    \"index\": index,\n                    \"mode\": state.opt.mode\n                };\n                state.output.current.value().params = params;\n            }\n        };\n        this.execs.push(func);\n    }\n};\n\n\nCSL.Util.substituteEnd = function (state, target) {\n    var func, bib_first_end, bib_other, if_end, choose_end, author_substitute, str;\n\n    if (state.sys.variableWrapper\n        && (this.hasVariable || (this.variables_real && this.variables_real.length))) {\n        \n        func = function (state) {\n            if (!state.tmp.just_looking && !state.tmp.suppress_decorations) {\n                state.output.endTag(\"variable_entry\");\n            }\n        };\n        this.execs.push(func);\n    }\n\n    func = function (state) {\n        for (var i = 0, ilen = this.decorations.length; i < ilen; i += 1) {\n            if (\"@strip-periods\" === this.decorations[i][0] && \"true\" === this.decorations[i][1]) {\n                state.tmp.strip_periods += -1;\n                break;\n            }\n        }\n    };\n    this.execs.push(func);\n\n    state.build.render_nesting_level += -1;\n    if (state.build.render_nesting_level === 0) {\n        if (state.build.cls) {\n            func = function (state) {\n                state.output.endTag(\"bib_first\");\n            };\n            this.execs.push(func);\n            state.build.cls = false;\n        } else if (state.build.area === \"bibliography\" && state.bibliography.opt[\"second-field-align\"]) {\n            bib_first_end = new CSL.Token(\"group\", CSL.END);\n            // first func end\n            func = function (state) {\n                if (!state.tmp.render_seen) {\n                    state.output.endTag(\"bib_first\"); // closes bib_first\n                }\n            };\n            bib_first_end.execs.push(func);\n            target.push(bib_first_end);\n            bib_other = new CSL.Token(\"group\", CSL.START);\n            bib_other.decorations = [[\"@display\", \"right-inline\"]];\n            func = function (state) {\n                if (!state.tmp.render_seen) {\n                    state.tmp.render_seen = true;\n                    state.output.startTag(\"bib_other\", bib_other);\n                }\n            };\n            bib_other.execs.push(func);\n            target.push(bib_other);\n        }\n    }\n    if (state.build.substitute_level.value() === 1) {\n        if_end = new CSL.Token(\"if\", CSL.END);\n        target.push(if_end);\n        choose_end = new CSL.Token(\"choose\", CSL.END);\n        CSL.Node.choose.build.call(choose_end, state, target);\n    }\n\n    if (\"names\" === this.name || (\"text\" === this.name && this.variables_real !== \"title\")) {\n        author_substitute = new CSL.Token(\"text\", CSL.SINGLETON);\n        var substitution_name = this.name;\n        func = function (state, Item) {\n            if (state.tmp.area !== \"bibliography\") {\n                return;\n            }\n            if (\"string\" !== typeof state.bibliography.opt[\"subsequent-author-substitute\"]) {\n                return;\n            }\n            if (this.variables_real && !Item[this.variables_real]) {\n                return;\n            }\n            // The logic of these two is not obvious. The effect is to enable placeholder substitution\n            // on a text macro name substitution, without printing both the text macro AND the placeholder.\n            // See https://forums.zotero.org/discussion/comment/350407\n            if (this.variables_real && substitution_name === \"names\") {\n                return;\n            }\n\n            var subrule = state.bibliography.opt[\"subsequent-author-substitute-rule\"];\n            var i, ilen;\n            //var text_esc = CSL.getSafeEscape(state);\n            var printing = !state.tmp.suppress_decorations;\n            if (printing && state.tmp.subsequent_author_substitute_ok) {\n                if (state.tmp.rendered_name) {\n                    if (\"partial-each\" === subrule || \"partial-first\" === subrule) {\n                        var dosub = true;\n                        var rendered_name = [];\n                        // This is a wee bit risky, as we're assuming that the name\n                        // children and the list of stringified names are congruent.\n                        // That *should* always be true, but you never know.\n                        for (i = 0, ilen = state.tmp.name_node.children.length; i < ilen; i += 1) {\n                            var name = state.tmp.rendered_name[i];\n                            if (dosub\n                                && state.tmp.last_rendered_name && state.tmp.last_rendered_name.length > (i - 1)\n                                && name && !name.localeCompare(state.tmp.last_rendered_name[i])) {\n                                str = new CSL.Blob(state[state.tmp.area].opt[\"subsequent-author-substitute\"]);\n                                state.tmp.name_node.children[i].blobs = [str];\n                                if (\"partial-first\" === subrule) {\n                                    dosub = false;\n                                }\n                            } else {\n                                dosub = false;\n                            }\n                            rendered_name.push(name);\n                        }\n                        // might want to slice this?\n                        state.tmp.last_rendered_name = rendered_name;\n                    } else if (\"complete-each\" === subrule) {\n                        var rendered_name = state.tmp.rendered_name.join(\",\");\n                        if (rendered_name) {\n                            if (state.tmp.last_rendered_name && !rendered_name.localeCompare(state.tmp.last_rendered_name)) {\n                                for (i = 0, ilen = state.tmp.name_node.children.length; i < ilen; i += 1) {\n                                    str = new CSL.Blob(state[state.tmp.area].opt[\"subsequent-author-substitute\"]);\n                                    state.tmp.name_node.children[i].blobs = [str];\n                                }\n                            }\n                            state.tmp.last_rendered_name = rendered_name;\n                        }\n                    } else {\n                        var rendered_name = state.tmp.rendered_name.join(\",\");\n                        if (rendered_name) {\n                            if (state.tmp.last_rendered_name && !rendered_name.localeCompare(state.tmp.last_rendered_name)) {\n                                str = new CSL.Blob(state[state.tmp.area].opt[\"subsequent-author-substitute\"]);\n                                if (state.tmp.label_blob) {\n                                    state.tmp.name_node.top.blobs = [str,state.tmp.label_blob];\n                                } else if (state.tmp.name_node.top.blobs.length) {\n                                    state.tmp.name_node.top.blobs[0].blobs = [str];\n                                } else {\n                                    state.tmp.name_node.top.blobs = [str];\n                                }\n                                state.tmp.substituted_variable = substitution_name;\n                            }\n                            state.tmp.last_rendered_name = rendered_name;\n                        }\n                    }\n                    state.tmp.subsequent_author_substitute_ok = false;\n                }\n            }\n        };\n        this.execs.push(func);\n    }\n\n    if ((\"text\" === this.name && !this.postponed_macro) || [\"number\", \"date\", \"names\"].indexOf(this.name) > -1) {\n        // element trace\n        func = function (state, Item) {\n            // element_trace is a mess, but it's trying to do something simple.\n            // A queue append is done, and element_trace.value() returns \"suppress-me\"\n            // the append is aborted. That's it.\n            // It seems only to be used on numeric elements of numeric styles ATM.\n            // If used only for that purpose, it could be greatly simplified.\n            // If cleaned up, it could do more interesting things, like control\n            // the suppression of names set later than first position.\n            if (state.tmp.element_trace.mystack.length>1) {\n                state.tmp.element_trace.pop();\n            }\n        };\n        this.execs.push(func);\n    }\n};\n\n/*global CSL: true */\n\nCSL.Util.padding = function (num) {\n    var m = num.match(/\\s*(-{0,1}[0-9]+)/);\n    if (m) {\n        num = parseInt(m[1], 10);\n        if (num < 0) {\n            num = 99999999999999999999 + num;\n        }\n        num = \"\" + num;\n        while (num.length < 20) {\n            num = \"0\" + num;\n        }\n    }\n    return num;\n};\n\nCSL.Util.LongOrdinalizer = function () {};\n\nCSL.Util.LongOrdinalizer.prototype.init = function (state) {\n    this.state = state;\n};\n\nCSL.Util.LongOrdinalizer.prototype.format = function (num, gender) {\n    if (num < 10) {\n        num = \"0\" + num;\n    }\n    // Argument true means \"loose\".\n    var ret = CSL.Engine.getField(\n        CSL.LOOSE, \n        this.state.locale[this.state.opt.lang].terms,\n        \"long-ordinal-\" + num,\n        \"long\", \n        0, \n        gender\n    );\n    if (!ret) {\n        ret = this.state.fun.ordinalizer.format(num, gender);\n    }\n    // Probably too optimistic -- what if only renders in _sort?\n    this.state.tmp.cite_renders_content = true;\n    return ret;\n};\n\n\nCSL.Util.Ordinalizer = function (state) {\n    this.state = state;\n    this.suffixes = {};\n};\n\nCSL.Util.Ordinalizer.prototype.init = function () {\n    if (!this.suffixes[this.state.opt.lang]) {\n        this.suffixes[this.state.opt.lang] = {};\n        for (var i = 0, ilen = 3; i < ilen; i += 1) {\n            var gender = [undefined, \"masculine\", \"feminine\"][i];\n            this.suffixes[this.state.opt.lang][gender] = [];\n            for (var j = 1; j < 5; j += 1) {\n                var ordinal = this.state.getTerm(\"ordinal-0\" + j, \"long\", false, gender);\n                if (\"undefined\" === typeof ordinal) {\n                    delete this.suffixes[this.state.opt.lang][gender];\n                    break;\n                }\n                this.suffixes[this.state.opt.lang][gender].push(ordinal);\n            }\n        }\n    }\n};\n\nCSL.Util.Ordinalizer.prototype.format = function (num, gender) {\n    var str;\n    num = parseInt(num, 10);\n    str = \"\" + num;\n    var suffix = \"\";\n    var trygenders = [];\n    if (gender) {\n        trygenders.push(gender);\n    }\n    trygenders.push(\"neuter\");\n    if (this.state.locale[this.state.opt.lang].ord[\"1.0.1\"]) {\n        suffix = this.state.getTerm(\"ordinal\",false,0,gender);\n        var trygender;\n        for (var i = 0, ilen = trygenders.length; i < ilen; i += 1) {\n            trygender = trygenders[i];\n            var ordinfo = this.state.locale[this.state.opt.lang].ord[\"1.0.1\"];\n            if (ordinfo[\"whole-number\"][str] && ordinfo[\"whole-number\"][str][trygender]) {\n                suffix = this.state.getTerm(this.state.locale[this.state.opt.lang].ord[\"1.0.1\"][\"whole-number\"][str][trygender],false,0,gender);\n            } else if (ordinfo[\"last-two-digits\"][str.slice(str.length - 2)] && ordinfo[\"last-two-digits\"][str.slice(str.length - 2)][trygender]) {\n                suffix = this.state.getTerm(this.state.locale[this.state.opt.lang].ord[\"1.0.1\"][\"last-two-digits\"][str.slice(str.length - 2)][trygender],false,0,gender);\n            } else if (ordinfo[\"last-digit\"][str.slice(str.length - 1)] && ordinfo[\"last-digit\"][str.slice(str.length - 1)][trygender]) {\n                suffix = this.state.getTerm(this.state.locale[this.state.opt.lang].ord[\"1.0.1\"][\"last-digit\"][str.slice(str.length - 1)][trygender],false,0,gender);\n            }\n            if (suffix) {\n                break;\n            }\n        }\n    } else {\n        if (!gender) {\n            // XXX hack to prevent crash on CSL 1.0 styles.\n            // Reported by Carles.\n            gender = undefined;\n        }\n        this.state.fun.ordinalizer.init();\n        if ((num / 10) % 10 === 1 || (num > 10 && num < 20)) {\n            suffix = this.suffixes[this.state.opt.lang][gender][3];\n        } else if (num % 10 === 1 && num % 100 !== 11) {\n            suffix = this.suffixes[this.state.opt.lang][gender][0];\n        } else if (num % 10 === 2 && num % 100 !== 12) {\n            suffix = this.suffixes[this.state.opt.lang][gender][1];\n        } else if (num % 10 === 3 && num % 100 !== 13) {\n            suffix = this.suffixes[this.state.opt.lang][gender][2];\n        } else {\n            suffix = this.suffixes[this.state.opt.lang][gender][3];\n        }\n    }\n    str = str += suffix;\n    return str;\n};\n\nCSL.Util.Romanizer = function () {};\n\nCSL.Util.Romanizer.prototype.format = function (num) {\n    var ret, pos, n, numstr, len;\n    ret = \"\";\n    if (num < 6000) {\n        numstr = num.toString().split(\"\");\n        numstr.reverse();\n        pos = 0;\n        n = 0;\n        len = numstr.length;\n        for (pos = 0; pos < len; pos += 1) {\n            n = parseInt(numstr[pos], 10);\n            ret = CSL.ROMAN_NUMERALS[pos][n] + ret;\n        }\n    }\n    return ret;\n};\n\n\n/**\n * Create a suffix formed from a list of arbitrary characters of arbitrary length.\n * <p>This is a <i>lot</i> harder than it seems.</p>\n */\nCSL.Util.Suffixator = function (slist) {\n    if (!slist) {\n        slist = CSL.SUFFIX_CHARS;\n    }\n    this.slist = slist.split(\",\");\n};\n\n/**\n * The format method.\n * <p>This method is used in generating ranges.  Every numeric\n * formatter (of which Suffixator is one) must be an instantiated\n * object with such a \"format\" method.</p>\n */\n\nCSL.Util.Suffixator.prototype.format = function (N) {\n    // Many thanks to Avram Lyon for this code, and good\n    // riddance to the several functions that it replaces.\n    var X;\n    N += 1;\n    var key = \"\";\n    do {\n        X = ((N % 26) === 0) ? 26 : (N % 26);\n        var key = this.slist[X-1] + key;\n        N = (N - X) / 26;\n    } while ( N !== 0 );\n    return key;\n};\n\n\nCSL.Engine.prototype.processNumber = function (node, ItemObject, variable) {\n    //print(\"** processNumber() ItemObject[variable]=\"+ItemObject[variable]);\n    var val;\n\n    var me = this;\n\n    var realVariable = variable;\n    variable = (variable === \"page-first\") ? \"page\" : variable;\n\n    var fullformAnd = \",\\\\s+and\\\\s+|\\\\s+and\\\\s+\";\n    if (this.opt.lang.slice(0, 2) !== \"en\") {\n        fullformAnd += \"|,\\\\s+\" + this.getTerm(\"and\") + \"\\\\s+|\\\\s+\" + this.getTerm(\"and\") + \"\\\\s+\";\n    }\n    var symbolAnd = \"\\\\s*&\\\\s*\";\n    var andRex = new RegExp(\"^\" + symbolAnd+ \"$\");\n    var joinerMatchRex = new RegExp(\"(\" + symbolAnd + \"|\" + fullformAnd + \"|;\\\\s+|,\\\\s+|\\\\s*\\\\\\\\*[\\\\-\\\\u2013]+\\\\s*)\", \"g\");\n    var joinerSplitRex = new RegExp(\"(?:\" + symbolAnd + \"|\" + fullformAnd + \"|;\\\\s+|,\\\\s+|\\\\s*\\\\\\\\*[\\\\-\\\\u2013]+\\\\s*)\");\n\n    // This guesses whether the symbol form is defined or not.\n    // It's the best we can do, because when locales are built, all of the\n    // holes are filled explictly with fallback values: the symbol form is never undefined.\n    var localeAnd = this.getTerm(\"and\");\n    var localeAmpersand = this.getTerm(\"and\", \"symbol\");\n    if (localeAnd === localeAmpersand) {\n        localeAmpersand = \"&\";\n    }\n\n    // XXXX shadow_numbers should carry an array of objects with\n    // XXXX full data for each. The test of a number should be\n    // XXXX a separate function, possibly supported by a splitter\n    // XXXX method also used here. Keep code for each action in one place,\n    // XXXX to prevent debugging from becoming a nightmare.\n\n    // The capture pattern below would apply affixes to all sub-elements,\n    // which is not what we want. Sub-elements should nest within, or\n    // affixes should be edited. The latter is probably easier to handle.\n    \n    // values = [\n    //   {\n    //     label: \"sec.\",\n    //     label-form: \"plural\",\n    //     value: 100,\n    //     styling: [object],\n    //     numeric: true\n    //     joiningSuffix: \" & \",\n    //   },\n    //   {\n    //     label: \"sec.\",\n    //     label-form: \"none\",\n    //     value: 103,\n    //     styling: [object],\n    //     numeric: true,\n    //     joiningSuffix: \"\"\n    //   }\n    // ]\n    \n    function normalizeFieldValue(str) {\n        str = str.trim();\n        var m = str.match(/^([^ ]+)/);\n        if (m && !CSL.STATUTE_SUBDIV_STRINGS[m[1]]) {\n            var embeddedLabel = null;\n            if ([\"locator\", \"locator-extra\", \"page\"].indexOf(variable) > -1) {\n                if (ItemObject.label) {\n                    embeddedLabel = CSL.STATUTE_SUBDIV_STRINGS_REVERSE[ItemObject.label];\n                } else {\n                    embeddedLabel = \"p.\";\n                }\n            } else {\n                embeddedLabel = CSL.STATUTE_SUBDIV_STRINGS_REVERSE[variable];\n            }\n            if (embeddedLabel) {\n                str = embeddedLabel + \" \" + str;\n            }\n        }\n        return str;\n    }\n    \n\n    function composeNumberInfo(origLabel, label, val, joiningSuffix, parsePosition) {\n        joiningSuffix = joiningSuffix ? joiningSuffix : \"\";\n        var info = {};\n\n        if (!label && !CSL.STATUTE_SUBDIV_STRINGS_REVERSE[variable]) {\n            label = \"var:\"+ variable;\n        }\n\n        if (label) {\n            var m = label.match(/(\\s*)([^\\s]+)(\\s*)/);\n            if (realVariable === \"page\" && parsePosition === 0 && [\"p.\", \"pp.\"].indexOf(m[2]) === -1) {\n                info.gotosleepability = true;\n                info.labelVisibility = true;\n            } else {\n                info.labelVisibility = false;\n            }\n            info.label = m[2];\n            info.origLabel = origLabel;\n            info.labelSuffix = m[3] ? m[3] : \"\";\n            info.plural = 0;\n        }\n        \n        var m = val.match(/^([0-9]*[a-zA-Z]+0*)?([0-9]+(?:[a-zA-Z]*|[-,a-zA-Z]+))$/);\n        //var m = val.match(/^([0-9]*[a-zA-Z]0*)([0-9]+(?:[a-zA-Z]*|[-,a-zA-Z]+))$/);\n        if (m) {\n            info.particle = m[1] ? m[1] : \"\";\n            info.value = m[2];\n        } else {\n            info.particle = \"\";\n            info.value = val;\n        }\n        info.joiningSuffix = joiningSuffix.replace(/\\s*-\\s*/, \"-\");\n        return info;\n    }\n\n    function fixupSubsections(elems) {\n        // This catches things like p. 12a-c, recombining content to yield\n        // numeric true despite the hyphen.\n        for (var i=elems.length-2;i>-1;i-=2) {\n            if (elems[i] === \"-\"\n               && elems[i-1].match(/^(?:(?:[a-z]|[a-z][a-z]|[a-z][a-z][a-z]|[a-z][a-z][a-z][a-z])\\.  *)*[0-9]+[,a-zA-Z]+$/)\n               && elems[i+1].match(/^[,a-zA-Z]+$/)) {\n                elems[i-1] = elems.slice(i-1,i+2).join(\"\");\n                elems = elems.slice(0,i).concat(elems.slice(i+2));\n            }\n        }\n        return elems;\n    }\n\n    function parseString(str, defaultLabel) {\n        defaultLabel = defaultLabel ? defaultLabel : \"\";\n        \n        str = normalizeFieldValue(str, defaultLabel);\n\n        var jmrex, jsrex, mystr;\n        if (\"page\" === variable) {\n            if (str.indexOf(\"\\u2013\") > -1) {\n                str = str.replace(/\\u2013/g, \"-\");\n            }\n        }\n        if (str.indexOf(\"\\\\-\") > -1) {\n            jmrex = new RegExp(joinerMatchRex.source.replace(\"\\\\-\", \"\"));\n            jsrex = new RegExp(joinerSplitRex.source.replace(\"\\\\-\", \"\"));\n            var lst = str.split(\"\\\\-\");\n            for (var i=0,ilen=lst.length;i<ilen;i++) {\n                lst[i] = lst[i].replace(/\\-/g, \"\\u2013\");\n            }\n            mystr = lst.join(\"\\\\-\");\n            mystr = mystr.replace(/\\\\/g, \"\");\n        } else {\n            jmrex = joinerMatchRex;\n            jsrex = joinerSplitRex;\n            mystr = str;\n        }\n        // jmrex = joinerMatchRex;\n        // jsrex = joinerSplitRex;\n        \n        // Split chunks and collate delimiters.\n        var elems = [];\n        var m = mystr.match(jmrex);\n        if (m) {\n            var lst = mystr.split(jsrex);\n            for (var i=0, ilen=m.length; i<ilen; i++) {\n                if (m[i].match(andRex)) {\n                    if (lst[i].match(/[a-zA-Z]$/) && lst[i].match(/^[a-zA-Z]/)) {\n                        m[i] = localeAmpersand;\n                    } else {\n                        m[i] = \" \" + localeAmpersand + \" \";\n                    }\n                }\n            }\n            var recombine = false;\n            for (var i in lst) {\n                if ((\"\" + lst[i]).replace(/^[a-z]\\.\\s+/, \"\").match(/[^\\s0-9ivxlcmIVXLCM]/)) {\n                    //recombine = true;\n                    break;\n                }\n            }\n            if (recombine) {\n                elems = [mystr];\n            } else {\n                for (var i=0,ilen=lst.length-1; i<ilen; i++) {\n                    elems.push(lst[i]);\n                    elems.push(m[i]);\n                }\n                elems.push(lst[lst.length-1]);\n                //print(\"ELEMS: \"+elems);\n                elems = fixupSubsections(elems);\n                //print(\"  fixup: \"+elems);\n            }\n        } else {\n            var elems = [mystr];\n        }\n        // Split elements within each chunk build list of value objects.\n        var values = [];\n        var label = defaultLabel;\n        var origLabel = \"\";\n        for (var i=0,ilen=elems.length;i<ilen;i += 2) {\n            \n            // AHA! HERE'S THE CULPRIT!!!\n            // Words up to four characters are treated as honorary short-form labels.\n            // Some valid labels are longer than four chars, so we stir those in explicitly\n            \n            var m = elems[i].match(/((?:^| )(?:[a-z]|[a-z][a-z]|[a-z][a-z][a-z]|[a-z][a-z][a-z][a-z]|subpara|subch|amend|bibliog|annot|illus|princ|intro|sched|subdiv|subsec)(?:\\.| ) *)/g);\n            if (m) {\n                var lst = elems[i].split(/(?:(?:^| )(?:[a-z]|[a-z][a-z]|[a-z][a-z][a-z]|[a-z][a-z][a-z][a-z]|subpara|subch|amend|bibliog|annot|illus|princ|intro|sched|subdiv|subsec)(?:\\.| ) *)/);\n                // Head off disaster by merging parsed labels on non-numeric values into content\n                for (var j=lst.length-1;j>0;j--) {\n                    if (lst[j-1] && (!lst[j].match(/^[0-9]+([-;,:a-zA-Z]*)$/) || !lst[j-1].match(/^[0-9]+([-;,:a-zA-Z]*)$/))) {\n                        lst[j-1] = lst[j-1] + m[j-1] + lst[j];\n                        lst = lst.slice(0,j).concat(lst.slice(j+1));\n                        m = m.slice(0,j-1).concat(m.slice(j));\n                    }\n                }\n                // merge bad leading label into content\n                if (m.length > 0) {\n                    var slug = m[0].trim();\n                    var notAlabel = !CSL.STATUTE_SUBDIV_STRINGS[slug]\n                        || \"undefined\" === typeof me.getTerm(CSL.STATUTE_SUBDIV_STRINGS[slug])\n                        || ([\"locator\", \"number\", \"locator-extra\", \"page\"].indexOf(variable) === -1 && CSL.STATUTE_SUBDIV_STRINGS[slug] !== variable);\n                    if (notAlabel) {\n                        if (i === 0) {\n                            m = m.slice(1);\n                            lst[0] = lst[0] + \" \" + slug + \" \" + lst[1];\n                            lst = lst.slice(0,1).concat(lst.slice(2));\n                        }\n                    } else {\n                        origLabel = slug;\n                    }\n                }\n\n                for (var j=0,jlen=lst.length; j<jlen; j++) {\n                    if (lst[j] || j === (lst.length-1)) {\n                        var filteredOrigLabel;\n                        label = m[j-1] ? m[j-1] : label;\n                        if (origLabel === label.trim()) {\n                            filteredOrigLabel = \"\";\n                        } else {\n                            filteredOrigLabel = origLabel;\n                        }\n                        //var origLabel = j > 1 ? m[j-1] : \"\";\n                        mystr = lst[j] ? lst[j].trim() : \"\";\n                        if (j === (lst.length-1)) {\n                            values.push(composeNumberInfo(filteredOrigLabel, label, mystr, elems[i+1], i));\n                        } else {\n                            values.push(composeNumberInfo(filteredOrigLabel, label, mystr, null, i));\n                        }\n                    }\n                }\n            } else {\n                var filteredOrigLabel;\n                if (origLabel === label.trim()) {\n                    filteredOrigLabel = \"\";\n                } else {\n                    filteredOrigLabel = origLabel;\n                }\n                values.push(composeNumberInfo(filteredOrigLabel, label, elems[i], elems[i+1]));\n            }\n        }\n        return values;\n    }\n\n    function setSpaces(values) {\n        // Add space joins (is this really right?)\n        for (var i=0,ilen=values.length-1;i<ilen;i++) {\n            if (!values[i].joiningSuffix && values[i+1].label) {\n                values[i].joiningSuffix = \" \";\n            }\n        }\n    }\n\n    function fixNumericAndCount(values, i, currentLabelInfo) {\n        var master = values[currentLabelInfo.pos];\n        var val = values[i].value;\n        var isEscapedHyphen = master.joiningSuffix === \"\\\\-\";\n        if (val.particle && val.particle !== master.particle) {\n            currentLabelInfo.collapsible = false;\n        }\n        var mVal = val.match(/^[0-9]+([-,:a-zA-Z]*)$/);\n        var mCurrentLabel = master.value.match(/^(?:[0-9]+|[ixv]+)([-,:a-zA-Z]*|\\-[\\-0-9]+)$/);\n        if (!val || !mVal || !mCurrentLabel || isEscapedHyphen) {\n            currentLabelInfo.collapsible = false;\n            if (!val || !mCurrentLabel) {\n                currentLabelInfo.numeric = false;\n            }\n            if (isEscapedHyphen) {\n                currentLabelInfo.count--;\n            }\n        }\n        if ((mVal && mVal[1]) || (mCurrentLabel && mCurrentLabel[1])) {\n            currentLabelInfo.collapsible = false;\n        }\n        if (undefined === values[i].collapsible) {\n            for (var j=i,jlen=i+currentLabelInfo.count;j<jlen;j++) {\n                if (isNaN(parseInt(values[j].value)) && !values[j].value.match(/^[ivxlcmIVXLCM]+$/)) {\n                    values[j].collapsible = false;\n                } else {\n                    values[j].collapsible = true;\n                }\n            }\n            currentLabelInfo.collapsible = values[i].collapsible;\n        }\n        var isCollapsible = currentLabelInfo.collapsible;\n        for (var j=currentLabelInfo.pos,jlen=(currentLabelInfo.pos + currentLabelInfo.count); j<jlen; j++) {\n            if (currentLabelInfo.count > 1 && isCollapsible) {\n                values[j].plural = 1;\n            }\n            values[j].numeric = currentLabelInfo.numeric;\n            values[j].collapsible = currentLabelInfo.collapsible;\n        }\n    }\n\n    function fixLabelVisibility(values, groupStartPos, currentLabelInfo) {\n        if (currentLabelInfo.label.slice(0, 4) !== \"var:\") {\n            if (currentLabelInfo.pos === 0) {\n                if ([\"locator\", \"number\", \"locator-extra\", \"page\"].indexOf(variable) > -1) {\n                    // Actually, shouldn't we do this always?\n                    if (\"undefined\" === typeof me.getTerm(CSL.STATUTE_SUBDIV_STRINGS[currentLabelInfo.label])) {\n                        values[currentLabelInfo.pos].labelVisibility = true;\n                    }\n                }\n                // If there is an explicit\n                // label embedded at the start of a field that\n                // does not match the context, it should be\n                // marked for rendering.\n                if ([\"locator\", \"number\", \"locator-extra\", \"page\"].indexOf(variable) === -1) {\n                    if (CSL.STATUTE_SUBDIV_STRINGS[currentLabelInfo.label] !== variable) {\n                        values[0].labelVisibility = true;\n                    }\n                }\n            } else {\n                // Also, mark initial mid-field labels for\n                // rendering.\n                //if (values[i-1].label !== values[i].label && currentLabelInfo.label.slice(0, 4) !== \"var:\") {\n                values[currentLabelInfo.pos].labelVisibility = true;\n                //}\n            }\n        }\n    }\n    \n    function setPluralsAndNumerics(values) {\n        if (values.length === 0) {\n            return;\n        }\n        var groupStartPos = 0;\n        var groupCount = 1;\n        \n        for (var i=1,ilen=values.length;i<ilen;i++) {\n            var lastVal = values[i-1];\n            var thisVal = values[i];\n            if (lastVal.label === thisVal.label && lastVal.particle === lastVal.particle) {\n                groupCount++;\n            } else {\n                var currentLabelInfo = JSON.parse(JSON.stringify(values[groupStartPos]));\n                currentLabelInfo.pos = groupStartPos;\n                currentLabelInfo.count = groupCount;\n                currentLabelInfo.numeric = true;\n                fixNumericAndCount(values, groupStartPos, currentLabelInfo);\n                if (lastVal.label !== thisVal.label) {\n                    fixLabelVisibility(values, groupStartPos, currentLabelInfo);\n                }\n                groupStartPos = i;\n                groupCount = 1;\n            }\n        }\n        // Not sure why this repetition is necessary?\n        var currentLabelInfo = JSON.parse(JSON.stringify(values[groupStartPos]));\n        currentLabelInfo.pos = groupStartPos;\n        currentLabelInfo.count = groupCount;\n        currentLabelInfo.numeric = true;\n        fixNumericAndCount(values, groupStartPos, currentLabelInfo);\n        fixLabelVisibility(values, groupStartPos, currentLabelInfo);\n        if (values.length && values[0].numeric && variable.slice(0, 10) === \"number-of-\") {\n            if (parseInt(ItemObject[realVariable], 10) > 1) {\n                values[0].plural = 1;\n            }\n        }\n    }        \n\n    function stripHyphenBackslash(joiningSuffix) {\n        return joiningSuffix.replace(\"\\\\-\", \"-\");\n    }\n\n    function setStyling(values) {\n        var masterNode = CSL.Util.cloneToken(node);\n        var masterStyling = new CSL.Token();\n        if (!me.tmp.just_looking) {\n            // Per discussion @ https://discourse.citationstyles.org/t/formatting-attributes-and-hyphen/1518\n            masterStyling.decorations = masterNode.decorations;\n            masterNode.decorations = [];\n            //for (var j=masterNode.decorations.length-1;j>-1;j--) {\n            //    if (masterNode.decorations[j][0] === \"@quotes\") {\n            //        // Add to styling\n            //        masterStyling.decorations = masterStyling.decorations.concat(masterNode.decorations.slice(j, j+1));\n            //        // Remove from node\n            //        masterNode.decorations = masterNode.decorations.slice(0, j).concat(masterNode.decorations.slice(j+1));\n            //    }\n            //}\n            masterStyling.strings.prefix = masterNode.strings.prefix;\n            masterNode.strings.prefix = \"\";\n            masterStyling.strings.suffix = masterNode.strings.suffix;\n            masterNode.strings.suffix = \"\";\n        }\n        var masterLabel = values.length ? values[0].label : null;\n        if (values.length) {\n            for (var i=0,ilen=values.length; i<ilen; i++) {\n                var val = values[i];\n                // Clone node, make styling parameters on each instance sane.\n                var newnode = CSL.Util.cloneToken(masterNode);\n                newnode.gender = node.gender;\n                if (masterLabel === val.label) {\n                    newnode.formatter = node.formatter;\n                }\n                if (val.numeric) {\n                    newnode.successor_prefix = val.successor_prefix;\n                }\n                newnode.strings.suffix = newnode.strings.suffix + stripHyphenBackslash(val.joiningSuffix);\n                val.styling = newnode;\n            }\n            if (!me.tmp.just_looking) {\n                if (values[0].value.slice(0,1) === \"\\\"\" && values[values.length-1].value.slice(-1) === \"\\\"\") {\n                    values[0].value = values[0].value.slice(1);\n                    values[values.length-1].value = values[values.length-1].value.slice(0,-1);\n                    masterStyling.decorations.push([\"@quotes\", true]);\n                }\n            }\n        }\n        return masterStyling;\n    }\n\n    function checkTerm(variable, val) {\n        var ret = true;\n        if ([\"locator\", \"locator-extra\", \"page\"].indexOf(variable) > -1) {\n            var label;\n            if (val.origLabel) {\n                label = val.origLabel;\n            } else {\n                label = val.label;\n            }\n            ret = !!me.getTerm(CSL.STATUTE_SUBDIV_STRINGS[label]);\n        }\n        return ret;\n    }\n\n    function checkPage(variable, val) {\n        return \"page\" === variable\n            || ([\"locator\", \"locator-extra\"].indexOf(variable) > -1 && ([\"p.\"].indexOf(val.label) > -1 || [\"p.\"].indexOf(val.origLabel) > -1));\n    }\n    \n    function fixupRangeDelimiter(variable, val, rangeDelimiter, isNumeric) {\n        var isPage = checkPage(variable, val);\n        var hasTerm = checkTerm(variable, val);\n        if (hasTerm && rangeDelimiter === \"-\") {\n            if (isNumeric) {\n                if (isPage || [\"locator\", \"locator-extra\", \"issue\", \"volume\", \"edition\", \"number\"].indexOf(variable) > -1) {\n                    rangeDelimiter = me.getTerm(\"page-range-delimiter\");\n                    if (!rangeDelimiter) {\n                        rangeDelimiter = \"\\u2013\";\n                    }\n                }\n                if (variable === \"collection-number\") {\n                    rangeDelimiter = me.getTerm(\"year-range-delimiter\");\n                    if (!rangeDelimiter) {\n                        rangeDelimiter = \"\\u2013\";\n                    }\n                }\n            }\n        }\n        //if (rangeDelimiter === \"\\\\-\") {\n        //    rangeDelimiter = \"-\";\n        //}\n        return rangeDelimiter;\n    }\n\n    function manglePageNumbers(values, i, currentInfo) {\n        if (i<1) {\n            return;\n        }\n        if (currentInfo.count !== 2) {\n            return;\n        }\n        if (values[i-1].particle !== values[i].particle) {\n            return;\n        }\n        if (values[i-1].joiningSuffix !== \"-\") {\n            currentInfo.count = 1;\n            return;\n        }\n        if (!me.opt[\"page-range-format\"] && (parseInt(values[i-1].value, 10) > parseInt(values[i].value, 10))) {\n            values[i-1].joiningSuffix = fixupRangeDelimiter(variable, values[i], values[i-1].joiningSuffix, true);\n            return;\n        }\n        var val = values[i];\n\n        var isPage = checkPage(variable, val);\n        var str;\n        if (isPage && !isNaN(parseInt(values[i-1].value)) && !isNaN(parseInt(values[i].value))) {\n            str = values[i-1].particle + values[i-1].value + \" - \" + values[i].particle + values[i].value;\n            str = me.fun.page_mangler(str);\n        } else {\n            // if ((\"\" + values[i-1].value).match(/[0-9]$/) && (\"\" + values[i].value).match(/^[0-9]/)) {\n            if ((\"\" + values[i-1].value).match(/^([0-9]+|[ivxlcmIVXLCM]+)$/) && (\"\" + values[i].value).match(/^([0-9]+|[ivxlcmIVXLCM]+)$/)) {\n                values[i-1].joiningSuffix = me.getTerm(\"page-range-delimiter\");\n            }\n            str = values[i-1].value + stripHyphenBackslash(values[i-1].joiningSuffix) + values[i].value;\n        }\n        var m = str.match(/^((?:[0-9]*[a-zA-Z]+0*))?([0-9]+[a-z]*)(\\s*[^0-9]+\\s*)([-,a-zA-Z]?0*)([0-9]+[a-z]*)$/);\n        // var m = str.match(/^((?:[0-9]*[a-zA-Z]+0*))?([0-9]+[a-z]*)(\\s*[^0-9]+\\s*)([-,a-zA-Z]?0*)([0-9]+[a-z]*)$/);\n        if (m) {\n            var rangeDelimiter = m[3];\n            rangeDelimiter = fixupRangeDelimiter(variable, val, rangeDelimiter, values[i].numeric);\n            values[i-1].particle = m[1];\n            values[i-1].value = m[2];\n            values[i-1].joiningSuffix = rangeDelimiter;\n            values[i].particle = m[4];\n            values[i].value = m[5];\n        }\n        currentInfo.count = 0;\n    }\n    \n    function fixRanges(values) {\n\n        if (!node) {\n            return;\n        }\n        if ([\"page\", \"chapter-number\", \"collection-number\", \"edition\", \"issue\", \"number\", \"number-of-pages\", \"number-of-volumes\", \"volume\", \"locator\", \"locator-extra\"].indexOf(variable) === -1) {\n            return;\n        }\n\n        var currentInfo = {\n            count: 0,\n            label: null,\n            lastHadRangeDelimiter: false\n        };\n\n        for (var i=0,ilen=values.length; i<ilen; i++) {\n            var val = values[i];\n            if (!val.collapsible) {\n                currentInfo.count = 0;\n                currentInfo.label = null;\n                var isNumeric = val.numeric;\n                val.joiningSuffix = fixupRangeDelimiter(variable, val, val.joiningSuffix, isNumeric);\n            } else if (currentInfo.label === val.label && val.joiningSuffix === \"-\") {\n                // So if there is a hyphen here, and none previous, reset to 1\n                currentInfo.count = 1;\n            } else if (currentInfo.label === val.label && val.joiningSuffix !== \"-\") {\n                // If there is NO hyphen here, count up\n                currentInfo.count++;\n                if (currentInfo.count === 2) {\n                    manglePageNumbers(values, i, currentInfo);\n                }\n            } else if (currentInfo.label !== val.label) {\n                // If the label doesn't match and count is 2, process\n                currentInfo.label = val.label;\n                currentInfo.count = 1;\n            } else {\n                // Safety belt: label doesn't match and count is some other value, so reset to 1\n                // This never happens, though.\n                currentInfo.count = 1;\n                currentInfo.label = val.label;\n            }\n        }\n        // Finally clear, if needed\n        if (currentInfo.count === 2) {\n            manglePageNumbers(values, values.length-1, currentInfo);\n        }\n    }\n\n    function setVariableParams(shadow_numbers, realVariable, values) {\n        var obj = shadow_numbers[realVariable];\n        if (values.length) {\n            obj.numeric = values[0].numeric;\n            obj.collapsible = values[0].collapsible;\n            obj.plural = values[0].plural;\n            obj.label = CSL.STATUTE_SUBDIV_STRINGS[values[0].label];\n            if (variable === \"number\" && obj.label === \"issue\" && me.getTerm(\"number\")) {\n                obj.label = \"number\";\n            }\n        }\n    }\n\n    // Split out the labels and values.\n\n    // short-circuit if object exists: if numeric, set styling, no other action\n    if (node && this.tmp.shadow_numbers[realVariable] && this.tmp.shadow_numbers[realVariable].values.length) {\n        var values = this.tmp.shadow_numbers[realVariable].values;\n        fixRanges(values);\n        //if (!this.tmp.shadow_numbers[variable].masterStyling && !this.tmp.just_looking) {\n            this.tmp.shadow_numbers[realVariable].masterStyling = setStyling(values);\n        //}\n        return;\n    }\n\n    // info.styling = node;\n\n    // This carries value, pluralization and numeric info for use in other contexts.\n    // XXX We used to use one set of params for the entire variable value.\n    // XXX Now params are set on individual objects, of which there may be several after parsing.\n    if (!this.tmp.shadow_numbers[realVariable]) {\n        this.tmp.shadow_numbers[realVariable] = {\n            values:[]\n        };\n    }\n    //this.tmp.shadow_numbers[variable].values = [];\n    //this.tmp.shadow_numbers[variable].plural = 0;\n    //this.tmp.shadow_numbers[variable].numeric = false;\n    //this.tmp.shadow_numbers[variable].label = false;\n\n    if (!ItemObject) {\n        return;\n    }\n\n    // Possibly apply multilingual transform\n    var languageRole = CSL.LangPrefsMap[variable];\n    if (languageRole) {\n        var localeType = this.opt[\"cite-lang-prefs\"][languageRole][0];\n        val = this.transform.getTextSubField(ItemObject, realVariable, \"locale-\"+localeType, true);\n        val = val.name;\n    } else {\n        val = ItemObject[realVariable];\n    }\n\n    if (val && realVariable === \"number\" && ItemObject.type === \"legal_case\") {\n        val = val.replace(/[\\\\]*-/g, \"\\\\-\");\n    }\n\n    // XXX HOLDING THIS\n    // Apply short form ONLY if first element tests is-numeric=false\n    if (val && this.sys.getAbbreviation) {\n        // RefMe bug report: print(\"XX D'oh! (3): \"+num);\n        // true as the fourth argument suppresses update of the UI\n\n        // No need for this.\n        //val = (\"\" + val).replace(/^\\\"/, \"\").replace(/\\\"$/, \"\");\n        if (this.sys.normalizeAbbrevsKey) {\n            var normval = this.sys.normalizeAbbrevsKey(realVariable, val);\n        } else {\n            var normval = val;\n        }\n        var jurisdiction = this.transform.loadAbbreviation(ItemObject.jurisdiction, \"number\", normval, ItemObject.language);\n        if (this.transform.abbrevs[jurisdiction].number) {\n            if (this.transform.abbrevs[jurisdiction].number[normval]) {\n                val = this.transform.abbrevs[jurisdiction].number[normval];\n            } else {\n                \n                // *** This is terrible ***\n                \n                // Strings rendered via cs:number should not be added to the abbreviations\n                // UI unless they test non-numeric. The test happens below.\n                if (\"undefined\" !== typeof this.transform.abbrevs[jurisdiction].number[normval]) {\n                    delete this.transform.abbrevs[jurisdiction].number[normval];\n                }\n            }\n        }\n    }\n\n    //   {\n    //     label: \"sec.\",\n    //     labelForm: \"plural\",\n    //     labelVisibility: true,\n    //     value: 100,\n    //     styling: [object],\n    //     numeric: true\n    //     joiningSuffix: \" & \",\n    //   },\n\n    // Process only if there is a value.\n    if (\"undefined\" !== typeof val && (\"string\" === typeof val || \"number\" === typeof val)) {\n        if (\"number\" === typeof val) {\n            val = \"\" + val;\n        }\n        var defaultLabel = CSL.STATUTE_SUBDIV_STRINGS_REVERSE[variable];\n\n        if (this.tmp.shadow_numbers[realVariable].values.length === 0) {\n            // XXX\n            var values = parseString(val, defaultLabel);\n\n            setSpaces(values);\n            //print(\"setSpaces(): \"+JSON.stringify(values, null, 2));\n\n            setPluralsAndNumerics(values);\n            //print(\"setPluralsAndNumerics(): \"+JSON.stringify(values, null, 2));\n\n            for (var obj of values) {\n                if (!obj.numeric) obj.plural = 0;\n            }\n            this.tmp.shadow_numbers[realVariable].values = values;\n            // me.sys.print(JSON.stringify(values))\n\n            if (node) {\n                fixRanges(values);\n                \n                this.tmp.shadow_numbers[realVariable].masterStyling = setStyling(values);\n                // me.sys.print(\"setStyling(): \"+JSON.stringify(values, null, 2));\n            }\n            setVariableParams(this.tmp.shadow_numbers, realVariable, values);\n        }\n        \n        // hack in support for non-numeric numerics like \"91 Civ. 5442 (RPP)|91 Civ. 5471\"\n        var info = this.tmp.shadow_numbers[realVariable];\n        if (variable === \"number\") {\n            if (info.values.length === 1 && info.values[0].value.indexOf(\"|\") > -1) {\n                info.values[0].value = info.values[0].value.replace(/\\|/g, \", \");\n                info.values[0].numeric = true;\n                info.values[0].plural = 1;\n                info.values[0].collapsible = false;\n                info.numeric = true;\n                info.plural = 1;\n                info.collapsible = false;\n            }\n        }\n        if (info.values.length === 1) {\n            if (info.values[0].value.match(/^[0-9]+(?:\\/[0-9]+)+$/)) {\n                info.values[0].numeric = true;\n                info.values[0].plural = 0;\n                info.values[0].collapsible = false;\n                info.numeric = true;\n                info.plural = 0;\n                info.collapsible = false;\n            }\n        }\n        if (variable === \"page\") {\n            if (info.values.length > 0) {\n                if (info.values[0].gotosleepability) {\n                    info.labelForm = \"short\";\n                }\n            }\n        }\n        //this.sys.print(\"OK \"+JSON.stringify(values, [\"label\", \"origLabel\", \"labelSuffix\", \"particle\", \"collapsible\", \"value\", \"numeric\", \"joiningSuffix\", \"labelVisibility\", \"plural\"], 2));\n    }\n};\n\nCSL.Util.outputNumericField = function(state, varname, itemID) {\n\n    state.output.openLevel(state.tmp.shadow_numbers[varname].masterStyling);\n    var masterStyling = state.tmp.shadow_numbers[varname].masterStyling;\n    var nums = state.tmp.shadow_numbers[varname].values;\n    var masterLabel = nums.length ? nums[0].label : null;\n    var labelForm = state.tmp.shadow_numbers[varname].labelForm;\n    var tryStatic = state.tmp.group_context.tip.label_static;\n    var embeddedLabelForm;\n    if (labelForm) {\n        embeddedLabelForm = labelForm;\n    } else {\n        embeddedLabelForm = \"short\";\n        //labelForm = \"short\";\n    }\n    var labelCapitalizeIfFirst = state.tmp.shadow_numbers[varname].labelCapitalizeIfFirst;\n    var labelDecorations = state.tmp.shadow_numbers[varname].labelDecorations;\n    var lastLabelName = null;\n\n    for (var i=0,ilen=nums.length;i<ilen;i++) {\n        var num = nums[i];\n        var label = \"\";\n        var labelName;\n        if (num.label) {\n            if ('var:' === num.label.slice(0,4)) {\n                labelName = num.label.slice(4);\n            } else {\n                labelName = CSL.STATUTE_SUBDIV_STRINGS[num.label];\n            }\n            if (labelName) {\n                // Simplify this some day.\n                if (num.label === masterLabel) {\n                    if (tryStatic) {\n                        label = state.getTerm(labelName, \"static\", num.plural);\n                        if (label.indexOf(\"%s\") === -1) {\n                            label = \"\";\n                        }\n                    }\n                    if (!label) {\n                        label = state.getTerm(labelName, labelForm, num.plural);\n                    }\n                } else {\n                    if (tryStatic) {\n                        label = state.getTerm(labelName, \"static\", num.plural);\n                        if (label.indexOf(\"%s\") === -1) {\n                            label = \"\";\n                        }\n                    }\n                    if (!label) {\n                        label = state.getTerm(labelName, embeddedLabelForm, num.plural);\n                    }\n                }\n                if (labelCapitalizeIfFirst) {\n                    label = CSL.Output.Formatters[\"capitalize-first\"](state, label);\n                }\n            }\n        }\n        var labelPlaceholderPos = -1;\n        if (label) {\n            labelPlaceholderPos = label.indexOf(\"%s\");\n        }\n        var numStyling = CSL.Util.cloneToken(num.styling);\n        numStyling.formatter = num.styling.formatter;\n        numStyling.type = num.styling.type;\n        numStyling.num = num.styling.num;\n        numStyling.gender = num.styling.gender;\n        \n        if (labelPlaceholderPos > 0 && labelPlaceholderPos < (label.length-2)) {\n            numStyling.strings.prefix += label.slice(0,labelPlaceholderPos);\n            numStyling.strings.suffix = label.slice(labelPlaceholderPos+2) + numStyling.strings.suffix;\n        } else if (num.labelVisibility) {\n            if (!label) {\n                label = num.label;\n                labelName = num.label;\n            }\n            if (labelPlaceholderPos > 0) {\n                var prefixLabelStyling = new CSL.Token();\n                prefixLabelStyling.decorations = labelDecorations;\n                state.output.append(label.slice(0,labelPlaceholderPos), prefixLabelStyling);\n            } else if (labelPlaceholderPos === (label.length-2) || labelPlaceholderPos === -1) {\n                // And add a trailing delimiter.\n                state.output.append(label+num.labelSuffix, \"empty\");\n            }\n        }\n        CSL.UPDATE_GROUP_CONTEXT_CONDITION(state, masterStyling.strings.prefix, null, masterStyling, `${num.particle}${num.value}`);\n        if (num.collapsible) {\n            var blob;\n            if (num.value.match(/^[1-9][0-9]*$/) && Number.isSafeInteger(parseInt(num.value, 10))) {\n                blob = new CSL.NumericBlob(state, num.particle, parseInt(num.value, 10), numStyling, itemID);\n            } else {\n                blob = new CSL.NumericBlob(state, num.particle, num.value, numStyling, itemID);\n            }\n            if (\"undefined\" === typeof blob.gender) {\n                blob.gender = state.locale[state.opt.lang][\"noun-genders\"][varname];\n            }\n            state.output.append(blob, \"literal\");\n        } else {\n            state.output.append(num.particle + num.value, numStyling);\n        }\n        if (labelPlaceholderPos === 0 && labelPlaceholderPos < (label.length-2)) {\n            // Only and always if this is the last entry of this label\n            if (lastLabelName === null) {\n                lastLabelName = labelName;\n            }\n            if (labelName !== lastLabelName || i === (nums.length-1)) {\n                var suffixLabelStyling = new CSL.Token();\n                suffixLabelStyling.decorations = labelDecorations;\n                state.output.append(label.slice(labelPlaceholderPos+2), suffixLabelStyling);\n            }\n        }\n        lastLabelName = labelName;\n        state.tmp.term_predecessor = true;\n    }\n    state.output.closeLevel();\n};\n\n/*global CSL: true */\n\nCSL.Util.PageRangeMangler = {};\n\nCSL.Util.PageRangeMangler.getFunction = function (state, rangeType) {\n    var rangerex, pos, len, stringify, listify, expand, minimize, minimize_internal, chicago15, chicago16, lst, m, b, e, ret, begin, end, ret_func;\n    \n    var range_delimiter = state.getTerm(rangeType + \"-range-delimiter\");\n\n    rangerex = /([0-9]*[a-zA-Z]+0*)?([0-9]+[a-z]*)\\s*(?:\\u2013|-)\\s*([0-9]*[a-zA-Z]+0*)?([0-9]+[a-z]*)/;\n\n    stringify = function (lst) {\n        len = lst.length;\n        for (pos = 1; pos < len; pos += 2) {\n            if (\"object\" === typeof lst[pos]) {\n                lst[pos] = lst[pos].join(\"\");\n            }\n        }\n        var ret = lst.join(\"\");\n        ret = ret.replace(/([^\\\\])\\-/g, \"$1\"+state.getTerm(rangeType + \"-range-delimiter\"));\n        return ret;\n    };\n\n    listify = function (str) {\n        var m, lst, ret;\n        // Normalized delimiter form, for use in regexps\n        var hyphens = \"\\\\s+\\\\-\\\\s+\";\n        // Normalize delimiters to hyphen wrapped in single spaces\n        var this_range_delimiter = range_delimiter === \"-\" ? \"\" : range_delimiter;\n        var delimRex = new RegExp(\"([^\\\\\\\\])[-\" + this_range_delimiter + \"\\\\u2013]\", \"g\");\n        str = str.replace(delimRex, \"$1 - \").replace(/\\s+-\\s+/g, \" - \");\n        // Workaround for Internet Explorer\n        //var rexm = new RegExp(\"((?:[0-9]*[a-zA-Z]+)?[0-9]+\" + hyphens + \"(?:[0-9]*[a-zA-Z]+)?[0-9]+)\", \"g\");\n        //var rexlst = new RegExp(\"(?:[0-9]*[a-zA-Z]+)?[0-9]+\" + hyphens + \"(?:[0-9]*[a-zA-Z]+)?[0-9]+\");\n        var rexm = new RegExp(\"((?:[0-9]*[a-zA-Z]+0*)?[0-9]+[a-z]*\" + hyphens + \"(?:[0-9]*[a-zA-Z]+0*)?[0-9]+[a-z]*)\", \"g\");\n        var rexlst = new RegExp(\"(?:[0-9]*[a-zA-Z]+0*)?[0-9]+[a-z]*\" + hyphens + \"(?:[0-9]*[a-zA-Z]+0*)?[0-9]+[a-z]*\");\n        m = str.match(rexm);\n        lst = str.split(rexlst);\n        if (lst.length === 0) {\n            ret = m;\n        } else {\n            ret = [lst[0]];\n            for (pos = 1, len = lst.length; pos < len; pos += 1) {\n                ret.push(m[pos - 1].replace(/\\s*\\-\\s*/g, \"-\"));\n                ret.push(lst[pos]);\n            }\n        }\n        return ret;\n    };\n\n    expand = function (str) {\n        str = \"\" + str;\n        lst = listify(str);\n        len = lst.length;\n        for (pos = 1; pos < len; pos += 2) {\n            m = lst[pos].match(rangerex);\n            if (m) {\n                if (!m[3] || m[1] === m[3]) {\n                    if (m[4].length < m[2].length) {\n                        m[4] = m[2].slice(0, (m[2].length - m[4].length)) + m[4];\n                    }\n                    if (parseInt(m[2], 10) < parseInt(m[4], 10)) {\n                        m[3] = range_delimiter + (m[1] ? m[1] : \"\");\n                        lst[pos] = m.slice(1);\n                    }\n                }\n            }\n            if (\"string\" === typeof lst[pos]) {\n                lst[pos] = lst[pos].replace(/\\-/g, range_delimiter);\n            }\n        }\n        return lst;\n    };\n\n    minimize = function (lst, minchars, isyear) {\n        len = lst.length;\n        for (var i = 1, ilen = lst.length; i < ilen; i += 2) {\n            if (\"object\" === typeof lst[i]) {\n                lst[i][3] = minimize_internal(lst[i][1], lst[i][3], minchars, isyear);\n                if (lst[i][2].slice(1) === lst[i][0]) {\n                    lst[i][2] = range_delimiter;\n                }\n            }\n        }\n        return stringify(lst);\n    };\n\n    minimize_internal = function (begin, end, minchars, isyear) {\n        if (!minchars) {\n            minchars = 0;\n        }\n        b = (\"\" + begin).split(\"\");\n        e = (\"\" + end).split(\"\");\n        ret = e.slice();\n        ret.reverse();\n        if (b.length === e.length) {\n            for (var i = 0, ilen = b.length; i < ilen; i += 1) {\n                if (b[i] === e[i] && ret.length > minchars) {\n                    ret.pop();\n                } else {\n                    if (minchars && isyear && ret.length === 3) {\n                        var front = b.slice(0, i);\n                        front.reverse();\n                        ret = ret.concat(front);\n                    }\n                    break;\n                }\n            }\n        }\n        ret.reverse();\n        return ret.join(\"\");\n    };\n\n    chicago15 = function (lst) {\n        len = lst.length;\n        for (pos = 1; pos < len; pos += 2) {\n            if (\"object\" === typeof lst[pos]) {\n                m = lst[pos];\n                begin = parseInt(m[1], 10);\n                end = parseInt(m[3], 10);\n                if (begin > 100 && begin % 100 && parseInt((begin / 100), 10) === parseInt((end / 100), 10)) {\n                    m[3] = \"\" + (end % 100);\n                } else if (begin >= 10000) {\n                    m[3] = \"\" + (end % 1000);\n                }\n            }\n            if (m[2].slice(1) === m[0]) {\n                m[2] = range_delimiter;\n            }\n        }\n        return stringify(lst);\n    };\n\n    chicago16 = function (lst) {\n        len = lst.length;\n        for (pos = 1; pos < len; pos += 2) {\n            if (\"object\" === typeof lst[pos]) {\n                m = lst[pos];\n                begin = parseInt(m[1], 10);\n                end = parseInt(m[3], 10);\n                e = \"\" + end;\n                if (begin > 100 && begin % 100) {\n                    for (var i = 2; i < e.length; i++) {\n                        var divisor = Math.pow(10, i);\n                        if (Math.floor(begin / divisor) === Math.floor(end / divisor)) {\n                            m[3] = \"\" + (end % divisor);\n                            break;\n                        }\n                    }\n                }\n            }\n            if (m[2].slice(1) === m[0]) {\n                m[2] = range_delimiter;\n            }\n        }\n        return stringify(lst);\n    };\n\n    //\n    // The top-level option handlers.\n    //\n    var sniff = function (str, func, minchars, isyear) {\n        var ret;\n\t\tstr = \"\" + str;\n\t\tvar lst = expand(str);\n        var ret = func(lst, minchars, isyear);\n        return ret;\n    };\n    if (!state.opt[rangeType + \"-range-format\"]) {\n        ret_func = function (str) {\n            //return str.replace(\"-\", \"\\u2013\", \"g\");\n            return sniff(str, stringify);\n        };\n    } else if (state.opt[rangeType + \"-range-format\"] === \"expanded\") {\n        ret_func = function (str) {\n            return sniff(str, stringify);\n        };\n    } else if (state.opt[rangeType + \"-range-format\"] === \"minimal\") {\n        ret_func = function (str) {\n            return sniff(str, minimize);\n        };\n    } else if (state.opt[rangeType + \"-range-format\"] === \"minimal-two\") {\n        ret_func = function (str, isyear) {\n            return sniff(str, minimize, 2, isyear);\n        };\n    } else if (state.opt[rangeType + \"-range-format\"] === \"chicago\") {\n        ret_func = function (str) {\n            return sniff(str, chicago15);\n        };\n    } else if (state.opt[rangeType + \"-range-format\"] === \"chicago-15\") {\n        ret_func = function (str) {\n            return sniff(str, chicago15);\n        };\n    } else if (state.opt[rangeType + \"-range-format\"] === \"chicago-16\") {\n        ret_func = function (str) {\n            return sniff(str, chicago16);\n        };\n    }\n\n    return ret_func;\n};\n\n\n/*global CSL: true */\n\n// Use a state machine\n\n// Okay, good!\n// Needs some tweaks:\n// 1. First pass: quotes only\n//    Special: Convert all sandwiched single-quote markup to apostrophe\n// 2. Second pass: tags\n\nCSL.Util.FlipFlopper = function(state) {\n    \n    /**\n     * INTERNAL\n     */\n\n    var _nestingState = [];\n\n    var _nestingData = {\n        \"<span class=\\\"nocase\\\">\": {\n            type: \"nocase\",\n            opener: \"<span class=\\\"nocase\\\">\",\n            closer: \"</span>\",\n            attr: null,\n            outer: null,\n            flipflop: null\n        },\n        \"<span class=\\\"nodecor\\\">\": {\n            type: \"nodecor\",\n            opener: \"<span class=\\\"nodecor\\\">\",\n            closer: \"</span>\",\n            attr: \"@class\",\n            outer: \"nodecor\",\n            flipflop: {\n                \"nodecor\": \"nodecor\"\n            }\n        },\n        \"<span style=\\\"font-variant:small-caps;\\\">\": {\n            type: \"tag\",\n            opener: \"<span style=\\\"font-variant:small-caps;\\\">\",\n            closer: \"</span>\",\n            attr: \"@font-variant\",\n            outer: \"small-caps\",\n            flipflop: {\n                \"small-caps\": \"normal\",\n                \"normal\": \"small-caps\"\n            }\n        },\n        \"<sc>\": {\n            type: \"tag\",\n            opener: \"<sc>\",\n            closer: \"</sc>\",\n            attr: \"@font-variant\",\n            outer: \"small-caps\",\n            flipflop: {\n                \"small-caps\": \"normal\",\n                \"normal\": \"small-caps\"\n            }\n        },\n        \"<i>\": {\n            type: \"tag\",\n            opener: \"<i>\",\n            closer: \"</i>\",\n            attr: \"@font-style\",\n            outer: \"italic\",\n            flipflop: {\n                \"italic\": \"normal\",\n                \"normal\": \"italic\"\n            }\n        },\n        \"<b>\": {\n            type: \"tag\",\n            opener: \"<b>\",\n            closer: \"</b>\",\n            attr: \"@font-weight\",\n            outer: \"bold\",\n            flipflop: {\n                \"bold\": \"normal\",\n                \"normal\": \"bold\"\n            }\n        },\n        \"<sup>\": {\n            type: \"tag\",\n            opener: \"<sup>\",\n            closer: \"</sup>\",\n            attr: \"@vertical-align\",\n            outer: \"sup\",\n            flipflop: {\n                \"sub\": \"sup\",\n                \"sup\": \"sup\"\n            }\n        },\n        \"<sub>\": {\n            type: \"tag\",\n            opener: \"<sub>\",\n            closer: \"</sub>\",\n            attr: \"@vertical-align\",\n            outer: \"sub\",\n            flipflop: {\n                \"sup\": \"sub\",\n                \"sub\": \"sub\"\n            }\n        },\n        \" \\\"\": {\n            type: \"quote\",\n            opener: \" \\\"\",\n            closer: \"\\\"\",\n            attr: \"@quotes\",\n            outer: \"true\",\n            flipflop: {\n                \"true\": \"inner\",\n                \"inner\": \"true\",\n                \"false\": \"true\"\n            }\n        },\n        \" \\'\": {\n            type: \"quote\",\n            opener: \" \\'\",\n            closer: \"\\'\",\n            attr: \"@quotes\",\n            outer: \"inner\",\n            flipflop: {\n                \"true\": \"inner\",\n                \"inner\": \"true\",\n                \"false\": \"true\"\n            }\n        }\n    };\n\n    _nestingData[\"(\\\"\"] = _nestingData[\" \\\"\"];\n    _nestingData[\"(\\'\"] = _nestingData[\" \\'\"];\n\n    var localeOpenQuote = state.getTerm(\"open-quote\");\n    var localeCloseQuote = state.getTerm(\"close-quote\");\n    var localeOpenInnerQuote = state.getTerm(\"open-inner-quote\");\n    var localeCloseInnerQuote = state.getTerm(\"close-inner-quote\");\n\n    // If locale uses straight quotes, do not register them. All will be well.\n    // Otherwise, clone straight-quote data, and adjust.\n    if (localeOpenQuote && localeCloseQuote && [\" \\\"\",\" \\'\",\"\\\"\",\"\\'\"].indexOf(localeOpenQuote) === -1) {\n        _nestingData[localeOpenQuote] = JSON.parse(JSON.stringify(_nestingData[\" \\\"\"]));\n        _nestingData[localeOpenQuote].opener = localeOpenQuote;\n        _nestingData[localeOpenQuote].closer = localeCloseQuote;\n    }\n    \n    if (localeOpenInnerQuote && localeCloseInnerQuote && [\" \\\"\",\" \\'\",\"\\\"\",\"\\'\"].indexOf(localeOpenInnerQuote) === -1) {\n        _nestingData[localeOpenInnerQuote] = JSON.parse(JSON.stringify(_nestingData[\" \\'\"]));\n        _nestingData[localeOpenInnerQuote].opener = localeOpenInnerQuote;\n        _nestingData[localeOpenInnerQuote].closer = localeCloseInnerQuote;\n    }\n    \n    function _setOuterQuoteForm(quot) {\n        var flip = {\n            \" \\'\": \" \\\"\",\n            \" \\\"\": \" \\'\",\n            \"(\\\"\": \"(\\'\",\n            \"(\\'\": \"(\\\"\"\n        };\n        _nestingData[quot].outer = \"true\";\n        _nestingData[flip[quot]].outer = \"inner\";\n    }\n    \n    function _getNestingOpenerParams(opener) {\n        var openers = [];\n        var keys = Object.keys(_nestingData);\n        for (var i = 0, l = keys.length; i < l; i++) {\n            var key = keys[i];\n            if (_nestingData[opener].type !== \"quote\" || !_nestingData[opener]) {\n                openers.push(key);\n            }\n        }\n        var ret = _nestingData[opener];\n        ret.opener = new RegExp(\"^(?:\" + openers.map(function(str){\n            return str.replace(\"(\", \"\\\\(\");\n        }).join(\"|\") + \")\");\n        return ret;\n    }\n\n    var _nestingParams = (function() {\n        var ret = {};\n        var keys = Object.keys(_nestingData);\n        for (var i = 0, l = keys.length; i < l; i++) {\n            var key = keys[i];\n            ret[key] = _getNestingOpenerParams(key);\n        }\n        return ret;\n    }());\n\n    var _tagRex = (function() {\n        var openers = [];\n        var closers = [];\n        var vals = {};\n        for (var opener in _nestingParams) {\n            openers.push(opener);\n            vals[_nestingParams[opener].closer] = true;\n        }\n        var keys = Object.keys(vals);\n        for (var i = 0, l = keys.length; i < l; i++) {\n            var closer = keys[i];\n            closers.push(closer);\n        }\n\n        var all = openers.concat(closers).map(function(str){\n            return str.replace(\"(\", \"\\\\(\");\n        }).join(\"|\");\n\n        return {\n            matchAll: new RegExp(\"((?:\" + all + \"))\", \"g\"),\n            splitAll: new RegExp(\"(?:\" + all + \")\", \"g\"),\n            open: new RegExp(\"(^(?:\" + openers.map(function(str){\n                return str.replace(\"(\", \"\\\\(\");\n            }).join(\"|\") + \")$)\"),\n            close: new RegExp(\"(^(?:\" + closers.join(\"|\") + \")$)\"),\n        };\n    }());\n\n    function _tryOpen(tag, pos) {\n        var params = _nestingState[_nestingState.length - 1];\n        if (!params || tag.match(params.opener)) {\n            _nestingState.push({\n                type: _nestingParams[tag].type,\n                opener: _nestingParams[tag].opener,\n                closer: _nestingParams[tag].closer,\n                pos: pos\n            });\n            return false;\n        } else {\n            _nestingState.pop();\n            _nestingState.push({\n                type: _nestingParams[tag].type,\n                opener: _nestingParams[tag].opener,\n                closer: _nestingParams[tag].closer,\n                pos: pos\n            });\n            return {\n                fixtag: params.pos\n            };\n        }\n    }\n    \n    function _tryClose(tag, pos) {\n        var params = _nestingState[_nestingState.length - 1];\n        if (params && tag === params.closer) {\n            _nestingState.pop();\n            if (params.type === \"nocase\") {\n                return {\n                    nocase: {\n                        open: params.pos,\n                        close: pos\n                    }\n                };\n            } else {\n                return false;\n            }\n        } else {\n            if (params) {\n                return {\n                    fixtag: params.pos\n                };\n            } else {\n                return {\n                    fixtag: pos\n                };\n            }\n        }\n    }\n    \n    function _pushNestingState(tag, pos) {\n        if (tag.match(_tagRex.open)) {\n            return _tryOpen(tag, pos);\n        } else {\n            return _tryClose(tag, pos);\n        }\n    }\n    \n    function _doppelString(str) {\n        var forcedSpaces = [];\n        // Normalize markup\n        str = str.replace(/(<span)\\s+(style=\\\"font-variant:)\\s*(small-caps);?\\\"[^>]*(>)/g, \"$1 $2$3;\\\"$4\");\n        str = str.replace(/(<span)\\s+(class=\\\"no(?:case|decor)\\\")[^>]*(>)/g, \"$1 $2$3\");\n\n        var match = str.match(_tagRex.matchAll);\n        if (!match) {\n            return {\n                tags: [],\n                strings: [str],\n                forcedSpaces: []\n            };\n        }\n        var split = str.split(_tagRex.splitAll);\n\n        for (var i=0,ilen=match.length-1;i<ilen;i++) {\n            if (_nestingData[match[i]]) {\n                if (split[i+1] === \"\" && [\"\\\"\", \"'\"].indexOf(match[i+1]) > -1) {\n                    match[i+1] = \" \" + match[i+1];\n                    forcedSpaces.push(true);\n                } else {\n                    forcedSpaces.push(false);\n                }\n            }\n        }\n        return {\n            tags: match,\n            strings: split,\n            forcedSpaces: forcedSpaces\n        };\n    }\n\n    var TagReg = function(blob) {\n        var _stack = [];\n        this.set = function (tag) {\n            var attr = _nestingData[tag].attr;\n            var decor = null;\n            for (var i=_stack.length-1;i>-1;i--) {\n                var _decor = _stack[i];\n                if (_decor[0] === attr) {\n                    decor = _decor;\n                    break;\n                }\n            }\n            if (!decor) {\n                var allTheDecor = [state[state.tmp.area].opt.layout_decorations].concat(blob.alldecor);\n                outer:\n                for (var i=allTheDecor.length-1;i>-1;i--) {\n                    var decorset = allTheDecor[i];\n                    if (!decorset) {\n                        continue;\n                    }\n                    for (var j=decorset.length-1;j>-1;j--) {\n                        var _decor = decorset[j];\n                        if (_decor[0] === attr) {\n                            decor = _decor;\n                            break outer;\n                        }\n                    }\n                }\n            }\n            if (!decor) {\n                decor = [attr, _nestingData[tag].outer];\n            } else {\n                decor = [attr, _nestingData[tag].flipflop[decor[1]]];\n            }\n            _stack.push(decor);\n        };\n        this.pair = function () {\n            return _stack[_stack.length-1];\n        };\n        this.pop = function () {\n            _stack.pop();\n        };\n    };\n    \n    function _apostropheForce(tag, str) {\n        if (tag === \"\\'\") {\n            if (str && str.match(/^[^\\,\\.\\?\\:\\;\\ ]/)) {\n                return \"\\u2019\";\n            }\n        } else if (tag === \" \\'\" && str && str.match(/^[\\ ]/)) {\n            return \" \\u2019\";\n        }\n        return false;\n    }\n\n    function _undoppelToQueue(blob, doppel, leadingSpace) {\n        var firstString = true;\n        var tagReg = new TagReg(blob);\n        blob.blobs = [];\n        function Stack (blob) {\n            this.stack = [blob];\n            this.latest = blob;\n            this.addStyling = function(str, decor) {\n                if (firstString) {\n                    if (str.slice(0, 1) === \" \") {\n                        str = str.slice(1);\n                    }\n                    if (str.slice(0, 1) === \" \") {\n                        str = str.slice(1);\n                    }\n                    firstString = false;\n                }\n                this.latest = this.stack[this.stack.length-1];\n                if (decor) {\n                    if (\"string\" === typeof this.latest.blobs) {\n                        var child = new CSL.Blob();\n                        child.blobs = this.latest.blobs;\n                        child.alldecor = this.latest.alldecor.slice();\n                        this.latest.blobs = [child];\n                    }\n                    var tok = new CSL.Token();\n                    var newblob = new CSL.Blob(null, tok);\n                    newblob.alldecor = this.latest.alldecor.slice();\n                    \n                    // AHA! Bad naming. There is _decorset from the list, and\n                    // there WAS decorset that we are building. Dumb. Fix the\n                    // names and fix it up.\n                    \n                    if (decor[0] === \"@class\" && decor[1] === \"nodecor\") {\n                        var newdecorset = [];\n                        var seen = {};\n                        var allTheDecor = [state[state.tmp.area].opt.layout_decorations].concat(newblob.alldecor);\n                        for (var i=allTheDecor.length-1;i>-1;i--) {\n                            var _decorset = allTheDecor[i];\n                            if (!_decorset) {\n                                continue;\n                            }\n                            for (var j=_decorset.length-1;j>-1;j--) {\n                                var _olddecor = _decorset[j];\n                                if ([\"@font-weight\", \"@font-style\", \"@font-variant\"].indexOf(_olddecor[0]) > -1\n                                    && !seen[_olddecor[0]]) {\n                                    \n                                    if (decor[1] !== \"normal\") {\n                                        newblob.decorations.push([_olddecor[0], \"normal\"]);\n                                        newdecorset.push([_olddecor[0], \"normal\"]);\n                                    }\n                                    seen[_olddecor[0]] = true;\n                                }\n                            }\n                        }\n                        newblob.alldecor.push(newdecorset);\n                        \n                    } else {\n                        newblob.decorations.push(decor);\n                        newblob.alldecor.push([decor]);\n                    }\n                    this.latest.blobs.push(newblob);\n                    this.stack.push(newblob);\n                    this.latest = newblob;\n                    if (str) {\n                        var tok = new CSL.Token();\n                        var newblob = new CSL.Blob(null, tok);\n                        newblob.blobs = str;\n                        newblob.alldecor = this.latest.alldecor.slice();\n                        this.latest.blobs.push(newblob);\n                    }\n                } else {\n                    if (str) {\n                        var child = new CSL.Blob();\n                        child.blobs = str;\n                        child.alldecor = this.latest.alldecor.slice();\n                        this.latest.blobs.push(child);\n                    }\n                }\n            };\n            this.popStyling = function() {\n                this.stack.pop();\n            };\n        }\n        var stack = new Stack(blob);\n        if (doppel.strings.length) {\n            var str = doppel.strings[0];\n            if (leadingSpace) {\n                str = \" \" + str;\n            }\n            stack.addStyling(str);\n        }\n        for (var i=0,ilen=doppel.tags.length;i<ilen;i++) {\n            var tag = doppel.tags[i];\n            var str = doppel.strings[i+1];\n            if (tag.match(_tagRex.open)) {\n                tagReg.set(tag);\n                stack.addStyling(str, tagReg.pair());\n            } else {\n                tagReg.pop();\n                stack.popStyling();\n                stack.addStyling(str);\n            }\n        }\n    }\n\n    /**\n     * PUBLIC\n     */\n\n    this.processTags = function (blob) {\n        var str = blob.blobs;\n        var leadingSpace = false;\n        if (str.slice(0, 1) === \" \" && !str.match(/^\\s+[\\'\\\"]/)) {\n            leadingSpace = true;\n        }\n        var rex = new RegExp(\"(\" + CSL.ROMANESQUE_REGEXP.source + \")\\u2019(\" + CSL.ROMANESQUE_REGEXP.source + \")\", \"g\");\n        var str = \" \" + str.replace(rex, \"$1\\'$2\");\n        var doppel = _doppelString(str);\n        if (doppel.tags.length === 0) {\n            return;\n        }\n        var quoteFormSeen = false;\n        \n    \tfor (var i=0,ilen=doppel.tags.length;i<ilen;i++) {\n            var tag = doppel.tags[i];\n            var str = doppel.strings[i+1];\n            var apostrophe = _apostropheForce(tag, str);\n            if (apostrophe) {\n                doppel.strings[i+1] = apostrophe + doppel.strings[i+1];\n                doppel.tags[i] = \"\";\n            } else {\n                var tagInfo;\n                while (true) {\n                    tagInfo = _pushNestingState(tag, i);\n                    if (tagInfo) {\n                        if (Object.keys(tagInfo).indexOf(\"fixtag\") > -1) {\n                            if (tag.match(_tagRex.close)\n                                && tag === \"\\'\") {\n                                \n                                doppel.strings[i+1] = \"\\u2019\" + doppel.strings[i+1];\n                                doppel.tags[i] = \"\";\n                            } else {\n                                var failedTag = doppel.tags[tagInfo.fixtag];\n                                if (doppel.forcedSpaces[tagInfo.fixtag-1]) {\n                                    failedTag = failedTag.slice(1);\n                                }\n                                doppel.strings[tagInfo.fixtag+1] = failedTag + doppel.strings[tagInfo.fixtag+1];\n                                doppel.tags[tagInfo.fixtag] = \"\";\n                            }\n                            if (_nestingState.length > 0) {\n                                if (tag !== \"\\'\") {\n                                    _nestingState.pop();\n                                } else {\n                                    break;\n                                }\n                            } else {\n                                break;\n                            }\n                        } else if (tagInfo.nocase) {\n                            doppel.tags[tagInfo.nocase.open] = \"\";\n                            doppel.tags[tagInfo.nocase.close] = \"\";\n                            break;\n                        } else {\n                            break;\n                        }\n                    } else {\n                        break;\n                    }\n                }\n                if (tagInfo && (tagInfo.fixtag|| tagInfo.fixtag === 0)) {\n                    doppel.strings[i+1] = doppel.tags[i] + doppel.strings[i+1];\n                    doppel.tags[i] = \"\";\n                }\n            }\n        }\n        // Stray tags are neutralized here\n        for (var i=_nestingState.length-1;i>-1;i--) {\n            var tagPos = _nestingState[i].pos;\n            var tag = doppel.tags[tagPos];\n            if (tag === \" \\'\" || tag === \"\\'\") {\n\n                doppel.strings[tagPos+1] = \" \\u2019\" + doppel.strings[tagPos+1];\n            } else {\n                doppel.strings[tagPos+1] = doppel.tags[tagPos] + doppel.strings[tagPos+1];\n            }\n            doppel.tags[tagPos] = \"\";\n            _nestingState.pop();\n        }\n        for (var i=doppel.tags.length-1;i>-1;i--) {\n            if (!doppel.tags[i]) {\n                doppel.tags = doppel.tags.slice(0,i).concat(doppel.tags.slice(i+1));\n                doppel.strings[i] = doppel.strings[i] + doppel.strings[i+1];\n                doppel.strings = doppel.strings.slice(0,i+1).concat(doppel.strings.slice(i+2));\n            }\n        }\n        // Sniff initial (outer) quote form (single or double) and configure parser\n        // Also add leading spaces.\n        for (var i=0,ilen=doppel.tags.length;i<ilen;i++) {\n            var tag = doppel.tags[i];\n            var forcedSpace = doppel.forcedSpaces[i-1];\n            if ([\" \\\"\", \" \\'\", \"(\\\"\", \"(\\'\"].indexOf(tag) > -1) {\n                if (!quoteFormSeen) {\n                    _setOuterQuoteForm(tag);\n                    quoteFormSeen = true;\n                }\n                if (!forcedSpace) {\n                    doppel.strings[i] += tag.slice(0, 1);\n                }\n            }\n        }\n        //print(JSON.stringify(doppel, null, 2))\n        //print(_undoppelString(doppel));\n        _undoppelToQueue(blob, doppel, leadingSpace);\n    };\n};\n\n/*global CSL: true */\n\nCSL.Output.Formatters = (function () {\n    var rexStr = \"(?:\\u2018|\\u2019|\\u201C|\\u201D| \\\"| \\'|\\\"|\\'|[-\\u2013\\u2014\\/.,;?!:]|\\\\[|\\\\]|\\\\(|\\\\)|<span style=\\\"font-variant: small-caps;\\\">|<span class=\\\"no(?:case|decor)\\\">|<\\/span>|<\\/?(?:i|sc|b|sub|sup)>)\";\n    var tagDoppel = new CSL.Doppeler(rexStr, function(str) {\n        return str.replace(/(<span)\\s+(class=\\\"no(?:case|decor)\\\")[^>]*(>)/g, \"$1 $2$3\").replace(/(<span)\\s+(style=\\\"font-variant:)\\s*(small-caps);?(\\\")[^>]*(>)/g, \"$1 $2 $3;$4$5\");\n    });\n    var rexNameStr = \"(?:[-\\\\s]*<\\\\/*(?:span\\s+class=\\\"no(?:case|decor)\\\"|i|sc|b|sub|sup)>[-\\\\s]*|[-\\\\s]+)\";\n    var nameDoppel = new CSL.Doppeler(rexNameStr);\n    \n    var wordDoppel = new CSL.Doppeler(\"(?:[\\u00A0\\u0020\\u00A0\\u2000-\\u200B\\u205F\\u3000]+)\");\n    \n    /**\n     * INTERNAL\n     */\n\n    var _tagParams = {\n        \"<span style=\\\"font-variant: small-caps;\\\">\": \"</span>\",\n        \"<span class=\\\"nocase\\\">\": \"</span>\",\n        \"<span class=\\\"nodecor\\\">\": \"</span>\",\n        \"<sc>\": \"</sc>\",\n        \"<sub>\": \"</sub>\",\n        \"<sup>\": \"</sup>\"\n    };\n\n    function _capitalise (word) {\n        // Weird stuff is (.) transpiled with regexpu\n        //   https://github.com/mathiasbynens/regexpu\n        var m = word.match(/(^\\s*)((?:[\\0-\\t\\x0B\\f\\x0E-\\u2027\\u202A-\\uD7FF\\uE000-\\uFFFF]|[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF]))(.*)/);\n        // Do not uppercase lone Greek letters\n        // (No case transforms in Greek citations, but chars used in titles to science papers)\n        if (m && !(m[2].match(/^[\\u0370-\\u03FF]$/) && !m[3])) {\n            return m[1] + CSL.toLocaleUpperCase.call(this, m[2]) + m[3];\n        }\n        return word;\n    }\n\n    function _textcaseEngine(config, string) {\n        if (!string) {\n            return \"\";\n        }\n        config.doppel = tagDoppel.split(string);\n        var quoteParams = {\n            \" \\\"\": {\n                opener: \" \\'\",\n                closer: \"\\\"\"\n            },\n            \" \\'\": {\n                opener: \" \\\"\",\n                closer: \"\\'\"\n            },\n            \"\\u2018\": {\n                opener: \"\\u2018\",\n                closer: \"\\u2019\"\n            },\n            \"\\u201C\": {\n                opener: \"\\u201C\",\n                closer: \"\\u201D\"\n            },\n        };\n        function tryOpen(tag, pos) {\n            if (config.quoteState.length === 0 || tag === config.quoteState[config.quoteState.length - 1].opener) {\n                config.quoteState.push({\n                    opener: quoteParams[tag].opener,\n                    closer: quoteParams[tag].closer,\n                    pos: pos\n                });\n                return false;\n            } else {\n                var prevPos = config.quoteState[config.quoteState.length-1].pos;\n                config.quoteState.pop();\n                config.quoteState.push({\n                    opener: quoteParams[tag].opener,\n                    closer: quoteParams[tag].closer,\n                    positions: pos\n                });\n                return prevPos;\n            }\n        }\n        function tryClose(tag, pos) {\n            if (config.quoteState.length > 0 && tag === config.quoteState[config.quoteState.length - 1].closer) {\n                config.quoteState.pop();\n            } else {\n                return pos;\n            }\n        }\n        function pushQuoteState(tag, pos) {\n            var isOpener = [\"\\u201C\", \"\\u2018\", \" \\\"\", \" \\'\"].indexOf(tag) > -1 ? true : false;\n            if (isOpener) {\n                return tryOpen(tag, pos);\n            } else {\n                return tryClose(tag, pos);\n            }\n        }\n        function quoteFix (tag, positions) {\n            var m = tag.match(/(^(?:\\u2018|\\u2019|\\u201C|\\u201D|\\\"|\\')|(?: \\\"| \\')$)/);\n            if (m) {\n                return pushQuoteState(m[1], positions);\n            }\n        }\n        // Run state machine\n        if (config.doppel.strings.length && config.doppel.strings[0].trim()) {\n            config.doppel.strings[0] = config.capitaliseWords(config.doppel.strings[0], 0, config.doppel.tags[0]);\n        }\n\n    \tfor (var i=0,ilen=config.doppel.tags.length;i<ilen;i++) {\n            var tag = config.doppel.tags[i];\n            var str = config.doppel.strings[i+1];\n\n            if (config.tagState !== null) {\n                // Evaluate tag state for current string\n                if (_tagParams[tag]) {\n                    config.tagState.push(_tagParams[tag]);\n                } else if (config.tagState.length && tag === config.tagState[config.tagState.length - 1]) {\n                    config.tagState.pop();\n                }\n            }\n\n            if (config.afterPunct !== null) {\n                // Evaluate punctuation state of current string\n                if (tag.match(/[\\!\\?\\:]$/)) {\n                    config.afterPunct = true;\n                }\n            }\n\n            // Process if outside tag scope, else noop for upper-casing\n            if (config.tagState.length === 0) {\n                config.doppel.strings[i+1] = config.capitaliseWords(str, i+1, config.doppel,config.doppel.tags[i+1]);\n                \n            } else if (config.doppel.strings[i+1].trim()) {\n                config.lastWordPos = null;\n            }\n            \n            if (config.quoteState !== null) {\n                // Evaluate quote state of current string and fix chars that have flown\n                var quotePos = quoteFix(tag, i);\n                if (quotePos || quotePos === 0) {\n                    var origChar = config.doppel.origStrings[quotePos+1].slice(0, 1);\n                    config.doppel.strings[quotePos+1] = origChar + config.doppel.strings[quotePos+1].slice(1);\n                    config.lastWordPos = null;\n                }\n            }\n\n            // If there was a printable string, unset first-word and after-punctuation\n            if (config.isFirst) {\n                if (str.trim()) {\n                    config.isFirst = false;\n                }\n            }\n            if (config.afterPunct) {\n                if (str.trim()) {\n                    config.afterPunct = false;\n                }\n            }\n        }\n        if (config.quoteState) {\n            for (var i=0,ilen=config.quoteState.length;i<ilen;i++) {\n                var quotePos = config.quoteState[i].pos;\n                // Test for quotePos avoids a crashing error:\n                //   https://github.com/citation-style-language/test-suite/blob/master/processor-tests/humans/flipflop_OrphanQuote.txt\n                if (typeof quotePos !== 'undefined') {\n                    var origChar = config.doppel.origStrings[quotePos+1].slice(0, 1);\n                    config.doppel.strings[quotePos+1] = origChar + config.doppel.strings[quotePos+1].slice(1);\n                }\n            }\n        }\n        // Specially capitalize the last word if necessary (invert stop-word list)\n        if (config.lastWordPos) {\n            var lastWords = wordDoppel.split(config.doppel.strings[config.lastWordPos.strings]);\n            var lastWord = lastWords.strings[config.lastWordPos.words];\n            if (lastWord.length > 1 && CSL.toLocaleLowerCase.call(this, lastWord).match(config.skipWordsRex)) {\n                lastWord = _capitalise.call(this, lastWord);\n                lastWords.strings[config.lastWordPos.words] = lastWord;\n            }\n            config.doppel.strings[config.lastWordPos.strings] = wordDoppel.join(lastWords);\n        }\n\n        // Recombine the string\n        return tagDoppel.join(config.doppel);\n    }\n\n    /**\n     * PUBLIC\n     */\n\n    /**\n     * A noop that just delivers the string.\n     */\n    function passthrough (state, str) {\n        return str;\n    }\n\n    /**\n     * Force all letters in the string to lowercase, skipping nocase spans\n     */\n    function lowercase(state, string) {\n        var config = {\n            quoteState: null,\n            capitaliseWords: function(str) {\n                var words = str.split(\" \");\n                for (var i=0,ilen=words.length;i<ilen;i++) {\n                    var word = words[i];\n                    if (word) {\n                        words[i] = CSL.toLocaleLowerCase.call(state, word);\n                    }\n                }\n                return words.join(\" \");\n            },\n            skipWordsRex: null,\n            tagState: [],\n            afterPunct: null,\n            isFirst: null\n        };\n        return _textcaseEngine.call(state, config, string);\n    }\n\n    /**\n     * Force all letters in the string to uppercase.\n     */\n    function uppercase(state, string) {\n        var config = {\n            quoteState: null,\n            capitaliseWords: function(str) {\n                var words = str.split(\" \");\n                for (var i=0,ilen=words.length;i<ilen;i++) {\n                    var word = words[i];\n                    if (word) {\n                        // Okay.\n                        // So we need to pick up an array of locales from state.tmp.\n                        // This function is invoked in the context of queue.js, so\n                        // the item is not available here. Three levels to be included\n                        // in the array:\n                        // 1. Field language tag, if any\n                        // 2. Item language tag, if any\n                        // 3. Value of state.opt.lang\n                        words[i] = CSL.toLocaleUpperCase.call(state, word);\n                    }\n                }\n                return words.join(\" \");\n            },\n            skipWordsRex: null,\n            tagState: [],\n            afterPunct: null,\n            isFirst: null\n        };\n        return _textcaseEngine.call(state, config, string);\n    }\n\n    /**\n     * Similar to <b>capitalize_first</b>, but force the\n     * subsequent characters to lowercase.\n     */\n    function sentence(state, string) {\n        var config = {\n            quoteState: [],\n            capitaliseWords: function(str) {\n                var words = str.split(\" \");\n                for (var i=0,ilen=words.length;i<ilen;i++) {\n                    var word = words[i];\n                    if (word) {\n                        if (config.isFirst) {\n                            words[i] = _capitalise.call(state, word);\n                            config.isFirst = false;\n                        } else {\n                            words[i] = CSL.toLocaleLowerCase.call(state, word);\n                        }\n                    }\n                }\n                return words.join(\" \");\n            },\n            skipWordsRex: null,\n            tagState: [],\n            afterPunct: null,\n            isFirst: true\n        };\n        return _textcaseEngine.call(state, config, string);\n    }\n\n    function title(state, string) {\n        var config = {\n            quoteState: [],\n            capitaliseWords: function(str, i, followingTag) {\n                if (str.trim()) {\n                    var wordle = wordDoppel.split(str);\n                    var words = wordle.strings;\n                    for (var j=0,jlen=words.length;j<jlen;j++) {\n                        var word = words[j];\n                        if (!word) {\n                            continue;\n                        }\n                        let lcase = CSL.toLocaleLowerCase.call(state, word);\n                        let capitalize = false;\n                        if (word.length > 1 && !lcase.match(config.skipWordsRex)) {\n                            // Capitalize every word that is not a stop-word\n                            capitalize = true;\n                        } else if (j === (words.length - 1) && followingTag === \"-\") {\n                            capitalize = true;\n                        } else if (config.isFirst) {\n                            // Capitalize first word, even if a stop-word\n                            capitalize = true;\n                        } else if (config.afterPunct) {\n                            // Capitalize after punctuation\n                            capitalize = true;\n                        }\n                        // Don't capitalize if word already contains capitalization\n                        if (capitalize && word === lcase) {\n                            words[j] = _capitalise.call(state, word);\n                        }\n                        config.afterPunct = false;\n                        config.isFirst = false;\n                        config.lastWordPos = {\n                            strings: i,\n                            words: j\n                        };\n                    }\n                    str = wordDoppel.join(wordle);\n                }\n                return str;\n            },\n            skipWordsRex: state.locale[state.opt.lang].opts[\"skip-words-regexp\"],\n            tagState: [],\n            afterPunct: false,\n            isFirst: true\n        };\n        return _textcaseEngine.call(state, config, string);\n    }\n    \n    \n    /**\n     * Force capitalization of the first letter in the string, leave\n     * the rest of the characters untouched.\n     */\n    function capitalizeFirst(state, string) {\n        var config = {\n            quoteState: [],\n            capitaliseWords: function(str) {\n                var wordle = wordDoppel.split(str);\n                var words = wordle.strings;\n                for (var i=0,ilen=words.length;i<ilen;i++) {\n                    var word = words[i];\n                    if (word) {\n                        if (config.isFirst) {\n                            // Don't capitalize if word already contains capitalization\n                            if (word === CSL.toLocaleLowerCase.call(state, word)) {\n                                words[i] = _capitalise.call(state, word);\n                            }\n                            config.isFirst = false;\n                            break;\n                        }\n                    }\n                }\n                return wordDoppel.join(wordle);\n            },\n            skipWordsRex: null,\n            tagState: [],\n            afterPunct: null,\n            isFirst: true\n        };\n        return _textcaseEngine.call(state, config, string);\n    }\n\n    /**\n     * Force the first letter of each space-delimited\n     * word in the string to uppercase, and leave the remainder\n     * of the string untouched.  Single characters are forced\n     * to uppercase.\n     */\n    function capitalizeAll (state, string) {\n        var config = {\n            quoteState: [],\n            capitaliseWords: function(str) {\n                var wordle = wordDoppel.split(str);\n                var words = wordle.strings;\n                for (var i=0,ilen=words.length;i<ilen;i++) {\n                    var word = words[i];\n                    if (word) {\n                        // Don't capitalize if word already contains capitalization\n                        if (word === CSL.toLocaleLowerCase.call(state, word)) {\n                            words[i] = _capitalise.call(state, word);\n                        }\n                    }\n                }\n                return wordDoppel.join(wordle);\n            },\n            skipWordsRex: null,\n            tagState: [],\n            afterPunct: null,\n            isFirst: null\n        };\n        return _textcaseEngine.call(state, config, string);\n    }\n    return {\n        nameDoppel: nameDoppel,\n        passthrough: passthrough,\n        lowercase: lowercase,\n        uppercase: uppercase,\n        sentence: sentence,\n        title: title,\n        \"capitalize-first\": capitalizeFirst,\n        \"capitalize-all\": capitalizeAll\n    };\n}());\n\n/*global CSL: true */\n\n\n/**\n * Output specifications.\n * @class\n */\nCSL.Output.Formats = function () {};\n\n/**\n * HTML output format specification.\n * <p>The headline says it all.  The source code for this\n * object can be used as a template for producing other\n * output modes.</p>\n */\nCSL.Output.Formats.prototype.html = {\n    //\n    // text_escape: Format-specific function for escaping text destined\n    // for output.  Takes the text to be escaped as sole argument.  Function\n    // will be run only once across each portion of text to be escaped, it\n    // need not be idempotent.\n    //\n    \"text_escape\": function (text) {\n        // Numeric entities, in case the output is processed as\n        // xml in an environment in which HTML named entities are\n        // not declared.\n        if (!text) {\n            text = \"\";\n        }\n        return text.replace(/&/g, \"&#38;\")\n            .replace(/</g, \"&#60;\")\n            .replace(/>/g, \"&#62;\")\n            .replace(/\\s\\s/g, \"\\u00A0 \")\n            .replace(CSL.SUPERSCRIPTS_REGEXP,\n                     function(aChar) {\n                         // return \"&#60;sup&#62;\" + CSL.SUPERSCRIPTS[aChar] + \"&#60;/sup&#62;\";\n                         return \"<sup>\" + CSL.SUPERSCRIPTS[aChar] + \"</sup>\";\n                     });\n    },\n    \"bibstart\": \"<div class=\\\"csl-bib-body\\\">\\n\",\n    \"bibend\": \"</div>\",\n    \"@font-style/italic\": \"<i>%%STRING%%</i>\",\n    \"@font-style/oblique\": \"<em>%%STRING%%</em>\",\n    \"@font-style/normal\": \"<span style=\\\"font-style:normal;\\\">%%STRING%%</span>\",\n    \"@font-variant/small-caps\": \"<span style=\\\"font-variant:small-caps;\\\">%%STRING%%</span>\",\n    \"@passthrough/true\": CSL.Output.Formatters.passthrough,\n    \"@font-variant/normal\": \"<span style=\\\"font-variant:normal;\\\">%%STRING%%</span>\",\n    \"@font-weight/bold\": \"<b>%%STRING%%</b>\",\n    \"@font-weight/normal\": \"<span style=\\\"font-weight:normal;\\\">%%STRING%%</span>\",\n    \"@font-weight/light\": false,\n    \"@text-decoration/none\": \"<span style=\\\"text-decoration:none;\\\">%%STRING%%</span>\",\n    \"@text-decoration/underline\": \"<span style=\\\"text-decoration:underline;\\\">%%STRING%%</span>\",\n    \"@vertical-align/sup\": \"<sup>%%STRING%%</sup>\",\n    \"@vertical-align/sub\": \"<sub>%%STRING%%</sub>\",\n    \"@vertical-align/baseline\": \"<span style=\\\"baseline\\\">%%STRING%%</span>\",\n    \"@strip-periods/true\": CSL.Output.Formatters.passthrough,\n    \"@strip-periods/false\": CSL.Output.Formatters.passthrough,\n    \"@quotes/true\": function (state, str) {\n        if (\"undefined\" === typeof str) {\n            return state.getTerm(\"open-quote\");\n        }\n        return state.getTerm(\"open-quote\") + str + state.getTerm(\"close-quote\");\n    },\n    \"@quotes/inner\": function (state, str) {\n        if (\"undefined\" === typeof str) {\n            //\n            // Mostly right by being wrong (for apostrophes)\n            //\n            return \"\\u2019\";\n        }\n        return state.getTerm(\"open-inner-quote\") + str + state.getTerm(\"close-inner-quote\");\n    },\n    \"@quotes/false\": false,\n    //\"@bibliography/body\": function (state,str){\n    //    return \"<div class=\\\"csl-bib-body\\\">\\n\"+str+\"</div>\";\n    //},\n    \"@cite/entry\": function (state, str) {\n        return state.sys.wrapCitationEntry(str, this.item_id, this.locator_txt, this.suffix_txt);\n\t},\n    \"@bibliography/entry\": function (state, str) {\n        // Test for this.item_id to add decorations to\n        // bibliography output of individual entries.\n        //\n        // Full item content can be obtained from\n        // state.registry.registry[id].ref, using\n        // CSL variable keys.\n        //\n        // Example:\n        //\n        //   print(state.registry.registry[this.item_id].ref[\"title\"]);\n        //\n        // At present, for parallel citations, only the\n        // id of the master item is supplied on this.item_id.\n        var insert = \"\";\n        if (state.sys.embedBibliographyEntry) {\n            insert = state.sys.embedBibliographyEntry(this.item_id) + \"\\n\";\n        }\n        return \"  <div class=\\\"csl-entry\\\">\" + str + \"</div>\\n\" + insert;\n    },\n    \"@display/block\": function (state, str) {\n        return \"\\n\\n    <div class=\\\"csl-block\\\">\" + str + \"</div>\\n\";\n    },\n    \"@display/left-margin\": function (state, str) {\n        return \"\\n    <div class=\\\"csl-left-margin\\\">\" + str + \"</div>\";\n    },\n    \"@display/right-inline\": function (state, str) {\n        return \"<div class=\\\"csl-right-inline\\\">\" + str + \"</div>\\n  \";\n    },\n    \"@display/indent\": function (state, str) {\n        return \"<div class=\\\"csl-indent\\\">\" + str + \"</div>\\n  \";\n    },\n    \"@showid/true\": function (state, str, cslid) {\n        if (!state.tmp.just_looking && ! state.tmp.suppress_decorations) {\n            if (cslid) {\n                return \"<span class=\\\"\" + state.opt.nodenames[cslid] + \"\\\" cslid=\\\"\" + cslid + \"\\\">\" + str + \"</span>\";\n            } else if (this.params && \"string\" === typeof str) {\n                var prePunct = \"\";\n                if (str) {\n                    var m = str.match(CSL.VARIABLE_WRAPPER_PREPUNCT_REX);\n                    prePunct = m[1];\n                    str = m[2];\n                }\n                var postPunct = \"\";\n                if (str && CSL.SWAPPING_PUNCTUATION.indexOf(str.slice(-1)) > -1) {\n                    postPunct = str.slice(-1);\n                    str = str.slice(0,-1);\n                }\n                return state.sys.variableWrapper(this.params, prePunct, str, postPunct);\n            } else {\n                return str;\n            }\n        } else {\n            return str;\n        }\n    },\n    \"@URL/true\": function (state, str) {\n        return \"<a href=\\\"\" + str + \"\\\">\" + str + \"</a>\";\n    },\n    \"@DOI/true\": function (state, str) {\n        var doiurl = str;\n        if (!str.match(/^https?:\\/\\//)) {\n            doiurl = \"https://doi.org/\" + str;\n        }\n        return \"<a href=\\\"\" + doiurl + \"\\\">\" + str + \"</a>\";\n    }\n};\n\n/**\n * Plain text output specification.\n *\n * (Code contributed by Simon Kornblith, Center for History and New Media,\n * George Mason University.)\n */\nCSL.Output.Formats.prototype.text = {\n    //\n    // text_escape: Format-specific function for escaping text destined\n    // for output.  Takes the text to be escaped as sole argument.  Function\n    // will be run only once across each portion of text to be escaped, it\n    // need not be idempotent.\n    //\n    \"text_escape\": function (text) {\n        if (!text) {\n            text = \"\";\n        }\n        return text;\n    },\n    \"bibstart\": \"\",\n    \"bibend\": \"\",\n    \"@font-style/italic\": false,\n    \"@font-style/oblique\": false,\n    \"@font-style/normal\": false,\n    \"@font-variant/small-caps\": false,\n    \"@passthrough/true\": CSL.Output.Formatters.passthrough,\n    \"@font-variant/normal\": false,\n    \"@font-weight/bold\": false,\n    \"@font-weight/normal\": false,\n    \"@font-weight/light\": false,\n    \"@text-decoration/none\": false,\n    \"@text-decoration/underline\": false,\n    \"@vertical-align/baseline\": false,\n    \"@vertical-align/sup\": false,\n    \"@vertical-align/sub\": false,\n    \"@strip-periods/true\": CSL.Output.Formatters.passthrough,\n    \"@strip-periods/false\": CSL.Output.Formatters.passthrough,\n    \"@quotes/true\": function (state, str) {\n        if (\"undefined\" === typeof str) {\n            return state.getTerm(\"open-quote\");\n        }\n        return state.getTerm(\"open-quote\") + str + state.getTerm(\"close-quote\");\n    },\n    \"@quotes/inner\": function (state, str) {\n        if (\"undefined\" === typeof str) {\n            //\n            // Mostly right by being wrong (for apostrophes)\n            //\n            return \"\\u2019\";\n        }\n        return state.getTerm(\"open-inner-quote\") + str + state.getTerm(\"close-inner-quote\");\n    },\n    \"@quotes/false\": false,\n    //\"@bibliography/body\": function (state,str){\n    //    return \"<div class=\\\"csl-bib-body\\\">\\n\"+str+\"</div>\";\n    //},\n    \"@cite/entry\": function (state, str) {\n\t\treturn state.sys.wrapCitationEntry(str, this.item_id, this.locator_txt, this.suffix_txt);\n\t},\n    \"@bibliography/entry\": function (state, str) {\n        return str+\"\\n\";\n    },\n    \"@display/block\": function (state, str) {\n        return \"\\n\"+str;\n    },\n    \"@display/left-margin\": function (state, str) {\n        return str + \" \";\n    },\n    \"@display/right-inline\": function (state, str) {\n        return str;\n    },\n    \"@display/indent\": function (state, str) {\n        return \"\\n    \"+str;\n    },\n    \"@showid/true\": function (state, str) {\n        return str;\n    },\n    \"@URL/true\": function (state, str) {\n        return str;\n    },\n    \"@DOI/true\": function (state, str) {\n        return str;\n    }\n};\n\n/**\n * Plain text output specification.\n *\n * (Code contributed by Simon Kornblith, Center for History and New Media,\n * George Mason University.)\n */\nCSL.Output.Formats.prototype.rtf = {\n    //\n    // text_escape: Format-specific function for escaping text destined\n    // for output.  Takes the text to be escaped as sole argument.  Function\n    // will be run only once across each portion of text to be escaped, it\n    // need not be idempotent.\n    //\n    \"text_escape\": function (text) {\n        if (!text) {\n            text = \"\";\n        }\n        return text\n        .replace(/([\\\\{}])/g, \"\\\\$1\")\n        .replace(CSL.SUPERSCRIPTS_REGEXP,\n                 function(aChar) {\n                     return \"\\\\super \" + CSL.SUPERSCRIPTS[aChar] + \"\\\\nosupersub{}\";\n                 })\n        .replace(/[\\u007F-\\uFFFF]/g,\n                 function(aChar) { return \"\\\\uc0\\\\u\"+aChar.charCodeAt(0).toString()+\"{}\"; })\n        .split(\"\\t\").join(\"\\\\tab{}\");\n    },\n    \"@passthrough/true\": CSL.Output.Formatters.passthrough,\n    \"@font-style/italic\":\"{\\\\i{}%%STRING%%}\",\n    \"@font-style/normal\":\"{\\\\i0{}%%STRING%%}\",\n    \"@font-style/oblique\":\"{\\\\i{}%%STRING%%}\",\n    \"@font-variant/small-caps\":\"{\\\\scaps %%STRING%%}\",\n    \"@font-variant/normal\":\"{\\\\scaps0{}%%STRING%%}\",\n    \"@font-weight/bold\":\"{\\\\b{}%%STRING%%}\",\n    \"@font-weight/normal\":\"{\\\\b0{}%%STRING%%}\",\n    \"@font-weight/light\":false,\n    \"@text-decoration/none\":false,\n    \"@text-decoration/underline\":\"{\\\\ul{}%%STRING%%}\",\n    \"@vertical-align/baseline\":false,\n    \"@vertical-align/sup\":\"\\\\super %%STRING%%\\\\nosupersub{}\",\n    \"@vertical-align/sub\":\"\\\\sub %%STRING%%\\\\nosupersub{}\",\n    \"@strip-periods/true\": CSL.Output.Formatters.passthrough,\n    \"@strip-periods/false\": CSL.Output.Formatters.passthrough,\n    \"@quotes/true\": function (state, str) {\n        if (\"undefined\" === typeof str) {\n            return CSL.Output.Formats.rtf.text_escape(state.getTerm(\"open-quote\"));\n        }\n        return CSL.Output.Formats.rtf.text_escape(state.getTerm(\"open-quote\")) + str + CSL.Output.Formats.rtf.text_escape(state.getTerm(\"close-quote\"));\n    },\n    \"@quotes/inner\": function (state, str) {\n        if (\"undefined\" === typeof str) {\n            return CSL.Output.Formats.rtf.text_escape(\"\\u2019\");\n        }\n        return CSL.Output.Formats.rtf.text_escape(state.getTerm(\"open-inner-quote\")) + str + CSL.Output.Formats.rtf.text_escape(state.getTerm(\"close-inner-quote\"));\n    },\n    \"@quotes/false\": false,\n    \"bibstart\":\"{\\\\rtf \",\n    \"bibend\":\"}\",\n    \"@display/block\": \"\\\\line{}%%STRING%%\\\\line\\r\\n\",\n    \"@cite/entry\": function (state, str) {\n        // If wrapCitationEntry does not exist, cite/entry \n        // is not applied.\n\t\treturn state.sys.wrapCitationEntry(str, this.item_id, this.locator_txt, this.suffix_txt);\n\t},\n    \"@bibliography/entry\": function(state,str){\n        return str;\n    },\n    \"@display/left-margin\": function(state,str){\n        return str+\"\\\\tab \";\n    },\n    \"@display/right-inline\": function (state, str) {\n        return str+\"\\r\\n\";\n    },\n    \"@display/indent\": function (state, str) {\n        return \"\\n\\\\tab \"+str+\"\\\\line\\r\\n\";\n    },\n    \"@showid/true\": function (state, str) {\n        if (!state.tmp.just_looking && ! state.tmp.suppress_decorations) {\n            var prePunct = \"\";\n            if (str) {\n                var m = str.match(CSL.VARIABLE_WRAPPER_PREPUNCT_REX);\n                prePunct = m[1];\n                str = m[2];\n            }\n            var postPunct = \"\";\n            if (str && CSL.SWAPPING_PUNCTUATION.indexOf(str.slice(-1)) > -1) {\n                postPunct = str.slice(-1);\n                str = str.slice(0,-1);\n            }\n            return state.sys.variableWrapper(this.params, prePunct, str, postPunct);\n        } else {\n            return str;\n        }\n    },\n    \"@URL/true\": function (state, str) {\n        return str;\n    },\n    \"@DOI/true\": function (state, str) {\n        return str;\n    }\n};\n\n/*\n\n    This does not seem to work in Zotero plugins. For some reason the scope of the link does not\n    close when interpreted by the LibreOffice. Perhaps this creates a field within a field,\n    and that is not allowed?\n\n    \"@URL/true\": function (state, str) {\n        return \"\\\\field{\\\\*\\\\fldinst{HYPERLINK \\\"\" + str + \"\\\"}}{\\\\fldrslt{\"+ str +\"}}\";\n    },\n    \"@DOI/true\": function (state, str) {\n        return \"\\\\field{\\\\*\\\\fldinst{HYPERLINK \\\"https://doi.org/\" + str + \"\\\"}}{\\\\fldrslt{\"+ str +\"}}\";\n    }\n*/\n\n/**\n * AsciiDoc output specification.\n *\n * See http://asciidoc.org/ or https://asciidoctor.org/\n */\nCSL.Output.Formats.prototype.asciidoc = {\n    \"text_escape\": function (text) {\n        if (!text) {\n            text = \"\";\n        }\n        return text.replace(\"*\", \"pass:[*]\", \"g\")\n            .replace(\"_\", \"pass:[_]\", \"g\")\n            .replace(\"#\", \"pass:[#]\", \"g\")\n            .replace(\"^\", \"pass:[^]\", \"g\")\n            .replace(\"~\", \"pass:[~]\", \"g\")\n            .replace(\"[[\", \"pass:[[[]\", \"g\")\n            .replace(\"  \", \"&#160; \", \"g\")\n            .replace(CSL.SUPERSCRIPTS_REGEXP, function(aChar) {\n                return \"^\" + CSL.SUPERSCRIPTS[aChar] + \"^\";\n            });\n    },\n    \"bibstart\": \"\",\n    \"bibend\": \"\",\n    \"@passthrough/true\": CSL.Output.Formatters.passthrough,\n    \"@font-style/italic\": \"__%%STRING%%__\",\n    \"@font-style/oblique\": \"__%%STRING%%__\",\n    \"@font-style/normal\": false,\n    \"@font-variant/small-caps\": \"[small-caps]#%%STRING%%#\",\n    \"@font-variant/normal\": false,\n    \"@font-weight/bold\": \"**%%STRING%%**\",\n    \"@font-weight/normal\": false,\n    \"@font-weight/light\": false,\n    \"@text-decoration/none\": false,\n    \"@text-decoration/underline\": \"[underline]##%%STRING%%##\",\n    \"@vertical-align/sup\": \"^^%%STRING%%^^\",\n    \"@vertical-align/sub\": \"~~%%STRING%%~~\",\n    \"@vertical-align/baseline\": false,\n    \"@strip-periods/true\": CSL.Output.Formatters.passthrough,\n    \"@strip-periods/false\": CSL.Output.Formatters.passthrough,\n    \"@quotes/true\": function (state, str) {\n        if (\"undefined\" === typeof str) {\n            return \"``\";\n        }\n        return \"``\" + str + \"''\";\n    },\n    \"@quotes/inner\": function (state, str) {\n        if (\"undefined\" === typeof str) {\n            return \"`\";\n        }\n        return \"`\" + str + \"'\";\n    },\n    \"@quotes/false\": false,\n    \"@cite/entry\": function (state, str) {\n        // if wrapCitationEntry does not exist, cite/entry is not applied\n        return state.sys.wrapCitationEntry(str, this.item_id, this.locator_txt, this.suffix_txt);\n    },\n    \"@bibliography/entry\": function (state, str) {\n        return str + \"\\n\";\n    },\n    \"@display/block\": function (state, str) {\n        return str;\n    },\n    \"@display/left-margin\": function (state, str) {\n        return str;\n    },\n    \"@display/right-inline\": function (state, str) {\n        return \" \" + str;\n    },\n    \"@display/indent\": function (state, str) {\n        return \" \" + str;\n    },\n    \"@showid/true\": function (state, str) {\n        if (!state.tmp.just_looking && !state.tmp.suppress_decorations && this.params && \"string\" === typeof str) {\n            var prePunct = \"\";\n            if (str) {\n                var m = str.match(CSL.VARIABLE_WRAPPER_PREPUNCT_REX);\n                prePunct = m[1];\n                str = m[2];\n            }\n            var postPunct = \"\";\n            if (str && CSL.SWAPPING_PUNCTUATION.indexOf(str.slice(-1)) > -1) {\n                postPunct = str.slice(-1);\n                str = str.slice(0,-1);\n            }\n            return state.sys.variableWrapper(this.params, prePunct, str, postPunct);\n        } else {\n            return str;\n        }\n    },\n    \"@URL/true\": function (state, str) {\n        // AsciiDoc renders URLs automatically as links\n        return str;\n    },\n    \"@DOI/true\": function (state, str) {\n        var doiurl = str;\n        if (!str.match(/^https?:\\/\\//)) {\n            doiurl = \"https://doi.org/\" + str;\n        }\n        return doiurl + \"[\" + str + \"]\";\n    }\n};\n\n/**\n * Output specification for XSL-FO (Extensible Stylesheet\n * Language - Formatting Objects)\n *\n * See https://www.w3.org/TR/xsl11/#fo-section\n */\nCSL.Output.Formats.prototype.fo = {\n    \"text_escape\": function (text) {\n        if (!text) {\n            text = \"\";\n        }\n        return text.replace(/&/g, \"&#38;\")\n            .replace(/</g, \"&#60;\")\n            .replace(/>/g, \"&#62;\")\n            .replace(\"  \", \"&#160; \", \"g\")\n            .replace(CSL.SUPERSCRIPTS_REGEXP, function(aChar) {\n                return \"<fo:inline vertical-align=\\\"super\\\">\" + CSL.SUPERSCRIPTS[aChar] + \"</fo:inline>\";\n            });\n    },\n    \"bibstart\": \"\",\n    \"bibend\": \"\",\n    \"@passthrough/true\": CSL.Output.Formatters.passthrough,\n    \"@font-style/italic\": \"<fo:inline font-style=\\\"italic\\\">%%STRING%%</fo:inline>\",\n    \"@font-style/oblique\": \"<fo:inline font-style=\\\"oblique\\\">%%STRING%%</fo:inline>\",\n    \"@font-style/normal\": \"<fo:inline font-style=\\\"normal\\\">%%STRING%%</fo:inline>\",\n    \"@font-variant/small-caps\": \"<fo:inline font-variant=\\\"small-caps\\\">%%STRING%%</fo:inline>\",\n    \"@font-variant/normal\": \"<fo:inline font-variant=\\\"normal\\\">%%STRING%%</fo:inline>\",\n    \"@font-weight/bold\": \"<fo:inline font-weight=\\\"bold\\\">%%STRING%%</fo:inline>\",\n    \"@font-weight/normal\": \"<fo:inline font-weight=\\\"normal\\\">%%STRING%%</fo:inline>\",\n    \"@font-weight/light\": \"<fo:inline font-weight=\\\"lighter\\\">%%STRING%%</fo:inline>\",\n    \"@text-decoration/none\": \"<fo:inline text-decoration=\\\"none\\\">%%STRING%%</fo:inline>\",\n    \"@text-decoration/underline\": \"<fo:inline text-decoration=\\\"underline\\\">%%STRING%%</fo:inline>\",\n    \"@vertical-align/sup\": \"<fo:inline vertical-align=\\\"super\\\">%%STRING%%</fo:inline>\",\n    \"@vertical-align/sub\": \"<fo:inline vertical-align=\\\"sub\\\">%%STRING%%</fo:inline>\",\n    \"@vertical-align/baseline\": \"<fo:inline vertical-align=\\\"baseline\\\">%%STRING%%</fo:inline>\",\n    \"@strip-periods/true\": CSL.Output.Formatters.passthrough,\n    \"@strip-periods/false\": CSL.Output.Formatters.passthrough,\n    \"@quotes/true\": function (state, str) {\n        if (\"undefined\" === typeof str) {\n            return state.getTerm(\"open-quote\");\n        }\n        return state.getTerm(\"open-quote\") + str + state.getTerm(\"close-quote\");\n    },\n    \"@quotes/inner\": function (state, str) {\n        if (\"undefined\" === typeof str) {\n            return \"\\u2019\";\n        }\n        return state.getTerm(\"open-inner-quote\") + str + state.getTerm(\"close-inner-quote\");\n    },\n    \"@quotes/false\": false,\n    \"@cite/entry\": function (state, str) {\n        return state.sys.wrapCitationEntry(str, this.item_id, this.locator_txt, this.suffix_txt);\n    },\n    \"@bibliography/entry\": function (state, str) {\n        var indent = \"\";\n        if (state.bibliography && state.bibliography.opt && state.bibliography.opt.hangingindent) {\n            var hi = state.bibliography.opt.hangingindent;\n            indent = \" start-indent=\\\"\" + hi +\"em\\\" text-indent=\\\"-\" + hi + \"em\\\"\";\n        }\n        var insert = \"\";\n        if (state.sys.embedBibliographyEntry) {\n            insert = state.sys.embedBibliographyEntry(this.item_id) + \"\\n\";\n        }\n        return \"<fo:block id=\\\"\" + this.system_id + \"\\\"\" + indent + \">\" + str + \"</fo:block>\\n\" + insert;\n    },\n    \"@display/block\": function (state, str) {\n        return \"\\n  <fo:block>\" + str + \"</fo:block>\\n\";\n    },\n    \"@display/left-margin\": function (state, str) {\n        return \"\\n  <fo:table table-layout=\\\"fixed\\\" width=\\\"100%\\\">\\n    \" +\n                \"<fo:table-column column-number=\\\"1\\\" column-width=\\\"$$$__COLUMN_WIDTH_1__$$$\\\"/>\\n    \" +\n                \"<fo:table-column column-number=\\\"2\\\" column-width=\\\"proportional-column-width(1)\\\"/>\\n    \" +\n                \"<fo:table-body>\\n      \" +\n                    \"<fo:table-row>\\n        \" +\n                        \"<fo:table-cell>\\n          \" +\n                            \"<fo:block>\" + str + \"</fo:block>\\n        \" +\n                        \"</fo:table-cell>\\n        \";\n    },\n    \"@display/right-inline\": function (state, str) {\n        return \"<fo:table-cell>\\n          \" +\n                \"<fo:block>\" + str + \"</fo:block>\\n        \" +\n            \"</fo:table-cell>\\n      \" +\n            \"</fo:table-row>\\n    \" +\n            \"</fo:table-body>\\n  \" +\n            \"</fo:table>\\n\";\n    },\n    \"@display/indent\": function (state, str) {\n        return \"<fo:block margin-left=\\\"2em\\\">\" + str + \"</fo:block>\\n\";\n    },\n    \"@showid/true\": function (state, str) {\n        if (!state.tmp.just_looking && !state.tmp.suppress_decorations && this.params && \"string\" === typeof str) {\n            var prePunct = \"\";\n            if (str) {\n                var m = str.match(CSL.VARIABLE_WRAPPER_PREPUNCT_REX);\n                prePunct = m[1];\n                str = m[2];\n            }\n            var postPunct = \"\";\n            if (str && CSL.SWAPPING_PUNCTUATION.indexOf(str.slice(-1)) > -1) {\n                postPunct = str.slice(-1);\n                str = str.slice(0,-1);\n            }\n            return state.sys.variableWrapper(this.params, prePunct, str, postPunct);\n        } else {\n            return str;\n        }\n    },\n    \"@URL/true\": function (state, str) {\n        return \"<fo:basic-link external-destination=\\\"url('\" + str + \"')\\\">\" + str + \"</fo:basic-link>\";\n    },\n    \"@DOI/true\": function (state, str) {\n        var doiurl = str;\n        if (!str.match(/^https?:\\/\\//)) {\n            doiurl = \"https://doi.org/\" + str;\n        }\n        return \"<fo:basic-link external-destination=\\\"url('\" + doiurl + \"')\\\">\" + str + \"</fo:basic-link>\";\n    }\n};\n\n/**\n * LaTeX .bbl output.\n *\n * (Code contributed by Egon Willighagen, based on the prototype.text code.)\n */\nCSL.Output.Formats.prototype.latex = {\n    \"text_escape\": function (text) {\n        if (!text) {\n            text = \"\";\n        }\n        return text;\n    },\n    \"bibstart\": \"\\\\begin{thebibliography}{4}\",\n    \"bibend\": \"\\\\end{thebibliography}\",\n    \"@font-style/italic\": \"{\\\\em %%STRING%%}\",\n    \"@font-style/oblique\": false,\n    \"@font-style/normal\": false,\n    \"@font-variant/small-caps\": false,\n    \"@passthrough/true\": CSL.Output.Formatters.passthrough,\n    \"@font-variant/normal\": false,\n    \"@font-weight/bold\": \"{\\\\bf %%STRING%%}\",\n    \"@font-weight/normal\": false,\n    \"@font-weight/light\": false,\n    \"@text-decoration/none\": false,\n    \"@text-decoration/underline\": false,\n    \"@vertical-align/baseline\": false,\n    \"@vertical-align/sup\": false,\n    \"@vertical-align/sub\": false,\n    \"@strip-periods/true\": CSL.Output.Formatters.passthrough,\n    \"@strip-periods/false\": CSL.Output.Formatters.passthrough,\n    \"@quotes/true\": function (state, str) {\n        if (\"undefined\" === typeof str) {\n            return state.getTerm(\"open-quote\");\n        }\n        return state.getTerm(\"open-quote\") + str + state.getTerm(\"close-quote\");\n    },\n    \"@quotes/inner\": function (state, str) {\n        if (\"undefined\" === typeof str) {\n            //\n            // Mostly right by being wrong (for apostrophes)\n            //\n            return \"\\u2019\";\n        }\n        return state.getTerm(\"open-inner-quote\") + str + state.getTerm(\"close-inner-quote\");\n    },\n    \"@quotes/false\": false,\n    //\"@bibliography/body\": function (state,str){\n    //    return \"<div class=\\\"csl-bib-body\\\">\\n\"+str+\"</div>\";\n    //},\n    \"@cite/entry\": function (state, str) {\n\t\treturn state.sys.wrapCitationEntry(str, this.item_id, this.locator_txt, this.suffix_txt);\n\t},\n    \"@bibliography/entry\": function (state, str) {\n        return \"\\\\bibitem{\" + state.sys.embedBibliographyEntry(this.item_id) + \"}\\n\";\n    },\n    \"@display/block\": function (state, str) {\n        return \"\\n\"+str;\n    },\n    \"@display/left-margin\": function (state, str) {\n        return str;\n    },\n    \"@display/right-inline\": function (state, str) {\n        return str;\n    },\n    \"@display/indent\": function (state, str) {\n        return \"\\n    \"+str;\n    },\n    \"@showid/true\": function (state, str, cslid) {\n        return str;\n    },\n    \"@URL/true\": function (state, str) {\n        return str;\n    },\n    \"@DOI/true\": function (state, str) {\n        return str;\n    }\n};\n\nCSL.Output.Formats = new CSL.Output.Formats();\n\n/*global CSL: true */\n\n\n//\n// Time for a rewrite of this module.\n//\n// Simon has pointed out that list and hash behavior can\n// be obtained by ... just using a list and a hash.  This\n// is faster for batched operations, because sorting is\n// greatly optimized.  Since most of the interaction\n// with plugins at runtime will involve batches of\n// references, there will be solid gains if the current,\n// one-reference-at-a-time approach implemented here\n// can be replaced with something that leverages the native\n// sort method of the Array() type.\n//\n// That's going to take some redesign, but it will simplify\n// things in the long run, so it might as well happen now.\n//\n// We'll keep makeCitationCluster and makeBibliography as\n// simple methods that return a string.  Neither should\n// have any effect on internal state.  This will be a change\n// in behavior for makeCitationCluster.\n//\n// A new updateItems command will be introduced, to replace\n// insertItems.  It will be a simple list of IDs, in the\n// sequence of first reference in the document.\n//\n// The calling application should always invoke updateItems\n// before makeCitationCluster.\n//\n\n//\n// should allow batched registration of items by\n// key.  should behave as an update, with deletion\n// of items and the tainting of disambiguation\n// partner sets affected by a deletes and additions.\n//\n//\n// we'll need a reset method, to clear the decks\n// in the citation area and start over.\n\n/**\n * Registry of cited items.\n * <p>This is a persistent store of disambiguation and\n * sort order information relating to individual items\n * for which rendering is requested.  Item data is stored\n * in a hash, with the item key as hash key, for quick\n * retrieval.  A virtual sequence within the hashed store\n * is maintained on the fly as items are added to the\n * store, using <code>*_next</code> and <code>*_prev</code>\n * attributes on each item.  A separate hash of items\n * based on their undisambiguated cite form is\n * maintained, and the item id list and disambiguation\n * level for each set of disambiguation partners is shared\n * through the registry item.</p>\n * @class\n */\nCSL.Registry = function (state) {\n    this.debug = false;\n    this.state = state;\n    this.registry = {};\n    this.reflist = [];\n    this.refhash = {};\n    this.namereg = new CSL.Registry.NameReg(state);\n    this.citationreg = new CSL.Registry.CitationReg(state);\n    // See CSL.NameOutput.prototype.outputNames\n    // and CSL.Registry.prototype.doinserts\n    this.authorstrings = {};\n    \n    // for parallel delimiter support\n    this.masterMap = {};\n    \n    //\n    // shared scratch vars\n    this.mylist = [];\n    this.myhash = {};\n    this.deletes = [];\n    this.inserts = [];\n    this.uncited = {};\n    this.refreshes = {};\n    this.akeys = {};\n    this.oldseq = {};\n    this.return_data = {};\n    //\n    // each ambig is a list of the ids of other objects\n    // that have the same base-level rendering\n    this.ambigcites = {};\n    this.ambigresets = {};\n    this.sorter = new CSL.Registry.Comparifier(state, \"bibliography_sort\");\n    //this.modes = CSL.getModes.call(this.state);\n    //this.checkerator = new CSL.Checkerator();\n\n    this.getSortedIds = function () {\n        var ret = [];\n        for (var i = 0, ilen = this.reflist.length; i < ilen; i += 1) {\n            ret.push(\"\" + this.reflist[i].id);\n        }\n        return ret;\n    };\n\n    this.getSortedRegistryItems = function () {\n        var ret = [];\n        for (var i = 0, ilen = this.reflist.length; i < ilen; i += 1) {\n            ret.push(this.reflist[i]);\n        }\n        return ret;\n    };\n};\n\n//\n// Here's the sequence of operations to be performed on\n// update:\n//\n//  1.  (o) [init] Receive list as function argument, store as hash and as list.\n//  2.  (o) [init] Initialize refresh list.  Never needs sorting, only hash required.\n\n//  3.  (o) [dodeletes] Delete loop.\n//  3a. (o) [dodeletes] Delete names in items to be deleted from names reg.\n//  3b. (o) [dodeletes] Complement refreshes list with items affected by\n//      possible name changes.  We'll actually perform the refresh once\n//      all of the necessary data and parameters have been established\n//      in the registry.\n//  3c. (o) [dodeletes] Delete all items to be deleted from their disambig pools.\n//  3d. (o) [dodeletes] Delete all items in deletion list from hash.\n\n//  4.  (o) [doinserts] Insert loop.\n//  4a. (o) [doinserts] Retrieve entries for items to insert.\n//  4b. (o) [doinserts] Generate ambig key.\n//  4c. (o) [doinserts] Add names in items to be inserted to names reg\n//      (implicit in getAmbiguousCite).\n//  4d. (o) [doinserts] Record ambig pool key on akey list (used for updating further\n//      down the chain).\n//  4e. (o) [doinserts] Create registry token.\n//  4f. (o) [doinserts] Add item ID to hash.\n//  4g. (o) [doinserts] Set and record the base token to hold disambiguation\n//      results (\"disambig\" in the object above).\n//  5.  (o) [rebuildlist] Create \"new\" list of hash pointers, in the order given\n//          in the argument to the update function.\n//  6.  (o) [rebuildlist] Apply citation numbers to new list.\n//  7.  (o) [dorefreshes] Refresh items requiring update.\n\n\n\n//  5. (o) [delnames] Delete names in items to be deleted from names reg, and obtain IDs\n//         of other items that would be affected by changes around that surname.\n//  6. (o) [delnames] Complement delete and insert lists with items affected by\n//         possible name changes.\n//  7. (o) [delambigs] Delete all items to be deleted from their disambig pools.\n//  8. (o) [delhash] Delete all items in deletion list from hash.\n\n//  9. (o) [addtohash] Retrieve entries for items to insert.\n// 10. (o) [addtohash] Add items to be inserted to their disambig pools.\n// 11. (o) [addtohash] Add names in items to be inserted to names reg\n//         (implicit in getAmbiguousCite).\n// 12. (o) [addtohash] Create registry token for each item to be inserted.\n// 13. (o) [addtohash] Add items for insert to hash.\n\n// 14. (o) [buildlist] Create \"new\" list of hash pointers, in the order given in the argument\n//         to the update function.\n// 15. (o) [renumber] Apply citation numbers to new list.\n// 16. (o) [setdisambigs] Set disambiguation parameters on each inserted item token.\n// 17. (o) [setsortkeys] Set sort keys on each item token.\n// 18. (o) [sorttokens] Resort token list\n// 19. (o) [renumber] Reset citation numbers on list items\n//\n\nCSL.Registry.prototype.init = function (itemIDs, uncited_flag) {\n    var i, ilen;\n    this.oldseq = {};\n    //  1. Receive list as function argument, store as hash and as list.\n    //\n    // Result:\n    //   this.mylist: a list of all itemIDs of referenced items, cited and uncited.\n    //   this.myhash: a hash of index positions in this.mylist.\n    //   this.uncited: hash of uncited itemIDs.\n    //\n    // Proceed as follows.\n    //\n    if (uncited_flag) {\n        // If uncited_flag is non-nil, add any missing itemIDs to this.mylist\n        // from itemIDs input list, and set the itemIDs in itemIDs on this.uncited.\n        this.uncited = {};\n        for (var i=0,ilen=itemIDs.length;i<ilen; i += 1) {\n            if (!this.myhash[itemIDs[i]]) {\n                this.mylist.push(\"\" + itemIDs[i]);\n            }\n            this.uncited[itemIDs[i]] = true;\n            this.myhash[itemIDs[i]] = true;\n        }\n    } else {\n        // If uncited_flag is nil, remove duplicate itemIDs from itemIDs input\n        // list, set the result on this.mylist, and add missing itemIDs to\n        // this.mylist from itemIDs input list.\n        for (var key in this.uncited) {\n            itemIDs.push(key);\n        }\n        var myhash = {};\n        for (i=itemIDs.length-1;i>-1; i += -1) {\n            if (myhash[itemIDs[i]]) {\n                itemIDs = itemIDs.slice(0, i).concat(itemIDs.slice(i + 1));\n            } else {\n                myhash[itemIDs[i]] = true;\n            }\n        }\n        this.mylist = itemIDs;\n        this.myhash = myhash;\n    }\n    //\n    //  2. Initialize refresh list.  Never needs sorting, only hash required.\n    //\n    this.refreshes = {};\n    this.touched = {};\n    this.ambigsTouched = {};\n    this.ambigresets = {};\n};\n\nCSL.Registry.prototype.dopurge = function (myhash) {\n    // Remove any uncited items not in myhash\n    for (var i=this.mylist.length-1;i>-1;i+=-1) {\n        // Might not want to be quite this restrictive.\n        if (this.citationreg.citationsByItemId) {\n            if ((!this.citationreg.citationsByItemId || !this.citationreg.citationsByItemId[this.mylist[i]]) && !myhash[this.mylist[i]]) {\n                delete this.myhash[this.mylist[i]];\n                delete this.uncited[this.mylist[i]];\n                this.mylist = this.mylist.slice(0,i).concat(this.mylist.slice(i+1));\n            }\n        }\n    }\n    this.dodeletes(this.myhash);\n};\n\nCSL.Registry.prototype.dodeletes = function (myhash) {\n    var otheritems, key, ambig, pos, len, items, kkey, mypos, id;\n    if (\"string\" === typeof myhash) {\n        var key = myhash;\n        myhash = {};\n        myhash[key] = true;\n    }\n    //\n    //  3. Delete loop.\n    //\n    for (var key in this.registry) {\n        if (!myhash[key]) {\n            // skip items explicitly marked as uncited\n            if (this.uncited[key]) {\n                continue;\n            }\n            //\n            //  3a. Delete names in items to be deleted from names reg.\n            //\n            otheritems = this.namereg.delitems(key);\n            //\n            //  3b. Complement refreshes list with items affected by\n            //      possible name changes.  We'll actually perform the refresh once\n            //      all of the necessary data and parameters have been established\n            //      in the registry.\n            //\n            for (kkey in otheritems) {\n                this.refreshes[kkey] = true;\n            }\n            //\n            //  3c. Delete all items to be deleted from their disambig pools.\n            //\n            ambig = this.registry[key].ambig;\n            mypos = this.ambigcites[ambig].indexOf(key);\n            if (mypos > -1) {\n                items = this.ambigcites[ambig].slice();\n                this.ambigcites[ambig] = items.slice(0, mypos).concat(items.slice(mypos+1, items.length));\n                this.ambigresets[ambig] = this.ambigcites[ambig].length;\n            }\n            //\n            // XX. What we've missed is to provide an update of all\n            // items sharing the same ambig  += -1 the remaining items in\n            // ambigcites.  So let's do that here, just in case the\n            // names update above doesn't catch them all.\n            //\n            len = this.ambigcites[ambig].length;\n            for (pos = 0; pos < len; pos += 1) {\n                id = \"\" + this.ambigcites[ambig][pos];\n                this.refreshes[id] = true;\n            }\n            //\n            // 3d-0. Remove parallel id references and realign\n            // parallel ID refs.\n            //\n            if (this.registry[key].siblings) {\n                if (this.registry[key].siblings.length == 1) {\n                    var loneSiblingID = this.registry[key].siblings[0];\n                    if (this.registry[loneSiblingID].siblings) {\n                        this.registry[loneSiblingID].siblings.pop();\n                        this.registry[loneSiblingID].master = true;\n                        // this.registry[loneSiblingID].parallel = false;\n                    }\n                } else if (this.registry[key].siblings.length > 1) {\n                    var removeIDs = [key];\n                    if (this.registry[key].master) {\n                        var newmasterID = this.registry[key].siblings[0];\n                        var newmaster = this.registry[newmasterID];\n                        newmaster.master = true;\n                        // newmaster.parallel_delimiter is set externally, if at all\n                        // newmaster.parallel = false;\n                        removeIDs.push(newmasterID);\n                        // for (var k = 0, klen = this.registry[key].siblings.length; k < klen; k += 1) {\n                        //     this.registry[this.registry[key].siblings[k]].parallel = newmasterID;\n                        // }\n                    }\n                    var buffer = [];\n                    for (var k = this.registry[key].siblings.length - 1; k > -1; k += -1) {\n                        var siblingID = this.registry[key].siblings.pop();\n                        if (removeIDs.indexOf(siblingID) === -1) {\n                            buffer.push(siblingID);\n                        }\n                    }\n                    for (var k = buffer.length - 1; k > -1; k += -1) {\n                        this.registry[key].siblings.push(buffer[k]);\n                    }\n                }\n            }\n            //\n            // 3d-1. Remove item from reflist\n            for (var i=this.reflist.length-1;i>-1;i--) {\n                if (this.reflist[i].id === key) {\n                    this.reflist = this.reflist.slice(0, i).concat(this.reflist.slice(i+1));\n                }\n            }\n            //\n            //  3d. Delete all items in deletion list from hash.\n            //\n            delete this.registry[key];\n            delete this.refhash[key];\n\n            // For processCitationCluster()\n            this.return_data.bibchange = true;\n        }\n    }\n    // Disabled.  See formats.js for code.\n    // this.state.fun.decorate.items_delete( this.state.output[this.state.opt.mode].tmp, myhash );\n};\n\nCSL.Registry.prototype.doinserts = function (mylist) {\n    var item, Item, akey, newitem, abase, i, ilen;\n    if (\"string\" === typeof mylist) {\n        mylist = [mylist];\n    }\n    //\n    //  4. Insert loop.\n    //\n    for (var i = 0, ilen = mylist.length; i < ilen; i += 1) {\n        item = mylist[i];\n        if (!this.registry[item]) {\n            //\n            //  4a. Retrieve entries for items to insert.\n            //\n            Item = this.state.retrieveItem(item);\n\n            //\n            //  4b. Generate ambig key.\n            //\n            // AND\n            //\n            //  4c. Add names in items to be inserted to names reg\n            //      (implicit in getAmbiguousCite).\n            //\n            akey = CSL.getAmbiguousCite.call(this.state, Item);\n            this.ambigsTouched[akey] = true;\n            //\n            //  4d. Record ambig pool key on akey list (used for updating further\n            //      down the chain).\n            //\n            if (!Item.legislation_id) {\n                this.akeys[akey] = true;\n            }\n            //\n            //  4e. Create registry token.\n            //\n            newitem = {\n                \"id\": \"\" + item,\n                \"seq\": 0,\n                \"offset\": 0,\n                \"sortkeys\": false,\n                \"ambig\": false,\n                \"rendered\": false,\n                \"disambig\": false,\n                \"ref\": Item,\n                \"newItem\": true\n            };\n            //\n            //\n            //  4f. Add item ID to hash.\n            //\n            this.registry[item] = newitem;\n            //\n            //  4f(a). Add first reference note number\n            //         (this may be redundant)\n            if (this.citationreg.citationsByItemId && this.citationreg.citationsByItemId[item]) {\n                this.registry[item][\"first-reference-note-number\"] = this.citationreg.citationsByItemId[item][0].properties.noteIndex;\n            }\n\n            //\n            //  4g. Set and record the base token to hold disambiguation\n            //      results (\"disambig\" in the object above).\n            //\n            abase = CSL.getAmbigConfig.call(this.state);\n            this.registerAmbigToken(akey, item, abase);\n\n            //if (!this.ambigcites[akey]){\n            //    this.ambigcites[akey] = [];\n            //}\n            //CSL.debug(\"Run: \"+item+\"(\"+this.ambigcites[akey]+\")\");\n            //if (this.ambigcites[akey].indexOf(item) === -1){\n            //    CSL.debug(\"  Add: \"+item);\n            //    this.ambigcites[akey].push(item);\n            //}\n            //\n            //  4h. Make a note that this item needs its sort keys refreshed.\n            //\n            this.touched[item] = true;\n            // For processCitationCluster()\n            this.return_data.bibchange = true;\n        }\n    }\n    // Disabled.  See formats.js for code.\n    // this.state.fun.decorate.items_add( this.state.output[this.state.opt.mode].tmp, mylist );\n};\n\n/*\n// No longer required.\nCSL.Registry.prototype.douncited = function () {\n    var pos, len;\n    var cited_len = this.mylist.length - this.uncited.length;\n    for (pos = 0, len = cited_len; pos < len; pos += 1) {\n        this.registry[this.mylist[pos]].uncited = false;\n    }\n    for (pos = cited_len, len = this.mylist.length; pos < len; pos += 1) {\n        this.registry[this.mylist[pos]].uncited = true;\n    }\n};\n*/\n\nCSL.Registry.prototype.rebuildlist = function (nosort) {\n    var len, pos, item, Item;\n    //\n    //  5. Create \"new\" list of hash pointers, in the order given in the argument\n    //     to the update function.\n    //\n    //\n    // XXX Keep reflist in place.\n    //\n    if (!nosort) {\n        this.reflist_inserts = [];\n        //\n        //  6. Apply citation numbers to new list,\n        //     saving off old sequence numbers as we go.\n        //\n        // XXX Just memo inserts -- actual insert happens below, at last \"sort\"\n        //\n        len = this.mylist.length;\n        for (pos = 0; pos < len; pos += 1) {\n            item = this.mylist[pos];\n            Item = this.registry[item];\n            if (Item.newItem) {\n                this.reflist_inserts.push(Item);\n            }\n            this.oldseq[item] = this.registry[item].seq;\n            this.registry[item].seq = (pos + 1);\n        }\n    } else {\n        this.reflist = [];\n        len = this.mylist.length;\n        for (pos = 0; pos < len; pos += 1) {\n            item = this.mylist[pos];\n            Item = this.registry[item];\n            this.reflist.push(Item);\n            this.oldseq[item] = this.registry[item].seq;\n            this.registry[item].seq = (pos + 1);\n        }\n    }\n};\n\n/*\n * Okay, at this point we should have a numbered list\n * of registry tokens in the notional order requested,\n * with sequence numbers to reconstruct the ordering\n * if the list is remangled.  So far so good.\n */\n\nCSL.Registry.prototype.dorefreshes = function () {\n    var key, regtoken, Item, akey, abase;\n    //\n    //  7. Refresh items requiring update.\n    //\n    // It looks like we need to do four things on each cite for refresh:\n    // (1) Generate the akey for the cite.\n    // (2) Register it on the ambig token.\n    // (3) Register the akey in this.akeys\n    // (4) Register the item ID in this.touched\n    //\n    for (var key in this.refreshes) {\n        regtoken = this.registry[key];\n        if (!regtoken) {\n            continue;\n        }\n        regtoken.sortkeys = undefined;\n        Item = this.state.refetchItem(key);\n        var akey = regtoken.ambig;\n\n        if (\"undefined\" === typeof akey) {\n            this.state.tmp.disambig_settings = false;\n            akey = CSL.getAmbiguousCite.call(this.state, Item);\n            abase = CSL.getAmbigConfig.call(this.state);\n            this.registerAmbigToken(akey, key, abase);\n        }\n        for (var akkey in this.ambigresets) {\n            if (this.ambigresets[akkey] === 1) {\n                var loneKey = this.ambigcites[akey][0];\n                var Item = this.state.refetchItem(loneKey);\n                this.registry[loneKey].disambig = new CSL.AmbigConfig();\n                this.state.tmp.disambig_settings = false;\n                var akey = CSL.getAmbiguousCite.call(this.state, Item);\n                var abase = CSL.getAmbigConfig.call(this.state);\n                this.registerAmbigToken(akey, loneKey, abase);\n            }\n        }\n        this.state.tmp.taintedItemIDs[key] = true;\n        this.ambigsTouched[akey] = true;\n        if (!Item.legislation_id) {\n            this.akeys[akey] = true;\n        }\n        this.touched[key] = true;\n    }\n};\n\n/*\n * Main disambiguation  += -1 can everything for disambiguation be\n * crunched into this function?\n */\nCSL.Registry.prototype.setdisambigs = function () {\n    //\n    // Okay, more changes.  Here is where we resolve all disambiguation\n    // issues for cites touched by the update.  The this.ambigcites set is\n    // based on the complete short form of citations, and is the basis on\n    // which names are added and minimal adding of initials or given names\n    // is performed.\n    //\n\n    //\n    //  8.  Set disambiguation parameters on each inserted item token.\n    //\n    for (var akey in this.ambigsTouched) {\n        //\n        // Disambiguation is fully encapsulated.\n        // Disambiguator will run only if there are multiple\n        // items, and at least one disambiguation mode is\n        // in effect.\n        this.state.disambiguate.run(akey);\n    }\n    this.ambigsTouched = {};\n    this.akeys = {};\n};\n\n\n\nCSL.Registry.prototype.renumber = function () {\n    var len, pos, item;\n    //\n    // 19. Reset citation numbers on list items\n    //\n    if (this.state.bibliography_sort.opt.citation_number_sort_direction === CSL.DESCENDING) {\n        this.state.bibliography_sort.tmp.citation_number_map = {};\n    }\n    len = this.reflist.length;\n    for (pos = 0; pos < len; pos += 1) {\n        item = this.reflist[pos];\n        // save the overhead of rerenderings if citation-number is not\n        // used in the style.\n        item.seq = (pos + 1);\n        if (this.state.bibliography_sort.opt.citation_number_sort_direction === CSL.DESCENDING) {\n            this.state.bibliography_sort.tmp.citation_number_map[item.seq] = (this.reflist.length - item.seq + 1);\n        }\n        // update_mode is set to CSL.NUMERIC if citation-number is rendered\n        // in citations.\n        if (this.state.opt.update_mode === CSL.NUMERIC && item.seq != this.oldseq[item.id]) {\n            this.state.tmp.taintedItemIDs[item.id] = true;\n        }\n        if (item.seq != this.oldseq[item.id]) {\n            this.return_data.bibchange = true;\n        }\n    }\n};\n\nCSL.Registry.prototype.setsortkeys = function () {\n    var key;\n    //\n    // 17. Set sort keys on each item token.\n    //\n    for (var i = 0, ilen = this.mylist.length; i < ilen; i += 1) {\n        var key = this.mylist[i];\n        // The last of these conditions may create some thrashing on styles that do not require sorting.\n        if (this.touched[key] || this.state.tmp.taintedItemIDs[key] || !this.registry[key].sortkeys) {\n            this.registry[key].sortkeys = CSL.getSortKeys.call(this.state, this.state.retrieveItem(key), \"bibliography_sort\");\n        }\n    }\n};\n\nCSL.Registry.prototype._insertItem = function(element, array) {\n    array.splice(this._locationOf(element, array) + 1, 0, element);\n    return array;\n};\n\nCSL.Registry.prototype._locationOf = function(element, array, start, end) {\n    if (array.length === 0) {\n        return -1;\n    }\n    start = start || 0;\n    end = end || array.length;\n    var pivot = (start + end) >> 1;  // should be faster than dividing by 2\n    \n    var c = this.sorter.compareKeys(element, array[pivot]);\n    if (end - start <= 1) {\n        return c == -1 ? pivot - 1 : pivot;\n    }\n    switch (c) {\n        case -1: return this._locationOf(element, array, start, pivot);\n        case 0: return pivot;\n        case 1: return this._locationOf(element, array, pivot, end);\n    }\n};\n\nCSL.Registry.prototype.sorttokens = function (nosort) {\n    var len, item, Item, pos;\n    //\n    // 18. Resort token list.\n    //\n    if (!nosort) {\n        this.reflist_inserts = [];\n        len = this.mylist.length;\n        for (pos = 0; pos < len; pos += 1) {\n            item = this.mylist[pos];\n            Item = this.registry[item];\n            if (Item.newItem) {\n                this.reflist_inserts.push(Item);\n            }\n        }\n        // There is a thin possibility that tainted items in a sorted list\n        // will change position due to disambiguation. We cover for that here.\n        for (var key in this.state.tmp.taintedItemIDs) {\n            if (this.registry[key] && !this.registry[key].newItem) {\n                // Move tainted items from reflist to reflist_inserts\n                for (var i=this.reflist.length-1;i>-1;i--) {\n                    if (this.reflist[i].id === key) {\n                        this.reflist_inserts.push(this.reflist[i]);\n                        this.reflist = this.reflist.slice(0, i).concat(this.reflist.slice(i+1));\n                    }\n                }\n            }\n        }\n        for (var i=0,ilen=this.reflist_inserts.length;i<ilen;i++) {\n            var Item = this.reflist_inserts[i];\n            delete Item.newItem;\n            this.reflist = this._insertItem(Item, this.reflist);\n        }\n        for (pos = 0; pos < len; pos += 1) {\n            item = this.mylist[pos];\n            Item = this.registry[item];\n            this.registry[item].seq = (pos + 1);\n        }\n    }\n};\n\n/**\n * Compare two sort keys\n * <p>Nested, because keys are an array.</p>\n */\nCSL.Registry.Comparifier = function (state, keyset) {\n    var sort_directions, len, pos, compareKeys;\n    var sortCompare = CSL.getSortCompare.call(state, state.opt[\"default-locale-sort\"]);\n    sort_directions = state[keyset].opt.sort_directions;\n    this.compareKeys = function (a, b) {\n        len = a.sortkeys ? a.sortkeys.length : 0;\n        for (pos = 0; pos < len; pos += 1) {\n            //\n            // for ascending sort 1 uses 1, -1 uses -1.\n            // For descending sort, the values are reversed.\n            //\n            // Need to handle undefined values.  No way around it.\n            // So have to screen .localeCompare (which is also\n            // needed) from undefined values.  Everywhere, in all\n            // compares.\n            //\n            var cmp = 0;\n            if (a.sortkeys[pos] === b.sortkeys[pos]) {\n                cmp = 0;\n            } else if (\"undefined\" === typeof a.sortkeys[pos]) {\n                cmp = sort_directions[pos][1];\n            } else if (\"undefined\" === typeof b.sortkeys[pos]) {\n                cmp = sort_directions[pos][0];\n            } else {\n                // cmp = a.sortkeys[pos].localeCompare(b.sortkeys[pos]);\n                cmp = sortCompare(a.sortkeys[pos], b.sortkeys[pos]);\n            }\n            if (0 < cmp) {\n                return sort_directions[pos][1];\n            } else if (0 > cmp) {\n                return sort_directions[pos][0];\n            }\n        }\n        if (a.seq > b.seq) {\n            return 1;\n        } else if (a.seq < b.seq) {\n            return -1;\n        }\n        return 0;\n    };\n    compareKeys = this.compareKeys;\n    this.compareCompositeKeys = function (a, b) {\n        return compareKeys(a[1], b[1]);\n    };\n};\n\n\n/**\n * Compare two disambiguation tokens by their registry sort order\n * <p>Disambiguation lists need to be sorted this way, to\n * obtain the correct year-suffix when that's used.</p>\n */\nCSL.Registry.prototype.compareRegistryTokens = function (a, b) {\n    if (a.seq > b.seq) {\n        return 1;\n    } else if (a.seq < b.seq) {\n        return -1;\n    }\n    return 0;\n};\n\nCSL.Registry.prototype.registerAmbigToken = function (akey, id, ambig_config) {\n    //SNIP-START\n    if (!this.registry[id]) {\n        CSL.debug(\"Warning: unregistered item: itemID=(\"+id+\"), akey=(\"+akey+\")\");\n    }\n    //SNIP-END\n    // Taint if number of names to be included has changed\n    if (this.registry[id] && this.registry[id].disambig && this.registry[id].disambig.names) {\n        for (var i = 0, ilen = ambig_config.names.length; i < ilen; i += 1) {\n            var new_names_params = ambig_config.names[i];\n            var old_names_params = this.registry[id].disambig.names[i];\n            if (new_names_params !== old_names_params) {\n                this.state.tmp.taintedItemIDs[id] = true;\n            } else if (ambig_config.givens[i]) {\n                // Compare givenses only if the number of names is aligned.\n                for (var j=0,jlen=ambig_config.givens[i].length;j<jlen;j+=1) {\n                    var new_gnames_params = ambig_config.givens[i][j];\n                    var old_gnames_params = this.registry[id].disambig.givens[i][j];\n                    if (new_gnames_params !== old_gnames_params) {\n                        this.state.tmp.taintedItemIDs[id] = true;\n                    }\n                }\n            }\n        }\n    }\n\n    if (!this.ambigcites[akey]) {\n        this.ambigcites[akey] = [];\n    }\n    if (this.ambigcites[akey].indexOf(\"\" + id) === -1) {\n        this.ambigcites[akey].push(\"\" + id);\n    }\n    this.registry[id].ambig = akey;\n    this.registry[id].disambig = CSL.cloneAmbigConfig(ambig_config);\n};\n\n\n/**\n * Get the sort key of an item, without decorations\n * <p>This is used internally by the Registry.</p>\n */\nCSL.getSortKeys = function (Item, key_type) {\n    var area, root, extension, strip_prepositions, len, pos;\n    //SNIP-START\n    if (false) {\n        CSL.debug(\"KEY TYPE: \" + key_type);\n    }\n    //SNIP-END\n    area = this.tmp.area;\n    root = this.tmp.root;\n    extension = this.tmp.extension;\n    strip_prepositions = CSL.Util.Sort.strip_prepositions;\n    this.tmp.area = key_type;\n    // Gawdawful, this.\n    this.tmp.root = key_type.indexOf(\"_\") > -1 ? key_type.slice(0,-5) : key_type;\n    this.tmp.extension = \"_sort\";\n    this.tmp.disambig_override = true;\n    this.tmp.disambig_request = false;\n    this.tmp.suppress_decorations = true;\n    CSL.getCite.call(this, Item);\n    this.tmp.suppress_decorations = false;\n    this.tmp.disambig_override = false;\n    len = this[key_type].keys.length;\n    for (pos = 0; pos < len; pos += 1) {\n        this[key_type].keys[pos] = strip_prepositions(this[key_type].keys[pos]);\n    }\n    //SNIP-START\n    if (false) {\n        CSL.debug(\"sort keys (\" + key_type + \"): \" + this[key_type].keys);\n    }\n    //SNIP-END\n    \n    this.tmp.area = area;\n    this.tmp.root = root;\n    this.tmp.extension = extension;\n    return this[key_type].keys;\n};\n\n\n/*global CSL: true */\n\nCSL.Registry.NameReg = function (state) {\n    var pkey, ikey, skey, dagopt, gdropt, items, strip_periods, set_keys, evalname, delitems, addname, myitems;\n    this.state = state;\n    this.namereg = {};\n    this.nameind = {};\n    // used for restoring state following preview\n    this.nameindpkeys = {};\n    //\n    // family, initials form, fullname (with given stripped of periods)\n    //\n    // keys registered, indexed by ID\n    this.itemkeyreg = {};\n\n    strip_periods = function (str) {\n        if (!str) {\n            str = \"\";\n        }\n        return str.replace(/\\./g, \" \").replace(/\\s+/g, \" \").replace(/\\s+$/,\"\");\n    };\n\n    set_keys = function (state, itemid, nameobj) {\n        pkey = strip_periods(nameobj.family);\n\n        if (state.opt[\"demote-non-dropping-particle\"] === \"never\" && nameobj[\"non-dropping-particle\"] && nameobj[\"family\"]) {\n            pkey = `${pkey} ${nameobj[\"non-dropping-particle\"]}`;\n        }\n        \n        skey = strip_periods(nameobj.given);\n        // Drop lowercase suffixes (such as et al.) from given name field\n        // for disambiguation purposes.\n        var m = skey.match(/[,\\!]* ([^,]+)$/);\n        if (m && m[1] === m[1].toLowerCase()) {\n            skey = skey.replace(/[,\\!]* [^,]+$/, \"\");\n        }\n        // The %s terminator enables normal initialization behavior\n        // with non-Byzantine names.\n        ikey = CSL.Util.Names.initializeWith(state, skey, \"%s\");\n        if (state.citation.opt[\"givenname-disambiguation-rule\"] === \"by-cite\") {\n            pkey = \"\" + itemid + pkey;\n        }\n    };\n\n    evalname = function (item_id, nameobj, namenum, request_base, form, initials) {\n        var param;\n        // XXX THIS CAN NO LONGER HAPPEN\n        if (state.tmp.area.slice(0, 12) === \"bibliography\" && !form) {\n            if (\"string\" === typeof initials) {\n                return 1;\n            } else {\n                return 2;\n            }\n        }\n        var res = state.nameOutput.getName(nameobj, \"locale-translit\", true);\n        nameobj = res.name;\n        set_keys(this.state, \"\" + item_id, nameobj);\n        //\n        // possible options are:\n        //\n        // <option disambiguate-add-givenname value=\"true\"/> (a)\n        // <option disambiguate-add-givenname value=\"all-names\"/> (a)\n        // <option disambiguate-add-givenname value=\"all-names-with-initials\"/> (b)\n        // <option disambiguate-add-givenname value=\"primary-name\"/> (d)\n        // <option disambiguate-add-givenname value=\"primary-name-with-initials\"/> (e)\n        // <option disambiguate-add-givenname value=\"by-cite\"/> (g)\n        //\n        param = 2;\n        dagopt = state.opt[\"disambiguate-add-givenname\"];\n        gdropt = state.citation.opt[\"givenname-disambiguation-rule\"];\n        var gdropt_orig = gdropt;\n        if (gdropt === \"by-cite\") {\n            gdropt = \"all-names\";\n        }\n        //\n        // set initial value\n        //\n        if (\"short\" === form) {\n            param = 0;\n        } else if (\"string\" === typeof initials) {\n            param = 1;\n        }\n        //\n        // give literals a pass\n        if (\"undefined\" === typeof this.namereg[pkey] || \"undefined\" === typeof this.namereg[pkey].ikey[ikey]) {\n            return param;\n        }\n        //\n        // adjust value upward if appropriate -- only if running\n        // a non-names-global disambiguation strategy\n        //\n        if (gdropt_orig === \"by-cite\" && param <= request_base) {\n            //param = request_base;\n            return request_base;\n        }\n        if (!dagopt) {\n            return param;\n        }\n        if (\"string\" === typeof gdropt && gdropt.slice(0, 12) === \"primary-name\" && namenum > 0) {\n            return param;\n        }\n        //\n        // the last composite condition is for backward compatibility\n        //\n        if (!gdropt || gdropt === \"all-names\" || gdropt === \"primary-name\") {\n            if (this.namereg[pkey].count > 1) {\n                param = 1;\n            }\n            if ((this.namereg[pkey].ikey \n                 && this.namereg[pkey].ikey[ikey].count > 1)\n                || (this.namereg[pkey].count > 1 \n                    && \"string\" !== typeof initials)) {\n\n                param = 2;\n            }\n        } else if (gdropt === \"all-names-with-initials\" || gdropt === \"primary-name-with-initials\") {\n            if (this.namereg[pkey].count > 1) {\n                param = 1;\n            } else {\n                param = 0;\n            }\n        }\n        if (!state.registry.registry[item_id]) {\n            if (form == \"short\") {\n                return 0;\n            } else if (\"string\" == typeof initials) {\n                return 1;\n            }\n        } else {\n            return param;\n        }\n    };\n\n    //\n    // The operation of this function does not show up in the\n    // standard test suite, but it has been hand-tested with\n    // a print trace, and seems to work okay.\n    //\n    delitems = function (ids) {\n        var pos, len, posB, id, fullkey;\n        if (\"string\" === typeof ids || \"number\" === typeof ids) {\n            ids = [\"\" + ids];\n        }\n        // ret carries the IDs of other items using this name.\n        var ret = {};\n        len = ids.length;\n        for (pos = 0; pos < len; pos += 1) {\n            id = \"\" + ids[pos];\n            if (!this.nameind[id]) {\n                continue;\n            }\n            for (fullkey in this.nameind[id]) {\n                if (this.nameind[id].hasOwnProperty(fullkey)) {\n                    var key = fullkey.split(\"::\");\n                    pkey = key[0];\n                    ikey = key[1];\n                    skey = key[2];\n                    // Skip names that have been deleted already.\n                    // Needed to clear integration DisambiguateAddGivenname1.txt\n                    // and integration DisambiguateAddGivenname2.txt\n                    if (\"undefined\" === typeof this.namereg[pkey]) {\n                        continue;\n                    }\n\n                    // ????\n                    //posA = this.namereg[pkey].items.indexOf(posA);\n\n                    items = this.namereg[pkey].items;\n                    // This was really, really unperceptive. They key elements\n                    // have absolutely nothing to do with whether there was ever\n                    // a registration at each key level.\n                    if (skey && this.namereg[pkey].ikey[ikey] && this.namereg[pkey].ikey[ikey].skey[skey]) {\n                        myitems = this.namereg[pkey].ikey[ikey].skey[skey].items;\n                        posB = myitems.indexOf(\"\" + id);\n                        if (posB > -1) {\n                            this.namereg[pkey].ikey[ikey].skey[skey].items = myitems.slice(0, posB).concat(myitems.slice([(posB + 1)]));\n                        }\n                        if (this.namereg[pkey].ikey[ikey].skey[skey].items.length === 0) {\n                            delete this.namereg[pkey].ikey[ikey].skey[skey];\n                            this.namereg[pkey].ikey[ikey].count += -1;\n                            if (this.namereg[pkey].ikey[ikey].count < 2) {\n                                for (var i = 0, ilen = this.namereg[pkey].ikey[ikey].items.length; i < ilen; i += 1) {\n                                    state.tmp.taintedItemIDs[this.namereg[pkey].ikey[ikey].items[i]] = true;\n                                }\n                            }\n                        }\n                    }\n                    if (ikey && this.namereg[pkey].ikey[ikey]) {\n                        posB = this.namereg[pkey].ikey[ikey].items.indexOf(\"\" + id);\n                        if (posB > -1) {\n                            items = this.namereg[pkey].ikey[ikey].items.slice();\n                            this.namereg[pkey].ikey[ikey].items = items.slice(0, posB).concat(items.slice([posB + 1]));\n                        }\n                        if (this.namereg[pkey].ikey[ikey].items.length === 0) {\n                            delete this.namereg[pkey].ikey[ikey];\n                            this.namereg[pkey].count += -1;\n                            if (this.namereg[pkey].count < 2) {\n                                for (var i = 0, ilen = this.namereg[pkey].items.length; i < ilen; i += 1) {\n                                    state.tmp.taintedItemIDs[this.namereg[pkey].items[i]] = true;\n                                }\n                            }\n                        }\n                    }\n                    if (pkey) {\n                        posB = this.namereg[pkey].items.indexOf(\"\" + id);\n                        if (posB > -1) {\n                            items = this.namereg[pkey].items.slice();\n                            this.namereg[pkey].items = items.slice(0, posB).concat(items.slice([posB + 1], items.length));\n                        }\n                        if (this.namereg[pkey].items.length < 2) {\n                            delete this.namereg[pkey];\n                        }\n                    }\n                    delete this.nameind[id][fullkey];\n                }\n            }\n            delete this.nameind[id];\n            delete this.nameindpkeys[id];\n        }\n        return ret;\n    };\n    //\n    // Run ALL\n    // renderings with disambiguate-add-givenname set to a value\n    // with the by-cite behaviour, and then set the names-based\n    // expanded form when the final makeCitationCluster rendering\n    // is output.  This could be done with a single var set on\n    // the state object in the execution wrappers that run the\n    // style.\n    //\n    addname = function (item_id, nameobj, pos) {\n        var i, ilen;\n        var res = state.nameOutput.getName(nameobj, \"locale-translit\", true);\n        nameobj = res.name;\n\n        if (state.citation.opt[\"givenname-disambiguation-rule\"]\n            && state.citation.opt[\"givenname-disambiguation-rule\"].slice(0, 8) === \"primary-\"\n            && pos !== 0) {\n                return;\n        }\n\n        // A hack. Safe if the name object is used only here, for disambiguation purposes.\n        /*\n        */\n        \n        //CSL.debug(\"INS\");\n        set_keys(this.state, \"\" + item_id, nameobj);\n        // pkey, ikey and skey should be stored in separate cascading objects.\n        // there should also be a kkey, on each, which holds the item ids using\n        // that form of the name.\n        //\n        // (later note: well, we seem to have slipped a notch here.\n        // Adding lists of IDs all over the place here makes no sense;\n        // the lists need to include _only_ the items currently rendered\n        // at the given level, and the place to do that is in evalname,\n        // and in delnames, not here.)\n        if (pkey) {\n            if (\"undefined\" === typeof this.namereg[pkey]) {\n                this.namereg[pkey] = {};\n                this.namereg[pkey].count = 0;\n                this.namereg[pkey].ikey = {};\n                this.namereg[pkey].items = [item_id];\n            } else if (this.namereg[pkey].items.indexOf(item_id) === -1) {\n                this.namereg[pkey].items.push(item_id);\n            }\n//            if (this.namereg[pkey].items.indexOf(item_id) === -1) {\n//                this.namereg[pkey].items.push(item_id);\n//            }\n        }\n        if (pkey && ikey) {\n            if (\"undefined\" === typeof this.namereg[pkey].ikey[ikey]) {\n                this.namereg[pkey].ikey[ikey] = {};\n                this.namereg[pkey].ikey[ikey].count = 0;\n                this.namereg[pkey].ikey[ikey].skey = {};\n                this.namereg[pkey].ikey[ikey].items = [item_id];\n                this.namereg[pkey].count += 1;\n                if (this.namereg[pkey].count === 2) {\n                    for (var i = 0, ilen = this.namereg[pkey].items.length; i < ilen; i += 1) {\n                        state.tmp.taintedItemIDs[this.namereg[pkey].items[i]] = true;\n                    }\n                }\n            } else if (this.namereg[pkey].ikey[ikey].items.indexOf(item_id) === -1) {\n                this.namereg[pkey].ikey[ikey].items.push(item_id);\n            }\n//            if (this.namereg[pkey].ikey[ikey].items.indexOf(item_id) === -1) {\n//                this.namereg[pkey].ikey[ikey].items.push(item_id);\n//            }\n        }\n        if (pkey && ikey && skey) {\n            if (\"undefined\" === typeof this.namereg[pkey].ikey[ikey].skey[skey]) {\n                this.namereg[pkey].ikey[ikey].skey[skey] = {};\n                this.namereg[pkey].ikey[ikey].skey[skey].items = [item_id];\n                this.namereg[pkey].ikey[ikey].count += 1;\n                if (this.namereg[pkey].ikey[ikey].count === 2) {\n                    for (var i = 0, ilen = this.namereg[pkey].ikey[ikey].items.length; i < ilen; i += 1) {\n                        state.tmp.taintedItemIDs[this.namereg[pkey].ikey[ikey].items[i]] = true;\n                    }\n                }\n            } else if (this.namereg[pkey].ikey[ikey].skey[skey].items.indexOf(item_id) === -1) {\n                this.namereg[pkey].ikey[ikey].skey[skey].items.push(item_id);\n            }\n//            if (this.namereg[pkey].ikey[ikey].skey[skey].items.indexOf(item_id) === -1) {\n//                this.namereg[pkey].ikey[ikey].skey[skey].items.push(item_id);\n//            }\n        }\n        if (\"undefined\" === typeof this.nameind[item_id]) {\n            this.nameind[item_id] = {};\n            this.nameindpkeys[item_id] = {};\n        }\n        //CSL.debug(\"INS-A: [\" + pkey + \"] [\" + ikey + \"] [\" + skey + \"]\");\n        if (pkey) {\n            this.nameind[item_id][pkey + \"::\" + ikey + \"::\" + skey] = true;\n            this.nameindpkeys[item_id][pkey] = this.namereg[pkey];\n        }\n        //CSL.debug(\"INS-B\");\n    };\n    this.addname = addname;\n    this.delitems = delitems;\n    this.evalname = evalname;\n};\n\n/*global CSL: true */\n\nCSL.Registry.CitationReg = function () {\n    this.citationById = {};\n    this.citationByIndex = [];\n};\n\n/*global CSL: true */\n\nCSL.Disambiguation = function (state) {\n    this.state = state;\n    this.sys = this.state.sys;\n    this.registry = state.registry.registry;\n    this.ambigcites = state.registry.ambigcites;\n    this.configModes();\n    this.debug = false;\n};\n\nCSL.Disambiguation.prototype.run = function(akey) {\n    if (!this.modes.length) {\n        return;\n    }\n    //SNIP-START\n    if (this.debug) {\n        this.state.sys.print(\"[A] === RUN ===\");\n    }\n    //SNIP-END\n    this.akey = akey;\n    if (this.initVars(akey)) {\n        this.runDisambig();\n    }\n\n};\n\nCSL.Disambiguation.prototype.runDisambig = function () {\n    var ismax;\n    //SNIP-START\n    if (this.debug) {\n        this.state.sys.print(\"[C] === runDisambig() ===\");\n    }\n    //SNIP-END\n    this.initGivens = true;\n    //\n    // Length of list may change during processing\n    while (this.lists.length) {\n        this.gnameset = 0;\n        this.gname = 0;\n        this.clashes = [1, 0];\n        // each list is scanned repeatedly until all\n        // items either succeed or ultimately fail.\n        while(this.lists[0][1].length) {\n            this.listpos = 0;\n            if (!this.base) {\n                this.base = this.lists[0][0];\n            }\n            ismax = this.incrementDisambig();\n            this.scanItems(this.lists[0]);\n            this.evalScan(ismax);\n        }\n        this.lists = this.lists.slice(1);\n    }\n};\n\nCSL.Disambiguation.prototype.scanItems = function (list) {\n    var pos, len, otherItem;\n    //SNIP-START\n    if (this.debug) {\n        this.state.sys.print(\"[2] === scanItems() ===\");\n    }\n    //SNIP-END\n\n    this.Item = list[1][0];\n    this.ItemCite = CSL.getAmbiguousCite.call(this.state, this.Item, this.base, true);\n\n    this.scanlist = list[1];\n    this.partners = [];\n    this.partners.push(this.Item);\n    this.nonpartners = [];\n    var clashes = 0;\n\n    for (var pos = 1, len = list[1].length; pos < len; pos += 1) {\n        otherItem = list[1][pos];\n        var otherItemCite = CSL.getAmbiguousCite.call(this.state, otherItem, this.base, true);\n        //SNIP-START\n        if (this.debug) {\n            if (pos > 1) {\n                this.state.sys.print(\"  -----------\");\n            }\n        }\n        //SNIP-END\n        if (this.ItemCite === otherItemCite) {\n            //SNIP-START\n            if (this.debug) {\n                this.state.sys.print(\"  [CLASH]--> \"+this.Item.id+\": \"+this.ItemCite);\n                this.state.sys.print(\"             \"+otherItem.id+\": \"+otherItemCite);\n            }\n            //SNIP-END\n            clashes += 1;\n            this.partners.push(otherItem);\n        } else {\n            //SNIP-START\n            if (this.debug) {\n                this.state.sys.print(\"  [clear]--> \"+this.Item.id+\": \"+this.ItemCite);\n                this.state.sys.print(\"             \"+otherItem.id+\": \"+otherItemCite);\n            }\n            //SNIP-END\n            this.nonpartners.push(otherItem);\n        }\n    }\n    this.clashes[0] = this.clashes[1];\n    this.clashes[1] = clashes;\n};\n\nCSL.Disambiguation.prototype.evalScan = function (maxed) {\n    this[this.modes[this.modeindex]](maxed);\n    if (maxed) {\n        if (this.modeindex < this.modes.length - 1) {\n            this.modeindex += 1;\n        } else {\n            this.lists[this.listpos + 1] = [this.base, []];\n        }\n    }\n};\n\nCSL.Disambiguation.prototype.disNames = function (ismax) {\n    var i, ilen;\n    \n    //SNIP-START\n    if (this.debug) {\n        this.state.sys.print(\"[3] == disNames() ==\");\n        //this.state.sys.print(\"       partners: \"+[this.partners[i].id for (i in this.partners)].join(\", \"));\n        //this.state.sys.print(\"    nonpartners: \"+[this.nonpartners[i].id for (i in this.nonpartners)].join(\", \"));\n    }\n    //SNIP-END\n\n    // New design\n    // this.base is a forward-only counter. Values are never\n    // reduced, and the counter object is never overwritten.\n    // It is methodically pushed forward in single-unit increments\n    // in incrementDisambig() until disNames() wipes out the list.\n\n    // this.betterbase is cloned from this.base exactly once,\n    // at the start of a disambiguation run. Whenever an operation\n    // results in improvement, the just-incremented elements\n    // identified as this.base.names[this.gnameset] (number of\n    // names)and as this.base.givens[this.gnameset][this.gname]\n    // (level of given name) are copied from this.base.\n\n    // The this.base object is used to control disambiguation\n    // renderings. These will be more fully expanded than the final\n    // text, but the flip side of the fact that the extra data does\n    // not contribute anything to disambiguation is that leaving\n    // it in does no harm -- think of it as the Cold Dark Matter of\n    // disambiguation.\n\n    if (this.clashes[1] === 0 && this.nonpartners.length === 1) {\n        this.captureStepToBase();\n        //SNIP-START\n        if (this.debug) {\n            this.state.sys.print(\"  ** RESOLUTION [a]: lone partner, one nonpartner\");\n            this.state.sys.print(\"  registering \"+this.partners[0].id+\" and \"+this.nonpartners[0].id);\n        }\n        //SNIP-END\n        this.state.registry.registerAmbigToken(this.akey, \"\" + this.nonpartners[0].id, this.betterbase);\n        this.state.registry.registerAmbigToken(this.akey, \"\" + this.partners[0].id, this.betterbase);\n        this.lists[this.listpos] = [this.betterbase, []];\n    } else if (this.clashes[1] === 0) {\n        this.captureStepToBase();\n        //SNIP-START\n        if (this.debug) {\n            this.state.sys.print(\"  ** RESOLUTION [b]: lone partner, unknown number of remaining nonpartners\");\n            this.state.sys.print(\"  registering \"+this.partners[0].id);\n        }\n        //SNIP-END\n        this.state.registry.registerAmbigToken(this.akey, \"\" + this.partners[0].id, this.betterbase);\n        this.lists[this.listpos] = [this.betterbase, this.nonpartners];\n        if (this.nonpartners.length) {\n            this.initGivens = true;\n        }\n    } else if (this.nonpartners.length === 1) {\n        this.captureStepToBase();\n        //SNIP-START\n        if (this.debug) {\n            this.state.sys.print(\"  ** RESOLUTION [c]: lone nonpartner, unknown number of partners remaining\");\n            this.state.sys.print(\"  registering \"+this.nonpartners[0].id);\n        }\n        //SNIP-END\n        this.state.registry.registerAmbigToken(this.akey, \"\" + this.nonpartners[0].id, this.betterbase);\n        //this.lists[this.listpos] = [this.betterbase, this.partners];\n        this.lists[this.listpos] = [this.betterbase, this.partners];\n    } else if (this.clashes[1] < this.clashes[0]) {\n        this.captureStepToBase();\n        //SNIP-START\n        if (this.debug) {\n            this.state.sys.print(\"  ** RESOLUTION [d]: better result, but no entries safe to register\");\n        }\n        //SNIP-END\n        this.lists[this.listpos] = [this.betterbase, this.partners];\n        this.lists.push([this.betterbase, this.nonpartners]);\n    } else {\n        //SNIP-START\n        if (this.debug) {\n            this.state.sys.print(\"  ** RESOLUTION [e]: no improvement, and clashes remain\");\n        }\n        //SNIP-END\n        if (ismax) {\n            this.lists[this.listpos] = [this.betterbase, this.nonpartners];\n            this.lists.push([this.betterbase, this.partners]);\n            if (this.modeindex === this.modes.length - 1) {\n                //SNIP-START\n                if (this.debug) {\n                    this.state.sys.print(\"     (registering clashing entries because we've run out of options)\");\n                }\n                //SNIP-END\n                for (var i = 0, ilen = this.partners.length; i < ilen; i += 1) {\n                    this.state.registry.registerAmbigToken(this.akey, \"\" + this.partners[i].id, this.betterbase);\n                }\n                this.lists[this.listpos] = [this.betterbase, []];\n            }\n        }\n    }\n};\n\nCSL.Disambiguation.prototype.disExtraText = function () {\n    //SNIP-START\n    if (this.debug) {\n        this.state.sys.print(\"[3] === disExtraText ==\");\n    }\n    //SNIP-END\n    \n    var done = false;\n\n    if (this.clashes[1] === 0 && this.nonpartners.length < 2) {\n        done = true;\n    }\n\n    // If first encounter in this cycle and multiple modes are\n    // available, decrement mode and reset base\n    if (!done && (!this.base.disambiguate || this.state.tmp.disambiguate_count !== this.state.tmp.disambiguate_maxMax)) {\n        // Rerun everything on each subcycle? This doesn't work currently.\n        //this.initVars(this.akey)\n        this.modeindex = 0;\n        this.base.disambiguate = this.state.tmp.disambiguate_count;\n        this.betterbase.disambiguate = this.state.tmp.disambiguate_count;\n        if (!this.base.disambiguate) {\n            // Evaluate here?\n            this.initGivens = true;\n            // If disambiguate is false set to true\n            this.base.disambiguate = 1;\n            // There may be changes\n            for (var i = 0, ilen = this.lists[this.listpos][1].length; i < ilen; i += 1) {\n                this.state.tmp.taintedItemIDs[this.lists[this.listpos][1][i].id] = true;\n            }\n        } else {\n            this.disNames();\n        }\n    } else if (done || this.state.tmp.disambiguate_count === this.state.tmp.disambiguate_maxMax) {\n        if (done || this.modeindex === this.modes.length - 1) {\n            // If this is the end, disambiguation failed.\n            // Discard disambiguate=true (?) and set parameters\n            var base = this.lists[this.listpos][0];\n            for (var i = 0, ilen = this.lists[this.listpos][1].length; i < ilen; i += 1) {\n                this.state.tmp.taintedItemIDs[this.lists[this.listpos][1][i].id] = true;\n                this.state.registry.registerAmbigToken(this.akey, \"\" + this.lists[this.listpos][1][i].id, base);\n            }\n            this.lists[this.listpos] = [this.betterbase, []];\n        } else {\n            // If this is followed by year-suffix, keep\n            // parameters and set disambiguate=true since it MIGHT\n            // include the date, needed for year-suffix.\n            // This may be a bit over-aggressive for cases in which the\n            // disambiguate condition does not add the date\n            this.modeindex = this.modes.length - 1;\n            var base = this.lists[this.listpos][0];\n            base.disambiguate = true;\n            for (var i = 0, ilen = this.lists[this.listpos][1].length; i < ilen; i += 1) {\n                // Always tainting here might be a little over-aggressive, but a taint may be required.\n                this.state.tmp.taintedItemIDs[this.lists[this.listpos][1][i].id] = true;\n                this.state.registry.registerAmbigToken(this.akey, \"\" + this.lists[this.listpos][1][i].id, base);\n            }\n        }\n    }\n};\n\nCSL.Disambiguation.prototype.disYears = function () {\n    var pos, len, tokens, token;\n    //SNIP-START\n    if (this.debug) {\n        this.state.sys.print(\"[3] === disYears ==\");\n    }\n    //SNIP-END\n    tokens = [];\n    var base = this.lists[this.listpos][0];\n    if (this.clashes[1]) {\n        // That is, if the initial increment on the ambigs group returns no\n        // clashes, don't apply suffix. The condition is a necessary failsafe.\n\t\t// In original submission order\n\t\tfor (var i = 0, ilen = this.state.registry.mylist.length; i < ilen; i += 1) {\n\t\t\tvar origid = this.state.registry.mylist[i];\n\t\t\tfor (var j = 0, jlen = this.lists[this.listpos][1].length; j < jlen; j += 1) {\n\t\t\t\tvar token = this.lists[this.listpos][1][j];\n\t\t\t\t// Warning: token.id can be number. This should be fixed at a higher level in citeproc-js if poss.\n\t\t\t\tif (token.id == origid) {\n\t\t\t\t\ttokens.push(this.registry[token.id]);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n    }\n    tokens.sort(this.state.registry.sorter.compareKeys);\n    for (var pos = 0, len = tokens.length; pos < len; pos += 1) {\n        base.year_suffix = \"\"+pos;\n        var oldBase = this.state.registry.registry[tokens[pos].id].disambig;\n        this.state.registry.registerAmbigToken(this.akey, \"\" + tokens[pos].id, base);\n        if (CSL.ambigConfigDiff(oldBase,base)) {\n            this.state.tmp.taintedItemIDs[tokens[pos].id] = true;\n        }\n    }\n    this.lists[this.listpos] = [this.betterbase, []];\n};\n\nCSL.Disambiguation.prototype.incrementDisambig = function () {\n    //SNIP-START\n    if (this.debug) {\n        this.state.sys.print(\"\\n[1] === incrementDisambig() ===\");\n    }\n    //SNIP-END\n    if (this.initGivens) {\n        this.initGivens = false;\n        return false;\n    }\n    var maxed = false;\n    var increment_names = true;\n    if (\"disNames\" === this.modes[this.modeindex]) {\n        // this.gnameset: the index pos of the current nameset\n        // this.gname: the index pos of the current name w/in the current nameset\n        \n        // Stages:\n        // - Increment givenname (optional)\n        // - Add a name (optional)\n        // - Move to next nameset\n\n        // Incrementing is done forward-only on this.base. Values\n        // that improve disambiguation results are copied to\n        // this.betterbase, which is used to set the disambig parameters\n        // in the processor registry.\n        \n\n        // Increment\n        // Max val is always true if a level is inactive.\n        increment_names = false;\n        if (\"number\" !== typeof this.givensMax) {\n            increment_names = true;\n        }\n        var increment_namesets = false;\n        if (\"number\" !== typeof this.namesMax) {\n            increment_namesets = true;\n        }\n        if (\"number\" === typeof this.givensMax) {\n            if (this.base.givens.length && this.base.givens[this.gnameset][this.gname] < this.givensMax) {\n                this.base.givens[this.gnameset][this.gname] += 1;\n            } else {\n                increment_names = true;\n            }\n        }\n        if (\"number\" === typeof this.namesMax \n            && increment_names) {\n            if (this.state.opt[\"disambiguate-add-names\"]) {\n                increment_namesets = false;\n                if (this.gname < this.namesMax) {\n                    this.base.names[this.gnameset] += 1;\n                    this.gname += 1;\n                } else {\n                    increment_namesets = true;\n                }\n            } else {\n                increment_namesets = true;\n            }\n        }\n        if (\"number\" === typeof this.namesetsMax && increment_namesets) {\n            if (this.gnameset < this.namesetsMax) {\n                this.gnameset += 1;\n                this.base.names[this.gnameset] = 1;\n                this.gname = 0;\n            }\n        }\n        //SNIP-START\n        if (this.debug) {\n            this.state.sys.print(\"    ------------------\");\n            this.state.sys.print(\"    incremented values\");\n            this.state.sys.print(\"    ------------------\");\n            this.state.sys.print(\"    | gnameset: \"+this.gnameset);\n            this.state.sys.print(\"    | gname: \"+this.gname);\n            this.state.sys.print(\"    | names value: \"+this.base.names[this.gnameset]);\n            if (this.base.givens.length) {\n                this.state.sys.print(\"    | givens value: \"+this.base.givens[this.gnameset][this.gname]);\n            } else {\n                this.state.sys.print(\"    | givens value: nil\");\n            }\n            this.state.sys.print(\"    | namesetsMax: \"+this.namesetsMax);\n            this.state.sys.print(\"    | namesMax: \"+this.namesMax);\n            this.state.sys.print(\"    | givensMax: \"+this.givensMax);\n        }\n        //SNIP-END\n        if ((\"number\" !== typeof this.namesetsMax || this.namesetsMax === -1 || this.gnameset === this.namesetsMax)\n            && (!this.state.opt[\"disambiguate-add-names\"] || \"number\" !== typeof this.namesMax || this.gname === this.namesMax)\n            && (\"number\" != typeof this.givensMax || \"undefined\" === typeof this.base.givens[this.gnameset] || \"undefined\" === typeof this.base.givens[this.gnameset][this.gname] || this.base.givens[this.gnameset][this.gname] === this.givensMax)) {\n  \n\n            maxed = true;\n            //SNIP-START\n            if (this.debug) {\n                this.state.sys.print(\"    MAXED\");\n            }\n            //SNIP-END\n        }\n    } else if (\"disExtraText\" === this.modes[this.modeindex]) {\n        this.base.disambiguate += 1;\n        this.betterbase.disambiguate += 1;\n    }\n    return maxed;\n};\n\nCSL.Disambiguation.prototype.initVars = function (akey) {\n    var i, ilen, myIds, myItemBundles, myItems;\n    //SNIP-START\n    if (this.debug) {\n        this.state.sys.print(\"[B] === initVars() ===\");\n    }\n    //SNIP-END\n    this.lists = [];\n    this.base = false;\n    this.betterbase = false;\n    this.akey = akey;\n\n    this.maxNamesByItemId = {};\n\n\n    myItemBundles = [];\n    myIds = this.ambigcites[akey];\n    if (!myIds || !myIds.length) {\n        return false;\n    }\n    var myItem = this.state.refetchItem(\"\" + myIds[0]);\n    this.getCiteData(myItem);\n    this.base = CSL.getAmbigConfig.call(this.state);\n    if (myIds && myIds.length > 1) {\n        myItemBundles.push([this.maxNamesByItemId[myItem.id], myItem]);\n        // Build a composite list of Items and associated\n        // max names. This is messy, but it's the only\n        // way to get the items sorted by the number of names\n        // to be disambiguated. If they are in descending order\n        // with name expansions, the processor will hang.\n        for (var i = 1, ilen = myIds.length; i < ilen; i += 1) {\n            myItem = this.state.refetchItem(\"\" + myIds[i]);\n            this.getCiteData(myItem, this.base);\n            myItemBundles.push([this.maxNamesByItemId[myItem.id], myItem]);\n        }\n        myItemBundles.sort(\n            function (a, b) {\n                if (a[0] > b[0]) {\n                    return 1;\n                } else if (a[0] < b[0]) {\n                    return -1;\n                } else {\n                    if (a[1].id > b[1].id) {\n                        return 1;\n                    } else if (a[1].id < b[1].id) {\n                        return -1;\n                    } else {\n                        return 0;\n                    }\n                }\n            }\n        );\n        myItems = [];\n        for (var i = 0, ilen = myItemBundles.length; i < ilen; i += 1) {\n            myItems.push(myItemBundles[i][1]);\n        }\n        this.lists.push([this.base, myItems]);\n        this.Item = this.lists[0][1][0];\n    } else {\n        this.Item = this.state.refetchItem(\"\" + myIds[0]);\n    }\n\n    this.modeindex = 0;\n    if (this.state.citation.opt[\"disambiguate-add-names\"] || true) {\n        this.namesMax = this.maxNamesByItemId[this.Item.id][0];\n    } else {\n        var namesMax = this.base.names[0];\n        for (var i=1,ilen=this.base.names.length;i<ilen;i+=1){\n            namesMax = Math.max(namesMax,this.base.names.names[i]);\n        }\n    }\n\n\n    this.padBase(this.base);\n    this.padBase(this.betterbase);\n    this.base.year_suffix = false;\n    this.base.disambiguate = false;\n    this.betterbase.year_suffix = false;\n    this.betterbase.disambiguate = false;\n    if (this.state.citation.opt[\"givenname-disambiguation-rule\"] === \"by-cite\"\n       && this.state.opt[\"disambiguate-add-givenname\"]) {\n        this.givensMax = 2;\n    }\n    return true;\n};\n\n\nCSL.Disambiguation.prototype.padBase = function (base) {\n    for (var i = 0, ilen = base.names.length; i < ilen; i += 1) {\n        if (!base.givens[i]) {\n            base.givens[i] = [];\n        }\n        for (var j=0,jlen=base.names[i];j<jlen;j+=1) {\n            if (!base.givens[i][j]) {\n                base.givens[i][j] = 0;\n            }\n        }\n    }\n};\n\n/**\n * Set available modes for disambiguation\n */\nCSL.Disambiguation.prototype.configModes = function () {\n    var dagopt, gdropt;\n    // Modes are function names prototyped to this instance.\n    this.modes = [];\n    dagopt = this.state.opt[\"disambiguate-add-givenname\"];\n    gdropt = this.state.citation.opt[\"givenname-disambiguation-rule\"];\n    if (this.state.opt['disambiguate-add-names'] || (dagopt && gdropt === \"by-cite\")) {\n        this.modes.push(\"disNames\");\n    }\n\n    if (this.state.opt.development_extensions.prioritize_disambiguate_condition) {\n        if (this.state.opt.has_disambiguate) {\n            this.modes.push(\"disExtraText\");\n        }\n        if (this.state.opt[\"disambiguate-add-year-suffix\"]) {\n            this.modes.push(\"disYears\");\n        }\n    } else {\n        if (this.state.opt[\"disambiguate-add-year-suffix\"]) {\n            this.modes.push(\"disYears\");\n        }\n        if (this.state.opt.has_disambiguate) {\n            this.modes.push(\"disExtraText\");\n        }\n    }\n};\n\nCSL.Disambiguation.prototype.getCiteData = function(Item, base) {\n    // Initialize base if first set item seen\n    if (!this.maxNamesByItemId[Item.id]) {\n        CSL.getAmbiguousCite.call(this.state, Item, base);\n        base = CSL.getAmbigConfig.call(this.state);\n        this.maxNamesByItemId[Item.id] = CSL.getMaxVals.call(this.state);\n        this.state.registry.registry[Item.id].disambig.givens = this.state.tmp.disambig_settings.givens.slice();\n        // Slice the nested lists as well. Without this, disambiguate_YearSuffixFiftyTwoEntriesByCite fails.\n        for (var i=0,ilen=this.state.registry.registry[Item.id].disambig.givens.length;i<ilen;i+=1) {\n            this.state.registry.registry[Item.id].disambig.givens[i] = this.state.tmp.disambig_settings.givens[i].slice();\n        }\n        this.namesetsMax = this.state.registry.registry[Item.id].disambig.names.length - 1;\n        if (!this.base) {\n            this.base = base;\n            this.betterbase = CSL.cloneAmbigConfig(base);\n        }\n        if (base.names.length < this.base.names.length) {\n            // I don't know what would happen with discrepancies in the number\n            // of namesets rendered on items, so we use the fewer of the two\n            // and limit the other to that size.\n            this.base = base;\n        }\n        // Padding. Within namesets, we use the longer of the two throughout.\n        for (var i = 0, ilen = base.names.length; i < ilen; i += 1) {\n            if (base.names[i] > this.base.names[i]) {\n                // XXX The old must have been wrong surely. The new, I'm not sure.\n                //this.base.givens[i] = this.base.givens[i].concat(this.base.givens[i].slice(this.base.names[i]));\n                this.base.givens[i] = base.givens[i].slice();\n                this.base.names[i] = base.names[i];\n                this.betterbase.names = this.base.names.slice();\n                this.betterbase.givens = this.base.givens.slice();\n                this.padBase(this.base);\n                this.padBase(this.betterbase);\n            }\n        }\n        // This shouldn't be necessary\n        // getAmbiguousCite() should return a valid and complete\n        // givens segment under all conditions, but it does not\n        // do so for institution authors, so we clean up after it\n        // here.\n        // Relevant test: sort_ChicagoYearSuffix2\n        this.betterbase.givens = this.base.givens.slice();\n        for (var j = 0, jlen = this.base.givens.length; j < jlen; j += 1) {\n            this.betterbase.givens[j] = this.base.givens[j].slice();\n        }\n    }\n};\n\nCSL.Disambiguation.prototype.captureStepToBase = function() {\n    // Be paranoid about the presence of givens\n    if (this.state.citation.opt[\"givenname-disambiguation-rule\"] === \"by-cite\"\n        && this.base.givens && this.base.givens.length) {\n        if (\"undefined\" !== typeof this.base.givens[this.gnameset][this.gname]) {\n            if (this.betterbase.givens.length < this.base.givens.length) {\n                this.betterbase.givens = JSON.parse(JSON.stringify(this.base.givens));\n            }\n            this.betterbase.givens[this.gnameset][this.gname] = this.base.givens[this.gnameset][this.gname];\n        }\n    }\n    this.betterbase.names[this.gnameset] = this.base.names[this.gnameset];\n};\n\nCSL.Engine.prototype.getJurisdictionList = function (jurisdiction) {\n    var jurisdictionList = [];\n    var jurisdictionElems = jurisdiction.split(\":\");\n    for (var j=jurisdictionElems.length;j>0;j--) {\n        var composedID = jurisdictionElems.slice(0,j).join(\":\");\n        jurisdictionList.push(composedID);\n        if (this.opt.jurisdiction_fallbacks[composedID]) {\n            var fallback = this.opt.jurisdiction_fallbacks[composedID];\n            jurisdictionList.push(fallback);\n        }\n    }\n    if (jurisdictionList.indexOf(\"us\") === -1) {\n        jurisdictionList.push(\"us\");\n    }\n    return jurisdictionList;\n};\n\nCSL.Engine.prototype.loadStyleModule = function (jurisdiction, xmlSource, skipFallback) {\n    var myFallback = null;\n    var macroCount = 0;\n    this.juris[jurisdiction] = {};\n    var myXml = CSL.setupXml(xmlSource);\n    myXml.addMissingNameNodes(myXml.dataObj);\n    myXml.addInstitutionNodes(myXml.dataObj);\n    myXml.insertPublisherAndPlace(myXml.dataObj);\n    myXml.flagDateMacros(myXml.dataObj);\n    var myNodes = myXml.getNodesByName(myXml.dataObj, \"law-module\");\n    for (var i=0,ilen=myNodes.length;i<ilen;i++) {\n        var myTypes = myXml.getAttributeValue(myNodes[i],\"types\");\n        if (myTypes) {\n            this.juris[jurisdiction].types = {};\n            myTypes =  myTypes.split(/\\s+/);\n            for (var j=0,jlen=myTypes.length;j<jlen;j++) {\n                this.juris[jurisdiction].types[myTypes[j]] = true;\n            }\n        }\n        if (!skipFallback) {\n            myFallback = myXml.getAttributeValue(myNodes[i],\"fallback\");\n            if (myFallback) {\n                if (jurisdiction !== \"us\") {\n                    this.opt.jurisdiction_fallbacks[jurisdiction] = myFallback;\n                }\n            }\n        }\n    }\n    var lang = this.opt.lang ? this.opt.lang : this.opt[\"default-locale\"][0];\n    CSL.SET_COURT_CLASSES(this, lang, myXml, myXml.dataObj);\n    \n    if (!this.juris[jurisdiction].types) {\n        this.juris[jurisdiction].types = CSL.MODULE_TYPES;\n    }\n    var myNodes = myXml.getNodesByName(myXml.dataObj, \"macro\");\n    for (var i=0,ilen=myNodes.length;i<ilen;i++) {\n        var myName = myXml.getAttributeValue(myNodes[i], \"name\");\n        if (!CSL.MODULE_MACROS[myName]) {\n            CSL.debug(\"CSL: skipping non-modular macro name \\\"\" + myName + \"\\\" in module context\");\n            continue;\n        }\n        macroCount++;\n        this.juris[jurisdiction][myName] = [];\n        // Must use the same XML parser for style and modules.\n        this.buildTokenLists(myNodes[i], this.juris[jurisdiction][myName]);\n        this.configureTokenList(this.juris[jurisdiction][myName]);\n    }\n    //if (macroCount < Object.keys(CSL.MODULE_MACROS).length) {\n    //    var missing = [];\n    //    throw \"CSL ERROR: Incomplete jurisdiction style module for: \" + jurisdiction;\n    //}\n    return myFallback;\n};\n\nCSL.Engine.prototype.retrieveAllStyleModules = function (jurisdictionList) {\n    var ret = {};\n    var preferences = this.locale[this.opt.lang].opts[\"jurisdiction-preference\"];\n    preferences = preferences ? preferences : [];\n    preferences = [\"\"].concat(preferences);\n    for (var i=preferences.length-1;i>-1;i--) {\n        var preference = preferences[i];\n        for (var j=0,jlen=jurisdictionList.length;j<jlen;j++) {\n            var jurisdiction = jurisdictionList[j];\n            // If we've \"seen\" it, we have it already, or we're not going to get it.\n            if (this.opt.jurisdictions_seen[jurisdiction]) {\n                continue;\n            }\n            // Try to get the module\n            var res = this.sys.retrieveStyleModule(jurisdiction, preference);\n            // If we fail and we've run out of preferences, mark as \"seen\"\n            // Otherwise mark as \"seen\" if we get something.\n            if ((!res && !preference) || res) {\n                this.opt.jurisdictions_seen[jurisdiction] = true;\n            }\n            // Don't memo unless get got style code.\n            if (!res) {\n                continue;\n            }\n            ret[jurisdiction] = res;\n        }\n    }\n    // Give 'em what we got.\n    return ret;\n};\n\nCSL.ParticleList = (function() {\n\tvar always_dropping_1 = [[[0,1], null]];\n\tvar always_dropping_3 = [[[0,3], null]];\n\tvar always_non_dropping_1 = [[null, [0,1]]];\n\tvar always_non_dropping_2 = [[null, [0,2]]];\n\tvar always_non_dropping_3 = [[null, [0,3]]];\n\tvar either_1 = [[null, [0,1]],[[0,1],null]];\n\tvar either_2 = [[null, [0,2]],[[0,2],null]];\n\tvar either_1_dropping_best = [[[0,1],null],[null, [0,1]]];\n\tvar either_2_dropping_best = [[[0,2],null],[null, [0,2]]];\n\tvar either_3_dropping_best = [[[0,3],null],[null, [0,3]]];\n\tvar non_dropping_2_alt_dropping_1_non_dropping_1 = [[null, [0,2]], [[0,1], [1,2]]];\n\tvar PARTICLES = [\n\t\t[\"'s\", always_non_dropping_1],\n\t\t[\"'s-\", always_non_dropping_1],\n\t\t[\"'t\", always_non_dropping_1],\n\t\t[\"a\", \talways_non_dropping_1],\n\t\t[\"aan 't\", always_non_dropping_2],\n\t\t[\"aan de\", always_non_dropping_2],\n\t\t[\"aan den\", always_non_dropping_2],\n\t\t[\"aan der\", always_non_dropping_2],\n\t\t[\"aan het\", always_non_dropping_2],\n\t\t[\"aan t\", always_non_dropping_2],\n\t\t[\"aan\", always_non_dropping_1],\n\t\t[\"ad-\", either_1],\n\t\t[\"adh-\", either_1],\n\t\t[\"af\", either_1],\n\t\t[\"al\", either_1],\n\t\t[\"al-\", either_1],\n\t\t[\"am de\", always_non_dropping_2],\n\t\t[\"am\", always_non_dropping_1],\n\t\t[\"an-\", either_1],\n\t\t[\"ar-\", either_1],\n\t\t[\"as-\", either_1],\n\t\t[\"ash-\", either_1],\n\t\t[\"at-\", either_1],\n\t\t[\"ath-\", either_1],\n\t\t[\"auf dem\", either_2_dropping_best],\n\t\t[\"auf den\", either_2_dropping_best],\n\t\t[\"auf der\", either_2_dropping_best],\n\t\t[\"auf ter\", always_non_dropping_2],\n\t\t[\"auf\", either_1_dropping_best],\n\t\t[\"aus 'm\", either_2_dropping_best],\n\t\t[\"aus dem\", either_2_dropping_best],\n\t\t[\"aus den\", either_2_dropping_best],\n\t\t[\"aus der\", either_2_dropping_best],\n\t\t[\"aus m\", either_2_dropping_best],\n\t\t[\"aus\", either_1_dropping_best],\n\t\t[\"aus'm\", either_2_dropping_best],\n\t\t[\"az-\", either_1],\n\t\t[\"aš-\", either_1],\n\t\t[\"aḍ-\", either_1],\n\t\t[\"aḏ-\", either_1],\n\t\t[\"aṣ-\", either_1],\n\t\t[\"aṭ-\", either_1],\n\t\t[\"aṯ-\", either_1],\n\t\t[\"aẓ-\", either_1],\n\t\t[\"ben\", always_non_dropping_1],\n\t\t[\"bij 't\", always_non_dropping_2],\n\t\t[\"bij de\", always_non_dropping_2],\n\t\t[\"bij den\", always_non_dropping_2],\n\t\t[\"bij het\", always_non_dropping_2],\n\t\t[\"bij t\", always_non_dropping_2],\n\t\t[\"bij\", always_non_dropping_1],\n\t\t[\"bin\", always_non_dropping_1],\n\t\t[\"boven d\", always_non_dropping_2],\n\t\t[\"boven d'\", always_non_dropping_2],\n\t\t[\"d\", always_non_dropping_1],\n\t\t[\"d'\", either_1],\n\t\t[\"da\", either_1],\n\t\t[\"dal\", always_non_dropping_1],\n\t\t[\"dal'\", always_non_dropping_1],\n\t\t[\"dall'\", always_non_dropping_1],\n\t\t[\"dalla\", always_non_dropping_1],\n\t\t[\"das\", either_1],\n\t\t[\"de die le\", always_non_dropping_3],\n\t\t[\"de die\", always_non_dropping_2],\n\t\t[\"de l\", always_non_dropping_2],\n\t\t[\"de l'\", always_non_dropping_2],\n\t\t[\"de la\", non_dropping_2_alt_dropping_1_non_dropping_1],\n\t\t[\"de las\", non_dropping_2_alt_dropping_1_non_dropping_1],\n\t\t[\"de le\", always_non_dropping_2],\n\t\t[\"de li\", either_2],\n\t\t[\"de van der\", always_non_dropping_3],\n\t\t[\"de\", either_1],\n\t\t[\"de'\", either_1],\n\t\t[\"deca\", always_non_dropping_1],\n\t\t[\"degli\", either_1],\n\t\t[\"dei\", either_1],\n\t\t[\"del\", either_1],\n\t\t[\"dela\", always_dropping_1],\n\t\t[\"dell'\", either_1],\n\t\t[\"della\", either_1],\n\t\t[\"delle\", either_1],\n\t\t[\"dello\", either_1],\n\t\t[\"den\", either_1],\n\t\t[\"der\", either_1],\n\t\t[\"des\", either_1],\n\t\t[\"di\", either_1],\n\t\t[\"die le\", always_non_dropping_2],\n\t\t[\"do\", always_non_dropping_1],\n\t\t[\"don\", always_non_dropping_1],\n\t\t[\"dos\", either_1],\n\t\t[\"du\", either_1],\n\t\t[\"ed-\", either_1],\n\t\t[\"edh-\", either_1],\n\t\t[\"el\", either_1],\n\t\t[\"el-\", either_1],\n\t\t[\"en-\", either_1],\n\t\t[\"er-\", either_1],\n\t\t[\"es-\", either_1],\n\t\t[\"esh-\", either_1],\n\t\t[\"et-\", either_1],\n\t\t[\"eth-\", either_1],\n\t\t[\"ez-\", either_1],\n\t\t[\"eš-\", either_1],\n\t\t[\"eḍ-\", either_1],\n\t\t[\"eḏ-\", either_1],\n\t\t[\"eṣ-\", either_1],\n\t\t[\"eṭ-\", either_1],\n\t\t[\"eṯ-\", either_1],\n\t\t[\"eẓ-\", either_1],\n\t\t[\"het\", always_non_dropping_1],\n\t\t[\"i\", always_non_dropping_1],\n\t\t[\"il\", always_dropping_1],\n\t\t[\"im\", always_non_dropping_1],\n\t\t[\"in 't\", always_non_dropping_2],\n\t\t[\"in de\", always_non_dropping_2],\n\t\t[\"in den\", always_non_dropping_2],\n\t\t[\"in der\", either_2],\n\t\t[\"in het\", always_non_dropping_2],\n\t\t[\"in t\", always_non_dropping_2],\n\t\t[\"in\", always_non_dropping_1],\n\t\t[\"l\", always_non_dropping_1],\n\t\t[\"l'\", always_non_dropping_1],\n\t\t[\"la\", always_non_dropping_1],\n\t\t[\"las\", always_non_dropping_1],\n\t\t[\"le\", always_non_dropping_1],\n\t\t[\"les\", either_1],\n\t\t[\"lo\", either_1],\n\t\t[\"los\", always_non_dropping_1],\n\t\t[\"lou\", always_non_dropping_1],\n\t\t[\"of\", always_non_dropping_1],\n\t\t[\"onder 't\", always_non_dropping_2],\n\t\t[\"onder de\", always_non_dropping_2],\n\t\t[\"onder den\", always_non_dropping_2],\n\t\t[\"onder het\", always_non_dropping_2],\n\t\t[\"onder t\", always_non_dropping_2],\n\t\t[\"onder\", always_non_dropping_1],\n\t\t[\"op 't\", always_non_dropping_2],\n\t\t[\"op de\", either_2],\n\t\t[\"op den\", always_non_dropping_2],\n\t\t[\"op der\", always_non_dropping_2],\n\t\t[\"op gen\", always_non_dropping_2],\n\t\t[\"op het\", always_non_dropping_2],\n\t\t[\"op t\", always_non_dropping_2],\n\t\t[\"op ten\", always_non_dropping_2],\n\t\t[\"op\", always_non_dropping_1],\n\t\t[\"over 't\", always_non_dropping_2],\n\t\t[\"over de\", always_non_dropping_2],\n\t\t[\"over den\", always_non_dropping_2],\n\t\t[\"over het\", always_non_dropping_2],\n\t\t[\"over t\", always_non_dropping_2],\n\t\t[\"over\", always_non_dropping_1],\n\t\t[\"s\", always_non_dropping_1],\n\t\t[\"s'\", always_non_dropping_1],\n\t\t[\"sen\", always_dropping_1],\n\t\t[\"t\", always_non_dropping_1],\n\t\t[\"te\", always_non_dropping_1],\n\t\t[\"ten\", always_non_dropping_1],\n\t\t[\"ter\", always_non_dropping_1],\n\t\t[\"tho\", always_non_dropping_1],\n\t\t[\"thoe\", always_non_dropping_1],\n\t\t[\"thor\", always_non_dropping_1],\n\t\t[\"to\", always_non_dropping_1],\n\t\t[\"toe\", always_non_dropping_1],\n\t\t[\"tot\", always_non_dropping_1],\n\t\t[\"uijt 't\", always_non_dropping_2],\n\t\t[\"uijt de\", always_non_dropping_2],\n\t\t[\"uijt den\", always_non_dropping_2],\n\t\t[\"uijt te de\", always_non_dropping_3],\n\t\t[\"uijt ten\", always_non_dropping_2],\n\t\t[\"uijt\", always_non_dropping_1],\n\t\t[\"uit 't\", always_non_dropping_2],\n\t\t[\"uit de\", always_non_dropping_2],\n\t\t[\"uit den\", always_non_dropping_2],\n\t\t[\"uit het\", always_non_dropping_2],\n\t\t[\"uit t\", always_non_dropping_2],\n\t\t[\"uit te de\", always_non_dropping_3],\n\t\t[\"uit ten\", always_non_dropping_2],\n\t\t[\"uit\", always_non_dropping_1],\n\t\t[\"unter\", always_non_dropping_1],\n\t\t[\"v\", always_non_dropping_1],\n\t\t[\"v.\", always_non_dropping_1],\n\t\t[\"v.d.\", always_non_dropping_1],\n\t\t[\"van 't\", always_non_dropping_2],\n\t\t[\"van de l\", always_non_dropping_3],\n\t\t[\"van de l'\", always_non_dropping_3],\n\t\t[\"van de\", always_non_dropping_2],\n\t\t[\"van de\", always_non_dropping_2],\n\t\t[\"van den\", always_non_dropping_2],\n\t\t[\"van der\", always_non_dropping_2],\n\t\t[\"van gen\", always_non_dropping_2],\n\t\t[\"van het\", always_non_dropping_2],\n\t\t[\"van la\", always_non_dropping_2],\n\t\t[\"van t\", always_non_dropping_2],\n\t\t[\"van ter\", always_non_dropping_2],\n\t\t[\"van van de\", always_non_dropping_3],\n\t\t[\"van\", either_1],\n\t\t[\"vander\", always_non_dropping_1],\n\t\t[\"vd\", always_non_dropping_1],\n\t\t[\"ver\", always_non_dropping_1],\n\t\t[\"vom und zum\", always_dropping_3],\n\t\t[\"vom\", either_1],\n\t\t[\"von 't\", always_non_dropping_2],\n\t\t[\"von dem\", either_2_dropping_best],\n\t\t[\"von den\", either_2_dropping_best],\n\t\t[\"von der\", either_2_dropping_best],\n\t\t[\"von t\", always_non_dropping_2],\n\t\t[\"von und zu\", either_3_dropping_best],\n\t\t[\"von zu\", either_2_dropping_best],\n\t\t[\"von\", either_1_dropping_best],\n\t\t[\"voor 't\", always_non_dropping_2],\n\t\t[\"voor de\", always_non_dropping_2],\n\t\t[\"voor den\", always_non_dropping_2],\n\t\t[\"voor in 't\", always_non_dropping_3],\n\t\t[\"voor in t\", always_non_dropping_3],\n\t\t[\"voor\", always_non_dropping_1],\n\t\t[\"vor der\", either_2_dropping_best],\n\t\t[\"vor\", either_1_dropping_best],\n\t\t[\"z\", always_dropping_1],\n\t\t[\"ze\", always_dropping_1],\n\t\t[\"zu\", either_1_dropping_best],\n\t\t[\"zum\", either_1],\n\t\t[\"zur\", either_1]\n\t];\n    return PARTICLES;\n}());\n\nCSL.parseParticles = (function(){\n    function splitParticles(nameValue, firstNameFlag, caseOverride) {\n\t\t// Parse particles out from name fields.\n\t\t// * nameValue (string) is the field content to be parsed.\n\t\t// * firstNameFlag (boolean) parse trailing particles\n\t\t//\t (default is to parse leading particles)\n\t\t// * caseOverride (boolean) include all but one word in particle set\n\t\t//\t (default is to include only words with lowercase first char)\n        //   [caseOverride is not used in this application]\n\t\t// Returns an array with:\n\t\t// * (boolean) flag indicating whether a particle was found\n\t\t// * (string) the name after removal of particles\n\t\t// * (array) the list of particles found\n\t\tvar origNameValue = nameValue;\n\t\tnameValue = caseOverride ? nameValue.toLowerCase() : nameValue;\n\t\tvar particleList = [];\n\t\tvar rex;\n        var hasParticle;\n\t\tif (firstNameFlag) {\n\t\t\tnameValue = nameValue.split(\"\").reverse().join(\"\");\n\t\t\trex = CSL.PARTICLE_GIVEN_REGEXP;\n\t\t} else {\n\t\t\trex = CSL.PARTICLE_FAMILY_REGEXP;\n\t\t}\n\t\tvar m = nameValue.match(rex);\n\t\twhile (m) {\n\t\t\tvar m1 = firstNameFlag ? m[1].split(\"\").reverse().join(\"\") : m[1];\n\t\t\tvar firstChar = m ? m1 : false;\n\t\t\tvar firstChar = firstChar ? m1.replace(/^[-\\'\\u02bb\\u2019\\s]*(.).*$/, \"$1\") : false;\n\t\t\thasParticle = firstChar ? firstChar.toUpperCase() !== firstChar : false;\n\t\t\tif (!hasParticle) {\n                break;\n            }\n\t\t\tif (firstNameFlag) {\n\t\t\t\tparticleList.push(origNameValue.slice(m1.length * -1));\n\t\t\t\torigNameValue = origNameValue.slice(0,m1.length * -1);\n\t\t\t} else {\n\t\t\t\tparticleList.push(origNameValue.slice(0,m1.length));\n\t\t\t\torigNameValue = origNameValue.slice(m1.length);\n\t\t\t}\n\t\t\t//particleList.push(m1);\n\t\t\tnameValue = m[2];\n\t\t\tm = nameValue.match(rex);\n\t\t}\n\t\tif (firstNameFlag) {\n\t\t\tnameValue = nameValue.split(\"\").reverse().join(\"\");\n\t\t\tparticleList.reverse();\n\t\t\tfor (var i=1,ilen=particleList.length;i<ilen;i++) {\n\t\t\t\tif (particleList[i].slice(0, 1) == \" \") {\n\t\t\t\t\tparticleList[i-1] += \" \";\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (var i=0,ilen=particleList.length;i<ilen;i++) {\n\t\t\t\tif (particleList[i].slice(0, 1) == \" \") {\n\t\t\t\t\tparticleList[i] = particleList[i].slice(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tnameValue = origNameValue.slice(0, nameValue.length);\n\t\t} else {\n\t\t\tnameValue = origNameValue.slice(nameValue.length * -1);\n\t\t}\n\t\treturn [hasParticle, nameValue, particleList];\n\t}\n    function trimLast(str) {\n        var lastChar = str.slice(-1);\n        str = str.trim();\n        if (lastChar === \" \" && [\"\\'\", \"\\u2019\"].indexOf(str.slice(-1)) > -1) {\n            str += \" \";\n        }\n        return str;\n    }\n    function parseSuffix(nameObj) {\n        if (!nameObj.suffix && nameObj.given) {\n            var m = nameObj.given.match(/(\\s*,!*\\s*)/);\n            if (m) {\n                var idx = nameObj.given.indexOf(m[1]);\n                var possible_suffix = nameObj.given.slice(idx + m[1].length);\n                var possible_comma = nameObj.given.slice(idx, idx + m[1].length).replace(/\\s*/g, \"\");\n                if (possible_suffix.replace(/\\./g, \"\") === 'et al' && !nameObj[\"dropping-particle\"]) {\n                    // This hack covers the case where \"et al.\" is explicitly used in the\n                    // authorship information of the work.\n                    nameObj[\"dropping-particle\"] = possible_suffix;\n                    nameObj[\"comma-dropping-particle\"] = \",\";\n                } else {\n                    if (possible_comma.length === 2) {\n                        nameObj[\"comma-suffix\"] = true;\n                    }\n                    nameObj.suffix = possible_suffix;\n                }\n                nameObj.given = nameObj.given.slice(0, idx);\n            }\n        }\n    }\n    return function(nameObj) {\n        // Extract and set non-dropping particle(s) from family name field\n        var res = splitParticles(nameObj.family);\n        var lastNameValue = res[1];\n        var lastParticleList = res[2];\n        nameObj.family = lastNameValue;\n        var nonDroppingParticle = trimLast(lastParticleList.join(\"\"));\n        if (nonDroppingParticle) {\n            nameObj['non-dropping-particle'] = nonDroppingParticle;\n        }\n        // Split off suffix first of all\n        parseSuffix(nameObj);\n        // Extract and set dropping particle(s) from given name field\n        var res = splitParticles(nameObj.given, true);\n        var firstNameValue = res[1];\n        var firstParticleList = res[2];\n        nameObj.given = firstNameValue;\n        var droppingParticle = firstParticleList.join(\"\").trim();\n        if (droppingParticle) {\n            nameObj['dropping-particle'] = droppingParticle;\n        }\n    };\n}());\n\n\nmodule.exports = CSL",
  "./component-parser": "/**\n * Hardened component parser for oracle.js.\n *\n * Replaces fragile substring prefix matching with exact field-aware\n * matching against known reference data. Prioritizes precision over\n * recall: false negatives are acceptable, false positives are not.\n *\n * Key improvements over the original parseComponents():\n * - Title: full-field match (was 20-char prefix)\n * - Container-title: full-field match (was 15-char prefix)\n * - Publisher: full-field match (was 10-char prefix)\n * - findRefDataForEntry: multi-field scoring (was first-author-only)\n * - Volume/issue: word-boundary matching (was includes())\n * - All components track their position in the entry string\n */\n\n'use strict';\n\n// -- Text normalization --\n\n/**\n * Normalize text by stripping HTML, markdown formatting, and\n * collapsing whitespace.\n */\nfunction normalizeText(text) {\n  return text\n    .replace(/<[^>]+>/g, '')           // Strip HTML tags\n    .replace(/&#38;/g, '&')            // HTML entity for &\n    .replace(/_([^_]+)_/g, '$1')       // Strip markdown italics\n    .replace(/\\*\\*([^*]+)\\*\\*/g, '$1') // Strip markdown bold\n    .replace(/\\s+/g, ' ')             // Normalize whitespace\n    .trim();\n}\n\n// -- Reference data lookup --\n\n/**\n * Find the reference data matching a bibliography entry.\n *\n * Uses multi-field scoring (author + year + title) to disambiguate\n * entries that share an author name. This fixes the original\n * findRefDataForEntry which returned the first author match\n * regardless of whether multiple refs shared that author.\n *\n * @param {string} entry - The bibliography entry text\n * @param {Object} testItems - Map of item IDs to reference data\n * @returns {Object|null} The best-matching reference, or null\n */\nfunction findRefDataForEntry(entry, testItems) {\n  const entryLower = normalizeText(entry).toLowerCase();\n  const candidates = [];\n  const nameRoles = ['author', 'editor', 'translator', 'interviewer', 'recipient'];\n\n  for (const [id, ref] of Object.entries(testItems)) {\n    let score = 0;\n    let nameMatch = false;\n\n    for (const role of nameRoles) {\n      if (nameMatch || !ref[role] || ref[role].length === 0) continue;\n      const first = ref[role][0];\n      const name = (first.family || first.literal || '').toLowerCase();\n      if (name && entryLower.includes(name)) {\n        score += 1;\n        nameMatch = true;\n      }\n    }\n\n    if (!nameMatch) {\n      if (!ref.title) continue;\n      const titleLower = normalizeText(ref.title).toLowerCase();\n      if (entryLower.includes(titleLower)) {\n        score += 4;\n      } else {\n        const prefix = titleLower.substring(0, Math.min(40, titleLower.length));\n        if (prefix.length >= 10 && entryLower.includes(prefix)) {\n          score += 2;\n        }\n      }\n      if (score === 0) continue;\n    }\n\n    // Year match (strongly discriminating)\n    if (ref.issued && ref.issued['date-parts'] && ref.issued['date-parts'][0]) {\n      const year = String(ref.issued['date-parts'][0][0]);\n      if (entryLower.includes(year)) {\n        score += 2;\n      }\n    }\n\n    // Title match (full title is the strongest signal)\n    if (ref.title) {\n      const titleLower = normalizeText(ref.title).toLowerCase();\n      if (entryLower.includes(titleLower)) {\n        score += 4;\n      } else {\n        // Partial title: use first 40 chars (styles may sentence-case or truncate)\n        const prefix = titleLower.substring(0, Math.min(40, titleLower.length));\n        if (prefix.length >= 10 && entryLower.includes(prefix)) {\n          score += 2;\n        }\n      }\n    }\n\n    candidates.push({ id, ref, score });\n  }\n\n  if (candidates.length === 0) return null;\n\n  // Return highest-scoring candidate\n  candidates.sort((a, b) => b.score - a.score);\n  return candidates[0].ref;\n}\n\n// -- Position helpers --\n\nfunction escapeRegex(str) {\n  return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * Find the position of a string field value in the entry.\n * Uses case-insensitive full-field matching.\n *\n * @returns {{ start: number, end: number }|null}\n */\nfunction findFieldPosition(entryLower, fieldValue) {\n  if (!fieldValue) return null;\n  const normalized = normalizeText(String(fieldValue)).toLowerCase();\n  if (!normalized) return null;\n\n  const idx = entryLower.indexOf(normalized);\n  if (idx >= 0) {\n    return { start: idx, end: idx + normalized.length };\n  }\n  return null;\n}\n\n/**\n * Find a numeric field value with digit-boundary guards to prevent\n * false positives. For example, volume \"10\" must not match \"2010\".\n *\n * @returns {{ start: number, end: number }|null}\n */\nfunction findNumericFieldPosition(entryLower, value) {\n  if (value == null) return null;\n  const str = String(value);\n  // Digit-boundary: not preceded or followed by another digit\n  const regex = new RegExp(`(?<![0-9])${escapeRegex(str)}(?![0-9])`);\n  const match = entryLower.match(regex);\n  if (match) {\n    return { start: match.index, end: match.index + str.length };\n  }\n  return null;\n}\n\n/**\n * Expand a name component position to include given name or initials if nearby.\n * @param {string} entryLower - Normalized lower-case entry text\n * @param {Object} familyPos - {start, end} of the family name\n * @param {string} givenName - The given name to search for\n */\nfunction expandNamePosition(entryLower, familyPos, givenName) {\n  if (!familyPos) return null;\n\n  if (!givenName) return familyPos;\n\n  const givenLower = givenName.toLowerCase();\n  const givenInitial = givenName.charAt(0).toLowerCase();\n\n  // Try finding full given name or initial near the family name\n  const searchWindow = 50;\n  const start = Math.max(0, familyPos.start - searchWindow);\n  const end = Math.min(entryLower.length, familyPos.end + searchWindow);\n  const text = entryLower.substring(start, end);\n\n  let givenPos = null;\n  let givenLen = 0;\n\n  // 1. Try full given name\n  const idxFull = text.indexOf(givenLower);\n  if (idxFull !== -1) {\n    givenPos = start + idxFull;\n    givenLen = givenLower.length;\n  } else {\n    // 2. Try initial\n    // Basic check for \"g.\" or \"g \"\n    const initialRegex = new RegExp(`\\\\b${escapeRegex(givenInitial)}\\\\.?`, 'i');\n    const match = text.match(initialRegex);\n    if (match) {\n      givenPos = start + match.index;\n      givenLen = match[0].length;\n    }\n  }\n\n  if (givenPos !== null) {\n    // Merge ranges\n    const mergedStart = Math.min(familyPos.start, givenPos);\n    const mergedEnd = Math.max(familyPos.end, givenPos + givenLen);\n    return { start: mergedStart, end: mergedEnd };\n  }\n\n  return familyPos;\n}\n\nfunction positionsOverlap(left, right) {\n  if (!left || !right) return false;\n  return left.start < right.end && right.start < left.end;\n}\n\nfunction sliceMatchedValue(normalizedEntry, position) {\n  if (!position) return null;\n  return normalizedEntry.substring(position.start, position.end);\n}\n\nfunction findContributorComponent(normalizedEntry, names, occupiedPositions = []) {\n  if (!Array.isArray(names) || names.length === 0) return null;\n\n  const first = names[0];\n  const family = first.family || first.literal || '';\n  const given = first.given || '';\n  if (!family) return null;\n\n  const entryLower = normalizedEntry.toLowerCase();\n  let idx = entryLower.indexOf(family.toLowerCase());\n  while (idx !== -1) {\n    let position = { start: idx, end: idx + family.length };\n    position = expandNamePosition(entryLower, position, given);\n    if (!occupiedPositions.some((occupied) => positionsOverlap(occupied, position))) {\n      return { found: true, value: sliceMatchedValue(normalizedEntry, position), position };\n    }\n    idx = entryLower.indexOf(family.toLowerCase(), idx + 1);\n  }\n\n  return null;\n}\n\n// -- Component extraction --\n\n/**\n * Extract structured components from a bibliography entry.\n *\n * Uses exact field matching against known reference data instead of\n * substring prefix heuristics. Every component includes a position\n * for ordering analysis and delimiter detection.\n *\n * @param {string} entry - The bibliography entry text\n * @param {Object|null} refData - The reference data for this entry\n * @returns {Object} Structured components with found/value/position\n */\nfunction parseComponents(entry, refData) {\n  const normalized = normalizeText(entry);\n  const entryLower = normalized.toLowerCase();\n\n  const components = {\n    raw: entry,\n    contributors: { found: false, value: null, position: null },\n    year: { found: false, value: null, position: null },\n    title: { found: false, value: null, position: null },\n    containerTitle: { found: false, value: null, position: null },\n    volume: { found: false, value: null, position: null },\n    issue: { found: false, value: null, position: null },\n    pages: { found: false, value: null, position: null },\n    publisher: { found: false, value: null, position: null },\n    place: { found: false, value: null, position: null },\n    doi: { found: false, value: null, position: null },\n    url: { found: false, value: null, position: null },\n    edition: { found: false, value: null, position: null },\n    editors: { found: false, value: null, position: null },\n    translators: { found: false, value: null, position: null },\n    interviewers: { found: false, value: null, position: null },\n    recipients: { found: false, value: null, position: null },\n  };\n\n  // === Pattern-based components (not dependent on refData) ===\n\n  // Year in parentheses: (2020) — don't capture trailing period (it's a delimiter)\n  const yearParensMatch = normalized.match(/\\((\\d{4})\\)/);\n  // Year standalone: 2020 followed by punctuation (don't capture the punctuation)\n  const yearStandaloneMatch = normalized.match(/(?:^|\\s)(\\d{4})(?=[.,\\)])/);\n  const yearMatch = yearParensMatch || yearStandaloneMatch;\n  if (yearMatch) {\n    const idx = normalized.indexOf(yearMatch[0]);\n    if (yearParensMatch) {\n      // Parenthesized: position covers \"(2020)\" — wrap is part of the component\n      components.year = {\n        found: true,\n        value: yearMatch[1],\n        position: { start: idx, end: idx + yearMatch[0].length },\n      };\n    } else {\n      // Standalone: position covers just the 4-digit year (skip leading space)\n      const yearStart = idx + yearMatch[0].indexOf(yearMatch[1]);\n      components.year = {\n        found: true,\n        value: yearMatch[1],\n        position: { start: yearStart, end: yearStart + yearMatch[1].length },\n      };\n    }\n  }\n\n  // DOI\n  const doiMatch = normalized.match(\n    /(?:https?:\\/\\/doi\\.org\\/|doi:\\s*|DOI:\\s*)(10\\.\\d+\\/[^\\s]+)/i\n  );\n  if (doiMatch) {\n    const idx = normalized.indexOf(doiMatch[0]);\n    components.doi = {\n      found: true,\n      value: doiMatch[1],\n      position: { start: idx, end: idx + doiMatch[0].length },\n    };\n  }\n\n  // URL (only if no DOI found)\n  if (!components.doi.found) {\n    const urlMatch = normalized.match(/https?:\\/\\/[^\\s]+/i);\n    if (urlMatch) {\n      const idx = normalized.indexOf(urlMatch[0]);\n      components.url = {\n        found: true,\n        value: urlMatch[0],\n        position: { start: idx, end: idx + urlMatch[0].length },\n      };\n    }\n  }\n\n  // Page ranges: pp. 123-456, 123-456, 123–456\n  const pagesMatch = normalized.match(/(?:pp?\\.\\s*)?(\\d+)[\\-–](\\d+)/);\n  if (pagesMatch) {\n    const idx = normalized.indexOf(pagesMatch[0]);\n    components.pages = {\n      found: true,\n      value: `${pagesMatch[1]}-${pagesMatch[2]}`,\n      position: { start: idx, end: idx + pagesMatch[0].length },\n    };\n  }\n\n  // Edition: 2nd ed., Silver Anniversary Edition\n  const editionMatch = normalized.match(\n    /(\\d+(?:st|nd|rd|th)\\s+ed\\.|[A-Za-z\\s]+Edition)/i\n  );\n  if (editionMatch) {\n    const idx = normalized.indexOf(editionMatch[0]);\n    components.edition = {\n      found: true,\n      value: editionMatch[1],\n      position: { start: idx, end: idx + editionMatch[0].length },\n    };\n  }\n\n  // Editor markers: (Ed.), (Eds.), edited by\n  const editorsMatch = normalized.match(/\\(Eds?\\.\\)|edited by|Ed\\.|Eds\\./i);\n  if (editorsMatch) {\n    const idx = normalized.indexOf(editorsMatch[0]);\n    components.editors = {\n      found: true,\n      value: true,\n      position: { start: idx, end: idx + editorsMatch[0].length },\n    };\n  }\n\n  // === Reference-data-driven components ===\n\n  if (refData) {\n    // Contributors: first author (or editor if no author)\n    const principalNames = (refData.author && refData.author.length > 0)\n      ? refData.author : refData.editor;\n\n    const principalComponent = findContributorComponent(normalized, principalNames);\n    if (principalComponent) {\n      components.contributors = principalComponent;\n    }\n\n    const occupiedPositions = [];\n    if (components.contributors.found && components.contributors.position) {\n      occupiedPositions.push(components.contributors.position);\n    }\n\n    const secondaryRoleMappings = [\n      ['editor', 'editors'],\n      ['translator', 'translators'],\n      ['interviewer', 'interviewers'],\n      ['recipient', 'recipients'],\n    ];\n\n    for (const [refKey, componentKey] of secondaryRoleMappings) {\n      const component = findContributorComponent(normalized, refData[refKey], occupiedPositions);\n      if (component) {\n        components[componentKey] = component;\n        occupiedPositions.push(component.position);\n      }\n    }\n\n    // Title: full-field exact match\n    if (refData.title) {\n      const pos = findFieldPosition(entryLower, refData.title);\n      if (pos) {\n        components.title = { found: true, value: refData.title, position: pos };\n      }\n    }\n\n    // Container-title: full-field exact match\n    if (refData['container-title']) {\n      const pos = findFieldPosition(entryLower, refData['container-title']);\n      if (pos) {\n        components.containerTitle = {\n          found: true,\n          value: refData['container-title'],\n          position: pos,\n        };\n      }\n    }\n\n    // Publisher: full-field exact match\n    if (refData.publisher) {\n      const pos = findFieldPosition(entryLower, refData.publisher);\n      if (pos) {\n        components.publisher = {\n          found: true,\n          value: refData.publisher,\n          position: pos,\n        };\n      }\n    }\n\n    // Publisher-place\n    if (refData['publisher-place']) {\n      const pos = findFieldPosition(entryLower, refData['publisher-place']);\n      if (pos) {\n        components.place = {\n          found: true,\n          value: refData['publisher-place'],\n          position: pos,\n        };\n      }\n    }\n\n    // Volume/issue: prefer combined vol(issue) pattern first\n    const volIssueMatch = normalized.match(/(\\d+)\\s*\\((\\d+)\\)/);\n    if (volIssueMatch) {\n      const matchedVol = volIssueMatch[1];\n      const matchedIssue = volIssueMatch[2];\n      const idx = normalized.indexOf(volIssueMatch[0]);\n\n      if (refData.volume && matchedVol === String(refData.volume)) {\n        components.volume = {\n          found: true,\n          value: matchedVol,\n          position: { start: idx, end: idx + matchedVol.length },\n        };\n      }\n      if (refData.issue && matchedIssue === String(refData.issue)) {\n        components.issue = {\n          found: true,\n          value: matchedIssue,\n          position: {\n            start: idx + matchedVol.length + 1,\n            end: idx + volIssueMatch[0].length - 1,\n          },\n        };\n      }\n    } else {\n      // Individual volume/issue with digit-boundary guards\n      if (refData.volume) {\n        const pos = findNumericFieldPosition(entryLower, refData.volume);\n        if (pos) {\n          components.volume = {\n            found: true,\n            value: String(refData.volume),\n            position: pos,\n          };\n        }\n      }\n      if (refData.issue) {\n        const pos = findNumericFieldPosition(entryLower, refData.issue);\n        if (pos) {\n          components.issue = {\n            found: true,\n            value: String(refData.issue),\n            position: pos,\n          };\n        }\n      }\n    }\n  }\n\n  return components;\n}\n\n// -- Ordering analysis --\n\n/**\n * Analyze component ordering by their positions in the entry.\n * Returns component names in the order they appear.\n *\n * @param {string} entry - The bibliography entry text\n * @param {Object|null} refData - The reference data for this entry\n * @returns {string[]} Component names sorted by position\n */\nfunction analyzeOrdering(entry, refData) {\n  const components = parseComponents(entry, refData);\n\n  const positioned = [];\n  for (const [name, comp] of Object.entries(components)) {\n    if (name === 'raw') continue;\n    if (comp.found && comp.position) {\n      positioned.push({ name, start: comp.position.start });\n    }\n  }\n\n  positioned.sort((a, b) => a.start - b.start);\n  return positioned.map(p => p.name);\n}\n\n// -- Delimiter detection --\n\n/**\n * Detect delimiters between adjacent matched components.\n *\n * Extracts the literal text between the end of one component and the\n * start of the next. Useful for inferring style-specific separators\n * (\". \" vs \", \" vs \": \") for the template inferrer.\n *\n * @param {string} entry - The bibliography entry text\n * @param {Object|null} refData - The reference data for this entry\n * @returns {Array<{ between: [string, string], delimiter: string }>}\n */\nfunction detectDelimiters(entry, refData) {\n  const normalized = normalizeText(entry);\n  const components = parseComponents(entry, refData);\n  const delimiters = [];\n\n  // Collect positioned components\n  const positioned = [];\n  for (const [name, comp] of Object.entries(components)) {\n    if (name === 'raw') continue;\n    if (comp.found && comp.position) {\n      positioned.push({ name, start: comp.position.start, end: comp.position.end });\n    }\n  }\n\n  positioned.sort((a, b) => a.start - b.start);\n\n  // Extract text between each adjacent pair\n  for (let i = 0; i < positioned.length - 1; i++) {\n    const current = positioned[i];\n    const next = positioned[i + 1];\n\n    // Only capture short delimiters (avoid capturing large unmatched spans)\n    if (next.start > current.end && (next.start - current.end) <= 15) {\n      const between = normalized.substring(current.end, next.start);\n      delimiters.push({\n        between: [current.name, next.name],\n        delimiter: between,\n      });\n    }\n  }\n\n  return delimiters;\n}\n\nmodule.exports = {\n  normalizeText,\n  findRefDataForEntry,\n  parseComponents,\n  analyzeOrdering,\n  detectDelimiters,\n  // Exported for testing\n  findFieldPosition,\n  findNumericFieldPosition,\n};\n",
  "./template-inferrer-core": "/**\n * Output-Driven Template Inference Engine for CSL26\n *\n * Given a CSL 1.0 style file, this module:\n * 1. Renders all test fixture references through citeproc-js\n * 2. Extracts structured components from bibliography (and citations for note styles)\n * 3. Groups entries by reference type\n * 4. Builds consensus component ordering across all types\n * 5. Infers delimiters between adjacent components\n * 6. Detects type-specific suppress overrides\n * 7. Generates Citum YAML template array\n *\n * Main export: inferTemplate(stylePath, section) → { template, yaml, meta }\n */\n\n'use strict';\n\nconst CSL = require('citeproc');\nconst {\n  normalizeText,\n  parseComponents,\n  analyzeOrdering,\n  findRefDataForEntry,\n  detectDelimiters,\n} = require('./component-parser');\n\n// -- Citeproc-js rendering --\n\n/**\n * Render bibliography entries using citeproc-js.\n *\n * @param {string} styleXml - The CSL 1.0 style XML\n * @param {Object} testItems - Map of item IDs to CSL JSON reference data\n * @param {string} localeXml - CSL locale XML content\n * @returns {Object|null} { entries: Array<string>, style } or null if rendering fails\n */\nfunction renderWithCiteproc(styleXml, testItems, localeXml) {\n  try {\n    const engine = new CSL.Engine({\n      retrieveLocale: () => localeXml,\n      retrieveItem: (id) => testItems[id],\n    }, styleXml);\n\n    // Get all item IDs\n    const itemIds = Object.keys(testItems);\n\n    // Set bibliography for the engine\n    engine.setOutputFormat('html');\n    engine.updateItems(itemIds);\n\n    // Get bibliography entries\n    const bibResult = engine.makeBibliography();\n    if (!bibResult || !bibResult[1]) {\n      return null;\n    }\n\n    return {\n      entries: bibResult[1],\n      style: styleXml,\n    };\n  } catch (error) {\n    console.error(`Failed to render with citeproc-js: ${error.message}`);\n    return null;\n  }\n}\n\n/**\n * Render note-style citations (for position tracking in note styles).\n * Returns array of citation strings indexed by item ID.\n */\nfunction renderCitations(styleXml, testItems, localeXml) {\n  try {\n    const engine = new CSL.Engine({\n      retrieveLocale: () => localeXml,\n      retrieveItem: (id) => testItems[id],\n    }, styleXml);\n\n    const itemIds = Object.keys(testItems);\n    engine.setOutputFormat('html');\n    engine.updateItems(itemIds);\n\n    const citations = {};\n    for (const id of itemIds) {\n      try {\n        const text = engine.makeCitationCluster([{ id }]);\n        citations[id] = text || '';\n      } catch (e) {\n        citations[id] = null;\n      }\n    }\n    return citations;\n  } catch (error) {\n    console.error(`Failed to render citations: ${error.message}`);\n    return null;\n  }\n}\n\n// -- Component aggregation and ordering --\n\n/**\n * Aggregate components across all entries of a single reference type.\n * Returns components found in any entry, plus their aggregate positions.\n */\nfunction aggregateByType(entries, refByEntry) {\n  const typedComponents = {};\n\n  for (let idx = 0; idx < entries.length; idx++) {\n    const entry = entries[idx];\n    const refData = refByEntry[idx];\n\n    // Parse components\n    const comps = parseComponents(entry, refData);\n    const type = refData?.type || 'unknown';\n\n    if (!typedComponents[type]) {\n      typedComponents[type] = {\n        entries: [],\n        componentCounts: {},\n        componentInstances: {},\n        // Track components with data in ref but suppressed in output\n        suppressedCounts: {},\n      };\n    }\n\n    typedComponents[type].entries.push({ index: idx, rendered: entry, refData });\n\n    // Track which components appear in this entry\n    for (const [name, comp] of Object.entries(comps)) {\n      if (name === 'raw') continue;\n      if (comp.found) {\n        typedComponents[type].componentCounts[name] =\n          (typedComponents[type].componentCounts[name] || 0) + 1;\n\n        if (!typedComponents[type].componentInstances[name]) {\n          typedComponents[type].componentInstances[name] = [];\n        }\n        typedComponents[type].componentInstances[name].push(comp);\n      }\n    }\n\n    // Special handling: track issue suppression (data present but not rendered)\n    if (refData?.issue && !comps.issue?.found) {\n      typedComponents[type].suppressedCounts['issue'] =\n        (typedComponents[type].suppressedCounts['issue'] || 0) + 1;\n    }\n  }\n\n  return typedComponents;\n}\n\n/**\n * Find the consensus component ordering across all reference types.\n */\nfunction findConsensusOrdering(entries, refByEntry) {\n  const typedComponents = aggregateByType(entries, refByEntry);\n\n  const allOrderings = [];\n  const orderingsByType = {};\n  const orderingAgreementByType = {};\n\n  for (const [type, data] of Object.entries(typedComponents)) {\n    const typeOrderings = [];\n    for (const { rendered, refData } of data.entries) {\n      const ordering = analyzeOrdering(rendered, refData);\n      allOrderings.push(ordering);\n      typeOrderings.push(ordering);\n    }\n    const counts = {};\n    for (const o of typeOrderings) {\n      const k = o.join(',');\n      counts[k] = (counts[k] || 0) + 1;\n    }\n    const best = Object.entries(counts).sort((a, b) => b[1] - a[1]);\n    orderingsByType[type] = best[0]?.[0]?.split(',').filter(Boolean) || [];\n    const bestCount = best[0]?.[1] || 0;\n    orderingAgreementByType[type] = typeOrderings.length > 0\n      ? bestCount / typeOrderings.length\n      : 0;\n  }\n\n  const allComponents = new Set();\n  for (const ordering of allOrderings) {\n    for (const comp of ordering) {\n      if (comp) allComponents.add(comp);\n    }\n  }\n\n  const componentFrequency = {};\n  for (const comp of allComponents) {\n    componentFrequency[comp] = 0;\n    for (const ordering of allOrderings) {\n      if (ordering.includes(comp)) {\n        componentFrequency[comp]++;\n      }\n    }\n  }\n\n  const precedence = {};\n  for (const comp of allComponents) {\n    precedence[comp] = {};\n  }\n  for (const ordering of allOrderings) {\n    for (let i = 0; i < ordering.length; i++) {\n      for (let j = i + 1; j < ordering.length; j++) {\n        const a = ordering[i];\n        const b = ordering[j];\n        if (a && b) {\n          precedence[a][b] = (precedence[a][b] || 0) + 1;\n        }\n      }\n    }\n  }\n\n  const componentScores = {};\n  for (const comp of allComponents) {\n    componentScores[comp] = 0;\n    for (const other of allComponents) {\n      if (other === comp) continue;\n      componentScores[comp] +=\n        (precedence[comp]?.[other] || 0) - (precedence[other]?.[comp] || 0);\n    }\n  }\n\n  const componentList = [...allComponents];\n  componentList.sort((a, b) => {\n    const scoreDelta = (componentScores[b] || 0) - (componentScores[a] || 0);\n    if (scoreDelta !== 0) {\n      return scoreDelta;\n    }\n    const frequencyDelta = (componentFrequency[b] || 0) - (componentFrequency[a] || 0);\n    if (frequencyDelta !== 0) {\n      return frequencyDelta;\n    }\n    return a.localeCompare(b);\n  });\n\n  const volIdx = componentList.indexOf('volume');\n  const issIdx = componentList.indexOf('issue');\n  if (volIdx >= 0 && issIdx >= 0 && issIdx !== volIdx + 1) {\n    componentList.splice(issIdx, 1);\n    const newVolIdx = componentList.indexOf('volume');\n    componentList.splice(newVolIdx + 1, 0, 'issue');\n  }\n\n  const minFrequency = Math.max(1, Math.floor(allOrderings.length * 0.1));\n  const consensusOrdering = componentList.filter(\n    comp => (componentFrequency[comp] || 0) >= minFrequency\n  );\n\n  return {\n    consensusOrdering,\n    orderingsByType,\n    orderingAgreementByType,\n    typedComponents,\n    componentFrequency,\n  };\n}\n\n// -- Delimiter detection and consensus --\n\nfunction findDelimiterConsensus(entries, refByEntry, comp1, comp2, minFraction) {\n  const delimiters = {};\n\n  for (let idx = 0; idx < entries.length; idx++) {\n    const entry = entries[idx];\n    const refData = refByEntry[idx];\n    const dets = detectDelimiters(entry, refData);\n\n    for (const det of dets) {\n      if (det.between[0] === comp1 && det.between[1] === comp2) {\n        const delim = det.delimiter;\n        delimiters[delim] = (delimiters[delim] || 0) + 1;\n      }\n    }\n  }\n\n  if (Object.keys(delimiters).length === 0) return null;\n  const sorted = Object.entries(delimiters).sort((a, b) => b[1] - a[1]);\n  const minCount = Math.max(1, Math.floor(entries.length * (minFraction || 0)));\n  if (sorted[0][1] < minCount) return null;\n  return sorted[0][0].replace(/[\"\\u201c\\u201d]+/g, '') || sorted[0][0];\n}\n\n// -- Prefix/suffix and wrap detection --\n\nfunction detectPrefixPatterns(componentName, entries, refByEntry) {\n  const results = {};\n\n  for (let idx = 0; idx < entries.length; idx++) {\n    const refData = refByEntry[idx];\n    if (!refData) continue;\n\n    const comps = parseComponents(entries[idx], refData);\n    const comp = comps[componentName];\n    if (!comp?.found || !comp.position) continue;\n\n    const type = refData.type || 'unknown';\n    const normalized = normalizeText(entries[idx]);\n    const matchText = normalized.slice(comp.position.start, comp.position.end);\n    const beforeStart = Math.max(0, comp.position.start - 20);\n    const before = normalized.slice(beforeStart, comp.position.start);\n\n    let prefix = null;\n    if (/^https?:\\/\\/doi\\.org\\//i.test(matchText)) {\n      prefix = 'https://doi.org/';\n    }\n    else if (/^pp?\\.\\s*/i.test(matchText)) {\n      prefix = 'pp. ';\n    }\n    else if ((componentName === 'editors' || componentName.startsWith('containerTitle')) &&\n      /(?:In|on)[:\\s]+\\s*$/i.test(before)) {\n      const match = before.match(/(?:In|on)[:\\s]+\\s*$/i);\n      prefix = match[0];\n    }\n\n    if (prefix) {\n      if (!results[type]) results[type] = {};\n      results[type][prefix] = (results[type][prefix] || 0) + 1;\n    }\n  }\n\n  const typeWinners = {};\n  for (const [type, pfxs] of Object.entries(results)) {\n    const typeTotal = entries.filter((e, i) => {\n      if ((refByEntry[i]?.type || 'unknown') !== type) return false;\n      const c = parseComponents(e, refByEntry[i]);\n      return c[componentName]?.found;\n    }).length;\n\n    const best = Object.entries(pfxs).sort((a, b) => b[1] - a[1]);\n    if (best.length > 0 && best[0][1] / typeTotal >= 0.5) {\n      typeWinners[type] = best[0][0];\n    }\n  }\n\n  const allTypesWithComp = new Set(refByEntry.filter(r => r).map(r => r.type || 'unknown'));\n  const globalCounts = {};\n  for (const pfx of Object.values(typeWinners)) {\n    globalCounts[pfx] = (globalCounts[pfx] || 0) + 1;\n  }\n  const bestGlobal = Object.entries(globalCounts).sort((a, b) => b[1] - a[1]);\n\n  const globalWinner = (bestGlobal.length > 0 && bestGlobal[0][1] / allTypesWithComp.size > 0.5)\n    ? bestGlobal[0][0] : null;\n\n  const overrides = {};\n  for (const [type, winner] of Object.entries(typeWinners)) {\n    if (winner !== globalWinner) {\n      overrides[type] = winner;\n    }\n  }\n\n  return { globalWinner, overrides };\n}\n\nfunction normalizeLocalizedPageLabelPrefix(component, prefix) {\n  if (component?.number !== 'pages') return { prefix, localized: false };\n\n  const pageLabelPrefixes = new Map([\n    ['pp. ', null],\n    [', pp. ', ', '],\n    [' pp. ', ' '],\n  ]);\n\n  if (!pageLabelPrefixes.has(prefix)) return { prefix, localized: false };\n\n  return { prefix: pageLabelPrefixes.get(prefix), localized: true };\n}\n\nfunction detectVolumeIssueGrouping(entries, refByEntry) {\n  let withBoth = 0;\n  let grouped = 0;\n\n  for (let idx = 0; idx < entries.length; idx++) {\n    const comps = parseComponents(entries[idx], refByEntry[idx]);\n    if (!comps.volume?.found || !comps.issue?.found) continue;\n    if (!comps.volume.position || !comps.issue.position) continue;\n\n    withBoth++;\n    const normalized = normalizeText(entries[idx]);\n    const between = normalized.slice(comps.volume.position.end, comps.issue.position.start);\n\n    if (/^\\s*\\(?\\s*$/.test(between)) {\n      grouped++;\n    }\n  }\n\n  return withBoth > 0 && grouped / withBoth >= 0.5;\n}\n\nfunction detectWrapPatterns(componentName, entries, refByEntry) {\n  const results = {};\n\n  for (let idx = 0; idx < entries.length; idx++) {\n    const refData = refByEntry[idx];\n    if (!refData) continue;\n\n    const comps = parseComponents(entries[idx], refData);\n    const comp = comps[componentName];\n    if (!comp?.found || !comp.position) continue;\n\n    const type = refData.type || 'unknown';\n    const normalized = normalizeText(entries[idx]);\n    const charBefore = normalized[comp.position.start - 1] || '';\n    const charAfter = normalized[comp.position.end] || '';\n\n    let wrap = null;\n    if (charBefore === '(' && charAfter === ')') {\n      wrap = 'parentheses';\n    } else if (charBefore === '[' && charAfter === ']') {\n      wrap = 'brackets';\n    }\n\n    if (wrap) {\n      if (!results[type]) results[type] = {};\n      results[type][wrap] = (results[type][wrap] || 0) + 1;\n    }\n  }\n\n  const typeWinners = {};\n  for (const [type, wraps] of Object.entries(results)) {\n    const typeTotal = entries.filter((e, i) => {\n      if ((refByEntry[i]?.type || 'unknown') !== type) return false;\n      const c = parseComponents(e, refByEntry[i]);\n      return c[componentName]?.found;\n    }).length;\n\n    const best = Object.entries(wraps).sort((a, b) => b[1] - a[1]);\n    if (best.length > 0 && best[0][1] / typeTotal >= 0.7) {\n      typeWinners[type] = best[0][0];\n    }\n  }\n\n  const allTypesWithComp = new Set();\n  for (let i = 0; i < entries.length; i++) {\n    const type = refByEntry[i]?.type || 'unknown';\n    const c = parseComponents(entries[i], refByEntry[i]);\n    if (c[componentName]?.found) allTypesWithComp.add(type);\n  }\n\n  const globalCounts = {};\n  for (const wrap of Object.values(typeWinners)) {\n    globalCounts[wrap] = (globalCounts[wrap] || 0) + 1;\n  }\n  const bestGlobal = Object.entries(globalCounts).sort((a, b) => b[1] - a[1]);\n\n  const globalWinner = (bestGlobal.length > 0 && bestGlobal[0][1] / allTypesWithComp.size > 0.5)\n    ? bestGlobal[0][0] : null;\n\n  const overrides = {};\n  for (const [type, winner] of Object.entries(typeWinners)) {\n    if (winner !== globalWinner) {\n      overrides[type] = winner;\n    }\n  }\n\n  return { globalWinner, overrides, typeWinners };\n}\n\n// -- Formatting detection --\n\nfunction detectFormatting(componentName, entries, refByEntry) {\n  const formats = { italic: 0, quotes: 0 };\n  let total = 0;\n\n  for (let idx = 0; idx < entries.length; idx++) {\n    const refData = refByEntry[idx];\n    if (!refData) continue;\n\n    let rawValue = null;\n    switch (componentName) {\n      case 'title': rawValue = refData.title; break;\n      case 'containerTitle': rawValue = refData['container-title']; break;\n      default: return null;\n    }\n    if (!rawValue) continue;\n\n    const rawHtml = entries[idx];\n    const valueLower = rawValue.toLowerCase();\n    const htmlLower = rawHtml.toLowerCase();\n\n    const valueIdx = htmlLower.indexOf(valueLower);\n    if (valueIdx < 0) continue;\n\n    total++;\n    const before = rawHtml.substring(Math.max(0, valueIdx - 10), valueIdx);\n    const after = rawHtml.substring(valueIdx + rawValue.length, valueIdx + rawValue.length + 10);\n\n    if (/<i>\\s*$/i.test(before) && /^\\s*<\\/i>/i.test(after)) {\n      formats.italic++;\n    }\n\n    const charBefore = rawHtml[valueIdx - 1] || '';\n    const charAfter = rawHtml[valueIdx + rawValue.length] || '';\n    if ((charBefore === '\\u201c' || charBefore === '\"') &&\n      (charAfter === '\\u201d' || charAfter === '\"' || charAfter === ',')) {\n      formats.quotes++;\n    }\n  }\n\n  if (total === 0) return null;\n  if (formats.italic / total >= 0.5) return { emph: true };\n  if (formats.quotes / total >= 0.5) return { wrap: 'quotes' };\n  return null;\n}\n\n// -- Name order detection --\n\nfunction detectNameOrder(componentText, names) {\n  if (!componentText || !names || !names.length) return null;\n  const nameWithBoth = names.find(n => n.family && n.given);\n  if (!nameWithBoth) return null;\n\n  const family = nameWithBoth.family.toLowerCase();\n  const text = normalizeText(componentText).toLowerCase();\n  const familyPos = text.indexOf(family);\n  const givenInitial = nameWithBoth.given.charAt(0).toLowerCase();\n  let givenPos = text.indexOf(nameWithBoth.given.toLowerCase());\n\n  if (givenPos === -1 && givenInitial) {\n    const match = text.match(new RegExp(`\\\\b${givenInitial}\\\\.?`, 'i'));\n    if (match) givenPos = match.index;\n  }\n\n  if (familyPos === -1 || givenPos === -1) return null;\n  return familyPos < givenPos ? 'family-first' : 'given-first';\n}\n\nfunction detectNameOrderPatterns(parserName, role, entries, refByEntry) {\n  const results = {};\n\n  for (let i = 0; i < entries.length; i++) {\n    const entry = entries[i];\n    const refData = refByEntry[i];\n    if (!refData) continue;\n\n    const comps = parseComponents(entry, refData);\n    if (!comps[parserName]?.found || !comps[parserName].position) continue;\n\n    const type = refData.type || 'unknown';\n    const normalized = normalizeText(entry);\n    const pos = comps[parserName].position;\n    const windowText = normalized.substring(Math.max(0, pos.start - 5), Math.min(normalized.length, pos.end + 5));\n\n    const names = (parserName === 'contributors')\n      ? (refData.author?.length > 0 ? refData.author : refData.editor)\n      : refData[role];\n\n    const order = detectNameOrder(windowText, names);\n    if (order) {\n      if (!results[type]) results[type] = {};\n      results[type][order] = (results[type][order] || 0) + 1;\n    }\n  }\n\n  const typeWinners = {};\n  for (const [type, orders] of Object.entries(results)) {\n    const best = Object.entries(orders).sort((a, b) => b[1] - a[1]);\n    if (best.length > 0) typeWinners[type] = best[0][0];\n  }\n\n  const globalOrders = {};\n  for (const order of Object.values(typeWinners)) {\n    globalOrders[order] = (globalOrders[order] || 0) + 1;\n  }\n  const bestGlobal = Object.entries(globalOrders).sort((a, b) => b[1] - a[1]);\n  const globalWinner = bestGlobal.length > 0 ? bestGlobal[0][0] : null;\n\n  const overrides = {};\n  for (const [type, winner] of Object.entries(typeWinners)) {\n    if (winner && winner !== globalWinner) overrides[type] = winner;\n  }\n\n  return { globalWinner, overrides };\n}\n\n// -- Citum component mapping --\n\nfunction mapComponentToYaml(componentName, entry, refData) {\n  const comps = parseComponents(entry, refData);\n  const parserName = componentName.startsWith('containerTitle') ? 'containerTitle' : componentName;\n  const comp = comps[parserName];\n\n  if (!comp?.found) return null;\n\n  switch (componentName) {\n    case 'contributors': return { contributor: 'author', form: 'long' };\n    case 'year': {\n      const obj = { date: 'issued', form: 'year' };\n      if (normalizeText(entry).match(/\\((\\d{4})\\)/)) obj.wrap = 'parentheses';\n      return obj;\n    }\n    case 'title': return { title: 'primary' };\n    case 'containerTitle':\n    case 'containerTitleSerial': return { title: 'parent-serial' };\n    case 'containerTitleMonograph': return { title: 'parent-monograph' };\n    case 'volume': return { number: 'volume' };\n    case 'issue': return { number: 'issue' };\n    case 'pages': return { number: 'pages' };\n    case 'publisher': return { variable: 'publisher' };\n    case 'place': return { variable: 'publisher-place' };\n    case 'doi': return { variable: 'doi' };\n    case 'url': return { variable: 'url' };\n    case 'edition': return { number: 'edition' };\n    case 'editors': return { contributor: 'editor', form: 'verb' };\n    default: return null;\n  }\n}\n\n// -- Suppress override detection --\n\nfunction detectSuppressions(consensusOrdering, typedComponents, componentFrequency, renderedEntries, refByEntry) {\n  const suppressions = {};\n  const knownTypes = Object.keys(typedComponents).filter(t => t !== 'unknown');\n  const totalTypes = knownTypes.length;\n\n  for (const componentName of consensusOrdering) {\n    suppressions[componentName] = {};\n\n    if (componentName === 'issue') {\n      for (const type of knownTypes) {\n        const data = typedComponents[type];\n        let hasIssueInData = false;\n        let suppressedInOutput = true;\n\n        for (const { rendered, refData } of data.entries) {\n          const ref = refData;\n          if (ref?.issue) {\n            hasIssueInData = true;\n            if (rendered.toLowerCase().includes(String(ref.issue).toLowerCase())) {\n              suppressedInOutput = false;\n              break;\n            }\n          }\n        }\n        if (hasIssueInData && suppressedInOutput) suppressions.issue[type] = true;\n      }\n      continue;\n    }\n\n    let typesWithComponent = 0;\n    const typesPresent = new Set();\n    const typesMissing = new Set();\n\n    for (const type of knownTypes) {\n      const data = typedComponents[type];\n      const count = data.componentCounts[componentName] || 0;\n      if (count / data.entries.length >= 0.5) {\n        typesWithComponent++;\n        typesPresent.add(type);\n      } else {\n        typesMissing.add(type);\n      }\n    }\n\n    const presentRatio = typesWithComponent / totalTypes;\n    if (presentRatio >= 0.4 && typesMissing.size > 0 && typesMissing.size <= typesPresent.size) {\n      for (const type of typesMissing) suppressions[componentName][type] = true;\n    }\n  }\n\n  return suppressions;\n}\n\nfunction detectEtAl(parserName, entries, refByEntry, renderedEntries) {\n  const settings = { min: 0, use_first: 0 };\n  let detected = false;\n\n  for (let i = 0; i < entries.length; i++) {\n    const entryId = entries[i];\n    const ref = refByEntry[i];\n    if (!ref) continue;\n    const rendered = entryId;\n    const role = parserName === 'contributors' ? 'author' : 'editor';\n    const names = ref[role];\n\n    if (names && names.length >= 2) {\n      const lowerRendered = rendered.toLowerCase();\n      const hasEtAlMarker = lowerRendered.includes('et al') || lowerRendered.includes('…') || lowerRendered.includes('others');\n      if (hasEtAlMarker) {\n        let renderedCount = 0;\n        for (const name of names) {\n          const family = (name.family || name.literal || '').toLowerCase();\n          if (family && lowerRendered.includes(family)) renderedCount++;\n        }\n        if (renderedCount < names.length && renderedCount > 0) {\n          settings.min = names.length;\n          settings.use_first = renderedCount;\n          detected = true;\n          break;\n        }\n      }\n    }\n  }\n\n  return detected ? settings : null;\n}\n\n// -- YAML generation --\n\nconst MAIN_KEYS = new Set(['contributor', 'date', 'title', 'number', 'variable', 'items']);\n\nfunction generateYaml(template, delimiter, wrap) {\n  let yaml = '';\n  if (wrap) yaml += `wrap: ${wrap}\\n`;\n  if (delimiter && delimiter !== '. ') yaml += `delimiter: \"${delimiter}\"\\n`;\n  yaml += 'template:\\n';\n  const indent = '  ';\n\n  for (const component of template) {\n    if (component.items) {\n      yaml += `${indent}- items:\\n`;\n      for (const item of component.items) {\n        const itemKey = Object.keys(item).find(k => MAIN_KEYS.has(k));\n        if (!itemKey) continue;\n        yaml += `${indent}    - ${itemKey}: ${item[itemKey]}\\n`;\n        if (item.wrap) yaml += `${indent}      wrap: ${item.wrap}\\n`;\n        if (item.overrides) {\n          yaml += `${indent}      overrides:\\n`;\n          for (const [type, ov] of Object.entries(item.overrides)) {\n            yaml += `${indent}        ${type}: { suppress: true }\\n`;\n          }\n        }\n      }\n      yaml += `${indent}  delimiter: ${component.delimiter || 'none'}\\n`;\n      if (component.prefix) yaml += `${indent}  prefix: \"${component.prefix}\"\\n`;\n      continue;\n    }\n\n    const mainKey = Object.keys(component).find(k => MAIN_KEYS.has(k));\n    if (!mainKey) continue;\n\n    yaml += `${indent}- ${mainKey}: ${component[mainKey]}\\n`;\n    if (component.form) yaml += `${indent}  form: ${component.form}\\n`;\n    if (component.emph) yaml += `${indent}  emph: true\\n`;\n    if (component.wrap) yaml += `${indent}  wrap: ${component.wrap}\\n`;\n    if (component.prefix) yaml += `${indent}  prefix: \"${component.prefix}\"\\n`;\n    if (component['label-form']) yaml += `${indent}  label-form: ${component['label-form']}\\n`;\n    if (component['name-order']) yaml += `${indent}  name-order: ${component['name-order']}\\n`;\n    if (component.shorten) {\n      yaml += `${indent}  shorten:\\n`;\n      yaml += `${indent}    min: ${component.shorten.min}\\n`;\n      yaml += `${indent}    use-first: ${component.shorten['use-first']}\\n`;\n    }\n    if (component.delimiter) yaml += `${indent}  delimiter: \"${component.delimiter}\"\\n`;\n\n    if (component.overrides && Object.keys(component.overrides).length > 0) {\n      yaml += `${indent}  overrides:\\n`;\n      for (const [type, override] of Object.entries(component.overrides)) {\n        yaml += `${indent}    ${type}:\\n`;\n        for (const [key, val] of Object.entries(override)) {\n          yaml += `${indent}      ${key}: ${val}\\n`;\n        }\n      }\n    }\n  }\n  return yaml;\n}\n\nfunction clamp01(value) {\n  if (Number.isNaN(value)) return 0;\n  if (value < 0) return 0;\n  if (value > 1) return 1;\n  return value;\n}\n\nfunction round2(value) {\n  return Math.round(value * 100) / 100;\n}\n\nfunction computeInferenceConfidence({\n  section,\n  template,\n  renderedEntries,\n  refByEntry,\n  typedComponents,\n  orderingAgreementByType,\n  componentFrequency,\n  consensusOrdering,\n  delimiterSupport,\n}) {\n  const entryCount = Math.max(1, renderedEntries.length);\n  const mappedEntries = refByEntry.filter(Boolean).length;\n  const mappedRate = mappedEntries / entryCount;\n\n  let weightedOrderingSum = 0;\n  let weightedOrderingWeight = 0;\n  for (const [type, data] of Object.entries(typedComponents)) {\n    if (type === 'unknown') continue;\n    const weight = Math.max(1, data.entries.length);\n    const agreement = orderingAgreementByType[type] ?? 0.5;\n    weightedOrderingSum += agreement * weight;\n    weightedOrderingWeight += weight;\n  }\n  const orderingScore = weightedOrderingWeight > 0\n    ? weightedOrderingSum / weightedOrderingWeight\n    : 0.5;\n\n  let componentSupportScore = 0.5;\n  if (consensusOrdering.length > 0) {\n    let supportSum = 0;\n    for (const componentName of consensusOrdering) {\n      supportSum += (componentFrequency[componentName] || 0) / entryCount;\n    }\n    componentSupportScore = supportSum / consensusOrdering.length;\n  }\n\n  const structuralScore = template.length === 0\n    ? 0\n    : section === 'citation'\n      ? Math.min(1, template.length / 2)\n      : Math.min(1, template.length / 5);\n\n  const unknownRate = ((typedComponents.unknown?.entries?.length) || 0) / entryCount;\n\n  let score =\n    0.10 +\n    (mappedRate * 0.35) +\n    (orderingScore * 0.25) +\n    (componentSupportScore * 0.15) +\n    (clamp01(delimiterSupport) * 0.10) +\n    (structuralScore * 0.15) -\n    (unknownRate * 0.10);\n\n  if (section === 'citation') {\n    const hasCoreSignal = template.some(comp =>\n      comp.contributor || comp.date || comp.number === 'citation-number'\n    );\n    if (!hasCoreSignal) score -= 0.15;\n  }\n\n  if (section === 'bibliography' && template.length < 3) {\n    score -= 0.10;\n  }\n\n  return round2(clamp01(score));\n}\n\n// -- Main inference function --\n\nfunction inferTemplateFromInputs({\n  styleXml,\n  section = 'bibliography',\n  testItems,\n  localeXml,\n}) {\n  if (!styleXml || !testItems || !localeXml) return null;\n\n  let rendered;\n  if (section === 'bibliography') {\n    rendered = renderWithCiteproc(styleXml, testItems, localeXml);\n  } else {\n    const citations = renderCitations(styleXml, testItems, localeXml);\n    if (!citations) return null;\n    rendered = { entries: Object.values(citations).filter(c => c !== null), style: styleXml };\n  }\n\n  if (!rendered?.entries?.length) return null;\n\n  const refByEntry = rendered.entries.map(entry => findRefDataForEntry(entry, testItems));\n  const { consensusOrdering, typedComponents, componentFrequency, orderingAgreementByType } = findConsensusOrdering(\n    rendered.entries,\n    refByEntry,\n  );\n\n  const MONOGRAPH_TYPES = new Set(['chapter', 'entry-encyclopedia', 'entry-dictionary', 'paper-conference']);\n  if (consensusOrdering.includes('containerTitle')) {\n    let hasSerial = false, hasMonograph = false;\n    for (const [type, data] of Object.entries(typedComponents)) {\n      if (type === 'unknown' || data.componentCounts['containerTitle'] / data.entries.length < 0.5) continue;\n      if (MONOGRAPH_TYPES.has(type)) hasMonograph = true; else hasSerial = true;\n    }\n    const ctIdx = consensusOrdering.indexOf('containerTitle');\n    if (hasSerial && hasMonograph) consensusOrdering.splice(ctIdx, 1, 'containerTitleMonograph', 'containerTitleSerial');\n    else if (hasMonograph) consensusOrdering[ctIdx] = 'containerTitleMonograph';\n  }\n\n  const isVolumeIssueGrouped = detectVolumeIssueGrouping(rendered.entries, refByEntry);\n  const prefixes = {};\n  for (const name of consensusOrdering) {\n    const patterns = detectPrefixPatterns(name, rendered.entries, refByEntry);\n    if (patterns.globalWinner || Object.keys(patterns.overrides).length > 0) prefixes[name] = patterns;\n  }\n\n  const wrapPatterns = {};\n  for (const name of ['issue', 'pages', 'year', 'volume']) {\n    const patterns = detectWrapPatterns(name, rendered.entries, refByEntry);\n    if (patterns.globalWinner || Object.keys(patterns.overrides).length > 0) wrapPatterns[name] = patterns;\n  }\n\n  const nameOrderPatterns = {};\n  const etAlSettings = {};\n  for (const [name, role] of Object.entries({ contributors: 'author', editors: 'editor' })) {\n    nameOrderPatterns[name] = detectNameOrderPatterns(name, role, rendered.entries, refByEntry);\n    const etAl = detectEtAl(name, rendered.entries, refByEntry, rendered.entries);\n    if (etAl) etAlSettings[name] = etAl;\n  }\n\n  let template = [];\n  let skipIssue = false;\n  for (const componentName of consensusOrdering) {\n    if (componentName === 'issue' && skipIssue) continue;\n    const parserName = componentName.startsWith('containerTitle') ? 'containerTitle' : componentName;\n    const entryIdx = rendered.entries.findIndex((e, i) => parseComponents(e, refByEntry[i])[parserName]?.found);\n    if (entryIdx < 0) continue;\n\n    if (componentName === 'volume' && isVolumeIssueGrouped && consensusOrdering.includes('issue')) {\n      const issueComp = { number: 'issue' };\n      const ip = wrapPatterns['issue'];\n      if (ip?.globalWinner) issueComp.wrap = ip.globalWinner;\n      if (ip?.overrides) {\n        issueComp.overrides = {};\n        for (const [t, w] of Object.entries(ip.overrides)) issueComp.overrides[t] = { wrap: w };\n      }\n      template.push({ items: [{ number: 'volume' }, issueComp], _componentName: 'volume' });\n      skipIssue = true;\n      continue;\n    }\n\n    const yamlComp = mapComponentToYaml(componentName, rendered.entries[entryIdx], refByEntry[entryIdx]);\n    if (yamlComp) {\n      const p = prefixes[componentName] || prefixes[parserName];\n      if (p?.globalWinner) {\n        const normalizedPrefix = normalizeLocalizedPageLabelPrefix(yamlComp, p.globalWinner);\n        if (normalizedPrefix.localized) yamlComp['label-form'] = 'short';\n        if (normalizedPrefix.prefix) yamlComp.prefix = normalizedPrefix.prefix;\n      }\n      if (p?.overrides) {\n        yamlComp.overrides = yamlComp.overrides || {};\n        for (const [t, pfx] of Object.entries(p.overrides)) {\n          const override = yamlComp.overrides[t] = yamlComp.overrides[t] || {};\n          const normalizedPrefix = normalizeLocalizedPageLabelPrefix(yamlComp, pfx);\n          if (normalizedPrefix.localized) override['label-form'] = 'short';\n          if (normalizedPrefix.prefix) override.prefix = normalizedPrefix.prefix;\n        }\n      }\n      const w = wrapPatterns[componentName];\n      if (w?.globalWinner && !yamlComp.wrap) yamlComp.wrap = w.globalWinner;\n      if (w?.overrides) {\n        yamlComp.overrides = yamlComp.overrides || {};\n        for (const [t, wr] of Object.entries(w.overrides)) (yamlComp.overrides[t] = yamlComp.overrides[t] || {}).wrap = wr;\n      }\n      const fmt = detectFormatting(parserName, rendered.entries, refByEntry);\n      if (fmt) Object.assign(yamlComp, fmt);\n\n      yamlComp._componentName = componentName;\n      if (nameOrderPatterns[parserName]?.globalWinner) yamlComp['name-order'] = nameOrderPatterns[parserName].globalWinner;\n      if (etAlSettings[parserName]) {\n        yamlComp.shorten = {\n          min: etAlSettings[parserName].min,\n          'use-first': etAlSettings[parserName].use_first\n        };\n      }\n\n      template.push(yamlComp);\n    }\n  }\n\n  const suppressions = detectSuppressions(consensusOrdering, typedComponents, componentFrequency, rendered, refByEntry);\n  let delimiterConsensus = '. ';\n  let delimiterSupport = 0.5;\n  {\n    const skipPairs = new Set(['contributors', 'year', 'editors']), delimCounts = {};\n    for (let i = 0; i < rendered.entries.length; i++) {\n      for (const det of detectDelimiters(rendered.entries[i], refByEntry[i])) {\n        if (skipPairs.has(det.between[0]) || skipPairs.has(det.between[1])) continue;\n        const d = det.delimiter.replace(/[\"\\u201c\\u201d]+/g, '');\n        if (d.length >= 1 && d.length <= 4 && /^[.,;: ]+$/.test(d)) delimCounts[d] = (delimCounts[d] || 0) + 1;\n      }\n    }\n    const best = Object.entries(delimCounts).sort((a, b) => b[1] - a[1]);\n    const totalDetections = Object.values(delimCounts).reduce((sum, n) => sum + n, 0);\n    if (best.length > 0) {\n      delimiterConsensus = best[0][0];\n      delimiterSupport = totalDetections > 0 ? best[0][1] / totalDetections : 0.5;\n    }\n  }\n\n  let entrySuffix = null;\n  const suffixCounts = {};\n  for (const text of rendered.entries) {\n    const match = text.replace(/<[^>]+>/g, '').trim().match(/([.,;:]+)$/);\n    if (match) suffixCounts[match[1]] = (suffixCounts[match[1]] || 0) + 1;\n  }\n  const bestSuffix = Object.entries(suffixCounts).sort((a, b) => b[1] - a[1]);\n  if (bestSuffix.length > 0 && bestSuffix[0][1] / rendered.entries.length >= 0.7) entrySuffix = bestSuffix[0][0];\n\n  for (let i = 1; i < template.length; i++) {\n    for (let j = i - 1; j >= Math.max(0, i - 4); j--) {\n      const pairDelim = findDelimiterConsensus(rendered.entries, refByEntry, template[j]._componentName || 'volume', template[i]._componentName, (j === i - 1 ? 0 : 0.2));\n      if (pairDelim && pairDelim !== delimiterConsensus) {\n        template[i].prefix = pairDelim;\n        break;\n      }\n    }\n  }\n\n  template = applyContainerGrouping(template);\n\n  let citationWrap = null;\n  if (section === 'citation') {\n    let parenCount = 0, bracketCount = 0;\n    for (const text of rendered.entries) {\n      const norm = normalizeText(text);\n      if (norm.startsWith('(') && norm.endsWith(')')) parenCount++;\n      else if (norm.startsWith('[') && norm.endsWith(']')) bracketCount++;\n    }\n    if (parenCount / rendered.entries.length >= 0.8) citationWrap = 'parentheses';\n    else if (bracketCount / rendered.entries.length >= 0.8) citationWrap = 'brackets';\n  }\n\n  for (const comp of template) {\n    if (comp._componentName && suppressions[comp._componentName]) {\n      for (const t of Object.keys(suppressions[comp._componentName])) (comp.overrides = comp.overrides || {})[t] = { suppress: true };\n    }\n    if (comp.items && suppressions.issue) {\n      const issue = comp.items.find(it => it.number === 'issue');\n      if (issue) for (const t of Object.keys(suppressions.issue)) (issue.overrides = issue.overrides || {})[t] = { suppress: true };\n    }\n    delete comp._componentName;\n  }\n\n  const confidence = computeInferenceConfidence({\n    section,\n    template,\n    renderedEntries: rendered.entries,\n    refByEntry,\n    typedComponents,\n    orderingAgreementByType,\n    componentFrequency,\n    consensusOrdering,\n    delimiterSupport,\n  });\n\n  if (section === 'citation') {\n    const integral = inferTemplateFromInputs({\n      styleXml,\n      section: 'citation-integral',\n      testItems,\n      localeXml,\n    });\n    const non_integral = inferTemplateFromInputs({\n      styleXml,\n      section: 'citation-non-integral',\n      testItems,\n      localeXml,\n    });\n\n    if (integral || non_integral) {\n      const baseJson = JSON.stringify(template);\n      const result = {\n        template,\n        meta: {\n          delimiterConsensus,\n          entrySuffix,\n          typesAnalyzed: Object.keys(typedComponents),\n          entryCount: rendered.entries.length,\n          confidence,\n          section,\n          wrap: citationWrap\n        }\n      };\n\n      if (integral && JSON.stringify(integral.template) !== baseJson) {\n        result.integral = { template: integral.template };\n      }\n      if (non_integral && JSON.stringify(non_integral.template) !== baseJson) {\n        result.non_integral = { template: non_integral.template };\n      }\n      return result;\n    }\n  }\n\n  return {\n    template,\n    yaml: generateYaml(template, delimiterConsensus, citationWrap),\n    meta: {\n      delimiterConsensus,\n      entrySuffix,\n      typesAnalyzed: Object.keys(typedComponents),\n      entryCount: rendered.entries.length,\n      confidence,\n      section,\n      wrap: citationWrap\n    }\n  };\n}\n\nfunction applyContainerGrouping(template) {\n  const containerTypes = ['editors', 'containerTitleMonograph'], newTemplate = [];\n  for (let i = 0; i < template.length; i++) {\n    const comp = template[i];\n    if (containerTypes.includes(comp._componentName)) {\n      let j = i + 1;\n      while (j < template.length && containerTypes.includes(template[j]._componentName)) j++;\n      if (j > i + 1) {\n        const groupItems = template.slice(i, j);\n        const group = { items: groupItems.map(c => { const { _componentName, ...rest } = c; return rest; }), _componentName: 'containerGroup' };\n        if (groupItems[0].prefix) { group.prefix = groupItems[0].prefix; delete group.items[0].prefix; }\n        if (group.items[1].prefix) { group.delimiter = group.items[1].prefix; delete group.items[1].prefix; }\n        newTemplate.push(group); i = j - 1; continue;\n      }\n    }\n    newTemplate.push(comp);\n  }\n  return newTemplate;\n}\n\nfunction buildFragmentOutput(result, section, styleName = 'unknown') {\n  if (!result) return null;\n\n  const fragment = {\n    meta: {\n      style: styleName,\n      confidence: result.meta?.confidence,\n      delimiter: result.meta?.delimiterConsensus,\n      entrySuffix: result.meta?.entrySuffix,\n      wrap: result.meta?.wrap,\n    },\n  };\n\n  fragment[section] = { template: result.template };\n  if (result.integral) fragment[section].integral = result.integral;\n  if (result.non_integral) fragment[section].non_integral = result.non_integral;\n\n  return fragment;\n}\n\nfunction inferTemplateFragment(inputs) {\n  const result = inferTemplateFromInputs(inputs);\n  return buildFragmentOutput(result, inputs.section || 'bibliography', inputs.styleName);\n}\n\nmodule.exports = {\n  buildFragmentOutput,\n  inferTemplateFromInputs,\n  inferTemplateFragment,\n  renderWithCiteproc,\n  renderCitations,\n  aggregateByType,\n  findConsensusOrdering,\n  findDelimiterConsensus,\n  detectSuppressions,\n  detectPrefixPatterns,\n  normalizeLocalizedPageLabelPrefix,\n  detectWrapPatterns,\n  detectVolumeIssueGrouping,\n  detectFormatting,\n  mapComponentToYaml,\n  generateYaml,\n  detectNameOrder,\n  detectNameOrderPatterns,\n};\n"
};
  const MODULE_CACHE = Object.create(null);

  function __require(id) {
    if (Object.prototype.hasOwnProperty.call(MODULE_CACHE, id)) {
      return MODULE_CACHE[id].exports;
    }
    if (!Object.prototype.hasOwnProperty.call(MODULE_SOURCES, id)) {
      throw new Error('Unknown embedded module: ' + id);
    }

    const module = { exports: {} };
    MODULE_CACHE[id] = module;
    const factory = new Function('module', 'exports', 'require', MODULE_SOURCES[id]);
    factory(module, module.exports, __require);
    return module.exports;
  }

  const core = __require('./template-inferrer-core');

  globalThis.infer_template_fragment = function inferTemplateFragment(input) {
    const args = typeof input === 'string' ? JSON.parse(input) : input;
    const fragment = core.inferTemplateFragment(args);
    return fragment === null ? null : JSON.stringify(fragment);
  };
}());
