require=(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
(function (global){(function (){
global.mapshaper = require('mapshaper');

}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"mapshaper":31}],2:[function(require,module,exports){
'use strict';

var GetIntrinsic = require('get-intrinsic');

var callBind = require('./');

var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf'));

module.exports = function callBoundIntrinsic(name, allowMissing) {
	var intrinsic = GetIntrinsic(name, !!allowMissing);
	if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
		return callBind(intrinsic);
	}
	return intrinsic;
};

},{"./":3,"get-intrinsic":6}],3:[function(require,module,exports){
'use strict';

var bind = require('function-bind');
var GetIntrinsic = require('get-intrinsic');

var $apply = GetIntrinsic('%Function.prototype.apply%');
var $call = GetIntrinsic('%Function.prototype.call%');
var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);

var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true);
var $defineProperty = GetIntrinsic('%Object.defineProperty%', true);
var $max = GetIntrinsic('%Math.max%');

if ($defineProperty) {
	try {
		$defineProperty({}, 'a', { value: 1 });
	} catch (e) {
		// IE 8 has a broken defineProperty
		$defineProperty = null;
	}
}

module.exports = function callBind(originalFunction) {
	var func = $reflectApply(bind, $call, arguments);
	if ($gOPD && $defineProperty) {
		var desc = $gOPD(func, 'length');
		if (desc.configurable) {
			// original length, plus the receiver, minus any additional arguments (after the receiver)
			$defineProperty(
				func,
				'length',
				{ value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) }
			);
		}
	}
	return func;
};

var applyBind = function applyBind() {
	return $reflectApply(bind, $apply, arguments);
};

if ($defineProperty) {
	$defineProperty(module.exports, 'apply', { value: applyBind });
} else {
	module.exports.apply = applyBind;
}

},{"function-bind":5,"get-intrinsic":6}],4:[function(require,module,exports){
'use strict';

/* eslint no-invalid-this: 1 */

var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var slice = Array.prototype.slice;
var toStr = Object.prototype.toString;
var funcType = '[object Function]';

module.exports = function bind(that) {
    var target = this;
    if (typeof target !== 'function' || toStr.call(target) !== funcType) {
        throw new TypeError(ERROR_MESSAGE + target);
    }
    var args = slice.call(arguments, 1);

    var bound;
    var binder = function () {
        if (this instanceof bound) {
            var result = target.apply(
                this,
                args.concat(slice.call(arguments))
            );
            if (Object(result) === result) {
                return result;
            }
            return this;
        } else {
            return target.apply(
                that,
                args.concat(slice.call(arguments))
            );
        }
    };

    var boundLength = Math.max(0, target.length - args.length);
    var boundArgs = [];
    for (var i = 0; i < boundLength; i++) {
        boundArgs.push('$' + i);
    }

    bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);

    if (target.prototype) {
        var Empty = function Empty() {};
        Empty.prototype = target.prototype;
        bound.prototype = new Empty();
        Empty.prototype = null;
    }

    return bound;
};

},{}],5:[function(require,module,exports){
'use strict';

var implementation = require('./implementation');

module.exports = Function.prototype.bind || implementation;

},{"./implementation":4}],6:[function(require,module,exports){
'use strict';

var undefined;

var $SyntaxError = SyntaxError;
var $Function = Function;
var $TypeError = TypeError;

// eslint-disable-next-line consistent-return
var getEvalledConstructor = function (expressionSyntax) {
	try {
		return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
	} catch (e) {}
};

var $gOPD = Object.getOwnPropertyDescriptor;
if ($gOPD) {
	try {
		$gOPD({}, '');
	} catch (e) {
		$gOPD = null; // this is IE 8, which has a broken gOPD
	}
}

var throwTypeError = function () {
	throw new $TypeError();
};
var ThrowTypeError = $gOPD
	? (function () {
		try {
			// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
			arguments.callee; // IE 8 does not throw here
			return throwTypeError;
		} catch (calleeThrows) {
			try {
				// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
				return $gOPD(arguments, 'callee').get;
			} catch (gOPDthrows) {
				return throwTypeError;
			}
		}
	}())
	: throwTypeError;

var hasSymbols = require('has-symbols')();

var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto

var needsEval = {};

var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array);

var INTRINSICS = {
	'%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,
	'%Array%': Array,
	'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
	'%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined,
	'%AsyncFromSyncIteratorPrototype%': undefined,
	'%AsyncFunction%': needsEval,
	'%AsyncGenerator%': needsEval,
	'%AsyncGeneratorFunction%': needsEval,
	'%AsyncIteratorPrototype%': needsEval,
	'%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
	'%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,
	'%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array,
	'%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array,
	'%Boolean%': Boolean,
	'%DataView%': typeof DataView === 'undefined' ? undefined : DataView,
	'%Date%': Date,
	'%decodeURI%': decodeURI,
	'%decodeURIComponent%': decodeURIComponent,
	'%encodeURI%': encodeURI,
	'%encodeURIComponent%': encodeURIComponent,
	'%Error%': Error,
	'%eval%': eval, // eslint-disable-line no-eval
	'%EvalError%': EvalError,
	'%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
	'%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
	'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,
	'%Function%': $Function,
	'%GeneratorFunction%': needsEval,
	'%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
	'%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
	'%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
	'%isFinite%': isFinite,
	'%isNaN%': isNaN,
	'%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined,
	'%JSON%': typeof JSON === 'object' ? JSON : undefined,
	'%Map%': typeof Map === 'undefined' ? undefined : Map,
	'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()),
	'%Math%': Math,
	'%Number%': Number,
	'%Object%': Object,
	'%parseFloat%': parseFloat,
	'%parseInt%': parseInt,
	'%Promise%': typeof Promise === 'undefined' ? undefined : Promise,
	'%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
	'%RangeError%': RangeError,
	'%ReferenceError%': ReferenceError,
	'%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
	'%RegExp%': RegExp,
	'%Set%': typeof Set === 'undefined' ? undefined : Set,
	'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()),
	'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
	'%String%': String,
	'%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined,
	'%Symbol%': hasSymbols ? Symbol : undefined,
	'%SyntaxError%': $SyntaxError,
	'%ThrowTypeError%': ThrowTypeError,
	'%TypedArray%': TypedArray,
	'%TypeError%': $TypeError,
	'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
	'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
	'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
	'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
	'%URIError%': URIError,
	'%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
	'%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,
	'%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet
};

try {
	null.error; // eslint-disable-line no-unused-expressions
} catch (e) {
	// https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229
	var errorProto = getProto(getProto(e));
	INTRINSICS['%Error.prototype%'] = errorProto;
}

var doEval = function doEval(name) {
	var value;
	if (name === '%AsyncFunction%') {
		value = getEvalledConstructor('async function () {}');
	} else if (name === '%GeneratorFunction%') {
		value = getEvalledConstructor('function* () {}');
	} else if (name === '%AsyncGeneratorFunction%') {
		value = getEvalledConstructor('async function* () {}');
	} else if (name === '%AsyncGenerator%') {
		var fn = doEval('%AsyncGeneratorFunction%');
		if (fn) {
			value = fn.prototype;
		}
	} else if (name === '%AsyncIteratorPrototype%') {
		var gen = doEval('%AsyncGenerator%');
		if (gen) {
			value = getProto(gen.prototype);
		}
	}

	INTRINSICS[name] = value;

	return value;
};

var LEGACY_ALIASES = {
	'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
	'%ArrayPrototype%': ['Array', 'prototype'],
	'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
	'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
	'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
	'%ArrayProto_values%': ['Array', 'prototype', 'values'],
	'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
	'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
	'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
	'%BooleanPrototype%': ['Boolean', 'prototype'],
	'%DataViewPrototype%': ['DataView', 'prototype'],
	'%DatePrototype%': ['Date', 'prototype'],
	'%ErrorPrototype%': ['Error', 'prototype'],
	'%EvalErrorPrototype%': ['EvalError', 'prototype'],
	'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
	'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
	'%FunctionPrototype%': ['Function', 'prototype'],
	'%Generator%': ['GeneratorFunction', 'prototype'],
	'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
	'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
	'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
	'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
	'%JSONParse%': ['JSON', 'parse'],
	'%JSONStringify%': ['JSON', 'stringify'],
	'%MapPrototype%': ['Map', 'prototype'],
	'%NumberPrototype%': ['Number', 'prototype'],
	'%ObjectPrototype%': ['Object', 'prototype'],
	'%ObjProto_toString%': ['Object', 'prototype', 'toString'],
	'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
	'%PromisePrototype%': ['Promise', 'prototype'],
	'%PromiseProto_then%': ['Promise', 'prototype', 'then'],
	'%Promise_all%': ['Promise', 'all'],
	'%Promise_reject%': ['Promise', 'reject'],
	'%Promise_resolve%': ['Promise', 'resolve'],
	'%RangeErrorPrototype%': ['RangeError', 'prototype'],
	'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
	'%RegExpPrototype%': ['RegExp', 'prototype'],
	'%SetPrototype%': ['Set', 'prototype'],
	'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
	'%StringPrototype%': ['String', 'prototype'],
	'%SymbolPrototype%': ['Symbol', 'prototype'],
	'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
	'%TypedArrayPrototype%': ['TypedArray', 'prototype'],
	'%TypeErrorPrototype%': ['TypeError', 'prototype'],
	'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
	'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
	'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
	'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
	'%URIErrorPrototype%': ['URIError', 'prototype'],
	'%WeakMapPrototype%': ['WeakMap', 'prototype'],
	'%WeakSetPrototype%': ['WeakSet', 'prototype']
};

var bind = require('function-bind');
var hasOwn = require('has');
var $concat = bind.call(Function.call, Array.prototype.concat);
var $spliceApply = bind.call(Function.apply, Array.prototype.splice);
var $replace = bind.call(Function.call, String.prototype.replace);
var $strSlice = bind.call(Function.call, String.prototype.slice);
var $exec = bind.call(Function.call, RegExp.prototype.exec);

/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
var stringToPath = function stringToPath(string) {
	var first = $strSlice(string, 0, 1);
	var last = $strSlice(string, -1);
	if (first === '%' && last !== '%') {
		throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
	} else if (last === '%' && first !== '%') {
		throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
	}
	var result = [];
	$replace(string, rePropName, function (match, number, quote, subString) {
		result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
	});
	return result;
};
/* end adaptation */

var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
	var intrinsicName = name;
	var alias;
	if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
		alias = LEGACY_ALIASES[intrinsicName];
		intrinsicName = '%' + alias[0] + '%';
	}

	if (hasOwn(INTRINSICS, intrinsicName)) {
		var value = INTRINSICS[intrinsicName];
		if (value === needsEval) {
			value = doEval(intrinsicName);
		}
		if (typeof value === 'undefined' && !allowMissing) {
			throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
		}

		return {
			alias: alias,
			name: intrinsicName,
			value: value
		};
	}

	throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
};

module.exports = function GetIntrinsic(name, allowMissing) {
	if (typeof name !== 'string' || name.length === 0) {
		throw new $TypeError('intrinsic name must be a non-empty string');
	}
	if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
		throw new $TypeError('"allowMissing" argument must be a boolean');
	}

	if ($exec(/^%?[^%]*%?$/, name) === null) {
		throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name');
	}
	var parts = stringToPath(name);
	var intrinsicBaseName = parts.length > 0 ? parts[0] : '';

	var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
	var intrinsicRealName = intrinsic.name;
	var value = intrinsic.value;
	var skipFurtherCaching = false;

	var alias = intrinsic.alias;
	if (alias) {
		intrinsicBaseName = alias[0];
		$spliceApply(parts, $concat([0, 1], alias));
	}

	for (var i = 1, isOwn = true; i < parts.length; i += 1) {
		var part = parts[i];
		var first = $strSlice(part, 0, 1);
		var last = $strSlice(part, -1);
		if (
			(
				(first === '"' || first === "'" || first === '`')
				|| (last === '"' || last === "'" || last === '`')
			)
			&& first !== last
		) {
			throw new $SyntaxError('property names with quotes must have matching quotes');
		}
		if (part === 'constructor' || !isOwn) {
			skipFurtherCaching = true;
		}

		intrinsicBaseName += '.' + part;
		intrinsicRealName = '%' + intrinsicBaseName + '%';

		if (hasOwn(INTRINSICS, intrinsicRealName)) {
			value = INTRINSICS[intrinsicRealName];
		} else if (value != null) {
			if (!(part in value)) {
				if (!allowMissing) {
					throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
				}
				return void undefined;
			}
			if ($gOPD && (i + 1) >= parts.length) {
				var desc = $gOPD(value, part);
				isOwn = !!desc;

				// By convention, when a data property is converted to an accessor
				// property to emulate a data property that does not suffer from
				// the override mistake, that accessor's getter is marked with
				// an `originalValue` property. Here, when we detect this, we
				// uphold the illusion by pretending to see that original data
				// property, i.e., returning the value rather than the getter
				// itself.
				if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
					value = desc.get;
				} else {
					value = value[part];
				}
			} else {
				isOwn = hasOwn(value, part);
				value = value[part];
			}

			if (isOwn && !skipFurtherCaching) {
				INTRINSICS[intrinsicRealName] = value;
			}
		}
	}
	return value;
};

},{"function-bind":5,"has":9,"has-symbols":7}],7:[function(require,module,exports){
'use strict';

var origSymbol = typeof Symbol !== 'undefined' && Symbol;
var hasSymbolSham = require('./shams');

module.exports = function hasNativeSymbols() {
	if (typeof origSymbol !== 'function') { return false; }
	if (typeof Symbol !== 'function') { return false; }
	if (typeof origSymbol('foo') !== 'symbol') { return false; }
	if (typeof Symbol('bar') !== 'symbol') { return false; }

	return hasSymbolSham();
};

},{"./shams":8}],8:[function(require,module,exports){
'use strict';

/* eslint complexity: [2, 18], max-statements: [2, 33] */
module.exports = function hasSymbols() {
	if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
	if (typeof Symbol.iterator === 'symbol') { return true; }

	var obj = {};
	var sym = Symbol('test');
	var symObj = Object(sym);
	if (typeof sym === 'string') { return false; }

	if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
	if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }

	// temp disabled per https://github.com/ljharb/object.assign/issues/17
	// if (sym instanceof Symbol) { return false; }
	// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
	// if (!(symObj instanceof Symbol)) { return false; }

	// if (typeof Symbol.prototype.toString !== 'function') { return false; }
	// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }

	var symVal = 42;
	obj[sym] = symVal;
	for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
	if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }

	if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }

	var syms = Object.getOwnPropertySymbols(obj);
	if (syms.length !== 1 || syms[0] !== sym) { return false; }

	if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }

	if (typeof Object.getOwnPropertyDescriptor === 'function') {
		var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
		if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
	}

	return true;
};

},{}],9:[function(require,module,exports){
'use strict';

var bind = require('function-bind');

module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty);

},{"function-bind":5}],10:[function(require,module,exports){
"use strict";
/**
 * A response from a web request
 */
var Response = /** @class */ (function () {
    function Response(statusCode, headers, body, url) {
        if (typeof statusCode !== 'number') {
            throw new TypeError('statusCode must be a number but was ' + typeof statusCode);
        }
        if (headers === null) {
            throw new TypeError('headers cannot be null');
        }
        if (typeof headers !== 'object') {
            throw new TypeError('headers must be an object but was ' + typeof headers);
        }
        this.statusCode = statusCode;
        var headersToLowerCase = {};
        for (var key in headers) {
            headersToLowerCase[key.toLowerCase()] = headers[key];
        }
        this.headers = headersToLowerCase;
        this.body = body;
        this.url = url;
    }
    Response.prototype.isError = function () {
        return this.statusCode === 0 || this.statusCode >= 400;
    };
    Response.prototype.getBody = function (encoding) {
        if (this.statusCode === 0) {
            var err = new Error('This request to ' +
                this.url +
                ' resulted in a status code of 0. This usually indicates some kind of network error in a browser (e.g. CORS not being set up or the DNS failing to resolve):\n' +
                this.body.toString());
            err.statusCode = this.statusCode;
            err.headers = this.headers;
            err.body = this.body;
            err.url = this.url;
            throw err;
        }
        if (this.statusCode >= 300) {
            var err = new Error('Server responded to ' +
                this.url +
                ' with status code ' +
                this.statusCode +
                ':\n' +
                this.body.toString());
            err.statusCode = this.statusCode;
            err.headers = this.headers;
            err.body = this.body;
            err.url = this.url;
            throw err;
        }
        if (!encoding || typeof this.body === 'string') {
            return this.body;
        }
        return this.body.toString(encoding);
    };
    return Response;
}());
module.exports = Response;

},{}],11:[function(require,module,exports){
"use strict";
var Buffer = require("safer-buffer").Buffer;

// Multibyte codec. In this scheme, a character is represented by 1 or more bytes.
// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences.
// To save memory and loading time, we read table files only when requested.

exports._dbcs = DBCSCodec;

var UNASSIGNED = -1,
    GB18030_CODE = -2,
    SEQ_START  = -10,
    NODE_START = -1000,
    UNASSIGNED_NODE = new Array(0x100),
    DEF_CHAR = -1;

for (var i = 0; i < 0x100; i++)
    UNASSIGNED_NODE[i] = UNASSIGNED;


// Class DBCSCodec reads and initializes mapping tables.
function DBCSCodec(codecOptions, iconv) {
    this.encodingName = codecOptions.encodingName;
    if (!codecOptions)
        throw new Error("DBCS codec is called without the data.")
    if (!codecOptions.table)
        throw new Error("Encoding '" + this.encodingName + "' has no data.");

    // Load tables.
    var mappingTable = codecOptions.table();


    // Decode tables: MBCS -> Unicode.

    // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256.
    // Trie root is decodeTables[0].
    // Values: >=  0 -> unicode character code. can be > 0xFFFF
    //         == UNASSIGNED -> unknown/unassigned sequence.
    //         == GB18030_CODE -> this is the end of a GB18030 4-byte sequence.
    //         <= NODE_START -> index of the next node in our trie to process next byte.
    //         <= SEQ_START  -> index of the start of a character code sequence, in decodeTableSeq.
    this.decodeTables = [];
    this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node.

    // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. 
    this.decodeTableSeq = [];

    // Actual mapping tables consist of chunks. Use them to fill up decode tables.
    for (var i = 0; i < mappingTable.length; i++)
        this._addDecodeChunk(mappingTable[i]);

    // Load & create GB18030 tables when needed.
    if (typeof codecOptions.gb18030 === 'function') {
        this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges.

        // Add GB18030 common decode nodes.
        var commonThirdByteNodeIdx = this.decodeTables.length;
        this.decodeTables.push(UNASSIGNED_NODE.slice(0));

        var commonFourthByteNodeIdx = this.decodeTables.length;
        this.decodeTables.push(UNASSIGNED_NODE.slice(0));

        // Fill out the tree
        var firstByteNode = this.decodeTables[0];
        for (var i = 0x81; i <= 0xFE; i++) {
            var secondByteNode = this.decodeTables[NODE_START - firstByteNode[i]];
            for (var j = 0x30; j <= 0x39; j++) {
                if (secondByteNode[j] === UNASSIGNED) {
                    secondByteNode[j] = NODE_START - commonThirdByteNodeIdx;
                } else if (secondByteNode[j] > NODE_START) {
                    throw new Error("gb18030 decode tables conflict at byte 2");
                }

                var thirdByteNode = this.decodeTables[NODE_START - secondByteNode[j]];
                for (var k = 0x81; k <= 0xFE; k++) {
                    if (thirdByteNode[k] === UNASSIGNED) {
                        thirdByteNode[k] = NODE_START - commonFourthByteNodeIdx;
                    } else if (thirdByteNode[k] === NODE_START - commonFourthByteNodeIdx) {
                        continue;
                    } else if (thirdByteNode[k] > NODE_START) {
                        throw new Error("gb18030 decode tables conflict at byte 3");
                    }

                    var fourthByteNode = this.decodeTables[NODE_START - thirdByteNode[k]];
                    for (var l = 0x30; l <= 0x39; l++) {
                        if (fourthByteNode[l] === UNASSIGNED)
                            fourthByteNode[l] = GB18030_CODE;
                    }
                }
            }
        }
    }

    this.defaultCharUnicode = iconv.defaultCharUnicode;

    
    // Encode tables: Unicode -> DBCS.

    // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance.
    // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null.
    // Values: >=  0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.).
    //         == UNASSIGNED -> no conversion found. Output a default char.
    //         <= SEQ_START  -> it's an index in encodeTableSeq, see below. The character starts a sequence.
    this.encodeTable = [];
    
    // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of
    // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key
    // means end of sequence (needed when one sequence is a strict subsequence of another).
    // Objects are kept separately from encodeTable to increase performance.
    this.encodeTableSeq = [];

    // Some chars can be decoded, but need not be encoded.
    var skipEncodeChars = {};
    if (codecOptions.encodeSkipVals)
        for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) {
            var val = codecOptions.encodeSkipVals[i];
            if (typeof val === 'number')
                skipEncodeChars[val] = true;
            else
                for (var j = val.from; j <= val.to; j++)
                    skipEncodeChars[j] = true;
        }
        
    // Use decode trie to recursively fill out encode tables.
    this._fillEncodeTable(0, 0, skipEncodeChars);

    // Add more encoding pairs when needed.
    if (codecOptions.encodeAdd) {
        for (var uChar in codecOptions.encodeAdd)
            if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar))
                this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]);
    }

    this.defCharSB  = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)];
    if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?'];
    if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0);
}

DBCSCodec.prototype.encoder = DBCSEncoder;
DBCSCodec.prototype.decoder = DBCSDecoder;

// Decoder helpers
DBCSCodec.prototype._getDecodeTrieNode = function(addr) {
    var bytes = [];
    for (; addr > 0; addr >>>= 8)
        bytes.push(addr & 0xFF);
    if (bytes.length == 0)
        bytes.push(0);

    var node = this.decodeTables[0];
    for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie.
        var val = node[bytes[i]];

        if (val == UNASSIGNED) { // Create new node.
            node[bytes[i]] = NODE_START - this.decodeTables.length;
            this.decodeTables.push(node = UNASSIGNED_NODE.slice(0));
        }
        else if (val <= NODE_START) { // Existing node.
            node = this.decodeTables[NODE_START - val];
        }
        else
            throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16));
    }
    return node;
}


DBCSCodec.prototype._addDecodeChunk = function(chunk) {
    // First element of chunk is the hex mbcs code where we start.
    var curAddr = parseInt(chunk[0], 16);

    // Choose the decoding node where we'll write our chars.
    var writeTable = this._getDecodeTrieNode(curAddr);
    curAddr = curAddr & 0xFF;

    // Write all other elements of the chunk to the table.
    for (var k = 1; k < chunk.length; k++) {
        var part = chunk[k];
        if (typeof part === "string") { // String, write as-is.
            for (var l = 0; l < part.length;) {
                var code = part.charCodeAt(l++);
                if (0xD800 <= code && code < 0xDC00) { // Decode surrogate
                    var codeTrail = part.charCodeAt(l++);
                    if (0xDC00 <= codeTrail && codeTrail < 0xE000)
                        writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00);
                    else
                        throw new Error("Incorrect surrogate pair in "  + this.encodingName + " at chunk " + chunk[0]);
                }
                else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used)
                    var len = 0xFFF - code + 2;
                    var seq = [];
                    for (var m = 0; m < len; m++)
                        seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq.

                    writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length;
                    this.decodeTableSeq.push(seq);
                }
                else
                    writeTable[curAddr++] = code; // Basic char
            }
        } 
        else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character.
            var charCode = writeTable[curAddr - 1] + 1;
            for (var l = 0; l < part; l++)
                writeTable[curAddr++] = charCode++;
        }
        else
            throw new Error("Incorrect type '" + typeof part + "' given in "  + this.encodingName + " at chunk " + chunk[0]);
    }
    if (curAddr > 0xFF)
        throw new Error("Incorrect chunk in "  + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr);
}

// Encoder helpers
DBCSCodec.prototype._getEncodeBucket = function(uCode) {
    var high = uCode >> 8; // This could be > 0xFF because of astral characters.
    if (this.encodeTable[high] === undefined)
        this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand.
    return this.encodeTable[high];
}

DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) {
    var bucket = this._getEncodeBucket(uCode);
    var low = uCode & 0xFF;
    if (bucket[low] <= SEQ_START)
        this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it.
    else if (bucket[low] == UNASSIGNED)
        bucket[low] = dbcsCode;
}

DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) {
    
    // Get the root of character tree according to first character of the sequence.
    var uCode = seq[0];
    var bucket = this._getEncodeBucket(uCode);
    var low = uCode & 0xFF;

    var node;
    if (bucket[low] <= SEQ_START) {
        // There's already a sequence with  - use it.
        node = this.encodeTableSeq[SEQ_START-bucket[low]];
    }
    else {
        // There was no sequence object - allocate a new one.
        node = {};
        if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence.
        bucket[low] = SEQ_START - this.encodeTableSeq.length;
        this.encodeTableSeq.push(node);
    }

    // Traverse the character tree, allocating new nodes as needed.
    for (var j = 1; j < seq.length-1; j++) {
        var oldVal = node[uCode];
        if (typeof oldVal === 'object')
            node = oldVal;
        else {
            node = node[uCode] = {}
            if (oldVal !== undefined)
                node[DEF_CHAR] = oldVal
        }
    }

    // Set the leaf to given dbcsCode.
    uCode = seq[seq.length-1];
    node[uCode] = dbcsCode;
}

DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) {
    var node = this.decodeTables[nodeIdx];
    var hasValues = false;
    var subNodeEmpty = {};
    for (var i = 0; i < 0x100; i++) {
        var uCode = node[i];
        var mbCode = prefix + i;
        if (skipEncodeChars[mbCode])
            continue;

        if (uCode >= 0) {
            this._setEncodeChar(uCode, mbCode);
            hasValues = true;
        } else if (uCode <= NODE_START) {
            var subNodeIdx = NODE_START - uCode;
            if (!subNodeEmpty[subNodeIdx]) {  // Skip empty subtrees (they are too large in gb18030).
                var newPrefix = (mbCode << 8) >>> 0;  // NOTE: '>>> 0' keeps 32-bit num positive.
                if (this._fillEncodeTable(subNodeIdx, newPrefix, skipEncodeChars))
                    hasValues = true;
                else
                    subNodeEmpty[subNodeIdx] = true;
            }
        } else if (uCode <= SEQ_START) {
            this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode);
            hasValues = true;
        }
    }
    return hasValues;
}



// == Encoder ==================================================================

function DBCSEncoder(options, codec) {
    // Encoder state
    this.leadSurrogate = -1;
    this.seqObj = undefined;
    
    // Static data
    this.encodeTable = codec.encodeTable;
    this.encodeTableSeq = codec.encodeTableSeq;
    this.defaultCharSingleByte = codec.defCharSB;
    this.gb18030 = codec.gb18030;
}

DBCSEncoder.prototype.write = function(str) {
    var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)),
        leadSurrogate = this.leadSurrogate,
        seqObj = this.seqObj, nextChar = -1,
        i = 0, j = 0;

    while (true) {
        // 0. Get next character.
        if (nextChar === -1) {
            if (i == str.length) break;
            var uCode = str.charCodeAt(i++);
        }
        else {
            var uCode = nextChar;
            nextChar = -1;    
        }

        // 1. Handle surrogates.
        if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates.
            if (uCode < 0xDC00) { // We've got lead surrogate.
                if (leadSurrogate === -1) {
                    leadSurrogate = uCode;
                    continue;
                } else {
                    leadSurrogate = uCode;
                    // Double lead surrogate found.
                    uCode = UNASSIGNED;
                }
            } else { // We've got trail surrogate.
                if (leadSurrogate !== -1) {
                    uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00);
                    leadSurrogate = -1;
                } else {
                    // Incomplete surrogate pair - only trail surrogate found.
                    uCode = UNASSIGNED;
                }
                
            }
        }
        else if (leadSurrogate !== -1) {
            // Incomplete surrogate pair - only lead surrogate found.
            nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char.
            leadSurrogate = -1;
        }

        // 2. Convert uCode character.
        var dbcsCode = UNASSIGNED;
        if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence
            var resCode = seqObj[uCode];
            if (typeof resCode === 'object') { // Sequence continues.
                seqObj = resCode;
                continue;

            } else if (typeof resCode == 'number') { // Sequence finished. Write it.
                dbcsCode = resCode;

            } else if (resCode == undefined) { // Current character is not part of the sequence.

                // Try default character for this sequence
                resCode = seqObj[DEF_CHAR];
                if (resCode !== undefined) {
                    dbcsCode = resCode; // Found. Write it.
                    nextChar = uCode; // Current character will be written too in the next iteration.

                } else {
                    // TODO: What if we have no default? (resCode == undefined)
                    // Then, we should write first char of the sequence as-is and try the rest recursively.
                    // Didn't do it for now because no encoding has this situation yet.
                    // Currently, just skip the sequence and write current char.
                }
            }
            seqObj = undefined;
        }
        else if (uCode >= 0) {  // Regular character
            var subtable = this.encodeTable[uCode >> 8];
            if (subtable !== undefined)
                dbcsCode = subtable[uCode & 0xFF];
            
            if (dbcsCode <= SEQ_START) { // Sequence start
                seqObj = this.encodeTableSeq[SEQ_START-dbcsCode];
                continue;
            }

            if (dbcsCode == UNASSIGNED && this.gb18030) {
                // Use GB18030 algorithm to find character(s) to write.
                var idx = findIdx(this.gb18030.uChars, uCode);
                if (idx != -1) {
                    var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]);
                    newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600;
                    newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260;
                    newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10;
                    newBuf[j++] = 0x30 + dbcsCode;
                    continue;
                }
            }
        }

        // 3. Write dbcsCode character.
        if (dbcsCode === UNASSIGNED)
            dbcsCode = this.defaultCharSingleByte;
        
        if (dbcsCode < 0x100) {
            newBuf[j++] = dbcsCode;
        }
        else if (dbcsCode < 0x10000) {
            newBuf[j++] = dbcsCode >> 8;   // high byte
            newBuf[j++] = dbcsCode & 0xFF; // low byte
        }
        else if (dbcsCode < 0x1000000) {
            newBuf[j++] = dbcsCode >> 16;
            newBuf[j++] = (dbcsCode >> 8) & 0xFF;
            newBuf[j++] = dbcsCode & 0xFF;
        } else {
            newBuf[j++] = dbcsCode >>> 24;
            newBuf[j++] = (dbcsCode >>> 16) & 0xFF;
            newBuf[j++] = (dbcsCode >>> 8) & 0xFF;
            newBuf[j++] = dbcsCode & 0xFF;
        }
    }

    this.seqObj = seqObj;
    this.leadSurrogate = leadSurrogate;
    return newBuf.slice(0, j);
}

DBCSEncoder.prototype.end = function() {
    if (this.leadSurrogate === -1 && this.seqObj === undefined)
        return; // All clean. Most often case.

    var newBuf = Buffer.alloc(10), j = 0;

    if (this.seqObj) { // We're in the sequence.
        var dbcsCode = this.seqObj[DEF_CHAR];
        if (dbcsCode !== undefined) { // Write beginning of the sequence.
            if (dbcsCode < 0x100) {
                newBuf[j++] = dbcsCode;
            }
            else {
                newBuf[j++] = dbcsCode >> 8;   // high byte
                newBuf[j++] = dbcsCode & 0xFF; // low byte
            }
        } else {
            // See todo above.
        }
        this.seqObj = undefined;
    }

    if (this.leadSurrogate !== -1) {
        // Incomplete surrogate pair - only lead surrogate found.
        newBuf[j++] = this.defaultCharSingleByte;
        this.leadSurrogate = -1;
    }
    
    return newBuf.slice(0, j);
}

// Export for testing
DBCSEncoder.prototype.findIdx = findIdx;


// == Decoder ==================================================================

function DBCSDecoder(options, codec) {
    // Decoder state
    this.nodeIdx = 0;
    this.prevBytes = [];

    // Static data
    this.decodeTables = codec.decodeTables;
    this.decodeTableSeq = codec.decodeTableSeq;
    this.defaultCharUnicode = codec.defaultCharUnicode;
    this.gb18030 = codec.gb18030;
}

DBCSDecoder.prototype.write = function(buf) {
    var newBuf = Buffer.alloc(buf.length*2),
        nodeIdx = this.nodeIdx, 
        prevBytes = this.prevBytes, prevOffset = this.prevBytes.length,
        seqStart = -this.prevBytes.length, // idx of the start of current parsed sequence.
        uCode;

    for (var i = 0, j = 0; i < buf.length; i++) {
        var curByte = (i >= 0) ? buf[i] : prevBytes[i + prevOffset];

        // Lookup in current trie node.
        var uCode = this.decodeTables[nodeIdx][curByte];

        if (uCode >= 0) { 
            // Normal character, just use it.
        }
        else if (uCode === UNASSIGNED) { // Unknown char.
            // TODO: Callback with seq.
            uCode = this.defaultCharUnicode.charCodeAt(0);
            i = seqStart; // Skip one byte ('i' will be incremented by the for loop) and try to parse again.
        }
        else if (uCode === GB18030_CODE) {
            if (i >= 3) {
                var ptr = (buf[i-3]-0x81)*12600 + (buf[i-2]-0x30)*1260 + (buf[i-1]-0x81)*10 + (curByte-0x30);
            } else {
                var ptr = (prevBytes[i-3+prevOffset]-0x81)*12600 + 
                          (((i-2 >= 0) ? buf[i-2] : prevBytes[i-2+prevOffset])-0x30)*1260 + 
                          (((i-1 >= 0) ? buf[i-1] : prevBytes[i-1+prevOffset])-0x81)*10 + 
                          (curByte-0x30);
            }
            var idx = findIdx(this.gb18030.gbChars, ptr);
            uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx];
        }
        else if (uCode <= NODE_START) { // Go to next trie node.
            nodeIdx = NODE_START - uCode;
            continue;
        }
        else if (uCode <= SEQ_START) { // Output a sequence of chars.
            var seq = this.decodeTableSeq[SEQ_START - uCode];
            for (var k = 0; k < seq.length - 1; k++) {
                uCode = seq[k];
                newBuf[j++] = uCode & 0xFF;
                newBuf[j++] = uCode >> 8;
            }
            uCode = seq[seq.length-1];
        }
        else
            throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte);

        // Write the character to buffer, handling higher planes using surrogate pair.
        if (uCode >= 0x10000) { 
            uCode -= 0x10000;
            var uCodeLead = 0xD800 | (uCode >> 10);
            newBuf[j++] = uCodeLead & 0xFF;
            newBuf[j++] = uCodeLead >> 8;

            uCode = 0xDC00 | (uCode & 0x3FF);
        }
        newBuf[j++] = uCode & 0xFF;
        newBuf[j++] = uCode >> 8;

        // Reset trie node.
        nodeIdx = 0; seqStart = i+1;
    }

    this.nodeIdx = nodeIdx;
    this.prevBytes = (seqStart >= 0)
        ? Array.prototype.slice.call(buf, seqStart)
        : prevBytes.slice(seqStart + prevOffset).concat(Array.prototype.slice.call(buf));

    return newBuf.slice(0, j).toString('ucs2');
}

DBCSDecoder.prototype.end = function() {
    var ret = '';

    // Try to parse all remaining chars.
    while (this.prevBytes.length > 0) {
        // Skip 1 character in the buffer.
        ret += this.defaultCharUnicode;
        var bytesArr = this.prevBytes.slice(1);

        // Parse remaining as usual.
        this.prevBytes = [];
        this.nodeIdx = 0;
        if (bytesArr.length > 0)
            ret += this.write(bytesArr);
    }

    this.prevBytes = [];
    this.nodeIdx = 0;
    return ret;
}

// Binary search for GB18030. Returns largest i such that table[i] <= val.
function findIdx(table, val) {
    if (table[0] > val)
        return -1;

    var l = 0, r = table.length;
    while (l < r-1) { // always table[l] <= val < table[r]
        var mid = l + ((r-l+1) >> 1);
        if (table[mid] <= val)
            l = mid;
        else
            r = mid;
    }
    return l;
}


},{"safer-buffer":45}],12:[function(require,module,exports){
"use strict";

// Description of supported double byte encodings and aliases.
// Tables are not require()-d until they are needed to speed up library load.
// require()-s are direct to support Browserify.

module.exports = {
    
    // == Japanese/ShiftJIS ====================================================
    // All japanese encodings are based on JIS X set of standards:
    // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF.
    // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. 
    //              Has several variations in 1978, 1983, 1990 and 1997.
    // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead.
    // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233.
    //              2 planes, first is superset of 0208, second - revised 0212.
    //              Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx)

    // Byte encodings are:
    //  * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte
    //               encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC.
    //               Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI.
    //  * EUC-JP:    Up to 3 bytes per character. Used mostly on *nixes.
    //               0x00-0x7F       - lower part of 0201
    //               0x8E, 0xA1-0xDF - upper part of 0201
    //               (0xA1-0xFE)x2   - 0208 plane (94x94).
    //               0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94).
    //  * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon.
    //               Used as-is in ISO2022 family.
    //  * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, 
    //                0201-1976 Roman, 0208-1978, 0208-1983.
    //  * ISO2022-JP-1: Adds esc seq for 0212-1990.
    //  * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7.
    //  * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2.
    //  * ISO2022-JP-2004: Adds 0213-2004 Plane 1.
    //
    // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes.
    //
    // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html

    'shiftjis': {
        type: '_dbcs',
        table: function() { return require('./tables/shiftjis.json') },
        encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E},
        encodeSkipVals: [{from: 0xED40, to: 0xF940}],
    },
    'csshiftjis': 'shiftjis',
    'mskanji': 'shiftjis',
    'sjis': 'shiftjis',
    'windows31j': 'shiftjis',
    'ms31j': 'shiftjis',
    'xsjis': 'shiftjis',
    'windows932': 'shiftjis',
    'ms932': 'shiftjis',
    '932': 'shiftjis',
    'cp932': 'shiftjis',

    'eucjp': {
        type: '_dbcs',
        table: function() { return require('./tables/eucjp.json') },
        encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E},
    },

    // TODO: KDDI extension to Shift_JIS
    // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes.
    // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars.


    // == Chinese/GBK ==========================================================
    // http://en.wikipedia.org/wiki/GBK
    // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder

    // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936
    'gb2312': 'cp936',
    'gb231280': 'cp936',
    'gb23121980': 'cp936',
    'csgb2312': 'cp936',
    'csiso58gb231280': 'cp936',
    'euccn': 'cp936',

    // Microsoft's CP936 is a subset and approximation of GBK.
    'windows936': 'cp936',
    'ms936': 'cp936',
    '936': 'cp936',
    'cp936': {
        type: '_dbcs',
        table: function() { return require('./tables/cp936.json') },
    },

    // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other.
    'gbk': {
        type: '_dbcs',
        table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) },
    },
    'xgbk': 'gbk',
    'isoir58': 'gbk',

    // GB18030 is an algorithmic extension of GBK.
    // Main source: https://www.w3.org/TR/encoding/#gbk-encoder
    // http://icu-project.org/docs/papers/gb18030.html
    // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml
    // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0
    'gb18030': {
        type: '_dbcs',
        table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) },
        gb18030: function() { return require('./tables/gb18030-ranges.json') },
        encodeSkipVals: [0x80],
        encodeAdd: {'€': 0xA2E3},
    },

    'chinese': 'gb18030',


    // == Korean ===============================================================
    // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same.
    'windows949': 'cp949',
    'ms949': 'cp949',
    '949': 'cp949',
    'cp949': {
        type: '_dbcs',
        table: function() { return require('./tables/cp949.json') },
    },

    'cseuckr': 'cp949',
    'csksc56011987': 'cp949',
    'euckr': 'cp949',
    'isoir149': 'cp949',
    'korean': 'cp949',
    'ksc56011987': 'cp949',
    'ksc56011989': 'cp949',
    'ksc5601': 'cp949',


    // == Big5/Taiwan/Hong Kong ================================================
    // There are lots of tables for Big5 and cp950. Please see the following links for history:
    // http://moztw.org/docs/big5/  http://www.haible.de/bruno/charsets/conversion-tables/Big5.html
    // Variations, in roughly number of defined chars:
    //  * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT
    //  * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/
    //  * Big5-2003 (Taiwan standard) almost superset of cp950.
    //  * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers.
    //  * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. 
    //    many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years.
    //    Plus, it has 4 combining sequences.
    //    Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299
    //    because big5-hkscs is the only encoding to include astral characters in non-algorithmic way.
    //    Implementations are not consistent within browsers; sometimes labeled as just big5.
    //    MS Internet Explorer switches from big5 to big5-hkscs when a patch applied.
    //    Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31
    //    In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s.
    //    Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt
    //                   http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt
    // 
    // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder
    // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong.

    'windows950': 'cp950',
    'ms950': 'cp950',
    '950': 'cp950',
    'cp950': {
        type: '_dbcs',
        table: function() { return require('./tables/cp950.json') },
    },

    // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus.
    'big5': 'big5hkscs',
    'big5hkscs': {
        type: '_dbcs',
        table: function() { return require('./tables/cp950.json').concat(require('./tables/big5-added.json')) },
        encodeSkipVals: [
            // Although Encoding Standard says we should avoid encoding to HKSCS area (See Step 1 of
            // https://encoding.spec.whatwg.org/#index-big5-pointer), we still do it to increase compatibility with ICU.
            // But if a single unicode point can be encoded both as HKSCS and regular Big5, we prefer the latter.
            0x8e69, 0x8e6f, 0x8e7e, 0x8eab, 0x8eb4, 0x8ecd, 0x8ed0, 0x8f57, 0x8f69, 0x8f6e, 0x8fcb, 0x8ffe,
            0x906d, 0x907a, 0x90c4, 0x90dc, 0x90f1, 0x91bf, 0x92af, 0x92b0, 0x92b1, 0x92b2, 0x92d1, 0x9447, 0x94ca,
            0x95d9, 0x96fc, 0x9975, 0x9b76, 0x9b78, 0x9b7b, 0x9bc6, 0x9bde, 0x9bec, 0x9bf6, 0x9c42, 0x9c53, 0x9c62,
            0x9c68, 0x9c6b, 0x9c77, 0x9cbc, 0x9cbd, 0x9cd0, 0x9d57, 0x9d5a, 0x9dc4, 0x9def, 0x9dfb, 0x9ea9, 0x9eef,
            0x9efd, 0x9f60, 0x9fcb, 0xa077, 0xa0dc, 0xa0df, 0x8fcc, 0x92c8, 0x9644, 0x96ed,

            // Step 2 of https://encoding.spec.whatwg.org/#index-big5-pointer: Use last pointer for U+2550, U+255E, U+2561, U+256A, U+5341, or U+5345
            0xa2a4, 0xa2a5, 0xa2a7, 0xa2a6, 0xa2cc, 0xa2ce,
        ],
    },

    'cnbig5': 'big5hkscs',
    'csbig5': 'big5hkscs',
    'xxbig5': 'big5hkscs',
};

},{"./tables/big5-added.json":18,"./tables/cp936.json":19,"./tables/cp949.json":20,"./tables/cp950.json":21,"./tables/eucjp.json":22,"./tables/gb18030-ranges.json":23,"./tables/gbk-added.json":24,"./tables/shiftjis.json":25}],13:[function(require,module,exports){
"use strict";

// Update this array if you add/rename/remove files in this directory.
// We support Browserify by skipping automatic module discovery and requiring modules directly.
var modules = [
    require("./internal"),
    require("./utf32"),
    require("./utf16"),
    require("./utf7"),
    require("./sbcs-codec"),
    require("./sbcs-data"),
    require("./sbcs-data-generated"),
    require("./dbcs-codec"),
    require("./dbcs-data"),
];

// Put all encoding/alias/codec definitions to single object and export it.
for (var i = 0; i < modules.length; i++) {
    var module = modules[i];
    for (var enc in module)
        if (Object.prototype.hasOwnProperty.call(module, enc))
            exports[enc] = module[enc];
}

},{"./dbcs-codec":11,"./dbcs-data":12,"./internal":14,"./sbcs-codec":15,"./sbcs-data":17,"./sbcs-data-generated":16,"./utf16":26,"./utf32":27,"./utf7":28}],14:[function(require,module,exports){
"use strict";
var Buffer = require("safer-buffer").Buffer;

// Export Node.js internal encodings.

module.exports = {
    // Encodings
    utf8:   { type: "_internal", bomAware: true},
    cesu8:  { type: "_internal", bomAware: true},
    unicode11utf8: "utf8",

    ucs2:   { type: "_internal", bomAware: true},
    utf16le: "ucs2",

    binary: { type: "_internal" },
    base64: { type: "_internal" },
    hex:    { type: "_internal" },

    // Codec.
    _internal: InternalCodec,
};

//------------------------------------------------------------------------------

function InternalCodec(codecOptions, iconv) {
    this.enc = codecOptions.encodingName;
    this.bomAware = codecOptions.bomAware;

    if (this.enc === "base64")
        this.encoder = InternalEncoderBase64;
    else if (this.enc === "cesu8") {
        this.enc = "utf8"; // Use utf8 for decoding.
        this.encoder = InternalEncoderCesu8;

        // Add decoder for versions of Node not supporting CESU-8
        if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') {
            this.decoder = InternalDecoderCesu8;
            this.defaultCharUnicode = iconv.defaultCharUnicode;
        }
    }
}

InternalCodec.prototype.encoder = InternalEncoder;
InternalCodec.prototype.decoder = InternalDecoder;

//------------------------------------------------------------------------------

// We use node.js internal decoder. Its signature is the same as ours.
var StringDecoder = require('string_decoder').StringDecoder;

if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method.
    StringDecoder.prototype.end = function() {};


function InternalDecoder(options, codec) {
    this.decoder = new StringDecoder(codec.enc);
}

InternalDecoder.prototype.write = function(buf) {
    if (!Buffer.isBuffer(buf)) {
        buf = Buffer.from(buf);
    }

    return this.decoder.write(buf);
}

InternalDecoder.prototype.end = function() {
    return this.decoder.end();
}


//------------------------------------------------------------------------------
// Encoder is mostly trivial

function InternalEncoder(options, codec) {
    this.enc = codec.enc;
}

InternalEncoder.prototype.write = function(str) {
    return Buffer.from(str, this.enc);
}

InternalEncoder.prototype.end = function() {
}


//------------------------------------------------------------------------------
// Except base64 encoder, which must keep its state.

function InternalEncoderBase64(options, codec) {
    this.prevStr = '';
}

InternalEncoderBase64.prototype.write = function(str) {
    str = this.prevStr + str;
    var completeQuads = str.length - (str.length % 4);
    this.prevStr = str.slice(completeQuads);
    str = str.slice(0, completeQuads);

    return Buffer.from(str, "base64");
}

InternalEncoderBase64.prototype.end = function() {
    return Buffer.from(this.prevStr, "base64");
}


//------------------------------------------------------------------------------
// CESU-8 encoder is also special.

function InternalEncoderCesu8(options, codec) {
}

InternalEncoderCesu8.prototype.write = function(str) {
    var buf = Buffer.alloc(str.length * 3), bufIdx = 0;
    for (var i = 0; i < str.length; i++) {
        var charCode = str.charCodeAt(i);
        // Naive implementation, but it works because CESU-8 is especially easy
        // to convert from UTF-16 (which all JS strings are encoded in).
        if (charCode < 0x80)
            buf[bufIdx++] = charCode;
        else if (charCode < 0x800) {
            buf[bufIdx++] = 0xC0 + (charCode >>> 6);
            buf[bufIdx++] = 0x80 + (charCode & 0x3f);
        }
        else { // charCode will always be < 0x10000 in javascript.
            buf[bufIdx++] = 0xE0 + (charCode >>> 12);
            buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f);
            buf[bufIdx++] = 0x80 + (charCode & 0x3f);
        }
    }
    return buf.slice(0, bufIdx);
}

InternalEncoderCesu8.prototype.end = function() {
}

//------------------------------------------------------------------------------
// CESU-8 decoder is not implemented in Node v4.0+

function InternalDecoderCesu8(options, codec) {
    this.acc = 0;
    this.contBytes = 0;
    this.accBytes = 0;
    this.defaultCharUnicode = codec.defaultCharUnicode;
}

InternalDecoderCesu8.prototype.write = function(buf) {
    var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, 
        res = '';
    for (var i = 0; i < buf.length; i++) {
        var curByte = buf[i];
        if ((curByte & 0xC0) !== 0x80) { // Leading byte
            if (contBytes > 0) { // Previous code is invalid
                res += this.defaultCharUnicode;
                contBytes = 0;
            }

            if (curByte < 0x80) { // Single-byte code
                res += String.fromCharCode(curByte);
            } else if (curByte < 0xE0) { // Two-byte code
                acc = curByte & 0x1F;
                contBytes = 1; accBytes = 1;
            } else if (curByte < 0xF0) { // Three-byte code
                acc = curByte & 0x0F;
                contBytes = 2; accBytes = 1;
            } else { // Four or more are not supported for CESU-8.
                res += this.defaultCharUnicode;
            }
        } else { // Continuation byte
            if (contBytes > 0) { // We're waiting for it.
                acc = (acc << 6) | (curByte & 0x3f);
                contBytes--; accBytes++;
                if (contBytes === 0) {
                    // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80)
                    if (accBytes === 2 && acc < 0x80 && acc > 0)
                        res += this.defaultCharUnicode;
                    else if (accBytes === 3 && acc < 0x800)
                        res += this.defaultCharUnicode;
                    else
                        // Actually add character.
                        res += String.fromCharCode(acc);
                }
            } else { // Unexpected continuation byte
                res += this.defaultCharUnicode;
            }
        }
    }
    this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes;
    return res;
}

InternalDecoderCesu8.prototype.end = function() {
    var res = 0;
    if (this.contBytes > 0)
        res += this.defaultCharUnicode;
    return res;
}

},{"safer-buffer":45,"string_decoder":104}],15:[function(require,module,exports){
"use strict";
var Buffer = require("safer-buffer").Buffer;

// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that
// correspond to encoded bytes (if 128 - then lower half is ASCII). 

exports._sbcs = SBCSCodec;
function SBCSCodec(codecOptions, iconv) {
    if (!codecOptions)
        throw new Error("SBCS codec is called without the data.")
    
    // Prepare char buffer for decoding.
    if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256))
        throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)");
    
    if (codecOptions.chars.length === 128) {
        var asciiString = "";
        for (var i = 0; i < 128; i++)
            asciiString += String.fromCharCode(i);
        codecOptions.chars = asciiString + codecOptions.chars;
    }

    this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2');
    
    // Encoding buffer.
    var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0));

    for (var i = 0; i < codecOptions.chars.length; i++)
        encodeBuf[codecOptions.chars.charCodeAt(i)] = i;

    this.encodeBuf = encodeBuf;
}

SBCSCodec.prototype.encoder = SBCSEncoder;
SBCSCodec.prototype.decoder = SBCSDecoder;


function SBCSEncoder(options, codec) {
    this.encodeBuf = codec.encodeBuf;
}

SBCSEncoder.prototype.write = function(str) {
    var buf = Buffer.alloc(str.length);
    for (var i = 0; i < str.length; i++)
        buf[i] = this.encodeBuf[str.charCodeAt(i)];
    
    return buf;
}

SBCSEncoder.prototype.end = function() {
}


function SBCSDecoder(options, codec) {
    this.decodeBuf = codec.decodeBuf;
}

SBCSDecoder.prototype.write = function(buf) {
    // Strings are immutable in JS -> we use ucs2 buffer to speed up computations.
    var decodeBuf = this.decodeBuf;
    var newBuf = Buffer.alloc(buf.length*2);
    var idx1 = 0, idx2 = 0;
    for (var i = 0; i < buf.length; i++) {
        idx1 = buf[i]*2; idx2 = i*2;
        newBuf[idx2] = decodeBuf[idx1];
        newBuf[idx2+1] = decodeBuf[idx1+1];
    }
    return newBuf.toString('ucs2');
}

SBCSDecoder.prototype.end = function() {
}

},{"safer-buffer":45}],16:[function(require,module,exports){
"use strict";

// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script.
module.exports = {
  "437": "cp437",
  "737": "cp737",
  "775": "cp775",
  "850": "cp850",
  "852": "cp852",
  "855": "cp855",
  "856": "cp856",
  "857": "cp857",
  "858": "cp858",
  "860": "cp860",
  "861": "cp861",
  "862": "cp862",
  "863": "cp863",
  "864": "cp864",
  "865": "cp865",
  "866": "cp866",
  "869": "cp869",
  "874": "windows874",
  "922": "cp922",
  "1046": "cp1046",
  "1124": "cp1124",
  "1125": "cp1125",
  "1129": "cp1129",
  "1133": "cp1133",
  "1161": "cp1161",
  "1162": "cp1162",
  "1163": "cp1163",
  "1250": "windows1250",
  "1251": "windows1251",
  "1252": "windows1252",
  "1253": "windows1253",
  "1254": "windows1254",
  "1255": "windows1255",
  "1256": "windows1256",
  "1257": "windows1257",
  "1258": "windows1258",
  "28591": "iso88591",
  "28592": "iso88592",
  "28593": "iso88593",
  "28594": "iso88594",
  "28595": "iso88595",
  "28596": "iso88596",
  "28597": "iso88597",
  "28598": "iso88598",
  "28599": "iso88599",
  "28600": "iso885910",
  "28601": "iso885911",
  "28603": "iso885913",
  "28604": "iso885914",
  "28605": "iso885915",
  "28606": "iso885916",
  "windows874": {
    "type": "_sbcs",
    "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
  },
  "win874": "windows874",
  "cp874": "windows874",
  "windows1250": {
    "type": "_sbcs",
    "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙"
  },
  "win1250": "windows1250",
  "cp1250": "windows1250",
  "windows1251": {
    "type": "_sbcs",
    "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"
  },
  "win1251": "windows1251",
  "cp1251": "windows1251",
  "windows1252": {
    "type": "_sbcs",
    "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
  },
  "win1252": "windows1252",
  "cp1252": "windows1252",
  "windows1253": {
    "type": "_sbcs",
    "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�"
  },
  "win1253": "windows1253",
  "cp1253": "windows1253",
  "windows1254": {
    "type": "_sbcs",
    "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ"
  },
  "win1254": "windows1254",
  "cp1254": "windows1254",
  "windows1255": {
    "type": "_sbcs",
    "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�"
  },
  "win1255": "windows1255",
  "cp1255": "windows1255",
  "windows1256": {
    "type": "_sbcs",
    "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے"
  },
  "win1256": "windows1256",
  "cp1256": "windows1256",
  "windows1257": {
    "type": "_sbcs",
    "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙"
  },
  "win1257": "windows1257",
  "cp1257": "windows1257",
  "windows1258": {
    "type": "_sbcs",
    "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"
  },
  "win1258": "windows1258",
  "cp1258": "windows1258",
  "iso88591": {
    "type": "_sbcs",
    "chars": " ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
  },
  "cp28591": "iso88591",
  "iso88592": {
    "type": "_sbcs",
    "chars": " Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙"
  },
  "cp28592": "iso88592",
  "iso88593": {
    "type": "_sbcs",
    "chars": " Ħ˘£¤�Ĥ§¨İŞĞĴ­�Ż°ħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙"
  },
  "cp28593": "iso88593",
  "iso88594": {
    "type": "_sbcs",
    "chars": " ĄĸŖ¤ĨĻ§¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩļˇ¸šēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖ×ØŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙"
  },
  "cp28594": "iso88594",
  "iso88595": {
    "type": "_sbcs",
    "chars": " ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ"
  },
  "cp28595": "iso88595",
  "iso88596": {
    "type": "_sbcs",
    "chars": " ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������"
  },
  "cp28596": "iso88596",
  "iso88597": {
    "type": "_sbcs",
    "chars": " ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�"
  },
  "cp28597": "iso88597",
  "iso88598": {
    "type": "_sbcs",
    "chars": " �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�"
  },
  "cp28598": "iso88598",
  "iso88599": {
    "type": "_sbcs",
    "chars": " ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ"
  },
  "cp28599": "iso88599",
  "iso885910": {
    "type": "_sbcs",
    "chars": " ĄĒĢĪĨĶ§ĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ"
  },
  "cp28600": "iso885910",
  "iso885911": {
    "type": "_sbcs",
    "chars": " กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
  },
  "cp28601": "iso885911",
  "iso885913": {
    "type": "_sbcs",
    "chars": " ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’"
  },
  "cp28603": "iso885913",
  "iso885914": {
    "type": "_sbcs",
    "chars": " Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ"
  },
  "cp28604": "iso885914",
  "iso885915": {
    "type": "_sbcs",
    "chars": " ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
  },
  "cp28605": "iso885915",
  "iso885916": {
    "type": "_sbcs",
    "chars": " ĄąŁ€„Š§š©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ"
  },
  "cp28606": "iso885916",
  "cp437": {
    "type": "_sbcs",
    "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñÑªº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
  },
  "ibm437": "cp437",
  "csibm437": "cp437",
  "cp737": {
    "type": "_sbcs",
    "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ "
  },
  "ibm737": "cp737",
  "csibm737": "cp737",
  "cp775": {
    "type": "_sbcs",
    "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£Ø×¤ĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ "
  },
  "ibm775": "cp775",
  "csibm775": "cp775",
  "cp850": {
    "type": "_sbcs",
    "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñÑªº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýÝ¯´­±‗¾¶§÷¸°¨·¹³²■ "
  },
  "ibm850": "cp850",
  "csibm850": "cp850",
  "cp852": {
    "type": "_sbcs",
    "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘę¬źČş«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ "
  },
  "ibm852": "cp852",
  "csibm852": "cp852",
  "cp855": {
    "type": "_sbcs",
    "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ "
  },
  "ibm855": "cp855",
  "csibm855": "cp855",
  "cp856": {
    "type": "_sbcs",
    "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ "
  },
  "ibm856": "cp856",
  "csibm856": "cp856",
  "cp857": {
    "type": "_sbcs",
    "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞğ¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ "
  },
  "ibm857": "cp857",
  "csibm857": "cp857",
  "cp858": {
    "type": "_sbcs",
    "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñÑªº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýÝ¯´­±‗¾¶§÷¸°¨·¹³²■ "
  },
  "ibm858": "cp858",
  "csibm858": "cp858",
  "cp860": {
    "type": "_sbcs",
    "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñÑªº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
  },
  "ibm860": "cp860",
  "csibm860": "cp860",
  "cp861": {
    "type": "_sbcs",
    "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
  },
  "ibm861": "cp861",
  "csibm861": "cp861",
  "cp862": {
    "type": "_sbcs",
    "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñÑªº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
  },
  "ibm862": "cp862",
  "csibm862": "cp862",
  "cp863": {
    "type": "_sbcs",
    "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
  },
  "ibm863": "cp863",
  "csibm863": "cp863",
  "cp864": {
    "type": "_sbcs",
    "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�"
  },
  "ibm864": "cp864",
  "csibm864": "cp864",
  "cp865": {
    "type": "_sbcs",
    "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñÑªº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
  },
  "ibm865": "cp865",
  "csibm865": "cp865",
  "cp866": {
    "type": "_sbcs",
    "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ "
  },
  "ibm866": "cp866",
  "csibm866": "cp866",
  "cp869": {
    "type": "_sbcs",
    "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ "
  },
  "ibm869": "cp869",
  "csibm869": "cp869",
  "cp922": {
    "type": "_sbcs",
    "chars": " ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖ×ØÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ"
  },
  "ibm922": "cp922",
  "csibm922": "cp922",
  "cp1046": {
    "type": "_sbcs",
    "chars": "ﺈ×÷ﹱ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�"
  },
  "ibm1046": "cp1046",
  "csibm1046": "cp1046",
  "cp1124": {
    "type": "_sbcs",
    "chars": " ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ"
  },
  "ibm1124": "cp1124",
  "csibm1124": "cp1124",
  "cp1125": {
    "type": "_sbcs",
    "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ "
  },
  "ibm1125": "cp1125",
  "csibm1125": "cp1125",
  "cp1129": {
    "type": "_sbcs",
    "chars": " ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"
  },
  "ibm1129": "cp1129",
  "csibm1129": "cp1129",
  "cp1133": {
    "type": "_sbcs",
    "chars": " ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�"
  },
  "ibm1133": "cp1133",
  "csibm1133": "cp1133",
  "cp1161": {
    "type": "_sbcs",
    "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ "
  },
  "ibm1161": "cp1161",
  "csibm1161": "cp1161",
  "cp1162": {
    "type": "_sbcs",
    "chars": "€…‘’“”•–— กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
  },
  "ibm1162": "cp1162",
  "csibm1162": "cp1162",
  "cp1163": {
    "type": "_sbcs",
    "chars": " ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"
  },
  "ibm1163": "cp1163",
  "csibm1163": "cp1163",
  "maccroatian": {
    "type": "_sbcs",
    "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ"
  },
  "maccyrillic": {
    "type": "_sbcs",
    "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤"
  },
  "macgreek": {
    "type": "_sbcs",
    "chars": "Ä¹²É³ÖÜ΅àâä΄¨çéèêë£™îï•½‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�"
  },
  "maciceland": {
    "type": "_sbcs",
    "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
  },
  "macroman": {
    "type": "_sbcs",
    "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›ﬁﬂ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
  },
  "macromania": {
    "type": "_sbcs",
    "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
  },
  "macthai": {
    "type": "_sbcs",
    "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู﻿​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����"
  },
  "macturkish": {
    "type": "_sbcs",
    "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ"
  },
  "macukraine": {
    "type": "_sbcs",
    "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤"
  },
  "koi8r": {
    "type": "_sbcs",
    "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
  },
  "koi8u": {
    "type": "_sbcs",
    "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
  },
  "koi8ru": {
    "type": "_sbcs",
    "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
  },
  "koi8t": {
    "type": "_sbcs",
    "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
  },
  "armscii8": {
    "type": "_sbcs",
    "chars": " �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�"
  },
  "rk1048": {
    "type": "_sbcs",
    "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"
  },
  "tcvn": {
    "type": "_sbcs",
    "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ"
  },
  "georgianacademy": {
    "type": "_sbcs",
    "chars": "‚ƒ„…†‡ˆ‰Š‹Œ‘’“”•–—˜™š›œŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
  },
  "georgianps": {
    "type": "_sbcs",
    "chars": "‚ƒ„…†‡ˆ‰Š‹Œ‘’“”•–—˜™š›œŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
  },
  "pt154": {
    "type": "_sbcs",
    "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"
  },
  "viscii": {
    "type": "_sbcs",
    "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ"
  },
  "iso646cn": {
    "type": "_sbcs",
    "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������"
  },
  "iso646jp": {
    "type": "_sbcs",
    "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������"
  },
  "hproman8": {
    "type": "_sbcs",
    "chars": " ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�"
  },
  "macintosh": {
    "type": "_sbcs",
    "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›ﬁﬂ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
  },
  "ascii": {
    "type": "_sbcs",
    "chars": "��������������������������������������������������������������������������������������������������������������������������������"
  },
  "tis620": {
    "type": "_sbcs",
    "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
  }
}
},{}],17:[function(require,module,exports){
"use strict";

// Manually added data to be used by sbcs codec in addition to generated one.

module.exports = {
    // Not supported by iconv, not sure why.
    "10029": "maccenteuro",
    "maccenteuro": {
        "type": "_sbcs",
        "chars": "ÄĀāÉĄÖÜáąČäčĆćéŹźĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņŃ¬√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ"
    },

    "808": "cp808",
    "ibm808": "cp808",
    "cp808": {
        "type": "_sbcs",
        "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ "
    },

    "mik": {
        "type": "_sbcs",
        "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
    },

    "cp720": {
        "type": "_sbcs",
        "chars": "\x80\x81éâ\x84à\x86çêëèïî\x8d\x8e\x8f\x90\u0651\u0652ô¤ـûùءآأؤ£إئابةتثجحخدذرزسشص«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ضطظعغفµقكلمنهوىي≡\u064b\u064c\u064d\u064e\u064f\u0650≈°∙·√ⁿ²■\u00a0"
    },

    // Aliases of generated encodings.
    "ascii8bit": "ascii",
    "usascii": "ascii",
    "ansix34": "ascii",
    "ansix341968": "ascii",
    "ansix341986": "ascii",
    "csascii": "ascii",
    "cp367": "ascii",
    "ibm367": "ascii",
    "isoir6": "ascii",
    "iso646us": "ascii",
    "iso646irv": "ascii",
    "us": "ascii",

    "latin1": "iso88591",
    "latin2": "iso88592",
    "latin3": "iso88593",
    "latin4": "iso88594",
    "latin5": "iso88599",
    "latin6": "iso885910",
    "latin7": "iso885913",
    "latin8": "iso885914",
    "latin9": "iso885915",
    "latin10": "iso885916",

    "csisolatin1": "iso88591",
    "csisolatin2": "iso88592",
    "csisolatin3": "iso88593",
    "csisolatin4": "iso88594",
    "csisolatincyrillic": "iso88595",
    "csisolatinarabic": "iso88596",
    "csisolatingreek" : "iso88597",
    "csisolatinhebrew": "iso88598",
    "csisolatin5": "iso88599",
    "csisolatin6": "iso885910",

    "l1": "iso88591",
    "l2": "iso88592",
    "l3": "iso88593",
    "l4": "iso88594",
    "l5": "iso88599",
    "l6": "iso885910",
    "l7": "iso885913",
    "l8": "iso885914",
    "l9": "iso885915",
    "l10": "iso885916",

    "isoir14": "iso646jp",
    "isoir57": "iso646cn",
    "isoir100": "iso88591",
    "isoir101": "iso88592",
    "isoir109": "iso88593",
    "isoir110": "iso88594",
    "isoir144": "iso88595",
    "isoir127": "iso88596",
    "isoir126": "iso88597",
    "isoir138": "iso88598",
    "isoir148": "iso88599",
    "isoir157": "iso885910",
    "isoir166": "tis620",
    "isoir179": "iso885913",
    "isoir199": "iso885914",
    "isoir203": "iso885915",
    "isoir226": "iso885916",

    "cp819": "iso88591",
    "ibm819": "iso88591",

    "cyrillic": "iso88595",

    "arabic": "iso88596",
    "arabic8": "iso88596",
    "ecma114": "iso88596",
    "asmo708": "iso88596",

    "greek" : "iso88597",
    "greek8" : "iso88597",
    "ecma118" : "iso88597",
    "elot928" : "iso88597",

    "hebrew": "iso88598",
    "hebrew8": "iso88598",

    "turkish": "iso88599",
    "turkish8": "iso88599",

    "thai": "iso885911",
    "thai8": "iso885911",

    "celtic": "iso885914",
    "celtic8": "iso885914",
    "isoceltic": "iso885914",

    "tis6200": "tis620",
    "tis62025291": "tis620",
    "tis62025330": "tis620",

    "10000": "macroman",
    "10006": "macgreek",
    "10007": "maccyrillic",
    "10079": "maciceland",
    "10081": "macturkish",

    "cspc8codepage437": "cp437",
    "cspc775baltic": "cp775",
    "cspc850multilingual": "cp850",
    "cspcp852": "cp852",
    "cspc862latinhebrew": "cp862",
    "cpgr": "cp869",

    "msee": "cp1250",
    "mscyrl": "cp1251",
    "msansi": "cp1252",
    "msgreek": "cp1253",
    "msturk": "cp1254",
    "mshebr": "cp1255",
    "msarab": "cp1256",
    "winbaltrim": "cp1257",

    "cp20866": "koi8r",
    "20866": "koi8r",
    "ibm878": "koi8r",
    "cskoi8r": "koi8r",

    "cp21866": "koi8u",
    "21866": "koi8u",
    "ibm1168": "koi8u",

    "strk10482002": "rk1048",

    "tcvn5712": "tcvn",
    "tcvn57121": "tcvn",

    "gb198880": "iso646cn",
    "cn": "iso646cn",

    "csiso14jisc6220ro": "iso646jp",
    "jisc62201969ro": "iso646jp",
    "jp": "iso646jp",

    "cshproman8": "hproman8",
    "r8": "hproman8",
    "roman8": "hproman8",
    "xroman8": "hproman8",
    "ibm1051": "hproman8",

    "mac": "macintosh",
    "csmacintosh": "macintosh",
};


},{}],18:[function(require,module,exports){
module.exports=[
["8740","䏰䰲䘃䖦䕸𧉧䵷䖳𧲱䳢𧳅㮕䜶䝄䱇䱀𤊿𣘗𧍒𦺋𧃒䱗𪍑䝏䗚䲅𧱬䴇䪤䚡𦬣爥𥩔𡩣𣸆𣽡晍囻"],
["8767","綕夝𨮹㷴霴𧯯寛𡵞媤㘥𩺰嫑宷峼杮薓𩥅瑡璝㡵𡵓𣚞𦀡㻬"],
["87a1","𥣞㫵竼龗𤅡𨤍𣇪𠪊𣉞䌊蒄龖鐯䤰蘓墖靊鈘秐稲晠権袝瑌篅枂稬剏遆㓦珄𥶹瓆鿇垳䤯呌䄱𣚎堘穲𧭥讏䚮𦺈䆁𥶙箮𢒼鿈𢓁𢓉𢓌鿉蔄𣖻䂴鿊䓡𪷿拁灮鿋"],
["8840","㇀",4,"𠄌㇅𠃑𠃍㇆㇇𠃋𡿨㇈𠃊㇉㇊㇋㇌𠄎㇍㇎ĀÁǍÀĒÉĚÈŌÓǑÒ࿿Ê̄Ế࿿Ê̌ỀÊāáǎàɑēéěèīíǐìōóǒòūúǔùǖǘǚ"],
["88a1","ǜü࿿ê̄ế࿿ê̌ềêɡ⏚⏛"],
["8940","𪎩𡅅"],
["8943","攊"],
["8946","丽滝鵎釟"],
["894c","𧜵撑会伨侨兖兴农凤务动医华发变团声处备夲头学实実岚庆总斉柾栄桥济炼电纤纬纺织经统缆缷艺苏药视设询车轧轮"],
["89a1","琑糼緍楆竉刧"],
["89ab","醌碸酞肼"],
["89b0","贋胶𠧧"],
["89b5","肟黇䳍鷉鸌䰾𩷶𧀎鸊𪄳㗁"],
["89c1","溚舾甙"],
["89c5","䤑马骏龙禇𨑬𡷊𠗐𢫦两亁亀亇亿仫伷㑌侽㹈倃傈㑽㒓㒥円夅凛凼刅争剹劐匧㗇厩㕑厰㕓参吣㕭㕲㚁咓咣咴咹哐哯唘唣唨㖘唿㖥㖿嗗㗅"],
["8a40","𧶄唥"],
["8a43","𠱂𠴕𥄫喐𢳆㧬𠍁蹆𤶸𩓥䁓𨂾睺𢰸㨴䟕𨅝𦧲𤷪擝𠵼𠾴𠳕𡃴撍蹾𠺖𠰋𠽤𢲩𨉖𤓓"],
["8a64","𠵆𩩍𨃩䟴𤺧𢳂骲㩧𩗴㿭㔆𥋇𩟔𧣈𢵄鵮頕"],
["8a76","䏙𦂥撴哣𢵌𢯊𡁷㧻𡁯"],
["8aa1","𦛚𦜖𧦠擪𥁒𠱃蹨𢆡𨭌𠜱"],
["8aac","䠋𠆩㿺塳𢶍"],
["8ab2","𤗈𠓼𦂗𠽌𠶖啹䂻䎺"],
["8abb","䪴𢩦𡂝膪飵𠶜捹㧾𢝵跀嚡摼㹃"],
["8ac9","𪘁𠸉𢫏𢳉"],
["8ace","𡃈𣧂㦒㨆𨊛㕸𥹉𢃇噒𠼱𢲲𩜠㒼氽𤸻"],
["8adf","𧕴𢺋𢈈𪙛𨳍𠹺𠰴𦠜羓𡃏𢠃𢤹㗻𥇣𠺌𠾍𠺪㾓𠼰𠵇𡅏𠹌"],
["8af6","𠺫𠮩𠵈𡃀𡄽㿹𢚖搲𠾭"],
["8b40","𣏴𧘹𢯎𠵾𠵿𢱑𢱕㨘𠺘𡃇𠼮𪘲𦭐𨳒𨶙𨳊閪哌苄喹"],
["8b55","𩻃鰦骶𧝞𢷮煀腭胬尜𦕲脴㞗卟𨂽醶𠻺𠸏𠹷𠻻㗝𤷫㘉𠳖嚯𢞵𡃉𠸐𠹸𡁸𡅈𨈇𡑕𠹹𤹐𢶤婔𡀝𡀞𡃵𡃶垜𠸑"],
["8ba1","𧚔𨋍𠾵𠹻𥅾㜃𠾶𡆀𥋘𪊽𤧚𡠺𤅷𨉼墙剨㘚𥜽箲孨䠀䬬鼧䧧鰟鮍𥭴𣄽嗻㗲嚉丨夂𡯁屮靑𠂆乛亻㔾尣彑忄㣺扌攵歺氵氺灬爫丬犭𤣩罒礻糹罓𦉪㓁"],
["8bde","𦍋耂肀𦘒𦥑卝衤见𧢲讠贝钅镸长门𨸏韦页风飞饣𩠐鱼鸟黄歯龜丷𠂇阝户钢"],
["8c40","倻淾𩱳龦㷉袏𤅎灷峵䬠𥇍㕙𥴰愢𨨲辧釶熑朙玺𣊁𪄇㲋𡦀䬐磤琂冮𨜏䀉橣𪊺䈣蘏𠩯稪𩥇𨫪靕灍匤𢁾鏴盙𨧣龧矝亣俰傼丯众龨吴綋墒壐𡶶庒庙忂𢜒斋"],
["8ca1","𣏹椙橃𣱣泿"],
["8ca7","爀𤔅玌㻛𤨓嬕璹讃𥲤𥚕窓篬糃繬苸薗龩袐龪躹龫迏蕟駠鈡龬𨶹𡐿䁱䊢娚"],
["8cc9","顨杫䉶圽"],
["8cce","藖𤥻芿𧄍䲁𦵴嵻𦬕𦾾龭龮宖龯曧繛湗秊㶈䓃𣉖𢞖䎚䔶"],
["8ce6","峕𣬚諹屸㴒𣕑嵸龲煗䕘𤃬𡸣䱷㥸㑊𠆤𦱁諌侴𠈹妿腬顖𩣺弻"],
["8d40","𠮟"],
["8d42","𢇁𨥭䄂䚻𩁹㼇龳𪆵䃸㟖䛷𦱆䅼𨚲𧏿䕭㣔𥒚䕡䔛䶉䱻䵶䗪㿈𤬏㙡䓞䒽䇭崾嵈嵖㷼㠏嶤嶹㠠㠸幂庽弥徃㤈㤔㤿㥍惗愽峥㦉憷憹懏㦸戬抐拥挘㧸嚱"],
["8da1","㨃揢揻搇摚㩋擀崕嘡龟㪗斆㪽旿晓㫲暒㬢朖㭂枤栀㭘桊梄㭲㭱㭻椉楃牜楤榟榅㮼槖㯝橥橴橱檂㯬檙㯲檫檵櫔櫶殁毁毪汵沪㳋洂洆洦涁㳯涤涱渕渘温溆𨧀溻滢滚齿滨滩漤漴㵆𣽁澁澾㵪㵵熷岙㶊瀬㶑灐灔灯灿炉𠌥䏁㗱𠻘"],
["8e40","𣻗垾𦻓焾𥟠㙎榢𨯩孴穉𥣡𩓙穥穽𥦬窻窰竂竃燑𦒍䇊竚竝竪䇯咲𥰁笋筕笩𥌎𥳾箢筯莜𥮴𦱿篐萡箒箸𥴠㶭𥱥蒒篺簆簵𥳁籄粃𤢂粦晽𤕸糉糇糦籴糳糵糎"],
["8ea1","繧䔝𦹄絝𦻖璍綉綫焵綳緒𤁗𦀩緤㴓緵𡟹緥𨍭縝𦄡𦅚繮纒䌫鑬縧罀罁罇礶𦋐駡羗𦍑羣𡙡𠁨䕜𣝦䔃𨌺翺𦒉者耈耝耨耯𪂇𦳃耻耼聡𢜔䦉𦘦𣷣𦛨朥肧𨩈脇脚墰𢛶汿𦒘𤾸擧𡒊舘𡡞橓𤩥𤪕䑺舩𠬍𦩒𣵾俹𡓽蓢荢𦬊𤦧𣔰𡝳𣷸芪椛芳䇛"],
["8f40","蕋苐茚𠸖𡞴㛁𣅽𣕚艻苢茘𣺋𦶣𦬅𦮗𣗎㶿茝嗬莅䔋𦶥莬菁菓㑾𦻔橗蕚㒖𦹂𢻯葘𥯤葱㷓䓤檧葊𣲵祘蒨𦮖𦹷𦹃蓞萏莑䒠蒓蓤𥲑䉀𥳀䕃蔴嫲𦺙䔧蕳䔖枿蘖"],
["8fa1","𨘥𨘻藁𧂈蘂𡖂𧃍䕫䕪蘨㙈𡢢号𧎚虾蝱𪃸蟮𢰧螱蟚蠏噡虬桖䘏衅衆𧗠𣶹𧗤衞袜䙛袴袵揁装睷𧜏覇覊覦覩覧覼𨨥觧𧤤𧪽誜瞓釾誐𧩙竩𧬺𣾏䜓𧬸煼謌謟𥐰𥕥謿譌譍誩𤩺讐讛誯𡛟䘕衏貛𧵔𧶏貫㜥𧵓賖𧶘𧶽贒贃𡤐賛灜贑𤳉㻐起"],
["9040","趩𨀂𡀔𤦊㭼𨆼𧄌竧躭躶軃鋔輙輭𨍥𨐒辥錃𪊟𠩐辳䤪𨧞𨔽𣶻廸𣉢迹𪀔𨚼𨔁𢌥㦀𦻗逷𨔼𧪾遡𨕬𨘋邨𨜓郄𨛦邮都酧㫰醩釄粬𨤳𡺉鈎沟鉁鉢𥖹銹𨫆𣲛𨬌𥗛"],
["90a1","𠴱錬鍫𨫡𨯫炏嫃𨫢𨫥䥥鉄𨯬𨰹𨯿鍳鑛躼閅閦鐦閠濶䊹𢙺𨛘𡉼𣸮䧟氜陻隖䅬隣𦻕懚隶磵𨫠隽双䦡𦲸𠉴𦐐𩂯𩃥𤫑𡤕𣌊霱虂霶䨏䔽䖅𤫩灵孁霛靜𩇕靗孊𩇫靟鐥僐𣂷𣂼鞉鞟鞱鞾韀韒韠𥑬韮琜𩐳響韵𩐝𧥺䫑頴頳顋顦㬎𧅵㵑𠘰𤅜"],
["9140","𥜆飊颷飈飇䫿𦴧𡛓喰飡飦飬鍸餹𤨩䭲𩡗𩤅駵騌騻騐驘𥜥㛄𩂱𩯕髠髢𩬅髴䰎鬔鬭𨘀倴鬴𦦨㣃𣁽魐魀𩴾婅𡡣鮎𤉋鰂鯿鰌𩹨鷔𩾷𪆒𪆫𪃡𪄣𪇟鵾鶃𪄴鸎梈"],
["91a1","鷄𢅛𪆓𪈠𡤻𪈳鴹𪂹𪊴麐麕麞麢䴴麪麯𤍤黁㭠㧥㴝伲㞾𨰫鼂鼈䮖鐤𦶢鼗鼖鼹嚟嚊齅馸𩂋韲葿齢齩竜龎爖䮾𤥵𤦻煷𤧸𤍈𤩑玞𨯚𡣺禟𨥾𨸶鍩鏳𨩄鋬鎁鏋𨥬𤒹爗㻫睲穃烐𤑳𤏸煾𡟯炣𡢾𣖙㻇𡢅𥐯𡟸㜢𡛻𡠹㛡𡝴𡣑𥽋㜣𡛀坛𤨥𡏾𡊨"],
["9240","𡏆𡒶蔃𣚦蔃葕𤦔𧅥𣸱𥕜𣻻𧁒䓴𣛮𩦝𦼦柹㜳㰕㷧塬𡤢栐䁗𣜿𤃡𤂋𤄏𦰡哋嚞𦚱嚒𠿟𠮨𠸍鏆𨬓鎜仸儫㠙𤐶亼𠑥𠍿佋侊𥙑婨𠆫𠏋㦙𠌊𠐔㐵伩𠋀𨺳𠉵諚𠈌亘"],
["92a1","働儍侢伃𤨎𣺊佂倮偬傁俌俥偘僼兙兛兝兞湶𣖕𣸹𣺿浲𡢄𣺉冨凃𠗠䓝𠒣𠒒𠒑赺𨪜𠜎剙劤𠡳勡鍮䙺熌𤎌𠰠𤦬𡃤槑𠸝瑹㻞璙琔瑖玘䮎𤪼𤂍叐㖄爏𤃉喴𠍅响𠯆圝鉝雴鍦埝垍坿㘾壋媙𨩆𡛺𡝯𡜐娬妸銏婾嫏娒𥥆𡧳𡡡𤊕㛵洅瑃娡𥺃"],
["9340","媁𨯗𠐓鏠璌𡌃焅䥲鐈𨧻鎽㞠尞岞幞幈𡦖𡥼𣫮廍孏𡤃𡤄㜁𡢠㛝𡛾㛓脪𨩇𡶺𣑲𨦨弌弎𡤧𡞫婫𡜻孄蘔𧗽衠恾𢡠𢘫忛㺸𢖯𢖾𩂈𦽳懀𠀾𠁆𢘛憙憘恵𢲛𢴇𤛔𩅍"],
["93a1","摱𤙥𢭪㨩𢬢𣑐𩣪𢹸挷𪑛撶挱揑𤧣𢵧护𢲡搻敫楲㯴𣂎𣊭𤦉𣊫唍𣋠𡣙𩐿曎𣊉𣆳㫠䆐𥖄𨬢𥖏𡛼𥕛𥐥磮𣄃𡠪𣈴㑤𣈏𣆂𤋉暎𦴤晫䮓昰𧡰𡷫晣𣋒𣋡昞𥡲㣑𣠺𣞼㮙𣞢𣏾瓐㮖枏𤘪梶栞㯄檾㡣𣟕𤒇樳橒櫉欅𡤒攑梘橌㯗橺歗𣿀𣲚鎠鋲𨯪𨫋"],
["9440","銉𨀞𨧜鑧涥漋𤧬浧𣽿㶏渄𤀼娽渊塇洤硂焻𤌚𤉶烱牐犇犔𤞏𤜥兹𤪤𠗫瑺𣻸𣙟𤩊𤤗𥿡㼆㺱𤫟𨰣𣼵悧㻳瓌琼鎇琷䒟𦷪䕑疃㽣𤳙𤴆㽘畕癳𪗆㬙瑨𨫌𤦫𤦎㫻"],
["94a1","㷍𤩎㻿𤧅𤣳釺圲鍂𨫣𡡤僟𥈡𥇧睸𣈲眎眏睻𤚗𣞁㩞𤣰琸璛㺿𤪺𤫇䃈𤪖𦆮錇𥖁砞碍碈磒珐祙𧝁𥛣䄎禛蒖禥樭𣻺稺秴䅮𡛦䄲鈵秱𠵌𤦌𠊙𣶺𡝮㖗啫㕰㚪𠇔𠰍竢婙𢛵𥪯𥪜娍𠉛磰娪𥯆竾䇹籝籭䈑𥮳𥺼𥺦糍𤧹𡞰粎籼粮檲緜縇緓罎𦉡"],
["9540","𦅜𧭈綗𥺂䉪𦭵𠤖柖𠁎𣗏埄𦐒𦏸𤥢翝笧𠠬𥫩𥵃笌𥸎駦虅驣樜𣐿㧢𤧷𦖭騟𦖠蒀𧄧𦳑䓪脷䐂胆脉腂𦞴飃𦩂艢艥𦩑葓𦶧蘐𧈛媆䅿𡡀嬫𡢡嫤𡣘蚠蜨𣶏蠭𧐢娂"],
["95a1","衮佅袇袿裦襥襍𥚃襔𧞅𧞄𨯵𨯙𨮜𨧹㺭蒣䛵䛏㟲訽訜𩑈彍鈫𤊄旔焩烄𡡅鵭貟賩𧷜妚矃姰䍮㛔踪躧𤰉輰轊䋴汘澻𢌡䢛潹溋𡟚鯩㚵𤤯邻邗啱䤆醻鐄𨩋䁢𨫼鐧𨰝𨰻蓥訫閙閧閗閖𨴴瑅㻂𤣿𤩂𤏪㻧𣈥随𨻧𨹦𨹥㻌𤧭𤩸𣿮琒瑫㻼靁𩂰"],
["9640","桇䨝𩂓𥟟靝鍨𨦉𨰦𨬯𦎾銺嬑譩䤼珹𤈛鞛靱餸𠼦巁𨯅𤪲頟𩓚鋶𩗗釥䓀𨭐𤩧𨭤飜𨩅㼀鈪䤥萔餻饍𧬆㷽馛䭯馪驜𨭥𥣈檏騡嫾騯𩣱䮐𩥈馼䮽䮗鍽塲𡌂堢𤦸"],
["96a1","𡓨硄𢜟𣶸棅㵽鑘㤧慐𢞁𢥫愇鱏鱓鱻鰵鰐魿鯏𩸭鮟𪇵𪃾鴡䲮𤄄鸘䲰鴌𪆴𪃭𪃳𩤯鶥蒽𦸒𦿟𦮂藼䔳𦶤𦺄𦷰萠藮𦸀𣟗𦁤秢𣖜𣙀䤭𤧞㵢鏛銾鍈𠊿碹鉷鑍俤㑀遤𥕝砽硔碶硋𡝗𣇉𤥁㚚佲濚濙瀞瀞吔𤆵垻壳垊鴖埗焴㒯𤆬燫𦱀𤾗嬨𡞵𨩉"],
["9740","愌嫎娋䊼𤒈㜬䭻𨧼鎻鎸𡣖𠼝葲𦳀𡐓𤋺𢰦𤏁妔𣶷𦝁綨𦅛𦂤𤦹𤦋𨧺鋥珢㻩璴𨭣𡢟㻡𤪳櫘珳珻㻖𤨾𤪔𡟙𤩦𠎧𡐤𤧥瑈𤤖炥𤥶銄珦鍟𠓾錱𨫎𨨖鎆𨯧𥗕䤵𨪂煫"],
["97a1","𤥃𠳿嚤𠘚𠯫𠲸唂秄𡟺緾𡛂𤩐𡡒䔮鐁㜊𨫀𤦭妰𡢿𡢃𧒄媡㛢𣵛㚰鉟婹𨪁𡡢鍴㳍𠪴䪖㦊僴㵩㵌𡎜煵䋻𨈘渏𩃤䓫浗𧹏灧沯㳖𣿭𣸭渂漌㵯𠏵畑㚼㓈䚀㻚䡱姄鉮䤾轁𨰜𦯀堒埈㛖𡑒烾𤍢𤩱𢿣𡊰𢎽梹楧𡎘𣓥𧯴𣛟𨪃𣟖𣏺𤲟樚𣚭𦲷萾䓟䓎"],
["9840","𦴦𦵑𦲂𦿞漗𧄉茽𡜺菭𦲀𧁓𡟛妉媂𡞳婡婱𡤅𤇼㜭姯𡜼㛇熎鎐暚𤊥婮娫𤊓樫𣻹𧜶𤑛𤋊焝𤉙𨧡侰𦴨峂𤓎𧹍𤎽樌𤉖𡌄炦焳𤏩㶥泟勇𤩏繥姫崯㷳彜𤩝𡟟綤萦"],
["98a1","咅𣫺𣌀𠈔坾𠣕𠘙㿥𡾞𪊶瀃𩅛嵰玏糓𨩙𩐠俈翧狍猐𧫴猸猹𥛶獁獈㺩𧬘遬燵𤣲珡臶㻊県㻑沢国琙琞琟㻢㻰㻴㻺瓓㼎㽓畂畭畲疍㽼痈痜㿀癍㿗癴㿜発𤽜熈嘣覀塩䀝睃䀹条䁅㗛瞘䁪䁯属瞾矋売砘点砜䂨砹硇硑硦葈𥔵礳栃礲䄃"],
["9940","䄉禑禙辻稆込䅧窑䆲窼艹䇄竏竛䇏両筢筬筻簒簛䉠䉺类粜䊌粸䊔糭输烀𠳏総緔緐緽羮羴犟䎗耠耥笹耮耱联㷌垴炠肷胩䏭脌猪脎脒畠脔䐁㬹腖腙腚"],
["99a1","䐓堺腼膄䐥膓䐭膥埯臁臤艔䒏芦艶苊苘苿䒰荗险榊萅烵葤惣蒈䔄蒾蓡蓸蔐蔸蕒䔻蕯蕰藠䕷虲蚒蚲蛯际螋䘆䘗袮裿褤襇覑𧥧訩訸誔誴豑賔賲贜䞘塟跃䟭仮踺嗘坔蹱嗵躰䠷軎転軤軭軲辷迁迊迌逳駄䢭飠鈓䤞鈨鉘鉫銱銮銿"],
["9a40","鋣鋫鋳鋴鋽鍃鎄鎭䥅䥑麿鐗匁鐝鐭鐾䥪鑔鑹锭関䦧间阳䧥枠䨤靀䨵鞲韂噔䫤惨颹䬙飱塄餎餙冴餜餷饂饝饢䭰駅䮝騼鬏窃魩鮁鯝鯱鯴䱭鰠㝯𡯂鵉鰺"],
["9aa1","黾噐鶓鶽鷀鷼银辶鹻麬麱麽黆铜黢黱黸竈齄𠂔𠊷𠎠椚铃妬𠓗塀铁㞹𠗕𠘕𠙶𡚺块煳𠫂𠫍𠮿呪吆𠯋咞𠯻𠰻𠱓𠱥𠱼惧𠲍噺𠲵𠳝𠳭𠵯𠶲𠷈楕鰯螥𠸄𠸎𠻗𠾐𠼭𠹳尠𠾼帋𡁜𡁏𡁶朞𡁻𡂈𡂖㙇𡂿𡃓𡄯𡄻卤蒭𡋣𡍵𡌶讁𡕷𡘙𡟃𡟇乸炻𡠭𡥪"],
["9b40","𡨭𡩅𡰪𡱰𡲬𡻈拃𡻕𡼕熘桕𢁅槩㛈𢉼𢏗𢏺𢜪𢡱𢥏苽𢥧𢦓𢫕覥𢫨辠𢬎鞸𢬿顇骽𢱌"],
["9b62","𢲈𢲷𥯨𢴈𢴒𢶷𢶕𢹂𢽴𢿌𣀳𣁦𣌟𣏞徱晈暿𧩹𣕧𣗳爁𤦺矗𣘚𣜖纇𠍆墵朎"],
["9ba1","椘𣪧𧙗𥿢𣸑𣺹𧗾𢂚䣐䪸𤄙𨪚𤋮𤌍𤀻𤌴𤎖𤩅𠗊凒𠘑妟𡺨㮾𣳿𤐄𤓖垈𤙴㦛𤜯𨗨𩧉㝢𢇃譞𨭎駖𤠒𤣻𤨕爉𤫀𠱸奥𤺥𤾆𠝹軚𥀬劏圿煱𥊙𥐙𣽊𤪧喼𥑆𥑮𦭒釔㑳𥔿𧘲𥕞䜘𥕢𥕦𥟇𤤿𥡝偦㓻𣏌惞𥤃䝼𨥈𥪮𥮉𥰆𡶐垡煑澶𦄂𧰒遖𦆲𤾚譢𦐂𦑊"],
["9c40","嵛𦯷輶𦒄𡤜諪𤧶𦒈𣿯𦔒䯀𦖿𦚵𢜛鑥𥟡憕娧晉侻嚹𤔡𦛼乪𤤴陖涏𦲽㘘襷𦞙𦡮𦐑𦡞營𦣇筂𩃀𠨑𦤦鄄𦤹穅鷰𦧺騦𦨭㙟𦑩𠀡禃𦨴𦭛崬𣔙菏𦮝䛐𦲤画补𦶮墶"],
["9ca1","㜜𢖍𧁋𧇍㱔𧊀𧊅銁𢅺𧊋錰𧋦𤧐氹钟𧑐𠻸蠧裵𢤦𨑳𡞱溸𤨪𡠠㦤㚹尐秣䔿暶𩲭𩢤襃𧟌𧡘囖䃟𡘊㦡𣜯𨃨𡏅熭荦𧧝𩆨婧䲷𧂯𨦫𧧽𧨊𧬋𧵦𤅺筃祾𨀉澵𪋟樃𨌘厢𦸇鎿栶靝𨅯𨀣𦦵𡏭𣈯𨁈嶅𨰰𨂃圕頣𨥉嶫𤦈斾槕叒𤪥𣾁㰑朶𨂐𨃴𨄮𡾡𨅏"],
["9d40","𨆉𨆯𨈚𨌆𨌯𨎊㗊𨑨𨚪䣺揦𨥖砈鉕𨦸䏲𨧧䏟𨧨𨭆𨯔姸𨰉輋𨿅𩃬筑𩄐𩄼㷷𩅞𤫊运犏嚋𩓧𩗩𩖰𩖸𩜲𩣑𩥉𩥪𩧃𩨨𩬎𩵚𩶛纟𩻸𩼣䲤镇𪊓熢𪋿䶑递𪗋䶜𠲜达嗁"],
["9da1","辺𢒰边𤪓䔉繿潖檱仪㓤𨬬𧢝㜺躀𡟵𨀤𨭬𨮙𧨾𦚯㷫𧙕𣲷𥘵𥥖亚𥺁𦉘嚿𠹭踎孭𣺈𤲞揞拐𡟶𡡻攰嘭𥱊吚𥌑㷆𩶘䱽嘢嘞罉𥻘奵𣵀蝰东𠿪𠵉𣚺脗鵞贘瘻鱅癎瞹鍅吲腈苷嘥脲萘肽嗪祢噃吖𠺝㗎嘅嗱曱𨋢㘭甴嗰喺咗啲𠱁𠲖廐𥅈𠹶𢱢"],
["9e40","𠺢麫絚嗞𡁵抝靭咔賍燶酶揼掹揾啩𢭃鱲𢺳冚㓟𠶧冧呍唞唓癦踭𦢊疱肶蠄螆裇膶萜𡃁䓬猄𤜆宐茋𦢓噻𢛴𧴯𤆣𧵳𦻐𧊶酰𡇙鈈𣳼𪚩𠺬𠻹牦𡲢䝎𤿂𧿹𠿫䃺"],
["9ea1","鱝攟𢶠䣳𤟠𩵼𠿬𠸊恢𧖣𠿭"],
["9ead","𦁈𡆇熣纎鵐业丄㕷嬍沲卧㚬㧜卽㚥𤘘墚𤭮舭呋垪𥪕𠥹"],
["9ec5","㩒𢑥獴𩺬䴉鯭𣳾𩼰䱛𤾩𩖞𩿞葜𣶶𧊲𦞳𣜠挮紥𣻷𣸬㨪逈勌㹴㙺䗩𠒎癀嫰𠺶硺𧼮墧䂿噼鮋嵴癔𪐴麅䳡痹㟻愙𣃚𤏲"],
["9ef5","噝𡊩垧𤥣𩸆刴𧂮㖭汊鵼"],
["9f40","籖鬹埞𡝬屓擓𩓐𦌵𧅤蚭𠴨𦴢𤫢𠵱"],
["9f4f","凾𡼏嶎霃𡷑麁遌笟鬂峑箣扨挵髿篏鬪籾鬮籂粆鰕篼鬉鼗鰛𤤾齚啳寃俽麘俲剠㸆勑坧偖妷帒韈鶫轜呩鞴饀鞺匬愰"],
["9fa1","椬叚鰊鴂䰻陁榀傦畆𡝭駚剳"],
["9fae","酙隁酜"],
["9fb2","酑𨺗捿𦴣櫊嘑醎畺抅𠏼獏籰𥰡𣳽"],
["9fc1","𤤙盖鮝个𠳔莾衂"],
["9fc9","届槀僭坺刟巵从氱𠇲伹咜哚劚趂㗾弌㗳"],
["9fdb","歒酼龥鮗頮颴骺麨麄煺笔"],
["9fe7","毺蠘罸"],
["9feb","嘠𪙊蹷齓"],
["9ff0","跔蹏鸜踁抂𨍽踨蹵竓𤩷稾磘泪詧瘇"],
["a040","𨩚鼦泎蟖痃𪊲硓咢贌狢獱謭猂瓱賫𤪻蘯徺袠䒷"],
["a055","𡠻𦸅"],
["a058","詾𢔛"],
["a05b","惽癧髗鵄鍮鮏蟵"],
["a063","蠏賷猬霡鮰㗖犲䰇籑饊𦅙慙䰄麖慽"],
["a073","坟慯抦戹拎㩜懢厪𣏵捤栂㗒"],
["a0a1","嵗𨯂迚𨸹"],
["a0a6","僙𡵆礆匲阸𠼻䁥"],
["a0ae","矾"],
["a0b0","糂𥼚糚稭聦聣絍甅瓲覔舚朌聢𧒆聛瓰脃眤覉𦟌畓𦻑螩蟎臈螌詉貭譃眫瓸蓚㘵榲趦"],
["a0d4","覩瑨涹蟁𤀑瓧㷛煶悤憜㳑煢恷"],
["a0e2","罱𨬭牐惩䭾删㰘𣳇𥻗𧙖𥔱𡥄𡋾𩤃𦷜𧂭峁𦆭𨨏𣙷𠃮𦡆𤼎䕢嬟𦍌齐麦𦉫"],
["a3c0","␀",31,"␡"],
["c6a1","①",9,"⑴",9,"ⅰ",9,"丶丿亅亠冂冖冫勹匸卩厶夊宀巛⼳广廴彐彡攴无疒癶辵隶¨ˆヽヾゝゞ〃仝々〆〇ー［］✽ぁ",23],
["c740","す",58,"ァアィイ"],
["c7a1","ゥ",81,"А",5,"ЁЖ",4],
["c840","Л",26,"ёж",25,"⇧↸↹㇏𠃌乚𠂊刂䒑"],
["c8a1","龰冈龱𧘇"],
["c8cd","￢￤＇＂㈱№℡゛゜⺀⺄⺆⺇⺈⺊⺌⺍⺕⺜⺝⺥⺧⺪⺬⺮⺶⺼⺾⻆⻊⻌⻍⻏⻖⻗⻞⻣"],
["c8f5","ʃɐɛɔɵœøŋʊɪ"],
["f9fe","￭"],
["fa40","𠕇鋛𠗟𣿅蕌䊵珯况㙉𤥂𨧤鍄𡧛苮𣳈砼杄拟𤤳𨦪𠊠𦮳𡌅侫𢓭倈𦴩𧪄𣘀𤪱𢔓倩𠍾徤𠎀𠍇滛𠐟偽儁㑺儎顬㝃萖𤦤𠒇兠𣎴兪𠯿𢃼𠋥𢔰𠖎𣈳𡦃宂蝽𠖳𣲙冲冸"],
["faa1","鴴凉减凑㳜凓𤪦决凢卂凭菍椾𣜭彻刋刦刼劵剗劔効勅簕蕂勠蘍𦬓包𨫞啉滙𣾀𠥔𣿬匳卄𠯢泋𡜦栛珕恊㺪㣌𡛨燝䒢卭却𨚫卾卿𡖖𡘓矦厓𨪛厠厫厮玧𥝲㽙玜叁叅汉义埾叙㪫𠮏叠𣿫𢶣叶𠱷吓灹唫晗浛呭𦭓𠵴啝咏咤䞦𡜍𠻝㶴𠵍"],
["fb40","𨦼𢚘啇䳭启琗喆喩嘅𡣗𤀺䕒𤐵暳𡂴嘷曍𣊊暤暭噍噏磱囱鞇叾圀囯园𨭦㘣𡉏坆𤆥汮炋坂㚱𦱾埦𡐖堃𡑔𤍣堦𤯵塜墪㕡壠壜𡈼壻寿坃𪅐𤉸鏓㖡够梦㛃湙"],
["fba1","𡘾娤啓𡚒蔅姉𠵎𦲁𦴪𡟜姙𡟻𡞲𦶦浱𡠨𡛕姹𦹅媫婣㛦𤦩婷㜈媖瑥嫓𦾡𢕔㶅𡤑㜲𡚸広勐孶斈孼𧨎䀄䡝𠈄寕慠𡨴𥧌𠖥寳宝䴐尅𡭄尓珎尔𡲥𦬨屉䣝岅峩峯嶋𡷹𡸷崐崘嵆𡺤岺巗苼㠭𤤁𢁉𢅳芇㠶㯂帮檊幵幺𤒼𠳓厦亷廐厨𡝱帉廴𨒂"],
["fc40","廹廻㢠廼栾鐛弍𠇁弢㫞䢮𡌺强𦢈𢏐彘𢑱彣鞽𦹮彲鍀𨨶徧嶶㵟𥉐𡽪𧃸𢙨釖𠊞𨨩怱暅𡡷㥣㷇㘹垐𢞴祱㹀悞悤悳𤦂𤦏𧩓璤僡媠慤萤慂慈𦻒憁凴𠙖憇宪𣾷"],
["fca1","𢡟懓𨮝𩥝懐㤲𢦀𢣁怣慜攞掋𠄘担𡝰拕𢸍捬𤧟㨗搸揸𡎎𡟼撐澊𢸶頔𤂌𥜝擡擥鑻㩦携㩗敍漖𤨨𤨣斅敭敟𣁾斵𤥀䬷旑䃘𡠩无旣忟𣐀昘𣇷𣇸晄𣆤𣆥晋𠹵晧𥇦晳晴𡸽𣈱𨗴𣇈𥌓矅𢣷馤朂𤎜𤨡㬫槺𣟂杞杧杢𤇍𩃭柗䓩栢湐鈼栁𣏦𦶠桝"],
["fd40","𣑯槡樋𨫟楳棃𣗍椁椀㴲㨁𣘼㮀枬楡𨩊䋼椶榘㮡𠏉荣傐槹𣙙𢄪橅𣜃檝㯳枱櫈𩆜㰍欝𠤣惞欵歴𢟍溵𣫛𠎵𡥘㝀吡𣭚毡𣻼毜氷𢒋𤣱𦭑汚舦汹𣶼䓅𣶽𤆤𤤌𤤀"],
["fda1","𣳉㛥㳫𠴲鮃𣇹𢒑羏样𦴥𦶡𦷫涖浜湼漄𤥿𤂅𦹲蔳𦽴凇沜渝萮𨬡港𣸯瑓𣾂秌湏媑𣁋濸㜍澝𣸰滺𡒗𤀽䕕鏰潄潜㵎潴𩅰㴻澟𤅄濓𤂑𤅕𤀹𣿰𣾴𤄿凟𤅖𤅗𤅀𦇝灋灾炧炁烌烕烖烟䄄㷨熴熖𤉷焫煅媈煊煮岜𤍥煏鍢𤋁焬𤑚𤨧𤨢熺𨯨炽爎"],
["fe40","鑂爕夑鑃爤鍁𥘅爮牀𤥴梽牕牗㹕𣁄栍漽犂猪猫𤠣𨠫䣭𨠄猨献珏玪𠰺𦨮珉瑉𤇢𡛧𤨤昣㛅𤦷𤦍𤧻珷琕椃𤨦琹𠗃㻗瑜𢢭瑠𨺲瑇珤瑶莹瑬㜰瑴鏱樬璂䥓𤪌"],
["fea1","𤅟𤩹𨮏孆𨰃𡢞瓈𡦈甎瓩甞𨻙𡩋寗𨺬鎅畍畊畧畮𤾂㼄𤴓疎瑝疞疴瘂瘬癑癏癯癶𦏵皐臯㟸𦤑𦤎皡皥皷盌𦾟葢𥂝𥅽𡸜眞眦着撯𥈠睘𣊬瞯𨥤𨥨𡛁矴砉𡍶𤨒棊碯磇磓隥礮𥗠磗礴碱𧘌辸袄𨬫𦂃𢘜禆褀椂禀𥡗禝𧬹礼禩渪𧄦㺨秆𩄍秔"]
]

},{}],19:[function(require,module,exports){
module.exports=[
["0","\u0000",127,"€"],
["8140","丂丄丅丆丏丒丗丟丠両丣並丩丮丯丱丳丵丷丼乀乁乂乄乆乊乑乕乗乚乛乢乣乤乥乧乨乪",5,"乲乴",9,"乿",6,"亇亊"],
["8180","亐亖亗亙亜亝亞亣亪亯亰亱亴亶亷亸亹亼亽亾仈仌仏仐仒仚仛仜仠仢仦仧仩仭仮仯仱仴仸仹仺仼仾伀伂",6,"伋伌伒",4,"伜伝伡伣伨伩伬伭伮伱伳伵伷伹伻伾",4,"佄佅佇",5,"佒佔佖佡佢佦佨佪佫佭佮佱佲併佷佸佹佺佽侀侁侂侅來侇侊侌侎侐侒侓侕侖侘侙侚侜侞侟価侢"],
["8240","侤侫侭侰",4,"侶",8,"俀俁係俆俇俈俉俋俌俍俒",4,"俙俛俠俢俤俥俧俫俬俰俲俴俵俶俷俹俻俼俽俿",11],
["8280","個倎倐們倓倕倖倗倛倝倞倠倢倣値倧倫倯",10,"倻倽倿偀偁偂偄偅偆偉偊偋偍偐",4,"偖偗偘偙偛偝",7,"偦",5,"偭",8,"偸偹偺偼偽傁傂傃傄傆傇傉傊傋傌傎",20,"傤傦傪傫傭",4,"傳",6,"傼"],
["8340","傽",17,"僐",5,"僗僘僙僛",10,"僨僩僪僫僯僰僱僲僴僶",4,"僼",9,"儈"],
["8380","儉儊儌",5,"儓",13,"儢",28,"兂兇兊兌兎兏児兒兓兗兘兙兛兝",4,"兣兤兦內兩兪兯兲兺兾兿冃冄円冇冊冋冎冏冐冑冓冔冘冚冝冞冟冡冣冦",4,"冭冮冴冸冹冺冾冿凁凂凃凅凈凊凍凎凐凒",5],
["8440","凘凙凚凜凞凟凢凣凥",5,"凬凮凱凲凴凷凾刄刅刉刋刌刏刐刓刔刕刜刞刟刡刢刣別刦刧刪刬刯刱刲刴刵刼刾剄",5,"剋剎剏剒剓剕剗剘"],
["8480","剙剚剛剝剟剠剢剣剤剦剨剫剬剭剮剰剱剳",9,"剾劀劃",4,"劉",6,"劑劒劔",6,"劜劤劥劦劧劮劯劰労",9,"勀勁勂勄勅勆勈勊勌勍勎勏勑勓勔動勗務",5,"勠勡勢勣勥",10,"勱",7,"勻勼勽匁匂匃匄匇匉匊匋匌匎"],
["8540","匑匒匓匔匘匛匜匞匟匢匤匥匧匨匩匫匬匭匯",9,"匼匽區卂卄卆卋卌卍卐協単卙卛卝卥卨卪卬卭卲卶卹卻卼卽卾厀厁厃厇厈厊厎厏"],
["8580","厐",4,"厖厗厙厛厜厞厠厡厤厧厪厫厬厭厯",6,"厷厸厹厺厼厽厾叀參",4,"収叏叐叒叓叕叚叜叝叞叡叢叧叴叺叾叿吀吂吅吇吋吔吘吙吚吜吢吤吥吪吰吳吶吷吺吽吿呁呂呄呅呇呉呌呍呎呏呑呚呝",4,"呣呥呧呩",7,"呴呹呺呾呿咁咃咅咇咈咉咊咍咑咓咗咘咜咞咟咠咡"],
["8640","咢咥咮咰咲咵咶咷咹咺咼咾哃哅哊哋哖哘哛哠",4,"哫哬哯哰哱哴",5,"哻哾唀唂唃唄唅唈唊",4,"唒唓唕",5,"唜唝唞唟唡唥唦"],
["8680","唨唩唫唭唲唴唵唶唸唹唺唻唽啀啂啅啇啈啋",4,"啑啒啓啔啗",4,"啝啞啟啠啢啣啨啩啫啯",5,"啹啺啽啿喅喆喌喍喎喐喒喓喕喖喗喚喛喞喠",6,"喨",8,"喲喴営喸喺喼喿",4,"嗆嗇嗈嗊嗋嗎嗏嗐嗕嗗",4,"嗞嗠嗢嗧嗩嗭嗮嗰嗱嗴嗶嗸",4,"嗿嘂嘃嘄嘅"],
["8740","嘆嘇嘊嘋嘍嘐",7,"嘙嘚嘜嘝嘠嘡嘢嘥嘦嘨嘩嘪嘫嘮嘯嘰嘳嘵嘷嘸嘺嘼嘽嘾噀",11,"噏",4,"噕噖噚噛噝",4],
["8780","噣噥噦噧噭噮噯噰噲噳噴噵噷噸噹噺噽",7,"嚇",6,"嚐嚑嚒嚔",14,"嚤",10,"嚰",6,"嚸嚹嚺嚻嚽",12,"囋",8,"囕囖囘囙囜団囥",5,"囬囮囯囲図囶囷囸囻囼圀圁圂圅圇國",6],
["8840","園",9,"圝圞圠圡圢圤圥圦圧圫圱圲圴",4,"圼圽圿坁坃坄坅坆坈坉坋坒",4,"坘坙坢坣坥坧坬坮坰坱坲坴坵坸坹坺坽坾坿垀"],
["8880","垁垇垈垉垊垍",4,"垔",6,"垜垝垞垟垥垨垪垬垯垰垱垳垵垶垷垹",8,"埄",6,"埌埍埐埑埓埖埗埛埜埞埡埢埣埥",7,"埮埰埱埲埳埵埶執埻埼埾埿堁堃堄堅堈堉堊堌堎堏堐堒堓堔堖堗堘堚堛堜堝堟堢堣堥",4,"堫",4,"報堲堳場堶",7],
["8940","堾",5,"塅",6,"塎塏塐塒塓塕塖塗塙",4,"塟",5,"塦",4,"塭",16,"塿墂墄墆墇墈墊墋墌"],
["8980","墍",4,"墔",4,"墛墜墝墠",7,"墪",17,"墽墾墿壀壂壃壄壆",10,"壒壓壔壖",13,"壥",5,"壭壯壱売壴壵壷壸壺",7,"夃夅夆夈",4,"夎夐夑夒夓夗夘夛夝夞夠夡夢夣夦夨夬夰夲夳夵夶夻"],
["8a40","夽夾夿奀奃奅奆奊奌奍奐奒奓奙奛",4,"奡奣奤奦",12,"奵奷奺奻奼奾奿妀妅妉妋妌妎妏妐妑妔妕妘妚妛妜妝妟妠妡妢妦"],
["8a80","妧妬妭妰妱妳",5,"妺妼妽妿",6,"姇姈姉姌姍姎姏姕姖姙姛姞",4,"姤姦姧姩姪姫姭",11,"姺姼姽姾娀娂娊娋娍娎娏娐娒娔娕娖娗娙娚娛娝娞娡娢娤娦娧娨娪",6,"娳娵娷",4,"娽娾娿婁",4,"婇婈婋",9,"婖婗婘婙婛",5],
["8b40","婡婣婤婥婦婨婩婫",8,"婸婹婻婼婽婾媀",17,"媓",6,"媜",13,"媫媬"],
["8b80","媭",4,"媴媶媷媹",4,"媿嫀嫃",5,"嫊嫋嫍",4,"嫓嫕嫗嫙嫚嫛嫝嫞嫟嫢嫤嫥嫧嫨嫪嫬",4,"嫲",22,"嬊",11,"嬘",25,"嬳嬵嬶嬸",7,"孁",6],
["8c40","孈",7,"孒孖孞孠孡孧孨孫孭孮孯孲孴孶孷學孹孻孼孾孿宂宆宊宍宎宐宑宒宔宖実宧宨宩宬宭宮宯宱宲宷宺宻宼寀寁寃寈寉寊寋寍寎寏"],
["8c80","寑寔",8,"寠寢寣實寧審",4,"寯寱",6,"寽対尀専尃尅將專尋尌對導尐尒尓尗尙尛尞尟尠尡尣尦尨尩尪尫尭尮尯尰尲尳尵尶尷屃屄屆屇屌屍屒屓屔屖屗屘屚屛屜屝屟屢層屧",6,"屰屲",6,"屻屼屽屾岀岃",4,"岉岊岋岎岏岒岓岕岝",4,"岤",4],
["8d40","岪岮岯岰岲岴岶岹岺岻岼岾峀峂峃峅",5,"峌",5,"峓",5,"峚",6,"峢峣峧峩峫峬峮峯峱",9,"峼",4],
["8d80","崁崄崅崈",5,"崏",4,"崕崗崘崙崚崜崝崟",4,"崥崨崪崫崬崯",4,"崵",7,"崿",7,"嵈嵉嵍",10,"嵙嵚嵜嵞",10,"嵪嵭嵮嵰嵱嵲嵳嵵",12,"嶃",21,"嶚嶛嶜嶞嶟嶠"],
["8e40","嶡",21,"嶸",12,"巆",6,"巎",12,"巜巟巠巣巤巪巬巭"],
["8e80","巰巵巶巸",4,"巿帀帄帇帉帊帋帍帎帒帓帗帞",7,"帨",4,"帯帰帲",4,"帹帺帾帿幀幁幃幆",5,"幍",6,"幖",4,"幜幝幟幠幣",14,"幵幷幹幾庁庂広庅庈庉庌庍庎庒庘庛庝庡庢庣庤庨",4,"庮",4,"庴庺庻庼庽庿",6],
["8f40","廆廇廈廋",5,"廔廕廗廘廙廚廜",11,"廩廫",8,"廵廸廹廻廼廽弅弆弇弉弌弍弎弐弒弔弖弙弚弜弝弞弡弢弣弤"],
["8f80","弨弫弬弮弰弲",6,"弻弽弾弿彁",14,"彑彔彙彚彛彜彞彟彠彣彥彧彨彫彮彯彲彴彵彶彸彺彽彾彿徃徆徍徎徏徑従徔徖徚徛徝從徟徠徢",5,"復徫徬徯",5,"徶徸徹徺徻徾",4,"忇忈忊忋忎忓忔忕忚忛応忞忟忢忣忥忦忨忩忬忯忰忲忳忴忶忷忹忺忼怇"],
["9040","怈怉怋怌怐怑怓怗怘怚怞怟怢怣怤怬怭怮怰",4,"怶",4,"怽怾恀恄",6,"恌恎恏恑恓恔恖恗恘恛恜恞恟恠恡恥恦恮恱恲恴恵恷恾悀"],
["9080","悁悂悅悆悇悈悊悋悎悏悐悑悓悕悗悘悙悜悞悡悢悤悥悧悩悪悮悰悳悵悶悷悹悺悽",7,"惇惈惉惌",4,"惒惓惔惖惗惙惛惞惡",4,"惪惱惲惵惷惸惻",4,"愂愃愄愅愇愊愋愌愐",4,"愖愗愘愙愛愜愝愞愡愢愥愨愩愪愬",18,"慀",6],
["9140","慇慉態慍慏慐慒慓慔慖",6,"慞慟慠慡慣慤慥慦慩",6,"慱慲慳慴慶慸",18,"憌憍憏",4,"憕"],
["9180","憖",6,"憞",8,"憪憫憭",9,"憸",5,"憿懀懁懃",4,"應懌",4,"懓懕",16,"懧",13,"懶",8,"戀",5,"戇戉戓戔戙戜戝戞戠戣戦戧戨戩戫戭戯戰戱戲戵戶戸",4,"扂扄扅扆扊"],
["9240","扏扐払扖扗扙扚扜",6,"扤扥扨扱扲扴扵扷扸扺扻扽抁抂抃抅抆抇抈抋",5,"抔抙抜抝択抣抦抧抩抪抭抮抯抰抲抳抴抶抷抸抺抾拀拁"],
["9280","拃拋拏拑拕拝拞拠拡拤拪拫拰拲拵拸拹拺拻挀挃挄挅挆挊挋挌挍挏挐挒挓挔挕挗挘挙挜挦挧挩挬挭挮挰挱挳",5,"挻挼挾挿捀捁捄捇捈捊捑捒捓捔捖",7,"捠捤捥捦捨捪捫捬捯捰捲捳捴捵捸捹捼捽捾捿掁掃掄掅掆掋掍掑掓掔掕掗掙",6,"採掤掦掫掯掱掲掵掶掹掻掽掿揀"],
["9340","揁揂揃揅揇揈揊揋揌揑揓揔揕揗",6,"揟揢揤",4,"揫揬揮揯揰揱揳揵揷揹揺揻揼揾搃搄搆",4,"損搎搑搒搕",5,"搝搟搢搣搤"],
["9380","搥搧搨搩搫搮",5,"搵",4,"搻搼搾摀摂摃摉摋",6,"摓摕摖摗摙",4,"摟",7,"摨摪摫摬摮",9,"摻",6,"撃撆撈",8,"撓撔撗撘撚撛撜撝撟",4,"撥撦撧撨撪撫撯撱撲撳撴撶撹撻撽撾撿擁擃擄擆",6,"擏擑擓擔擕擖擙據"],
["9440","擛擜擝擟擠擡擣擥擧",24,"攁",7,"攊",7,"攓",4,"攙",8],
["9480","攢攣攤攦",4,"攬攭攰攱攲攳攷攺攼攽敀",4,"敆敇敊敋敍敎敐敒敓敔敗敘敚敜敟敠敡敤敥敧敨敩敪敭敮敯敱敳敵敶數",14,"斈斉斊斍斎斏斒斔斕斖斘斚斝斞斠斢斣斦斨斪斬斮斱",7,"斺斻斾斿旀旂旇旈旉旊旍旐旑旓旔旕旘",7,"旡旣旤旪旫"],
["9540","旲旳旴旵旸旹旻",4,"昁昄昅昇昈昉昋昍昐昑昒昖昗昘昚昛昜昞昡昢昣昤昦昩昪昫昬昮昰昲昳昷",4,"昽昿晀時晄",6,"晍晎晐晑晘"],
["9580","晙晛晜晝晞晠晢晣晥晧晩",4,"晱晲晳晵晸晹晻晼晽晿暀暁暃暅暆暈暉暊暋暍暎暏暐暒暓暔暕暘",4,"暞",8,"暩",4,"暯",4,"暵暶暷暸暺暻暼暽暿",25,"曚曞",7,"曧曨曪",5,"曱曵曶書曺曻曽朁朂會"],
["9640","朄朅朆朇朌朎朏朑朒朓朖朘朙朚朜朞朠",5,"朧朩朮朰朲朳朶朷朸朹朻朼朾朿杁杄杅杇杊杋杍杒杔杕杗",4,"杝杢杣杤杦杧杫杬杮東杴杶"],
["9680","杸杹杺杻杽枀枂枃枅枆枈枊枌枍枎枏枑枒枓枔枖枙枛枟枠枡枤枦枩枬枮枱枲枴枹",7,"柂柅",9,"柕柖柗柛柟柡柣柤柦柧柨柪柫柭柮柲柵",7,"柾栁栂栃栄栆栍栐栒栔栕栘",4,"栞栟栠栢",6,"栫",6,"栴栵栶栺栻栿桇桋桍桏桒桖",5],
["9740","桜桝桞桟桪桬",7,"桵桸",8,"梂梄梇",7,"梐梑梒梔梕梖梘",9,"梣梤梥梩梪梫梬梮梱梲梴梶梷梸"],
["9780","梹",6,"棁棃",5,"棊棌棎棏棐棑棓棔棖棗棙棛",4,"棡棢棤",9,"棯棲棳棴棶棷棸棻棽棾棿椀椂椃椄椆",4,"椌椏椑椓",11,"椡椢椣椥",7,"椮椯椱椲椳椵椶椷椸椺椻椼椾楀楁楃",16,"楕楖楘楙楛楜楟"],
["9840","楡楢楤楥楧楨楩楪楬業楯楰楲",4,"楺楻楽楾楿榁榃榅榊榋榌榎",5,"榖榗榙榚榝",9,"榩榪榬榮榯榰榲榳榵榶榸榹榺榼榽"],
["9880","榾榿槀槂",7,"構槍槏槑槒槓槕",5,"槜槝槞槡",11,"槮槯槰槱槳",9,"槾樀",9,"樋",11,"標",5,"樠樢",5,"権樫樬樭樮樰樲樳樴樶",6,"樿",4,"橅橆橈",7,"橑",6,"橚"],
["9940","橜",4,"橢橣橤橦",10,"橲",6,"橺橻橽橾橿檁檂檃檅",8,"檏檒",4,"檘",7,"檡",5],
["9980","檧檨檪檭",114,"欥欦欨",6],
["9a40","欯欰欱欳欴欵欶欸欻欼欽欿歀歁歂歄歅歈歊歋歍",11,"歚",7,"歨歩歫",13,"歺歽歾歿殀殅殈"],
["9a80","殌殎殏殐殑殔殕殗殘殙殜",4,"殢",7,"殫",7,"殶殸",6,"毀毃毄毆",4,"毌毎毐毑毘毚毜",4,"毢",7,"毬毭毮毰毱毲毴毶毷毸毺毻毼毾",6,"氈",4,"氎氒気氜氝氞氠氣氥氫氬氭氱氳氶氷氹氺氻氼氾氿汃汄汅汈汋",4,"汑汒汓汖汘"],
["9b40","汙汚汢汣汥汦汧汫",4,"汱汳汵汷汸決汻汼汿沀沄沇沊沋沍沎沑沒沕沖沗沘沚沜沝沞沠沢沨沬沯沰沴沵沶沷沺泀況泂泃泆泇泈泋泍泎泏泑泒泘"],
["9b80","泙泚泜泝泟泤泦泧泩泬泭泲泴泹泿洀洂洃洅洆洈洉洊洍洏洐洑洓洔洕洖洘洜洝洟",5,"洦洨洩洬洭洯洰洴洶洷洸洺洿浀浂浄浉浌浐浕浖浗浘浛浝浟浡浢浤浥浧浨浫浬浭浰浱浲浳浵浶浹浺浻浽",4,"涃涄涆涇涊涋涍涏涐涒涖",4,"涜涢涥涬涭涰涱涳涴涶涷涹",5,"淁淂淃淈淉淊"],
["9c40","淍淎淏淐淒淓淔淕淗淚淛淜淟淢淣淥淧淨淩淪淭淯淰淲淴淵淶淸淺淽",7,"渆渇済渉渋渏渒渓渕渘渙減渜渞渟渢渦渧渨渪測渮渰渱渳渵"],
["9c80","渶渷渹渻",7,"湅",7,"湏湐湑湒湕湗湙湚湜湝湞湠",10,"湬湭湯",14,"満溁溂溄溇溈溊",4,"溑",6,"溙溚溛溝溞溠溡溣溤溦溨溩溫溬溭溮溰溳溵溸溹溼溾溿滀滃滄滅滆滈滉滊滌滍滎滐滒滖滘滙滛滜滝滣滧滪",5],
["9d40","滰滱滲滳滵滶滷滸滺",7,"漃漄漅漇漈漊",4,"漐漑漒漖",9,"漡漢漣漥漦漧漨漬漮漰漲漴漵漷",6,"漿潀潁潂"],
["9d80","潃潄潅潈潉潊潌潎",9,"潙潚潛潝潟潠潡潣潤潥潧",5,"潯潰潱潳潵潶潷潹潻潽",6,"澅澆澇澊澋澏",12,"澝澞澟澠澢",4,"澨",10,"澴澵澷澸澺",5,"濁濃",5,"濊",6,"濓",10,"濟濢濣濤濥"],
["9e40","濦",7,"濰",32,"瀒",7,"瀜",6,"瀤",6],
["9e80","瀫",9,"瀶瀷瀸瀺",17,"灍灎灐",13,"灟",11,"灮灱灲灳灴灷灹灺灻災炁炂炃炄炆炇炈炋炌炍炏炐炑炓炗炘炚炛炞",12,"炰炲炴炵炶為炾炿烄烅烆烇烉烋",12,"烚"],
["9f40","烜烝烞烠烡烢烣烥烪烮烰",6,"烸烺烻烼烾",10,"焋",4,"焑焒焔焗焛",10,"焧",7,"焲焳焴"],
["9f80","焵焷",13,"煆煇煈煉煋煍煏",12,"煝煟",4,"煥煩",4,"煯煰煱煴煵煶煷煹煻煼煾",5,"熅",4,"熋熌熍熎熐熑熒熓熕熖熗熚",4,"熡",6,"熩熪熫熭",5,"熴熶熷熸熺",8,"燄",9,"燏",4],
["a040","燖",9,"燡燢燣燤燦燨",5,"燯",9,"燺",11,"爇",19],
["a080","爛爜爞",9,"爩爫爭爮爯爲爳爴爺爼爾牀",6,"牉牊牋牎牏牐牑牓牔牕牗牘牚牜牞牠牣牤牥牨牪牫牬牭牰牱牳牴牶牷牸牻牼牽犂犃犅",4,"犌犎犐犑犓",11,"犠",11,"犮犱犲犳犵犺",6,"狅狆狇狉狊狋狌狏狑狓狔狕狖狘狚狛"],
["a1a1","　、。·ˉˇ¨〃々—～‖…‘’“”〔〕〈",7,"〖〗【】±×÷∶∧∨∑∏∪∩∈∷√⊥∥∠⌒⊙∫∮≡≌≈∽∝≠≮≯≤≥∞∵∴♂♀°′″℃＄¤￠￡‰§№☆★○●◎◇◆□■△▲※→←↑↓〓"],
["a2a1","ⅰ",9],
["a2b1","⒈",19,"⑴",19,"①",9],
["a2e5","㈠",9],
["a2f1","Ⅰ",11],
["a3a1","！＂＃￥％",88,"￣"],
["a4a1","ぁ",82],
["a5a1","ァ",85],
["a6a1","Α",16,"Σ",6],
["a6c1","α",16,"σ",6],
["a6e0","︵︶︹︺︿﹀︽︾﹁﹂﹃﹄"],
["a6ee","︻︼︷︸︱"],
["a6f4","︳︴"],
["a7a1","А",5,"ЁЖ",25],
["a7d1","а",5,"ёж",25],
["a840","ˊˋ˙–―‥‵℅℉↖↗↘↙∕∟∣≒≦≧⊿═",35,"▁",6],
["a880","█",7,"▓▔▕▼▽◢◣◤◥☉⊕〒〝〞"],
["a8a1","āáǎàēéěèīíǐìōóǒòūúǔùǖǘǚǜüêɑ"],
["a8bd","ńň"],
["a8c0","ɡ"],
["a8c5","ㄅ",36],
["a940","〡",8,"㊣㎎㎏㎜㎝㎞㎡㏄㏎㏑㏒㏕︰￢￤"],
["a959","℡㈱"],
["a95c","‐"],
["a960","ー゛゜ヽヾ〆ゝゞ﹉",9,"﹔﹕﹖﹗﹙",8],
["a980","﹢",4,"﹨﹩﹪﹫"],
["a996","〇"],
["a9a4","─",75],
["aa40","狜狝狟狢",5,"狪狫狵狶狹狽狾狿猀猂猄",5,"猋猌猍猏猐猑猒猔猘猙猚猟猠猣猤猦猧猨猭猯猰猲猳猵猶猺猻猼猽獀",8],
["aa80","獉獊獋獌獎獏獑獓獔獕獖獘",7,"獡",10,"獮獰獱"],
["ab40","獲",11,"獿",4,"玅玆玈玊玌玍玏玐玒玓玔玕玗玘玙玚玜玝玞玠玡玣",5,"玪玬玭玱玴玵玶玸玹玼玽玾玿珁珃",4],
["ab80","珋珌珎珒",6,"珚珛珜珝珟珡珢珣珤珦珨珪珫珬珮珯珰珱珳",4],
["ac40","珸",10,"琄琇琈琋琌琍琎琑",8,"琜",5,"琣琤琧琩琫琭琯琱琲琷",4,"琽琾琿瑀瑂",11],
["ac80","瑎",6,"瑖瑘瑝瑠",12,"瑮瑯瑱",4,"瑸瑹瑺"],
["ad40","瑻瑼瑽瑿璂璄璅璆璈璉璊璌璍璏璑",10,"璝璟",7,"璪",15,"璻",12],
["ad80","瓈",9,"瓓",8,"瓝瓟瓡瓥瓧",6,"瓰瓱瓲"],
["ae40","瓳瓵瓸",6,"甀甁甂甃甅",7,"甎甐甒甔甕甖甗甛甝甞甠",4,"甦甧甪甮甴甶甹甼甽甿畁畂畃畄畆畇畉畊畍畐畑畒畓畕畖畗畘"],
["ae80","畝",7,"畧畨畩畫",6,"畳畵當畷畺",4,"疀疁疂疄疅疇"],
["af40","疈疉疊疌疍疎疐疓疕疘疛疜疞疢疦",4,"疭疶疷疺疻疿痀痁痆痋痌痎痏痐痑痓痗痙痚痜痝痟痠痡痥痩痬痭痮痯痲痳痵痶痷痸痺痻痽痾瘂瘄瘆瘇"],
["af80","瘈瘉瘋瘍瘎瘏瘑瘒瘓瘔瘖瘚瘜瘝瘞瘡瘣瘧瘨瘬瘮瘯瘱瘲瘶瘷瘹瘺瘻瘽癁療癄"],
["b040","癅",6,"癎",5,"癕癗",4,"癝癟癠癡癢癤",6,"癬癭癮癰",7,"癹発發癿皀皁皃皅皉皊皌皍皏皐皒皔皕皗皘皚皛"],
["b080","皜",7,"皥",8,"皯皰皳皵",9,"盀盁盃啊阿埃挨哎唉哀皑癌蔼矮艾碍爱隘鞍氨安俺按暗岸胺案肮昂盎凹敖熬翱袄傲奥懊澳芭捌扒叭吧笆八疤巴拔跋靶把耙坝霸罢爸白柏百摆佰败拜稗斑班搬扳般颁板版扮拌伴瓣半办绊邦帮梆榜膀绑棒磅蚌镑傍谤苞胞包褒剥"],
["b140","盄盇盉盋盌盓盕盙盚盜盝盞盠",4,"盦",7,"盰盳盵盶盷盺盻盽盿眀眂眃眅眆眊県眎",10,"眛眜眝眞眡眣眤眥眧眪眫"],
["b180","眬眮眰",4,"眹眻眽眾眿睂睄睅睆睈",7,"睒",7,"睜薄雹保堡饱宝抱报暴豹鲍爆杯碑悲卑北辈背贝钡倍狈备惫焙被奔苯本笨崩绷甭泵蹦迸逼鼻比鄙笔彼碧蓖蔽毕毙毖币庇痹闭敝弊必辟壁臂避陛鞭边编贬扁便变卞辨辩辫遍标彪膘表鳖憋别瘪彬斌濒滨宾摈兵冰柄丙秉饼炳"],
["b240","睝睞睟睠睤睧睩睪睭",11,"睺睻睼瞁瞂瞃瞆",5,"瞏瞐瞓",11,"瞡瞣瞤瞦瞨瞫瞭瞮瞯瞱瞲瞴瞶",4],
["b280","瞼瞾矀",12,"矎",8,"矘矙矚矝",4,"矤病并玻菠播拨钵波博勃搏铂箔伯帛舶脖膊渤泊驳捕卜哺补埠不布步簿部怖擦猜裁材才财睬踩采彩菜蔡餐参蚕残惭惨灿苍舱仓沧藏操糙槽曹草厕策侧册测层蹭插叉茬茶查碴搽察岔差诧拆柴豺搀掺蝉馋谗缠铲产阐颤昌猖"],
["b340","矦矨矪矯矰矱矲矴矵矷矹矺矻矼砃",5,"砊砋砎砏砐砓砕砙砛砞砠砡砢砤砨砪砫砮砯砱砲砳砵砶砽砿硁硂硃硄硆硈硉硊硋硍硏硑硓硔硘硙硚"],
["b380","硛硜硞",11,"硯",7,"硸硹硺硻硽",6,"场尝常长偿肠厂敞畅唱倡超抄钞朝嘲潮巢吵炒车扯撤掣彻澈郴臣辰尘晨忱沉陈趁衬撑称城橙成呈乘程惩澄诚承逞骋秤吃痴持匙池迟弛驰耻齿侈尺赤翅斥炽充冲虫崇宠抽酬畴踌稠愁筹仇绸瞅丑臭初出橱厨躇锄雏滁除楚"],
["b440","碄碅碆碈碊碋碏碐碒碔碕碖碙碝碞碠碢碤碦碨",7,"碵碶碷碸確碻碼碽碿磀磂磃磄磆磇磈磌磍磎磏磑磒磓磖磗磘磚",9],
["b480","磤磥磦磧磩磪磫磭",4,"磳磵磶磸磹磻",5,"礂礃礄礆",6,"础储矗搐触处揣川穿椽传船喘串疮窗幢床闯创吹炊捶锤垂春椿醇唇淳纯蠢戳绰疵茨磁雌辞慈瓷词此刺赐次聪葱囱匆从丛凑粗醋簇促蹿篡窜摧崔催脆瘁粹淬翠村存寸磋撮搓措挫错搭达答瘩打大呆歹傣戴带殆代贷袋待逮"],
["b540","礍",5,"礔",9,"礟",4,"礥",14,"礵",4,"礽礿祂祃祄祅祇祊",8,"祔祕祘祙祡祣"],
["b580","祤祦祩祪祫祬祮祰",6,"祹祻",4,"禂禃禆禇禈禉禋禌禍禎禐禑禒怠耽担丹单郸掸胆旦氮但惮淡诞弹蛋当挡党荡档刀捣蹈倒岛祷导到稻悼道盗德得的蹬灯登等瞪凳邓堤低滴迪敌笛狄涤翟嫡抵底地蒂第帝弟递缔颠掂滇碘点典靛垫电佃甸店惦奠淀殿碉叼雕凋刁掉吊钓调跌爹碟蝶迭谍叠"],
["b640","禓",6,"禛",11,"禨",10,"禴",4,"禼禿秂秄秅秇秈秊秌秎秏秐秓秔秖秗秙",5,"秠秡秢秥秨秪"],
["b680","秬秮秱",6,"秹秺秼秾秿稁稄稅稇稈稉稊稌稏",4,"稕稖稘稙稛稜丁盯叮钉顶鼎锭定订丢东冬董懂动栋侗恫冻洞兜抖斗陡豆逗痘都督毒犊独读堵睹赌杜镀肚度渡妒端短锻段断缎堆兑队对墩吨蹲敦顿囤钝盾遁掇哆多夺垛躲朵跺舵剁惰堕蛾峨鹅俄额讹娥恶厄扼遏鄂饿恩而儿耳尔饵洱二"],
["b740","稝稟稡稢稤",14,"稴稵稶稸稺稾穀",5,"穇",9,"穒",4,"穘",16],
["b780","穩",6,"穱穲穳穵穻穼穽穾窂窅窇窉窊窋窌窎窏窐窓窔窙窚窛窞窡窢贰发罚筏伐乏阀法珐藩帆番翻樊矾钒繁凡烦反返范贩犯饭泛坊芳方肪房防妨仿访纺放菲非啡飞肥匪诽吠肺废沸费芬酚吩氛分纷坟焚汾粉奋份忿愤粪丰封枫蜂峰锋风疯烽逢冯缝讽奉凤佛否夫敷肤孵扶拂辐幅氟符伏俘服"],
["b840","窣窤窧窩窪窫窮",4,"窴",10,"竀",10,"竌",9,"竗竘竚竛竜竝竡竢竤竧",5,"竮竰竱竲竳"],
["b880","竴",4,"竻竼竾笀笁笂笅笇笉笌笍笎笐笒笓笖笗笘笚笜笝笟笡笢笣笧笩笭浮涪福袱弗甫抚辅俯釜斧脯腑府腐赴副覆赋复傅付阜父腹负富讣附妇缚咐噶嘎该改概钙盖溉干甘杆柑竿肝赶感秆敢赣冈刚钢缸肛纲岗港杠篙皋高膏羔糕搞镐稿告哥歌搁戈鸽胳疙割革葛格蛤阁隔铬个各给根跟耕更庚羹"],
["b940","笯笰笲笴笵笶笷笹笻笽笿",5,"筆筈筊筍筎筓筕筗筙筜筞筟筡筣",10,"筯筰筳筴筶筸筺筼筽筿箁箂箃箄箆",6,"箎箏"],
["b980","箑箒箓箖箘箙箚箛箞箟箠箣箤箥箮箯箰箲箳箵箶箷箹",7,"篂篃範埂耿梗工攻功恭龚供躬公宫弓巩汞拱贡共钩勾沟苟狗垢构购够辜菇咕箍估沽孤姑鼓古蛊骨谷股故顾固雇刮瓜剐寡挂褂乖拐怪棺关官冠观管馆罐惯灌贯光广逛瑰规圭硅归龟闺轨鬼诡癸桂柜跪贵刽辊滚棍锅郭国果裹过哈"],
["ba40","篅篈築篊篋篍篎篏篐篒篔",4,"篛篜篞篟篠篢篣篤篧篨篩篫篬篭篯篰篲",4,"篸篹篺篻篽篿",7,"簈簉簊簍簎簐",5,"簗簘簙"],
["ba80","簚",4,"簠",5,"簨簩簫",12,"簹",5,"籂骸孩海氦亥害骇酣憨邯韩含涵寒函喊罕翰撼捍旱憾悍焊汗汉夯杭航壕嚎豪毫郝好耗号浩呵喝荷菏核禾和何合盒貉阂河涸赫褐鹤贺嘿黑痕很狠恨哼亨横衡恒轰哄烘虹鸿洪宏弘红喉侯猴吼厚候后呼乎忽瑚壶葫胡蝴狐糊湖"],
["bb40","籃",9,"籎",36,"籵",5,"籾",9],
["bb80","粈粊",6,"粓粔粖粙粚粛粠粡粣粦粧粨粩粫粬粭粯粰粴",4,"粺粻弧虎唬护互沪户花哗华猾滑画划化话槐徊怀淮坏欢环桓还缓换患唤痪豢焕涣宦幻荒慌黄磺蝗簧皇凰惶煌晃幌恍谎灰挥辉徽恢蛔回毁悔慧卉惠晦贿秽会烩汇讳诲绘荤昏婚魂浑混豁活伙火获或惑霍货祸击圾基机畸稽积箕"],
["bc40","粿糀糂糃糄糆糉糋糎",6,"糘糚糛糝糞糡",6,"糩",5,"糰",7,"糹糺糼",13,"紋",5],
["bc80","紑",14,"紡紣紤紥紦紨紩紪紬紭紮細",6,"肌饥迹激讥鸡姬绩缉吉极棘辑籍集及急疾汲即嫉级挤几脊己蓟技冀季伎祭剂悸济寄寂计记既忌际妓继纪嘉枷夹佳家加荚颊贾甲钾假稼价架驾嫁歼监坚尖笺间煎兼肩艰奸缄茧检柬碱硷拣捡简俭剪减荐槛鉴践贱见键箭件"],
["bd40","紷",54,"絯",7],
["bd80","絸",32,"健舰剑饯渐溅涧建僵姜将浆江疆蒋桨奖讲匠酱降蕉椒礁焦胶交郊浇骄娇嚼搅铰矫侥脚狡角饺缴绞剿教酵轿较叫窖揭接皆秸街阶截劫节桔杰捷睫竭洁结解姐戒藉芥界借介疥诫届巾筋斤金今津襟紧锦仅谨进靳晋禁近烬浸"],
["be40","継",12,"綧",6,"綯",42],
["be80","線",32,"尽劲荆兢茎睛晶鲸京惊精粳经井警景颈静境敬镜径痉靖竟竞净炯窘揪究纠玖韭久灸九酒厩救旧臼舅咎就疚鞠拘狙疽居驹菊局咀矩举沮聚拒据巨具距踞锯俱句惧炬剧捐鹃娟倦眷卷绢撅攫抉掘倔爵觉决诀绝均菌钧军君峻"],
["bf40","緻",62],
["bf80","縺縼",4,"繂",4,"繈",21,"俊竣浚郡骏喀咖卡咯开揩楷凯慨刊堪勘坎砍看康慷糠扛抗亢炕考拷烤靠坷苛柯棵磕颗科壳咳可渴克刻客课肯啃垦恳坑吭空恐孔控抠口扣寇枯哭窟苦酷库裤夸垮挎跨胯块筷侩快宽款匡筐狂框矿眶旷况亏盔岿窥葵奎魁傀"],
["c040","繞",35,"纃",23,"纜纝纞"],
["c080","纮纴纻纼绖绤绬绹缊缐缞缷缹缻",6,"罃罆",9,"罒罓馈愧溃坤昆捆困括扩廓阔垃拉喇蜡腊辣啦莱来赖蓝婪栏拦篮阑兰澜谰揽览懒缆烂滥琅榔狼廊郎朗浪捞劳牢老佬姥酪烙涝勒乐雷镭蕾磊累儡垒擂肋类泪棱楞冷厘梨犁黎篱狸离漓理李里鲤礼莉荔吏栗丽厉励砾历利傈例俐"],
["c140","罖罙罛罜罝罞罠罣",4,"罫罬罭罯罰罳罵罶罷罸罺罻罼罽罿羀羂",7,"羋羍羏",4,"羕",4,"羛羜羠羢羣羥羦羨",6,"羱"],
["c180","羳",4,"羺羻羾翀翂翃翄翆翇翈翉翋翍翏",4,"翖翗翙",5,"翢翣痢立粒沥隶力璃哩俩联莲连镰廉怜涟帘敛脸链恋炼练粮凉梁粱良两辆量晾亮谅撩聊僚疗燎寥辽潦了撂镣廖料列裂烈劣猎琳林磷霖临邻鳞淋凛赁吝拎玲菱零龄铃伶羚凌灵陵岭领另令溜琉榴硫馏留刘瘤流柳六龙聋咙笼窿"],
["c240","翤翧翨翪翫翬翭翯翲翴",6,"翽翾翿耂耇耈耉耊耎耏耑耓耚耛耝耞耟耡耣耤耫",5,"耲耴耹耺耼耾聀聁聄聅聇聈聉聎聏聐聑聓聕聖聗"],
["c280","聙聛",13,"聫",5,"聲",11,"隆垄拢陇楼娄搂篓漏陋芦卢颅庐炉掳卤虏鲁麓碌露路赂鹿潞禄录陆戮驴吕铝侣旅履屡缕虑氯律率滤绿峦挛孪滦卵乱掠略抡轮伦仑沦纶论萝螺罗逻锣箩骡裸落洛骆络妈麻玛码蚂马骂嘛吗埋买麦卖迈脉瞒馒蛮满蔓曼慢漫"],
["c340","聾肁肂肅肈肊肍",5,"肔肕肗肙肞肣肦肧肨肬肰肳肵肶肸肹肻胅胇",4,"胏",6,"胘胟胠胢胣胦胮胵胷胹胻胾胿脀脁脃脄脅脇脈脋"],
["c380","脌脕脗脙脛脜脝脟",12,"脭脮脰脳脴脵脷脹",4,"脿谩芒茫盲氓忙莽猫茅锚毛矛铆卯茂冒帽貌贸么玫枚梅酶霉煤没眉媒镁每美昧寐妹媚门闷们萌蒙檬盟锰猛梦孟眯醚靡糜迷谜弥米秘觅泌蜜密幂棉眠绵冕免勉娩缅面苗描瞄藐秒渺庙妙蔑灭民抿皿敏悯闽明螟鸣铭名命谬摸"],
["c440","腀",5,"腇腉腍腎腏腒腖腗腘腛",4,"腡腢腣腤腦腨腪腫腬腯腲腳腵腶腷腸膁膃",4,"膉膋膌膍膎膐膒",5,"膙膚膞",4,"膤膥"],
["c480","膧膩膫",7,"膴",5,"膼膽膾膿臄臅臇臈臉臋臍",6,"摹蘑模膜磨摩魔抹末莫墨默沫漠寞陌谋牟某拇牡亩姆母墓暮幕募慕木目睦牧穆拿哪呐钠那娜纳氖乃奶耐奈南男难囊挠脑恼闹淖呢馁内嫩能妮霓倪泥尼拟你匿腻逆溺蔫拈年碾撵捻念娘酿鸟尿捏聂孽啮镊镍涅您柠狞凝宁"],
["c540","臔",14,"臤臥臦臨臩臫臮",4,"臵",5,"臽臿舃與",4,"舎舏舑舓舕",5,"舝舠舤舥舦舧舩舮舲舺舼舽舿"],
["c580","艀艁艂艃艅艆艈艊艌艍艎艐",7,"艙艛艜艝艞艠",7,"艩拧泞牛扭钮纽脓浓农弄奴努怒女暖虐疟挪懦糯诺哦欧鸥殴藕呕偶沤啪趴爬帕怕琶拍排牌徘湃派攀潘盘磐盼畔判叛乓庞旁耪胖抛咆刨炮袍跑泡呸胚培裴赔陪配佩沛喷盆砰抨烹澎彭蓬棚硼篷膨朋鹏捧碰坯砒霹批披劈琵毗"],
["c640","艪艫艬艭艱艵艶艷艸艻艼芀芁芃芅芆芇芉芌芐芓芔芕芖芚芛芞芠芢芣芧芲芵芶芺芻芼芿苀苂苃苅苆苉苐苖苙苚苝苢苧苨苩苪苬苭苮苰苲苳苵苶苸"],
["c680","苺苼",4,"茊茋茍茐茒茓茖茘茙茝",9,"茩茪茮茰茲茷茻茽啤脾疲皮匹痞僻屁譬篇偏片骗飘漂瓢票撇瞥拼频贫品聘乒坪苹萍平凭瓶评屏坡泼颇婆破魄迫粕剖扑铺仆莆葡菩蒲埔朴圃普浦谱曝瀑期欺栖戚妻七凄漆柒沏其棋奇歧畦崎脐齐旗祈祁骑起岂乞企启契砌器气迄弃汽泣讫掐"],
["c740","茾茿荁荂荄荅荈荊",4,"荓荕",4,"荝荢荰",6,"荹荺荾",6,"莇莈莊莋莌莍莏莐莑莔莕莖莗莙莚莝莟莡",6,"莬莭莮"],
["c780","莯莵莻莾莿菂菃菄菆菈菉菋菍菎菐菑菒菓菕菗菙菚菛菞菢菣菤菦菧菨菫菬菭恰洽牵扦钎铅千迁签仟谦乾黔钱钳前潜遣浅谴堑嵌欠歉枪呛腔羌墙蔷强抢橇锹敲悄桥瞧乔侨巧鞘撬翘峭俏窍切茄且怯窃钦侵亲秦琴勤芹擒禽寝沁青轻氢倾卿清擎晴氰情顷请庆琼穷秋丘邱球求囚酋泅趋区蛆曲躯屈驱渠"],
["c840","菮華菳",4,"菺菻菼菾菿萀萂萅萇萈萉萊萐萒",5,"萙萚萛萞",5,"萩",7,"萲",5,"萹萺萻萾",7,"葇葈葉"],
["c880","葊",6,"葒",4,"葘葝葞葟葠葢葤",4,"葪葮葯葰葲葴葷葹葻葼取娶龋趣去圈颧权醛泉全痊拳犬券劝缺炔瘸却鹊榷确雀裙群然燃冉染瓤壤攘嚷让饶扰绕惹热壬仁人忍韧任认刃妊纫扔仍日戎茸蓉荣融熔溶容绒冗揉柔肉茹蠕儒孺如辱乳汝入褥软阮蕊瑞锐闰润若弱撒洒萨腮鳃塞赛三叁"],
["c940","葽",4,"蒃蒄蒅蒆蒊蒍蒏",7,"蒘蒚蒛蒝蒞蒟蒠蒢",12,"蒰蒱蒳蒵蒶蒷蒻蒼蒾蓀蓂蓃蓅蓆蓇蓈蓋蓌蓎蓏蓒蓔蓕蓗"],
["c980","蓘",4,"蓞蓡蓢蓤蓧",4,"蓭蓮蓯蓱",10,"蓽蓾蔀蔁蔂伞散桑嗓丧搔骚扫嫂瑟色涩森僧莎砂杀刹沙纱傻啥煞筛晒珊苫杉山删煽衫闪陕擅赡膳善汕扇缮墒伤商赏晌上尚裳梢捎稍烧芍勺韶少哨邵绍奢赊蛇舌舍赦摄射慑涉社设砷申呻伸身深娠绅神沈审婶甚肾慎渗声生甥牲升绳"],
["ca40","蔃",8,"蔍蔎蔏蔐蔒蔔蔕蔖蔘蔙蔛蔜蔝蔞蔠蔢",8,"蔭",9,"蔾",4,"蕄蕅蕆蕇蕋",10],
["ca80","蕗蕘蕚蕛蕜蕝蕟",4,"蕥蕦蕧蕩",8,"蕳蕵蕶蕷蕸蕼蕽蕿薀薁省盛剩胜圣师失狮施湿诗尸虱十石拾时什食蚀实识史矢使屎驶始式示士世柿事拭誓逝势是嗜噬适仕侍释饰氏市恃室视试收手首守寿授售受瘦兽蔬枢梳殊抒输叔舒淑疏书赎孰熟薯暑曙署蜀黍鼠属术述树束戍竖墅庶数漱"],
["cb40","薂薃薆薈",6,"薐",10,"薝",6,"薥薦薧薩薫薬薭薱",5,"薸薺",6,"藂",6,"藊",4,"藑藒"],
["cb80","藔藖",5,"藝",6,"藥藦藧藨藪",14,"恕刷耍摔衰甩帅栓拴霜双爽谁水睡税吮瞬顺舜说硕朔烁斯撕嘶思私司丝死肆寺嗣四伺似饲巳松耸怂颂送宋讼诵搜艘擞嗽苏酥俗素速粟僳塑溯宿诉肃酸蒜算虽隋随绥髓碎岁穗遂隧祟孙损笋蓑梭唆缩琐索锁所塌他它她塔"],
["cc40","藹藺藼藽藾蘀",4,"蘆",10,"蘒蘓蘔蘕蘗",15,"蘨蘪",13,"蘹蘺蘻蘽蘾蘿虀"],
["cc80","虁",11,"虒虓處",4,"虛虜虝號虠虡虣",7,"獭挞蹋踏胎苔抬台泰酞太态汰坍摊贪瘫滩坛檀痰潭谭谈坦毯袒碳探叹炭汤塘搪堂棠膛唐糖倘躺淌趟烫掏涛滔绦萄桃逃淘陶讨套特藤腾疼誊梯剔踢锑提题蹄啼体替嚏惕涕剃屉天添填田甜恬舔腆挑条迢眺跳贴铁帖厅听烃"],
["cd40","虭虯虰虲",6,"蚃",6,"蚎",4,"蚔蚖",5,"蚞",4,"蚥蚦蚫蚭蚮蚲蚳蚷蚸蚹蚻",4,"蛁蛂蛃蛅蛈蛌蛍蛒蛓蛕蛖蛗蛚蛜"],
["cd80","蛝蛠蛡蛢蛣蛥蛦蛧蛨蛪蛫蛬蛯蛵蛶蛷蛺蛻蛼蛽蛿蜁蜄蜅蜆蜋蜌蜎蜏蜐蜑蜔蜖汀廷停亭庭挺艇通桐酮瞳同铜彤童桶捅筒统痛偷投头透凸秃突图徒途涂屠土吐兔湍团推颓腿蜕褪退吞屯臀拖托脱鸵陀驮驼椭妥拓唾挖哇蛙洼娃瓦袜歪外豌弯湾玩顽丸烷完碗挽晚皖惋宛婉万腕汪王亡枉网往旺望忘妄威"],
["ce40","蜙蜛蜝蜟蜠蜤蜦蜧蜨蜪蜫蜬蜭蜯蜰蜲蜳蜵蜶蜸蜹蜺蜼蜽蝀",6,"蝊蝋蝍蝏蝐蝑蝒蝔蝕蝖蝘蝚",5,"蝡蝢蝦",7,"蝯蝱蝲蝳蝵"],
["ce80","蝷蝸蝹蝺蝿螀螁螄螆螇螉螊螌螎",4,"螔螕螖螘",6,"螠",4,"巍微危韦违桅围唯惟为潍维苇萎委伟伪尾纬未蔚味畏胃喂魏位渭谓尉慰卫瘟温蚊文闻纹吻稳紊问嗡翁瓮挝蜗涡窝我斡卧握沃巫呜钨乌污诬屋无芜梧吾吴毋武五捂午舞伍侮坞戊雾晤物勿务悟误昔熙析西硒矽晰嘻吸锡牺"],
["cf40","螥螦螧螩螪螮螰螱螲螴螶螷螸螹螻螼螾螿蟁",4,"蟇蟈蟉蟌",4,"蟔",6,"蟜蟝蟞蟟蟡蟢蟣蟤蟦蟧蟨蟩蟫蟬蟭蟯",9],
["cf80","蟺蟻蟼蟽蟿蠀蠁蠂蠄",5,"蠋",7,"蠔蠗蠘蠙蠚蠜",4,"蠣稀息希悉膝夕惜熄烯溪汐犀檄袭席习媳喜铣洗系隙戏细瞎虾匣霞辖暇峡侠狭下厦夏吓掀锨先仙鲜纤咸贤衔舷闲涎弦嫌显险现献县腺馅羡宪陷限线相厢镶香箱襄湘乡翔祥详想响享项巷橡像向象萧硝霄削哮嚣销消宵淆晓"],
["d040","蠤",13,"蠳",5,"蠺蠻蠽蠾蠿衁衂衃衆",5,"衎",5,"衕衖衘衚",6,"衦衧衪衭衯衱衳衴衵衶衸衹衺"],
["d080","衻衼袀袃袆袇袉袊袌袎袏袐袑袓袔袕袗",4,"袝",4,"袣袥",5,"小孝校肖啸笑效楔些歇蝎鞋协挟携邪斜胁谐写械卸蟹懈泄泻谢屑薪芯锌欣辛新忻心信衅星腥猩惺兴刑型形邢行醒幸杏性姓兄凶胸匈汹雄熊休修羞朽嗅锈秀袖绣墟戌需虚嘘须徐许蓄酗叙旭序畜恤絮婿绪续轩喧宣悬旋玄"],
["d140","袬袮袯袰袲",4,"袸袹袺袻袽袾袿裀裃裄裇裈裊裋裌裍裏裐裑裓裖裗裚",4,"裠裡裦裧裩",6,"裲裵裶裷裺裻製裿褀褁褃",5],
["d180","褉褋",4,"褑褔",4,"褜",4,"褢褣褤褦褧褨褩褬褭褮褯褱褲褳褵褷选癣眩绚靴薛学穴雪血勋熏循旬询寻驯巡殉汛训讯逊迅压押鸦鸭呀丫芽牙蚜崖衙涯雅哑亚讶焉咽阉烟淹盐严研蜒岩延言颜阎炎沿奄掩眼衍演艳堰燕厌砚雁唁彦焰宴谚验殃央鸯秧杨扬佯疡羊洋阳氧仰痒养样漾邀腰妖瑶"],
["d240","褸",8,"襂襃襅",24,"襠",5,"襧",19,"襼"],
["d280","襽襾覀覂覄覅覇",26,"摇尧遥窑谣姚咬舀药要耀椰噎耶爷野冶也页掖业叶曳腋夜液一壹医揖铱依伊衣颐夷遗移仪胰疑沂宜姨彝椅蚁倚已乙矣以艺抑易邑屹亿役臆逸肄疫亦裔意毅忆义益溢诣议谊译异翼翌绎茵荫因殷音阴姻吟银淫寅饮尹引隐"],
["d340","覢",30,"觃觍觓觔觕觗觘觙觛觝觟觠觡觢觤觧觨觩觪觬觭觮觰觱觲觴",6],
["d380","觻",4,"訁",5,"計",21,"印英樱婴鹰应缨莹萤营荧蝇迎赢盈影颖硬映哟拥佣臃痈庸雍踊蛹咏泳涌永恿勇用幽优悠忧尤由邮铀犹油游酉有友右佑釉诱又幼迂淤于盂榆虞愚舆余俞逾鱼愉渝渔隅予娱雨与屿禹宇语羽玉域芋郁吁遇喻峪御愈欲狱育誉"],
["d440","訞",31,"訿",8,"詉",21],
["d480","詟",25,"詺",6,"浴寓裕预豫驭鸳渊冤元垣袁原援辕园员圆猿源缘远苑愿怨院曰约越跃钥岳粤月悦阅耘云郧匀陨允运蕴酝晕韵孕匝砸杂栽哉灾宰载再在咱攒暂赞赃脏葬遭糟凿藻枣早澡蚤躁噪造皂灶燥责择则泽贼怎增憎曾赠扎喳渣札轧"],
["d540","誁",7,"誋",7,"誔",46],
["d580","諃",32,"铡闸眨栅榨咋乍炸诈摘斋宅窄债寨瞻毡詹粘沾盏斩辗崭展蘸栈占战站湛绽樟章彰漳张掌涨杖丈帐账仗胀瘴障招昭找沼赵照罩兆肇召遮折哲蛰辙者锗蔗这浙珍斟真甄砧臻贞针侦枕疹诊震振镇阵蒸挣睁征狰争怔整拯正政"],
["d640","諤",34,"謈",27],
["d680","謤謥謧",30,"帧症郑证芝枝支吱蜘知肢脂汁之织职直植殖执值侄址指止趾只旨纸志挚掷至致置帜峙制智秩稚质炙痔滞治窒中盅忠钟衷终种肿重仲众舟周州洲诌粥轴肘帚咒皱宙昼骤珠株蛛朱猪诸诛逐竹烛煮拄瞩嘱主著柱助蛀贮铸筑"],
["d740","譆",31,"譧",4,"譭",25],
["d780","讇",24,"讬讱讻诇诐诪谉谞住注祝驻抓爪拽专砖转撰赚篆桩庄装妆撞壮状椎锥追赘坠缀谆准捉拙卓桌琢茁酌啄着灼浊兹咨资姿滋淄孜紫仔籽滓子自渍字鬃棕踪宗综总纵邹走奏揍租足卒族祖诅阻组钻纂嘴醉最罪尊遵昨左佐柞做作坐座"],
["d840","谸",8,"豂豃豄豅豈豊豋豍",7,"豖豗豘豙豛",5,"豣",6,"豬",6,"豴豵豶豷豻",6,"貃貄貆貇"],
["d880","貈貋貍",6,"貕貖貗貙",20,"亍丌兀丐廿卅丕亘丞鬲孬噩丨禺丿匕乇夭爻卮氐囟胤馗毓睾鼗丶亟鼐乜乩亓芈孛啬嘏仄厍厝厣厥厮靥赝匚叵匦匮匾赜卦卣刂刈刎刭刳刿剀剌剞剡剜蒯剽劂劁劐劓冂罔亻仃仉仂仨仡仫仞伛仳伢佤仵伥伧伉伫佞佧攸佚佝"],
["d940","貮",62],
["d980","賭",32,"佟佗伲伽佶佴侑侉侃侏佾佻侪佼侬侔俦俨俪俅俚俣俜俑俟俸倩偌俳倬倏倮倭俾倜倌倥倨偾偃偕偈偎偬偻傥傧傩傺僖儆僭僬僦僮儇儋仝氽佘佥俎龠汆籴兮巽黉馘冁夔勹匍訇匐凫夙兕亠兖亳衮袤亵脔裒禀嬴蠃羸冫冱冽冼"],
["da40","贎",14,"贠赑赒赗赟赥赨赩赪赬赮赯赱赲赸",8,"趂趃趆趇趈趉趌",4,"趒趓趕",9,"趠趡"],
["da80","趢趤",12,"趲趶趷趹趻趽跀跁跂跅跇跈跉跊跍跐跒跓跔凇冖冢冥讠讦讧讪讴讵讷诂诃诋诏诎诒诓诔诖诘诙诜诟诠诤诨诩诮诰诳诶诹诼诿谀谂谄谇谌谏谑谒谔谕谖谙谛谘谝谟谠谡谥谧谪谫谮谯谲谳谵谶卩卺阝阢阡阱阪阽阼陂陉陔陟陧陬陲陴隈隍隗隰邗邛邝邙邬邡邴邳邶邺"],
["db40","跕跘跙跜跠跡跢跥跦跧跩跭跮跰跱跲跴跶跼跾",6,"踆踇踈踋踍踎踐踑踒踓踕",7,"踠踡踤",4,"踫踭踰踲踳踴踶踷踸踻踼踾"],
["db80","踿蹃蹅蹆蹌",4,"蹓",5,"蹚",11,"蹧蹨蹪蹫蹮蹱邸邰郏郅邾郐郄郇郓郦郢郜郗郛郫郯郾鄄鄢鄞鄣鄱鄯鄹酃酆刍奂劢劬劭劾哿勐勖勰叟燮矍廴凵凼鬯厶弁畚巯坌垩垡塾墼壅壑圩圬圪圳圹圮圯坜圻坂坩垅坫垆坼坻坨坭坶坳垭垤垌垲埏垧垴垓垠埕埘埚埙埒垸埴埯埸埤埝"],
["dc40","蹳蹵蹷",4,"蹽蹾躀躂躃躄躆躈",6,"躑躒躓躕",6,"躝躟",11,"躭躮躰躱躳",6,"躻",7],
["dc80","軃",10,"軏",21,"堋堍埽埭堀堞堙塄堠塥塬墁墉墚墀馨鼙懿艹艽艿芏芊芨芄芎芑芗芙芫芸芾芰苈苊苣芘芷芮苋苌苁芩芴芡芪芟苄苎芤苡茉苷苤茏茇苜苴苒苘茌苻苓茑茚茆茔茕苠苕茜荑荛荜茈莒茼茴茱莛荞茯荏荇荃荟荀茗荠茭茺茳荦荥"],
["dd40","軥",62],
["dd80","輤",32,"荨茛荩荬荪荭荮莰荸莳莴莠莪莓莜莅荼莶莩荽莸荻莘莞莨莺莼菁萁菥菘堇萘萋菝菽菖萜萸萑萆菔菟萏萃菸菹菪菅菀萦菰菡葜葑葚葙葳蒇蒈葺蒉葸萼葆葩葶蒌蒎萱葭蓁蓍蓐蓦蒽蓓蓊蒿蒺蓠蒡蒹蒴蒗蓥蓣蔌甍蔸蓰蔹蔟蔺"],
["de40","轅",32,"轪辀辌辒辝辠辡辢辤辥辦辧辪辬辭辮辯農辳辴辵辷辸辺辻込辿迀迃迆"],
["de80","迉",4,"迏迒迖迗迚迠迡迣迧迬迯迱迲迴迵迶迺迻迼迾迿逇逈逌逎逓逕逘蕖蔻蓿蓼蕙蕈蕨蕤蕞蕺瞢蕃蕲蕻薤薨薇薏蕹薮薜薅薹薷薰藓藁藜藿蘧蘅蘩蘖蘼廾弈夼奁耷奕奚奘匏尢尥尬尴扌扪抟抻拊拚拗拮挢拶挹捋捃掭揶捱捺掎掴捭掬掊捩掮掼揲揸揠揿揄揞揎摒揆掾摅摁搋搛搠搌搦搡摞撄摭撖"],
["df40","這逜連逤逥逧",5,"逰",4,"逷逹逺逽逿遀遃遅遆遈",4,"過達違遖遙遚遜",5,"遤遦遧適遪遫遬遯",4,"遶",6,"遾邁"],
["df80","還邅邆邇邉邊邌",4,"邒邔邖邘邚邜邞邟邠邤邥邧邨邩邫邭邲邷邼邽邿郀摺撷撸撙撺擀擐擗擤擢攉攥攮弋忒甙弑卟叱叽叩叨叻吒吖吆呋呒呓呔呖呃吡呗呙吣吲咂咔呷呱呤咚咛咄呶呦咝哐咭哂咴哒咧咦哓哔呲咣哕咻咿哌哙哚哜咩咪咤哝哏哞唛哧唠哽唔哳唢唣唏唑唧唪啧喏喵啉啭啁啕唿啐唼"],
["e040","郂郃郆郈郉郋郌郍郒郔郕郖郘郙郚郞郟郠郣郤郥郩郪郬郮郰郱郲郳郵郶郷郹郺郻郼郿鄀鄁鄃鄅",19,"鄚鄛鄜"],
["e080","鄝鄟鄠鄡鄤",10,"鄰鄲",6,"鄺",8,"酄唷啖啵啶啷唳唰啜喋嗒喃喱喹喈喁喟啾嗖喑啻嗟喽喾喔喙嗪嗷嗉嘟嗑嗫嗬嗔嗦嗝嗄嗯嗥嗲嗳嗌嗍嗨嗵嗤辔嘞嘈嘌嘁嘤嘣嗾嘀嘧嘭噘嘹噗嘬噍噢噙噜噌噔嚆噤噱噫噻噼嚅嚓嚯囔囗囝囡囵囫囹囿圄圊圉圜帏帙帔帑帱帻帼"],
["e140","酅酇酈酑酓酔酕酖酘酙酛酜酟酠酦酧酨酫酭酳酺酻酼醀",4,"醆醈醊醎醏醓",6,"醜",5,"醤",5,"醫醬醰醱醲醳醶醷醸醹醻"],
["e180","醼",10,"釈釋釐釒",9,"針",8,"帷幄幔幛幞幡岌屺岍岐岖岈岘岙岑岚岜岵岢岽岬岫岱岣峁岷峄峒峤峋峥崂崃崧崦崮崤崞崆崛嵘崾崴崽嵬嵛嵯嵝嵫嵋嵊嵩嵴嶂嶙嶝豳嶷巅彳彷徂徇徉後徕徙徜徨徭徵徼衢彡犭犰犴犷犸狃狁狎狍狒狨狯狩狲狴狷猁狳猃狺"],
["e240","釦",62],
["e280","鈥",32,"狻猗猓猡猊猞猝猕猢猹猥猬猸猱獐獍獗獠獬獯獾舛夥飧夤夂饣饧",5,"饴饷饽馀馄馇馊馍馐馑馓馔馕庀庑庋庖庥庠庹庵庾庳赓廒廑廛廨廪膺忄忉忖忏怃忮怄忡忤忾怅怆忪忭忸怙怵怦怛怏怍怩怫怊怿怡恸恹恻恺恂"],
["e340","鉆",45,"鉵",16],
["e380","銆",7,"銏",24,"恪恽悖悚悭悝悃悒悌悛惬悻悱惝惘惆惚悴愠愦愕愣惴愀愎愫慊慵憬憔憧憷懔懵忝隳闩闫闱闳闵闶闼闾阃阄阆阈阊阋阌阍阏阒阕阖阗阙阚丬爿戕氵汔汜汊沣沅沐沔沌汨汩汴汶沆沩泐泔沭泷泸泱泗沲泠泖泺泫泮沱泓泯泾"],
["e440","銨",5,"銯",24,"鋉",31],
["e480","鋩",32,"洹洧洌浃浈洇洄洙洎洫浍洮洵洚浏浒浔洳涑浯涞涠浞涓涔浜浠浼浣渚淇淅淞渎涿淠渑淦淝淙渖涫渌涮渫湮湎湫溲湟溆湓湔渲渥湄滟溱溘滠漭滢溥溧溽溻溷滗溴滏溏滂溟潢潆潇漤漕滹漯漶潋潴漪漉漩澉澍澌潸潲潼潺濑"],
["e540","錊",51,"錿",10],
["e580","鍊",31,"鍫濉澧澹澶濂濡濮濞濠濯瀚瀣瀛瀹瀵灏灞宀宄宕宓宥宸甯骞搴寤寮褰寰蹇謇辶迓迕迥迮迤迩迦迳迨逅逄逋逦逑逍逖逡逵逶逭逯遄遑遒遐遨遘遢遛暹遴遽邂邈邃邋彐彗彖彘尻咫屐屙孱屣屦羼弪弩弭艴弼鬻屮妁妃妍妩妪妣"],
["e640","鍬",34,"鎐",27],
["e680","鎬",29,"鏋鏌鏍妗姊妫妞妤姒妲妯姗妾娅娆姝娈姣姘姹娌娉娲娴娑娣娓婀婧婊婕娼婢婵胬媪媛婷婺媾嫫媲嫒嫔媸嫠嫣嫱嫖嫦嫘嫜嬉嬗嬖嬲嬷孀尕尜孚孥孳孑孓孢驵驷驸驺驿驽骀骁骅骈骊骐骒骓骖骘骛骜骝骟骠骢骣骥骧纟纡纣纥纨纩"],
["e740","鏎",7,"鏗",54],
["e780","鐎",32,"纭纰纾绀绁绂绉绋绌绐绔绗绛绠绡绨绫绮绯绱绲缍绶绺绻绾缁缂缃缇缈缋缌缏缑缒缗缙缜缛缟缡",6,"缪缫缬缭缯",4,"缵幺畿巛甾邕玎玑玮玢玟珏珂珑玷玳珀珉珈珥珙顼琊珩珧珞玺珲琏琪瑛琦琥琨琰琮琬"],
["e840","鐯",14,"鐿",43,"鑬鑭鑮鑯"],
["e880","鑰",20,"钑钖钘铇铏铓铔铚铦铻锜锠琛琚瑁瑜瑗瑕瑙瑷瑭瑾璜璎璀璁璇璋璞璨璩璐璧瓒璺韪韫韬杌杓杞杈杩枥枇杪杳枘枧杵枨枞枭枋杷杼柰栉柘栊柩枰栌柙枵柚枳柝栀柃枸柢栎柁柽栲栳桠桡桎桢桄桤梃栝桕桦桁桧桀栾桊桉栩梵梏桴桷梓桫棂楮棼椟椠棹"],
["e940","锧锳锽镃镈镋镕镚镠镮镴镵長",7,"門",42],
["e980","閫",32,"椤棰椋椁楗棣椐楱椹楠楂楝榄楫榀榘楸椴槌榇榈槎榉楦楣楹榛榧榻榫榭槔榱槁槊槟榕槠榍槿樯槭樗樘橥槲橄樾檠橐橛樵檎橹樽樨橘橼檑檐檩檗檫猷獒殁殂殇殄殒殓殍殚殛殡殪轫轭轱轲轳轵轶轸轷轹轺轼轾辁辂辄辇辋"],
["ea40","闌",27,"闬闿阇阓阘阛阞阠阣",6,"阫阬阭阯阰阷阸阹阺阾陁陃陊陎陏陑陒陓陖陗"],
["ea80","陘陙陚陜陝陞陠陣陥陦陫陭",4,"陳陸",12,"隇隉隊辍辎辏辘辚軎戋戗戛戟戢戡戥戤戬臧瓯瓴瓿甏甑甓攴旮旯旰昊昙杲昃昕昀炅曷昝昴昱昶昵耆晟晔晁晏晖晡晗晷暄暌暧暝暾曛曜曦曩贲贳贶贻贽赀赅赆赈赉赇赍赕赙觇觊觋觌觎觏觐觑牮犟牝牦牯牾牿犄犋犍犏犒挈挲掰"],
["eb40","隌階隑隒隓隕隖隚際隝",9,"隨",7,"隱隲隴隵隷隸隺隻隿雂雃雈雊雋雐雑雓雔雖",9,"雡",6,"雫"],
["eb80","雬雭雮雰雱雲雴雵雸雺電雼雽雿霂霃霅霊霋霌霐霑霒霔霕霗",4,"霝霟霠搿擘耄毪毳毽毵毹氅氇氆氍氕氘氙氚氡氩氤氪氲攵敕敫牍牒牖爰虢刖肟肜肓肼朊肽肱肫肭肴肷胧胨胩胪胛胂胄胙胍胗朐胝胫胱胴胭脍脎胲胼朕脒豚脶脞脬脘脲腈腌腓腴腙腚腱腠腩腼腽腭腧塍媵膈膂膑滕膣膪臌朦臊膻"],
["ec40","霡",8,"霫霬霮霯霱霳",4,"霺霻霼霽霿",18,"靔靕靗靘靚靜靝靟靣靤靦靧靨靪",7],
["ec80","靲靵靷",4,"靽",7,"鞆",4,"鞌鞎鞏鞐鞓鞕鞖鞗鞙",4,"臁膦欤欷欹歃歆歙飑飒飓飕飙飚殳彀毂觳斐齑斓於旆旄旃旌旎旒旖炀炜炖炝炻烀炷炫炱烨烊焐焓焖焯焱煳煜煨煅煲煊煸煺熘熳熵熨熠燠燔燧燹爝爨灬焘煦熹戾戽扃扈扉礻祀祆祉祛祜祓祚祢祗祠祯祧祺禅禊禚禧禳忑忐"],
["ed40","鞞鞟鞡鞢鞤",6,"鞬鞮鞰鞱鞳鞵",46],
["ed80","韤韥韨韮",4,"韴韷",23,"怼恝恚恧恁恙恣悫愆愍慝憩憝懋懑戆肀聿沓泶淼矶矸砀砉砗砘砑斫砭砜砝砹砺砻砟砼砥砬砣砩硎硭硖硗砦硐硇硌硪碛碓碚碇碜碡碣碲碹碥磔磙磉磬磲礅磴礓礤礞礴龛黹黻黼盱眄眍盹眇眈眚眢眙眭眦眵眸睐睑睇睃睚睨"],
["ee40","頏",62],
["ee80","顎",32,"睢睥睿瞍睽瞀瞌瞑瞟瞠瞰瞵瞽町畀畎畋畈畛畲畹疃罘罡罟詈罨罴罱罹羁罾盍盥蠲钅钆钇钋钊钌钍钏钐钔钗钕钚钛钜钣钤钫钪钭钬钯钰钲钴钶",4,"钼钽钿铄铈",6,"铐铑铒铕铖铗铙铘铛铞铟铠铢铤铥铧铨铪"],
["ef40","顯",5,"颋颎颒颕颙颣風",37,"飏飐飔飖飗飛飜飝飠",4],
["ef80","飥飦飩",30,"铩铫铮铯铳铴铵铷铹铼铽铿锃锂锆锇锉锊锍锎锏锒",4,"锘锛锝锞锟锢锪锫锩锬锱锲锴锶锷锸锼锾锿镂锵镄镅镆镉镌镎镏镒镓镔镖镗镘镙镛镞镟镝镡镢镤",8,"镯镱镲镳锺矧矬雉秕秭秣秫稆嵇稃稂稞稔"],
["f040","餈",4,"餎餏餑",28,"餯",26],
["f080","饊",9,"饖",12,"饤饦饳饸饹饻饾馂馃馉稹稷穑黏馥穰皈皎皓皙皤瓞瓠甬鸠鸢鸨",4,"鸲鸱鸶鸸鸷鸹鸺鸾鹁鹂鹄鹆鹇鹈鹉鹋鹌鹎鹑鹕鹗鹚鹛鹜鹞鹣鹦",6,"鹱鹭鹳疒疔疖疠疝疬疣疳疴疸痄疱疰痃痂痖痍痣痨痦痤痫痧瘃痱痼痿瘐瘀瘅瘌瘗瘊瘥瘘瘕瘙"],
["f140","馌馎馚",10,"馦馧馩",47],
["f180","駙",32,"瘛瘼瘢瘠癀瘭瘰瘿瘵癃瘾瘳癍癞癔癜癖癫癯翊竦穸穹窀窆窈窕窦窠窬窨窭窳衤衩衲衽衿袂袢裆袷袼裉裢裎裣裥裱褚裼裨裾裰褡褙褓褛褊褴褫褶襁襦襻疋胥皲皴矜耒耔耖耜耠耢耥耦耧耩耨耱耋耵聃聆聍聒聩聱覃顸颀颃"],
["f240","駺",62],
["f280","騹",32,"颉颌颍颏颔颚颛颞颟颡颢颥颦虍虔虬虮虿虺虼虻蚨蚍蚋蚬蚝蚧蚣蚪蚓蚩蚶蛄蚵蛎蚰蚺蚱蚯蛉蛏蚴蛩蛱蛲蛭蛳蛐蜓蛞蛴蛟蛘蛑蜃蜇蛸蜈蜊蜍蜉蜣蜻蜞蜥蜮蜚蜾蝈蜴蜱蜩蜷蜿螂蜢蝽蝾蝻蝠蝰蝌蝮螋蝓蝣蝼蝤蝙蝥螓螯螨蟒"],
["f340","驚",17,"驲骃骉骍骎骔骕骙骦骩",6,"骲骳骴骵骹骻骽骾骿髃髄髆",4,"髍髎髏髐髒體髕髖髗髙髚髛髜"],
["f380","髝髞髠髢髣髤髥髧髨髩髪髬髮髰",8,"髺髼",6,"鬄鬅鬆蟆螈螅螭螗螃螫蟥螬螵螳蟋蟓螽蟑蟀蟊蟛蟪蟠蟮蠖蠓蟾蠊蠛蠡蠹蠼缶罂罄罅舐竺竽笈笃笄笕笊笫笏筇笸笪笙笮笱笠笥笤笳笾笞筘筚筅筵筌筝筠筮筻筢筲筱箐箦箧箸箬箝箨箅箪箜箢箫箴篑篁篌篝篚篥篦篪簌篾篼簏簖簋"],
["f440","鬇鬉",5,"鬐鬑鬒鬔",10,"鬠鬡鬢鬤",10,"鬰鬱鬳",7,"鬽鬾鬿魀魆魊魋魌魎魐魒魓魕",5],
["f480","魛",32,"簟簪簦簸籁籀臾舁舂舄臬衄舡舢舣舭舯舨舫舸舻舳舴舾艄艉艋艏艚艟艨衾袅袈裘裟襞羝羟羧羯羰羲籼敉粑粝粜粞粢粲粼粽糁糇糌糍糈糅糗糨艮暨羿翎翕翥翡翦翩翮翳糸絷綦綮繇纛麸麴赳趄趔趑趱赧赭豇豉酊酐酎酏酤"],
["f540","魼",62],
["f580","鮻",32,"酢酡酰酩酯酽酾酲酴酹醌醅醐醍醑醢醣醪醭醮醯醵醴醺豕鹾趸跫踅蹙蹩趵趿趼趺跄跖跗跚跞跎跏跛跆跬跷跸跣跹跻跤踉跽踔踝踟踬踮踣踯踺蹀踹踵踽踱蹉蹁蹂蹑蹒蹊蹰蹶蹼蹯蹴躅躏躔躐躜躞豸貂貊貅貘貔斛觖觞觚觜"],
["f640","鯜",62],
["f680","鰛",32,"觥觫觯訾謦靓雩雳雯霆霁霈霏霎霪霭霰霾龀龃龅",5,"龌黾鼋鼍隹隼隽雎雒瞿雠銎銮鋈錾鍪鏊鎏鐾鑫鱿鲂鲅鲆鲇鲈稣鲋鲎鲐鲑鲒鲔鲕鲚鲛鲞",5,"鲥",4,"鲫鲭鲮鲰",7,"鲺鲻鲼鲽鳄鳅鳆鳇鳊鳋"],
["f740","鰼",62],
["f780","鱻鱽鱾鲀鲃鲄鲉鲊鲌鲏鲓鲖鲗鲘鲙鲝鲪鲬鲯鲹鲾",4,"鳈鳉鳑鳒鳚鳛鳠鳡鳌",4,"鳓鳔鳕鳗鳘鳙鳜鳝鳟鳢靼鞅鞑鞒鞔鞯鞫鞣鞲鞴骱骰骷鹘骶骺骼髁髀髅髂髋髌髑魅魃魇魉魈魍魑飨餍餮饕饔髟髡髦髯髫髻髭髹鬈鬏鬓鬟鬣麽麾縻麂麇麈麋麒鏖麝麟黛黜黝黠黟黢黩黧黥黪黯鼢鼬鼯鼹鼷鼽鼾齄"],
["f840","鳣",62],
["f880","鴢",32],
["f940","鵃",62],
["f980","鶂",32],
["fa40","鶣",62],
["fa80","鷢",32],
["fb40","鸃",27,"鸤鸧鸮鸰鸴鸻鸼鹀鹍鹐鹒鹓鹔鹖鹙鹝鹟鹠鹡鹢鹥鹮鹯鹲鹴",9,"麀"],
["fb80","麁麃麄麅麆麉麊麌",5,"麔",8,"麞麠",5,"麧麨麩麪"],
["fc40","麫",8,"麵麶麷麹麺麼麿",4,"黅黆黇黈黊黋黌黐黒黓黕黖黗黙黚點黡黣黤黦黨黫黬黭黮黰",8,"黺黽黿",6],
["fc80","鼆",4,"鼌鼏鼑鼒鼔鼕鼖鼘鼚",5,"鼡鼣",8,"鼭鼮鼰鼱"],
["fd40","鼲",4,"鼸鼺鼼鼿",4,"齅",10,"齒",38],
["fd80","齹",5,"龁龂龍",11,"龜龝龞龡",4,"郎凉秊裏隣"],
["fe40","兀嗀﨎﨏﨑﨓﨔礼﨟蘒﨡﨣﨤﨧﨨﨩"]
]

},{}],20:[function(require,module,exports){
module.exports=[
["0","\u0000",127],
["8141","갂갃갅갆갋",4,"갘갞갟갡갢갣갥",6,"갮갲갳갴"],
["8161","갵갶갷갺갻갽갾갿걁",9,"걌걎",5,"걕"],
["8181","걖걗걙걚걛걝",18,"걲걳걵걶걹걻",4,"겂겇겈겍겎겏겑겒겓겕",6,"겞겢",5,"겫겭겮겱",6,"겺겾겿곀곂곃곅곆곇곉곊곋곍",7,"곖곘",7,"곢곣곥곦곩곫곭곮곲곴곷",4,"곾곿괁괂괃괅괇",4,"괎괐괒괓"],
["8241","괔괕괖괗괙괚괛괝괞괟괡",7,"괪괫괮",5],
["8261","괶괷괹괺괻괽",6,"굆굈굊",5,"굑굒굓굕굖굗"],
["8281","굙",7,"굢굤",7,"굮굯굱굲굷굸굹굺굾궀궃",4,"궊궋궍궎궏궑",10,"궞",5,"궥",17,"궸",7,"귂귃귅귆귇귉",6,"귒귔",7,"귝귞귟귡귢귣귥",18],
["8341","귺귻귽귾긂",5,"긊긌긎",5,"긕",7],
["8361","긝",18,"긲긳긵긶긹긻긼"],
["8381","긽긾긿깂깄깇깈깉깋깏깑깒깓깕깗",4,"깞깢깣깤깦깧깪깫깭깮깯깱",6,"깺깾",5,"꺆",5,"꺍",46,"꺿껁껂껃껅",6,"껎껒",5,"껚껛껝",8],
["8441","껦껧껩껪껬껮",5,"껵껶껷껹껺껻껽",8],
["8461","꼆꼉꼊꼋꼌꼎꼏꼑",18],
["8481","꼤",7,"꼮꼯꼱꼳꼵",6,"꼾꽀꽄꽅꽆꽇꽊",5,"꽑",10,"꽞",5,"꽦",18,"꽺",5,"꾁꾂꾃꾅꾆꾇꾉",6,"꾒꾓꾔꾖",5,"꾝",26,"꾺꾻꾽꾾"],
["8541","꾿꿁",5,"꿊꿌꿏",4,"꿕",6,"꿝",4],
["8561","꿢",5,"꿪",5,"꿲꿳꿵꿶꿷꿹",6,"뀂뀃"],
["8581","뀅",6,"뀍뀎뀏뀑뀒뀓뀕",6,"뀞",9,"뀩",26,"끆끇끉끋끍끏끐끑끒끖끘끚끛끜끞",29,"끾끿낁낂낃낅",6,"낎낐낒",5,"낛낝낞낣낤"],
["8641","낥낦낧낪낰낲낶낷낹낺낻낽",6,"냆냊",5,"냒"],
["8661","냓냕냖냗냙",6,"냡냢냣냤냦",10],
["8681","냱",22,"넊넍넎넏넑넔넕넖넗넚넞",4,"넦넧넩넪넫넭",6,"넶넺",5,"녂녃녅녆녇녉",6,"녒녓녖녗녙녚녛녝녞녟녡",22,"녺녻녽녾녿놁놃",4,"놊놌놎놏놐놑놕놖놗놙놚놛놝"],
["8741","놞",9,"놩",15],
["8761","놹",18,"뇍뇎뇏뇑뇒뇓뇕"],
["8781","뇖",5,"뇞뇠",7,"뇪뇫뇭뇮뇯뇱",7,"뇺뇼뇾",5,"눆눇눉눊눍",6,"눖눘눚",5,"눡",18,"눵",6,"눽",26,"뉙뉚뉛뉝뉞뉟뉡",6,"뉪",4],
["8841","뉯",4,"뉶",5,"뉽",6,"늆늇늈늊",4],
["8861","늏늒늓늕늖늗늛",4,"늢늤늧늨늩늫늭늮늯늱늲늳늵늶늷"],
["8881","늸",15,"닊닋닍닎닏닑닓",4,"닚닜닞닟닠닡닣닧닩닪닰닱닲닶닼닽닾댂댃댅댆댇댉",6,"댒댖",5,"댝",54,"덗덙덚덝덠덡덢덣"],
["8941","덦덨덪덬덭덯덲덳덵덶덷덹",6,"뎂뎆",5,"뎍"],
["8961","뎎뎏뎑뎒뎓뎕",10,"뎢",5,"뎩뎪뎫뎭"],
["8981","뎮",21,"돆돇돉돊돍돏돑돒돓돖돘돚돜돞돟돡돢돣돥돦돧돩",18,"돽",18,"됑",6,"됙됚됛됝됞됟됡",6,"됪됬",7,"됵",15],
["8a41","둅",10,"둒둓둕둖둗둙",6,"둢둤둦"],
["8a61","둧",4,"둭",18,"뒁뒂"],
["8a81","뒃",4,"뒉",19,"뒞",5,"뒥뒦뒧뒩뒪뒫뒭",7,"뒶뒸뒺",5,"듁듂듃듅듆듇듉",6,"듑듒듓듔듖",5,"듞듟듡듢듥듧",4,"듮듰듲",5,"듹",26,"딖딗딙딚딝"],
["8b41","딞",5,"딦딫",4,"딲딳딵딶딷딹",6,"땂땆"],
["8b61","땇땈땉땊땎땏땑땒땓땕",6,"땞땢",8],
["8b81","땫",52,"떢떣떥떦떧떩떬떭떮떯떲떶",4,"떾떿뗁뗂뗃뗅",6,"뗎뗒",5,"뗙",18,"뗭",18],
["8c41","똀",15,"똒똓똕똖똗똙",4],
["8c61","똞",6,"똦",5,"똭",6,"똵",5],
["8c81","똻",12,"뙉",26,"뙥뙦뙧뙩",50,"뚞뚟뚡뚢뚣뚥",5,"뚭뚮뚯뚰뚲",16],
["8d41","뛃",16,"뛕",8],
["8d61","뛞",17,"뛱뛲뛳뛵뛶뛷뛹뛺"],
["8d81","뛻",4,"뜂뜃뜄뜆",33,"뜪뜫뜭뜮뜱",6,"뜺뜼",7,"띅띆띇띉띊띋띍",6,"띖",9,"띡띢띣띥띦띧띩",6,"띲띴띶",5,"띾띿랁랂랃랅",6,"랎랓랔랕랚랛랝랞"],
["8e41","랟랡",6,"랪랮",5,"랶랷랹",8],
["8e61","럂",4,"럈럊",19],
["8e81","럞",13,"럮럯럱럲럳럵",6,"럾렂",4,"렊렋렍렎렏렑",6,"렚렜렞",5,"렦렧렩렪렫렭",6,"렶렺",5,"롁롂롃롅",11,"롒롔",7,"롞롟롡롢롣롥",6,"롮롰롲",5,"롹롺롻롽",7],
["8f41","뢅",7,"뢎",17],
["8f61","뢠",7,"뢩",6,"뢱뢲뢳뢵뢶뢷뢹",4],
["8f81","뢾뢿룂룄룆",5,"룍룎룏룑룒룓룕",7,"룞룠룢",5,"룪룫룭룮룯룱",6,"룺룼룾",5,"뤅",18,"뤙",6,"뤡",26,"뤾뤿륁륂륃륅",6,"륍륎륐륒",5],
["9041","륚륛륝륞륟륡",6,"륪륬륮",5,"륶륷륹륺륻륽"],
["9061","륾",5,"릆릈릋릌릏",15],
["9081","릟",12,"릮릯릱릲릳릵",6,"릾맀맂",5,"맊맋맍맓",4,"맚맜맟맠맢맦맧맩맪맫맭",6,"맶맻",4,"먂",5,"먉",11,"먖",33,"먺먻먽먾먿멁멃멄멅멆"],
["9141","멇멊멌멏멐멑멒멖멗멙멚멛멝",6,"멦멪",5],
["9161","멲멳멵멶멷멹",9,"몆몈몉몊몋몍",5],
["9181","몓",20,"몪몭몮몯몱몳",4,"몺몼몾",5,"뫅뫆뫇뫉",14,"뫚",33,"뫽뫾뫿묁묂묃묅",7,"묎묐묒",5,"묙묚묛묝묞묟묡",6],
["9241","묨묪묬",7,"묷묹묺묿",4,"뭆뭈뭊뭋뭌뭎뭑뭒"],
["9261","뭓뭕뭖뭗뭙",7,"뭢뭤",7,"뭭",4],
["9281","뭲",21,"뮉뮊뮋뮍뮎뮏뮑",18,"뮥뮦뮧뮩뮪뮫뮭",6,"뮵뮶뮸",7,"믁믂믃믅믆믇믉",6,"믑믒믔",35,"믺믻믽믾밁"],
["9341","밃",4,"밊밎밐밒밓밙밚밠밡밢밣밦밨밪밫밬밮밯밲밳밵"],
["9361","밶밷밹",6,"뱂뱆뱇뱈뱊뱋뱎뱏뱑",8],
["9381","뱚뱛뱜뱞",37,"벆벇벉벊벍벏",4,"벖벘벛",4,"벢벣벥벦벩",6,"벲벶",5,"벾벿볁볂볃볅",7,"볎볒볓볔볖볗볙볚볛볝",22,"볷볹볺볻볽"],
["9441","볾",5,"봆봈봊",5,"봑봒봓봕",8],
["9461","봞",5,"봥",6,"봭",12],
["9481","봺",5,"뵁",6,"뵊뵋뵍뵎뵏뵑",6,"뵚",9,"뵥뵦뵧뵩",22,"붂붃붅붆붋",4,"붒붔붖붗붘붛붝",6,"붥",10,"붱",6,"붹",24],
["9541","뷒뷓뷖뷗뷙뷚뷛뷝",11,"뷪",5,"뷱"],
["9561","뷲뷳뷵뷶뷷뷹",6,"븁븂븄븆",5,"븎븏븑븒븓"],
["9581","븕",6,"븞븠",35,"빆빇빉빊빋빍빏",4,"빖빘빜빝빞빟빢빣빥빦빧빩빫",4,"빲빶",4,"빾빿뺁뺂뺃뺅",6,"뺎뺒",5,"뺚",13,"뺩",14],
["9641","뺸",23,"뻒뻓"],
["9661","뻕뻖뻙",6,"뻡뻢뻦",5,"뻭",8],
["9681","뻶",10,"뼂",5,"뼊",13,"뼚뼞",33,"뽂뽃뽅뽆뽇뽉",6,"뽒뽓뽔뽖",44],
["9741","뾃",16,"뾕",8],
["9761","뾞",17,"뾱",7],
["9781","뾹",11,"뿆",5,"뿎뿏뿑뿒뿓뿕",6,"뿝뿞뿠뿢",89,"쀽쀾쀿"],
["9841","쁀",16,"쁒",5,"쁙쁚쁛"],
["9861","쁝쁞쁟쁡",6,"쁪",15],
["9881","쁺",21,"삒삓삕삖삗삙",6,"삢삤삦",5,"삮삱삲삷",4,"삾샂샃샄샆샇샊샋샍샎샏샑",6,"샚샞",5,"샦샧샩샪샫샭",6,"샶샸샺",5,"섁섂섃섅섆섇섉",6,"섑섒섓섔섖",5,"섡섢섥섨섩섪섫섮"],
["9941","섲섳섴섵섷섺섻섽섾섿셁",6,"셊셎",5,"셖셗"],
["9961","셙셚셛셝",6,"셦셪",5,"셱셲셳셵셶셷셹셺셻"],
["9981","셼",8,"솆",5,"솏솑솒솓솕솗",4,"솞솠솢솣솤솦솧솪솫솭솮솯솱",11,"솾",5,"쇅쇆쇇쇉쇊쇋쇍",6,"쇕쇖쇙",6,"쇡쇢쇣쇥쇦쇧쇩",6,"쇲쇴",7,"쇾쇿숁숂숃숅",6,"숎숐숒",5,"숚숛숝숞숡숢숣"],
["9a41","숤숥숦숧숪숬숮숰숳숵",16],
["9a61","쉆쉇쉉",6,"쉒쉓쉕쉖쉗쉙",6,"쉡쉢쉣쉤쉦"],
["9a81","쉧",4,"쉮쉯쉱쉲쉳쉵",6,"쉾슀슂",5,"슊",5,"슑",6,"슙슚슜슞",5,"슦슧슩슪슫슮",5,"슶슸슺",33,"싞싟싡싢싥",5,"싮싰싲싳싴싵싷싺싽싾싿쌁",6,"쌊쌋쌎쌏"],
["9b41","쌐쌑쌒쌖쌗쌙쌚쌛쌝",6,"쌦쌧쌪",8],
["9b61","쌳",17,"썆",7],
["9b81","썎",25,"썪썫썭썮썯썱썳",4,"썺썻썾",5,"쎅쎆쎇쎉쎊쎋쎍",50,"쏁",22,"쏚"],
["9c41","쏛쏝쏞쏡쏣",4,"쏪쏫쏬쏮",5,"쏶쏷쏹",5],
["9c61","쏿",8,"쐉",6,"쐑",9],
["9c81","쐛",8,"쐥",6,"쐭쐮쐯쐱쐲쐳쐵",6,"쐾",9,"쑉",26,"쑦쑧쑩쑪쑫쑭",6,"쑶쑷쑸쑺",5,"쒁",18,"쒕",6,"쒝",12],
["9d41","쒪",13,"쒹쒺쒻쒽",8],
["9d61","쓆",25],
["9d81","쓠",8,"쓪",5,"쓲쓳쓵쓶쓷쓹쓻쓼쓽쓾씂",9,"씍씎씏씑씒씓씕",6,"씝",10,"씪씫씭씮씯씱",6,"씺씼씾",5,"앆앇앋앏앐앑앒앖앚앛앜앟앢앣앥앦앧앩",6,"앲앶",5,"앾앿얁얂얃얅얆얈얉얊얋얎얐얒얓얔"],
["9e41","얖얙얚얛얝얞얟얡",7,"얪",9,"얶"],
["9e61","얷얺얿",4,"엋엍엏엒엓엕엖엗엙",6,"엢엤엦엧"],
["9e81","엨엩엪엫엯엱엲엳엵엸엹엺엻옂옃옄옉옊옋옍옎옏옑",6,"옚옝",6,"옦옧옩옪옫옯옱옲옶옸옺옼옽옾옿왂왃왅왆왇왉",6,"왒왖",5,"왞왟왡",10,"왭왮왰왲",5,"왺왻왽왾왿욁",6,"욊욌욎",5,"욖욗욙욚욛욝",6,"욦"],
["9f41","욨욪",5,"욲욳욵욶욷욻",4,"웂웄웆",5,"웎"],
["9f61","웏웑웒웓웕",6,"웞웟웢",5,"웪웫웭웮웯웱웲"],
["9f81","웳",4,"웺웻웼웾",5,"윆윇윉윊윋윍",6,"윖윘윚",5,"윢윣윥윦윧윩",6,"윲윴윶윸윹윺윻윾윿읁읂읃읅",4,"읋읎읐읙읚읛읝읞읟읡",6,"읩읪읬",7,"읶읷읹읺읻읿잀잁잂잆잋잌잍잏잒잓잕잙잛",4,"잢잧",4,"잮잯잱잲잳잵잶잷"],
["a041","잸잹잺잻잾쟂",5,"쟊쟋쟍쟏쟑",6,"쟙쟚쟛쟜"],
["a061","쟞",5,"쟥쟦쟧쟩쟪쟫쟭",13],
["a081","쟻",4,"젂젃젅젆젇젉젋",4,"젒젔젗",4,"젞젟젡젢젣젥",6,"젮젰젲",5,"젹젺젻젽젾젿졁",6,"졊졋졎",5,"졕",26,"졲졳졵졶졷졹졻",4,"좂좄좈좉좊좎",5,"좕",7,"좞좠좢좣좤"],
["a141","좥좦좧좩",18,"좾좿죀죁"],
["a161","죂죃죅죆죇죉죊죋죍",6,"죖죘죚",5,"죢죣죥"],
["a181","죦",14,"죶",5,"죾죿줁줂줃줇",4,"줎　、。·‥…¨〃­―∥＼∼‘’“”〔〕〈",9,"±×÷≠≤≥∞∴°′″℃Å￠￡￥♂♀∠⊥⌒∂∇≡≒§※☆★○●◎◇◆□■△▲▽▼→←↑↓↔〓≪≫√∽∝∵∫∬∈∋⊆⊇⊂⊃∪∩∧∨￢"],
["a241","줐줒",5,"줙",18],
["a261","줭",6,"줵",18],
["a281","쥈",7,"쥒쥓쥕쥖쥗쥙",6,"쥢쥤",7,"쥭쥮쥯⇒⇔∀∃´～ˇ˘˝˚˙¸˛¡¿ː∮∑∏¤℉‰◁◀▷▶♤♠♡♥♧♣⊙◈▣◐◑▒▤▥▨▧▦▩♨☏☎☜☞¶†‡↕↗↙↖↘♭♩♪♬㉿㈜№㏇™㏂㏘℡€®"],
["a341","쥱쥲쥳쥵",6,"쥽",10,"즊즋즍즎즏"],
["a361","즑",6,"즚즜즞",16],
["a381","즯",16,"짂짃짅짆짉짋",4,"짒짔짗짘짛！",58,"￦］",32,"￣"],
["a441","짞짟짡짣짥짦짨짩짪짫짮짲",5,"짺짻짽짾짿쨁쨂쨃쨄"],
["a461","쨅쨆쨇쨊쨎",5,"쨕쨖쨗쨙",12],
["a481","쨦쨧쨨쨪",28,"ㄱ",93],
["a541","쩇",4,"쩎쩏쩑쩒쩓쩕",6,"쩞쩢",5,"쩩쩪"],
["a561","쩫",17,"쩾",5,"쪅쪆"],
["a581","쪇",16,"쪙",14,"ⅰ",9],
["a5b0","Ⅰ",9],
["a5c1","Α",16,"Σ",6],
["a5e1","α",16,"σ",6],
["a641","쪨",19,"쪾쪿쫁쫂쫃쫅"],
["a661","쫆",5,"쫎쫐쫒쫔쫕쫖쫗쫚",5,"쫡",6],
["a681","쫨쫩쫪쫫쫭",6,"쫵",18,"쬉쬊─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂┒┑┚┙┖┕┎┍┞┟┡┢┦┧┩┪┭┮┱┲┵┶┹┺┽┾╀╁╃",7],
["a741","쬋",4,"쬑쬒쬓쬕쬖쬗쬙",6,"쬢",7],
["a761","쬪",22,"쭂쭃쭄"],
["a781","쭅쭆쭇쭊쭋쭍쭎쭏쭑",6,"쭚쭛쭜쭞",5,"쭥",7,"㎕㎖㎗ℓ㎘㏄㎣㎤㎥㎦㎙",9,"㏊㎍㎎㎏㏏㎈㎉㏈㎧㎨㎰",9,"㎀",4,"㎺",5,"㎐",4,"Ω㏀㏁㎊㎋㎌㏖㏅㎭㎮㎯㏛㎩㎪㎫㎬㏝㏐㏓㏃㏉㏜㏆"],
["a841","쭭",10,"쭺",14],
["a861","쮉",18,"쮝",6],
["a881","쮤",19,"쮹",11,"ÆÐªĦ"],
["a8a6","Ĳ"],
["a8a8","ĿŁØŒºÞŦŊ"],
["a8b1","㉠",27,"ⓐ",25,"①",14,"½⅓⅔¼¾⅛⅜⅝⅞"],
["a941","쯅",14,"쯕",10],
["a961","쯠쯡쯢쯣쯥쯦쯨쯪",18],
["a981","쯽",14,"찎찏찑찒찓찕",6,"찞찟찠찣찤æđðħıĳĸŀłøœßþŧŋŉ㈀",27,"⒜",25,"⑴",14,"¹²³⁴ⁿ₁₂₃₄"],
["aa41","찥찦찪찫찭찯찱",6,"찺찿",4,"챆챇챉챊챋챍챎"],
["aa61","챏",4,"챖챚",5,"챡챢챣챥챧챩",6,"챱챲"],
["aa81","챳챴챶",29,"ぁ",82],
["ab41","첔첕첖첗첚첛첝첞첟첡",6,"첪첮",5,"첶첷첹"],
["ab61","첺첻첽",6,"쳆쳈쳊",5,"쳑쳒쳓쳕",5],
["ab81","쳛",8,"쳥",6,"쳭쳮쳯쳱",12,"ァ",85],
["ac41","쳾쳿촀촂",5,"촊촋촍촎촏촑",6,"촚촜촞촟촠"],
["ac61","촡촢촣촥촦촧촩촪촫촭",11,"촺",4],
["ac81","촿",28,"쵝쵞쵟А",5,"ЁЖ",25],
["acd1","а",5,"ёж",25],
["ad41","쵡쵢쵣쵥",6,"쵮쵰쵲",5,"쵹",7],
["ad61","춁",6,"춉",10,"춖춗춙춚춛춝춞춟"],
["ad81","춠춡춢춣춦춨춪",5,"춱",18,"췅"],
["ae41","췆",5,"췍췎췏췑",16],
["ae61","췢",5,"췩췪췫췭췮췯췱",6,"췺췼췾",4],
["ae81","츃츅츆츇츉츊츋츍",6,"츕츖츗츘츚",5,"츢츣츥츦츧츩츪츫"],
["af41","츬츭츮츯츲츴츶",19],
["af61","칊",13,"칚칛칝칞칢",5,"칪칬"],
["af81","칮",5,"칶칷칹칺칻칽",6,"캆캈캊",5,"캒캓캕캖캗캙"],
["b041","캚",5,"캢캦",5,"캮",12],
["b061","캻",5,"컂",19],
["b081","컖",13,"컦컧컩컪컭",6,"컶컺",5,"가각간갇갈갉갊감",7,"같",4,"갠갤갬갭갯갰갱갸갹갼걀걋걍걔걘걜거걱건걷걸걺검겁것겄겅겆겉겊겋게겐겔겜겝겟겠겡겨격겪견겯결겸겹겻겼경곁계곈곌곕곗고곡곤곧골곪곬곯곰곱곳공곶과곽관괄괆"],
["b141","켂켃켅켆켇켉",6,"켒켔켖",5,"켝켞켟켡켢켣"],
["b161","켥",6,"켮켲",5,"켹",11],
["b181","콅",14,"콖콗콙콚콛콝",6,"콦콨콪콫콬괌괍괏광괘괜괠괩괬괭괴괵괸괼굄굅굇굉교굔굘굡굣구국군굳굴굵굶굻굼굽굿궁궂궈궉권궐궜궝궤궷귀귁귄귈귐귑귓규균귤그극근귿글긁금급긋긍긔기긱긴긷길긺김깁깃깅깆깊까깍깎깐깔깖깜깝깟깠깡깥깨깩깬깰깸"],
["b241","콭콮콯콲콳콵콶콷콹",6,"쾁쾂쾃쾄쾆",5,"쾍"],
["b261","쾎",18,"쾢",5,"쾩"],
["b281","쾪",5,"쾱",18,"쿅",6,"깹깻깼깽꺄꺅꺌꺼꺽꺾껀껄껌껍껏껐껑께껙껜껨껫껭껴껸껼꼇꼈꼍꼐꼬꼭꼰꼲꼴꼼꼽꼿꽁꽂꽃꽈꽉꽐꽜꽝꽤꽥꽹꾀꾄꾈꾐꾑꾕꾜꾸꾹꾼꿀꿇꿈꿉꿋꿍꿎꿔꿜꿨꿩꿰꿱꿴꿸뀀뀁뀄뀌뀐뀔뀜뀝뀨끄끅끈끊끌끎끓끔끕끗끙"],
["b341","쿌",19,"쿢쿣쿥쿦쿧쿩"],
["b361","쿪",5,"쿲쿴쿶",5,"쿽쿾쿿퀁퀂퀃퀅",5],
["b381","퀋",5,"퀒",5,"퀙",19,"끝끼끽낀낄낌낍낏낑나낙낚난낟날낡낢남납낫",4,"낱낳내낵낸낼냄냅냇냈냉냐냑냔냘냠냥너넉넋넌널넒넓넘넙넛넜넝넣네넥넨넬넴넵넷넸넹녀녁년녈념녑녔녕녘녜녠노녹논놀놂놈놉놋농높놓놔놘놜놨뇌뇐뇔뇜뇝"],
["b441","퀮",5,"퀶퀷퀹퀺퀻퀽",6,"큆큈큊",5],
["b461","큑큒큓큕큖큗큙",6,"큡",10,"큮큯"],
["b481","큱큲큳큵",6,"큾큿킀킂",18,"뇟뇨뇩뇬뇰뇹뇻뇽누눅눈눋눌눔눕눗눙눠눴눼뉘뉜뉠뉨뉩뉴뉵뉼늄늅늉느늑는늘늙늚늠늡늣능늦늪늬늰늴니닉닌닐닒님닙닛닝닢다닥닦단닫",4,"닳담답닷",4,"닿대댁댄댈댐댑댓댔댕댜더덕덖던덛덜덞덟덤덥"],
["b541","킕",14,"킦킧킩킪킫킭",5],
["b561","킳킶킸킺",5,"탂탃탅탆탇탊",5,"탒탖",4],
["b581","탛탞탟탡탢탣탥",6,"탮탲",5,"탹",11,"덧덩덫덮데덱덴델뎀뎁뎃뎄뎅뎌뎐뎔뎠뎡뎨뎬도독돈돋돌돎돐돔돕돗동돛돝돠돤돨돼됐되된될됨됩됫됴두둑둔둘둠둡둣둥둬뒀뒈뒝뒤뒨뒬뒵뒷뒹듀듄듈듐듕드득든듣들듦듬듭듯등듸디딕딘딛딜딤딥딧딨딩딪따딱딴딸"],
["b641","턅",7,"턎",17],
["b661","턠",15,"턲턳턵턶턷턹턻턼턽턾"],
["b681","턿텂텆",5,"텎텏텑텒텓텕",6,"텞텠텢",5,"텩텪텫텭땀땁땃땄땅땋때땍땐땔땜땝땟땠땡떠떡떤떨떪떫떰떱떳떴떵떻떼떽뗀뗄뗌뗍뗏뗐뗑뗘뗬또똑똔똘똥똬똴뙈뙤뙨뚜뚝뚠뚤뚫뚬뚱뛔뛰뛴뛸뜀뜁뜅뜨뜩뜬뜯뜰뜸뜹뜻띄띈띌띔띕띠띤띨띰띱띳띵라락란랄람랍랏랐랑랒랖랗"],
["b741","텮",13,"텽",6,"톅톆톇톉톊"],
["b761","톋",20,"톢톣톥톦톧"],
["b781","톩",6,"톲톴톶톷톸톹톻톽톾톿퇁",14,"래랙랜랠램랩랫랬랭랴략랸럇량러럭런럴럼럽럿렀렁렇레렉렌렐렘렙렛렝려력련렬렴렵렷렸령례롄롑롓로록론롤롬롭롯롱롸롼뢍뢨뢰뢴뢸룀룁룃룅료룐룔룝룟룡루룩룬룰룸룹룻룽뤄뤘뤠뤼뤽륀륄륌륏륑류륙륜률륨륩"],
["b841","퇐",7,"퇙",17],
["b861","퇫",8,"퇵퇶퇷퇹",13],
["b881","툈툊",5,"툑",24,"륫륭르륵른를름릅릇릉릊릍릎리릭린릴림립릿링마막만많",4,"맘맙맛망맞맡맣매맥맨맬맴맵맷맸맹맺먀먁먈먕머먹먼멀멂멈멉멋멍멎멓메멕멘멜멤멥멧멨멩며멱면멸몃몄명몇몌모목몫몬몰몲몸몹못몽뫄뫈뫘뫙뫼"],
["b941","툪툫툮툯툱툲툳툵",6,"툾퉀퉂",5,"퉉퉊퉋퉌"],
["b961","퉍",14,"퉝",6,"퉥퉦퉧퉨"],
["b981","퉩",22,"튂튃튅튆튇튉튊튋튌묀묄묍묏묑묘묜묠묩묫무묵묶문묻물묽묾뭄뭅뭇뭉뭍뭏뭐뭔뭘뭡뭣뭬뮈뮌뮐뮤뮨뮬뮴뮷므믄믈믐믓미믹민믿밀밂밈밉밋밌밍및밑바",4,"받",4,"밤밥밧방밭배백밴밸뱀뱁뱃뱄뱅뱉뱌뱍뱐뱝버벅번벋벌벎범법벗"],
["ba41","튍튎튏튒튓튔튖",5,"튝튞튟튡튢튣튥",6,"튭"],
["ba61","튮튯튰튲",5,"튺튻튽튾틁틃",4,"틊틌",5],
["ba81","틒틓틕틖틗틙틚틛틝",6,"틦",9,"틲틳틵틶틷틹틺벙벚베벡벤벧벨벰벱벳벴벵벼벽변별볍볏볐병볕볘볜보복볶본볼봄봅봇봉봐봔봤봬뵀뵈뵉뵌뵐뵘뵙뵤뵨부북분붇불붉붊붐붑붓붕붙붚붜붤붰붸뷔뷕뷘뷜뷩뷰뷴뷸븀븃븅브븍븐블븜븝븟비빅빈빌빎빔빕빗빙빚빛빠빡빤"],
["bb41","틻",4,"팂팄팆",5,"팏팑팒팓팕팗",4,"팞팢팣"],
["bb61","팤팦팧팪팫팭팮팯팱",6,"팺팾",5,"퍆퍇퍈퍉"],
["bb81","퍊",31,"빨빪빰빱빳빴빵빻빼빽뺀뺄뺌뺍뺏뺐뺑뺘뺙뺨뻐뻑뻔뻗뻘뻠뻣뻤뻥뻬뼁뼈뼉뼘뼙뼛뼜뼝뽀뽁뽄뽈뽐뽑뽕뾔뾰뿅뿌뿍뿐뿔뿜뿟뿡쀼쁑쁘쁜쁠쁨쁩삐삑삔삘삠삡삣삥사삭삯산삳살삵삶삼삽삿샀상샅새색샌샐샘샙샛샜생샤"],
["bc41","퍪",17,"퍾퍿펁펂펃펅펆펇"],
["bc61","펈펉펊펋펎펒",5,"펚펛펝펞펟펡",6,"펪펬펮"],
["bc81","펯",4,"펵펶펷펹펺펻펽",6,"폆폇폊",5,"폑",5,"샥샨샬샴샵샷샹섀섄섈섐섕서",4,"섣설섦섧섬섭섯섰성섶세섹센셀셈셉셋셌셍셔셕션셜셤셥셧셨셩셰셴셸솅소속솎손솔솖솜솝솟송솥솨솩솬솰솽쇄쇈쇌쇔쇗쇘쇠쇤쇨쇰쇱쇳쇼쇽숀숄숌숍숏숑수숙순숟술숨숩숫숭"],
["bd41","폗폙",7,"폢폤",7,"폮폯폱폲폳폵폶폷"],
["bd61","폸폹폺폻폾퐀퐂",5,"퐉",13],
["bd81","퐗",5,"퐞",25,"숯숱숲숴쉈쉐쉑쉔쉘쉠쉥쉬쉭쉰쉴쉼쉽쉿슁슈슉슐슘슛슝스슥슨슬슭슴습슷승시식신싣실싫심십싯싱싶싸싹싻싼쌀쌈쌉쌌쌍쌓쌔쌕쌘쌜쌤쌥쌨쌩썅써썩썬썰썲썸썹썼썽쎄쎈쎌쏀쏘쏙쏜쏟쏠쏢쏨쏩쏭쏴쏵쏸쐈쐐쐤쐬쐰"],
["be41","퐸",7,"푁푂푃푅",14],
["be61","푔",7,"푝푞푟푡푢푣푥",7,"푮푰푱푲"],
["be81","푳",4,"푺푻푽푾풁풃",4,"풊풌풎",5,"풕",8,"쐴쐼쐽쑈쑤쑥쑨쑬쑴쑵쑹쒀쒔쒜쒸쒼쓩쓰쓱쓴쓸쓺쓿씀씁씌씐씔씜씨씩씬씰씸씹씻씽아악안앉않알앍앎앓암압앗았앙앝앞애액앤앨앰앱앳앴앵야약얀얄얇얌얍얏양얕얗얘얜얠얩어억언얹얻얼얽얾엄",6,"엌엎"],
["bf41","풞",10,"풪",14],
["bf61","풹",18,"퓍퓎퓏퓑퓒퓓퓕"],
["bf81","퓖",5,"퓝퓞퓠",7,"퓩퓪퓫퓭퓮퓯퓱",6,"퓹퓺퓼에엑엔엘엠엡엣엥여역엮연열엶엷염",5,"옅옆옇예옌옐옘옙옛옜오옥온올옭옮옰옳옴옵옷옹옻와왁완왈왐왑왓왔왕왜왝왠왬왯왱외왹왼욀욈욉욋욍요욕욘욜욤욥욧용우욱운울욹욺움웁웃웅워웍원월웜웝웠웡웨"],
["c041","퓾",5,"픅픆픇픉픊픋픍",6,"픖픘",5],
["c061","픞",25],
["c081","픸픹픺픻픾픿핁핂핃핅",6,"핎핐핒",5,"핚핛핝핞핟핡핢핣웩웬웰웸웹웽위윅윈윌윔윕윗윙유육윤율윰윱윳융윷으윽은을읊음읍읏응",7,"읜읠읨읫이익인일읽읾잃임입잇있잉잊잎자작잔잖잗잘잚잠잡잣잤장잦재잭잰잴잼잽잿쟀쟁쟈쟉쟌쟎쟐쟘쟝쟤쟨쟬저적전절젊"],
["c141","핤핦핧핪핬핮",5,"핶핷핹핺핻핽",6,"햆햊햋"],
["c161","햌햍햎햏햑",19,"햦햧"],
["c181","햨",31,"점접젓정젖제젝젠젤젬젭젯젱져젼졀졈졉졌졍졔조족존졸졺좀좁좃종좆좇좋좌좍좔좝좟좡좨좼좽죄죈죌죔죕죗죙죠죡죤죵주죽준줄줅줆줌줍줏중줘줬줴쥐쥑쥔쥘쥠쥡쥣쥬쥰쥴쥼즈즉즌즐즘즙즛증지직진짇질짊짐집짓"],
["c241","헊헋헍헎헏헑헓",4,"헚헜헞",5,"헦헧헩헪헫헭헮"],
["c261","헯",4,"헶헸헺",5,"혂혃혅혆혇혉",6,"혒"],
["c281","혖",5,"혝혞혟혡혢혣혥",7,"혮",9,"혺혻징짖짙짚짜짝짠짢짤짧짬짭짯짰짱째짹짼쨀쨈쨉쨋쨌쨍쨔쨘쨩쩌쩍쩐쩔쩜쩝쩟쩠쩡쩨쩽쪄쪘쪼쪽쫀쫄쫌쫍쫏쫑쫓쫘쫙쫠쫬쫴쬈쬐쬔쬘쬠쬡쭁쭈쭉쭌쭐쭘쭙쭝쭤쭸쭹쮜쮸쯔쯤쯧쯩찌찍찐찔찜찝찡찢찧차착찬찮찰참찹찻"],
["c341","혽혾혿홁홂홃홄홆홇홊홌홎홏홐홒홓홖홗홙홚홛홝",4],
["c361","홢",4,"홨홪",5,"홲홳홵",11],
["c381","횁횂횄횆",5,"횎횏횑횒횓횕",7,"횞횠횢",5,"횩횪찼창찾채책챈챌챔챕챗챘챙챠챤챦챨챰챵처척천철첨첩첫첬청체첵첸첼쳄쳅쳇쳉쳐쳔쳤쳬쳰촁초촉촌촐촘촙촛총촤촨촬촹최쵠쵤쵬쵭쵯쵱쵸춈추축춘출춤춥춧충춰췄췌췐취췬췰췸췹췻췽츄츈츌츔츙츠측츤츨츰츱츳층"],
["c441","횫횭횮횯횱",7,"횺횼",7,"훆훇훉훊훋"],
["c461","훍훎훏훐훒훓훕훖훘훚",5,"훡훢훣훥훦훧훩",4],
["c481","훮훯훱훲훳훴훶",5,"훾훿휁휂휃휅",11,"휒휓휔치칙친칟칠칡침칩칫칭카칵칸칼캄캅캇캉캐캑캔캘캠캡캣캤캥캬캭컁커컥컨컫컬컴컵컷컸컹케켁켄켈켐켑켓켕켜켠켤켬켭켯켰켱켸코콕콘콜콤콥콧콩콰콱콴콸쾀쾅쾌쾡쾨쾰쿄쿠쿡쿤쿨쿰쿱쿳쿵쿼퀀퀄퀑퀘퀭퀴퀵퀸퀼"],
["c541","휕휖휗휚휛휝휞휟휡",6,"휪휬휮",5,"휶휷휹"],
["c561","휺휻휽",6,"흅흆흈흊",5,"흒흓흕흚",4],
["c581","흟흢흤흦흧흨흪흫흭흮흯흱흲흳흵",6,"흾흿힀힂",5,"힊힋큄큅큇큉큐큔큘큠크큭큰클큼큽킁키킥킨킬킴킵킷킹타탁탄탈탉탐탑탓탔탕태택탠탤탬탭탯탰탱탸턍터턱턴털턺텀텁텃텄텅테텍텐텔템텝텟텡텨텬텼톄톈토톡톤톨톰톱톳통톺톼퇀퇘퇴퇸툇툉툐투툭툰툴툼툽툿퉁퉈퉜"],
["c641","힍힎힏힑",6,"힚힜힞",5],
["c6a1","퉤튀튁튄튈튐튑튕튜튠튤튬튱트특튼튿틀틂틈틉틋틔틘틜틤틥티틱틴틸팀팁팃팅파팍팎판팔팖팜팝팟팠팡팥패팩팬팰팸팹팻팼팽퍄퍅퍼퍽펀펄펌펍펏펐펑페펙펜펠펨펩펫펭펴편펼폄폅폈평폐폘폡폣포폭폰폴폼폽폿퐁"],
["c7a1","퐈퐝푀푄표푠푤푭푯푸푹푼푿풀풂품풉풋풍풔풩퓌퓐퓔퓜퓟퓨퓬퓰퓸퓻퓽프픈플픔픕픗피픽핀필핌핍핏핑하학한할핥함합핫항해핵핸핼햄햅햇했행햐향허헉헌헐헒험헙헛헝헤헥헨헬헴헵헷헹혀혁현혈혐협혓혔형혜혠"],
["c8a1","혤혭호혹혼홀홅홈홉홋홍홑화확환활홧황홰홱홴횃횅회획횐횔횝횟횡효횬횰횹횻후훅훈훌훑훔훗훙훠훤훨훰훵훼훽휀휄휑휘휙휜휠휨휩휫휭휴휵휸휼흄흇흉흐흑흔흖흗흘흙흠흡흣흥흩희흰흴흼흽힁히힉힌힐힘힙힛힝"],
["caa1","伽佳假價加可呵哥嘉嫁家暇架枷柯歌珂痂稼苛茄街袈訶賈跏軻迦駕刻却各恪慤殼珏脚覺角閣侃刊墾奸姦干幹懇揀杆柬桿澗癎看磵稈竿簡肝艮艱諫間乫喝曷渴碣竭葛褐蝎鞨勘坎堪嵌感憾戡敢柑橄減甘疳監瞰紺邯鑑鑒龕"],
["cba1","匣岬甲胛鉀閘剛堈姜岡崗康强彊慷江畺疆糠絳綱羌腔舡薑襁講鋼降鱇介价個凱塏愷愾慨改槪漑疥皆盖箇芥蓋豈鎧開喀客坑更粳羹醵倨去居巨拒据據擧渠炬祛距踞車遽鉅鋸乾件健巾建愆楗腱虔蹇鍵騫乞傑杰桀儉劍劒檢"],
["cca1","瞼鈐黔劫怯迲偈憩揭擊格檄激膈覡隔堅牽犬甄絹繭肩見譴遣鵑抉決潔結缺訣兼慊箝謙鉗鎌京俓倞傾儆勁勍卿坰境庚徑慶憬擎敬景暻更梗涇炅烱璟璥瓊痙硬磬竟競絅經耕耿脛莖警輕逕鏡頃頸驚鯨係啓堺契季屆悸戒桂械"],
["cda1","棨溪界癸磎稽系繫繼計誡谿階鷄古叩告呱固姑孤尻庫拷攷故敲暠枯槁沽痼皐睾稿羔考股膏苦苽菰藁蠱袴誥賈辜錮雇顧高鼓哭斛曲梏穀谷鵠困坤崑昆梱棍滾琨袞鯤汨滑骨供公共功孔工恐恭拱控攻珙空蚣貢鞏串寡戈果瓜"],
["cea1","科菓誇課跨過鍋顆廓槨藿郭串冠官寬慣棺款灌琯瓘管罐菅觀貫關館刮恝括适侊光匡壙廣曠洸炚狂珖筐胱鑛卦掛罫乖傀塊壞怪愧拐槐魁宏紘肱轟交僑咬喬嬌嶠巧攪敎校橋狡皎矯絞翹膠蕎蛟較轎郊餃驕鮫丘久九仇俱具勾"],
["cfa1","區口句咎嘔坵垢寇嶇廐懼拘救枸柩構歐毆毬求溝灸狗玖球瞿矩究絿耉臼舅舊苟衢謳購軀逑邱鉤銶駒驅鳩鷗龜國局菊鞠鞫麴君窘群裙軍郡堀屈掘窟宮弓穹窮芎躬倦券勸卷圈拳捲權淃眷厥獗蕨蹶闕机櫃潰詭軌饋句晷歸貴"],
["d0a1","鬼龜叫圭奎揆槻珪硅窺竅糾葵規赳逵閨勻均畇筠菌鈞龜橘克剋劇戟棘極隙僅劤勤懃斤根槿瑾筋芹菫覲謹近饉契今妗擒昑檎琴禁禽芩衾衿襟金錦伋及急扱汲級給亘兢矜肯企伎其冀嗜器圻基埼夔奇妓寄岐崎己幾忌技旗旣"],
["d1a1","朞期杞棋棄機欺氣汽沂淇玘琦琪璂璣畸畿碁磯祁祇祈祺箕紀綺羈耆耭肌記譏豈起錡錤飢饑騎騏驥麒緊佶吉拮桔金喫儺喇奈娜懦懶拏拿癩",5,"那樂",4,"諾酪駱亂卵暖欄煖爛蘭難鸞捏捺南嵐枏楠湳濫男藍襤拉"],
["d2a1","納臘蠟衲囊娘廊",4,"乃來內奈柰耐冷女年撚秊念恬拈捻寧寗努勞奴弩怒擄櫓爐瑙盧",5,"駑魯",10,"濃籠聾膿農惱牢磊腦賂雷尿壘",7,"嫩訥杻紐勒",5,"能菱陵尼泥匿溺多茶"],
["d3a1","丹亶但單團壇彖斷旦檀段湍短端簞緞蛋袒鄲鍛撻澾獺疸達啖坍憺擔曇淡湛潭澹痰聃膽蕁覃談譚錟沓畓答踏遝唐堂塘幢戇撞棠當糖螳黨代垈坮大對岱帶待戴擡玳臺袋貸隊黛宅德悳倒刀到圖堵塗導屠島嶋度徒悼挑掉搗桃"],
["d4a1","棹櫂淘渡滔濤燾盜睹禱稻萄覩賭跳蹈逃途道都鍍陶韜毒瀆牘犢獨督禿篤纛讀墩惇敦旽暾沌焞燉豚頓乭突仝冬凍動同憧東桐棟洞潼疼瞳童胴董銅兜斗杜枓痘竇荳讀豆逗頭屯臀芚遁遯鈍得嶝橙燈登等藤謄鄧騰喇懶拏癩羅"],
["d5a1","蘿螺裸邏樂洛烙珞絡落諾酪駱丹亂卵欄欒瀾爛蘭鸞剌辣嵐擥攬欖濫籃纜藍襤覽拉臘蠟廊朗浪狼琅瑯螂郞來崍徠萊冷掠略亮倆兩凉梁樑粮粱糧良諒輛量侶儷勵呂廬慮戾旅櫚濾礪藜蠣閭驢驪麗黎力曆歷瀝礫轢靂憐戀攣漣"],
["d6a1","煉璉練聯蓮輦連鍊冽列劣洌烈裂廉斂殮濂簾獵令伶囹寧岺嶺怜玲笭羚翎聆逞鈴零靈領齡例澧禮醴隷勞怒撈擄櫓潞瀘爐盧老蘆虜路輅露魯鷺鹵碌祿綠菉錄鹿麓論壟弄朧瀧瓏籠聾儡瀨牢磊賂賚賴雷了僚寮廖料燎療瞭聊蓼"],
["d7a1","遼鬧龍壘婁屢樓淚漏瘻累縷蔞褸鏤陋劉旒柳榴流溜瀏琉瑠留瘤硫謬類六戮陸侖倫崙淪綸輪律慄栗率隆勒肋凜凌楞稜綾菱陵俚利厘吏唎履悧李梨浬犁狸理璃異痢籬罹羸莉裏裡里釐離鯉吝潾燐璘藺躪隣鱗麟林淋琳臨霖砬"],
["d8a1","立笠粒摩瑪痲碼磨馬魔麻寞幕漠膜莫邈万卍娩巒彎慢挽晩曼滿漫灣瞞萬蔓蠻輓饅鰻唜抹末沫茉襪靺亡妄忘忙望網罔芒茫莽輞邙埋妹媒寐昧枚梅每煤罵買賣邁魅脈貊陌驀麥孟氓猛盲盟萌冪覓免冕勉棉沔眄眠綿緬面麵滅"],
["d9a1","蔑冥名命明暝椧溟皿瞑茗蓂螟酩銘鳴袂侮冒募姆帽慕摸摹暮某模母毛牟牡瑁眸矛耗芼茅謀謨貌木沐牧目睦穆鶩歿沒夢朦蒙卯墓妙廟描昴杳渺猫竗苗錨務巫憮懋戊拇撫无楙武毋無珷畝繆舞茂蕪誣貿霧鵡墨默們刎吻問文"],
["daa1","汶紊紋聞蚊門雯勿沕物味媚尾嵋彌微未梶楣渼湄眉米美薇謎迷靡黴岷悶愍憫敏旻旼民泯玟珉緡閔密蜜謐剝博拍搏撲朴樸泊珀璞箔粕縛膊舶薄迫雹駁伴半反叛拌搬攀斑槃泮潘班畔瘢盤盼磐磻礬絆般蟠返頒飯勃拔撥渤潑"],
["dba1","發跋醱鉢髮魃倣傍坊妨尨幇彷房放方旁昉枋榜滂磅紡肪膀舫芳蒡蚌訪謗邦防龐倍俳北培徘拜排杯湃焙盃背胚裴裵褙賠輩配陪伯佰帛柏栢白百魄幡樊煩燔番磻繁蕃藩飜伐筏罰閥凡帆梵氾汎泛犯範范法琺僻劈壁擘檗璧癖"],
["dca1","碧蘗闢霹便卞弁變辨辯邊別瞥鱉鼈丙倂兵屛幷昞昺柄棅炳甁病秉竝輧餠騈保堡報寶普步洑湺潽珤甫菩補褓譜輔伏僕匐卜宓復服福腹茯蔔複覆輹輻馥鰒本乶俸奉封峯峰捧棒烽熢琫縫蓬蜂逢鋒鳳不付俯傅剖副否咐埠夫婦"],
["dda1","孚孵富府復扶敷斧浮溥父符簿缶腐腑膚艀芙莩訃負賦賻赴趺部釜阜附駙鳧北分吩噴墳奔奮忿憤扮昐汾焚盆粉糞紛芬賁雰不佛弗彿拂崩朋棚硼繃鵬丕備匕匪卑妃婢庇悲憊扉批斐枇榧比毖毗毘沸泌琵痺砒碑秕秘粃緋翡肥"],
["dea1","脾臂菲蜚裨誹譬費鄙非飛鼻嚬嬪彬斌檳殯浜濱瀕牝玭貧賓頻憑氷聘騁乍事些仕伺似使俟僿史司唆嗣四士奢娑寫寺射巳師徙思捨斜斯柶査梭死沙泗渣瀉獅砂社祀祠私篩紗絲肆舍莎蓑蛇裟詐詞謝賜赦辭邪飼駟麝削數朔索"],
["dfa1","傘刪山散汕珊産疝算蒜酸霰乷撒殺煞薩三參杉森渗芟蔘衫揷澁鈒颯上傷像償商喪嘗孀尙峠常床庠廂想桑橡湘爽牀狀相祥箱翔裳觴詳象賞霜塞璽賽嗇塞穡索色牲生甥省笙墅壻嶼序庶徐恕抒捿敍暑曙書栖棲犀瑞筮絮緖署"],
["e0a1","胥舒薯西誓逝鋤黍鼠夕奭席惜昔晳析汐淅潟石碩蓆釋錫仙僊先善嬋宣扇敾旋渲煽琁瑄璇璿癬禪線繕羨腺膳船蘚蟬詵跣選銑鐥饍鮮卨屑楔泄洩渫舌薛褻設說雪齧剡暹殲纖蟾贍閃陝攝涉燮葉城姓宬性惺成星晟猩珹盛省筬"],
["e1a1","聖聲腥誠醒世勢歲洗稅笹細說貰召嘯塑宵小少巢所掃搔昭梳沼消溯瀟炤燒甦疏疎瘙笑篠簫素紹蔬蕭蘇訴逍遡邵銷韶騷俗屬束涑粟續謖贖速孫巽損蓀遜飡率宋悚松淞訟誦送頌刷殺灑碎鎖衰釗修受嗽囚垂壽嫂守岫峀帥愁"],
["e2a1","戍手授搜收數樹殊水洙漱燧狩獸琇璲瘦睡秀穗竪粹綏綬繡羞脩茱蒐蓚藪袖誰讐輸遂邃酬銖銹隋隧隨雖需須首髓鬚叔塾夙孰宿淑潚熟琡璹肅菽巡徇循恂旬栒楯橓殉洵淳珣盾瞬筍純脣舜荀蓴蕣詢諄醇錞順馴戌術述鉥崇崧"],
["e3a1","嵩瑟膝蝨濕拾習褶襲丞乘僧勝升承昇繩蠅陞侍匙嘶始媤尸屎屍市弑恃施是時枾柴猜矢示翅蒔蓍視試詩諡豕豺埴寔式息拭植殖湜熄篒蝕識軾食飾伸侁信呻娠宸愼新晨燼申神紳腎臣莘薪藎蜃訊身辛辰迅失室實悉審尋心沁"],
["e4a1","沈深瀋甚芯諶什十拾雙氏亞俄兒啞娥峨我牙芽莪蛾衙訝阿雅餓鴉鵝堊岳嶽幄惡愕握樂渥鄂鍔顎鰐齷安岸按晏案眼雁鞍顔鮟斡謁軋閼唵岩巖庵暗癌菴闇壓押狎鴨仰央怏昻殃秧鴦厓哀埃崖愛曖涯碍艾隘靄厄扼掖液縊腋額"],
["e5a1","櫻罌鶯鸚也倻冶夜惹揶椰爺耶若野弱掠略約若葯蒻藥躍亮佯兩凉壤孃恙揚攘敭暘梁楊樣洋瀁煬痒瘍禳穰糧羊良襄諒讓釀陽量養圄御於漁瘀禦語馭魚齬億憶抑檍臆偃堰彦焉言諺孼蘖俺儼嚴奄掩淹嶪業円予余勵呂女如廬"],
["e6a1","旅歟汝濾璵礖礪與艅茹輿轝閭餘驪麗黎亦力域役易曆歷疫繹譯轢逆驛嚥堧姸娟宴年延憐戀捐挻撚椽沇沿涎涓淵演漣烟然煙煉燃燕璉硏硯秊筵緣練縯聯衍軟輦蓮連鉛鍊鳶列劣咽悅涅烈熱裂說閱厭廉念捻染殮炎焰琰艶苒"],
["e7a1","簾閻髥鹽曄獵燁葉令囹塋寧嶺嶸影怜映暎楹榮永泳渶潁濚瀛瀯煐營獰玲瑛瑩瓔盈穎纓羚聆英詠迎鈴鍈零霙靈領乂倪例刈叡曳汭濊猊睿穢芮藝蘂禮裔詣譽豫醴銳隸霓預五伍俉傲午吾吳嗚塢墺奧娛寤悟惡懊敖旿晤梧汚澳"],
["e8a1","烏熬獒筽蜈誤鰲鼇屋沃獄玉鈺溫瑥瘟穩縕蘊兀壅擁瓮甕癰翁邕雍饔渦瓦窩窪臥蛙蝸訛婉完宛梡椀浣玩琓琬碗緩翫脘腕莞豌阮頑曰往旺枉汪王倭娃歪矮外嵬巍猥畏了僚僥凹堯夭妖姚寥寮尿嶢拗搖撓擾料曜樂橈燎燿瑤療"],
["e9a1","窈窯繇繞耀腰蓼蟯要謠遙遼邀饒慾欲浴縟褥辱俑傭冗勇埇墉容庸慂榕涌湧溶熔瑢用甬聳茸蓉踊鎔鏞龍于佑偶優又友右宇寓尤愚憂旴牛玗瑀盂祐禑禹紆羽芋藕虞迂遇郵釪隅雨雩勖彧旭昱栯煜稶郁頊云暈橒殞澐熉耘芸蕓"],
["eaa1","運隕雲韻蔚鬱亐熊雄元原員圓園垣媛嫄寃怨愿援沅洹湲源爰猿瑗苑袁轅遠阮院願鴛月越鉞位偉僞危圍委威尉慰暐渭爲瑋緯胃萎葦蔿蝟衛褘謂違韋魏乳侑儒兪劉唯喩孺宥幼幽庾悠惟愈愉揄攸有杻柔柚柳楡楢油洧流游溜"],
["eba1","濡猶猷琉瑜由留癒硫紐維臾萸裕誘諛諭踰蹂遊逾遺酉釉鍮類六堉戮毓肉育陸倫允奫尹崙淪潤玧胤贇輪鈗閏律慄栗率聿戎瀜絨融隆垠恩慇殷誾銀隱乙吟淫蔭陰音飮揖泣邑凝應膺鷹依倚儀宜意懿擬椅毅疑矣義艤薏蟻衣誼"],
["eca1","議醫二以伊利吏夷姨履已弛彛怡易李梨泥爾珥理異痍痢移罹而耳肄苡荑裏裡貽貳邇里離飴餌匿溺瀷益翊翌翼謚人仁刃印吝咽因姻寅引忍湮燐璘絪茵藺蚓認隣靭靷鱗麟一佚佾壹日溢逸鎰馹任壬妊姙恁林淋稔臨荏賃入卄"],
["eda1","立笠粒仍剩孕芿仔刺咨姉姿子字孜恣慈滋炙煮玆瓷疵磁紫者自茨蔗藉諮資雌作勺嚼斫昨灼炸爵綽芍酌雀鵲孱棧殘潺盞岑暫潛箴簪蠶雜丈仗匠場墻壯奬將帳庄張掌暲杖樟檣欌漿牆狀獐璋章粧腸臟臧莊葬蔣薔藏裝贓醬長"],
["eea1","障再哉在宰才材栽梓渽滓災縡裁財載齋齎爭箏諍錚佇低儲咀姐底抵杵楮樗沮渚狙猪疽箸紵苧菹著藷詛貯躇這邸雎齟勣吊嫡寂摘敵滴狄炙的積笛籍績翟荻謫賊赤跡蹟迪迹適鏑佃佺傳全典前剪塡塼奠專展廛悛戰栓殿氈澱"],
["efa1","煎琠田甸畑癲筌箋箭篆纏詮輾轉鈿銓錢鐫電顚顫餞切截折浙癤竊節絶占岾店漸点粘霑鮎點接摺蝶丁井亭停偵呈姃定幀庭廷征情挺政整旌晶晸柾楨檉正汀淀淨渟湞瀞炡玎珽町睛碇禎程穽精綎艇訂諪貞鄭酊釘鉦鋌錠霆靖"],
["f0a1","靜頂鼎制劑啼堤帝弟悌提梯濟祭第臍薺製諸蹄醍除際霽題齊俎兆凋助嘲弔彫措操早晁曺曹朝條棗槽漕潮照燥爪璪眺祖祚租稠窕粗糟組繰肇藻蚤詔調趙躁造遭釣阻雕鳥族簇足鏃存尊卒拙猝倧宗從悰慫棕淙琮種終綜縱腫"],
["f1a1","踪踵鍾鐘佐坐左座挫罪主住侏做姝胄呪周嗾奏宙州廚晝朱柱株注洲湊澍炷珠疇籌紂紬綢舟蛛註誅走躊輳週酎酒鑄駐竹粥俊儁准埈寯峻晙樽浚準濬焌畯竣蠢逡遵雋駿茁中仲衆重卽櫛楫汁葺增憎曾拯烝甑症繒蒸證贈之只"],
["f2a1","咫地址志持指摯支旨智枝枳止池沚漬知砥祉祗紙肢脂至芝芷蜘誌識贄趾遲直稙稷織職唇嗔塵振搢晉晋桭榛殄津溱珍瑨璡畛疹盡眞瞋秦縉縝臻蔯袗診賑軫辰進鎭陣陳震侄叱姪嫉帙桎瓆疾秩窒膣蛭質跌迭斟朕什執潗緝輯"],
["f3a1","鏶集徵懲澄且侘借叉嗟嵯差次此磋箚茶蹉車遮捉搾着窄錯鑿齪撰澯燦璨瓚竄簒纂粲纘讚贊鑽餐饌刹察擦札紮僭參塹慘慙懺斬站讒讖倉倡創唱娼廠彰愴敞昌昶暢槍滄漲猖瘡窓脹艙菖蒼債埰寀寨彩採砦綵菜蔡采釵冊柵策"],
["f4a1","責凄妻悽處倜刺剔尺慽戚拓擲斥滌瘠脊蹠陟隻仟千喘天川擅泉淺玔穿舛薦賤踐遷釧闡阡韆凸哲喆徹撤澈綴輟轍鐵僉尖沾添甛瞻簽籤詹諂堞妾帖捷牒疊睫諜貼輒廳晴淸聽菁請靑鯖切剃替涕滯締諦逮遞體初剿哨憔抄招梢"],
["f5a1","椒楚樵炒焦硝礁礎秒稍肖艸苕草蕉貂超酢醋醮促囑燭矗蜀觸寸忖村邨叢塚寵悤憁摠總聰蔥銃撮催崔最墜抽推椎楸樞湫皺秋芻萩諏趨追鄒酋醜錐錘鎚雛騶鰍丑畜祝竺筑築縮蓄蹙蹴軸逐春椿瑃出朮黜充忠沖蟲衝衷悴膵萃"],
["f6a1","贅取吹嘴娶就炊翠聚脆臭趣醉驟鷲側仄厠惻測層侈値嗤峙幟恥梔治淄熾痔痴癡稚穉緇緻置致蚩輜雉馳齒則勅飭親七柒漆侵寢枕沈浸琛砧針鍼蟄秤稱快他咤唾墮妥惰打拖朶楕舵陀馱駝倬卓啄坼度托拓擢晫柝濁濯琢琸託"],
["f7a1","鐸呑嘆坦彈憚歎灘炭綻誕奪脫探眈耽貪塔搭榻宕帑湯糖蕩兌台太怠態殆汰泰笞胎苔跆邰颱宅擇澤撑攄兎吐土討慟桶洞痛筒統通堆槌腿褪退頹偸套妬投透鬪慝特闖坡婆巴把播擺杷波派爬琶破罷芭跛頗判坂板版瓣販辦鈑"],
["f8a1","阪八叭捌佩唄悖敗沛浿牌狽稗覇貝彭澎烹膨愎便偏扁片篇編翩遍鞭騙貶坪平枰萍評吠嬖幣廢弊斃肺蔽閉陛佈包匍匏咆哺圃布怖抛抱捕暴泡浦疱砲胞脯苞葡蒲袍褒逋鋪飽鮑幅暴曝瀑爆輻俵剽彪慓杓標漂瓢票表豹飇飄驃"],
["f9a1","品稟楓諷豊風馮彼披疲皮被避陂匹弼必泌珌畢疋筆苾馝乏逼下何厦夏廈昰河瑕荷蝦賀遐霞鰕壑學虐謔鶴寒恨悍旱汗漢澣瀚罕翰閑閒限韓割轄函含咸啣喊檻涵緘艦銜陷鹹合哈盒蛤閤闔陜亢伉姮嫦巷恒抗杭桁沆港缸肛航"],
["faa1","行降項亥偕咳垓奚孩害懈楷海瀣蟹解該諧邂駭骸劾核倖幸杏荇行享向嚮珦鄕響餉饗香噓墟虛許憲櫶獻軒歇險驗奕爀赫革俔峴弦懸晛泫炫玄玹現眩睍絃絢縣舷衒見賢鉉顯孑穴血頁嫌俠協夾峽挾浹狹脅脇莢鋏頰亨兄刑型"],
["fba1","形泂滎瀅灐炯熒珩瑩荊螢衡逈邢鎣馨兮彗惠慧暳蕙蹊醯鞋乎互呼壕壺好岵弧戶扈昊晧毫浩淏湖滸澔濠濩灝狐琥瑚瓠皓祜糊縞胡芦葫蒿虎號蝴護豪鎬頀顥惑或酷婚昏混渾琿魂忽惚笏哄弘汞泓洪烘紅虹訌鴻化和嬅樺火畵"],
["fca1","禍禾花華話譁貨靴廓擴攫確碻穫丸喚奐宦幻患換歡晥桓渙煥環紈還驩鰥活滑猾豁闊凰幌徨恍惶愰慌晃晄榥況湟滉潢煌璜皇篁簧荒蝗遑隍黃匯回廻徊恢悔懷晦會檜淮澮灰獪繪膾茴蛔誨賄劃獲宖橫鐄哮嚆孝效斅曉梟涍淆"],
["fda1","爻肴酵驍侯候厚后吼喉嗅帿後朽煦珝逅勛勳塤壎焄熏燻薰訓暈薨喧暄煊萱卉喙毁彙徽揮暉煇諱輝麾休携烋畦虧恤譎鷸兇凶匈洶胸黑昕欣炘痕吃屹紇訖欠欽歆吸恰洽翕興僖凞喜噫囍姬嬉希憙憘戱晞曦熙熹熺犧禧稀羲詰"]
]

},{}],21:[function(require,module,exports){
module.exports=[
["0","\u0000",127],
["a140","　，、。．‧；：？！︰…‥﹐﹑﹒·﹔﹕﹖﹗｜–︱—︳╴︴﹏（）︵︶｛｝︷︸〔〕︹︺【】︻︼《》︽︾〈〉︿﹀「」﹁﹂『』﹃﹄﹙﹚"],
["a1a1","﹛﹜﹝﹞‘’“”〝〞‵′＃＆＊※§〃○●△▲◎☆★◇◆□■▽▼㊣℅¯￣＿ˍ﹉﹊﹍﹎﹋﹌﹟﹠﹡＋－×÷±√＜＞＝≦≧≠∞≒≡﹢",4,"～∩∪⊥∠∟⊿㏒㏑∫∮∵∴♀♂⊕⊙↑↓←→↖↗↙↘∥∣／"],
["a240","＼∕﹨＄￥〒￠￡％＠℃℉﹩﹪﹫㏕㎜㎝㎞㏎㎡㎎㎏㏄°兙兛兞兝兡兣嗧瓩糎▁",7,"▏▎▍▌▋▊▉┼┴┬┤├▔─│▕┌┐└┘╭"],
["a2a1","╮╰╯═╞╪╡◢◣◥◤╱╲╳０",9,"Ⅰ",9,"〡",8,"十卄卅Ａ",25,"ａ",21],
["a340","ｗｘｙｚΑ",16,"Σ",6,"α",16,"σ",6,"ㄅ",10],
["a3a1","ㄐ",25,"˙ˉˊˇˋ"],
["a3e1","€"],
["a440","一乙丁七乃九了二人儿入八几刀刁力匕十卜又三下丈上丫丸凡久么也乞于亡兀刃勺千叉口土士夕大女子孑孓寸小尢尸山川工己已巳巾干廾弋弓才"],
["a4a1","丑丐不中丰丹之尹予云井互五亢仁什仃仆仇仍今介仄元允內六兮公冗凶分切刈勻勾勿化匹午升卅卞厄友及反壬天夫太夭孔少尤尺屯巴幻廿弔引心戈戶手扎支文斗斤方日曰月木欠止歹毋比毛氏水火爪父爻片牙牛犬王丙"],
["a540","世丕且丘主乍乏乎以付仔仕他仗代令仙仞充兄冉冊冬凹出凸刊加功包匆北匝仟半卉卡占卯卮去可古右召叮叩叨叼司叵叫另只史叱台句叭叻四囚外"],
["a5a1","央失奴奶孕它尼巨巧左市布平幼弁弘弗必戊打扔扒扑斥旦朮本未末札正母民氐永汁汀氾犯玄玉瓜瓦甘生用甩田由甲申疋白皮皿目矛矢石示禾穴立丞丟乒乓乩亙交亦亥仿伉伙伊伕伍伐休伏仲件任仰仳份企伋光兇兆先全"],
["a640","共再冰列刑划刎刖劣匈匡匠印危吉吏同吊吐吁吋各向名合吃后吆吒因回囝圳地在圭圬圯圩夙多夷夸妄奸妃好她如妁字存宇守宅安寺尖屹州帆并年"],
["a6a1","式弛忙忖戎戌戍成扣扛托收早旨旬旭曲曳有朽朴朱朵次此死氖汝汗汙江池汐汕污汛汍汎灰牟牝百竹米糸缶羊羽老考而耒耳聿肉肋肌臣自至臼舌舛舟艮色艾虫血行衣西阡串亨位住佇佗佞伴佛何估佐佑伽伺伸佃佔似但佣"],
["a740","作你伯低伶余佝佈佚兌克免兵冶冷別判利刪刨劫助努劬匣即卵吝吭吞吾否呎吧呆呃吳呈呂君吩告吹吻吸吮吵吶吠吼呀吱含吟听囪困囤囫坊坑址坍"],
["a7a1","均坎圾坐坏圻壯夾妝妒妨妞妣妙妖妍妤妓妊妥孝孜孚孛完宋宏尬局屁尿尾岐岑岔岌巫希序庇床廷弄弟彤形彷役忘忌志忍忱快忸忪戒我抄抗抖技扶抉扭把扼找批扳抒扯折扮投抓抑抆改攻攸旱更束李杏材村杜杖杞杉杆杠"],
["a840","杓杗步每求汞沙沁沈沉沅沛汪決沐汰沌汨沖沒汽沃汲汾汴沆汶沍沔沘沂灶灼災灸牢牡牠狄狂玖甬甫男甸皂盯矣私秀禿究系罕肖肓肝肘肛肚育良芒"],
["a8a1","芋芍見角言谷豆豕貝赤走足身車辛辰迂迆迅迄巡邑邢邪邦那酉釆里防阮阱阪阬並乖乳事些亞享京佯依侍佳使佬供例來侃佰併侈佩佻侖佾侏侑佺兔兒兕兩具其典冽函刻券刷刺到刮制剁劾劻卒協卓卑卦卷卸卹取叔受味呵"],
["a940","咖呸咕咀呻呷咄咒咆呼咐呱呶和咚呢周咋命咎固垃坷坪坩坡坦坤坼夜奉奇奈奄奔妾妻委妹妮姑姆姐姍始姓姊妯妳姒姅孟孤季宗定官宜宙宛尚屈居"],
["a9a1","屆岷岡岸岩岫岱岳帘帚帖帕帛帑幸庚店府底庖延弦弧弩往征彿彼忝忠忽念忿怏怔怯怵怖怪怕怡性怩怫怛或戕房戾所承拉拌拄抿拂抹拒招披拓拔拋拈抨抽押拐拙拇拍抵拚抱拘拖拗拆抬拎放斧於旺昔易昌昆昂明昀昏昕昊"],
["aa40","昇服朋杭枋枕東果杳杷枇枝林杯杰板枉松析杵枚枓杼杪杲欣武歧歿氓氛泣注泳沱泌泥河沽沾沼波沫法泓沸泄油況沮泗泅泱沿治泡泛泊沬泯泜泖泠"],
["aaa1","炕炎炒炊炙爬爭爸版牧物狀狎狙狗狐玩玨玟玫玥甽疝疙疚的盂盲直知矽社祀祁秉秈空穹竺糾罔羌羋者肺肥肢肱股肫肩肴肪肯臥臾舍芳芝芙芭芽芟芹花芬芥芯芸芣芰芾芷虎虱初表軋迎返近邵邸邱邶采金長門阜陀阿阻附"],
["ab40","陂隹雨青非亟亭亮信侵侯便俠俑俏保促侶俘俟俊俗侮俐俄係俚俎俞侷兗冒冑冠剎剃削前剌剋則勇勉勃勁匍南卻厚叛咬哀咨哎哉咸咦咳哇哂咽咪品"],
["aba1","哄哈咯咫咱咻咩咧咿囿垂型垠垣垢城垮垓奕契奏奎奐姜姘姿姣姨娃姥姪姚姦威姻孩宣宦室客宥封屎屏屍屋峙峒巷帝帥帟幽庠度建弈弭彥很待徊律徇後徉怒思怠急怎怨恍恰恨恢恆恃恬恫恪恤扁拜挖按拼拭持拮拽指拱拷"],
["ac40","拯括拾拴挑挂政故斫施既春昭映昧是星昨昱昤曷柿染柱柔某柬架枯柵柩柯柄柑枴柚查枸柏柞柳枰柙柢柝柒歪殃殆段毒毗氟泉洋洲洪流津洌洱洞洗"],
["aca1","活洽派洶洛泵洹洧洸洩洮洵洎洫炫為炳炬炯炭炸炮炤爰牲牯牴狩狠狡玷珊玻玲珍珀玳甚甭畏界畎畋疫疤疥疢疣癸皆皇皈盈盆盃盅省盹相眉看盾盼眇矜砂研砌砍祆祉祈祇禹禺科秒秋穿突竿竽籽紂紅紀紉紇約紆缸美羿耄"],
["ad40","耐耍耑耶胖胥胚胃胄背胡胛胎胞胤胝致舢苧范茅苣苛苦茄若茂茉苒苗英茁苜苔苑苞苓苟苯茆虐虹虻虺衍衫要觔計訂訃貞負赴赳趴軍軌述迦迢迪迥"],
["ada1","迭迫迤迨郊郎郁郃酋酊重閂限陋陌降面革韋韭音頁風飛食首香乘亳倌倍倣俯倦倥俸倩倖倆值借倚倒們俺倀倔倨俱倡個候倘俳修倭倪俾倫倉兼冤冥冢凍凌准凋剖剜剔剛剝匪卿原厝叟哨唐唁唷哼哥哲唆哺唔哩哭員唉哮哪"],
["ae40","哦唧唇哽唏圃圄埂埔埋埃堉夏套奘奚娑娘娜娟娛娓姬娠娣娩娥娌娉孫屘宰害家宴宮宵容宸射屑展屐峭峽峻峪峨峰島崁峴差席師庫庭座弱徒徑徐恙"],
["aea1","恣恥恐恕恭恩息悄悟悚悍悔悌悅悖扇拳挈拿捎挾振捕捂捆捏捉挺捐挽挪挫挨捍捌效敉料旁旅時晉晏晃晒晌晅晁書朔朕朗校核案框桓根桂桔栩梳栗桌桑栽柴桐桀格桃株桅栓栘桁殊殉殷氣氧氨氦氤泰浪涕消涇浦浸海浙涓"],
["af40","浬涉浮浚浴浩涌涊浹涅浥涔烊烘烤烙烈烏爹特狼狹狽狸狷玆班琉珮珠珪珞畔畝畜畚留疾病症疲疳疽疼疹痂疸皋皰益盍盎眩真眠眨矩砰砧砸砝破砷"],
["afa1","砥砭砠砟砲祕祐祠祟祖神祝祗祚秤秣秧租秦秩秘窄窈站笆笑粉紡紗紋紊素索純紐紕級紜納紙紛缺罟羔翅翁耆耘耕耙耗耽耿胱脂胰脅胭胴脆胸胳脈能脊胼胯臭臬舀舐航舫舨般芻茫荒荔荊茸荐草茵茴荏茲茹茶茗荀茱茨荃"],
["b040","虔蚊蚪蚓蚤蚩蚌蚣蚜衰衷袁袂衽衹記訐討訌訕訊託訓訖訏訑豈豺豹財貢起躬軒軔軏辱送逆迷退迺迴逃追逅迸邕郡郝郢酒配酌釘針釗釜釙閃院陣陡"],
["b0a1","陛陝除陘陞隻飢馬骨高鬥鬲鬼乾偺偽停假偃偌做偉健偶偎偕偵側偷偏倏偯偭兜冕凰剪副勒務勘動匐匏匙匿區匾參曼商啪啦啄啞啡啃啊唱啖問啕唯啤唸售啜唬啣唳啁啗圈國圉域堅堊堆埠埤基堂堵執培夠奢娶婁婉婦婪婀"],
["b140","娼婢婚婆婊孰寇寅寄寂宿密尉專將屠屜屝崇崆崎崛崖崢崑崩崔崙崤崧崗巢常帶帳帷康庸庶庵庾張強彗彬彩彫得徙從徘御徠徜恿患悉悠您惋悴惦悽"],
["b1a1","情悻悵惜悼惘惕惆惟悸惚惇戚戛扈掠控捲掖探接捷捧掘措捱掩掉掃掛捫推掄授掙採掬排掏掀捻捩捨捺敝敖救教敗啟敏敘敕敔斜斛斬族旋旌旎晝晚晤晨晦晞曹勗望梁梯梢梓梵桿桶梱梧梗械梃棄梭梆梅梔條梨梟梡梂欲殺"],
["b240","毫毬氫涎涼淳淙液淡淌淤添淺清淇淋涯淑涮淞淹涸混淵淅淒渚涵淚淫淘淪深淮淨淆淄涪淬涿淦烹焉焊烽烯爽牽犁猜猛猖猓猙率琅琊球理現琍瓠瓶"],
["b2a1","瓷甜產略畦畢異疏痔痕疵痊痍皎盔盒盛眷眾眼眶眸眺硫硃硎祥票祭移窒窕笠笨笛第符笙笞笮粒粗粕絆絃統紮紹紼絀細紳組累終紲紱缽羞羚翌翎習耜聊聆脯脖脣脫脩脰脤舂舵舷舶船莎莞莘荸莢莖莽莫莒莊莓莉莠荷荻荼"],
["b340","莆莧處彪蛇蛀蚶蛄蚵蛆蛋蚱蚯蛉術袞袈被袒袖袍袋覓規訪訝訣訥許設訟訛訢豉豚販責貫貨貪貧赧赦趾趺軛軟這逍通逗連速逝逐逕逞造透逢逖逛途"],
["b3a1","部郭都酗野釵釦釣釧釭釩閉陪陵陳陸陰陴陶陷陬雀雪雩章竟頂頃魚鳥鹵鹿麥麻傢傍傅備傑傀傖傘傚最凱割剴創剩勞勝勛博厥啻喀喧啼喊喝喘喂喜喪喔喇喋喃喳單喟唾喲喚喻喬喱啾喉喫喙圍堯堪場堤堰報堡堝堠壹壺奠"],
["b440","婷媚婿媒媛媧孳孱寒富寓寐尊尋就嵌嵐崴嵇巽幅帽幀幃幾廊廁廂廄弼彭復循徨惑惡悲悶惠愜愣惺愕惰惻惴慨惱愎惶愉愀愒戟扉掣掌描揀揩揉揆揍"],
["b4a1","插揣提握揖揭揮捶援揪換摒揚揹敞敦敢散斑斐斯普晰晴晶景暑智晾晷曾替期朝棺棕棠棘棗椅棟棵森棧棹棒棲棣棋棍植椒椎棉棚楮棻款欺欽殘殖殼毯氮氯氬港游湔渡渲湧湊渠渥渣減湛湘渤湖湮渭渦湯渴湍渺測湃渝渾滋"],
["b540","溉渙湎湣湄湲湩湟焙焚焦焰無然煮焜牌犄犀猶猥猴猩琺琪琳琢琥琵琶琴琯琛琦琨甥甦畫番痢痛痣痙痘痞痠登發皖皓皴盜睏短硝硬硯稍稈程稅稀窘"],
["b5a1","窗窖童竣等策筆筐筒答筍筋筏筑粟粥絞結絨絕紫絮絲絡給絢絰絳善翔翕耋聒肅腕腔腋腑腎脹腆脾腌腓腴舒舜菩萃菸萍菠菅萋菁華菱菴著萊菰萌菌菽菲菊萸萎萄菜萇菔菟虛蛟蛙蛭蛔蛛蛤蛐蛞街裁裂袱覃視註詠評詞証詁"],
["b640","詔詛詐詆訴診訶詖象貂貯貼貳貽賁費賀貴買貶貿貸越超趁跎距跋跚跑跌跛跆軻軸軼辜逮逵週逸進逶鄂郵鄉郾酣酥量鈔鈕鈣鈉鈞鈍鈐鈇鈑閔閏開閑"],
["b6a1","間閒閎隊階隋陽隅隆隍陲隄雁雅雄集雇雯雲韌項順須飧飪飯飩飲飭馮馭黃黍黑亂傭債傲傳僅傾催傷傻傯僇剿剷剽募勦勤勢勣匯嗟嗨嗓嗦嗎嗜嗇嗑嗣嗤嗯嗚嗡嗅嗆嗥嗉園圓塞塑塘塗塚塔填塌塭塊塢塒塋奧嫁嫉嫌媾媽媼"],
["b740","媳嫂媲嵩嵯幌幹廉廈弒彙徬微愚意慈感想愛惹愁愈慎慌慄慍愾愴愧愍愆愷戡戢搓搾搞搪搭搽搬搏搜搔損搶搖搗搆敬斟新暗暉暇暈暖暄暘暍會榔業"],
["b7a1","楚楷楠楔極椰概楊楨楫楞楓楹榆楝楣楛歇歲毀殿毓毽溢溯滓溶滂源溝滇滅溥溘溼溺溫滑準溜滄滔溪溧溴煎煙煩煤煉照煜煬煦煌煥煞煆煨煖爺牒猷獅猿猾瑯瑚瑕瑟瑞瑁琿瑙瑛瑜當畸瘀痰瘁痲痱痺痿痴痳盞盟睛睫睦睞督"],
["b840","睹睪睬睜睥睨睢矮碎碰碗碘碌碉硼碑碓硿祺祿禁萬禽稜稚稠稔稟稞窟窠筷節筠筮筧粱粳粵經絹綑綁綏絛置罩罪署義羨群聖聘肆肄腱腰腸腥腮腳腫"],
["b8a1","腹腺腦舅艇蒂葷落萱葵葦葫葉葬葛萼萵葡董葩葭葆虞虜號蛹蜓蜈蜇蜀蛾蛻蜂蜃蜆蜊衙裟裔裙補裘裝裡裊裕裒覜解詫該詳試詩詰誇詼詣誠話誅詭詢詮詬詹詻訾詨豢貊貉賊資賈賄貲賃賂賅跡跟跨路跳跺跪跤跦躲較載軾輊"],
["b940","辟農運遊道遂達逼違遐遇遏過遍遑逾遁鄒鄗酬酪酩釉鈷鉗鈸鈽鉀鈾鉛鉋鉤鉑鈴鉉鉍鉅鈹鈿鉚閘隘隔隕雍雋雉雊雷電雹零靖靴靶預頑頓頊頒頌飼飴"],
["b9a1","飽飾馳馱馴髡鳩麂鼎鼓鼠僧僮僥僖僭僚僕像僑僱僎僩兢凳劃劂匱厭嗾嘀嘛嘗嗽嘔嘆嘉嘍嘎嗷嘖嘟嘈嘐嗶團圖塵塾境墓墊塹墅塽壽夥夢夤奪奩嫡嫦嫩嫗嫖嫘嫣孵寞寧寡寥實寨寢寤察對屢嶄嶇幛幣幕幗幔廓廖弊彆彰徹慇"],
["ba40","愿態慷慢慣慟慚慘慵截撇摘摔撤摸摟摺摑摧搴摭摻敲斡旗旖暢暨暝榜榨榕槁榮槓構榛榷榻榫榴槐槍榭槌榦槃榣歉歌氳漳演滾漓滴漩漾漠漬漏漂漢"],
["baa1","滿滯漆漱漸漲漣漕漫漯澈漪滬漁滲滌滷熔熙煽熊熄熒爾犒犖獄獐瑤瑣瑪瑰瑭甄疑瘧瘍瘋瘉瘓盡監瞄睽睿睡磁碟碧碳碩碣禎福禍種稱窪窩竭端管箕箋筵算箝箔箏箸箇箄粹粽精綻綰綜綽綾綠緊綴網綱綺綢綿綵綸維緒緇綬"],
["bb40","罰翠翡翟聞聚肇腐膀膏膈膊腿膂臧臺與舔舞艋蓉蒿蓆蓄蒙蒞蒲蒜蓋蒸蓀蓓蒐蒼蓑蓊蜿蜜蜻蜢蜥蜴蜘蝕蜷蜩裳褂裴裹裸製裨褚裯誦誌語誣認誡誓誤"],
["bba1","說誥誨誘誑誚誧豪貍貌賓賑賒赫趙趕跼輔輒輕輓辣遠遘遜遣遙遞遢遝遛鄙鄘鄞酵酸酷酴鉸銀銅銘銖鉻銓銜銨鉼銑閡閨閩閣閥閤隙障際雌雒需靼鞅韶頗領颯颱餃餅餌餉駁骯骰髦魁魂鳴鳶鳳麼鼻齊億儀僻僵價儂儈儉儅凜"],
["bc40","劇劈劉劍劊勰厲嘮嘻嘹嘲嘿嘴嘩噓噎噗噴嘶嘯嘰墀墟增墳墜墮墩墦奭嬉嫻嬋嫵嬌嬈寮寬審寫層履嶝嶔幢幟幡廢廚廟廝廣廠彈影德徵慶慧慮慝慕憂"],
["bca1","慼慰慫慾憧憐憫憎憬憚憤憔憮戮摩摯摹撞撲撈撐撰撥撓撕撩撒撮播撫撚撬撙撢撳敵敷數暮暫暴暱樣樟槨樁樞標槽模樓樊槳樂樅槭樑歐歎殤毅毆漿潼澄潑潦潔澆潭潛潸潮澎潺潰潤澗潘滕潯潠潟熟熬熱熨牖犛獎獗瑩璋璃"],
["bd40","瑾璀畿瘠瘩瘟瘤瘦瘡瘢皚皺盤瞎瞇瞌瞑瞋磋磅確磊碾磕碼磐稿稼穀稽稷稻窯窮箭箱範箴篆篇篁箠篌糊締練緯緻緘緬緝編緣線緞緩綞緙緲緹罵罷羯"],
["bda1","翩耦膛膜膝膠膚膘蔗蔽蔚蓮蔬蔭蔓蔑蔣蔡蔔蓬蔥蓿蔆螂蝴蝶蝠蝦蝸蝨蝙蝗蝌蝓衛衝褐複褒褓褕褊誼諒談諄誕請諸課諉諂調誰論諍誶誹諛豌豎豬賠賞賦賤賬賭賢賣賜質賡赭趟趣踫踐踝踢踏踩踟踡踞躺輝輛輟輩輦輪輜輞"],
["be40","輥適遮遨遭遷鄰鄭鄧鄱醇醉醋醃鋅銻銷鋪銬鋤鋁銳銼鋒鋇鋰銲閭閱霄霆震霉靠鞍鞋鞏頡頫頜颳養餓餒餘駝駐駟駛駑駕駒駙骷髮髯鬧魅魄魷魯鴆鴉"],
["bea1","鴃麩麾黎墨齒儒儘儔儐儕冀冪凝劑劓勳噙噫噹噩噤噸噪器噥噱噯噬噢噶壁墾壇壅奮嬝嬴學寰導彊憲憑憩憊懍憶憾懊懈戰擅擁擋撻撼據擄擇擂操撿擒擔撾整曆曉暹曄曇暸樽樸樺橙橫橘樹橄橢橡橋橇樵機橈歙歷氅濂澱澡"],
["bf40","濃澤濁澧澳激澹澶澦澠澴熾燉燐燒燈燕熹燎燙燜燃燄獨璜璣璘璟璞瓢甌甍瘴瘸瘺盧盥瞠瞞瞟瞥磨磚磬磧禦積穎穆穌穋窺篙簑築篤篛篡篩篦糕糖縊"],
["bfa1","縑縈縛縣縞縝縉縐罹羲翰翱翮耨膳膩膨臻興艘艙蕊蕙蕈蕨蕩蕃蕉蕭蕪蕞螃螟螞螢融衡褪褲褥褫褡親覦諦諺諫諱謀諜諧諮諾謁謂諷諭諳諶諼豫豭貓賴蹄踱踴蹂踹踵輻輯輸輳辨辦遵遴選遲遼遺鄴醒錠錶鋸錳錯錢鋼錫錄錚"],
["c040","錐錦錡錕錮錙閻隧隨險雕霎霑霖霍霓霏靛靜靦鞘頰頸頻頷頭頹頤餐館餞餛餡餚駭駢駱骸骼髻髭鬨鮑鴕鴣鴦鴨鴒鴛默黔龍龜優償儡儲勵嚎嚀嚐嚅嚇"],
["c0a1","嚏壕壓壑壎嬰嬪嬤孺尷屨嶼嶺嶽嶸幫彌徽應懂懇懦懋戲戴擎擊擘擠擰擦擬擱擢擭斂斃曙曖檀檔檄檢檜櫛檣橾檗檐檠歜殮毚氈濘濱濟濠濛濤濫濯澀濬濡濩濕濮濰燧營燮燦燥燭燬燴燠爵牆獰獲璩環璦璨癆療癌盪瞳瞪瞰瞬"],
["c140","瞧瞭矯磷磺磴磯礁禧禪穗窿簇簍篾篷簌篠糠糜糞糢糟糙糝縮績繆縷縲繃縫總縱繅繁縴縹繈縵縿縯罄翳翼聱聲聰聯聳臆臃膺臂臀膿膽臉膾臨舉艱薪"],
["c1a1","薄蕾薜薑薔薯薛薇薨薊虧蟀蟑螳蟒蟆螫螻螺蟈蟋褻褶襄褸褽覬謎謗謙講謊謠謝謄謐豁谿豳賺賽購賸賻趨蹉蹋蹈蹊轄輾轂轅輿避遽還邁邂邀鄹醣醞醜鍍鎂錨鍵鍊鍥鍋錘鍾鍬鍛鍰鍚鍔闊闋闌闈闆隱隸雖霜霞鞠韓顆颶餵騁"],
["c240","駿鮮鮫鮪鮭鴻鴿麋黏點黜黝黛鼾齋叢嚕嚮壙壘嬸彝懣戳擴擲擾攆擺擻擷斷曜朦檳檬櫃檻檸櫂檮檯歟歸殯瀉瀋濾瀆濺瀑瀏燻燼燾燸獷獵璧璿甕癖癘"],
["c2a1","癒瞽瞿瞻瞼礎禮穡穢穠竄竅簫簧簪簞簣簡糧織繕繞繚繡繒繙罈翹翻職聶臍臏舊藏薩藍藐藉薰薺薹薦蟯蟬蟲蟠覆覲觴謨謹謬謫豐贅蹙蹣蹦蹤蹟蹕軀轉轍邇邃邈醫醬釐鎔鎊鎖鎢鎳鎮鎬鎰鎘鎚鎗闔闖闐闕離雜雙雛雞霤鞣鞦"],
["c340","鞭韹額顏題顎顓颺餾餿餽餮馥騎髁鬃鬆魏魎魍鯊鯉鯽鯈鯀鵑鵝鵠黠鼕鼬儳嚥壞壟壢寵龐廬懲懷懶懵攀攏曠曝櫥櫝櫚櫓瀛瀟瀨瀚瀝瀕瀘爆爍牘犢獸"],
["c3a1","獺璽瓊瓣疇疆癟癡矇礙禱穫穩簾簿簸簽簷籀繫繭繹繩繪羅繳羶羹羸臘藩藝藪藕藤藥藷蟻蠅蠍蟹蟾襠襟襖襞譁譜識證譚譎譏譆譙贈贊蹼蹲躇蹶蹬蹺蹴轔轎辭邊邋醱醮鏡鏑鏟鏃鏈鏜鏝鏖鏢鏍鏘鏤鏗鏨關隴難霪霧靡韜韻類"],
["c440","願顛颼饅饉騖騙鬍鯨鯧鯖鯛鶉鵡鵲鵪鵬麒麗麓麴勸嚨嚷嚶嚴嚼壤孀孃孽寶巉懸懺攘攔攙曦朧櫬瀾瀰瀲爐獻瓏癢癥礦礪礬礫竇競籌籃籍糯糰辮繽繼"],
["c4a1","纂罌耀臚艦藻藹蘑藺蘆蘋蘇蘊蠔蠕襤覺觸議譬警譯譟譫贏贍躉躁躅躂醴釋鐘鐃鏽闡霰飄饒饑馨騫騰騷騵鰓鰍鹹麵黨鼯齟齣齡儷儸囁囀囂夔屬巍懼懾攝攜斕曩櫻欄櫺殲灌爛犧瓖瓔癩矓籐纏續羼蘗蘭蘚蠣蠢蠡蠟襪襬覽譴"],
["c540","護譽贓躊躍躋轟辯醺鐮鐳鐵鐺鐸鐲鐫闢霸霹露響顧顥饗驅驃驀騾髏魔魑鰭鰥鶯鶴鷂鶸麝黯鼙齜齦齧儼儻囈囊囉孿巔巒彎懿攤權歡灑灘玀瓤疊癮癬"],
["c5a1","禳籠籟聾聽臟襲襯觼讀贖贗躑躓轡酈鑄鑑鑒霽霾韃韁顫饕驕驍髒鬚鱉鰱鰾鰻鷓鷗鼴齬齪龔囌巖戀攣攫攪曬欐瓚竊籤籣籥纓纖纔臢蘸蘿蠱變邐邏鑣鑠鑤靨顯饜驚驛驗髓體髑鱔鱗鱖鷥麟黴囑壩攬灞癱癲矗罐羈蠶蠹衢讓讒"],
["c640","讖艷贛釀鑪靂靈靄韆顰驟鬢魘鱟鷹鷺鹼鹽鼇齷齲廳欖灣籬籮蠻觀躡釁鑲鑰顱饞髖鬣黌灤矚讚鑷韉驢驥纜讜躪釅鑽鑾鑼鱷鱸黷豔鑿鸚爨驪鬱鸛鸞籲"],
["c940","乂乜凵匚厂万丌乇亍囗兀屮彳丏冇与丮亓仂仉仈冘勼卬厹圠夃夬尐巿旡殳毌气爿丱丼仨仜仩仡仝仚刌匜卌圢圣夗夯宁宄尒尻屴屳帄庀庂忉戉扐氕"],
["c9a1","氶汃氿氻犮犰玊禸肊阞伎优伬仵伔仱伀价伈伝伂伅伢伓伄仴伒冱刓刉刐劦匢匟卍厊吇囡囟圮圪圴夼妀奼妅奻奾奷奿孖尕尥屼屺屻屾巟幵庄异弚彴忕忔忏扜扞扤扡扦扢扙扠扚扥旯旮朾朹朸朻机朿朼朳氘汆汒汜汏汊汔汋"],
["ca40","汌灱牞犴犵玎甪癿穵网艸艼芀艽艿虍襾邙邗邘邛邔阢阤阠阣佖伻佢佉体佤伾佧佒佟佁佘伭伳伿佡冏冹刜刞刡劭劮匉卣卲厎厏吰吷吪呔呅吙吜吥吘"],
["caa1","吽呏呁吨吤呇囮囧囥坁坅坌坉坋坒夆奀妦妘妠妗妎妢妐妏妧妡宎宒尨尪岍岏岈岋岉岒岊岆岓岕巠帊帎庋庉庌庈庍弅弝彸彶忒忑忐忭忨忮忳忡忤忣忺忯忷忻怀忴戺抃抌抎抏抔抇扱扻扺扰抁抈扷扽扲扴攷旰旴旳旲旵杅杇"],
["cb40","杙杕杌杈杝杍杚杋毐氙氚汸汧汫沄沋沏汱汯汩沚汭沇沕沜汦汳汥汻沎灴灺牣犿犽狃狆狁犺狅玕玗玓玔玒町甹疔疕皁礽耴肕肙肐肒肜芐芏芅芎芑芓"],
["cba1","芊芃芄豸迉辿邟邡邥邞邧邠阰阨阯阭丳侘佼侅佽侀侇佶佴侉侄佷佌侗佪侚佹侁佸侐侜侔侞侒侂侕佫佮冞冼冾刵刲刳剆刱劼匊匋匼厒厔咇呿咁咑咂咈呫呺呾呥呬呴呦咍呯呡呠咘呣呧呤囷囹坯坲坭坫坱坰坶垀坵坻坳坴坢"],
["cc40","坨坽夌奅妵妺姏姎妲姌姁妶妼姃姖妱妽姀姈妴姇孢孥宓宕屄屇岮岤岠岵岯岨岬岟岣岭岢岪岧岝岥岶岰岦帗帔帙弨弢弣弤彔徂彾彽忞忥怭怦怙怲怋"],
["cca1","怴怊怗怳怚怞怬怢怍怐怮怓怑怌怉怜戔戽抭抴拑抾抪抶拊抮抳抯抻抩抰抸攽斨斻昉旼昄昒昈旻昃昋昍昅旽昑昐曶朊枅杬枎枒杶杻枘枆构杴枍枌杺枟枑枙枃杽极杸杹枔欥殀歾毞氝沓泬泫泮泙沶泔沭泧沷泐泂沺泃泆泭泲"],
["cd40","泒泝沴沊沝沀泞泀洰泍泇沰泹泏泩泑炔炘炅炓炆炄炑炖炂炚炃牪狖狋狘狉狜狒狔狚狌狑玤玡玭玦玢玠玬玝瓝瓨甿畀甾疌疘皯盳盱盰盵矸矼矹矻矺"],
["cda1","矷祂礿秅穸穻竻籵糽耵肏肮肣肸肵肭舠芠苀芫芚芘芛芵芧芮芼芞芺芴芨芡芩苂芤苃芶芢虰虯虭虮豖迒迋迓迍迖迕迗邲邴邯邳邰阹阽阼阺陃俍俅俓侲俉俋俁俔俜俙侻侳俛俇俖侺俀侹俬剄剉勀勂匽卼厗厖厙厘咺咡咭咥哏"],
["ce40","哃茍咷咮哖咶哅哆咠呰咼咢咾呲哞咰垵垞垟垤垌垗垝垛垔垘垏垙垥垚垕壴复奓姡姞姮娀姱姝姺姽姼姶姤姲姷姛姩姳姵姠姾姴姭宨屌峐峘峌峗峋峛"],
["cea1","峞峚峉峇峊峖峓峔峏峈峆峎峟峸巹帡帢帣帠帤庰庤庢庛庣庥弇弮彖徆怷怹恔恲恞恅恓恇恉恛恌恀恂恟怤恄恘恦恮扂扃拏挍挋拵挎挃拫拹挏挌拸拶挀挓挔拺挕拻拰敁敃斪斿昶昡昲昵昜昦昢昳昫昺昝昴昹昮朏朐柁柲柈枺"],
["cf40","柜枻柸柘柀枷柅柫柤柟枵柍枳柷柶柮柣柂枹柎柧柰枲柼柆柭柌枮柦柛柺柉柊柃柪柋欨殂殄殶毖毘毠氠氡洨洴洭洟洼洿洒洊泚洳洄洙洺洚洑洀洝浂"],
["cfa1","洁洘洷洃洏浀洇洠洬洈洢洉洐炷炟炾炱炰炡炴炵炩牁牉牊牬牰牳牮狊狤狨狫狟狪狦狣玅珌珂珈珅玹玶玵玴珫玿珇玾珃珆玸珋瓬瓮甮畇畈疧疪癹盄眈眃眄眅眊盷盻盺矧矨砆砑砒砅砐砏砎砉砃砓祊祌祋祅祄秕种秏秖秎窀"],
["d040","穾竑笀笁籺籸籹籿粀粁紃紈紁罘羑羍羾耇耎耏耔耷胘胇胠胑胈胂胐胅胣胙胜胊胕胉胏胗胦胍臿舡芔苙苾苹茇苨茀苕茺苫苖苴苬苡苲苵茌苻苶苰苪"],
["d0a1","苤苠苺苳苭虷虴虼虳衁衎衧衪衩觓訄訇赲迣迡迮迠郱邽邿郕郅邾郇郋郈釔釓陔陏陑陓陊陎倞倅倇倓倢倰倛俵俴倳倷倬俶俷倗倜倠倧倵倯倱倎党冔冓凊凄凅凈凎剡剚剒剞剟剕剢勍匎厞唦哢唗唒哧哳哤唚哿唄唈哫唑唅哱"],
["d140","唊哻哷哸哠唎唃唋圁圂埌堲埕埒垺埆垽垼垸垶垿埇埐垹埁夎奊娙娖娭娮娕娏娗娊娞娳孬宧宭宬尃屖屔峬峿峮峱峷崀峹帩帨庨庮庪庬弳弰彧恝恚恧"],
["d1a1","恁悢悈悀悒悁悝悃悕悛悗悇悜悎戙扆拲挐捖挬捄捅挶捃揤挹捋捊挼挩捁挴捘捔捙挭捇挳捚捑挸捗捀捈敊敆旆旃旄旂晊晟晇晑朒朓栟栚桉栲栳栻桋桏栖栱栜栵栫栭栯桎桄栴栝栒栔栦栨栮桍栺栥栠欬欯欭欱欴歭肂殈毦毤"],
["d240","毨毣毢毧氥浺浣浤浶洍浡涒浘浢浭浯涑涍淯浿涆浞浧浠涗浰浼浟涂涘洯浨涋浾涀涄洖涃浻浽浵涐烜烓烑烝烋缹烢烗烒烞烠烔烍烅烆烇烚烎烡牂牸"],
["d2a1","牷牶猀狺狴狾狶狳狻猁珓珙珥珖玼珧珣珩珜珒珛珔珝珚珗珘珨瓞瓟瓴瓵甡畛畟疰痁疻痄痀疿疶疺皊盉眝眛眐眓眒眣眑眕眙眚眢眧砣砬砢砵砯砨砮砫砡砩砳砪砱祔祛祏祜祓祒祑秫秬秠秮秭秪秜秞秝窆窉窅窋窌窊窇竘笐"],
["d340","笄笓笅笏笈笊笎笉笒粄粑粊粌粈粍粅紞紝紑紎紘紖紓紟紒紏紌罜罡罞罠罝罛羖羒翃翂翀耖耾耹胺胲胹胵脁胻脀舁舯舥茳茭荄茙荑茥荖茿荁茦茜茢"],
["d3a1","荂荎茛茪茈茼荍茖茤茠茷茯茩荇荅荌荓茞茬荋茧荈虓虒蚢蚨蚖蚍蚑蚞蚇蚗蚆蚋蚚蚅蚥蚙蚡蚧蚕蚘蚎蚝蚐蚔衃衄衭衵衶衲袀衱衿衯袃衾衴衼訒豇豗豻貤貣赶赸趵趷趶軑軓迾迵适迿迻逄迼迶郖郠郙郚郣郟郥郘郛郗郜郤酐"],
["d440","酎酏釕釢釚陜陟隼飣髟鬯乿偰偪偡偞偠偓偋偝偲偈偍偁偛偊偢倕偅偟偩偫偣偤偆偀偮偳偗偑凐剫剭剬剮勖勓匭厜啵啶唼啍啐唴唪啑啢唶唵唰啒啅"],
["d4a1","唌唲啥啎唹啈唭唻啀啋圊圇埻堔埢埶埜埴堀埭埽堈埸堋埳埏堇埮埣埲埥埬埡堎埼堐埧堁堌埱埩埰堍堄奜婠婘婕婧婞娸娵婭婐婟婥婬婓婤婗婃婝婒婄婛婈媎娾婍娹婌婰婩婇婑婖婂婜孲孮寁寀屙崞崋崝崚崠崌崨崍崦崥崏"],
["d540","崰崒崣崟崮帾帴庱庴庹庲庳弶弸徛徖徟悊悐悆悾悰悺惓惔惏惤惙惝惈悱惛悷惊悿惃惍惀挲捥掊掂捽掽掞掭掝掗掫掎捯掇掐据掯捵掜捭掮捼掤挻掟"],
["d5a1","捸掅掁掑掍捰敓旍晥晡晛晙晜晢朘桹梇梐梜桭桮梮梫楖桯梣梬梩桵桴梲梏桷梒桼桫桲梪梀桱桾梛梖梋梠梉梤桸桻梑梌梊桽欶欳欷欸殑殏殍殎殌氪淀涫涴涳湴涬淩淢涷淶淔渀淈淠淟淖涾淥淜淝淛淴淊涽淭淰涺淕淂淏淉"],
["d640","淐淲淓淽淗淍淣涻烺焍烷焗烴焌烰焄烳焐烼烿焆焓焀烸烶焋焂焎牾牻牼牿猝猗猇猑猘猊猈狿猏猞玈珶珸珵琄琁珽琇琀珺珼珿琌琋珴琈畤畣痎痒痏"],
["d6a1","痋痌痑痐皏皉盓眹眯眭眱眲眴眳眽眥眻眵硈硒硉硍硊硌砦硅硐祤祧祩祪祣祫祡离秺秸秶秷窏窔窐笵筇笴笥笰笢笤笳笘笪笝笱笫笭笯笲笸笚笣粔粘粖粣紵紽紸紶紺絅紬紩絁絇紾紿絊紻紨罣羕羜羝羛翊翋翍翐翑翇翏翉耟"],
["d740","耞耛聇聃聈脘脥脙脛脭脟脬脞脡脕脧脝脢舑舸舳舺舴舲艴莐莣莨莍荺荳莤荴莏莁莕莙荵莔莩荽莃莌莝莛莪莋荾莥莯莈莗莰荿莦莇莮荶莚虙虖蚿蚷"],
["d7a1","蛂蛁蛅蚺蚰蛈蚹蚳蚸蛌蚴蚻蚼蛃蚽蚾衒袉袕袨袢袪袚袑袡袟袘袧袙袛袗袤袬袌袓袎覂觖觙觕訰訧訬訞谹谻豜豝豽貥赽赻赹趼跂趹趿跁軘軞軝軜軗軠軡逤逋逑逜逌逡郯郪郰郴郲郳郔郫郬郩酖酘酚酓酕釬釴釱釳釸釤釹釪"],
["d840","釫釷釨釮镺閆閈陼陭陫陱陯隿靪頄飥馗傛傕傔傞傋傣傃傌傎傝偨傜傒傂傇兟凔匒匑厤厧喑喨喥喭啷噅喢喓喈喏喵喁喣喒喤啽喌喦啿喕喡喎圌堩堷"],
["d8a1","堙堞堧堣堨埵塈堥堜堛堳堿堶堮堹堸堭堬堻奡媯媔媟婺媢媞婸媦婼媥媬媕媮娷媄媊媗媃媋媩婻婽媌媜媏媓媝寪寍寋寔寑寊寎尌尰崷嵃嵫嵁嵋崿崵嵑嵎嵕崳崺嵒崽崱嵙嵂崹嵉崸崼崲崶嵀嵅幄幁彘徦徥徫惉悹惌惢惎惄愔"],
["d940","惲愊愖愅惵愓惸惼惾惁愃愘愝愐惿愄愋扊掔掱掰揎揥揨揯揃撝揳揊揠揶揕揲揵摡揟掾揝揜揄揘揓揂揇揌揋揈揰揗揙攲敧敪敤敜敨敥斌斝斞斮旐旒"],
["d9a1","晼晬晻暀晱晹晪晲朁椌棓椄棜椪棬棪棱椏棖棷棫棤棶椓椐棳棡椇棌椈楰梴椑棯棆椔棸棐棽棼棨椋椊椗棎棈棝棞棦棴棑椆棔棩椕椥棇欹欻欿欼殔殗殙殕殽毰毲毳氰淼湆湇渟湉溈渼渽湅湢渫渿湁湝湳渜渳湋湀湑渻渃渮湞"],
["da40","湨湜湡渱渨湠湱湫渹渢渰湓湥渧湸湤湷湕湹湒湦渵渶湚焠焞焯烻焮焱焣焥焢焲焟焨焺焛牋牚犈犉犆犅犋猒猋猰猢猱猳猧猲猭猦猣猵猌琮琬琰琫琖"],
["daa1","琚琡琭琱琤琣琝琩琠琲瓻甯畯畬痧痚痡痦痝痟痤痗皕皒盚睆睇睄睍睅睊睎睋睌矞矬硠硤硥硜硭硱硪确硰硩硨硞硢祴祳祲祰稂稊稃稌稄窙竦竤筊笻筄筈筌筎筀筘筅粢粞粨粡絘絯絣絓絖絧絪絏絭絜絫絒絔絩絑絟絎缾缿罥"],
["db40","罦羢羠羡翗聑聏聐胾胔腃腊腒腏腇脽腍脺臦臮臷臸臹舄舼舽舿艵茻菏菹萣菀菨萒菧菤菼菶萐菆菈菫菣莿萁菝菥菘菿菡菋菎菖菵菉萉萏菞萑萆菂菳"],
["dba1","菕菺菇菑菪萓菃菬菮菄菻菗菢萛菛菾蛘蛢蛦蛓蛣蛚蛪蛝蛫蛜蛬蛩蛗蛨蛑衈衖衕袺裗袹袸裀袾袶袼袷袽袲褁裉覕覘覗觝觚觛詎詍訹詙詀詗詘詄詅詒詈詑詊詌詏豟貁貀貺貾貰貹貵趄趀趉跘跓跍跇跖跜跏跕跙跈跗跅軯軷軺"],
["dc40","軹軦軮軥軵軧軨軶軫軱軬軴軩逭逴逯鄆鄬鄄郿郼鄈郹郻鄁鄀鄇鄅鄃酡酤酟酢酠鈁鈊鈥鈃鈚鈦鈏鈌鈀鈒釿釽鈆鈄鈧鈂鈜鈤鈙鈗鈅鈖镻閍閌閐隇陾隈"],
["dca1","隉隃隀雂雈雃雱雰靬靰靮頇颩飫鳦黹亃亄亶傽傿僆傮僄僊傴僈僂傰僁傺傱僋僉傶傸凗剺剸剻剼嗃嗛嗌嗐嗋嗊嗝嗀嗔嗄嗩喿嗒喍嗏嗕嗢嗖嗈嗲嗍嗙嗂圔塓塨塤塏塍塉塯塕塎塝塙塥塛堽塣塱壼嫇嫄嫋媺媸媱媵媰媿嫈媻嫆"],
["dd40","媷嫀嫊媴媶嫍媹媐寖寘寙尟尳嵱嵣嵊嵥嵲嵬嵞嵨嵧嵢巰幏幎幊幍幋廅廌廆廋廇彀徯徭惷慉慊愫慅愶愲愮慆愯慏愩慀戠酨戣戥戤揅揱揫搐搒搉搠搤"],
["dda1","搳摃搟搕搘搹搷搢搣搌搦搰搨摁搵搯搊搚摀搥搧搋揧搛搮搡搎敯斒旓暆暌暕暐暋暊暙暔晸朠楦楟椸楎楢楱椿楅楪椹楂楗楙楺楈楉椵楬椳椽楥棰楸椴楩楀楯楄楶楘楁楴楌椻楋椷楜楏楑椲楒椯楻椼歆歅歃歂歈歁殛嗀毻毼"],
["de40","毹毷毸溛滖滈溏滀溟溓溔溠溱溹滆滒溽滁溞滉溷溰滍溦滏溲溾滃滜滘溙溒溎溍溤溡溿溳滐滊溗溮溣煇煔煒煣煠煁煝煢煲煸煪煡煂煘煃煋煰煟煐煓"],
["dea1","煄煍煚牏犍犌犑犐犎猼獂猻猺獀獊獉瑄瑊瑋瑒瑑瑗瑀瑏瑐瑎瑂瑆瑍瑔瓡瓿瓾瓽甝畹畷榃痯瘏瘃痷痾痼痹痸瘐痻痶痭痵痽皙皵盝睕睟睠睒睖睚睩睧睔睙睭矠碇碚碔碏碄碕碅碆碡碃硹碙碀碖硻祼禂祽祹稑稘稙稒稗稕稢稓"],
["df40","稛稐窣窢窞竫筦筤筭筴筩筲筥筳筱筰筡筸筶筣粲粴粯綈綆綀綍絿綅絺綎絻綃絼綌綔綄絽綒罭罫罧罨罬羦羥羧翛翜耡腤腠腷腜腩腛腢腲朡腞腶腧腯"],
["dfa1","腄腡舝艉艄艀艂艅蓱萿葖葶葹蒏蒍葥葑葀蒆葧萰葍葽葚葙葴葳葝蔇葞萷萺萴葺葃葸萲葅萩菙葋萯葂萭葟葰萹葎葌葒葯蓅蒎萻葇萶萳葨葾葄萫葠葔葮葐蜋蜄蛷蜌蛺蛖蛵蝍蛸蜎蜉蜁蛶蜍蜅裖裋裍裎裞裛裚裌裐覅覛觟觥觤"],
["e040","觡觠觢觜触詶誆詿詡訿詷誂誄詵誃誁詴詺谼豋豊豥豤豦貆貄貅賌赨赩趑趌趎趏趍趓趔趐趒跰跠跬跱跮跐跩跣跢跧跲跫跴輆軿輁輀輅輇輈輂輋遒逿"],
["e0a1","遄遉逽鄐鄍鄏鄑鄖鄔鄋鄎酮酯鉈鉒鈰鈺鉦鈳鉥鉞銃鈮鉊鉆鉭鉬鉏鉠鉧鉯鈶鉡鉰鈱鉔鉣鉐鉲鉎鉓鉌鉖鈲閟閜閞閛隒隓隑隗雎雺雽雸雵靳靷靸靲頏頍頎颬飶飹馯馲馰馵骭骫魛鳪鳭鳧麀黽僦僔僗僨僳僛僪僝僤僓僬僰僯僣僠"],
["e140","凘劀劁勩勫匰厬嘧嘕嘌嘒嗼嘏嘜嘁嘓嘂嗺嘝嘄嗿嗹墉塼墐墘墆墁塿塴墋塺墇墑墎塶墂墈塻墔墏壾奫嫜嫮嫥嫕嫪嫚嫭嫫嫳嫢嫠嫛嫬嫞嫝嫙嫨嫟孷寠"],
["e1a1","寣屣嶂嶀嵽嶆嵺嶁嵷嶊嶉嶈嵾嵼嶍嵹嵿幘幙幓廘廑廗廎廜廕廙廒廔彄彃彯徶愬愨慁慞慱慳慒慓慲慬憀慴慔慺慛慥愻慪慡慖戩戧戫搫摍摛摝摴摶摲摳摽摵摦撦摎撂摞摜摋摓摠摐摿搿摬摫摙摥摷敳斠暡暠暟朅朄朢榱榶槉"],
["e240","榠槎榖榰榬榼榑榙榎榧榍榩榾榯榿槄榽榤槔榹槊榚槏榳榓榪榡榞槙榗榐槂榵榥槆歊歍歋殞殟殠毃毄毾滎滵滱漃漥滸漷滻漮漉潎漙漚漧漘漻漒滭漊"],
["e2a1","漶潳滹滮漭潀漰漼漵滫漇漎潃漅滽滶漹漜滼漺漟漍漞漈漡熇熐熉熀熅熂熏煻熆熁熗牄牓犗犕犓獃獍獑獌瑢瑳瑱瑵瑲瑧瑮甀甂甃畽疐瘖瘈瘌瘕瘑瘊瘔皸瞁睼瞅瞂睮瞀睯睾瞃碲碪碴碭碨硾碫碞碥碠碬碢碤禘禊禋禖禕禔禓"],
["e340","禗禈禒禐稫穊稰稯稨稦窨窫窬竮箈箜箊箑箐箖箍箌箛箎箅箘劄箙箤箂粻粿粼粺綧綷緂綣綪緁緀緅綝緎緄緆緋緌綯綹綖綼綟綦綮綩綡緉罳翢翣翥翞"],
["e3a1","耤聝聜膉膆膃膇膍膌膋舕蒗蒤蒡蒟蒺蓎蓂蒬蒮蒫蒹蒴蓁蓍蒪蒚蒱蓐蒝蒧蒻蒢蒔蓇蓌蒛蒩蒯蒨蓖蒘蒶蓏蒠蓗蓔蓒蓛蒰蒑虡蜳蜣蜨蝫蝀蜮蜞蜡蜙蜛蝃蜬蝁蜾蝆蜠蜲蜪蜭蜼蜒蜺蜱蜵蝂蜦蜧蜸蜤蜚蜰蜑裷裧裱裲裺裾裮裼裶裻"],
["e440","裰裬裫覝覡覟覞觩觫觨誫誙誋誒誏誖谽豨豩賕賏賗趖踉踂跿踍跽踊踃踇踆踅跾踀踄輐輑輎輍鄣鄜鄠鄢鄟鄝鄚鄤鄡鄛酺酲酹酳銥銤鉶銛鉺銠銔銪銍"],
["e4a1","銦銚銫鉹銗鉿銣鋮銎銂銕銢鉽銈銡銊銆銌銙銧鉾銇銩銝銋鈭隞隡雿靘靽靺靾鞃鞀鞂靻鞄鞁靿韎韍頖颭颮餂餀餇馝馜駃馹馻馺駂馽駇骱髣髧鬾鬿魠魡魟鳱鳲鳵麧僿儃儰僸儆儇僶僾儋儌僽儊劋劌勱勯噈噂噌嘵噁噊噉噆噘"],
["e540","噚噀嘳嘽嘬嘾嘸嘪嘺圚墫墝墱墠墣墯墬墥墡壿嫿嫴嫽嫷嫶嬃嫸嬂嫹嬁嬇嬅嬏屧嶙嶗嶟嶒嶢嶓嶕嶠嶜嶡嶚嶞幩幝幠幜緳廛廞廡彉徲憋憃慹憱憰憢憉"],
["e5a1","憛憓憯憭憟憒憪憡憍慦憳戭摮摰撖撠撅撗撜撏撋撊撌撣撟摨撱撘敶敺敹敻斲斳暵暰暩暲暷暪暯樀樆樗槥槸樕槱槤樠槿槬槢樛樝槾樧槲槮樔槷槧橀樈槦槻樍槼槫樉樄樘樥樏槶樦樇槴樖歑殥殣殢殦氁氀毿氂潁漦潾澇濆澒"],
["e640","澍澉澌潢潏澅潚澖潶潬澂潕潲潒潐潗澔澓潝漀潡潫潽潧澐潓澋潩潿澕潣潷潪潻熲熯熛熰熠熚熩熵熝熥熞熤熡熪熜熧熳犘犚獘獒獞獟獠獝獛獡獚獙"],
["e6a1","獢璇璉璊璆璁瑽璅璈瑼瑹甈甇畾瘥瘞瘙瘝瘜瘣瘚瘨瘛皜皝皞皛瞍瞏瞉瞈磍碻磏磌磑磎磔磈磃磄磉禚禡禠禜禢禛歶稹窲窴窳箷篋箾箬篎箯箹篊箵糅糈糌糋緷緛緪緧緗緡縃緺緦緶緱緰緮緟罶羬羰羭翭翫翪翬翦翨聤聧膣膟"],
["e740","膞膕膢膙膗舖艏艓艒艐艎艑蔤蔻蔏蔀蔩蔎蔉蔍蔟蔊蔧蔜蓻蔫蓺蔈蔌蓴蔪蓲蔕蓷蓫蓳蓼蔒蓪蓩蔖蓾蔨蔝蔮蔂蓽蔞蓶蔱蔦蓧蓨蓰蓯蓹蔘蔠蔰蔋蔙蔯虢"],
["e7a1","蝖蝣蝤蝷蟡蝳蝘蝔蝛蝒蝡蝚蝑蝞蝭蝪蝐蝎蝟蝝蝯蝬蝺蝮蝜蝥蝏蝻蝵蝢蝧蝩衚褅褌褔褋褗褘褙褆褖褑褎褉覢覤覣觭觰觬諏諆誸諓諑諔諕誻諗誾諀諅諘諃誺誽諙谾豍貏賥賟賙賨賚賝賧趠趜趡趛踠踣踥踤踮踕踛踖踑踙踦踧"],
["e840","踔踒踘踓踜踗踚輬輤輘輚輠輣輖輗遳遰遯遧遫鄯鄫鄩鄪鄲鄦鄮醅醆醊醁醂醄醀鋐鋃鋄鋀鋙銶鋏鋱鋟鋘鋩鋗鋝鋌鋯鋂鋨鋊鋈鋎鋦鋍鋕鋉鋠鋞鋧鋑鋓"],
["e8a1","銵鋡鋆銴镼閬閫閮閰隤隢雓霅霈霂靚鞊鞎鞈韐韏頞頝頦頩頨頠頛頧颲餈飺餑餔餖餗餕駜駍駏駓駔駎駉駖駘駋駗駌骳髬髫髳髲髱魆魃魧魴魱魦魶魵魰魨魤魬鳼鳺鳽鳿鳷鴇鴀鳹鳻鴈鴅鴄麃黓鼏鼐儜儓儗儚儑凞匴叡噰噠噮"],
["e940","噳噦噣噭噲噞噷圜圛壈墽壉墿墺壂墼壆嬗嬙嬛嬡嬔嬓嬐嬖嬨嬚嬠嬞寯嶬嶱嶩嶧嶵嶰嶮嶪嶨嶲嶭嶯嶴幧幨幦幯廩廧廦廨廥彋徼憝憨憖懅憴懆懁懌憺"],
["e9a1","憿憸憌擗擖擐擏擉撽撉擃擛擳擙攳敿敼斢曈暾曀曊曋曏暽暻暺曌朣樴橦橉橧樲橨樾橝橭橶橛橑樨橚樻樿橁橪橤橐橏橔橯橩橠樼橞橖橕橍橎橆歕歔歖殧殪殫毈毇氄氃氆澭濋澣濇澼濎濈潞濄澽澞濊澨瀄澥澮澺澬澪濏澿澸"],
["ea40","澢濉澫濍澯澲澰燅燂熿熸燖燀燁燋燔燊燇燏熽燘熼燆燚燛犝犞獩獦獧獬獥獫獪瑿璚璠璔璒璕璡甋疀瘯瘭瘱瘽瘳瘼瘵瘲瘰皻盦瞚瞝瞡瞜瞛瞢瞣瞕瞙"],
["eaa1","瞗磝磩磥磪磞磣磛磡磢磭磟磠禤穄穈穇窶窸窵窱窷篞篣篧篝篕篥篚篨篹篔篪篢篜篫篘篟糒糔糗糐糑縒縡縗縌縟縠縓縎縜縕縚縢縋縏縖縍縔縥縤罃罻罼罺羱翯耪耩聬膱膦膮膹膵膫膰膬膴膲膷膧臲艕艖艗蕖蕅蕫蕍蕓蕡蕘"],
["eb40","蕀蕆蕤蕁蕢蕄蕑蕇蕣蔾蕛蕱蕎蕮蕵蕕蕧蕠薌蕦蕝蕔蕥蕬虣虥虤螛螏螗螓螒螈螁螖螘蝹螇螣螅螐螑螝螄螔螜螚螉褞褦褰褭褮褧褱褢褩褣褯褬褟觱諠"],
["eba1","諢諲諴諵諝謔諤諟諰諈諞諡諨諿諯諻貑貒貐賵賮賱賰賳赬赮趥趧踳踾踸蹀蹅踶踼踽蹁踰踿躽輶輮輵輲輹輷輴遶遹遻邆郺鄳鄵鄶醓醐醑醍醏錧錞錈錟錆錏鍺錸錼錛錣錒錁鍆錭錎錍鋋錝鋺錥錓鋹鋷錴錂錤鋿錩錹錵錪錔錌"],
["ec40","錋鋾錉錀鋻錖閼闍閾閹閺閶閿閵閽隩雔霋霒霐鞙鞗鞔韰韸頵頯頲餤餟餧餩馞駮駬駥駤駰駣駪駩駧骹骿骴骻髶髺髹髷鬳鮀鮅鮇魼魾魻鮂鮓鮒鮐魺鮕"],
["eca1","魽鮈鴥鴗鴠鴞鴔鴩鴝鴘鴢鴐鴙鴟麈麆麇麮麭黕黖黺鼒鼽儦儥儢儤儠儩勴嚓嚌嚍嚆嚄嚃噾嚂噿嚁壖壔壏壒嬭嬥嬲嬣嬬嬧嬦嬯嬮孻寱寲嶷幬幪徾徻懃憵憼懧懠懥懤懨懞擯擩擣擫擤擨斁斀斶旚曒檍檖檁檥檉檟檛檡檞檇檓檎"],
["ed40","檕檃檨檤檑橿檦檚檅檌檒歛殭氉濌澩濴濔濣濜濭濧濦濞濲濝濢濨燡燱燨燲燤燰燢獳獮獯璗璲璫璐璪璭璱璥璯甐甑甒甏疄癃癈癉癇皤盩瞵瞫瞲瞷瞶"],
["eda1","瞴瞱瞨矰磳磽礂磻磼磲礅磹磾礄禫禨穜穛穖穘穔穚窾竀竁簅簏篲簀篿篻簎篴簋篳簂簉簃簁篸篽簆篰篱簐簊糨縭縼繂縳顈縸縪繉繀繇縩繌縰縻縶繄縺罅罿罾罽翴翲耬膻臄臌臊臅臇膼臩艛艚艜薃薀薏薧薕薠薋薣蕻薤薚薞"],
["ee40","蕷蕼薉薡蕺蕸蕗薎薖薆薍薙薝薁薢薂薈薅蕹蕶薘薐薟虨螾螪螭蟅螰螬螹螵螼螮蟉蟃蟂蟌螷螯蟄蟊螴螶螿螸螽蟞螲褵褳褼褾襁襒褷襂覭覯覮觲觳謞"],
["eea1","謘謖謑謅謋謢謏謒謕謇謍謈謆謜謓謚豏豰豲豱豯貕貔賹赯蹎蹍蹓蹐蹌蹇轃轀邅遾鄸醚醢醛醙醟醡醝醠鎡鎃鎯鍤鍖鍇鍼鍘鍜鍶鍉鍐鍑鍠鍭鎏鍌鍪鍹鍗鍕鍒鍏鍱鍷鍻鍡鍞鍣鍧鎀鍎鍙闇闀闉闃闅閷隮隰隬霠霟霘霝霙鞚鞡鞜"],
["ef40","鞞鞝韕韔韱顁顄顊顉顅顃餥餫餬餪餳餲餯餭餱餰馘馣馡騂駺駴駷駹駸駶駻駽駾駼騃骾髾髽鬁髼魈鮚鮨鮞鮛鮦鮡鮥鮤鮆鮢鮠鮯鴳鵁鵧鴶鴮鴯鴱鴸鴰"],
["efa1","鵅鵂鵃鴾鴷鵀鴽翵鴭麊麉麍麰黈黚黻黿鼤鼣鼢齔龠儱儭儮嚘嚜嚗嚚嚝嚙奰嬼屩屪巀幭幮懘懟懭懮懱懪懰懫懖懩擿攄擽擸攁攃擼斔旛曚曛曘櫅檹檽櫡櫆檺檶檷櫇檴檭歞毉氋瀇瀌瀍瀁瀅瀔瀎濿瀀濻瀦濼濷瀊爁燿燹爃燽獶"],
["f040","璸瓀璵瓁璾璶璻瓂甔甓癜癤癙癐癓癗癚皦皽盬矂瞺磿礌礓礔礉礐礒礑禭禬穟簜簩簙簠簟簭簝簦簨簢簥簰繜繐繖繣繘繢繟繑繠繗繓羵羳翷翸聵臑臒"],
["f0a1","臐艟艞薴藆藀藃藂薳薵薽藇藄薿藋藎藈藅薱薶藒蘤薸薷薾虩蟧蟦蟢蟛蟫蟪蟥蟟蟳蟤蟔蟜蟓蟭蟘蟣螤蟗蟙蠁蟴蟨蟝襓襋襏襌襆襐襑襉謪謧謣謳謰謵譇謯謼謾謱謥謷謦謶謮謤謻謽謺豂豵貙貘貗賾贄贂贀蹜蹢蹠蹗蹖蹞蹥蹧"],
["f140","蹛蹚蹡蹝蹩蹔轆轇轈轋鄨鄺鄻鄾醨醥醧醯醪鎵鎌鎒鎷鎛鎝鎉鎧鎎鎪鎞鎦鎕鎈鎙鎟鎍鎱鎑鎲鎤鎨鎴鎣鎥闒闓闑隳雗雚巂雟雘雝霣霢霥鞬鞮鞨鞫鞤鞪"],
["f1a1","鞢鞥韗韙韖韘韺顐顑顒颸饁餼餺騏騋騉騍騄騑騊騅騇騆髀髜鬈鬄鬅鬩鬵魊魌魋鯇鯆鯃鮿鯁鮵鮸鯓鮶鯄鮹鮽鵜鵓鵏鵊鵛鵋鵙鵖鵌鵗鵒鵔鵟鵘鵚麎麌黟鼁鼀鼖鼥鼫鼪鼩鼨齌齕儴儵劖勷厴嚫嚭嚦嚧嚪嚬壚壝壛夒嬽嬾嬿巃幰"],
["f240","徿懻攇攐攍攉攌攎斄旞旝曞櫧櫠櫌櫑櫙櫋櫟櫜櫐櫫櫏櫍櫞歠殰氌瀙瀧瀠瀖瀫瀡瀢瀣瀩瀗瀤瀜瀪爌爊爇爂爅犥犦犤犣犡瓋瓅璷瓃甖癠矉矊矄矱礝礛"],
["f2a1","礡礜礗礞禰穧穨簳簼簹簬簻糬糪繶繵繸繰繷繯繺繲繴繨罋罊羃羆羷翽翾聸臗臕艤艡艣藫藱藭藙藡藨藚藗藬藲藸藘藟藣藜藑藰藦藯藞藢蠀蟺蠃蟶蟷蠉蠌蠋蠆蟼蠈蟿蠊蠂襢襚襛襗襡襜襘襝襙覈覷覶觶譐譈譊譀譓譖譔譋譕"],
["f340","譑譂譒譗豃豷豶貚贆贇贉趬趪趭趫蹭蹸蹳蹪蹯蹻軂轒轑轏轐轓辴酀鄿醰醭鏞鏇鏏鏂鏚鏐鏹鏬鏌鏙鎩鏦鏊鏔鏮鏣鏕鏄鏎鏀鏒鏧镽闚闛雡霩霫霬霨霦"],
["f3a1","鞳鞷鞶韝韞韟顜顙顝顗颿颽颻颾饈饇饃馦馧騚騕騥騝騤騛騢騠騧騣騞騜騔髂鬋鬊鬎鬌鬷鯪鯫鯠鯞鯤鯦鯢鯰鯔鯗鯬鯜鯙鯥鯕鯡鯚鵷鶁鶊鶄鶈鵱鶀鵸鶆鶋鶌鵽鵫鵴鵵鵰鵩鶅鵳鵻鶂鵯鵹鵿鶇鵨麔麑黀黼鼭齀齁齍齖齗齘匷嚲"],
["f440","嚵嚳壣孅巆巇廮廯忀忁懹攗攖攕攓旟曨曣曤櫳櫰櫪櫨櫹櫱櫮櫯瀼瀵瀯瀷瀴瀱灂瀸瀿瀺瀹灀瀻瀳灁爓爔犨獽獼璺皫皪皾盭矌矎矏矍矲礥礣礧礨礤礩"],
["f4a1","禲穮穬穭竷籉籈籊籇籅糮繻繾纁纀羺翿聹臛臙舋艨艩蘢藿蘁藾蘛蘀藶蘄蘉蘅蘌藽蠙蠐蠑蠗蠓蠖襣襦覹觷譠譪譝譨譣譥譧譭趮躆躈躄轙轖轗轕轘轚邍酃酁醷醵醲醳鐋鐓鏻鐠鐏鐔鏾鐕鐐鐨鐙鐍鏵鐀鏷鐇鐎鐖鐒鏺鐉鏸鐊鏿"],
["f540","鏼鐌鏶鐑鐆闞闠闟霮霯鞹鞻韽韾顠顢顣顟飁飂饐饎饙饌饋饓騲騴騱騬騪騶騩騮騸騭髇髊髆鬐鬒鬑鰋鰈鯷鰅鰒鯸鱀鰇鰎鰆鰗鰔鰉鶟鶙鶤鶝鶒鶘鶐鶛"],
["f5a1","鶠鶔鶜鶪鶗鶡鶚鶢鶨鶞鶣鶿鶩鶖鶦鶧麙麛麚黥黤黧黦鼰鼮齛齠齞齝齙龑儺儹劘劗囃嚽嚾孈孇巋巏廱懽攛欂櫼欃櫸欀灃灄灊灈灉灅灆爝爚爙獾甗癪矐礭礱礯籔籓糲纊纇纈纋纆纍罍羻耰臝蘘蘪蘦蘟蘣蘜蘙蘧蘮蘡蘠蘩蘞蘥"],
["f640","蠩蠝蠛蠠蠤蠜蠫衊襭襩襮襫觺譹譸譅譺譻贐贔趯躎躌轞轛轝酆酄酅醹鐿鐻鐶鐩鐽鐼鐰鐹鐪鐷鐬鑀鐱闥闤闣霵霺鞿韡顤飉飆飀饘饖騹騽驆驄驂驁騺"],
["f6a1","騿髍鬕鬗鬘鬖鬺魒鰫鰝鰜鰬鰣鰨鰩鰤鰡鶷鶶鶼鷁鷇鷊鷏鶾鷅鷃鶻鶵鷎鶹鶺鶬鷈鶱鶭鷌鶳鷍鶲鹺麜黫黮黭鼛鼘鼚鼱齎齥齤龒亹囆囅囋奱孋孌巕巑廲攡攠攦攢欋欈欉氍灕灖灗灒爞爟犩獿瓘瓕瓙瓗癭皭礵禴穰穱籗籜籙籛籚"],
["f740","糴糱纑罏羇臞艫蘴蘵蘳蘬蘲蘶蠬蠨蠦蠪蠥襱覿覾觻譾讄讂讆讅譿贕躕躔躚躒躐躖躗轠轢酇鑌鑐鑊鑋鑏鑇鑅鑈鑉鑆霿韣顪顩飋饔饛驎驓驔驌驏驈驊"],
["f7a1","驉驒驐髐鬙鬫鬻魖魕鱆鱈鰿鱄鰹鰳鱁鰼鰷鰴鰲鰽鰶鷛鷒鷞鷚鷋鷐鷜鷑鷟鷩鷙鷘鷖鷵鷕鷝麶黰鼵鼳鼲齂齫龕龢儽劙壨壧奲孍巘蠯彏戁戃戄攩攥斖曫欑欒欏毊灛灚爢玂玁玃癰矔籧籦纕艬蘺虀蘹蘼蘱蘻蘾蠰蠲蠮蠳襶襴襳觾"],
["f840","讌讎讋讈豅贙躘轤轣醼鑢鑕鑝鑗鑞韄韅頀驖驙鬞鬟鬠鱒鱘鱐鱊鱍鱋鱕鱙鱌鱎鷻鷷鷯鷣鷫鷸鷤鷶鷡鷮鷦鷲鷰鷢鷬鷴鷳鷨鷭黂黐黲黳鼆鼜鼸鼷鼶齃齏"],
["f8a1","齱齰齮齯囓囍孎屭攭曭曮欓灟灡灝灠爣瓛瓥矕礸禷禶籪纗羉艭虃蠸蠷蠵衋讔讕躞躟躠躝醾醽釂鑫鑨鑩雥靆靃靇韇韥驞髕魙鱣鱧鱦鱢鱞鱠鸂鷾鸇鸃鸆鸅鸀鸁鸉鷿鷽鸄麠鼞齆齴齵齶囔攮斸欘欙欗欚灢爦犪矘矙礹籩籫糶纚"],
["f940","纘纛纙臠臡虆虇虈襹襺襼襻觿讘讙躥躤躣鑮鑭鑯鑱鑳靉顲饟鱨鱮鱭鸋鸍鸐鸏鸒鸑麡黵鼉齇齸齻齺齹圞灦籯蠼趲躦釃鑴鑸鑶鑵驠鱴鱳鱱鱵鸔鸓黶鼊"],
["f9a1","龤灨灥糷虪蠾蠽蠿讞貜躩軉靋顳顴飌饡馫驤驦驧鬤鸕鸗齈戇欞爧虌躨钂钀钁驩驨鬮鸙爩虋讟钃鱹麷癵驫鱺鸝灩灪麤齾齉龘碁銹裏墻恒粧嫺╔╦╗╠╬╣╚╩╝╒╤╕╞╪╡╘╧╛╓╥╖╟╫╢╙╨╜║═╭╮╰╯▓"]
]

},{}],22:[function(require,module,exports){
module.exports=[
["0","\u0000",127],
["8ea1","｡",62],
["a1a1","　、。，．・：；？！゛゜´｀¨＾￣＿ヽヾゝゞ〃仝々〆〇ー―‐／＼～∥｜…‥‘’“”（）〔〕［］｛｝〈",9,"＋－±×÷＝≠＜＞≦≧∞∴♂♀°′″℃￥＄￠￡％＃＆＊＠§☆★○●◎◇"],
["a2a1","◆□■△▲▽▼※〒→←↑↓〓"],
["a2ba","∈∋⊆⊇⊂⊃∪∩"],
["a2ca","∧∨￢⇒⇔∀∃"],
["a2dc","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"],
["a2f2","Å‰♯♭♪†‡¶"],
["a2fe","◯"],
["a3b0","０",9],
["a3c1","Ａ",25],
["a3e1","ａ",25],
["a4a1","ぁ",82],
["a5a1","ァ",85],
["a6a1","Α",16,"Σ",6],
["a6c1","α",16,"σ",6],
["a7a1","А",5,"ЁЖ",25],
["a7d1","а",5,"ёж",25],
["a8a1","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"],
["ada1","①",19,"Ⅰ",9],
["adc0","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"],
["addf","㍻〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"],
["b0a1","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"],
["b1a1","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応"],
["b2a1","押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"],
["b3a1","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱"],
["b4a1","粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"],
["b5a1","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京"],
["b6a1","供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"],
["b7a1","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲"],
["b8a1","検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"],
["b9a1","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込"],
["baa1","此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"],
["bba1","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時"],
["bca1","次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"],
["bda1","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償"],
["bea1","勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"],
["bfa1","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾"],
["c0a1","澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"],
["c1a1","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎"],
["c2a1","臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"],
["c3a1","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵"],
["c4a1","帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"],
["c5a1","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到"],
["c6a1","董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"],
["c7a1","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦"],
["c8a1","函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"],
["c9a1","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服"],
["caa1","福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"],
["cba1","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満"],
["cca1","漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"],
["cda1","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃"],
["cea1","痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"],
["cfa1","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"],
["d0a1","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"],
["d1a1","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨"],
["d2a1","辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"],
["d3a1","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉"],
["d4a1","圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"],
["d5a1","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓"],
["d6a1","屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"],
["d7a1","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚"],
["d8a1","悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"],
["d9a1","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼"],
["daa1","據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"],
["dba1","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍"],
["dca1","棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"],
["dda1","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾"],
["dea1","沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"],
["dfa1","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼"],
["e0a1","燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"],
["e1a1","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰"],
["e2a1","癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"],
["e3a1","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐"],
["e4a1","筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"],
["e5a1","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺"],
["e6a1","罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"],
["e7a1","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙"],
["e8a1","茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"],
["e9a1","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙"],
["eaa1","蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"],
["eba1","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫"],
["eca1","譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"],
["eda1","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸"],
["eea1","遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"],
["efa1","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞"],
["f0a1","陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"],
["f1a1","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷"],
["f2a1","髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"],
["f3a1","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠"],
["f4a1","堯槇遙瑤凜熙"],
["f9a1","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德"],
["faa1","忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"],
["fba1","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚"],
["fca1","釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"],
["fcf1","ⅰ",9,"￢￤＇＂"],
["8fa2af","˘ˇ¸˙˝¯˛˚～΄΅"],
["8fa2c2","¡¦¿"],
["8fa2eb","ºª©®™¤№"],
["8fa6e1","ΆΈΉΊΪ"],
["8fa6e7","Ό"],
["8fa6e9","ΎΫ"],
["8fa6ec","Ώ"],
["8fa6f1","άέήίϊΐόςύϋΰώ"],
["8fa7c2","Ђ",10,"ЎЏ"],
["8fa7f2","ђ",10,"ўџ"],
["8fa9a1","ÆĐ"],
["8fa9a4","Ħ"],
["8fa9a6","Ĳ"],
["8fa9a8","ŁĿ"],
["8fa9ab","ŊØŒ"],
["8fa9af","ŦÞ"],
["8fa9c1","æđðħıĳĸłŀŉŋøœßŧþ"],
["8faaa1","ÁÀÄÂĂǍĀĄÅÃĆĈČÇĊĎÉÈËÊĚĖĒĘ"],
["8faaba","ĜĞĢĠĤÍÌÏÎǏİĪĮĨĴĶĹĽĻŃŇŅÑÓÒÖÔǑŐŌÕŔŘŖŚŜŠŞŤŢÚÙÜÛŬǓŰŪŲŮŨǗǛǙǕŴÝŸŶŹŽŻ"],
["8faba1","áàäâăǎāąåãćĉčçċďéèëêěėēęǵĝğ"],
["8fabbd","ġĥíìïîǐ"],
["8fabc5","īįĩĵķĺľļńňņñóòöôǒőōõŕřŗśŝšşťţúùüûŭǔűūųůũǘǜǚǖŵýÿŷźžż"],
["8fb0a1","丂丄丅丌丒丟丣两丨丫丮丯丰丵乀乁乄乇乑乚乜乣乨乩乴乵乹乿亍亖亗亝亯亹仃仐仚仛仠仡仢仨仯仱仳仵份仾仿伀伂伃伈伋伌伒伕伖众伙伮伱你伳伵伷伹伻伾佀佂佈佉佋佌佒佔佖佘佟佣佪佬佮佱佷佸佹佺佽佾侁侂侄"],
["8fb1a1","侅侉侊侌侎侐侒侓侔侗侙侚侞侟侲侷侹侻侼侽侾俀俁俅俆俈俉俋俌俍俏俒俜俠俢俰俲俼俽俿倀倁倄倇倊倌倎倐倓倗倘倛倜倝倞倢倧倮倰倲倳倵偀偁偂偅偆偊偌偎偑偒偓偗偙偟偠偢偣偦偧偪偭偰偱倻傁傃傄傆傊傎傏傐"],
["8fb2a1","傒傓傔傖傛傜傞",4,"傪傯傰傹傺傽僀僃僄僇僌僎僐僓僔僘僜僝僟僢僤僦僨僩僯僱僶僺僾儃儆儇儈儋儌儍儎僲儐儗儙儛儜儝儞儣儧儨儬儭儯儱儳儴儵儸儹兂兊兏兓兕兗兘兟兤兦兾冃冄冋冎冘冝冡冣冭冸冺冼冾冿凂"],
["8fb3a1","凈减凑凒凓凕凘凞凢凥凮凲凳凴凷刁刂刅划刓刕刖刘刢刨刱刲刵刼剅剉剕剗剘剚剜剟剠剡剦剮剷剸剹劀劂劅劊劌劓劕劖劗劘劚劜劤劥劦劧劯劰劶劷劸劺劻劽勀勄勆勈勌勏勑勔勖勛勜勡勥勨勩勪勬勰勱勴勶勷匀匃匊匋"],
["8fb4a1","匌匑匓匘匛匜匞匟匥匧匨匩匫匬匭匰匲匵匼匽匾卂卌卋卙卛卡卣卥卬卭卲卹卾厃厇厈厎厓厔厙厝厡厤厪厫厯厲厴厵厷厸厺厽叀叅叏叒叓叕叚叝叞叠另叧叵吂吓吚吡吧吨吪启吱吴吵呃呄呇呍呏呞呢呤呦呧呩呫呭呮呴呿"],
["8fb5a1","咁咃咅咈咉咍咑咕咖咜咟咡咦咧咩咪咭咮咱咷咹咺咻咿哆哊响哎哠哪哬哯哶哼哾哿唀唁唅唈唉唌唍唎唕唪唫唲唵唶唻唼唽啁啇啉啊啍啐啑啘啚啛啞啠啡啤啦啿喁喂喆喈喎喏喑喒喓喔喗喣喤喭喲喿嗁嗃嗆嗉嗋嗌嗎嗑嗒"],
["8fb6a1","嗓嗗嗘嗛嗞嗢嗩嗶嗿嘅嘈嘊嘍",5,"嘙嘬嘰嘳嘵嘷嘹嘻嘼嘽嘿噀噁噃噄噆噉噋噍噏噔噞噠噡噢噣噦噩噭噯噱噲噵嚄嚅嚈嚋嚌嚕嚙嚚嚝嚞嚟嚦嚧嚨嚩嚫嚬嚭嚱嚳嚷嚾囅囉囊囋囏囐囌囍囙囜囝囟囡囤",4,"囱囫园"],
["8fb7a1","囶囷圁圂圇圊圌圑圕圚圛圝圠圢圣圤圥圩圪圬圮圯圳圴圽圾圿坅坆坌坍坒坢坥坧坨坫坭",4,"坳坴坵坷坹坺坻坼坾垁垃垌垔垗垙垚垜垝垞垟垡垕垧垨垩垬垸垽埇埈埌埏埕埝埞埤埦埧埩埭埰埵埶埸埽埾埿堃堄堈堉埡"],
["8fb8a1","堌堍堛堞堟堠堦堧堭堲堹堿塉塌塍塏塐塕塟塡塤塧塨塸塼塿墀墁墇墈墉墊墌墍墏墐墔墖墝墠墡墢墦墩墱墲壄墼壂壈壍壎壐壒壔壖壚壝壡壢壩壳夅夆夋夌夒夓夔虁夝夡夣夤夨夯夰夳夵夶夿奃奆奒奓奙奛奝奞奟奡奣奫奭"],
["8fb9a1","奯奲奵奶她奻奼妋妌妎妒妕妗妟妤妧妭妮妯妰妳妷妺妼姁姃姄姈姊姍姒姝姞姟姣姤姧姮姯姱姲姴姷娀娄娌娍娎娒娓娞娣娤娧娨娪娭娰婄婅婇婈婌婐婕婞婣婥婧婭婷婺婻婾媋媐媓媖媙媜媞媟媠媢媧媬媱媲媳媵媸媺媻媿"],
["8fbaa1","嫄嫆嫈嫏嫚嫜嫠嫥嫪嫮嫵嫶嫽嬀嬁嬈嬗嬴嬙嬛嬝嬡嬥嬭嬸孁孋孌孒孖孞孨孮孯孼孽孾孿宁宄宆宊宎宐宑宓宔宖宨宩宬宭宯宱宲宷宺宼寀寁寍寏寖",4,"寠寯寱寴寽尌尗尞尟尣尦尩尫尬尮尰尲尵尶屙屚屜屢屣屧屨屩"],
["8fbba1","屭屰屴屵屺屻屼屽岇岈岊岏岒岝岟岠岢岣岦岪岲岴岵岺峉峋峒峝峗峮峱峲峴崁崆崍崒崫崣崤崦崧崱崴崹崽崿嵂嵃嵆嵈嵕嵑嵙嵊嵟嵠嵡嵢嵤嵪嵭嵰嵹嵺嵾嵿嶁嶃嶈嶊嶒嶓嶔嶕嶙嶛嶟嶠嶧嶫嶰嶴嶸嶹巃巇巋巐巎巘巙巠巤"],
["8fbca1","巩巸巹帀帇帍帒帔帕帘帟帠帮帨帲帵帾幋幐幉幑幖幘幛幜幞幨幪",4,"幰庀庋庎庢庤庥庨庪庬庱庳庽庾庿廆廌廋廎廑廒廔廕廜廞廥廫异弆弇弈弎弙弜弝弡弢弣弤弨弫弬弮弰弴弶弻弽弿彀彄彅彇彍彐彔彘彛彠彣彤彧"],
["8fbda1","彯彲彴彵彸彺彽彾徉徍徏徖徜徝徢徧徫徤徬徯徰徱徸忄忇忈忉忋忐",4,"忞忡忢忨忩忪忬忭忮忯忲忳忶忺忼怇怊怍怓怔怗怘怚怟怤怭怳怵恀恇恈恉恌恑恔恖恗恝恡恧恱恾恿悂悆悈悊悎悑悓悕悘悝悞悢悤悥您悰悱悷"],
["8fbea1","悻悾惂惄惈惉惊惋惎惏惔惕惙惛惝惞惢惥惲惵惸惼惽愂愇愊愌愐",4,"愖愗愙愜愞愢愪愫愰愱愵愶愷愹慁慅慆慉慞慠慬慲慸慻慼慿憀憁憃憄憋憍憒憓憗憘憜憝憟憠憥憨憪憭憸憹憼懀懁懂懎懏懕懜懝懞懟懡懢懧懩懥"],
["8fbfa1","懬懭懯戁戃戄戇戓戕戜戠戢戣戧戩戫戹戽扂扃扄扆扌扐扑扒扔扖扚扜扤扭扯扳扺扽抍抎抏抐抦抨抳抶抷抺抾抿拄拎拕拖拚拪拲拴拼拽挃挄挊挋挍挐挓挖挘挩挪挭挵挶挹挼捁捂捃捄捆捊捋捎捒捓捔捘捛捥捦捬捭捱捴捵"],
["8fc0a1","捸捼捽捿掂掄掇掊掐掔掕掙掚掞掤掦掭掮掯掽揁揅揈揎揑揓揔揕揜揠揥揪揬揲揳揵揸揹搉搊搐搒搔搘搞搠搢搤搥搩搪搯搰搵搽搿摋摏摑摒摓摔摚摛摜摝摟摠摡摣摭摳摴摻摽撅撇撏撐撑撘撙撛撝撟撡撣撦撨撬撳撽撾撿"],
["8fc1a1","擄擉擊擋擌擎擐擑擕擗擤擥擩擪擭擰擵擷擻擿攁攄攈攉攊攏攓攔攖攙攛攞攟攢攦攩攮攱攺攼攽敃敇敉敐敒敔敟敠敧敫敺敽斁斅斊斒斕斘斝斠斣斦斮斲斳斴斿旂旈旉旎旐旔旖旘旟旰旲旴旵旹旾旿昀昄昈昉昍昑昒昕昖昝"],
["8fc2a1","昞昡昢昣昤昦昩昪昫昬昮昰昱昳昹昷晀晅晆晊晌晑晎晗晘晙晛晜晠晡曻晪晫晬晾晳晵晿晷晸晹晻暀晼暋暌暍暐暒暙暚暛暜暟暠暤暭暱暲暵暻暿曀曂曃曈曌曎曏曔曛曟曨曫曬曮曺朅朇朎朓朙朜朠朢朳朾杅杇杈杌杔杕杝"],
["8fc3a1","杦杬杮杴杶杻极构枎枏枑枓枖枘枙枛枰枱枲枵枻枼枽柹柀柂柃柅柈柉柒柗柙柜柡柦柰柲柶柷桒栔栙栝栟栨栧栬栭栯栰栱栳栻栿桄桅桊桌桕桗桘桛桫桮",4,"桵桹桺桻桼梂梄梆梈梖梘梚梜梡梣梥梩梪梮梲梻棅棈棌棏"],
["8fc4a1","棐棑棓棖棙棜棝棥棨棪棫棬棭棰棱棵棶棻棼棽椆椉椊椐椑椓椖椗椱椳椵椸椻楂楅楉楎楗楛楣楤楥楦楨楩楬楰楱楲楺楻楿榀榍榒榖榘榡榥榦榨榫榭榯榷榸榺榼槅槈槑槖槗槢槥槮槯槱槳槵槾樀樁樃樏樑樕樚樝樠樤樨樰樲"],
["8fc5a1","樴樷樻樾樿橅橆橉橊橎橐橑橒橕橖橛橤橧橪橱橳橾檁檃檆檇檉檋檑檛檝檞檟檥檫檯檰檱檴檽檾檿櫆櫉櫈櫌櫐櫔櫕櫖櫜櫝櫤櫧櫬櫰櫱櫲櫼櫽欂欃欆欇欉欏欐欑欗欛欞欤欨欫欬欯欵欶欻欿歆歊歍歒歖歘歝歠歧歫歮歰歵歽"],
["8fc6a1","歾殂殅殗殛殟殠殢殣殨殩殬殭殮殰殸殹殽殾毃毄毉毌毖毚毡毣毦毧毮毱毷毹毿氂氄氅氉氍氎氐氒氙氟氦氧氨氬氮氳氵氶氺氻氿汊汋汍汏汒汔汙汛汜汫汭汯汴汶汸汹汻沅沆沇沉沔沕沗沘沜沟沰沲沴泂泆泍泏泐泑泒泔泖"],
["8fc7a1","泚泜泠泧泩泫泬泮泲泴洄洇洊洎洏洑洓洚洦洧洨汧洮洯洱洹洼洿浗浞浟浡浥浧浯浰浼涂涇涑涒涔涖涗涘涪涬涴涷涹涽涿淄淈淊淎淏淖淛淝淟淠淢淥淩淯淰淴淶淼渀渄渞渢渧渲渶渹渻渼湄湅湈湉湋湏湑湒湓湔湗湜湝湞"],
["8fc8a1","湢湣湨湳湻湽溍溓溙溠溧溭溮溱溳溻溿滀滁滃滇滈滊滍滎滏滫滭滮滹滻滽漄漈漊漌漍漖漘漚漛漦漩漪漯漰漳漶漻漼漭潏潑潒潓潗潙潚潝潞潡潢潨潬潽潾澃澇澈澋澌澍澐澒澓澔澖澚澟澠澥澦澧澨澮澯澰澵澶澼濅濇濈濊"],
["8fc9a1","濚濞濨濩濰濵濹濼濽瀀瀅瀆瀇瀍瀗瀠瀣瀯瀴瀷瀹瀼灃灄灈灉灊灋灔灕灝灞灎灤灥灬灮灵灶灾炁炅炆炔",4,"炛炤炫炰炱炴炷烊烑烓烔烕烖烘烜烤烺焃",4,"焋焌焏焞焠焫焭焯焰焱焸煁煅煆煇煊煋煐煒煗煚煜煞煠"],
["8fcaa1","煨煹熀熅熇熌熒熚熛熠熢熯熰熲熳熺熿燀燁燄燋燌燓燖燙燚燜燸燾爀爇爈爉爓爗爚爝爟爤爫爯爴爸爹牁牂牃牅牎牏牐牓牕牖牚牜牞牠牣牨牫牮牯牱牷牸牻牼牿犄犉犍犎犓犛犨犭犮犱犴犾狁狇狉狌狕狖狘狟狥狳狴狺狻"],
["8fcba1","狾猂猄猅猇猋猍猒猓猘猙猞猢猤猧猨猬猱猲猵猺猻猽獃獍獐獒獖獘獝獞獟獠獦獧獩獫獬獮獯獱獷獹獼玀玁玃玅玆玎玐玓玕玗玘玜玞玟玠玢玥玦玪玫玭玵玷玹玼玽玿珅珆珉珋珌珏珒珓珖珙珝珡珣珦珧珩珴珵珷珹珺珻珽"],
["8fcca1","珿琀琁琄琇琊琑琚琛琤琦琨",9,"琹瑀瑃瑄瑆瑇瑋瑍瑑瑒瑗瑝瑢瑦瑧瑨瑫瑭瑮瑱瑲璀璁璅璆璇璉璏璐璑璒璘璙璚璜璟璠璡璣璦璨璩璪璫璮璯璱璲璵璹璻璿瓈瓉瓌瓐瓓瓘瓚瓛瓞瓟瓤瓨瓪瓫瓯瓴瓺瓻瓼瓿甆"],
["8fcda1","甒甖甗甠甡甤甧甩甪甯甶甹甽甾甿畀畃畇畈畎畐畒畗畞畟畡畯畱畹",5,"疁疅疐疒疓疕疙疜疢疤疴疺疿痀痁痄痆痌痎痏痗痜痟痠痡痤痧痬痮痯痱痹瘀瘂瘃瘄瘇瘈瘊瘌瘏瘒瘓瘕瘖瘙瘛瘜瘝瘞瘣瘥瘦瘩瘭瘲瘳瘵瘸瘹"],
["8fcea1","瘺瘼癊癀癁癃癄癅癉癋癕癙癟癤癥癭癮癯癱癴皁皅皌皍皕皛皜皝皟皠皢",6,"皪皭皽盁盅盉盋盌盎盔盙盠盦盨盬盰盱盶盹盼眀眆眊眎眒眔眕眗眙眚眜眢眨眭眮眯眴眵眶眹眽眾睂睅睆睊睍睎睏睒睖睗睜睞睟睠睢"],
["8fcfa1","睤睧睪睬睰睲睳睴睺睽瞀瞄瞌瞍瞔瞕瞖瞚瞟瞢瞧瞪瞮瞯瞱瞵瞾矃矉矑矒矕矙矞矟矠矤矦矪矬矰矱矴矸矻砅砆砉砍砎砑砝砡砢砣砭砮砰砵砷硃硄硇硈硌硎硒硜硞硠硡硣硤硨硪确硺硾碊碏碔碘碡碝碞碟碤碨碬碭碰碱碲碳"],
["8fd0a1","碻碽碿磇磈磉磌磎磒磓磕磖磤磛磟磠磡磦磪磲磳礀磶磷磺磻磿礆礌礐礚礜礞礟礠礥礧礩礭礱礴礵礻礽礿祄祅祆祊祋祏祑祔祘祛祜祧祩祫祲祹祻祼祾禋禌禑禓禔禕禖禘禛禜禡禨禩禫禯禱禴禸离秂秄秇秈秊秏秔秖秚秝秞"],
["8fd1a1","秠秢秥秪秫秭秱秸秼稂稃稇稉稊稌稑稕稛稞稡稧稫稭稯稰稴稵稸稹稺穄穅穇穈穌穕穖穙穜穝穟穠穥穧穪穭穵穸穾窀窂窅窆窊窋窐窑窔窞窠窣窬窳窵窹窻窼竆竉竌竎竑竛竨竩竫竬竱竴竻竽竾笇笔笟笣笧笩笪笫笭笮笯笰"],
["8fd2a1","笱笴笽笿筀筁筇筎筕筠筤筦筩筪筭筯筲筳筷箄箉箎箐箑箖箛箞箠箥箬箯箰箲箵箶箺箻箼箽篂篅篈篊篔篖篗篙篚篛篨篪篲篴篵篸篹篺篼篾簁簂簃簄簆簉簋簌簎簏簙簛簠簥簦簨簬簱簳簴簶簹簺籆籊籕籑籒籓籙",5],
["8fd3a1","籡籣籧籩籭籮籰籲籹籼籽粆粇粏粔粞粠粦粰粶粷粺粻粼粿糄糇糈糉糍糏糓糔糕糗糙糚糝糦糩糫糵紃紇紈紉紏紑紒紓紖紝紞紣紦紪紭紱紼紽紾絀絁絇絈絍絑絓絗絙絚絜絝絥絧絪絰絸絺絻絿綁綂綃綅綆綈綋綌綍綑綖綗綝"],
["8fd4a1","綞綦綧綪綳綶綷綹緂",4,"緌緍緎緗緙縀緢緥緦緪緫緭緱緵緶緹緺縈縐縑縕縗縜縝縠縧縨縬縭縯縳縶縿繄繅繇繎繐繒繘繟繡繢繥繫繮繯繳繸繾纁纆纇纊纍纑纕纘纚纝纞缼缻缽缾缿罃罄罇罏罒罓罛罜罝罡罣罤罥罦罭"],
["8fd5a1","罱罽罾罿羀羋羍羏羐羑羖羗羜羡羢羦羪羭羴羼羿翀翃翈翎翏翛翟翣翥翨翬翮翯翲翺翽翾翿耇耈耊耍耎耏耑耓耔耖耝耞耟耠耤耦耬耮耰耴耵耷耹耺耼耾聀聄聠聤聦聭聱聵肁肈肎肜肞肦肧肫肸肹胈胍胏胒胔胕胗胘胠胭胮"],
["8fd6a1","胰胲胳胶胹胺胾脃脋脖脗脘脜脞脠脤脧脬脰脵脺脼腅腇腊腌腒腗腠腡腧腨腩腭腯腷膁膐膄膅膆膋膎膖膘膛膞膢膮膲膴膻臋臃臅臊臎臏臕臗臛臝臞臡臤臫臬臰臱臲臵臶臸臹臽臿舀舃舏舓舔舙舚舝舡舢舨舲舴舺艃艄艅艆"],
["8fd7a1","艋艎艏艑艖艜艠艣艧艭艴艻艽艿芀芁芃芄芇芉芊芎芑芔芖芘芚芛芠芡芣芤芧芨芩芪芮芰芲芴芷芺芼芾芿苆苐苕苚苠苢苤苨苪苭苯苶苷苽苾茀茁茇茈茊茋荔茛茝茞茟茡茢茬茭茮茰茳茷茺茼茽荂荃荄荇荍荎荑荕荖荗荰荸"],
["8fd8a1","荽荿莀莂莄莆莍莒莔莕莘莙莛莜莝莦莧莩莬莾莿菀菇菉菏菐菑菔菝荓菨菪菶菸菹菼萁萆萊萏萑萕萙莭萯萹葅葇葈葊葍葏葑葒葖葘葙葚葜葠葤葥葧葪葰葳葴葶葸葼葽蒁蒅蒒蒓蒕蒞蒦蒨蒩蒪蒯蒱蒴蒺蒽蒾蓀蓂蓇蓈蓌蓏蓓"],
["8fd9a1","蓜蓧蓪蓯蓰蓱蓲蓷蔲蓺蓻蓽蔂蔃蔇蔌蔎蔐蔜蔞蔢蔣蔤蔥蔧蔪蔫蔯蔳蔴蔶蔿蕆蕏",4,"蕖蕙蕜",6,"蕤蕫蕯蕹蕺蕻蕽蕿薁薅薆薉薋薌薏薓薘薝薟薠薢薥薧薴薶薷薸薼薽薾薿藂藇藊藋藎薭藘藚藟藠藦藨藭藳藶藼"],
["8fdaa1","藿蘀蘄蘅蘍蘎蘐蘑蘒蘘蘙蘛蘞蘡蘧蘩蘶蘸蘺蘼蘽虀虂虆虒虓虖虗虘虙虝虠",4,"虩虬虯虵虶虷虺蚍蚑蚖蚘蚚蚜蚡蚦蚧蚨蚭蚱蚳蚴蚵蚷蚸蚹蚿蛀蛁蛃蛅蛑蛒蛕蛗蛚蛜蛠蛣蛥蛧蚈蛺蛼蛽蜄蜅蜇蜋蜎蜏蜐蜓蜔蜙蜞蜟蜡蜣"],
["8fdba1","蜨蜮蜯蜱蜲蜹蜺蜼蜽蜾蝀蝃蝅蝍蝘蝝蝡蝤蝥蝯蝱蝲蝻螃",6,"螋螌螐螓螕螗螘螙螞螠螣螧螬螭螮螱螵螾螿蟁蟈蟉蟊蟎蟕蟖蟙蟚蟜蟟蟢蟣蟤蟪蟫蟭蟱蟳蟸蟺蟿蠁蠃蠆蠉蠊蠋蠐蠙蠒蠓蠔蠘蠚蠛蠜蠞蠟蠨蠭蠮蠰蠲蠵"],
["8fdca1","蠺蠼衁衃衅衈衉衊衋衎衑衕衖衘衚衜衟衠衤衩衱衹衻袀袘袚袛袜袟袠袨袪袺袽袾裀裊",4,"裑裒裓裛裞裧裯裰裱裵裷褁褆褍褎褏褕褖褘褙褚褜褠褦褧褨褰褱褲褵褹褺褾襀襂襅襆襉襏襒襗襚襛襜襡襢襣襫襮襰襳襵襺"],
["8fdda1","襻襼襽覉覍覐覔覕覛覜覟覠覥覰覴覵覶覷覼觔",4,"觥觩觫觭觱觳觶觹觽觿訄訅訇訏訑訒訔訕訞訠訢訤訦訫訬訯訵訷訽訾詀詃詅詇詉詍詎詓詖詗詘詜詝詡詥詧詵詶詷詹詺詻詾詿誀誃誆誋誏誐誒誖誗誙誟誧誩誮誯誳"],
["8fdea1","誶誷誻誾諃諆諈諉諊諑諓諔諕諗諝諟諬諰諴諵諶諼諿謅謆謋謑謜謞謟謊謭謰謷謼譂",4,"譈譒譓譔譙譍譞譣譭譶譸譹譼譾讁讄讅讋讍讏讔讕讜讞讟谸谹谽谾豅豇豉豋豏豑豓豔豗豘豛豝豙豣豤豦豨豩豭豳豵豶豻豾貆"],
["8fdfa1","貇貋貐貒貓貙貛貜貤貹貺賅賆賉賋賏賖賕賙賝賡賨賬賯賰賲賵賷賸賾賿贁贃贉贒贗贛赥赩赬赮赿趂趄趈趍趐趑趕趞趟趠趦趫趬趯趲趵趷趹趻跀跅跆跇跈跊跎跑跔跕跗跙跤跥跧跬跰趼跱跲跴跽踁踄踅踆踋踑踔踖踠踡踢"],
["8fe0a1","踣踦踧踱踳踶踷踸踹踽蹀蹁蹋蹍蹎蹏蹔蹛蹜蹝蹞蹡蹢蹩蹬蹭蹯蹰蹱蹹蹺蹻躂躃躉躐躒躕躚躛躝躞躢躧躩躭躮躳躵躺躻軀軁軃軄軇軏軑軔軜軨軮軰軱軷軹軺軭輀輂輇輈輏輐輖輗輘輞輠輡輣輥輧輨輬輭輮輴輵輶輷輺轀轁"],
["8fe1a1","轃轇轏轑",4,"轘轝轞轥辝辠辡辤辥辦辵辶辸达迀迁迆迊迋迍运迒迓迕迠迣迤迨迮迱迵迶迻迾适逄逈逌逘逛逨逩逯逪逬逭逳逴逷逿遃遄遌遛遝遢遦遧遬遰遴遹邅邈邋邌邎邐邕邗邘邙邛邠邡邢邥邰邲邳邴邶邽郌邾郃"],
["8fe2a1","郄郅郇郈郕郗郘郙郜郝郟郥郒郶郫郯郰郴郾郿鄀鄄鄅鄆鄈鄍鄐鄔鄖鄗鄘鄚鄜鄞鄠鄥鄢鄣鄧鄩鄮鄯鄱鄴鄶鄷鄹鄺鄼鄽酃酇酈酏酓酗酙酚酛酡酤酧酭酴酹酺酻醁醃醅醆醊醎醑醓醔醕醘醞醡醦醨醬醭醮醰醱醲醳醶醻醼醽醿"],
["8fe3a1","釂釃釅釓釔釗釙釚釞釤釥釩釪釬",5,"釷釹釻釽鈀鈁鈄鈅鈆鈇鈉鈊鈌鈐鈒鈓鈖鈘鈜鈝鈣鈤鈥鈦鈨鈮鈯鈰鈳鈵鈶鈸鈹鈺鈼鈾鉀鉂鉃鉆鉇鉊鉍鉎鉏鉑鉘鉙鉜鉝鉠鉡鉥鉧鉨鉩鉮鉯鉰鉵",4,"鉻鉼鉽鉿銈銉銊銍銎銒銗"],
["8fe4a1","銙銟銠銤銥銧銨銫銯銲銶銸銺銻銼銽銿",4,"鋅鋆鋇鋈鋋鋌鋍鋎鋐鋓鋕鋗鋘鋙鋜鋝鋟鋠鋡鋣鋥鋧鋨鋬鋮鋰鋹鋻鋿錀錂錈錍錑錔錕錜錝錞錟錡錤錥錧錩錪錳錴錶錷鍇鍈鍉鍐鍑鍒鍕鍗鍘鍚鍞鍤鍥鍧鍩鍪鍭鍯鍰鍱鍳鍴鍶"],
["8fe5a1","鍺鍽鍿鎀鎁鎂鎈鎊鎋鎍鎏鎒鎕鎘鎛鎞鎡鎣鎤鎦鎨鎫鎴鎵鎶鎺鎩鏁鏄鏅鏆鏇鏉",4,"鏓鏙鏜鏞鏟鏢鏦鏧鏹鏷鏸鏺鏻鏽鐁鐂鐄鐈鐉鐍鐎鐏鐕鐖鐗鐟鐮鐯鐱鐲鐳鐴鐻鐿鐽鑃鑅鑈鑊鑌鑕鑙鑜鑟鑡鑣鑨鑫鑭鑮鑯鑱鑲钄钃镸镹"],
["8fe6a1","镾閄閈閌閍閎閝閞閟閡閦閩閫閬閴閶閺閽閿闆闈闉闋闐闑闒闓闙闚闝闞闟闠闤闦阝阞阢阤阥阦阬阱阳阷阸阹阺阼阽陁陒陔陖陗陘陡陮陴陻陼陾陿隁隂隃隄隉隑隖隚隝隟隤隥隦隩隮隯隳隺雊雒嶲雘雚雝雞雟雩雯雱雺霂"],
["8fe7a1","霃霅霉霚霛霝霡霢霣霨霱霳靁靃靊靎靏靕靗靘靚靛靣靧靪靮靳靶靷靸靻靽靿鞀鞉鞕鞖鞗鞙鞚鞞鞟鞢鞬鞮鞱鞲鞵鞶鞸鞹鞺鞼鞾鞿韁韄韅韇韉韊韌韍韎韐韑韔韗韘韙韝韞韠韛韡韤韯韱韴韷韸韺頇頊頙頍頎頔頖頜頞頠頣頦"],
["8fe8a1","頫頮頯頰頲頳頵頥頾顄顇顊顑顒顓顖顗顙顚顢顣顥顦顪顬颫颭颮颰颴颷颸颺颻颿飂飅飈飌飡飣飥飦飧飪飳飶餂餇餈餑餕餖餗餚餛餜餟餢餦餧餫餱",4,"餹餺餻餼饀饁饆饇饈饍饎饔饘饙饛饜饞饟饠馛馝馟馦馰馱馲馵"],
["8fe9a1","馹馺馽馿駃駉駓駔駙駚駜駞駧駪駫駬駰駴駵駹駽駾騂騃騄騋騌騐騑騖騞騠騢騣騤騧騭騮騳騵騶騸驇驁驄驊驋驌驎驑驔驖驝骪骬骮骯骲骴骵骶骹骻骾骿髁髃髆髈髎髐髒髕髖髗髛髜髠髤髥髧髩髬髲髳髵髹髺髽髿",4],
["8feaa1","鬄鬅鬈鬉鬋鬌鬍鬎鬐鬒鬖鬙鬛鬜鬠鬦鬫鬭鬳鬴鬵鬷鬹鬺鬽魈魋魌魕魖魗魛魞魡魣魥魦魨魪",4,"魳魵魷魸魹魿鮀鮄鮅鮆鮇鮉鮊鮋鮍鮏鮐鮔鮚鮝鮞鮦鮧鮩鮬鮰鮱鮲鮷鮸鮻鮼鮾鮿鯁鯇鯈鯎鯐鯗鯘鯝鯟鯥鯧鯪鯫鯯鯳鯷鯸"],
["8feba1","鯹鯺鯽鯿鰀鰂鰋鰏鰑鰖鰘鰙鰚鰜鰞鰢鰣鰦",4,"鰱鰵鰶鰷鰽鱁鱃鱄鱅鱉鱊鱎鱏鱐鱓鱔鱖鱘鱛鱝鱞鱟鱣鱩鱪鱜鱫鱨鱮鱰鱲鱵鱷鱻鳦鳲鳷鳹鴋鴂鴑鴗鴘鴜鴝鴞鴯鴰鴲鴳鴴鴺鴼鵅鴽鵂鵃鵇鵊鵓鵔鵟鵣鵢鵥鵩鵪鵫鵰鵶鵷鵻"],
["8feca1","鵼鵾鶃鶄鶆鶊鶍鶎鶒鶓鶕鶖鶗鶘鶡鶪鶬鶮鶱鶵鶹鶼鶿鷃鷇鷉鷊鷔鷕鷖鷗鷚鷞鷟鷠鷥鷧鷩鷫鷮鷰鷳鷴鷾鸊鸂鸇鸎鸐鸑鸒鸕鸖鸙鸜鸝鹺鹻鹼麀麂麃麄麅麇麎麏麖麘麛麞麤麨麬麮麯麰麳麴麵黆黈黋黕黟黤黧黬黭黮黰黱黲黵"],
["8feda1","黸黿鼂鼃鼉鼏鼐鼑鼒鼔鼖鼗鼙鼚鼛鼟鼢鼦鼪鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃",4,"齓齕齖齗齘齚齝齞齨齩齭",4,"齳齵齺齽龏龐龑龒龔龖龗龞龡龢龣龥"]
]

},{}],23:[function(require,module,exports){
module.exports={"uChars":[128,165,169,178,184,216,226,235,238,244,248,251,253,258,276,284,300,325,329,334,364,463,465,467,469,471,473,475,477,506,594,610,712,716,730,930,938,962,970,1026,1104,1106,8209,8215,8218,8222,8231,8241,8244,8246,8252,8365,8452,8454,8458,8471,8482,8556,8570,8596,8602,8713,8720,8722,8726,8731,8737,8740,8742,8748,8751,8760,8766,8777,8781,8787,8802,8808,8816,8854,8858,8870,8896,8979,9322,9372,9548,9588,9616,9622,9634,9652,9662,9672,9676,9680,9702,9735,9738,9793,9795,11906,11909,11913,11917,11928,11944,11947,11951,11956,11960,11964,11979,12284,12292,12312,12319,12330,12351,12436,12447,12535,12543,12586,12842,12850,12964,13200,13215,13218,13253,13263,13267,13270,13384,13428,13727,13839,13851,14617,14703,14801,14816,14964,15183,15471,15585,16471,16736,17208,17325,17330,17374,17623,17997,18018,18212,18218,18301,18318,18760,18811,18814,18820,18823,18844,18848,18872,19576,19620,19738,19887,40870,59244,59336,59367,59413,59417,59423,59431,59437,59443,59452,59460,59478,59493,63789,63866,63894,63976,63986,64016,64018,64021,64025,64034,64037,64042,65074,65093,65107,65112,65127,65132,65375,65510,65536],"gbChars":[0,36,38,45,50,81,89,95,96,100,103,104,105,109,126,133,148,172,175,179,208,306,307,308,309,310,311,312,313,341,428,443,544,545,558,741,742,749,750,805,819,820,7922,7924,7925,7927,7934,7943,7944,7945,7950,8062,8148,8149,8152,8164,8174,8236,8240,8262,8264,8374,8380,8381,8384,8388,8390,8392,8393,8394,8396,8401,8406,8416,8419,8424,8437,8439,8445,8482,8485,8496,8521,8603,8936,8946,9046,9050,9063,9066,9076,9092,9100,9108,9111,9113,9131,9162,9164,9218,9219,11329,11331,11334,11336,11346,11361,11363,11366,11370,11372,11375,11389,11682,11686,11687,11692,11694,11714,11716,11723,11725,11730,11736,11982,11989,12102,12336,12348,12350,12384,12393,12395,12397,12510,12553,12851,12962,12973,13738,13823,13919,13933,14080,14298,14585,14698,15583,15847,16318,16434,16438,16481,16729,17102,17122,17315,17320,17402,17418,17859,17909,17911,17915,17916,17936,17939,17961,18664,18703,18814,18962,19043,33469,33470,33471,33484,33485,33490,33497,33501,33505,33513,33520,33536,33550,37845,37921,37948,38029,38038,38064,38065,38066,38069,38075,38076,38078,39108,39109,39113,39114,39115,39116,39265,39394,189000]}
},{}],24:[function(require,module,exports){
module.exports=[
["a140","",62],
["a180","",32],
["a240","",62],
["a280","",32],
["a2ab","",5],
["a2e3","€"],
["a2ef",""],
["a2fd",""],
["a340","",62],
["a380","",31,"　"],
["a440","",62],
["a480","",32],
["a4f4","",10],
["a540","",62],
["a580","",32],
["a5f7","",7],
["a640","",62],
["a680","",32],
["a6b9","",7],
["a6d9","",6],
["a6ec",""],
["a6f3",""],
["a6f6","",8],
["a740","",62],
["a780","",32],
["a7c2","",14],
["a7f2","",12],
["a896","",10],
["a8bc","ḿ"],
["a8bf","ǹ"],
["a8c1",""],
["a8ea","",20],
["a958",""],
["a95b",""],
["a95d",""],
["a989","〾⿰",11],
["a997","",12],
["a9f0","",14],
["aaa1","",93],
["aba1","",93],
["aca1","",93],
["ada1","",93],
["aea1","",93],
["afa1","",93],
["d7fa","",4],
["f8a1","",93],
["f9a1","",93],
["faa1","",93],
["fba1","",93],
["fca1","",93],
["fda1","",93],
["fe50","⺁⺄㑳㑇⺈⺋㖞㘚㘎⺌⺗㥮㤘㧏㧟㩳㧐㭎㱮㳠⺧⺪䁖䅟⺮䌷⺳⺶⺷䎱䎬⺻䏝䓖䙡䙌"],
["fe80","䜣䜩䝼䞍⻊䥇䥺䥽䦂䦃䦅䦆䦟䦛䦷䦶䲣䲟䲠䲡䱷䲢䴓",6,"䶮",93],
["8135f437",""]
]

},{}],25:[function(require,module,exports){
module.exports=[
["0","\u0000",128],
["a1","｡",62],
["8140","　、。，．・：；？！゛゜´｀¨＾￣＿ヽヾゝゞ〃仝々〆〇ー―‐／＼～∥｜…‥‘’“”（）〔〕［］｛｝〈",9,"＋－±×"],
["8180","÷＝≠＜＞≦≧∞∴♂♀°′″℃￥＄￠￡％＃＆＊＠§☆★○●◎◇◆□■△▲▽▼※〒→←↑↓〓"],
["81b8","∈∋⊆⊇⊂⊃∪∩"],
["81c8","∧∨￢⇒⇔∀∃"],
["81da","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"],
["81f0","Å‰♯♭♪†‡¶"],
["81fc","◯"],
["824f","０",9],
["8260","Ａ",25],
["8281","ａ",25],
["829f","ぁ",82],
["8340","ァ",62],
["8380","ム",22],
["839f","Α",16,"Σ",6],
["83bf","α",16,"σ",6],
["8440","А",5,"ЁЖ",25],
["8470","а",5,"ёж",7],
["8480","о",17],
["849f","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"],
["8740","①",19,"Ⅰ",9],
["875f","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"],
["877e","㍻"],
["8780","〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"],
["889f","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"],
["8940","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円"],
["8980","園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"],
["8a40","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫"],
["8a80","橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"],
["8b40","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救"],
["8b80","朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"],
["8c40","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨"],
["8c80","劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"],
["8d40","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降"],
["8d80","項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"],
["8e40","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止"],
["8e80","死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"],
["8f40","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳"],
["8f80","準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"],
["9040","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨"],
["9080","逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"],
["9140","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻"],
["9180","操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"],
["9240","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄"],
["9280","逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"],
["9340","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬"],
["9380","凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"],
["9440","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅"],
["9480","楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"],
["9540","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷"],
["9580","斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"],
["9640","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆"],
["9680","摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"],
["9740","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲"],
["9780","沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"],
["9840","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"],
["989f","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"],
["9940","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭"],
["9980","凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"],
["9a40","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸"],
["9a80","噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"],
["9b40","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀"],
["9b80","它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"],
["9c40","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠"],
["9c80","怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"],
["9d40","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫"],
["9d80","捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"],
["9e40","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎"],
["9e80","梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"],
["9f40","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯"],
["9f80","麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"],
["e040","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝"],
["e080","烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"],
["e140","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿"],
["e180","痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"],
["e240","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰"],
["e280","窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"],
["e340","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷"],
["e380","縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"],
["e440","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤"],
["e480","艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"],
["e540","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬"],
["e580","蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"],
["e640","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧"],
["e680","諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"],
["e740","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜"],
["e780","轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"],
["e840","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙"],
["e880","閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"],
["e940","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃"],
["e980","騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"],
["ea40","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯"],
["ea80","黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠堯槇遙瑤凜熙"],
["ed40","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏"],
["ed80","塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"],
["ee40","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙"],
["ee80","蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"],
["eeef","ⅰ",9,"￢￤＇＂"],
["f040","",62],
["f080","",124],
["f140","",62],
["f180","",124],
["f240","",62],
["f280","",124],
["f340","",62],
["f380","",124],
["f440","",62],
["f480","",124],
["f540","",62],
["f580","",124],
["f640","",62],
["f680","",124],
["f740","",62],
["f780","",124],
["f840","",62],
["f880","",124],
["f940",""],
["fa40","ⅰ",9,"Ⅰ",9,"￢￤＇＂㈱№℡∵纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊"],
["fa80","兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯"],
["fb40","涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神"],
["fb80","祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙"],
["fc40","髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"]
]

},{}],26:[function(require,module,exports){
"use strict";
var Buffer = require("safer-buffer").Buffer;

// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js

// == UTF16-BE codec. ==========================================================

exports.utf16be = Utf16BECodec;
function Utf16BECodec() {
}

Utf16BECodec.prototype.encoder = Utf16BEEncoder;
Utf16BECodec.prototype.decoder = Utf16BEDecoder;
Utf16BECodec.prototype.bomAware = true;


// -- Encoding

function Utf16BEEncoder() {
}

Utf16BEEncoder.prototype.write = function(str) {
    var buf = Buffer.from(str, 'ucs2');
    for (var i = 0; i < buf.length; i += 2) {
        var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp;
    }
    return buf;
}

Utf16BEEncoder.prototype.end = function() {
}


// -- Decoding

function Utf16BEDecoder() {
    this.overflowByte = -1;
}

Utf16BEDecoder.prototype.write = function(buf) {
    if (buf.length == 0)
        return '';

    var buf2 = Buffer.alloc(buf.length + 1),
        i = 0, j = 0;

    if (this.overflowByte !== -1) {
        buf2[0] = buf[0];
        buf2[1] = this.overflowByte;
        i = 1; j = 2;
    }

    for (; i < buf.length-1; i += 2, j+= 2) {
        buf2[j] = buf[i+1];
        buf2[j+1] = buf[i];
    }

    this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1;

    return buf2.slice(0, j).toString('ucs2');
}

Utf16BEDecoder.prototype.end = function() {
    this.overflowByte = -1;
}


// == UTF-16 codec =============================================================
// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic.
// Defaults to UTF-16LE, as it's prevalent and default in Node.
// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le
// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'});

// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false).

exports.utf16 = Utf16Codec;
function Utf16Codec(codecOptions, iconv) {
    this.iconv = iconv;
}

Utf16Codec.prototype.encoder = Utf16Encoder;
Utf16Codec.prototype.decoder = Utf16Decoder;


// -- Encoding (pass-through)

function Utf16Encoder(options, codec) {
    options = options || {};
    if (options.addBOM === undefined)
        options.addBOM = true;
    this.encoder = codec.iconv.getEncoder('utf-16le', options);
}

Utf16Encoder.prototype.write = function(str) {
    return this.encoder.write(str);
}

Utf16Encoder.prototype.end = function() {
    return this.encoder.end();
}


// -- Decoding

function Utf16Decoder(options, codec) {
    this.decoder = null;
    this.initialBufs = [];
    this.initialBufsLen = 0;

    this.options = options || {};
    this.iconv = codec.iconv;
}

Utf16Decoder.prototype.write = function(buf) {
    if (!this.decoder) {
        // Codec is not chosen yet. Accumulate initial bytes.
        this.initialBufs.push(buf);
        this.initialBufsLen += buf.length;
        
        if (this.initialBufsLen < 16) // We need more bytes to use space heuristic (see below)
            return '';

        // We have enough bytes -> detect endianness.
        var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding);
        this.decoder = this.iconv.getDecoder(encoding, this.options);

        var resStr = '';
        for (var i = 0; i < this.initialBufs.length; i++)
            resStr += this.decoder.write(this.initialBufs[i]);

        this.initialBufs.length = this.initialBufsLen = 0;
        return resStr;
    }

    return this.decoder.write(buf);
}

Utf16Decoder.prototype.end = function() {
    if (!this.decoder) {
        var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding);
        this.decoder = this.iconv.getDecoder(encoding, this.options);

        var resStr = '';
        for (var i = 0; i < this.initialBufs.length; i++)
            resStr += this.decoder.write(this.initialBufs[i]);

        var trail = this.decoder.end();
        if (trail)
            resStr += trail;

        this.initialBufs.length = this.initialBufsLen = 0;
        return resStr;
    }
    return this.decoder.end();
}

function detectEncoding(bufs, defaultEncoding) {
    var b = [];
    var charsProcessed = 0;
    var asciiCharsLE = 0, asciiCharsBE = 0; // Number of ASCII chars when decoded as LE or BE.

    outer_loop:
    for (var i = 0; i < bufs.length; i++) {
        var buf = bufs[i];
        for (var j = 0; j < buf.length; j++) {
            b.push(buf[j]);
            if (b.length === 2) {
                if (charsProcessed === 0) {
                    // Check BOM first.
                    if (b[0] === 0xFF && b[1] === 0xFE) return 'utf-16le';
                    if (b[0] === 0xFE && b[1] === 0xFF) return 'utf-16be';
                }

                if (b[0] === 0 && b[1] !== 0) asciiCharsBE++;
                if (b[0] !== 0 && b[1] === 0) asciiCharsLE++;

                b.length = 0;
                charsProcessed++;

                if (charsProcessed >= 100) {
                    break outer_loop;
                }
            }
        }
    }

    // Make decisions.
    // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon.
    // So, we count ASCII as if it was LE or BE, and decide from that.
    if (asciiCharsBE > asciiCharsLE) return 'utf-16be';
    if (asciiCharsBE < asciiCharsLE) return 'utf-16le';

    // Couldn't decide (likely all zeros or not enough data).
    return defaultEncoding || 'utf-16le';
}



},{"safer-buffer":45}],27:[function(require,module,exports){
'use strict';

var Buffer = require('safer-buffer').Buffer;

// == UTF32-LE/BE codec. ==========================================================

exports._utf32 = Utf32Codec;

function Utf32Codec(codecOptions, iconv) {
    this.iconv = iconv;
    this.bomAware = true;
    this.isLE = codecOptions.isLE;
}

exports.utf32le = { type: '_utf32', isLE: true };
exports.utf32be = { type: '_utf32', isLE: false };

// Aliases
exports.ucs4le = 'utf32le';
exports.ucs4be = 'utf32be';

Utf32Codec.prototype.encoder = Utf32Encoder;
Utf32Codec.prototype.decoder = Utf32Decoder;

// -- Encoding

function Utf32Encoder(options, codec) {
    this.isLE = codec.isLE;
    this.highSurrogate = 0;
}

Utf32Encoder.prototype.write = function(str) {
    var src = Buffer.from(str, 'ucs2');
    var dst = Buffer.alloc(src.length * 2);
    var write32 = this.isLE ? dst.writeUInt32LE : dst.writeUInt32BE;
    var offset = 0;

    for (var i = 0; i < src.length; i += 2) {
        var code = src.readUInt16LE(i);
        var isHighSurrogate = (0xD800 <= code && code < 0xDC00);
        var isLowSurrogate = (0xDC00 <= code && code < 0xE000);

        if (this.highSurrogate) {
            if (isHighSurrogate || !isLowSurrogate) {
                // There shouldn't be two high surrogates in a row, nor a high surrogate which isn't followed by a low
                // surrogate. If this happens, keep the pending high surrogate as a stand-alone semi-invalid character
                // (technically wrong, but expected by some applications, like Windows file names).
                write32.call(dst, this.highSurrogate, offset);
                offset += 4;
            }
            else {
                // Create 32-bit value from high and low surrogates;
                var codepoint = (((this.highSurrogate - 0xD800) << 10) | (code - 0xDC00)) + 0x10000;

                write32.call(dst, codepoint, offset);
                offset += 4;
                this.highSurrogate = 0;

                continue;
            }
        }

        if (isHighSurrogate)
            this.highSurrogate = code;
        else {
            // Even if the current character is a low surrogate, with no previous high surrogate, we'll
            // encode it as a semi-invalid stand-alone character for the same reasons expressed above for
            // unpaired high surrogates.
            write32.call(dst, code, offset);
            offset += 4;
            this.highSurrogate = 0;
        }
    }

    if (offset < dst.length)
        dst = dst.slice(0, offset);

    return dst;
};

Utf32Encoder.prototype.end = function() {
    // Treat any leftover high surrogate as a semi-valid independent character.
    if (!this.highSurrogate)
        return;

    var buf = Buffer.alloc(4);

    if (this.isLE)
        buf.writeUInt32LE(this.highSurrogate, 0);
    else
        buf.writeUInt32BE(this.highSurrogate, 0);

    this.highSurrogate = 0;

    return buf;
};

// -- Decoding

function Utf32Decoder(options, codec) {
    this.isLE = codec.isLE;
    this.badChar = codec.iconv.defaultCharUnicode.charCodeAt(0);
    this.overflow = [];
}

Utf32Decoder.prototype.write = function(src) {
    if (src.length === 0)
        return '';

    var i = 0;
    var codepoint = 0;
    var dst = Buffer.alloc(src.length + 4);
    var offset = 0;
    var isLE = this.isLE;
    var overflow = this.overflow;
    var badChar = this.badChar;

    if (overflow.length > 0) {
        for (; i < src.length && overflow.length < 4; i++)
            overflow.push(src[i]);
        
        if (overflow.length === 4) {
            // NOTE: codepoint is a signed int32 and can be negative.
            // NOTE: We copied this block from below to help V8 optimize it (it works with array, not buffer).
            if (isLE) {
                codepoint = overflow[i] | (overflow[i+1] << 8) | (overflow[i+2] << 16) | (overflow[i+3] << 24);
            } else {
                codepoint = overflow[i+3] | (overflow[i+2] << 8) | (overflow[i+1] << 16) | (overflow[i] << 24);
            }
            overflow.length = 0;

            offset = _writeCodepoint(dst, offset, codepoint, badChar);
        }
    }

    // Main loop. Should be as optimized as possible.
    for (; i < src.length - 3; i += 4) {
        // NOTE: codepoint is a signed int32 and can be negative.
        if (isLE) {
            codepoint = src[i] | (src[i+1] << 8) | (src[i+2] << 16) | (src[i+3] << 24);
        } else {
            codepoint = src[i+3] | (src[i+2] << 8) | (src[i+1] << 16) | (src[i] << 24);
        }
        offset = _writeCodepoint(dst, offset, codepoint, badChar);
    }

    // Keep overflowing bytes.
    for (; i < src.length; i++) {
        overflow.push(src[i]);
    }

    return dst.slice(0, offset).toString('ucs2');
};

function _writeCodepoint(dst, offset, codepoint, badChar) {
    // NOTE: codepoint is signed int32 and can be negative. We keep it that way to help V8 with optimizations.
    if (codepoint < 0 || codepoint > 0x10FFFF) {
        // Not a valid Unicode codepoint
        codepoint = badChar;
    } 

    // Ephemeral Planes: Write high surrogate.
    if (codepoint >= 0x10000) {
        codepoint -= 0x10000;

        var high = 0xD800 | (codepoint >> 10);
        dst[offset++] = high & 0xff;
        dst[offset++] = high >> 8;

        // Low surrogate is written below.
        var codepoint = 0xDC00 | (codepoint & 0x3FF);
    }

    // Write BMP char or low surrogate.
    dst[offset++] = codepoint & 0xff;
    dst[offset++] = codepoint >> 8;

    return offset;
};

Utf32Decoder.prototype.end = function() {
    this.overflow.length = 0;
};

// == UTF-32 Auto codec =============================================================
// Decoder chooses automatically from UTF-32LE and UTF-32BE using BOM and space-based heuristic.
// Defaults to UTF-32LE. http://en.wikipedia.org/wiki/UTF-32
// Encoder/decoder default can be changed: iconv.decode(buf, 'utf32', {defaultEncoding: 'utf-32be'});

// Encoder prepends BOM (which can be overridden with (addBOM: false}).

exports.utf32 = Utf32AutoCodec;
exports.ucs4 = 'utf32';

function Utf32AutoCodec(options, iconv) {
    this.iconv = iconv;
}

Utf32AutoCodec.prototype.encoder = Utf32AutoEncoder;
Utf32AutoCodec.prototype.decoder = Utf32AutoDecoder;

// -- Encoding

function Utf32AutoEncoder(options, codec) {
    options = options || {};

    if (options.addBOM === undefined)
        options.addBOM = true;

    this.encoder = codec.iconv.getEncoder(options.defaultEncoding || 'utf-32le', options);
}

Utf32AutoEncoder.prototype.write = function(str) {
    return this.encoder.write(str);
};

Utf32AutoEncoder.prototype.end = function() {
    return this.encoder.end();
};

// -- Decoding

function Utf32AutoDecoder(options, codec) {
    this.decoder = null;
    this.initialBufs = [];
    this.initialBufsLen = 0;
    this.options = options || {};
    this.iconv = codec.iconv;
}

Utf32AutoDecoder.prototype.write = function(buf) {
    if (!this.decoder) { 
        // Codec is not chosen yet. Accumulate initial bytes.
        this.initialBufs.push(buf);
        this.initialBufsLen += buf.length;

        if (this.initialBufsLen < 32) // We need more bytes to use space heuristic (see below)
            return '';

        // We have enough bytes -> detect endianness.
        var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding);
        this.decoder = this.iconv.getDecoder(encoding, this.options);

        var resStr = '';
        for (var i = 0; i < this.initialBufs.length; i++)
            resStr += this.decoder.write(this.initialBufs[i]);

        this.initialBufs.length = this.initialBufsLen = 0;
        return resStr;
    }

    return this.decoder.write(buf);
};

Utf32AutoDecoder.prototype.end = function() {
    if (!this.decoder) {
        var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding);
        this.decoder = this.iconv.getDecoder(encoding, this.options);

        var resStr = '';
        for (var i = 0; i < this.initialBufs.length; i++)
            resStr += this.decoder.write(this.initialBufs[i]);

        var trail = this.decoder.end();
        if (trail)
            resStr += trail;

        this.initialBufs.length = this.initialBufsLen = 0;
        return resStr;
    }

    return this.decoder.end();
};

function detectEncoding(bufs, defaultEncoding) {
    var b = [];
    var charsProcessed = 0;
    var invalidLE = 0, invalidBE = 0;   // Number of invalid chars when decoded as LE or BE.
    var bmpCharsLE = 0, bmpCharsBE = 0; // Number of BMP chars when decoded as LE or BE.

    outer_loop:
    for (var i = 0; i < bufs.length; i++) {
        var buf = bufs[i];
        for (var j = 0; j < buf.length; j++) {
            b.push(buf[j]);
            if (b.length === 4) {
                if (charsProcessed === 0) {
                    // Check BOM first.
                    if (b[0] === 0xFF && b[1] === 0xFE && b[2] === 0 && b[3] === 0) {
                        return 'utf-32le';
                    }
                    if (b[0] === 0 && b[1] === 0 && b[2] === 0xFE && b[3] === 0xFF) {
                        return 'utf-32be';
                    }
                }

                if (b[0] !== 0 || b[1] > 0x10) invalidBE++;
                if (b[3] !== 0 || b[2] > 0x10) invalidLE++;

                if (b[0] === 0 && b[1] === 0 && (b[2] !== 0 || b[3] !== 0)) bmpCharsBE++;
                if ((b[0] !== 0 || b[1] !== 0) && b[2] === 0 && b[3] === 0) bmpCharsLE++;

                b.length = 0;
                charsProcessed++;

                if (charsProcessed >= 100) {
                    break outer_loop;
                }
            }
        }
    }

    // Make decisions.
    if (bmpCharsBE - invalidBE > bmpCharsLE - invalidLE)  return 'utf-32be';
    if (bmpCharsBE - invalidBE < bmpCharsLE - invalidLE)  return 'utf-32le';

    // Couldn't decide (likely all zeros or not enough data).
    return defaultEncoding || 'utf-32le';
}

},{"safer-buffer":45}],28:[function(require,module,exports){
"use strict";
var Buffer = require("safer-buffer").Buffer;

// UTF-7 codec, according to https://tools.ietf.org/html/rfc2152
// See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3

exports.utf7 = Utf7Codec;
exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7
function Utf7Codec(codecOptions, iconv) {
    this.iconv = iconv;
};

Utf7Codec.prototype.encoder = Utf7Encoder;
Utf7Codec.prototype.decoder = Utf7Decoder;
Utf7Codec.prototype.bomAware = true;


// -- Encoding

var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g;

function Utf7Encoder(options, codec) {
    this.iconv = codec.iconv;
}

Utf7Encoder.prototype.write = function(str) {
    // Naive implementation.
    // Non-direct chars are encoded as "+<base64>-"; single "+" char is encoded as "+-".
    return Buffer.from(str.replace(nonDirectChars, function(chunk) {
        return "+" + (chunk === '+' ? '' : 
            this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) 
            + "-";
    }.bind(this)));
}

Utf7Encoder.prototype.end = function() {
}


// -- Decoding

function Utf7Decoder(options, codec) {
    this.iconv = codec.iconv;
    this.inBase64 = false;
    this.base64Accum = '';
}

var base64Regex = /[A-Za-z0-9\/+]/;
var base64Chars = [];
for (var i = 0; i < 256; i++)
    base64Chars[i] = base64Regex.test(String.fromCharCode(i));

var plusChar = '+'.charCodeAt(0), 
    minusChar = '-'.charCodeAt(0),
    andChar = '&'.charCodeAt(0);

Utf7Decoder.prototype.write = function(buf) {
    var res = "", lastI = 0,
        inBase64 = this.inBase64,
        base64Accum = this.base64Accum;

    // The decoder is more involved as we must handle chunks in stream.

    for (var i = 0; i < buf.length; i++) {
        if (!inBase64) { // We're in direct mode.
            // Write direct chars until '+'
            if (buf[i] == plusChar) {
                res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars.
                lastI = i+1;
                inBase64 = true;
            }
        } else { // We decode base64.
            if (!base64Chars[buf[i]]) { // Base64 ended.
                if (i == lastI && buf[i] == minusChar) {// "+-" -> "+"
                    res += "+";
                } else {
                    var b64str = base64Accum + this.iconv.decode(buf.slice(lastI, i), "ascii");
                    res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
                }

                if (buf[i] != minusChar) // Minus is absorbed after base64.
                    i--;

                lastI = i+1;
                inBase64 = false;
                base64Accum = '';
            }
        }
    }

    if (!inBase64) {
        res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars.
    } else {
        var b64str = base64Accum + this.iconv.decode(buf.slice(lastI), "ascii");

        var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars.
        base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future.
        b64str = b64str.slice(0, canBeDecoded);

        res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
    }

    this.inBase64 = inBase64;
    this.base64Accum = base64Accum;

    return res;
}

Utf7Decoder.prototype.end = function() {
    var res = "";
    if (this.inBase64 && this.base64Accum.length > 0)
        res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be");

    this.inBase64 = false;
    this.base64Accum = '';
    return res;
}


// UTF-7-IMAP codec.
// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3)
// Differences:
//  * Base64 part is started by "&" instead of "+"
//  * Direct characters are 0x20-0x7E, except "&" (0x26)
//  * In Base64, "," is used instead of "/"
//  * Base64 must not be used to represent direct characters.
//  * No implicit shift back from Base64 (should always end with '-')
//  * String must end in non-shifted position.
//  * "-&" while in base64 is not allowed.


exports.utf7imap = Utf7IMAPCodec;
function Utf7IMAPCodec(codecOptions, iconv) {
    this.iconv = iconv;
};

Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder;
Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder;
Utf7IMAPCodec.prototype.bomAware = true;


// -- Encoding

function Utf7IMAPEncoder(options, codec) {
    this.iconv = codec.iconv;
    this.inBase64 = false;
    this.base64Accum = Buffer.alloc(6);
    this.base64AccumIdx = 0;
}

Utf7IMAPEncoder.prototype.write = function(str) {
    var inBase64 = this.inBase64,
        base64Accum = this.base64Accum,
        base64AccumIdx = this.base64AccumIdx,
        buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0;

    for (var i = 0; i < str.length; i++) {
        var uChar = str.charCodeAt(i);
        if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'.
            if (inBase64) {
                if (base64AccumIdx > 0) {
                    bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx);
                    base64AccumIdx = 0;
                }

                buf[bufIdx++] = minusChar; // Write '-', then go to direct mode.
                inBase64 = false;
            }

            if (!inBase64) {
                buf[bufIdx++] = uChar; // Write direct character

                if (uChar === andChar)  // Ampersand -> '&-'
                    buf[bufIdx++] = minusChar;
            }

        } else { // Non-direct character
            if (!inBase64) {
                buf[bufIdx++] = andChar; // Write '&', then go to base64 mode.
                inBase64 = true;
            }
            if (inBase64) {
                base64Accum[base64AccumIdx++] = uChar >> 8;
                base64Accum[base64AccumIdx++] = uChar & 0xFF;

                if (base64AccumIdx == base64Accum.length) {
                    bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx);
                    base64AccumIdx = 0;
                }
            }
        }
    }

    this.inBase64 = inBase64;
    this.base64AccumIdx = base64AccumIdx;

    return buf.slice(0, bufIdx);
}

Utf7IMAPEncoder.prototype.end = function() {
    var buf = Buffer.alloc(10), bufIdx = 0;
    if (this.inBase64) {
        if (this.base64AccumIdx > 0) {
            bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx);
            this.base64AccumIdx = 0;
        }

        buf[bufIdx++] = minusChar; // Write '-', then go to direct mode.
        this.inBase64 = false;
    }

    return buf.slice(0, bufIdx);
}


// -- Decoding

function Utf7IMAPDecoder(options, codec) {
    this.iconv = codec.iconv;
    this.inBase64 = false;
    this.base64Accum = '';
}

var base64IMAPChars = base64Chars.slice();
base64IMAPChars[','.charCodeAt(0)] = true;

Utf7IMAPDecoder.prototype.write = function(buf) {
    var res = "", lastI = 0,
        inBase64 = this.inBase64,
        base64Accum = this.base64Accum;

    // The decoder is more involved as we must handle chunks in stream.
    // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end).

    for (var i = 0; i < buf.length; i++) {
        if (!inBase64) { // We're in direct mode.
            // Write direct chars until '&'
            if (buf[i] == andChar) {
                res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars.
                lastI = i+1;
                inBase64 = true;
            }
        } else { // We decode base64.
            if (!base64IMAPChars[buf[i]]) { // Base64 ended.
                if (i == lastI && buf[i] == minusChar) { // "&-" -> "&"
                    res += "&";
                } else {
                    var b64str = base64Accum + this.iconv.decode(buf.slice(lastI, i), "ascii").replace(/,/g, '/');
                    res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
                }

                if (buf[i] != minusChar) // Minus may be absorbed after base64.
                    i--;

                lastI = i+1;
                inBase64 = false;
                base64Accum = '';
            }
        }
    }

    if (!inBase64) {
        res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars.
    } else {
        var b64str = base64Accum + this.iconv.decode(buf.slice(lastI), "ascii").replace(/,/g, '/');

        var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars.
        base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future.
        b64str = b64str.slice(0, canBeDecoded);

        res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
    }

    this.inBase64 = inBase64;
    this.base64Accum = base64Accum;

    return res;
}

Utf7IMAPDecoder.prototype.end = function() {
    var res = "";
    if (this.inBase64 && this.base64Accum.length > 0)
        res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be");

    this.inBase64 = false;
    this.base64Accum = '';
    return res;
}



},{"safer-buffer":45}],29:[function(require,module,exports){
"use strict";

var BOMChar = '\uFEFF';

exports.PrependBOM = PrependBOMWrapper
function PrependBOMWrapper(encoder, options) {
    this.encoder = encoder;
    this.addBOM = true;
}

PrependBOMWrapper.prototype.write = function(str) {
    if (this.addBOM) {
        str = BOMChar + str;
        this.addBOM = false;
    }

    return this.encoder.write(str);
}

PrependBOMWrapper.prototype.end = function() {
    return this.encoder.end();
}


//------------------------------------------------------------------------------

exports.StripBOM = StripBOMWrapper;
function StripBOMWrapper(decoder, options) {
    this.decoder = decoder;
    this.pass = false;
    this.options = options || {};
}

StripBOMWrapper.prototype.write = function(buf) {
    var res = this.decoder.write(buf);
    if (this.pass || !res)
        return res;

    if (res[0] === BOMChar) {
        res = res.slice(1);
        if (typeof this.options.stripBOM === 'function')
            this.options.stripBOM();
    }

    this.pass = true;
    return res;
}

StripBOMWrapper.prototype.end = function() {
    return this.decoder.end();
}


},{}],30:[function(require,module,exports){
"use strict";

var Buffer = require("safer-buffer").Buffer;

// NOTE: Due to 'stream' module being pretty large (~100Kb, significant in browser environments), 
// we opt to dependency-inject it instead of creating a hard dependency.
module.exports = function(stream_module) {
    var Transform = stream_module.Transform;

    // == Encoder stream =======================================================

    function IconvLiteEncoderStream(conv, options) {
        this.conv = conv;
        options = options || {};
        options.decodeStrings = false; // We accept only strings, so we don't need to decode them.
        Transform.call(this, options);
    }

    IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, {
        constructor: { value: IconvLiteEncoderStream }
    });

    IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) {
        if (typeof chunk != 'string')
            return done(new Error("Iconv encoding stream needs strings as its input."));
        try {
            var res = this.conv.write(chunk);
            if (res && res.length) this.push(res);
            done();
        }
        catch (e) {
            done(e);
        }
    }

    IconvLiteEncoderStream.prototype._flush = function(done) {
        try {
            var res = this.conv.end();
            if (res && res.length) this.push(res);
            done();
        }
        catch (e) {
            done(e);
        }
    }

    IconvLiteEncoderStream.prototype.collect = function(cb) {
        var chunks = [];
        this.on('error', cb);
        this.on('data', function(chunk) { chunks.push(chunk); });
        this.on('end', function() {
            cb(null, Buffer.concat(chunks));
        });
        return this;
    }


    // == Decoder stream =======================================================

    function IconvLiteDecoderStream(conv, options) {
        this.conv = conv;
        options = options || {};
        options.encoding = this.encoding = 'utf8'; // We output strings.
        Transform.call(this, options);
    }

    IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, {
        constructor: { value: IconvLiteDecoderStream }
    });

    IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) {
        if (!Buffer.isBuffer(chunk) && !(chunk instanceof Uint8Array))
            return done(new Error("Iconv decoding stream needs buffers as its input."));
        try {
            var res = this.conv.write(chunk);
            if (res && res.length) this.push(res, this.encoding);
            done();
        }
        catch (e) {
            done(e);
        }
    }

    IconvLiteDecoderStream.prototype._flush = function(done) {
        try {
            var res = this.conv.end();
            if (res && res.length) this.push(res, this.encoding);                
            done();
        }
        catch (e) {
            done(e);
        }
    }

    IconvLiteDecoderStream.prototype.collect = function(cb) {
        var res = '';
        this.on('error', cb);
        this.on('data', function(chunk) { res += chunk; });
        this.on('end', function() {
            cb(null, res);
        });
        return this;
    }

    return {
        IconvLiteEncoderStream: IconvLiteEncoderStream,
        IconvLiteDecoderStream: IconvLiteDecoderStream,
    };
};

},{"safer-buffer":45}],31:[function(require,module,exports){
(function (process,Buffer,setImmediate,__argument0,__argument1,__argument2,__argument3,__dirname){(function (){
(function () {

  var VERSION = "0.6.25";


  var utils = /*#__PURE__*/Object.freeze({
    __proto__: null,
    get default () { return utils; },
    get getUniqueName () { return getUniqueName; },
    get isFunction () { return isFunction; },
    get isObject () { return isObject; },
    get clamp () { return clamp; },
    get isArray () { return isArray; },
    get isNumber () { return isNumber; },
    get isValidNumber () { return isValidNumber; },
    get isFiniteNumber () { return isFiniteNumber; },
    get isNonNegNumber () { return isNonNegNumber; },
    get isInteger () { return isInteger; },
    get isEven () { return isEven; },
    get isOdd () { return isOdd; },
    get isString () { return isString; },
    get isDate () { return isDate; },
    get isBoolean () { return isBoolean; },
    get formatDateISO () { return formatDateISO; },
    get toArray () { return toArray; },
    get isArrayLike () { return isArrayLike; },
    get addslashes () { return addslashes; },
    get regexEscape () { return regexEscape; },
    get htmlEscape () { return htmlEscape; },
    get defaults () { return defaults; },
    get extend () { return extend$1; },
    get inherit () { return inherit; },
    get promisify () { return promisify; },
    get reduceAsync () { return reduceAsync; },
    get merge () { return merge; },
    get difference () { return difference; },
    get intersection () { return intersection; },
    get indexOf () { return indexOf; },
    get contains () { return contains; },
    get some () { return some; },
    get every () { return every; },
    get find () { return find; },
    get range () { return range; },
    get repeat () { return repeat; },
    get sum () { return sum$1; },
    get getArrayBounds () { return getArrayBounds; },
    get uniq () { return uniq; },
    get pluck () { return pluck; },
    get countValues () { return countValues; },
    get indexOn () { return indexOn; },
    get groupBy () { return groupBy; },
    get arrayToIndex () { return arrayToIndex; },
    get forEach () { return forEach; },
    get forEachProperty () { return forEachProperty; },
    get initializeArray () { return initializeArray; },
    get replaceArray () { return replaceArray; },
    get repeatString () { return repeatString; },
    get splitLines () { return splitLines; },
    get pluralSuffix () { return pluralSuffix; },
    get endsWith () { return endsWith; },
    get lpad () { return lpad; },
    get rpad () { return rpad; },
    get trim () { return trim; },
    get ltrim () { return ltrim; },
    get rtrim () { return rtrim; },
    get addThousandsSep () { return addThousandsSep; },
    get numToStr () { return numToStr; },
    get formatNumber () { return formatNumber; },
    get formatIntlNumber () { return formatIntlNumber; },
    get formatNumberForDisplay () { return formatNumberForDisplay; },
    get shuffle () { return shuffle; },
    get sortOn () { return sortOn; },
    get genericSort () { return genericSort; },
    get getSortedIds () { return getSortedIds; },
    get sortArrayIndex () { return sortArrayIndex; },
    get reorderArray () { return reorderArray; },
    get getKeyComparator () { return getKeyComparator; },
    get getGenericComparator () { return getGenericComparator; },
    get quicksort () { return quicksort$1; },
    get quicksortPartition () { return quicksortPartition; },
    get findRankByValue () { return findRankByValue; },
    get findValueByPct () { return findValueByPct; },
    get findValueByRank () { return findValueByRank; },
    get findMedian () { return findMedian; },
    get findQuantile () { return findQuantile; },
    get mean () { return mean; },
    get format () { return format; },
    get formatter () { return formatter; },
    get wildcardToRegExp () { return wildcardToRegExp; },
    get createBuffer () { return createBuffer; },
    get toBuffer () { return toBuffer; },
    get expandoBuffer () { return expandoBuffer; },
    get copyElements () { return copyElements; },
    get extendBuffer () { return extendBuffer; },
    get mergeNames () { return mergeNames; },
    get findStringPrefix () { return findStringPrefix; },
    get parsePercent () { return parsePercent; },
    get formatVersionedName () { return formatVersionedName; },
    get uniqifyNames () { return uniqifyNames; },
    get parseString () { return parseString; },
    get parseNumber () { return parseNumber; },
    get parseIntlNumber () { return parseIntlNumber; },
    get cleanNumericString () { return cleanNumericString; },
    get trimQuotes () { return trimQuotes; }
  });

  // This module provides a way for multiple jobs to run together asynchronously
  // while keeping job-level context variables (like "defs") separate.

  var stash = {};

  function stashVar(key, val) {
    if (key in stash) {
      error('Tried to replace a stashed variable:', key);
    }
    stash[key] = val;
  }

  function getStashedVar(key) {
    if (key in stash === false) {
      return undefined; // to support running commands in tests
      // error('Tried to read a nonexistent variable from the stash:', key);
    }
    return stash[key];
  }

  function clearStash() {
    stash = {};
  }

  var Stash = /*#__PURE__*/Object.freeze({
    __proto__: null,
    stashVar: stashVar,
    getStashedVar: getStashedVar,
    clearStash: clearStash
  });

  // Fall back to browserify's Buffer polyfill
  var B$3 = typeof Buffer != 'undefined' ? Buffer : require('buffer').Buffer;

  var uniqCount = 0;
  function getUniqueName(prefix) {
    return (prefix || "__id_") + (++uniqCount);
  }

  function isFunction(obj) {
    return typeof obj == 'function';
  }

  function isObject(obj) {
    return obj === Object(obj); // via underscore
  }

  function clamp(val, min, max) {
    return val < min ? min : (val > max ? max : val);
  }

  function isArray(obj) {
    return Array.isArray(obj);
  }

  // Is obj a valid number or NaN? (test if obj is type number)
  function isNumber(obj) {
    return obj != null && obj.constructor == Number;
  }

  function isValidNumber(val) {
    return isNumber(val) && !isNaN(val);
  }

  // Similar to isFinite() but does not coerce strings or other types
  function isFiniteNumber(val) {
    return isValidNumber(val) && val !== Infinity && val !== -Infinity;
  }

  // This uses type conversion
  // export function isFiniteNumber(val) {
  //   return val > -Infinity && val < Infinity;
  // }

  function isNonNegNumber(val) {
    return isNumber(val) && val >= 0;
  }

  function isInteger(obj) {
    return isNumber(obj) && ((obj | 0) === obj);
  }

  function isEven(obj) {
    return (obj % 2) === 0;
  }

  function isOdd(obj) {
    return (obj % 2) === 1;
  }

  function isString(obj) {
    return obj != null && obj.toString === String.prototype.toString;
    // TODO: replace w/ something better.
  }

  function isDate(obj) {
    return !!obj && obj.getTime === Date.prototype.getTime;
  }

  function isBoolean(obj) {
    return obj === true || obj === false;
  }

  function formatDateISO(d) {
    if (!isDate(d)) return '';
    return d.toISOString().replace(':00.000Z', 'Z');
  }

  // Convert an array-like object to an Array, or make a copy if @obj is an Array
  function toArray(obj) {
    var arr;
    if (!isArrayLike(obj)) error("toArray() requires an array-like object");
    try {
      arr = Array.prototype.slice.call(obj, 0); // breaks in ie8
    } catch(e) {
      // support ie8
      arr = [];
      for (var i=0, n=obj.length; i<n; i++) {
        arr[i] = obj[i];
      }
    }
    return arr;
  }

  // Array like: has length property, is numerically indexed and mutable.
  // TODO: try to detect objects with length property but no indexed data elements
  function isArrayLike(obj) {
    if (!obj) return false;
    if (isArray(obj)) return true;
    if (isString(obj)) return false;
    if (obj.length === 0) return true;
    if (obj.length > 0) return true;
    return false;
  }

  // See https://raw.github.com/kvz/phpjs/master/functions/strings/addslashes.js
  function addslashes(str) {
    return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
  }

  // Escape a literal string to use in a regexp.
  // Ref.: http://simonwillison.net/2006/Jan/20/escape/
  function regexEscape(str) {
    return str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  }


  // See https://github.com/janl/mustache.js/blob/master/mustache.js
  var entityMap = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#39;',
    '/': '&#x2F;'
  };
  function htmlEscape(s) {
    return String(s).replace(/[&<>"'/]/g, function(s) {
      return entityMap[s];
    });
  }

  function defaults(dest) {
    for (var i=1, n=arguments.length; i<n; i++) {
      var src = arguments[i] || {};
      for (var key in src) {
        if (key in dest === false && src.hasOwnProperty(key)) {
          dest[key] = src[key];
        }
      }
    }
    return dest;
  }

  function extend$1(o) {
    var dest = o || {},
        n = arguments.length,
        key, i, src;
    for (i=1; i<n; i++) {
      src = arguments[i] || {};
      for (key in src) {
        if (src.hasOwnProperty(key)) {
          dest[key] = src[key];
        }
      }
    }
    return dest;
  }

  // Pseudoclassical inheritance
  //
  // Inherit from a Parent function:
  //    inherit(Child, Parent);
  // Call parent's constructor (inside child constructor):
  //    this.__super__([args...]);
  function inherit(targ, src) {
    var f = function() {
      if (this.__super__ == f) {
        // add __super__ of parent to front of lookup chain
        // so parent class constructor can call its parent using this.__super__
        this.__super__ = src.prototype.__super__;
        // call parent constructor function. this.__super__ now points to parent-of-parent
        src.apply(this, arguments);
        // remove temp __super__, expose targ.prototype.__super__ again
        delete this.__super__;
      }
    };

    f.prototype = src.prototype || src; // added || src to allow inheriting from objects as well as functions
    // Extend targ prototype instead of wiping it out --
    //   in case inherit() is called after targ.prototype = {stuff}; statement
    targ.prototype = extend$1(new f(), targ.prototype); //
    targ.prototype.constructor = targ;
    targ.prototype.__super__ = f;
  }

  function promisify(asyncFn) {
    return function() {
      var args = toArray(arguments);
      return new Promise((resolve, reject) => {
        var cb = function(err, data) {
          if (err) reject(err);
          else resolve(data);
        };
        args.push(cb);
        asyncFn.apply(this, args);
      });
    };
  }

  // Call @iter on each member of an array (similar to Array#reduce(iter))
  //    iter: function(memo, item, callback)
  // Call @done when all members have been processed or if an error occurs
  //    done: function(err, memo)
  // @memo: Initial value
  //
  function reduceAsync(arr, memo, iter, done) {
    // var call = typeof setImmediate == 'undefined' ? setTimeout : setImmediate;
    var i=0;
    next(null, memo);

    function next(err, memo) {
      // Detach next operation from call stack to prevent overflow
      // Don't use setTimeout(, 0) if setImmediate is available
      // (setTimeout() can introduce a long delay if previous operation was slow,
      //    as of Node 0.10.32 -- a bug?)
      if (err) {
        return done(err, null);
      }
      // call(function() {
      //   if (i < arr.length === false) {
      //     done(null, memo);
      //   } else {
      //     iter(memo, arr[i++], next);
      //   }
      // }, 0);
      (function() {
        if (i < arr.length === false) {
          done(null, memo);
        } else {
          iter(memo, arr[i++], next);
        }
      })();
    }
  }


  // Append elements of @src array to @dest array
  function merge(dest, src) {
    if (!isArray(dest) || !isArray(src)) {
      error("Usage: merge(destArray, srcArray);");
    }
    for (var i=0, n=src.length; i<n; i++) {
      dest.push(src[i]);
    }
    return dest;
  }

  // Returns elements in arr and not in other
  // (similar to underscore diff)
  function difference(arr, other) {
    var index = arrayToIndex(other);
    return arr.filter(function(el) {
      return !Object.prototype.hasOwnProperty.call(index, el);
    });
  }

  // Return the intersection of two arrays
  function intersection(a, b) {
    return a.filter(function(el) {
      return b.includes(el);
    });
  }

  function indexOf(arr, item) {
    var nan = item !== item;
    for (var i = 0, len = arr.length || 0; i < len; i++) {
      if (arr[i] === item) return i;
      if (nan && arr[i] !== arr[i]) return i;
    }
    return -1;
  }

  // Test a string or array-like object for existence of substring or element
  function contains(container, item) {
    if (isString(container)) {
      return container.indexOf(item) != -1;
    }
    else if (isArrayLike(container)) {
      return indexOf(container, item) != -1;
    }
    error("Expected Array or String argument");
  }

  function some(arr, test) {
    return arr.reduce(function(val, item) {
      return val || test(item); // TODO: short-circuit?
    }, false);
  }

  function every(arr, test) {
    return arr.reduce(function(val, item) {
      return val && test(item);
    }, true);
  }

  function find(arr, test, ctx) {
    var matches = arr.filter(test, ctx);
    return matches.length === 0 ? null : matches[0];
  }

  function range(len, start, inc) {
    var arr = [],
        v = start === void 0 ? 0 : start,
        i = inc === void 0 ? 1 : inc;
    while(len--) {
      arr.push(v);
      v += i;
    }
    return arr;
  }

  function repeat(times, func) {
    var values = [],
        val;
    for (var i=0; i<times; i++) {
      val = func(i);
      if (val !== void 0) {
        values[i] = val;
      }
    }
    return values.length > 0 ? values : void 0;
  }

  // Calc sum, skip falsy and NaN values
  // Assumes: no other non-numeric objects in array
  //
  function sum$1(arr, info) {
    if (!isArrayLike(arr)) error ("sum() expects an array, received:", arr);
    var tot = 0,
        nan = 0,
        val;
    for (var i=0, n=arr.length; i<n; i++) {
      val = arr[i];
      if (val) {
        tot += val;
      } else if (isNaN(val)) {
        nan++;
      }
    }
    if (info) {
      info.nan = nan;
    }
    return tot;
  }

  // Calculate min and max values of an array, ignoring NaN values
  function getArrayBounds(arr) {
    var min = Infinity,
      max = -Infinity,
      nan = 0, val;
    for (var i=0, len=arr.length; i<len; i++) {
      val = arr[i];
      if (val !== val) nan++;
      if (val < min) min = val;
      if (val > max) max = val;
    }
    return {
      min: min,
      max: max,
      nan: nan
    };
  }

  // export function uniq(src) {
  //   var index = {};
  //   return src.reduce(function(memo, el) {
  //     if (el in index === false) {
  //       index[el] = true;
  //       memo.push(el);
  //     }
  //     return memo;
  //   }, []);
  // }

  function uniq(src) {
    var index = new Set();
    var arr = [];
    var item;
    for (var i=0, n=src.length; i<n; i++) {
      item = src[i];
      if (!index.has(item)) {
        arr.push(item);
        index.add(item);
      }
    }
    return arr;
  }

  function pluck(arr, key) {
    return arr.map(function(obj) {
      return obj[key];
    });
  }

  function countValues(arr) {
    return arr.reduce(function(memo, val) {
      memo[val] = (val in memo) ? memo[val] + 1 : 1;
      return memo;
    }, {});
  }

  function indexOn(arr, k) {
    return arr.reduce(function(index, o) {
      index[o[k]] = o;
      return index;
    }, {});
  }

  function groupBy(arr, k) {
    return arr.reduce(function(index, o) {
      var keyval = o[k];
      if (keyval in index) {
        index[keyval].push(o);
      } else {
        index[keyval] = [o];
      }
      return index;
    }, {});
  }

  function arrayToIndex(arr, val) {
    var init = arguments.length > 1;
    return arr.reduce(function(index, key) {
      index[key] = init ? val : true;
      return index;
    }, {});
  }

  // Support for iterating over array-like objects, like typed arrays
  function forEach(arr, func, ctx) {
    if (!isArrayLike(arr)) {
      throw new Error("#forEach() takes an array-like argument. " + arr);
    }
    for (var i=0, n=arr.length; i < n; i++) {
      func.call(ctx, arr[i], i);
    }
  }

  function forEachProperty(o, func, ctx) {
    Object.keys(o).forEach(function(key) {
      func.call(ctx, o[key], key);
    });
  }

  function initializeArray(arr, init) {
    for (var i=0, len=arr.length; i<len; i++) {
      arr[i] = init;
    }
    return arr;
  }

  function replaceArray(arr, arr2) {
    arr.splice(0, arr.length);
    for (var i=0, n=arr2.length; i<n; i++) {
      arr.push(arr2[i]);
    }
  }

  function repeatString(src, n) {
    var str = "";
    for (var i=0; i<n; i++)
      str += src;
    return str;
  }

  function splitLines(str) {
    return str.split(/\r?\n/);
  }

  function pluralSuffix(count) {
    return count != 1 ? 's' : '';
  }

  function endsWith(str, ending) {
      return str.indexOf(ending, str.length - ending.length) !== -1;
  }

  function lpad(str, size, pad) {
    pad = pad || ' ';
    str = String(str);
    return repeatString(pad, size - str.length) + str;
  }

  function rpad(str, size, pad) {
    pad = pad || ' ';
    str = String(str);
    return str + repeatString(pad, size - str.length);
  }

  function trim(str) {
    return ltrim(rtrim(str));
  }

  var ltrimRxp = /^\s+/;
  function ltrim(str) {
    return str.replace(ltrimRxp, '');
  }

  var rtrimRxp = /\s+$/;
  function rtrim(str) {
    return str.replace(rtrimRxp, '');
  }

  function addThousandsSep(str) {
    var fmt = '',
        start = str[0] == '-' ? 1 : 0,
        dec = str.indexOf('.'),
        end = str.length,
        ins = (dec == -1 ? end : dec) - 3;
    while (ins > start) {
      fmt = ',' + str.substring(ins, end) + fmt;
      end = ins;
      ins -= 3;
    }
    return str.substring(0, end) + fmt;
  }

  function numToStr(num, decimals) {
    return decimals >= 0 ? num.toFixed(decimals) : String(num);
  }

  function formatNumber(val) {
    return val + '';
  }

  function formatIntlNumber(val) {
    var str = formatNumber(val);
    return '"' + str.replace('.', ',') + '"'; // need to quote if comma-delimited
  }

  function formatNumberForDisplay(num, decimals, nullStr, showPos) {
    var fmt;
    if (isNaN(num)) {
      fmt = nullStr || '-';
    } else {
      fmt = numToStr(num, decimals);
      fmt = addThousandsSep(fmt);
      if (showPos && parseFloat(fmt) > 0) {
        fmt = "+" + fmt;
      }
    }
    return fmt;
  }

  function shuffle(arr) {
    var tmp, i, j;
    for (i = arr.length - 1; i > 0; i--) {
      j = Math.floor(Math.random() * (i + 1));
      tmp = arr[i];
      arr[i] = arr[j];
      arr[j] = tmp;
    }
  }

  // Sort an array of objects based on one or more properties.
  // Usage: sortOn(array, key1, asc?[, key2, asc? ...])
  //
  function sortOn(arr) {
    var comparators = [];
    for (var i=1; i<arguments.length; i+=2) {
      comparators.push(getKeyComparator(arguments[i], arguments[i+1]));
    }
    arr.sort(function(a, b) {
      var cmp = 0,
          i = 0,
          n = comparators.length;
      while (i < n && cmp === 0) {
        cmp = comparators[i](a, b);
        i++;
      }
      return cmp;
    });
    return arr;
  }

  // Sort array of values that can be compared with < > operators (strings, numbers)
  // null, undefined and NaN are sorted to the end of the array
  // default order is ascending
  //
  function genericSort(arr, ascending) {
    var compare = getGenericComparator(ascending);
    Array.prototype.sort.call(arr, compare);
    return arr;
  }

  function getSortedIds(arr, asc) {
    var ids = range(arr.length);
    sortArrayIndex(ids, arr, asc);
    return ids;
  }

  function sortArrayIndex(ids, arr, asc) {
    var compare = getGenericComparator(asc);
    ids.sort(function(i, j) {
      // added i, j comparison to guarantee that sort is stable
      var cmp = compare(arr[i], arr[j]);
      return cmp > 0 || cmp === 0 && i > j ? 1 : -1;
    });
  }

  function reorderArray(arr, idxs) {
    var len = idxs.length;
    var arr2 = [];
    for (var i=0; i<len; i++) {
      var idx = idxs[i];
      if (idx < 0 || idx >= len) error("Out-of-bounds array idx");
      arr2[i] = arr[idx];
    }
    replaceArray(arr, arr2);
  }

  function getKeyComparator(key, asc) {
    var compare = getGenericComparator(asc);
    return function(a, b) {
      return compare(a[key], b[key]);
    };
  }

  function getGenericComparator(asc) {
    asc = asc !== false;
    return function(a, b) {
      var retn = 0;
      if (b == null) {
        retn = a == null ? 0 : -1;
      } else if (a == null) {
        retn = 1;
      } else if (a < b) {
        retn = asc ? -1 : 1;
      } else if (a > b) {
        retn = asc ? 1 : -1;
      } else if (a !== a) {
        retn = 1;
      } else if (b !== b) {
        retn = -1;
      }
      return retn;
    };
  }


  // Generic in-place sort (null, NaN, undefined not handled)
  function quicksort$1(arr, asc) {
    quicksortPartition(arr, 0, arr.length-1);
    if (asc === false) Array.prototype.reverse.call(arr); // Works with typed arrays
    return arr;
  }

  // Moved out of quicksort() (saw >100% speedup in Chrome with deep recursion)
  function quicksortPartition (a, lo, hi) {
    var i = lo,
        j = hi,
        pivot, tmp;
    while (i < hi) {
      pivot = a[lo + hi >> 1]; // avoid n^2 performance on sorted arrays
      while (i <= j) {
        while (a[i] < pivot) i++;
        while (a[j] > pivot) j--;
        if (i <= j) {
          tmp = a[i];
          a[i] = a[j];
          a[j] = tmp;
          i++;
          j--;
        }
      }
      if (lo < j) quicksortPartition(a, lo, j);
      lo = i;
      j = hi;
    }
  }


  function findRankByValue(arr, value) {
    if (isNaN(value)) return arr.length;
    var rank = 1;
    for (var i=0, n=arr.length; i<n; i++) {
      if (value > arr[i]) rank++;
    }
    return rank;
  }

  function findValueByPct(arr, pct) {
    var rank = Math.ceil((1-pct) * (arr.length));
    return findValueByRank(arr, rank);
  }

  // See http://ndevilla.free.fr/median/median/src/wirth.c
  // Elements of @arr are reordered
  //
  function findValueByRank(arr, rank) {
    if (!arr.length || rank < 1 || rank > arr.length) error("[findValueByRank()] invalid input");

    rank = clamp(rank | 0, 1, arr.length);
    var k = rank - 1, // conv. rank to array index
        n = arr.length,
        l = 0,
        m = n - 1,
        i, j, val, tmp;

    while (l < m) {
      val = arr[k];
      i = l;
      j = m;
      do {
        while (arr[i] < val) {i++;}
        while (val < arr[j]) {j--;}
        if (i <= j) {
          tmp = arr[i];
          arr[i] = arr[j];
          arr[j] = tmp;
          i++;
          j--;
        }
      } while (i <= j);
      if (j < k) l = i;
      if (k < i) m = j;
    }
    return arr[k];
  }

  function findMedian(arr) {
    return findQuantile(arr, 0.5);
  }

  function findQuantile(arr, k) {
    var n = arr.length,
        i1 = Math.floor((n - 1) * k),
        i2 = Math.ceil((n - 1) * k);
    if (i1 < 0 || i2 >= n) return NaN;
    var v1 = findValueByRank(arr, i1 + 1);
    if (i1 == i2) return v1;
    var v2 = findValueByRank(arr, i2 + 1);
    // use linear interpolation
    var w1 = i2 / (n - 1) - k;
    var w2 = k - i1 / (n - 1);
    var v = (v1 * w1 + v2 * w2) * (n - 1);
    return v;
  }

  function mean(arr) {
    var count = 0,
        avg = NaN,
        val;
    for (var i=0, n=arr.length; i<n; i++) {
      val = arr[i];
      if (isNaN(val)) continue;
      avg = ++count == 1 ? val : val / count + (count - 1) / count * avg;
    }
    return avg;
  }


  /*
  A simplified version of printf formatting
  Format codes: %[flags][width][.precision]type

  supported flags:
    +   add '+' before positive numbers
    0   left-pad with '0'
    '   Add thousands separator
  width: 1 to many
  precision: .(1 to many)
  type:
    s     string
    di    integers
    f     decimal numbers
    xX    hexidecimal (unsigned)
    %     literal '%'

  Examples:
    code    val    formatted
    %+d     1      '+1'
    %4i     32     '  32'
    %04i    32     '0032'
    %x      255    'ff'
    %.2f    0.125  '0.13'
    %'f     1000   '1,000'
  */

  // Usage: format(formatString, [values])
  // Tip: When reusing the same format many times, use formatter() for 5x - 10x better performance
  //
  function format(fmt) {
    var fn = formatter(fmt);
    var str = fn.apply(null, Array.prototype.slice.call(arguments, 1));
    return str;
  }

  function formatValue(val, matches) {
    var flags = matches[1];
    var padding = matches[2];
    var decimals = matches[3] ? parseInt(matches[3].substr(1)) : void 0;
    var type = matches[4];
    var isString = type == 's',
        isHex = type == 'x' || type == 'X',
        // isInt = type == 'd' || type == 'i',
        // isFloat = type == 'f',
        isNumber = !isString;

    var sign = "",
        padDigits = 0,
        isZero = false,
        isNeg = false;

    var str, padChar, padStr;
    if (isString) {
      str = String(val);
    }
    else if (isHex) {
      str = val.toString(16);
      if (type == 'X')
        str = str.toUpperCase();
    }
    else if (isNumber) {
      // str = formatNumberForDisplay(val, isInt ? 0 : decimals);
      str = numToStr(val, decimals);
      if (str[0] == '-') {
        isNeg = true;
        str = str.substr(1);
      }
      isZero = parseFloat(str) == 0;
      if (flags.indexOf("'") != -1 || flags.indexOf(',') != -1) {
        str = addThousandsSep(str);
      }
      if (!isZero) { // BUG: sign is added when num rounds to 0
        if (isNeg) {
          sign = "\u2212"; // U+2212
        } else if (flags.indexOf('+') != -1) {
          sign = '+';
        }
      }
    }

    if (padding) {
      var strLen = str.length + sign.length;
      var minWidth = parseInt(padding, 10);
      if (strLen < minWidth) {
        padDigits = minWidth - strLen;
        padChar = flags.indexOf('0') == -1 ? ' ' : '0';
        padStr = repeatString(padChar, padDigits);
      }
    }

    if (padDigits == 0) {
      str = sign + str;
    } else if (padChar == '0') {
      str = sign + padStr + str;
    } else {
      str = padStr + sign + str;
    }
    return str;
  }

  // Get a function for interpolating formatted values into a string.
  function formatter(fmt) {
    var codeRxp = /%([',+0]*)([1-9]?)((?:\.[1-9])?)([sdifxX%])/g;
    var literals = [],
        formatCodes = [],
        startIdx = 0,
        prefix = "",
        matches = codeRxp.exec(fmt),
        literal;

    while (matches) {
      literal = fmt.substring(startIdx, codeRxp.lastIndex - matches[0].length);
      if (matches[0] == '%%') {
        prefix += literal + '%';
      } else {
        literals.push(prefix + literal);
        prefix = '';
        formatCodes.push(matches);
      }
      startIdx = codeRxp.lastIndex;
      matches = codeRxp.exec(fmt);
    }
    literals.push(prefix + fmt.substr(startIdx));

    return function() {
      var str = literals[0],
          n = arguments.length;
      if (n != formatCodes.length) {
        error("[format()] Data does not match format string; format:", fmt, "data:", arguments);
      }
      for (var i=0; i<n; i++) {
        str += formatValue(arguments[i], formatCodes[i]) + literals[i+1];
      }
      return str;
    };
  }

  function wildcardToRegExp(name) {
    var rxp = name.split('*').map(function(str) {
      return regexEscape(str);
    }).join('.*');
    return new RegExp('^' + rxp + '$');
  }

  function createBuffer(arg, arg2) {
    if (isInteger(arg)) {
      return B$3.allocUnsafe ? B$3.allocUnsafe(arg) : new B$3(arg);
    } else {
      // check allocUnsafe to make sure Buffer.from() will accept strings (it didn't before Node v5.10)
      return B$3.from && B$3.allocUnsafe ? B$3.from(arg, arg2) : new B$3(arg, arg2);
    }
  }

  function toBuffer(src) {
    if (src instanceof B$3) return src;
    if (src instanceof ArrayBuffer) return B$3.from(src);
    if (src instanceof Uint8Array) {
      return B$3.from(src.buffer, src.byteOffset, src.byteLength);
    }
    error('Unexpected argument type');
  }

  function expandoBuffer(constructor, rate) {
    var capacity = 0,
        k = rate >= 1 ? rate : 1.2,
        buf;
    return function(size) {
      if (size > capacity) {
        capacity = Math.ceil(size * k);
        buf = constructor ? new constructor(capacity) : createBuffer(capacity);
      }
      return buf;
    };
  }

  function copyElements(src, i, dest, j, n, rev) {
    var same = src == dest || src.buffer && src.buffer == dest.buffer;
    var inc = 1,
        offs = 0,
        k;
    if (rev) {
      if (same) error('copy error');
      inc = -1;
      offs = n - 1;
    }
    if (same && j > i) {
      for (k=n-1; k>=0; k--) {
        dest[j + k] = src[i + k];
      }
    } else {
      for (k=0; k<n; k++, offs += inc) {
        dest[k + j] = src[i + offs];
      }
    }
  }

  function extendBuffer(src, newLen, copyLen) {
    var len = Math.max(src.length, newLen);
    var n = copyLen || src.length;
    var dest = new src.constructor(len);
    copyElements(src, 0, dest, 0, n);
    return dest;
  }

  function mergeNames(name1, name2) {
    var merged;
    if (name1 && name2) {
      merged = findStringPrefix(name1, name2).replace(/[-_]$/, '');
    }
    return merged || '';
  }

  function findStringPrefix(a, b) {
    var i = 0;
    for (var n=a.length; i<n; i++) {
      if (a[i] !== b[i]) break;
    }
    return a.substr(0, i);
  }

  function parsePercent(o) {
    var str = String(o);
    var isPct = str.indexOf('%') > 0;
    var pct;
    if (isPct) {
      pct = Number(str.replace('%', '')) / 100;
    } else {
      pct = Number(str);
    }
    if (!(pct >= 0 && pct <= 1)) {
      stop(format("Invalid percentage: %s", str));
    }
    return pct;
  }

  function formatVersionedName(name, i) {
    var suffix = String(i);
    if (/[0-9]$/.test(name)) {
      suffix = '-' + suffix;
    }
    return name + suffix;
  }

  function uniqifyNames(names, formatter) {
    var counts = countValues(names),
        format = formatter || formatVersionedName,
        names2 = [];

    names.forEach(function(name) {
      var i = 0,
          candidate = name,
          versionedName;
      while (
          names2.indexOf(candidate) > -1 || // candidate name has already been used
          candidate == name && counts[candidate] > 1 || // duplicate unversioned names
          candidate != name && counts[candidate] > 0) { // versioned name is a preexisting name
        i++;
        versionedName = format(name, i);
        if (!versionedName || versionedName == candidate) {
          throw new Error("Naming error"); // catch buggy versioning function
        }
        candidate = versionedName;
      }
      names2.push(candidate);
    });
    return names2;
  }


  // Assume: @raw is string, undefined or null
  function parseString(raw) {
    return raw ? raw : "";
  }

  // Assume: @raw is string, undefined or null
  // Use null instead of NaN for unparsable values
  // (in part because if NaN is used, empty strings get converted to "NaN"
  // when re-exported).
  function parseNumber(raw) {
    return parseToNum(raw, cleanNumericString);
  }

  function parseIntlNumber(raw) {
    return parseToNum(raw, convertIntlNumString);
  }

  function parseToNum(raw, clean) {
    var str = String(raw).trim();
    var parsed = str ? Number(clean(str)) : NaN;
    return isNaN(parsed) ? null : parsed;
  }

  // Remove comma separators from strings
  function cleanNumericString(str) {
    return (str.indexOf(',') > 0) ? str.replace(/,([0-9]{3})/g, '$1') : str;
  }

  function convertIntlNumString(str) {
    str = str.replace(/[ .]([0-9]{3})/g, '$1');
    return str.replace(',', '.');
  }

  function trimQuotes(str) {
    var len = str.length, first, last;
    if (len >= 2) {
      first = str.charAt(0);
      last = str.charAt(len-1);
      if (first == '"' && last == '"' && !str.includes('","') ||
          first == "'" && last == "'" && !str.includes("','")) {
        str = str.substr(1, len-2);
        // remove string escapes
        str = str.replace(first == '"' ? /\\(?=")/g : /\\(?=')/g, '');
      }
    }
    return str;
  }

  var LOGGING = false;
  var STDOUT = false; // use stdout for status messages
  var _error, _stop, _message;

  var _interrupt = function() {
    throw new NonFatalError(formatLogArgs(arguments));
  };

  setLoggingForCLI();

  function getLoggingSetter() {
    var e = _error, s = _stop, m = _message;
    return function() {
      setLoggingFunctions(m, e, s);
    };
  }

  function setLoggingForCLI() {
    function stop() {
      throw new UserError(formatLogArgs(arguments));
    }

    function error() {
      var msg = utils.toArray(arguments).join(' ');
      throw new Error(msg);
    }

    function message() {
      logArgs(arguments);
    }

    setLoggingFunctions(message, error, stop);
  }

  function enableLogging() {
    LOGGING = true;
  }

  function loggingEnabled() {
    return !!LOGGING;
  }

  // Handle an unexpected condition (internal error)
  function error() {
    _error.apply(null, utils.toArray(arguments));
  }

  // Handle an error caused by invalid input or misuse of API
  function stop() {
    _stop.apply(null, utils.toArray(arguments));
  }

  function interrupt() {
    _interrupt.apply(null, utils.toArray(arguments));
  }

  // Print a status message
  function message() {
    _message.apply(null, messageArgs(arguments));
  }

  // A way for the GUI to replace the CLI logging functions
  function setLoggingFunctions(message, error, stop) {
    _message = message;
    _error = error;
    _stop = stop;
  }


  // print a message to stdout
  function print() {
    STDOUT = true; // tell logArgs() to print to stdout, not stderr
    // calling message() adds the "[command name]" prefix
    _message(utils.toArray(arguments));
    STDOUT = false;
  }

  function verbose() {
    // verbose can be set globally with the -verbose command or separately for each command
    if (getStashedVar('VERBOSE')) {
      message.apply(null, arguments);
    }
  }

  function debug() {
    if (getStashedVar('DEBUG')) {
      logArgs(arguments);
    }
  }

  function printError(err) {
    var msg;
    if (!LOGGING) return;
    if (utils.isString(err)) {
      err = new UserError(err);
    }
    if (err.name == 'NonFatalError') {
      console.error(messageArgs([err.message]).join(' '));
    } else if (err.name == 'UserError') {
      msg = err.message;
      if (!/Error/.test(msg)) {
        msg = "Error: " + msg;
      }
      console.error(messageArgs([msg]).join(' '));
      console.error("Run mapshaper -h to view help");
    } else {
      // not a user error (i.e. a bug in mapshaper)
      console.error(err);
      // throw err;
    }
  }

  function UserError(msg) {
    var err = new Error(msg);
    err.name = 'UserError';
    return err;
  }

  function NonFatalError(msg) {
    var err = new Error(msg);
    err.name = 'NonFatalError';
    return err;
  }

  function formatColumns(arr, alignments) {
    var widths = arr.reduce(function(memo, line) {
      return line.map(function(str, i) {
        return memo ? Math.max(memo[i], str.length) : str.length;
      });
    }, null);
    return arr.map(function(line) {
      line = line.map(function(str, i) {
        var rt = alignments && alignments[i] == 'right';
        var pad = (rt ? str.padStart : str.padEnd).bind(str);
        return pad(widths[i], ' ');
      });
      return '  ' + line.join(' ');
    }).join('\n');
  }

  // Format an array of (preferably short) strings in columns for console logging.
  function formatStringsAsGrid(arr) {
    // TODO: variable column width
    var longest = arr.reduce(function(len, str) {
          return Math.max(len, str.length);
        }, 0),
        colWidth = longest + 2,
        perLine = Math.floor(80 / colWidth) || 1;
    return arr.reduce(function(memo, name, i) {
      var col = i % perLine;
      if (i > 0 && col === 0) memo += '\n';
      if (col < perLine - 1) { // right-pad all but rightmost column
        name = utils.rpad(name, colWidth - 2, ' ');
      }
      return memo +  '  ' + name;
    }, '');
  }

  // expose so GUI can use it
  function formatLogArgs(args) {
    return utils.toArray(args).join(' ');
  }

  function messageArgs(args) {
    var arr = utils.toArray(args);
    var cmd = getStashedVar('current_command');
    if (cmd && cmd != 'help') {
      arr.unshift('[' + cmd + ']');
    }
    return arr;
  }

  function logArgs(args) {
    if (!LOGGING || getStashedVar('QUIET') || !utils.isArrayLike(args)) return;
    var msg = formatLogArgs(args);
    if (STDOUT) console.log(msg);
    else console.error(msg);
  }

  var Logging = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getLoggingSetter: getLoggingSetter,
    setLoggingForCLI: setLoggingForCLI,
    enableLogging: enableLogging,
    loggingEnabled: loggingEnabled,
    error: error,
    stop: stop,
    interrupt: interrupt,
    message: message,
    setLoggingFunctions: setLoggingFunctions,
    print: print,
    verbose: verbose,
    debug: debug,
    printError: printError,
    UserError: UserError,
    NonFatalError: NonFatalError,
    formatColumns: formatColumns,
    formatStringsAsGrid: formatStringsAsGrid,
    formatLogArgs: formatLogArgs,
    logArgs: logArgs
  });

  function Transform() {
    this.mx = this.my = 1;
    this.bx = this.by = 0;
  }

  Transform.prototype.isNull = function() {
    return !this.mx || !this.my || isNaN(this.bx) || isNaN(this.by);
  };

  Transform.prototype.invert = function() {
    var inv = new Transform();
    inv.mx = 1 / this.mx;
    inv.my = 1 / this.my;
    //inv.bx = -this.bx * inv.mx;
    //inv.by = -this.by * inv.my;
    inv.bx = -this.bx / this.mx;
    inv.by = -this.by / this.my;
    return inv;
  };


  Transform.prototype.transform = function(x, y, xy) {
    xy = xy || [];
    xy[0] = x * this.mx + this.bx;
    xy[1] = y * this.my + this.by;
    return xy;
  };

  Transform.prototype.toString = function() {
    return JSON.stringify(Object.assign({}, this));
  };

  function Bounds() {
    if (arguments.length > 0) {
      this.setBounds.apply(this, arguments);
    }
  }

  Bounds.from = function() {
    var b = new Bounds();
    return b.setBounds.apply(b, arguments);
  };

  Bounds.prototype.toString = function() {
    return JSON.stringify({
      xmin: this.xmin,
      xmax: this.xmax,
      ymin: this.ymin,
      ymax: this.ymax
    });
  };

  Bounds.prototype.toArray = function() {
    return this.hasBounds() ? [this.xmin, this.ymin, this.xmax, this.ymax] : [];
  };

  Bounds.prototype.hasBounds = function() {
    return this.xmin <= this.xmax && this.ymin <= this.ymax;
  };

  Bounds.prototype.sameBounds =
  Bounds.prototype.equals = function(bb) {
    return bb && this.xmin === bb.xmin && this.xmax === bb.xmax &&
      this.ymin === bb.ymin && this.ymax === bb.ymax;
  };

  Bounds.prototype.width = function() {
    return (this.xmax - this.xmin) || 0;
  };

  Bounds.prototype.height = function() {
    return (this.ymax - this.ymin) || 0;
  };

  Bounds.prototype.area = function() {
    return this.width() * this.height() || 0;
  };

  Bounds.prototype.empty = function() {
    this.xmin = this.ymin = this.xmax = this.ymax = void 0;
    return this;
  };

  Bounds.prototype.setBounds = function(a, b, c, d) {
    if (arguments.length == 1) {
      // assume first arg is a Bounds or array
      if (utils.isArrayLike(a)) {
        b = a[1];
        c = a[2];
        d = a[3];
        a = a[0];
      } else {
        b = a.ymin;
        c = a.xmax;
        d = a.ymax;
        a = a.xmin;
      }
    }

    this.xmin = a;
    this.ymin = b;
    this.xmax = c;
    this.ymax = d;
    if (a > c || b > d) this.update();
    // error("Bounds#setBounds() min/max reversed:", a, b, c, d);
    return this;
  };


  Bounds.prototype.centerX = function() {
    var x = (this.xmin + this.xmax) * 0.5;
    return x;
  };

  Bounds.prototype.centerY = function() {
    var y = (this.ymax + this.ymin) * 0.5;
    return y;
  };

  Bounds.prototype.containsPoint = function(x, y) {
    if (x >= this.xmin && x <= this.xmax &&
      y <= this.ymax && y >= this.ymin) {
      return true;
    }
    return false;
  };

  // intended to speed up slightly bubble symbol detection; could use intersects() instead
  // TODO: fix false positive where circle is just outside a corner of the box
  Bounds.prototype.containsBufferedPoint =
  Bounds.prototype.containsCircle = function(x, y, buf) {
    if ( x + buf > this.xmin && x - buf < this.xmax ) {
      if ( y - buf < this.ymax && y + buf > this.ymin ) {
        return true;
      }
    }
    return false;
  };

  Bounds.prototype.intersects = function(bb) {
    if (bb.xmin <= this.xmax && bb.xmax >= this.xmin &&
      bb.ymax >= this.ymin && bb.ymin <= this.ymax) {
      return true;
    }
    return false;
  };

  Bounds.prototype.contains = function(bb) {
    if (bb.xmin >= this.xmin && bb.ymax <= this.ymax &&
      bb.xmax <= this.xmax && bb.ymin >= this.ymin) {
      return true;
    }
    return false;
  };

  Bounds.prototype.shift = function(x, y) {
    this.setBounds(this.xmin + x,
      this.ymin + y, this.xmax + x, this.ymax + y);
  };

  Bounds.prototype.padBounds = function(a, b, c, d) {
    this.xmin -= a;
    this.ymin -= b;
    this.xmax += c;
    this.ymax += d;
  };

  // Rescale the bounding box by a fraction. TODO: implement focus.
  // @param {number} pct Fraction of original extents
  // @param {number} pctY Optional amount to scale Y
  //
  Bounds.prototype.scale = function(pct, pctY) { /*, focusX, focusY*/
    var halfWidth = (this.xmax - this.xmin) * 0.5;
    var halfHeight = (this.ymax - this.ymin) * 0.5;
    var kx = pct - 1;
    var ky = pctY === undefined ? kx : pctY - 1;
    this.xmin -= halfWidth * kx;
    this.ymin -= halfHeight * ky;
    this.xmax += halfWidth * kx;
    this.ymax += halfHeight * ky;
  };

  // Return a bounding box with the same extent as this one.
  Bounds.prototype.cloneBounds = // alias so child classes can override clone()
  Bounds.prototype.clone = function() {
    return new Bounds(this.xmin, this.ymin, this.xmax, this.ymax);
  };

  Bounds.prototype.clearBounds = function() {
    this.setBounds(new Bounds());
  };

  Bounds.prototype.mergePoint = function(x, y) {
    if (this.xmin === void 0) {
      this.setBounds(x, y, x, y);
    } else {
      // this works even if x,y are NaN
      if (x < this.xmin)  this.xmin = x;
      else if (x > this.xmax)  this.xmax = x;

      if (y < this.ymin) this.ymin = y;
      else if (y > this.ymax) this.ymax = y;
    }
  };

  // expands either x or y dimension to match @aspect (width/height ratio)
  // @focusX, @focusY (optional): expansion focus, as a fraction of width and height
  Bounds.prototype.fillOut = function(aspect, focusX, focusY) {
    if (arguments.length < 3) {
      focusX = 0.5;
      focusY = 0.5;
    }
    var w = this.width(),
        h = this.height(),
        currAspect = w / h,
        pad;
    if (isNaN(aspect) || aspect <= 0) ; else if (currAspect < aspect) { // fill out x dimension
      pad = h * aspect - w;
      this.xmin -= (1 - focusX) * pad;
      this.xmax += focusX * pad;
    } else {
      pad = w / aspect - h;
      this.ymin -= (1 - focusY) * pad;
      this.ymax += focusY * pad;
    }
    return this;
  };

  Bounds.prototype.update = function() {
    var tmp;
    if (this.xmin > this.xmax) {
      tmp = this.xmin;
      this.xmin = this.xmax;
      this.xmax = tmp;
    }
    if (this.ymin > this.ymax) {
      tmp = this.ymin;
      this.ymin = this.ymax;
      this.ymax = tmp;
    }
  };

  Bounds.prototype.transform = function(t) {
    this.xmin = this.xmin * t.mx + t.bx;
    this.xmax = this.xmax * t.mx + t.bx;
    this.ymin = this.ymin * t.my + t.by;
    this.ymax = this.ymax * t.my + t.by;
    this.update();
    return this;
  };

  // Returns a Transform object for mapping this onto Bounds @b2
  // @flipY (optional) Flip y-axis coords, for converting to/from pixel coords
  //
  Bounds.prototype.getTransform = function(b2, flipY) {
    var t = new Transform();
    t.mx = b2.width() / this.width() || 1; // TODO: better handling of 0 w,h
    t.bx = b2.xmin - t.mx * this.xmin;
    if (flipY) {
      t.my = -b2.height() / this.height() || 1;
      t.by = b2.ymax - t.my * this.ymin;
    } else {
      t.my = b2.height() / this.height() || 1;
      t.by = b2.ymin - t.my * this.ymin;
    }
    return t;
  };

  Bounds.prototype.mergeCircle = function(x, y, r) {
    if (r < 0) r = -r;
    this.mergeBounds([x - r, y - r, x + r, y + r]);
  };

  Bounds.prototype.mergeBounds = function(bb) {
    var a, b, c, d;
    if (bb instanceof Bounds) {
      a = bb.xmin;
      b = bb.ymin;
      c = bb.xmax;
      d = bb.ymax;
    } else if (arguments.length == 4) {
      a = arguments[0];
      b = arguments[1];
      c = arguments[2];
      d = arguments[3];
    } else if (bb.length == 4) {
      // assume array: [xmin, ymin, xmax, ymax]
      a = bb[0];
      b = bb[1];
      c = bb[2];
      d = bb[3];
    } else {
      error("Bounds#mergeBounds() invalid argument:", bb);
    }

    if (this.xmin === void 0) {
      this.setBounds(a, b, c, d);
    } else {
      if (a < this.xmin) this.xmin = a;
      if (b < this.ymin) this.ymin = b;
      if (c > this.xmax) this.xmax = c;
      if (d > this.ymax) this.ymax = d;
    }
    return this;
  };

  function countPointsInLayer(lyr) {
    var count = 0;
    if (layerHasPoints(lyr)) {
      forEachPoint(lyr.shapes, function() {count++;});
    }
    return count;
  }

  function getPointBounds$1(shapes) {
    var bounds = new Bounds();
    forEachPoint(shapes, function(p) {
      bounds.mergePoint(p[0], p[1]);
    });
    return bounds;
  }

  function getPointFeatureBounds(shape, bounds) {
    var n = shape ? shape.length : 0;
    var p;
    if (!bounds) bounds = new Bounds();
    for (var i=0; i<n; i++) {
      p = shape[i];
      bounds.mergePoint(p[0], p[1]);
    }
    return bounds;
  }

  // NOTE: layers can have multipoint features and null features
  function getPointsInLayer(lyr) {
    var coords = [];
    forEachPoint(lyr.shapes, function(p) {
      coords.push(p);
    });
    return coords;
  }

  // Iterate over each [x,y] point in a layer
  // shapes: one layer's "shapes" array
  function forEachPoint(shapes, cb) {
    var i, n, j, m, shp;
    for (i=0, n=shapes.length; i<n; i++) {
      shp = shapes[i];
      for (j=0, m=shp ? shp.length : 0; j<m; j++) {
        cb(shp[j], i);
      }
    }
  }

  var PointUtils = /*#__PURE__*/Object.freeze({
    __proto__: null,
    countPointsInLayer: countPointsInLayer,
    getPointBounds: getPointBounds$1,
    getPointFeatureBounds: getPointFeatureBounds,
    getPointsInLayer: getPointsInLayer,
    forEachPoint: forEachPoint
  });

  function absArcId(arcId) {
    return arcId >= 0 ? arcId : ~arcId;
  }

  function calcArcBounds(xx, yy, start, len) {
    var i = start | 0,
        n = isNaN(len) ? xx.length - i : len + i,
        x, y, xmin, ymin, xmax, ymax;
    if (n > 0) {
      xmin = xmax = xx[i];
      ymin = ymax = yy[i];
    }
    for (i++; i<n; i++) {
      x = xx[i];
      y = yy[i];
      if (x < xmin) xmin = x;
      if (x > xmax) xmax = x;
      if (y < ymin) ymin = y;
      if (y > ymax) ymax = y;
    }
    return [xmin, ymin, xmax, ymax];
  }

  function deleteVertex(arcs, i) {
    var data = arcs.getVertexData();
    var nn = data.nn;
    var n = data.xx.length;
    // avoid re-allocating memory
    var xx2 = new Float64Array(data.xx.buffer, 0, n-1);
    var yy2 = new Float64Array(data.yy.buffer, 0, n-1);
    var zz2 = arcs.isFlat() ? null : new Float64Array(data.zz.buffer, 0, n-1);
    var z = arcs.getRetainedInterval();
    var count = 0;
    var found = false;
    for (var j=0; j<nn.length; j++) {
      count += nn[j];
      if (count >= i && !found) { // TODO: confirm this
        nn[j] = nn[j] - 1;
        found = true;
      }
    }
    utils.copyElements(data.xx, 0, xx2, 0, i);
    utils.copyElements(data.yy, 0, yy2, 0, i);
    utils.copyElements(data.xx, i+1, xx2, i, n-i-1);
    utils.copyElements(data.yy, i+1, yy2, i, n-i-1);
    if (zz2) {
      utils.copyElements(data.zz, 0, zz2, 0, i);
      utils.copyElements(data.zz, i+1, zz2, i, n-i-1);
    }
    arcs.updateVertexData(nn, xx2, yy2, zz2);
    arcs.setRetainedInterval(z);
  }

  function insertVertex(arcs, i, p) {
    var data = arcs.getVertexData();
    var nn = data.nn;
    var n = data.xx.length;
    var count = 0;
    var found = false;
    var xx2, yy2, zz2;
    // avoid re-allocating memory on each insertion
    if (data.xx.buffer.byteLength >= data.xx.length * 8 + 8) {
      xx2 = new Float64Array(data.xx.buffer, 0, n+1);
      yy2 = new Float64Array(data.yy.buffer, 0, n+1);
    } else {
      xx2 = new Float64Array(new ArrayBuffer((n + 50) * 8), 0, n+1);
      yy2 = new Float64Array(new ArrayBuffer((n + 50) * 8), 0, n+1);
    }
    if (!arcs.isFlat()) {
      zz2 = new Float64Array(new ArrayBuffer((n + 1) * 8), 0, n+1);
    }
    for (var j=0; j<nn.length; j++) {
      count += nn[j];
      if (count >= i && !found) { // TODO: confirm this
        nn[j] = nn[j] + 1;
        found = true;
      }
    }
    utils.copyElements(data.xx, 0, xx2, 0, i);
    utils.copyElements(data.yy, 0, yy2, 0, i);
    utils.copyElements(data.xx, i, xx2, i+1, n-i);
    utils.copyElements(data.yy, i, yy2, i+1, n-i);
    xx2[i] = p[0];
    yy2[i] = p[1];
    if (zz2) {
      zz2[i] = Infinity;
      utils.copyElements(data.zz, 0, zz2, 0, i);
      utils.copyElements(data.zz, i, zz2, i+1, n-i);
    }
    arcs.updateVertexData(nn, xx2, yy2, zz2);
  }

  var ArcUtils = /*#__PURE__*/Object.freeze({
    __proto__: null,
    absArcId: absArcId,
    calcArcBounds: calcArcBounds,
    deleteVertex: deleteVertex,
    insertVertex: insertVertex
  });

  var WGS84 = {
    // https://en.wikipedia.org/wiki/Earth_radius
    SEMIMAJOR_AXIS: 6378137,
    SEMIMINOR_AXIS: 6356752.3142,
    AUTHALIC_RADIUS: 6371007.2,
    VOLUMETRIC_RADIUS: 6371000.8
  };

  // TODO: remove this constant, use actual data from dataset CRS,
  // also consider using ellipsoidal formulas where greater accuracy might be important.
  var R$1 = WGS84.SEMIMAJOR_AXIS;
  var D2R = Math.PI / 180;
  var R2D = 180 / Math.PI;

  // Equirectangular projection
  function degreesToMeters(deg) {
    return deg * D2R * R$1;
  }

  function distance3D(ax, ay, az, bx, by, bz) {
    var dx = ax - bx,
      dy = ay - by,
      dz = az - bz;
    return Math.sqrt(dx * dx + dy * dy + dz * dz);
  }

  function distanceSq(ax, ay, bx, by) {
    var dx = ax - bx,
        dy = ay - by;
    return dx * dx + dy * dy;
  }

  function distance2D(ax, ay, bx, by) {
    var dx = ax - bx,
        dy = ay - by;
    return Math.sqrt(dx * dx + dy * dy);
  }

  function distanceSq3D(ax, ay, az, bx, by, bz) {
    var dx = ax - bx,
        dy = ay - by,
        dz = az - bz;
    return dx * dx + dy * dy + dz * dz;
  }

  // atan2() makes this function fairly slow, replaced by ~2x faster formula
  function innerAngle2(ax, ay, bx, by, cx, cy) {
    var a1 = Math.atan2(ay - by, ax - bx),
        a2 = Math.atan2(cy - by, cx - bx),
        a3 = Math.abs(a1 - a2);
    if (a3 > Math.PI) {
      a3 = 2 * Math.PI - a3;
    }
    return a3;
  }

  // Return angle abc in range [0, 2PI) or NaN if angle is invalid
  // (e.g. if length of ab or bc is 0)
  /*
  function signedAngle2(ax, ay, bx, by, cx, cy) {
    var a1 = Math.atan2(ay - by, ax - bx),
        a2 = Math.atan2(cy - by, cx - bx),
        a3 = a2 - a1;

    if (ax == bx && ay == by || bx == cx && by == cy) {
      a3 = NaN; // Use NaN for invalid angles
    } else if (a3 >= Math.PI * 2) {
      a3 = 2 * Math.PI - a3;
    } else if (a3 < 0) {
      a3 = a3 + 2 * Math.PI;
    }
    return a3;
  }
  */

  function standardAngle(a) {
    var twoPI = Math.PI * 2;
    while (a < 0) {
      a += twoPI;
    }
    while (a >= twoPI) {
      a -= twoPI;
    }
    return a;
  }

  function signedAngle(ax, ay, bx, by, cx, cy) {
    if (ax == bx && ay == by || bx == cx && by == cy) {
      return NaN; // Use NaN for invalid angles
    }
    var abx = ax - bx,
        aby = ay - by,
        cbx = cx - bx,
        cby = cy - by,
        dotp = abx * cbx + aby * cby,
        crossp = abx * cby - aby * cbx,
        a = Math.atan2(crossp, dotp);
    return standardAngle(a);
  }

  function bearing2D(x1, y1, x2, y2) {
    var val = Math.PI/2 - Math.atan2(y2 - y1, x2 - x1);
    return val > Math.PI ? val - 2 * Math.PI : val;
  }

  // Calc bearing in radians at lng1, lat1
  function bearing(lng1, lat1, lng2, lat2) {
    var D2R = Math.PI / 180;
    lng1 *= D2R;
    lng2 *= D2R;
    lat1 *= D2R;
    lat2 *= D2R;
    var y = Math.sin(lng2-lng1) * Math.cos(lat2),
        x = Math.cos(lat1)*Math.sin(lat2) - Math.sin(lat1)*Math.cos(lat2)*Math.cos(lng2-lng1);
    return Math.atan2(y, x);
  }

  // Calc angle of turn from ab to bc, in range [0, 2PI)
  // Receive lat-lng values in degrees
  function signedAngleSph(alng, alat, blng, blat, clng, clat) {
    if (alng == blng && alat == blat || blng == clng && blat == clat) {
      return NaN;
    }
    var b1 = bearing(blng, blat, alng, alat), // calc bearing at b
        b2 = bearing(blng, blat, clng, clat),
        a = Math.PI * 2 + b1 - b2;
    return standardAngle(a);
  }

  /*
  // Convert arrays of lng and lat coords (xsrc, ysrc) into
  // x, y, z coords (meters) on the most common spherical Earth model.
  //
  function convLngLatToSph(xsrc, ysrc, xbuf, ybuf, zbuf) {
    var deg2rad = Math.PI / 180,
        r = R;
    for (var i=0, len=xsrc.length; i<len; i++) {
      var lng = xsrc[i] * deg2rad,
          lat = ysrc[i] * deg2rad,
          cosLat = Math.cos(lat);
      xbuf[i] = Math.cos(lng) * cosLat * r;
      ybuf[i] = Math.sin(lng) * cosLat * r;
      zbuf[i] = Math.sin(lat) * r;
    }
  }
  */

  // Convert arrays of lng and lat coords (xsrc, ysrc) into
  // x, y, z coords (meters) on the most common spherical Earth model.
  //
  function convLngLatToSph(xsrc, ysrc, xbuf, ybuf, zbuf) {
    var p = [];
    for (var i=0, len=xsrc.length; i<len; i++) {
      lngLatToXYZ(xsrc[i], ysrc[i], p);
      xbuf[i] = p[0];
      ybuf[i] = p[1];
      zbuf[i] = p[2];
    }
  }

  function xyzToLngLat(x, y, z, p) {
    var d = distance3D(0, 0, 0, x, y, z); // normalize
    var lat = Math.asin(z / d) / D2R;
    var lng = Math.atan2(y / d, x / d) / D2R;
    p[0] = lng;
    p[1] = lat;
  }

  function lngLatToXYZ(lng, lat, p) {
    var cosLat;
    lng *= D2R;
    lat *= D2R;
    cosLat = Math.cos(lat);
    p[0] = Math.cos(lng) * cosLat * R$1;
    p[1] = Math.sin(lng) * cosLat * R$1;
    p[2] = Math.sin(lat) * R$1;
  }

  // Haversine formula (well conditioned at small distances)
  function sphericalDistance(lam1, phi1, lam2, phi2) {
    var dlam = lam2 - lam1,
        dphi = phi2 - phi1,
        a = Math.sin(dphi / 2) * Math.sin(dphi / 2) +
            Math.cos(phi1) * Math.cos(phi2) *
            Math.sin(dlam / 2) * Math.sin(dlam / 2),
        c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    return c;
  }

  // Receive: coords in decimal degrees;
  // Return: distance in meters on spherical earth
  function greatCircleDistance(lng1, lat1, lng2, lat2) {
    var D2R = Math.PI / 180,
        dist = sphericalDistance(lng1 * D2R, lat1 * D2R, lng2 * D2R, lat2 * D2R);
    return dist * R$1;
  }

  // TODO: make this safe for small angles
  function innerAngle(ax, ay, bx, by, cx, cy) {
    var ab = distance2D(ax, ay, bx, by),
        bc = distance2D(bx, by, cx, cy),
        theta, dotp;
    if (ab === 0 || bc === 0) {
      theta = 0;
    } else {
      dotp = ((ax - bx) * (cx - bx) + (ay - by) * (cy - by)) / (ab * bc);
      if (dotp >= 1 - 1e-14) {
        theta = 0;
      } else if (dotp <= -1 + 1e-14) {
        theta = Math.PI;
      } else {
        theta = Math.acos(dotp); // consider using other formula at small dp
      }
    }
    return theta;
  }

  function innerAngle3D(ax, ay, az, bx, by, bz, cx, cy, cz) {
    var ab = distance3D(ax, ay, az, bx, by, bz),
        bc = distance3D(bx, by, bz, cx, cy, cz),
        theta, dotp;
    if (ab === 0 || bc === 0) {
      theta = 0;
    } else {
      dotp = ((ax - bx) * (cx - bx) + (ay - by) * (cy - by) + (az - bz) * (cz - bz)) / (ab * bc);
      if (dotp >= 1) {
        theta = 0;
      } else if (dotp <= -1) {
        theta = Math.PI;
      } else {
        theta = Math.acos(dotp); // consider using other formula at small dp
      }
    }
    return theta;
  }

  function triangleArea(ax, ay, bx, by, cx, cy) {
    var area = Math.abs(((ay - cy) * (bx - cx) + (by - cy) * (cx - ax)) / 2);
    return area;
  }

  function detSq(ax, ay, bx, by, cx, cy) {
    var det = ax * by - ax * cy + bx * cy - bx * ay + cx * ay - cx * by;
    return det * det;
  }

  function cosine(ax, ay, bx, by, cx, cy) {
    var den = distance2D(ax, ay, bx, by) * distance2D(bx, by, cx, cy),
        cos = 0;
    if (den > 0) {
      cos = ((ax - bx) * (cx - bx) + (ay - by) * (cy - by)) / den;
      if (cos > 1) cos = 1; // handle fp rounding error
      else if (cos < -1) cos = -1;
    }
    return cos;
  }

  function cosine3D(ax, ay, az, bx, by, bz, cx, cy, cz) {
    var den = distance3D(ax, ay, az, bx, by, bz) * distance3D(bx, by, bz, cx, cy, cz),
        cos = 0;
    if (den > 0) {
      cos = ((ax - bx) * (cx - bx) + (ay - by) * (cy - by) + (az - bz) * (cz - bz)) / den;
      if (cos > 1) cos = 1; // handle fp rounding error
      else if (cos < -1) cos = -1;
    }
    return cos;
  }

  function triangleArea3D(ax, ay, az, bx, by, bz, cx, cy, cz) {
    var area = 0.5 * Math.sqrt(detSq(ax, ay, bx, by, cx, cy) +
      detSq(ax, az, bx, bz, cx, cz) + detSq(ay, az, by, bz, cy, cz));
    return area;
  }

  // Given point B and segment AC, return the squared distance from B to the
  // nearest point on AC
  // Receive the squared length of segments AB, BC, AC
  // TODO: analyze rounding error. Returns 0 for these coordinates:
  //    P: [2, 3 - 1e-8]  AB: [[1, 3], [3, 3]]
  //
  function apexDistSq(ab2, bc2, ac2) {
    var dist2;
    if (ac2 === 0) {
      dist2 = ab2;
    } else if (ab2 >= bc2 + ac2) {
      dist2 = bc2;
    } else if (bc2 >= ab2 + ac2) {
      dist2 = ab2;
    } else {
      var dval = (ab2 + ac2 - bc2);
      dist2 = ab2 -  dval * dval / ac2  * 0.25;
    }
    if (dist2 < 0) {
      dist2 = 0;
    }
    return dist2;
  }

  function pointSegDistSq(ax, ay, bx, by, cx, cy) {
    var ab2 = distanceSq(ax, ay, bx, by),
        ac2 = distanceSq(ax, ay, cx, cy),
        bc2 = distanceSq(bx, by, cx, cy);
    return apexDistSq(ab2, ac2, bc2);
  }

  function pointSegDistSq3D(ax, ay, az, bx, by, bz, cx, cy, cz) {
    var ab2 = distanceSq3D(ax, ay, az, bx, by, bz),
        ac2 = distanceSq3D(ax, ay, az, cx, cy, cz),
        bc2 = distanceSq3D(bx, by, bz, cx, cy, cz);
    return apexDistSq(ab2, ac2, bc2);
  }

  // Apparently better conditioned for some inputs than pointSegDistSq()
  //
  function pointSegDistSq2(px, py, ax, ay, bx, by) {
    var ab2 = distanceSq(ax, ay, bx, by);
    var t = ((px - ax) * (bx - ax) + (py - ay) * (by - ay)) / ab2;
    if (ab2 === 0) return distanceSq(px, py, ax, ay);
    if (t < 0) t = 0;
    if (t > 1) t = 1;
    return distanceSq(px, py, ax + t * (bx - ax), ay + t * (by - ay));
  }


  // internal.reversePathCoords = function(arr, start, len) {
  //   var i = start,
  //       j = start + len - 1,
  //       tmp;
  //   while (i < j) {
  //     tmp = arr[i];
  //     arr[i] = arr[j];
  //     arr[j] = tmp;
  //     i++;
  //     j--;
  //   }
  // };

  // merge B into A
  // function mergeBounds(a, b) {
  //   if (b[0] < a[0]) a[0] = b[0];
  //   if (b[1] < a[1]) a[1] = b[1];
  //   if (b[2] > a[2]) a[2] = b[2];
  //   if (b[3] > a[3]) a[3] = b[3];
  // }

  function containsBounds(a, b) {
    return a[0] <= b[0] && a[2] >= b[2] && a[1] <= b[1] && a[3] >= b[3];
  }

  // function boundsArea(b) {
  //   return (b[2] - b[0]) * (b[3] - b[1]);
  // }

  var Geom = /*#__PURE__*/Object.freeze({
    __proto__: null,
    R: R$1,
    D2R: D2R,
    R2D: R2D,
    degreesToMeters: degreesToMeters,
    distance3D: distance3D,
    distanceSq: distanceSq,
    distance2D: distance2D,
    distanceSq3D: distanceSq3D,
    innerAngle2: innerAngle2,
    standardAngle: standardAngle,
    signedAngle: signedAngle,
    bearing2D: bearing2D,
    bearing: bearing,
    signedAngleSph: signedAngleSph,
    convLngLatToSph: convLngLatToSph,
    xyzToLngLat: xyzToLngLat,
    lngLatToXYZ: lngLatToXYZ,
    sphericalDistance: sphericalDistance,
    greatCircleDistance: greatCircleDistance,
    innerAngle: innerAngle,
    innerAngle3D: innerAngle3D,
    triangleArea: triangleArea,
    cosine: cosine,
    cosine3D: cosine3D,
    triangleArea3D: triangleArea3D,
    pointSegDistSq: pointSegDistSq,
    pointSegDistSq3D: pointSegDistSq3D,
    pointSegDistSq2: pointSegDistSq2,
    containsBounds: containsBounds
  });

  function pathIsClosed(ids, arcs) {
    var firstArc = ids[0];
    var lastArc = ids[ids.length - 1];
    var p1 = arcs.getVertex(firstArc, 0);
    var p2 = arcs.getVertex(lastArc, -1);
    var closed = p1.x === p2.x && p1.y === p2.y;
    return closed;
  }

  function getPointToPathDistance(px, py, ids, arcs) {
    return getPointToPathInfo(px, py, ids, arcs).distance;
  }

  function getPointToPathInfo(px, py, ids, arcs) {
    var iter = arcs.getShapeIter(ids);
    var pPathSq = Infinity;
    var arcId;
    var ax, ay, bx, by, axmin, aymin, bxmin, bymin, pabSq;
    if (iter.hasNext()) {
      ax = axmin = bxmin = iter.x;
      ay = aymin = bymin = iter.y;
    }
    while (iter.hasNext()) {
      bx = iter.x;
      by = iter.y;
      pabSq = pointSegDistSq2(px, py, ax, ay, bx, by);
      if (pabSq < pPathSq) {
        pPathSq = pabSq;
        arcId = iter._ids[iter._i]; // kludge
        axmin = ax;
        aymin = ay;
        bxmin = bx;
        bymin = by;
      }
      ax = bx;
      ay = by;
    }
    if (pPathSq == Infinity) return {distance: Infinity};
    return {
      segment: [[axmin, aymin], [bxmin, bymin]],
      distance: Math.sqrt(pPathSq),
      arcId: arcId
    };
  }


  // Return unsigned distance of a point to the nearest point on a polygon or polyline path
  //
  function getPointToShapeDistance(x, y, shp, arcs) {
    var info = getPointToShapeInfo(x, y, shp, arcs);
    return info ? info.distance : Infinity;
  }

  function getPointToShapeInfo(x, y, shp, arcs) {
    return (shp || []).reduce(function(memo, ids) {
      var pathInfo = getPointToPathInfo(x, y, ids, arcs);
      if (!memo || pathInfo.distance < memo.distance) return pathInfo;
      return memo;
    }, null) || {
      distance: Infinity,
      arcId: -1,
      segment: null
    };
  }

  // @ids array of arc ids
  // @arcs ArcCollection
  function getAvgPathXY(ids, arcs) {
    var iter = arcs.getShapeIter(ids);
    if (!iter.hasNext()) return null;
    var x0 = iter.x,
        y0 = iter.y,
        count = 0,
        sumX = 0,
        sumY = 0;
    while (iter.hasNext()) {
      count++;
      sumX += iter.x;
      sumY += iter.y;
    }
    if (count === 0 || iter.x !== x0 || iter.y !== y0) {
      sumX += x0;
      sumY += y0;
      count++;
    }
    return {
      x: sumX / count,
      y: sumY / count
    };
  }

  // Return path with the largest (area) bounding box
  // @shp array of array of arc ids
  // @arcs ArcCollection
  function getMaxPath(shp, arcs) {
    var maxArea = 0;
    return (shp || []).reduce(function(maxPath, path) {
      var bbArea = arcs.getSimpleShapeBounds(path).area();
      if (bbArea > maxArea) {
        maxArea = bbArea;
        maxPath = path;
      }
      return maxPath;
    }, null);
  }

  function countVerticesInPath(ids, arcs) {
    var iter = arcs.getShapeIter(ids),
        count = 0;
    while (iter.hasNext()) count++;
    return count;
  }

  function getPathBounds$1(points) {
    var bounds = new Bounds();
    for (var i=0, n=points.length; i<n; i++) {
      bounds.mergePoint(points[i][0], points[i][1]);
    }
    return bounds;
  }

  var calcPathLen;
  calcPathLen = (function() {
    var len, calcLen;
    function addSegLen(i, j, xx, yy) {
      len += calcLen(xx[i], yy[i], xx[j], yy[j]);
    }
    // @spherical (optional bool) calculate great circle length in meters
    return function(path, arcs, spherical) {
      if (spherical && arcs.isPlanar()) {
        error("Expected lat-long coordinates");
      }
      calcLen = spherical ? greatCircleDistance : distance2D;
      len = 0;
      for (var i=0, n=path.length; i<n; i++) {
        arcs.forEachArcSegment(path[i], addSegLen);
      }
      return len;
    };
  }());

  var PathGeom = /*#__PURE__*/Object.freeze({
    __proto__: null,
    pathIsClosed: pathIsClosed,
    getPointToPathDistance: getPointToPathDistance,
    getPointToPathInfo: getPointToPathInfo,
    getPointToShapeDistance: getPointToShapeDistance,
    getPointToShapeInfo: getPointToShapeInfo,
    getAvgPathXY: getAvgPathXY,
    getMaxPath: getMaxPath,
    countVerticesInPath: countVerticesInPath,
    getPathBounds: getPathBounds$1,
    get calcPathLen () { return calcPathLen; }
  });

  // Get the centroid of the largest ring of a polygon
  // TODO: Include holes in the calculation
  // TODO: Add option to find centroid of all rings, not just the largest
  function getShapeCentroid(shp, arcs) {
    var maxPath = getMaxPath(shp, arcs);
    return maxPath ? getPathCentroid(maxPath, arcs) : null;
  }

  function getPathCentroid(ids, arcs) {
    var iter = arcs.getShapeIter(ids),
        sum = 0,
        sumX = 0,
        sumY = 0,
        dx, dy, ax, ay, bx, by, tmp, area;
    if (!iter.hasNext()) return null;
    // reduce effect of fp errors by shifting shape origin to 0,0 (issue #304)
    ax = 0;
    ay = 0;
    dx = -iter.x;
    dy = -iter.y;
    while (iter.hasNext()) {
      bx = ax;
      by = ay;
      ax = iter.x + dx;
      ay = iter.y + dy;
      tmp = bx * ay - by * ax;
      sum += tmp;
      sumX += tmp * (bx + ax);
      sumY += tmp * (by + ay);
    }
    area = sum / 2;
    if (area === 0) {
      return getAvgPathXY(ids, arcs);
    } else return {
      x: sumX / (6 * area) - dx,
      y: sumY / (6 * area) - dy
    };
  }

  var PolygonCentroid = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getShapeCentroid: getShapeCentroid,
    getPathCentroid: getPathCentroid
  });

  function testSegmentBoundsIntersection(a, b, bb) {
    if (bb.containsPoint(a[0], a[1])) {
      return true;
    }
    return !!(
      geom.segmentIntersection(a[0], a[1], b[0], b[1], bb.xmin, bb.ymin, bb.xmin, bb.ymax) ||
      geom.segmentIntersection(a[0], a[1], b[0], b[1], bb.xmin, bb.ymax, bb.xmax, bb.ymax) ||
      geom.segmentIntersection(a[0], a[1], b[0], b[1], bb.xmax, bb.ymax, bb.xmax, bb.ymin) ||
      geom.segmentIntersection(a[0], a[1], b[0], b[1], bb.xmax, bb.ymin, bb.xmin, bb.ymin));
  }

  // A compactness measure designed for testing electoral districts for gerrymandering.
  // Returns value in [0-1] range. 1 = perfect circle, 0 = collapsed polygon
  function calcPolsbyPopperCompactness(area, perimeter) {
    if (perimeter <= 0) return 0;
    return Math.abs(area) * Math.PI * 4 / (perimeter * perimeter);
  }

  // Larger values (less severe penalty) than Polsby Popper
  function calcSchwartzbergCompactness(area, perimeter) {
    if (perimeter <= 0) return 0;
    return 2 * Math.PI * Math.sqrt(Math.abs(area) / Math.PI) / perimeter;
  }

  // Returns: 1 if CW, -1 if CCW, 0 if collapsed
  function getPathWinding(ids, arcs) {
    var area = getPathArea(ids, arcs);
    return area > 0 && 1 || area < 0 && -1 || 0;
  }

  function getShapeArea(shp, arcs) {
    // return (arcs.isPlanar() ? geom.getPlanarShapeArea : geom.getSphericalShapeArea)(shp, arcs);
    return (shp || []).reduce(function(area, ids) {
      return area + getPathArea(ids, arcs);
    }, 0);
  }

  function getPlanarShapeArea(shp, arcs) {
    return (shp || []).reduce(function(area, ids) {
      return area + getPlanarPathArea(ids, arcs);
    }, 0);
  }

  function getSphericalShapeArea(shp, arcs, R) {
    if (arcs.isPlanar()) {
      error("[getSphericalShapeArea()] Function requires decimal degree coordinates");
    }
    return (shp || []).reduce(function(area, ids) {
      return area + getSphericalPathArea(ids, arcs, R);
    }, 0);
  }

  // export function getEllipsoidalShapeArea(shp, arcs, crs) {
  //   return (shp || []).reduce(function(area, ids) {
  //     return area + getEllipsoidalPathArea(ids, arcs, crs);
  //   }, 0);
  // }

  // test if a rectangle is completely enclosed in a planar polygon
  function testBoundsInPolygon(bounds, shp, arcs) {
    if (!shp || !testPointInPolygon(bounds.xmin, bounds.ymin, shp, arcs)) return false;
    var isIn = true;
    shp.forEach(function(ids) {
      forEachSegmentInPath(ids, arcs, function(a, b, xx, yy) {
        isIn = isIn && !testSegmentBoundsIntersection([xx[a], yy[a]], [xx[b], yy[b]], bounds);
      });
    });
    return isIn;
  }

  // Return true if point is inside or on boundary of a shape
  //
  function testPointInPolygon(x, y, shp, arcs) {
    var isIn = false,
        isOn = false;
    if (!shp) return false;
    shp.forEach(function(ids) {
      var inRing = testPointInRing(x, y, ids, arcs);
      if (inRing == 1) {
        isIn = !isIn;
      } else if (inRing == -1) {
        isOn = true;
      }
    });
    return isOn || isIn;
  }

  function getYIntercept(x, ax, ay, bx, by) {
    return ay + (x - ax) * (by - ay) / (bx - ax);
  }



  // Test if point (x, y) is inside, outside or on the boundary of a polygon ring
  // Return 0: outside; 1: inside; -1: on boundary
  //
  function testPointInRing(x, y, ids, arcs) {
    /*
    // arcs.getSimpleShapeBounds() doesn't apply simplification, can't use here
    //// wait, why not? simplifcation shoudn't expand bounds, so this test makes sense
    if (!arcs.getSimpleShapeBounds(ids).containsPoint(x, y)) {
      return false;
    }
    */
    var isIn = false,
        isOn = false;
    forEachSegmentInPath(ids, arcs, function(a, b, xx, yy) {
      var result = testRayIntersection(x, y, xx[a], yy[a], xx[b], yy[b]);
      if (result == 1) {
        isIn = !isIn;
      } else if (isNaN(result)) {
        isOn = true;
      }
    });
    return isOn ? -1 : (isIn ? 1 : 0);
  }

  // test if a vertical ray originating at (x, y) intersects a segment
  // returns 1 if intersection, 0 if no intersection, NaN if point touches segment
  // (Special rules apply to endpoint intersections, to support point-in-polygon testing.)
  function testRayIntersection(x, y, ax, ay, bx, by) {
    var val = getRayIntersection(x, y, ax, ay, bx, by);
    if (val != val) {
      return NaN;
    }
    return val == -Infinity ? 0 : 1;
  }

  function getRayIntersection(x, y, ax, ay, bx, by) {
    var hit = -Infinity, // default: no hit
        yInt;

    // case: p is entirely above, left or right of segment
    if (x < ax && x < bx || x > ax && x > bx || y > ay && y > by) ;
    // case: px aligned with a segment vertex
    else if (x === ax || x === bx) {
      // case: vertical segment or collapsed segment
      if (x === ax && x === bx) {
        // p is on segment
        if (y == ay || y == by || y > ay != y > by) {
          hit = NaN;
        }
        // else: no hit
      }
      // case: px equal to ax (only)
      else if (x === ax) {
        if (y === ay) {
          hit = NaN;
        } else if (bx < ax && y < ay) {
          // only score hit if px aligned to rightmost endpoint
          hit = ay;
        }
      }
      // case: px equal to bx (only)
      else {
        if (y === by) {
          hit = NaN;
        } else if (ax < bx && y < by) {
          // only score hit if px aligned to rightmost endpoint
          hit = by;
        }
      }
    // case: px is between endpoints
    } else {
      yInt = getYIntercept(x, ax, ay, bx, by);
      if (yInt > y) {
        hit = yInt;
      } else if (yInt == y) {
        hit = NaN;
      }
    }
    return hit;
  }

  function getPathArea(ids, arcs) {
    return (arcs.isPlanar() ? getPlanarPathArea : getSphericalPathArea)(ids, arcs);
  }

  function getSphericalPathArea(ids, arcs, R) {
    var iter = arcs.getShapeIter(ids);
    return getSphericalPathArea2(iter, R);
  }

  function getSphericalPathArea2(iter, R) {
    var sum = 0,
        started = false,
        deg2rad = Math.PI / 180,
        x, y, xp, yp;
    R = R || WGS84.SEMIMAJOR_AXIS;
    while (iter.hasNext()) {
      x = iter.x * deg2rad;
      y = Math.sin(iter.y * deg2rad);
      if (started) {
        sum += (x - xp) * (2 + y + yp);
      } else {
        started = true;
      }
      xp = x;
      yp = y;
    }
    return sum / 2 * R * R;
  }

  // Get path area from an array of [x, y] points
  // TODO: consider removing duplication with getPathArea(), e.g. by
  //   wrapping points in an iterator.
  //
  function getPlanarPathArea2(points) {
    var sum = 0,
        ax, ay, bx, by, dx, dy, p;
    for (var i=0, n=points.length; i<n; i++) {
      p = points[i];
      if (i === 0) {
        ax = 0;
        ay = 0;
        dx = -p[0];
        dy = -p[1];
      } else {
        ax = p[0] + dx;
        ay = p[1] + dy;
        sum += ax * by - bx * ay;
      }
      bx = ax;
      by = ay;
    }
    return sum / 2;
  }

  function getPlanarPathArea(ids, arcs) {
    var iter = arcs.getShapeIter(ids),
        sum = 0,
        ax, ay, bx, by, dx, dy;
    if (iter.hasNext()) {
      ax = 0;
      ay = 0;
      dx = -iter.x;
      dy = -iter.y;
      while (iter.hasNext()) {
        bx = ax;
        by = ay;
        ax = iter.x + dx;
        ay = iter.y + dy;
        sum += ax * by - bx * ay;
      }
    }
    return sum / 2;
  }

  function getPathPerimeter(ids, arcs) {
    return (arcs.isPlanar() ? getPlanarPathPerimeter : getSphericalPathPerimeter)(ids, arcs);
  }

  function getShapePerimeter(shp, arcs) {
    return (shp || []).reduce(function(len, ids) {
      return len + getPathPerimeter(ids, arcs);
    }, 0);
  }

  function getSphericalShapePerimeter(shp, arcs) {
    if (arcs.isPlanar()) {
      error("[getSphericalShapePerimeter()] Function requires decimal degree coordinates");
    }
    return (shp || []).reduce(function(len, ids) {
      return len + getSphericalPathPerimeter(ids, arcs);
    }, 0);
  }

  function getPlanarPathPerimeter(ids, arcs) {
    return calcPathLen(ids, arcs, false);
  }

  function getSphericalPathPerimeter(ids, arcs) {
    return calcPathLen(ids, arcs, true);
  }

  var PolygonGeom = /*#__PURE__*/Object.freeze({
    __proto__: null,
    calcPolsbyPopperCompactness: calcPolsbyPopperCompactness,
    calcSchwartzbergCompactness: calcSchwartzbergCompactness,
    getPathWinding: getPathWinding,
    getShapeArea: getShapeArea,
    getPlanarShapeArea: getPlanarShapeArea,
    getSphericalShapeArea: getSphericalShapeArea,
    testBoundsInPolygon: testBoundsInPolygon,
    testPointInPolygon: testPointInPolygon,
    testPointInRing: testPointInRing,
    testRayIntersection: testRayIntersection,
    getRayIntersection: getRayIntersection,
    getPathArea: getPathArea,
    getSphericalPathArea: getSphericalPathArea,
    getSphericalPathArea2: getSphericalPathArea2,
    getPlanarPathArea2: getPlanarPathArea2,
    getPlanarPathArea: getPlanarPathArea,
    getPathPerimeter: getPathPerimeter,
    getShapePerimeter: getShapePerimeter,
    getSphericalShapePerimeter: getSphericalShapePerimeter,
    getPlanarPathPerimeter: getPlanarPathPerimeter,
    getSphericalPathPerimeter: getSphericalPathPerimeter
  });

  // Returns an interval for snapping together coordinates that be co-incident bug
  // have diverged because of floating point rounding errors. Intended to be small
  // enought not not to snap points that should be distinct.
  // This is not a robust method... e.g. some formulas for some inputs may produce
  // errors that are larger than this interval.
  // @coords: Array of relevant coordinates (e.g. bbox coordinates of vertex coordinates
  //   of two intersecting segments).
  //
  function getHighPrecisionSnapInterval(coords) {
    var maxCoord = Math.max.apply(null, coords.map(Math.abs));
    return maxCoord * 1e-14;
  }

  function snapCoords(arcs, threshold) {
      var avgDist = getAvgSegment(arcs),
          autoSnapDist = avgDist * 0.0025,
          snapDist = autoSnapDist;

    if (threshold > 0) {
      snapDist = threshold;
      message(utils.format("Applying snapping threshold of %s -- %.6f times avg. segment length", threshold, threshold / avgDist));
    }
    var snapCount = snapCoordsByInterval(arcs, snapDist);
    if (snapCount > 0) arcs.dedupCoords();
    message(utils.format("Snapped %s point%s", snapCount, utils.pluralSuffix(snapCount)));
  }

  function snapCoordsByInterval(arcs, snapDist) {
    if (snapDist > 0 === false) return 0;
    var ids = getCoordinateIds(arcs);
    return snapCoordsInternal(ids, arcs, snapDist);
  }

  function snapEndpointsByInterval(arcs, snapDist) {
    if (snapDist > 0 === false) return 0;
    var ids = getEndpointIds(arcs);
    return snapCoordsInternal(ids, arcs, snapDist);
  }

  // Snap together points within a small threshold
  //
  function snapCoordsInternal(ids, arcs, snapDist) {
    var snapCount = 0,
        n = ids.length,
        data = arcs.getVertexData();

    quicksortIds(data.xx, ids, 0, n-1);

    // Consider: speed up sorting -- try bucket sort as first pass.
    for (var i=0; i<n; i++) {
      snapCount += snapPoint(i, snapDist, ids, data.xx, data.yy);
    }
    return snapCount;

    function snapPoint(i, limit, ids, xx, yy) {
      var j = i,
          n = ids.length,
          x = xx[ids[i]],
          y = yy[ids[i]],
          snaps = 0,
          id2, dx, dy;

      while (++j < n) {
        id2 = ids[j];
        dx = xx[id2] - x;
        if (dx > limit) break;
        dy = yy[id2] - y;
        if (dx === 0 && dy === 0 || dx * dx + dy * dy > limit * limit) continue;
        xx[id2] = x;
        yy[id2] = y;
        snaps++;
      }
      return snaps;
    }
  }

  function getCoordinateIds(arcs) {
    var data = arcs.getVertexData(),
        n = data.xx.length,
        ids = new Uint32Array(n);
    for (var i=0; i<n; i++) {
      ids[i] = i;
    }
    return ids;
  }

  function getEndpointIds(arcs) {
    var i = 0;
    var ids = [];
    var data = arcs.getVertexData();
    data.nn.forEach(function(n) {
      if (n > 0 === false) return;
      ids.push(i, i+n-1);
      i += n;
    });
    return ids;
  }

  /*
  // Returns array of array ids, in ascending order.
  // @a array of numbers
  //
  utils.sortCoordinateIds = function(a) {
    return utils.bucketSortIds(a);
  };

  // This speeds up sorting of large datasets (~2x faster for 1e7 values)
  // worth the additional code?
  utils.bucketSortIds = function(a, n) {
    var len = a.length,
        ids = new Uint32Array(len),
        bounds = utils.getArrayBounds(a),
        buckets = Math.ceil(n > 0 ? n : len / 10),
        counts = new Uint32Array(buckets),
        offsets = new Uint32Array(buckets),
        i, j, offs, count;

    // get bucket sizes
    for (i=0; i<len; i++) {
      j = bucketId(a[i], bounds.min, bounds.max, buckets);
      counts[j]++;
    }

    // convert counts to offsets
    offs = 0;
    for (i=0; i<buckets; i++) {
      offsets[i] = offs;
      offs += counts[i];
    }

    // assign ids to buckets
    for (i=0; i<len; i++) {
      j = bucketId(a[i], bounds.min, bounds.max, buckets);
      offs = offsets[j]++;
      ids[offs] = i;
    }

    // sort each bucket with quicksort
    for (i = 0; i<buckets; i++) {
      count = counts[i];
      if (count > 1) {
        offs = offsets[i] - count;
        utils.quicksortIds(a, ids, offs, offs + count - 1);
      }
    }
    return ids;

    function bucketId(val, min, max, buckets) {
      var id = (buckets * (val - min) / (max - min)) | 0;
      return id < buckets ? id : buckets - 1;
    }
  };
  */

  function quicksortIds(a, ids, lo, hi) {
    if (hi - lo > 24) {
      var pivot = a[ids[lo + hi >> 1]],
          i = lo,
          j = hi,
          tmp;
      while (i <= j) {
        while (a[ids[i]] < pivot) i++;
        while (a[ids[j]] > pivot) j--;
        if (i <= j) {
          tmp = ids[i];
          ids[i] = ids[j];
          ids[j] = tmp;
          i++;
          j--;
        }
      }
      if (j > lo) quicksortIds(a, ids, lo, j);
      if (i < hi) quicksortIds(a, ids, i, hi);
    } else {
      insertionSortIds(a, ids, lo, hi);
    }
  }

  function insertionSortIds(arr, ids, start, end) {
    var id, i, j;
    for (j = start + 1; j <= end; j++) {
      id = ids[j];
      for (i = j - 1; i >= start && arr[id] < arr[ids[i]]; i--) {
        ids[i+1] = ids[i];
      }
      ids[i+1] = id;
    }
  }

  var Snapping = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getHighPrecisionSnapInterval: getHighPrecisionSnapInterval,
    snapCoords: snapCoords,
    snapCoordsByInterval: snapCoordsByInterval,
    snapEndpointsByInterval: snapEndpointsByInterval,
    getCoordinateIds: getCoordinateIds,
    getEndpointIds: getEndpointIds
  });

  // Find the intersection between two 2D segments
  // Returns 0, 1 or 2 [x, y] locations as null, [x, y], or [x1, y1, x2, y2]
  // Special cases:
  // Endpoint-to-endpoint touches are not treated as intersections.
  // If the segments touch at a T-intersection, it is treated as an intersection.
  // If the segments are collinear and partially overlapping, each subsumed endpoint
  //    is counted as an intersection (there will be either one or two)
  //
  function segmentIntersection(ax, ay, bx, by, cx, cy, dx, dy, epsArg) {
    // Use a small tolerance interval, so collinear segments and T-intersections
    // are detected (floating point rounding often causes exact functions to fail)
    var eps = epsArg >= 0 ? epsArg :
        getHighPrecisionSnapInterval([ax, ay, bx, by, cx, cy, dx, dy]);
    var epsSq = eps * eps;
    var touches, cross;
    // Detect 0, 1 or 2 'touch' intersections, where a vertex of one segment
    // is very close to the other segment's linear portion.
    // One touch indicates either a T-intersection or two overlapping collinear
    // segments that share an endpoint. Two touches indicates overlapping
    // collinear segments that do not share an endpoint.
    touches = findPointSegTouches(epsSq, ax, ay, bx, by, cx, cy, dx, dy);
    // if (touches) return touches;
    // Ignore endpoint-only intersections
    if (!touches && testEndpointHit(epsSq, ax, ay, bx, by, cx, cy, dx, dy)) {
      return null;
    }
    // Detect cross intersection
    cross = findCrossIntersection(ax, ay, bx, by, cx, cy, dx, dy, eps);
    return touches || cross || null;
  }


  // Find the intersection point of two segments that cross each other,
  // or return null if the segments do not cross.
  // Assumes endpoint intersections have already been detected
  function findCrossIntersection(ax, ay, bx, by, cx, cy, dx, dy, eps) {
    if (!segmentHit(ax, ay, bx, by, cx, cy, dx, dy)) return null;
    var den = determinant2D(bx - ax, by - ay, dx - cx, dy - cy);
    var m = orient2D(cx, cy, dx, dy, ax, ay) / den;
    var p = [ax + m * (bx - ax), ay + m * (by - ay)];
    if (Math.abs(den) < 1e-18) {
      // assume that collinear and near-collinear segment intersections have been
      // accounted for already.
      // TODO: is this a valid assumption?
      return null;
    }

    // Snap p to a vertex if very close to one
    // This avoids tiny segments caused by T-intersection overshoots and prevents
    //   pathfinder errors related to f-p rounding.
    // (NOTE: this may no longer be needed, since T-intersections are now detected
    // first)
    if (eps > 0) {
      snapIntersectionPoint(p, ax, ay, bx, by, cx, cy, dx, dy, eps);
    }
    // Clamp point to x range and y range of both segments
    // (This may occur due to fp rounding, if one segment is vertical or horizontal)
    clampIntersectionPoint(p, ax, ay, bx, by, cx, cy, dx, dy);
    return p;
  }

  function testEndpointHit(epsSq, ax, ay, bx, by, cx, cy, dx, dy) {
    return distanceSq(ax, ay, cx, cy) <= epsSq || distanceSq(ax, ay, dx, dy) <= epsSq ||
      distanceSq(bx, by, cx, cy) <= epsSq || distanceSq(bx, by, dx, dy) <= epsSq;
  }

  function findPointSegTouches(epsSq, ax, ay, bx, by, cx, cy, dx, dy) {
    var touches = [];
    collectPointSegTouch(touches, epsSq, ax, ay, cx, cy, dx, dy);
    collectPointSegTouch(touches, epsSq, bx, by, cx, cy, dx, dy);
    collectPointSegTouch(touches, epsSq, cx, cy, ax, ay, bx, by);
    collectPointSegTouch(touches, epsSq, dx, dy, ax, ay, bx, by);
    if (touches.length === 0) return null;
    if (touches.length > 4) {
      // Geometrically, more than two touch intersections can not occur.
      // Is it possible that fp rounding or a bug might result in >2 touches?
      debug('Intersection detection error');
    }
    return touches;
  }

  function collectPointSegTouch(arr, epsSq, px, py, ax, ay, bx, by) {
    // The original point-seg distance function caused errors in test data.
    // (probably because of large rounding errors with some inputs).
    // var pab = pointSegDistSq(px, py, ax, ay, bx, by);
    var pab = pointSegDistSq2(px, py, ax, ay, bx, by);
    if (pab > epsSq) return; // point is too far from segment to touch
    var pa = distanceSq(ax, ay, px, py);
    var pb = distanceSq(bx, by, px, py);
    if (pa <= epsSq || pb <= epsSq) return; // ignore endpoint hits
    arr.push(px, py); // T intersection at P and AB
  }


  // Used by mapshaper-undershoots.js
  // TODO: make more robust, make sure result is compatible with segmentIntersection()
  // (rounding errors currently must be handled downstream)
  function findClosestPointOnSeg(px, py, ax, ay, bx, by) {
    var dx = bx - ax,
        dy = by - ay,
        dotp = (px - ax) * dx + (py - ay) * dy,
        abSq = dx * dx + dy * dy,
        k = abSq === 0 ? -1 : dotp / abSq,
        eps = 0.1, // 1e-6, // snap to endpoint
        p;
    if (k <= eps) {
      p = [ax, ay];
    } else if (k >= 1 - eps) {
      p = [bx, by];
    } else {
      p = [ax + k * dx, ay + k * dy];
    }
    return p;
  }

  function snapIfCloser(p, minDist, x, y, x2, y2) {
    var dist = distance2D(x, y, x2, y2);
    if (dist < minDist) {
      minDist = dist;
      p[0] = x2;
      p[1] = y2;
    }
    return minDist;
  }

  function snapIntersectionPoint(p, ax, ay, bx, by, cx, cy, dx, dy, eps) {
    var x = p[0],
        y = p[1],
        snapDist = eps;
    snapDist = snapIfCloser(p, snapDist, x, y, ax, ay);
    snapDist = snapIfCloser(p, snapDist, x, y, bx, by);
    snapDist = snapIfCloser(p, snapDist, x, y, cx, cy);
    snapDist = snapIfCloser(p, snapDist, x, y, dx, dy);
  }

  function clampIntersectionPoint(p, ax, ay, bx, by, cx, cy, dx, dy) {
    // Handle intersection points that fall outside the x-y range of either
    // segment by snapping to nearest endpoint coordinate. Out-of-range
    // intersection points can be caused by floating point rounding errors
    // when a segment is vertical or horizontal. This has caused problems when
    // repeatedly applying bbox clipping along the same segment
    var x = p[0],
        y = p[1];
    // assumes that segment ranges intersect
    x = clampToCloseRange(x, ax, bx);
    x = clampToCloseRange(x, cx, dx);
    y = clampToCloseRange(y, ay, by);
    y = clampToCloseRange(y, cy, dy);
    p[0] = x;
    p[1] = y;
  }

  // a: coordinate of point
  // b: endpoint coordinate of segment
  // c: other endpoint of segment
  function outsideRange(a, b, c) {
    var out;
    if (b < c) {
      out = a < b || a > c;
    } else if (b > c) {
      out = a > b || a < c;
    } else {
      out = a != b;
    }
    return out;
  }

  function clampToCloseRange(a, b, c) {
    var lim;
    if (outsideRange(a, b, c)) {
      lim = Math.abs(a - b) < Math.abs(a - c) ? b : c;
      if (Math.abs(a - lim) > 1e-15) {
        debug("[clampToCloseRange()] large clamping interval", a, b, c);
      }
      a = lim;
    }
    return a;
  }

  // Determinant of matrix
  //  | a  b |
  //  | c  d |
  function determinant2D(a, b, c, d) {
    return a * d - b * c;
  }

  // returns a positive value if the points a, b, and c are arranged in
  // counterclockwise order, a negative value if the points are in clockwise
  // order, and zero if the points are collinear.
  // Source: Jonathan Shewchuk http://www.cs.berkeley.edu/~jrs/meshpapers/robnotes.pdf
  function orient2D(ax, ay, bx, by, cx, cy) {
    return determinant2D(ax - cx, ay - cy, bx - cx, by - cy);
  }

  // Source: Sedgewick, _Algorithms in C_
  // (Other functions were tried that were more sensitive to floating point errors
  //  than this function)
  function segmentHit(ax, ay, bx, by, cx, cy, dx, dy) {
    return orient2D(ax, ay, bx, by, cx, cy) *
        orient2D(ax, ay, bx, by, dx, dy) <= 0 &&
        orient2D(cx, cy, dx, dy, ax, ay) *
        orient2D(cx, cy, dx, dy, bx, by) <= 0;
  }

  // Useful for determining if a segment that intersects another segment is
  // entering or leaving an enclosed buffer area
  // returns -1 if angle of p1p2 -> p3p4 is counter-clockwise (left turn)
  // returns 1 if angle is clockwise
  // return 0 if segments are collinear
  function segmentTurn(p1, p2, p3, p4) {
    var ax = p1[0],
        ay = p1[1],
        bx = p2[0],
        by = p2[1],
        // shift p3p4 segment to start at p2
        dx = bx - p3[0],
        dy = by - p3[1],
        cx = p4[0] + dx,
        cy = p4[1] + dy,
        orientation = orient2D(ax, ay, bx, by, cx, cy);
      if (!orientation) return 0;
      return orientation < 0 ? 1 : -1;
  }

  var SegmentGeom = /*#__PURE__*/Object.freeze({
    __proto__: null,
    segmentIntersection: segmentIntersection,
    findClosestPointOnSeg: findClosestPointOnSeg,
    orient2D: orient2D,
    segmentHit: segmentHit,
    segmentTurn: segmentTurn
  });

  var geom = Object.assign({}, Geom, PolygonGeom, PathGeom, SegmentGeom, PolygonCentroid);

  // Utility functions for working with ArcCollection and arrays of arc ids.

  // Return average segment length (with simplification)
  function getAvgSegment(arcs) {
    var sum = 0;
    var count = arcs.forEachSegment(function(i, j, xx, yy) {
      var dx = xx[i] - xx[j],
          dy = yy[i] - yy[j];
      sum += Math.sqrt(dx * dx + dy * dy);
    });
    return sum / count || 0;
  }

  // Return average magnitudes of dx, dy (with simplification)
  function getAvgSegment2(arcs) {
    var dx = 0, dy = 0;
    var count = arcs.forEachSegment(function(i, j, xx, yy) {
      dx += Math.abs(xx[i] - xx[j]);
      dy += Math.abs(yy[i] - yy[j]);
    });
    return [dx / count || 0, dy / count || 0];
  }

  /*
  this.getAvgSegmentSph2 = function() {
    var sumx = 0, sumy = 0;
    var count = this.forEachSegment(function(i, j, xx, yy) {
      var lat1 = yy[i],
          lat2 = yy[j];
      sumy += geom.degreesToMeters(Math.abs(lat1 - lat2));
      sumx += geom.degreesToMeters(Math.abs(xx[i] - xx[j]) *
          Math.cos((lat1 + lat2) * 0.5 * geom.D2R);
    });
    return [sumx / count || 0, sumy / count || 0];
  };
  */

  function getDirectedArcPresenceTest(shapes, n) {
    var flags = new Uint8Array(n);
    forEachArcId(shapes, function(id) {
      var absId = absArcId(id);
      if (absId < n === false) error('index error');
      flags[absId] |= id < 0 ? 2 : 1;
    });
    return function(arcId) {
      var absId = absArcId(arcId);
      return arcId < 0 ? (flags[absId] & 2) == 2 : (flags[absId] & 1) == 1;
    };
  }

  function getArcPresenceTest(shapes, arcs) {
    var counts = new Uint8Array(arcs.size());
    countArcsInShapes(shapes, counts);
    return function(id) {
      if (id < 0) id = ~id;
      return counts[id] > 0;
    };
  }

  // @counts A typed array for accumulating count of each abs arc id
  //   (assume it won't overflow)
  function countArcsInShapes(shapes, counts) {
    traversePaths(shapes, null, function(obj) {
      var arcs = obj.arcs,
          id;
      for (var i=0; i<arcs.length; i++) {
        id = arcs[i];
        if (id < 0) id = ~id;
        counts[id]++;
      }
    });
  }

  function getPathBounds(shapes, arcs) {
    var bounds = new Bounds();
    forEachArcId(shapes, function(id) {
      arcs.mergeArcBounds(id, bounds);
    });
    return bounds;
  }

  // Returns subset of shapes in @shapes that contain one or more arcs in @arcIds
  function findShapesByArcId(shapes, arcIds, numArcs) {
    var index = numArcs ? new Uint8Array(numArcs) : [],
        found = [];
    arcIds.forEach(function(id) {
      index[absArcId(id)] = 1;
    });
    shapes.forEach(function(shp, shpId) {
      var isHit = false;
      forEachArcId(shp || [], function(id) {
        isHit = isHit || index[absArcId(id)] == 1;
      });
      if (isHit) {
        found.push(shpId);
      }
    });
    return found;
  }

  function reversePath(ids) {
    ids.reverse();
    for (var i=0, n=ids.length; i<n; i++) {
      ids[i] = ~ids[i];
    }
    return ids;
  }

  function clampIntervalByPct(z, pct) {
    if (pct <= 0) z = Infinity;
    else if (pct >= 1) z = 0;
    return z;
  }

  // Return id of the vertex between @start and @end with the highest
  // threshold that is less than @zlim, or -1 if none
  //
  function findNextRemovableVertex(zz, zlim, start, end) {
    var tmp, jz = 0, j = -1, z;
    if (start > end) {
      tmp = start;
      start = end;
      end = tmp;
    }
    for (var i=start+1; i<end; i++) {
      z = zz[i];
      if (z < zlim && z > jz) {
        j = i;
        jz = z;
      }
    }
    return j;
  }

  // Visit each arc id in a path, shape or array of shapes
  // Use non-undefined return values of callback @cb as replacements.
  function forEachArcId(arr, cb) {
    var item;
    for (var i=0; i<arr.length; i++) {
      item = arr[i];
      if (item instanceof Array) {
        forEachArcId(item, cb);
      } else if (utils.isInteger(item)) {
        var val = cb(item);
        if (val !== void 0) {
          arr[i] = val;
        }
      } else if (item) {
        error("Non-integer arc id in:", arr);
      }
    }
  }

  function forEachSegmentInShape(shape, arcs, cb) {
    for (var i=0, n=shape ? shape.length : 0; i<n; i++) {
      forEachSegmentInPath(shape[i], arcs, cb);
    }
  }

  function forEachSegmentInPath(ids, arcs, cb) {
    for (var i=0, n=ids.length; i<n; i++) {
      arcs.forEachArcSegment(ids[i], cb);
    }
  }

  function traversePaths(shapes, cbArc, cbPart, cbShape) {
    var segId = 0;
    shapes.forEach(function(parts, shapeId) {
      if (!parts || parts.length === 0) return; // null shape
      var arcIds, arcId;
      if (cbShape) {
        cbShape(shapeId);
      }
      for (var i=0, m=parts.length; i<m; i++) {
        arcIds = parts[i];
        if (cbPart) {
          cbPart({
            i: i,
            shapeId: shapeId,
            shape: parts,
            arcs: arcIds
          });
        }

        if (cbArc) {
          for (var j=0, n=arcIds.length; j<n; j++, segId++) {
            arcId = arcIds[j];
            cbArc({
              i: j,
              shapeId: shapeId,
              partId: i,
              arcId: arcId,
              segId: segId
            });
          }
        }
      }
    });
  }

  function arcHasLength(id, coords) {
    var iter = coords.getArcIter(id), x, y;
    if (iter.hasNext()) {
      x = iter.x;
      y = iter.y;
      while (iter.hasNext()) {
        if (iter.x != x || iter.y != y) return true;
      }
    }
    return false;
  }

  function filterEmptyArcs(shape, coords) {
    if (!shape) return null;
    var shape2 = [];
    shape.forEach(function(ids) {
      var path = [];
      for (var i=0; i<ids.length; i++) {
        if (arcHasLength(ids[i], coords)) {
          path.push(ids[i]);
        }
      }
      if (path.length > 0) shape2.push(path);
    });
    return shape2.length > 0 ? shape2 : null;
  }

  // Return an array of information about each part/ring in a polygon or polyline shape
  function getPathMetadata(shape, arcs, type) {
    var data = [],
        ids;
    for (var i=0, n=shape && shape.length; i<n; i++) {
      ids = shape[i];
      data.push({
        ids: ids,
        area: type == 'polygon' ? geom.getPlanarPathArea(ids, arcs) : 0,
        bounds: arcs.getSimpleShapeBounds(ids)
      });
    }
    return data;
  }

  function quantizeArcs(arcs, quanta) {
    // Snap coordinates to a grid of @quanta locations on both axes
    // This may snap nearby points to the same coordinates.
    // Consider a cleanup pass to remove dupes, make sure collapsed arcs are
    //   removed on export.
    //
    var bb1 = arcs.getBounds(),
        bb2 = new Bounds(0, 0, quanta-1, quanta-1),
        fw = bb1.getTransform(bb2),
        inv = fw.invert();

    arcs.transformPoints(function(x, y) {
      var p = fw.transform(x, y);
      return inv.transform(Math.round(p[0]), Math.round(p[1]));
    });
  }

  var PathUtils = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getAvgSegment: getAvgSegment,
    getAvgSegment2: getAvgSegment2,
    getDirectedArcPresenceTest: getDirectedArcPresenceTest,
    getArcPresenceTest: getArcPresenceTest,
    countArcsInShapes: countArcsInShapes,
    getPathBounds: getPathBounds,
    findShapesByArcId: findShapesByArcId,
    reversePath: reversePath,
    clampIntervalByPct: clampIntervalByPct,
    findNextRemovableVertex: findNextRemovableVertex,
    forEachArcId: forEachArcId,
    forEachSegmentInShape: forEachSegmentInShape,
    forEachSegmentInPath: forEachSegmentInPath,
    traversePaths: traversePaths,
    filterEmptyArcs: filterEmptyArcs,
    getPathMetadata: getPathMetadata,
    quantizeArcs: quantizeArcs
  });

  // Utility functions for both paths and points

  // @shp An element of the layer.shapes array
  //   (may be null, or, depending on layer type, an array of points or an array of arrays of arc ids)
  function cloneShape(shp) {
    if (!shp) return null;
    return shp.map(function(part) {
      return part.concat();
    });
  }

  function cloneShapes(arr) {
    return utils.isArray(arr) ? arr.map(cloneShape) : null;
  }

  function forEachShapePart(paths, cb) {
    editShapeParts(paths, cb);
  }

  // Updates shapes array in-place.
  // editPart: callback function
  function editShapes(shapes, editPart) {
    for (var i=0, n=shapes.length; i<n; i++) {
      shapes[i] = editShapeParts(shapes[i], editPart);
    }
  }

  // @parts: geometry of a feature (array of paths, array of points or null)
  // @cb: function(part, i, parts)
  //    If @cb returns an array, it replaces the existing value
  //    If @cb returns null, the path is removed from the feature
  //
  function editShapeParts(parts, cb) {
    if (!parts) return null; // null geometry not edited
    if (!utils.isArray(parts)) error("Expected an array, received:", parts);
    var nulls = 0,
        n = parts.length,
        retn;

    for (var i=0; i<n; i++) {
      retn = cb(parts[i], i, parts);
      if (retn === null) {
        nulls++;
        parts[i] = null;
      } else if (utils.isArray(retn)) {
        parts[i] = retn;
      }
    }
    if (nulls == n) {
      return null;
    } else if (nulls > 0) {
      return parts.filter(function(part) {return !!part;});
    } else {
      return parts;
    }
  }

  // Get max number of parts in a single shape from an array of shapes.
  // Caveat: polygon holes are counted as separate parts.
  function findMaxPartCount(shapes) {
    var maxCount = 0, shp;
    for (var i=0, n=shapes.length; i<n; i++) {
      shp = shapes[i];
      if (shp && shp.length > maxCount) {
        maxCount = shp.length;
      }
    }
    return maxCount;
  }

  var ShapeUtils = /*#__PURE__*/Object.freeze({
    __proto__: null,
    cloneShape: cloneShape,
    cloneShapes: cloneShapes,
    forEachShapePart: forEachShapePart,
    editShapes: editShapes,
    editShapeParts: editShapeParts,
    findMaxPartCount: findMaxPartCount
  });

  // Several dependencies are loaded via require() ... this module returns a
  // stub function when require() does not exist as a global function,
  // to avoid runtime errors (this should only happen in some tests when single
  // modules are imported)
  var f;
  if (typeof require == 'function') {
    f = require;
  } else {
    f = function() {
      // console.error('Unable to load module', name);
    };
  }
  var require$1 = f;

  // import { createRequire } from "module";

  var iconv = require$1('iconv-lite');

  // import iconv from 'iconv-lite';
  // import * as iconv from 'iconv-lite';
  // import * as iconv from '../../node_modules/iconv-lite/lib/index.js';

  // List of encodings supported by iconv-lite:
  // https://github.com/ashtuchkin/iconv-lite/wiki/Supported-Encodings

  var toUtf8 = getNativeEncoder('utf8');
  var fromUtf8 = getNativeDecoder('utf8');

  // Return list of supported encodings
  function getEncodings() {
    iconv.encodingExists('ascii'); // make iconv load its encodings
    return Object.keys(iconv.encodings);
  }

  function validateEncoding(enc) {
    if (!encodingIsSupported(enc)) {
      stop("Unknown encoding:", enc, "\nRun the -encodings command see a list of supported encodings");
    }
    return enc;
  }

  function stringsAreAscii(arr) {
    return stringIsAscii(arr.join(''));
  }

  function stringIsAscii(str) {
    var c;
    for (var i=0, n=str.length; i<n; i++) {
      c = str.charCodeAt(i);
      if (c >= 128) return false;
    }
    return true;
  }

  function encodingIsUtf8(enc) {
    // treating utf-8 as default
    return !enc || /^utf-?8$/i.test(String(enc));
  }

  // Identify the most common encodings that are supersets of ascii at the
  // single-byte level (meaning that bytes in 0 - 0x7f range must be ascii)
  // (this allows identifying line breaks and other ascii patterns in buffers)
  function encodingIsAsciiCompat(enc) {
    enc = standardizeEncodingName(enc);
    // gb.* selects the Guo Biao encodings
    // big5 in not compatible -- second byte starts at 0x40
    return !enc || /^(win|latin|utf8|ascii|iso88|gb)/.test(enc);
  }

  // Ex. convert UTF-8 to utf8
  function standardizeEncodingName(enc) {
    return (enc || '').toLowerCase().replace(/[_-]/g, '');
  }

  // Similar to Buffer#toString(); tries to speed up utf8 conversion in
  // web browser (when using browserify Buffer shim)
  function bufferToString(buf, enc, start, end) {
    if (start >= 0) {
      buf = buf.slice(start, end);
    }
    return decodeString(buf, enc);
  }

  function getNativeEncoder(enc) {
    var encoder = null;
    enc = standardizeEncodingName(enc);
    if (enc != 'utf8') {
      // TODO: support more encodings if TextEncoder is available
      return null;
    }
    if (typeof TextEncoder != 'undefined') {
      encoder = new TextEncoder(enc);
    }
    return function(str) {
      // Convert Uint8Array from encoder to Buffer (fix for issue #216)
      return encoder ? B$3.from(encoder.encode(str).buffer) : utils.createBuffer(str, enc);
    };
  }

  function encodeString(str, enc) {
    // TODO: faster ascii encoding?
    var buf;
    if (encodingIsUtf8(enc)) {
      buf = toUtf8(str);
    } else {
      buf = iconv.encode(str, enc);
    }
    return buf;
  }

  function getNativeDecoder(enc) {
    var decoder = null;
    enc = standardizeEncodingName(enc);
    if (enc != 'utf8') {
      // TODO: support more encodings if TextDecoder is available
      return null;
    }
    if (typeof TextDecoder != 'undefined') {
      decoder = new TextDecoder(enc);
    }
    return function(buf) {
      return decoder ? decoder.decode(buf) : buf.toString(enc);
    };
  }

  // @buf a Node Buffer
  function decodeString(buf, enc) {
    var str;
    if (encodingIsUtf8(enc)) {
      str = fromUtf8(buf);
    } else {
      str = iconv.decode(buf, enc);
    }
    return str;
  }

  function encodingIsSupported(raw) {
    var enc = standardizeEncodingName(raw);
    return getEncodings().includes(enc);
  }

  function trimBOM(str) {
    // remove BOM if present
    if (str.charCodeAt(0) == 0xfeff) {
      str = str.substr(1);
    }
    return str;
  }

  function printEncodings() {
    var encodings = getEncodings().filter(function(name) {
      // filter out some aliases and non-applicable encodings
      return !/^(_|cs|internal|ibm|isoir|singlebyte|table|[0-9]|l[0-9]|windows)/.test(name);
    });
    encodings.sort();
    print("Supported encodings:\n" + formatStringsAsGrid(encodings));
  }

  var Encodings = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getEncodings: getEncodings,
    validateEncoding: validateEncoding,
    stringsAreAscii: stringsAreAscii,
    stringIsAscii: stringIsAscii,
    encodingIsUtf8: encodingIsUtf8,
    encodingIsAsciiCompat: encodingIsAsciiCompat,
    standardizeEncodingName: standardizeEncodingName,
    bufferToString: bufferToString,
    encodeString: encodeString,
    decodeString: decodeString,
    encodingIsSupported: encodingIsSupported,
    trimBOM: trimBOM,
    printEncodings: printEncodings
  });

  // Not a general-purpose deep copy function
  function copyRecord(o) {
    var o2 = {}, key, val;
    if (!o) return null;
    for (key in o) {
      if (o.hasOwnProperty(key)) {
        val = o[key];
        if (val == o) {
          // avoid infinite recursion if val is a circular reference, by copying all properties except key
          val = utils.extend({}, val);
          delete val[key];
        }
        o2[key] = val && val.constructor === Object ? copyRecord(val) : val;
      }
    }
    return o2;
  }

  function getValueType(val) {
    var type = null;
    if (utils.isString(val)) {
      type = 'string';
    } else if (utils.isNumber(val)) {
      type = 'number';
    } else if (utils.isBoolean(val)) {
      type = 'boolean';
    } else if (utils.isDate(val)) {
      type = 'date';
    } else if (utils.isObject(val)) {
      type = 'object';
    }
    return type;
  }

  // Fill out a data table with undefined values
  // The undefined members will disappear when records are exported as JSON,
  // but will show up when fields are listed using Object.keys()
  function fixInconsistentFields(records) {
    var fields = findIncompleteFields(records);
    patchMissingFields(records, fields);
  }

  function findIncompleteFields(records) {
    var counts = {},
        i, j, keys;
    for (i=0; i<records.length; i++) {
      keys = Object.keys(records[i] || {});
      for (j=0; j<keys.length; j++) {
        counts[keys[j]] = (counts[keys[j]] | 0) + 1;
      }
    }
    return Object.keys(counts).filter(function(k) {return counts[k] < records.length;});
  }

  function patchMissingFields(records, fields) {
    var rec, i, j, f;
    for (i=0; i<records.length; i++) {
      rec = records[i] || (records[i] = {});
      for (j=0; j<fields.length; j++) {
        f = fields[j];
        if (f in rec === false) {
          rec[f] = undefined;
        }
      }
    }
  }

  function fieldListContainsAll(list, fields) {
    return list.indexOf('*') > -1 || utils.difference(fields, list).length === 0;
  }

  function getColumnType(key, records) {
    var type = null,
        rec;
    for (var i=0, n=records.length; i<n; i++) {
      rec = records[i];
      type = rec ? getValueType(rec[key]) : null;
      if (type) break;
    }
    return type;
  }

  function deleteFields(table, test) {
    table.getFields().forEach(function(name) {
      if (test(name)) {
        table.deleteField(name);
      }
    });
  }

  function isInvalidFieldName(f) {
    // Reject empty and all-whitespace strings. TODO: consider other criteria
    return /^\s*$/.test(f);
  }

  // Resolve name conflicts in field names by appending numbers
  // @fields Array of field names
  // @maxLen (optional) Maximum chars in name
  //
  function getUniqFieldNames(fields, maxLen, encoding) {
    var used = {};
    return fields.map(function(name) {
      var i = 0,
          validName;
      do {
        validName = encoding && encoding != 'ascii' ?
          adjustEncodedFieldName(name, maxLen, i, encoding) :
          adjustFieldName(name, maxLen, i);
        i++;
      } while ((validName in used) ||
        // don't replace an existing valid field name with a truncated name
        name != validName && utils.contains(fields, validName));
      used[validName] = true;
      return validName;
    });
  }

  function getFieldValues(records, field) {
    return records.map(function(rec) {
      return rec ? rec[field] : undefined;
    });
  }

  function getUniqFieldValues(records, field) {
    var index = {};
    var values = [];
    records.forEach(function(rec) {
      var val = rec[field];
      if (val in index === false) {
        index[val] = true;
        values.push(val);
      }
    });
    return values;
  }

  // Truncate and/or uniqify a name (if relevant params are present)
  function adjustFieldName(name, maxLen, i) {
    var name2, suff;
    maxLen = maxLen || 256;
    if (!i) {
      name2 = name.substr(0, maxLen);
    } else {
      suff = String(i);
      if (suff.length == 1) {
        suff = '_' + suff;
      }
      name2 = name.substr(0, maxLen - suff.length) + suff;
    }
    return name2;
  }

  // Truncate and/or uniqify a name (if relevant params are present)
  function adjustEncodedFieldName(name, maxLen, i, encoding) {
    var suff = i ? String(i) : '';
    var name2 = name + suff;
    var buf = encodeString(name2, encoding);
    if (buf.length > (maxLen || 256)) {
      name = name.substr(0, name.length - 1);
      return adjustEncodedFieldName(name, maxLen, i, encoding);
    }
    return name2;
  }

  function applyFieldOrder(arr, option) {
    if (option == 'ascending') {
      arr.sort(function(a, b) {
        return a.toLowerCase() < b.toLowerCase() ? -1 : 1;
      });
    }
    return arr;
  }

  function getFirstNonEmptyRecord(records) {
    for (var i=0, n=records ? records.length : 0; i<n; i++) {
      if (records[i]) return records[i];
    }
    return null;
  }

  function findFieldNames(records, order) {
    var first = getFirstNonEmptyRecord(records);
    var names = first ? Object.keys(first) : [];
    return applyFieldOrder(names, order);
  }

  var DataUtils = /*#__PURE__*/Object.freeze({
    __proto__: null,
    copyRecord: copyRecord,
    getValueType: getValueType,
    fixInconsistentFields: fixInconsistentFields,
    fieldListContainsAll: fieldListContainsAll,
    getColumnType: getColumnType,
    deleteFields: deleteFields,
    isInvalidFieldName: isInvalidFieldName,
    getUniqFieldNames: getUniqFieldNames,
    getFieldValues: getFieldValues,
    getUniqFieldValues: getUniqFieldValues,
    applyFieldOrder: applyFieldOrder,
    getFirstNonEmptyRecord: getFirstNonEmptyRecord,
    findFieldNames: findFieldNames
  });

  function DataTable(obj) {
    var records;
    if (utils.isArray(obj)) {
      records = obj;
    } else {
      records = [];
      // integer object: create empty records
      if (utils.isInteger(obj)) {
        for (var i=0; i<obj; i++) {
          records.push({});
        }
      } else if (obj) {
        error("Invalid DataTable constructor argument:", obj);
      }
    }

    this.getRecords = function() {
      return records;
    };

    // Same-name method in ShapefileTable doesn't require parsing the entire DBF file
    this.getReadOnlyRecordAt = function(i) {
      return copyRecord(records[i]); // deep-copies plain objects but not other constructed objects
    };
  }

  DataTable.prototype = {

    fieldExists: function(name) {
      return utils.contains(this.getFields(), name);
    },

    toString: function() {return JSON.stringify(this);},

    toJSON: function() {
      return this.getRecords();
    },

    addField: function(name, init) {
      var useFunction = utils.isFunction(init);
      if (!utils.isNumber(init) && !utils.isString(init) && !useFunction) {
        error("DataTable#addField() requires a string, number or function for initialization");
      }
      if (this.fieldExists(name)) error("DataTable#addField() tried to add a field that already exists:", name);
      // var dataFieldRxp = /^[a-zA-Z_][a-zA-Z_0-9]*$/;
      // if (!dataFieldRxp.test(name)) error("DataTable#addField() invalid field name:", name);

      this.getRecords().forEach(function(obj, i) {
        obj[name] = useFunction ? init(obj, i) : init;
      });
    },

    getRecordAt: function(i) {
      return this.getRecords()[i];
    },

    addIdField: function() {
      this.addField('FID', function(obj, i) {
        return i;
      });
    },

    deleteField: function(f) {
      this.getRecords().forEach(function(o) {
        delete o[f];
      });
    },

    getFields: function() {
      return findFieldNames(this.getRecords());
    },

    isEmpty: function() {
      return this.getFields().length === 0 || this.size() === 0;
    },

    update: function(f) {
      var records = this.getRecords();
      for (var i=0, n=records.length; i<n; i++) {
        records[i] = f(records[i], i);
      }
    },

    clone: function() {
      // TODO: this could be sped up using a record constructor function
      // (see getRecordConstructor() in DbfReader)
      var records2 = this.getRecords().map(copyRecord);
      return new DataTable(records2);
    },

    size: function() {
      return this.getRecords().length;
    }
  };

  // Insert a column of values into a (new or existing) data field
  function insertFieldValues(lyr, fieldName, values) {
    var size = getFeatureCount(lyr) || values.length,
        table = lyr.data = (lyr.data || new DataTable(size)),
        records = table.getRecords(),
        rec, val;

    for (var i=0, n=records.length; i<n; i++) {
      rec = records[i];
      val = values[i];
      if (!rec) rec = records[i] = {};
      rec[fieldName] = val === undefined ? null : val;
    }
  }

  function getLayerDataTable(lyr) {
    var data = lyr.data;
    if (!data) {
      data = lyr.data = new DataTable(lyr.shapes ? lyr.shapes.length : 0);
    }
    return data;
  }

  function layerHasNonNullData(lyr) {
    return lyr.data && getFirstNonEmptyRecord(lyr.data.getRecords()) ? true : false;
  }

  function layerHasGeometry(lyr) {
    return layerHasPaths(lyr) || layerHasPoints(lyr);
  }

  function layerHasPaths(lyr) {
    return (lyr.geometry_type == 'polygon' || lyr.geometry_type == 'polyline') &&
      layerHasNonNullShapes(lyr);
  }

  function layerHasPoints(lyr) {
    return lyr.geometry_type == 'point' && layerHasNonNullShapes(lyr);
  }

  function layerHasNonNullShapes(lyr) {
    return utils.some(lyr.shapes || [], function(shp) {
      return !!shp;
    });
  }

  function deleteFeatureById(lyr, i) {
    if (lyr.shapes) lyr.shapes.splice(i, 1);
    if (lyr.data) lyr.data.getRecords().splice(i, 1);
  }

  // TODO: move elsewhere (moved here from mapshaper-point-utils to avoid circular dependency)
  function transformPointsInLayer(lyr, f) {
    if (layerHasPoints(lyr)) {
      forEachPoint(lyr.shapes, function(p) {
        var p2 = f(p[0], p[1]);
        p[0] = p2[0];
        p[1] = p2[1];
      });
    }
  }

  function getFeatureCount(lyr) {
    var count = 0;
    if (lyr.data) {
      count = lyr.data.size();
    } else if (lyr.shapes) {
      count = lyr.shapes.length;
    }
    return count;
  }

  function layerIsEmpty(lyr) {
    return getFeatureCount(lyr) == 0;
  }

  function requireDataField(obj, field, msg) {
    var data = obj.fieldExists ? obj : obj.data; // accept layer or DataTable
    if (!field) stop('Missing a field parameter');
    if (!data || !data.fieldExists(field)) {
      stop(msg || 'Missing a field named:', field);
    }
  }

  function requireDataFields(table, fields) {
    if (!fields || !fields.length) return;
    if (!table) {
      stop("Missing attribute data");
    }
    var dataFields = table.getFields(),
        missingFields = utils.difference(fields, dataFields);
    if (missingFields.length > 0) {
      stop("Table is missing one or more fields:\n",
          missingFields, "\nExisting fields:", '\n' + formatStringsAsGrid(dataFields));
    }
  }

  function layerTypeMessage(lyr, defaultMsg, customMsg) {
    var msg;
    // check that custom msg is a string (could be an index if require function is called by forEach)
    if (customMsg && utils.isString(customMsg)) {
      msg = customMsg;
    } else {
      msg = defaultMsg + ', ';
      if (!lyr || !lyr.geometry_type) {
        msg += 'received a layer with no geometry';
      } else {
        msg += 'received a ' + lyr.geometry_type + ' layer';
      }
    }
    return msg;
  }

  function requirePointLayer(lyr, msg) {
    if (!lyr || lyr.geometry_type !== 'point')
      stop(layerTypeMessage(lyr, "Expected a point layer", msg));
  }

  function requireSinglePointLayer(lyr, msg) {
    requirePointLayer(lyr);
    if (countMultiPartFeatures(lyr) > 0) {
      stop(msg || 'This command requires single points; layer contains multi-point features.');
    }
  }

  function requirePolylineLayer(lyr, msg) {
    if (!lyr || lyr.geometry_type !== 'polyline')
      stop(layerTypeMessage(lyr, "Expected a polyline layer", msg));
  }

  function requirePolygonLayer(lyr, msg) {
    if (!lyr || lyr.geometry_type !== 'polygon')
      stop(layerTypeMessage(lyr, "Expected a polygon layer", msg));
  }

  function requirePathLayer(lyr, msg) {
    if (!lyr || !layerHasPaths(lyr))
      stop(layerTypeMessage(lyr, "Expected a polygon or polyline layer", msg));
  }

  // Used by info command and gui layer menu
  function getLayerSourceFile(lyr, dataset) {
    var inputs = dataset.info && dataset.info.input_files;
    return inputs && inputs[0] || '';
  }

  // Divide a collection of features with mixed types into layers of a single type
  // (Used for importing TopoJSON and GeoJSON features)
  function divideFeaturesByType(shapes, properties, types) {
    var typeSet = utils.uniq(types);
    var layers = typeSet.map(function(geoType) {
      var p = [],
          s = [],
          dataNulls = 0,
          rec;

      for (var i=0, n=shapes.length; i<n; i++) {
        if (types[i] != geoType) continue;
        if (geoType) s.push(shapes[i]);
        rec = properties[i];
        p.push(rec);
        if (!rec) dataNulls++;
      }
      return {
        geometry_type: geoType,
        shapes: s,
        data: dataNulls < p.length ? new DataTable(p) : null
      };
    });
    return layers;
  }

  // make a stub copy if the no_replace option is given, else pass thru src layer
  function getOutputLayer(src, opts) {
    return opts && opts.no_replace ? {geometry_type: src.geometry_type} : src;
  }

  //
  function setOutputLayerName(dest, src, defName, opts) {
    opts = opts || {};
    if (opts.name) {
      dest.name = opts.name;
    } else if (opts.no_replace) {
      dest.name = defName || undefined;
    } else {
      dest.name = src && src.name || defName || undefined;
    }
  }

  // Make a deep copy of a layer
  function copyLayer(lyr) {
    var copy = copyLayerShapes(lyr);
    if (copy.data) {
      copy.data = copy.data.clone();
    }
    return copy;
  }

  // Make a shallow copy of a path layer; replace layer.shapes with an array that is
  // filtered to exclude paths containing any of the arc ids contained in arcIds.
  // arcIds: an array of (non-negative) arc ids to exclude
  function filterPathLayerByArcIds(pathLyr, arcIds) {
    var index = arcIds.reduce(function(memo, id) {
      memo[id] = true;
      return memo;
    }, {});
    // deep copy shapes; this could be optimized to only copy shapes that are modified
    var shapes = cloneShapes(pathLyr.shapes);
    editShapes(shapes, onPath); // remove paths that are missing shapes
    return utils.defaults({shapes: shapes}, pathLyr);

    function onPath(path) {
      for (var i=0; i<path.length; i++) {
        if (absArcId(path[i]) in index) {
          return null;
        }
      }
      return path;
    }
  }

  function copyLayerShapes(lyr) {
    var copy = utils.extend({}, lyr);
    if (lyr.shapes) {
      copy.shapes = cloneShapes(lyr.shapes);
    }
    return copy;
  }

  function countMultiPartFeatures(shapes) {
    var count = 0;
    for (var i=0, n=shapes.length; i<n; i++) {
      if (shapes[i] && shapes[i].length > 1) count++;
    }
    return count;
  }

  // moving this here from mapshaper-path-utils to avoid circular dependency
  function getArcPresenceTest2(layers, arcs) {
    var counts = countArcsInLayers(layers, arcs);
    return function(arcId) {
      return counts[absArcId(arcId)] > 0;
    };
  }

  // Count arcs in a collection of layers
  function countArcsInLayers(layers, arcs) {
    var counts = new Uint32Array(arcs.size());
    layers.filter(layerHasPaths).forEach(function(lyr) {
      countArcsInShapes(lyr.shapes, counts);
    });
    return counts;
  }

  // Returns a Bounds object
  function getLayerBounds(lyr, arcs) {
    var bounds = null;
    if (lyr.geometry_type == 'point') {
      bounds = getPointBounds$1(lyr.shapes);
    } else if (lyr.geometry_type == 'polygon' || lyr.geometry_type == 'polyline') {
      bounds = getPathBounds(lyr.shapes, arcs);
    } else ;
    return bounds;
  }

  function isolateLayer(layer, dataset) {
    return utils.defaults({
      layers: dataset.layers.filter(function(lyr) {return lyr == layer;})
    }, dataset);
  }

  function initDataTable(lyr) {
    lyr.data = new DataTable(getFeatureCount(lyr));
  }

  var LayerUtils = /*#__PURE__*/Object.freeze({
    __proto__: null,
    insertFieldValues: insertFieldValues,
    getLayerDataTable: getLayerDataTable,
    layerHasNonNullData: layerHasNonNullData,
    layerHasGeometry: layerHasGeometry,
    layerHasPaths: layerHasPaths,
    layerHasPoints: layerHasPoints,
    layerHasNonNullShapes: layerHasNonNullShapes,
    deleteFeatureById: deleteFeatureById,
    transformPointsInLayer: transformPointsInLayer,
    getFeatureCount: getFeatureCount,
    layerIsEmpty: layerIsEmpty,
    requireDataField: requireDataField,
    requireDataFields: requireDataFields,
    layerTypeMessage: layerTypeMessage,
    requirePointLayer: requirePointLayer,
    requireSinglePointLayer: requireSinglePointLayer,
    requirePolylineLayer: requirePolylineLayer,
    requirePolygonLayer: requirePolygonLayer,
    requirePathLayer: requirePathLayer,
    getLayerSourceFile: getLayerSourceFile,
    divideFeaturesByType: divideFeaturesByType,
    getOutputLayer: getOutputLayer,
    setOutputLayerName: setOutputLayerName,
    copyLayer: copyLayer,
    filterPathLayerByArcIds: filterPathLayerByArcIds,
    copyLayerShapes: copyLayerShapes,
    countMultiPartFeatures: countMultiPartFeatures,
    getArcPresenceTest2: getArcPresenceTest2,
    countArcsInLayers: countArcsInLayers,
    getLayerBounds: getLayerBounds,
    isolateLayer: isolateLayer,
    initDataTable: initDataTable
  });

  // A matrix class that supports affine transformations (scaling, translation, rotation).
  // Elements:
  //   a  c  tx
  //   b  d  ty
  //   0  0  1  (u v w are not used)
  //
  function Matrix2D() {
    this.a = 1;
    this.c = 0;
    this.tx = 0;
    this.b = 0;
    this.d = 1;
    this.ty = 0;
  }

  Matrix2D.prototype.transformXY = function(x, y, p) {
    p = p || {};
    p.x = x * this.a + y * this.c + this.tx;
    p.y = x * this.b + y * this.d + this.ty;
    return p;
  };

  Matrix2D.prototype.translate = function(dx, dy) {
    this.tx += dx;
    this.ty += dy;
  };

  // x, y: optional origin
  Matrix2D.prototype.rotate = function(q, x, y) {
    var cos = Math.cos(q);
    var sin = Math.sin(q);
    x = x || 0;
    y = y || 0;
    this.a = cos;
    this.c = -sin;
    this.b = sin;
    this.d = cos;
    this.tx += x - x * cos + y * sin;
    this.ty += y - x * sin - y * cos;
  };

  // cx, cy: optional origin
  Matrix2D.prototype.scale = function(sx, sy, cx, cy) {
    cx = cx || 0;
    cy = cy || 0;
    this.a *= sx;
    this.c *= sx;
    this.b *= sy;
    this.d *= sy;
    this.tx -= cx * (sx - 1);
    this.ty -= cy * (sy - 1);
  };

  var mproj$1 = require$1('mproj');

  // A compound projection, consisting of a default projection and one or more rectangular frames
  // that are projected separately and affine transformed.
  // @mainParams: parameters for main projection, including:
  //    proj: Proj string
  //    bbox: lat-lon bounding box
  function MixedProjection(mainParams, options) {
    var mainFrame = initFrame(mainParams);
    var mainP = mainFrame.crs;
    var frames = [mainFrame];
    var mixedP = initMixedProjection(mproj$1);

    // This CRS masquerades as the main projection... the version with
    // custom insets is exposed to savvy users
    mainP.__mixed_crs = mixedP;

    // required opts:
    //    origin: [lng, lat] origin of frame (unprojected)
    //    placement: [x, y] location (in projected coordinates) to shift the origin
    //    proj: Proj.4 string for projecting data within the frame
    //    bbox: Lat-long bounding box of frame area
    //
    // optional:
    //    dx: x shift (meters)
    //    dy: y shift (meters)
    //    scale: scale factor (1 = no scaling)
    //    rotation: rotation in degrees (0 = no rotation)
    //
    mainP.addFrame = function(paramsArg) {
      var params = getFrameParams(paramsArg, options); // apply defaults and overrides
      var frame = initFrame(params);
      var m = new Matrix2D();
      //  originXY: the projected coordinates of the frame origin
      var originXY = params.origin ? projectFrameOrigin(params.origin, frame.crs) : [0, 0];
      var placementXY = params.placement || [0, 0];
      var dx = placementXY[0] - originXY[0] + (+params.dx || 0);
      var dy = placementXY[1] - originXY[1] + (+params.dy || 0);

      if (params.rotation) {
        m.rotate(params.rotation * Math.PI / 180.0, originXY[0], originXY[1]);
      }
      if (params.scale) {
        m.scale(params.scale, params.scale, originXY[0], originXY[1]);
      }
      m.translate(dx, dy);

      frame.matrix = m;
      frames.push(frame);
      return this;
    };

    function initFrame(params) {
      return {
        bounds: new Bounds(bboxToRadians(params.bbox)),
        crs:  mproj$1.pj_init(params.proj)
      };
    }

    function bboxToRadians(bbox) {
      var D2R = Math.PI / 180;
      return bbox.map(function(deg) {
        return deg * D2R;
      });
    }

    function projectFrameOrigin(origin, P) {
      var xy = mproj$1.pj_fwd_deg({lam: origin[0], phi: origin[1]}, P);
      return [xy.x, xy.y];
    }

    mixedP.fwd = function(lp, xy) {
      var frame, xy2;
      for (var i=0, n=frames.length; i<n; i++) {
        frame = frames[i];
        if (frame.bounds.containsPoint(lp.lam, lp.phi)) {
          xy2 = mproj$1.pj_fwd(lp, frame.crs);
          if (frame.matrix) {
            frame.matrix.transformXY(xy2.x, xy2.y, xy2);
          }
          break;
        }
      }
      xy.x = xy2 ? xy2.x : Infinity;
      xy.y = xy2 ? xy2.y : Infinity;
    };

    return mainP;
  }

  function initMixedProjection(mproj) {
    if (!mproj.internal.pj_list.mixed) {
      mproj.pj_add(function(P) {
        P.a = 1;
      }, 'mixed', 'Mapshaper Mixed Projection');
    }
    return mproj.pj_init('+proj=mixed');
  }

  function getFrameParams (params, options) {
    var opts = options[params.name];
    utils.defaults(params, {scale: 1, dx: 0, dy: 0, rotation: 0}); // add defaults
    if (!opts) return params;
    Object.keys(opts).forEach(function(key) {
      var val = opts[key];
      if (key in params) {
        params[key] = opts[key];
      } else {
        params.proj = replaceProjParam(params.proj, key, val);
      }
    });
    return params;
  }

  function replaceProjParam(proj, key, val) {
    var param = '+' + key + '=';
    return proj.split(' ').map(function(str) {
      if (str.indexOf(param) === 0) {
        str = str.substr(0, param.length) + val;
      }
      return str;
    }).join(' ');
  }

  // str: a custom projection string, e.g.: "albersusa +PR"
  function parseCustomProjection(str) {
    var parts = str.trim().split(/ +/);
    var params = [];
    var names = parts.filter(function(part) {
      if (/^\+/.test(part)) {
        params.push(part.substr(1)); // strip '+'
        return false;
      }
      return true;
    });
    var name = names[0];
    var opts = parseCustomParams(params);
    if (names.length != 1) return null; // parse error if other than one name found
    return getCustomProjection(name, opts);
  }

  // returns a custom projection object
  function getCustomProjection(name, opts) {
    if (name == 'albersusa') {
      return new AlbersUSA(opts);
    }
    return null;
  }

  function AlbersUSA(optsArg) {
    var opts = optsArg || {};
    var main = {
      proj: '+proj=aea +lon_0=-96 +lat_0=37.5 +lat_1=29.5 +lat_2=45.5',
      bbox: [-129,23,-62,52]
    };
    var AK = {
      name: 'AK',
      proj: '+proj=aea +lat_1=55 +lat_2=70 +lat_0=65 +lon_0=-148 +x_0=0 +y_0=0',
      bbox: [-172.26,50.89,-127.00,73.21],
      origin: [-152, 63],
      placement: [-1882782,-969242],
      scale: 0.37
    };
    var HI = {
      name: 'HI',
      proj: '+proj=aea +lat_1=19 +lat_2=24 +lat_0=20.9 +lon_0=-156.5 +x_0=0 +y_0=0',
      bbox: [-160.50,18.72,-154.57,22.58],
      origin: [-157, 21],
      placement: [-1050326,-1055362]
    };
    var PR = {
      name: 'PR',
      proj: '+proj=aea +lat_1=18 +lat_2=18.43 +lat_0=17.83 +lon_0=-66.43 +x_0=0 +y_0=0',
      bbox: [-68.092,17.824,-65.151,18.787],
      origin: [-66.431, 18.228],
      placement: [1993101,-1254517]
    };
    var VI = {
      name: 'VI',
      // same projection and origin as PR, so they maintain their true geographical relationship
      proj: '+proj=aea +lat_1=18 +lat_2=18.43 +lat_0=17.83 +lon_0=-66.43 +x_0=0 +y_0=0',
      bbox: [-65.104,17.665,-64.454,18.505],
      origin: [-66.431, 18.228],
      placement: [1993101,-1254517]
    };
    var mixed = new MixedProjection(main, opts)
      .addFrame(AK)
      .addFrame(HI);
    if (opts.PR) {
      mixed.addFrame(PR);
    }
    if (opts.VI) {
      mixed.addFrame(VI);
    }
    return mixed;
  }


  function parseCustomParams(arr) {
    var opts = {};
    arr.forEach(function(str) {
      parseCustomParam(str, opts);
    });
    return opts;
  }

  function parseCustomParam(str, opts) {
    var parts = str.split('=');
    var path = parts[0].split('.');
    var key = path.pop();
    var obj = path.reduce(function(memo, name) {
      if (name in memo === false) {
        memo[name] = {};
      } else if (!utils.isObject(memo[name])) {
        return {};// error condition, could display a warning
      }
      return memo[name];
    }, opts);
    if (parts.length > 1) {
      obj[key] = parseCustomParamValue(parts[1]);
    } else if (key in obj === false && !path.length) {
      // e.g. convert string 'PR' into {PR: {}} (empty object),
      // to show PR with default properties
      obj[key] = {};
    }
  }

  function parseCustomParamValue(str) {
    var val;
    if (str.indexOf(',') > 0) {
      val = str.split(',').map(parseFloat);
      // TODO: validate
      return val;
    }
    val = utils.parseNumber(str);
    if (val === null) {
      val = str;
    }
    return val;
  }

  var CustomProjections = /*#__PURE__*/Object.freeze({
    __proto__: null,
    parseCustomProjection: parseCustomProjection,
    AlbersUSA: AlbersUSA,
    parseCustomParams: parseCustomParams
  });

  function getWorldBounds(e) {
    e = utils.isFiniteNumber(e) ? e : 1e-10;
    return [-180 + e, -90 + e, 180 - e, 90 - e];
  }

  function probablyDecimalDegreeBounds(b) {
    var world = getWorldBounds(-1), // add a bit of excess
        bbox = (b instanceof Bounds) ? b.toArray() : b;
    return geom.containsBounds(world, bbox);
  }

  function clampToWorldBounds(b) {
    var bbox = (b instanceof Bounds) ? b.toArray() : b;
    return new Bounds().setBounds(Math.max(bbox[0], -180), Math.max(bbox[1], -90),
        Math.min(bbox[2], 180), Math.min(bbox[3], 90));
  }

  function getAntimeridian(lon0) {
    var anti = lon0 - 180;
    while (anti <= -180) anti += 360;
    return anti;
  }

  var LatLon = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getWorldBounds: getWorldBounds,
    probablyDecimalDegreeBounds: probablyDecimalDegreeBounds,
    clampToWorldBounds: clampToWorldBounds,
    getAntimeridian: getAntimeridian
  });

  var mproj = require$1('mproj');

  var asyncLoader = null;

  var projectionAliases = {
    robinson: '+proj=robin +datum=WGS84',
    webmercator: '+proj=merc +a=6378137 +b=6378137',
    wgs84: '+proj=longlat +datum=WGS84',
    albersusa: AlbersUSA
  };

  // This stub is replaced when loaded in GUI, which may need to load some files
  function initProjLibrary(opts, done) {
    if (!asyncLoader) return done();
    asyncLoader(opts, done);
  }

  function setProjectionLoader(loader) {
    asyncLoader = loader;
  }

  // Find Proj.4 definition file names in strings like "+init=epsg:3000"
  // (Used by GUI, defined here for testing)
  function findProjLibs(str) {
    var matches = str.match(/\b(esri|epsg|nad83|nad27)(?=:[0-9]+\b)/ig) || [];
    return utils.uniq(matches.map(function(str) {return str.toLowerCase();}));
  }

  // Returns a function for reprojecting [x, y] points; function throws an error
  // if the transformation fails
  // src, dest: proj4 objects
  function getProjTransform(src, dest) {
    var clampSrc = isLatLngCRS(src);
    dest = dest.__mixed_crs || dest;
    return function(x, y) {
      var xy;
      if (clampSrc) {
        // snap lng to bounds
        if (x < -180) x = -180;
        else if (x > 180) x = 180;
      }
      xy = [x, y];
      mproj.pj_transform_point(src, dest, xy);
      return xy;
    };
  }

  // Same as getProjTransform(), but return null if projection fails
  // (also faster)
  function getProjTransform2(src, dest) {
    var xx = [0],
        yy = [0],
        preK = src.is_latlong ? mproj.internal.DEG_TO_RAD : 1,
        postK = dest.is_latlong ? mproj.internal.RAD_TO_DEG : 1,
        clampSrc = isLatLngCRS(src);

    return function(x, y) {
      var fail;
      if (clampSrc) {
        // snap lng to bounds
        if (x < -180) x = -180;
        else if (x > 180) x = 180;
      }
      xx[0] = x * preK;
      yy[0] = y * preK;
      try {
        dest = dest.__mixed_crs || dest;
        mproj.pj_transform(src, dest, xx, yy);
        fail = xx[0] == Infinity; // mproj invalid coord value
      } catch(e) {
        fail = true;
      }
      return fail ? null : [xx[0] * postK, yy[0] * postK];
    };
  }

  function toLngLat(xy, P) {
    var proj;
    if (isLatLngCRS(P)) {
      return xy.concat();
    }
    proj = getProjTransform(P, parseCrsString('wgs84'));
    return proj(xy[0], xy[1]);
  }

  function getProjInfo(dataset) {
    var P, info;
    try {
      P = getDatasetCRS(dataset);
      if (P) {
        info = crsToProj4(P);
      }
    } catch(e) {}
    return info || "[unknown]";
  }

  function crsToProj4(P) {
    return mproj.internal.get_proj_defn(P);
  }

  function crsToPrj(P) {
    var wkt;
    try {
      wkt = mproj.internal.wkt_from_proj4(P);
    } catch(e) {
      // console.log(e)
    }
    return wkt;
  }

  function crsAreEqual(a, b) {
    var str = crsToProj4(a);
    return !!str && str == crsToProj4(b);
  }

  function isProjAlias(str) {
    return str in projectionAliases;
  }

  function getProjDefn(str) {
    var defn;
    // prepend '+proj=' to bare proj names
    str = str.replace(/(^| )([\w]+)($| )/, function(a, b, c, d) {
      if (c in mproj.internal.pj_list) {
        return b + '+proj=' + c + d;
      }
      return a;
    });
    if (looksLikeProj4String(str)) {
      defn = str;
    } else if (isProjAlias(str)) {
      defn = projectionAliases[str];
      if (utils.isFunction(defn)) {
        defn = defn();
      }
    } else if (looksLikeInitString(str)) {
      defn = '+init=' + str.toLowerCase();
    } else if (str in (getStashedVar('defs') || {})) {
      // a proj4 alias could be dynamically created in a -calc expression
      defn = getStashedVar('defs')[str];
    } else {
      defn = parseCustomProjection(str);
    }
    if (!defn) {
      stop("Unknown projection definition:", str);
    }
    return defn;
  }

  function looksLikeInitString(str) {
    return /^(esri|epsg|nad83|nad27):[0-9]+$/i.test(String(str));
  }

  function looksLikeProj4String(str) {
    return /^(\+[^ ]+ *)+$/.test(str);
  }

  function getCrsInfo(str) {
    return {
      crs_string: str,
      crs: parseCrsString(str)
    };
  }

  function parseCrsString(str) {
    var defn = getProjDefn(str);  // defn is a string or a Proj object
    var P;
    if (!utils.isString(defn)) {
      P = defn;
    } else {
      try {
        P = mproj.pj_init(defn);
      } catch(e) {
        stop('Unable to use projection', defn, '(' + e.message + ')');
      }
    }
    return P || null;
  }

  function requireProjectedDataset(dataset) {
    if (isLatLngCRS(getDatasetCRS(dataset))) {
      stop("Command requires a target with projected coordinates (not lat-long)");
    }
  }

  // @info: info property of source dataset (instead of crs object, so wkt string
  //        can be preserved if present)
  function setDatasetCrsInfo(dataset, info) {
    dataset.info = dataset.info || {};
    // Assumes that proj4 object is never mutated.
    // TODO: assign a copy of crs (if present)
    dataset.info.crs = info.crs;
    dataset.info.prj = info.prj;
    dataset.info.crs_string = info.crs_string;
    return dataset;
  }

  function getDatasetCrsInfo(dataset) {
    var info = dataset.info || {},
        P = info.crs,
        str = info.crs_string;
    if (!P && info.prj) {
      P = parseCrsString(translatePrj(info.prj));
    }
    if (!P && probablyDecimalDegreeBounds(getDatasetBounds(dataset))) {
      // use wgs84 for probable latlong datasets with unknown datums
      str = 'wgs84';
      P = parseCrsString(str);
    }
    return {
      crs: P || null,
      crs_string: str,
      prj: info.prj
    };
  }

  function getDatasetCRS(dataset) {
    return getDatasetCrsInfo(dataset).crs;
  }

  function requireDatasetsHaveCompatibleCRS(arr) {
    arr.reduce(function(memo, dataset) {
      var P = getDatasetCRS(dataset);
      if (memo && P) {
        if (isLatLngCRS(memo) != isLatLngCRS(P)) {
          stop("Unable to combine projected and unprojected datasets");
        }
      }
      return P || memo;
    }, null);
  }

  // Assumes conformal projections; consider returning average of vertical and
  // horizontal scale factors.
  // x, y: a point location in projected coordinates
  // Returns k, the ratio of coordinate distance to distance on the ground
  function getScaleFactorAtXY(x, y, crs) {
    var dist = 1;
    var lp = mproj.pj_inv_deg({x: x, y: y}, crs);
    var lp2 = mproj.pj_inv_deg({x: x + dist, y: y}, crs);
    var k = dist / geom.greatCircleDistance(lp.lam, lp.phi, lp2.lam, lp2.phi);
    return k;
  }

  function isProjectedCRS(P) {
    return !isLatLngCRS(P);
  }

  function isInvertibleCRS(P) {
    if (!P || !P.inv) return false;
    return true;
  }

  function isLatLngCRS(P) {
    return P && P.is_latlong || false;
  }

  function isWGS84(P) {
    if (!isLatLngCRS(P)) return false;
    var proj4 = crsToProj4(P);
    return proj4.toLowerCase().includes('84');
  }

  function isWebMercator(P) {
    if (!P) return false;
    var str = crsToProj4(P);
    // e.g. +proj=merc +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +wktext +a=6378137 +b=6378137 +nadgrids=@null
    // e.g. +proj=merc +a=6378137 +b=6378137
    // TODO: support  https://proj.org/operations/projections/webmerc.html
    return str.includes('+proj=merc') && str.includes('+a=6378137') && str.includes('+b=6378137');
  }

  function isLatLngDataset(dataset) {
    return isLatLngCRS(getDatasetCRS(dataset));
  }

  function printProjections() {
    var index = mproj.internal.pj_list;
    var msg = 'Proj4 projections\n';
    Object.keys(index).sort().forEach(function(id) {
      msg += '  ' + utils.rpad(id, 7, ' ') + '  ' + index[id].name + '\n';
    });
    msg += '\nAliases';
    Object.keys(projectionAliases).sort().forEach(function(n) {
      msg += '\n  ' + n;
    });
    print(msg);
  }

  function translatePrj(str) {
    var proj4;
    try {
      proj4 = mproj.internal.wkt_to_proj4(str);
    } catch(e) {
      stop('Unusable .prj file (' + e.message + ')');
    }
    return proj4;
  }

  // Convert contents of a .prj file to a projection object
  function parsePrj(str) {
    return parseCrsString(translatePrj(str));
  }

  var Projections = /*#__PURE__*/Object.freeze({
    __proto__: null,
    initProjLibrary: initProjLibrary,
    setProjectionLoader: setProjectionLoader,
    findProjLibs: findProjLibs,
    getProjTransform: getProjTransform,
    getProjTransform2: getProjTransform2,
    toLngLat: toLngLat,
    getProjInfo: getProjInfo,
    crsToProj4: crsToProj4,
    crsToPrj: crsToPrj,
    crsAreEqual: crsAreEqual,
    isProjAlias: isProjAlias,
    getProjDefn: getProjDefn,
    looksLikeProj4String: looksLikeProj4String,
    getCrsInfo: getCrsInfo,
    parseCrsString: parseCrsString,
    requireProjectedDataset: requireProjectedDataset,
    setDatasetCrsInfo: setDatasetCrsInfo,
    getDatasetCrsInfo: getDatasetCrsInfo,
    getDatasetCRS: getDatasetCRS,
    requireDatasetsHaveCompatibleCRS: requireDatasetsHaveCompatibleCRS,
    getScaleFactorAtXY: getScaleFactorAtXY,
    isProjectedCRS: isProjectedCRS,
    isInvertibleCRS: isInvertibleCRS,
    isLatLngCRS: isLatLngCRS,
    isWGS84: isWGS84,
    isWebMercator: isWebMercator,
    isLatLngDataset: isLatLngDataset,
    printProjections: printProjections,
    translatePrj: translatePrj,
    parsePrj: parsePrj
  });

  // Coordinate iterators
  //
  // Interface:
  //   properties: x, y
  //   method: hasNext()
  //
  // Usage:
  //   while (iter.hasNext()) {
  //     iter.x, iter.y; // do something w/ x & y
  //   }

  // Iterate over an array of [x, y] points
  //
  function PointIter(points) {
    var n = points.length,
        i = 0,
        iter = {
          x: 0,
          y: 0,
          hasNext: hasNext
        };
    function hasNext() {
      if (i >= n) return false;
      iter.x = points[i][0];
      iter.y = points[i][1];
      i++;
      return true;
    }
    return iter;
  }


  // Constructor takes arrays of coords: xx, yy, zz (optional)
  //
  function ArcIter(xx, yy) {
    this._i = 0;
    this._n = 0;
    this._inc = 1;
    this._xx = xx;
    this._yy = yy;
    this.i = 0;
    this.x = 0;
    this.y = 0;
  }

  ArcIter.prototype.init = function(i, len, fw) {
    if (fw) {
      this._i = i;
      this._inc = 1;
    } else {
      this._i = i + len - 1;
      this._inc = -1;
    }
    this._n = len;
    return this;
  };

  ArcIter.prototype.hasNext = function() {
    var i = this._i;
    if (this._n > 0) {
      this._i = i + this._inc;
      this.x = this._xx[i];
      this.y = this._yy[i];
      this.i = i;
      this._n--;
      return true;
    }
    return false;
  };

  function FilteredArcIter(xx, yy, zz) {
    var _zlim = 0,
        _i = 0,
        _inc = 1,
        _stop = 0;

    this.init = function(i, len, fw, zlim) {
      _zlim = zlim || 0;
      if (fw) {
        _i = i;
        _inc = 1;
        _stop = i + len;
      } else {
        _i = i + len - 1;
        _inc = -1;
        _stop = i - 1;
      }
      return this;
    };

    this.hasNext = function() {
      // using local vars is significantly faster when skipping many points
      var zarr = zz,
          i = _i,
          j = i,
          zlim = _zlim,
          stop = _stop,
          inc = _inc;
      if (i == stop) return false;
      do {
        j += inc;
      } while (j != stop && zarr[j] < zlim);
      _i = j;
      this.x = xx[i];
      this.y = yy[i];
      this.i = i;
      return true;
    };
  }

  function MultiShapeIter(arcs) {
    new ShapeIter(arcs);

  }

  // Iterate along a path made up of one or more arcs.
  //
  function ShapeIter(arcs) {
    this._arcs = arcs;
    this._i = 0;
    this._n = 0;
    this.x = 0;
    this.y = 0;
    // this.i = -1;
  }

  ShapeIter.prototype.hasNext = function() {
    var arc = this._arc;
    if (this._i < this._n === false) {
      return false;
    }
    if (arc.hasNext()) {
      this.x = arc.x;
      this.y = arc.y;
      // this.i = arc.i;
      return true;
    }
    this.nextArc();
    return this.hasNext();
  };

  ShapeIter.prototype.init = function(ids) {
    this._ids = ids;
    this._n = ids.length;
    this.reset();
    return this;
  };

  ShapeIter.prototype.nextArc = function() {
    var i = this._i + 1;
    if (i < this._n) {
      this._arc = this._arcs.getArcIter(this._ids[i]);
      if (i > 0) this._arc.hasNext(); // skip first point
    }
    this._i = i;
  };

  ShapeIter.prototype.reset = function() {
    this._i = -1;
    this.nextArc();
  };

  var ShapeIter$1 = /*#__PURE__*/Object.freeze({
    __proto__: null,
    PointIter: PointIter,
    ArcIter: ArcIter,
    FilteredArcIter: FilteredArcIter,
    MultiShapeIter: MultiShapeIter,
    ShapeIter: ShapeIter
  });

  // Returns a function for converting simplification ratio [0-1] to an interval value.
  // If the dataset is large, the value is an approximation (for speed while using slider)
  function getThresholdFunction(arcs) {
    var size = arcs.getPointCount(),
        nth = Math.ceil(size / 5e5),
        sortedThresholds = arcs.getRemovableThresholds(nth);
        // Sort simplification thresholds for all non-endpoint vertices
        // for quick conversion of simplification percentage to threshold value.
        // For large datasets, use every nth point, for faster sorting.
        // utils.quicksort(sortedThresholds, false); // descending
        utils.quicksort(sortedThresholds, true); // ascending

    return function(pct) {
      var n = sortedThresholds.length;
      var rank = retainedPctToRank(pct, sortedThresholds.length);
      if (rank < 1) return 0;
      if (rank > n) return Infinity;
      return sortedThresholds[rank-1];
    };
  }

  // Return integer rank of n (1-indexed) or 0 if pct <= 0 or n+1 if pct >= 1
  function retainedPctToRank(pct, n) {
    var rank;
    if (n === 0 || pct >= 1) {
      rank = 0;
    } else if (pct <= 0) {
      rank = n + 1;
    } else {
      rank = Math.floor((1 - pct) * (n + 2));
    }
    return rank;
  }

  // nth (optional): sample every nth threshold (use estimate for speed)
  function getThresholdByPct(pct, arcs, nth) {
    var tmp = arcs.getRemovableThresholds(nth),
        rank = retainedPctToRank(pct, tmp.length);
    if (rank < 1) return 0;
    if (rank > tmp.length) return Infinity;
    return utils.findValueByRank(tmp, rank);
  }

  var SimplifyPct = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getThresholdFunction: getThresholdFunction,
    getThresholdByPct: getThresholdByPct
  });

  // An interface for managing a collection of paths.
  // Constructor signatures:
  //
  // ArcCollection(arcs)
  //    arcs is an array of polyline arcs; each arc is an array of points: [[x0, y0], [x1, y1], ... ]
  //
  // ArcCollection(nn, xx, yy)
  //    nn is an array of arc lengths; xx, yy are arrays of concatenated coords;
  function ArcCollection() {
    var _xx, _yy,  // coordinates data
        _ii, _nn,  // indexes, sizes
        _zz, _zlimit = 0, // simplification
        _bb, _allBounds, // bounding boxes
        _arcIter, _filteredArcIter; // path iterators

    if (arguments.length == 1) {
      initLegacyArcs(arguments[0]);  // want to phase this out
    } else if (arguments.length == 3) {
      initXYData.apply(this, arguments);
    } else {
      error("ArcCollection() Invalid arguments");
    }

    function initLegacyArcs(arcs) {
      var xx = [], yy = [];
      var nn = arcs.map(function(points) {
        var n = points ? points.length : 0;
        for (var i=0; i<n; i++) {
          xx.push(points[i][0]);
          yy.push(points[i][1]);
        }
        return n;
      });
      initXYData(nn, xx, yy);
    }

    function initXYData(nn, xx, yy) {
      var size = nn.length;
      if (nn instanceof Array) nn = new Uint32Array(nn);
      if (xx instanceof Array) xx = new Float64Array(xx);
      if (yy instanceof Array) yy = new Float64Array(yy);
      _xx = xx;
      _yy = yy;
      _nn = nn;
      _zz = null;
      _zlimit = 0;
      _filteredArcIter = null;

      // generate array of starting idxs of each arc
      _ii = new Uint32Array(size);
      for (var idx = 0, j=0; j<size; j++) {
        _ii[j] = idx;
        idx += nn[j];
      }

      if (idx != _xx.length || _xx.length != _yy.length) {
        error("ArcCollection#initXYData() Counting error");
      }

      initBounds();
      // Pre-allocate some path iterators for repeated use.
      _arcIter = new ArcIter(_xx, _yy);
      return this;
    }

    function initZData(zz) {
      if (!zz) {
        _zz = null;
        _zlimit = 0;
        _filteredArcIter = null;
      } else {
        if (zz.length != _xx.length) error("ArcCollection#initZData() mismatched arrays");
        if (zz instanceof Array) zz = new Float64Array(zz);
        _zz = zz;
        _filteredArcIter = new FilteredArcIter(_xx, _yy, _zz);
      }
    }

    function initBounds() {
      var data = calcArcBounds2(_xx, _yy, _nn);
      _bb = data.bb;
      _allBounds = data.bounds;
    }

    function calcArcBounds2(xx, yy, nn) {
      var numArcs = nn.length,
          bb = new Float64Array(numArcs * 4),
          bounds = new Bounds(),
          arcOffs = 0,
          arcLen,
          j, b;
      for (var i=0; i<numArcs; i++) {
        arcLen = nn[i];
        if (arcLen > 0) {
          j = i * 4;
          b = calcArcBounds(xx, yy, arcOffs, arcLen);
          bb[j++] = b[0];
          bb[j++] = b[1];
          bb[j++] = b[2];
          bb[j] = b[3];
          arcOffs += arcLen;
          bounds.mergeBounds(b);
        }
      }
      return {
        bb: bb,
        bounds: bounds
      };
    }

    this.updateVertexData = function(nn, xx, yy, zz) {
      initXYData(nn, xx, yy);
      initZData(zz || null);
    };

    // Give access to raw data arrays...
    this.getVertexData = function() {
      return {
        xx: _xx,
        yy: _yy,
        zz: _zz,
        bb: _bb,
        nn: _nn,
        ii: _ii
      };
    };

    this.getCopy = function() {
      var copy = new ArcCollection(new Int32Array(_nn), new Float64Array(_xx),
          new Float64Array(_yy));
      if (_zz) {
        copy.setThresholds(new Float64Array(_zz));
        copy.setRetainedInterval(_zlimit);
      }
      return copy;
    };

    function getFilteredPointCount() {
      var zz = _zz, z = _zlimit;
      if (!zz || !z) return this.getPointCount();
      var count = 0;
      for (var i=0, n = zz.length; i<n; i++) {
        if (zz[i] >= z) count++;
      }
      return count;
    }

    function getFilteredVertexData() {
      var len2 = getFilteredPointCount();
      var arcCount = _nn.length;
      var xx2 = new Float64Array(len2),
          yy2 = new Float64Array(len2),
          zz2 = new Float64Array(len2),
          nn2 = new Int32Array(arcCount),
          i=0, i2 = 0,
          n, n2;

      for (var arcId=0; arcId < arcCount; arcId++) {
        n2 = 0;
        n = _nn[arcId];
        for (var end = i+n; i < end; i++) {
          if (_zz[i] >= _zlimit) {
            xx2[i2] = _xx[i];
            yy2[i2] = _yy[i];
            zz2[i2] = _zz[i];
            i2++;
            n2++;
          }
        }
        if (n2 == 1) {
          error("Collapsed arc");
          // This should not happen (endpoints should be z == Infinity)
          // Could handle like this, instead of throwing an error:
          // n2 = 0;
          // xx2.pop();
          // yy2.pop();
          // zz2.pop();
        }
        nn2[arcId] = n2;
      }
      return {
        xx: xx2,
        yy: yy2,
        zz: zz2,
        nn: nn2
      };
    }

    this.getFilteredCopy = function() {
      if (!_zz || _zlimit === 0) return this.getCopy();
      var data = getFilteredVertexData();
      var copy = new ArcCollection(data.nn, data.xx, data.yy);
      copy.setThresholds(data.zz);
      return copy;
    };

    // Return arcs as arrays of [x, y] points (intended for testing).
    this.toArray = function() {
      var arr = [];
      this.forEach(function(iter) {
        var arc = [];
        while (iter.hasNext()) {
          arc.push([iter.x, iter.y]);
        }
        arr.push(arc);
      });
      return arr;
    };

    this.toJSON = function() {
      return this.toArray();
    };

    // @cb function(i, j, xx, yy)
    this.forEachArcSegment = function(arcId, cb) {
      var fw = arcId >= 0,
          absId = fw ? arcId : ~arcId,
          zlim = this.getRetainedInterval(),
          n = _nn[absId],
          step = fw ? 1 : -1,
          v1 = fw ? _ii[absId] : _ii[absId] + n - 1,
          v2 = v1,
          xx = _xx, yy = _yy, zz = _zz,
          count = 0;

      for (var j = 1; j < n; j++) {
        v2 += step;
        if (zlim === 0 || zz[v2] >= zlim) {
          cb(v1, v2, xx, yy);
          v1 = v2;
          count++;
        }
      }
      return count;
    };

    // @cb function(i, j, xx, yy)
    this.forEachSegment = function(cb) {
      var count = 0;
      for (var i=0, n=this.size(); i<n; i++) {
        count += this.forEachArcSegment(i, cb);
      }
      return count;
    };

    this.transformPoints = function(f) {
      var xx = _xx, yy = _yy, arcId = -1, n = 0, p;
      for (var i=0, len=xx.length; i<len; i++, n--) {
        while (n === 0) {
          n = _nn[++arcId];
        }
        p = f(xx[i], yy[i], arcId);
        if (p) {
          xx[i] = p[0];
          yy[i] = p[1];
        }
      }
      initBounds();
    };

    // Return an ArcIter object for each path in the dataset
    //
    this.forEach = function(cb) {
      for (var i=0, n=this.size(); i<n; i++) {
        cb(this.getArcIter(i), i);
      }
    };

    // Iterate over arcs with access to low-level data
    //
    this.forEach2 = function(cb) {
      for (var arcId=0, n=this.size(); arcId<n; arcId++) {
        cb(_ii[arcId], _nn[arcId], _xx, _yy, _zz, arcId);
      }
    };

    this.forEach3 = function(cb) {
      var start, end, xx, yy, zz;
      for (var arcId=0, n=this.size(); arcId<n; arcId++) {
        start = _ii[arcId];
        end = start + _nn[arcId];
        xx = _xx.subarray(start, end);
        yy = _yy.subarray(start, end);
        if (_zz) zz = _zz.subarray(start, end);
        cb(xx, yy, zz, arcId);
      }
    };

    // Remove arcs that don't pass a filter test and re-index arcs
    // Return array mapping original arc ids to re-indexed ids. If arr[n] == -1
    // then arc n was removed. arr[n] == m indicates that the arc at n was
    // moved to index m.
    // Return null if no arcs were re-indexed (and no arcs were removed)
    //
    this.filter = function(cb) {
      var test = function(i) {
        return cb(this.getArcIter(i), i);
      }.bind(this);
      return this.deleteArcs(test);
    };

    this.deleteArcs = function(test) {
      var n = this.size(),
          map = new Int32Array(n),
          goodArcs = 0,
          goodPoints = 0;
      for (var i=0; i<n; i++) {
        if (test(i)) {
          map[i] = goodArcs++;
          goodPoints += _nn[i];
        } else {
          map[i] = -1;
        }
      }
      if (goodArcs < n) {
        condenseArcs(map);
      }
      return map;
    };

    function condenseArcs(map) {
      var goodPoints = 0,
          goodArcs = 0,
          copyElements = utils.copyElements,
          k, arcLen;
      for (var i=0, n=map.length; i<n; i++) {
        k = map[i];
        arcLen = _nn[i];
        if (k > -1) {
          copyElements(_xx, _ii[i], _xx, goodPoints, arcLen);
          copyElements(_yy, _ii[i], _yy, goodPoints, arcLen);
          if (_zz) copyElements(_zz, _ii[i], _zz, goodPoints, arcLen);
          _nn[k] = arcLen;
          goodPoints += arcLen;
          goodArcs++;
        }
      }

      initXYData(_nn.subarray(0, goodArcs), _xx.subarray(0, goodPoints),
          _yy.subarray(0, goodPoints));
      if (_zz) initZData(_zz.subarray(0, goodPoints));
    }

    this.dedupCoords = function() {
      var arcId = 0, i = 0, i2 = 0,
          arcCount = this.size(),
          zz = _zz,
          arcLen, arcLen2;
      while (arcId < arcCount) {
        arcLen = _nn[arcId];
        arcLen2 = dedupArcCoords(i, i2, arcLen, _xx, _yy, zz);
        _nn[arcId] = arcLen2;
        i += arcLen;
        i2 += arcLen2;
        arcId++;
      }
      if (i > i2) {
        initXYData(_nn, _xx.subarray(0, i2), _yy.subarray(0, i2));
        if (zz) initZData(zz.subarray(0, i2));
      }
      return i - i2;
    };

    this.getVertex = function(arcId, nth) {
      var i = this.indexOfVertex(arcId, nth);
      return {
        x: _xx[i],
        y: _yy[i]
      };
    };

    this.getVertex2 = function(i) {
      return [_xx[i], _yy[i]];
    };

    // @nth: index of vertex. ~(idx) starts from the opposite endpoint
    this.indexOfVertex = function(arcId, nth) {
      var absId = arcId < 0 ? ~arcId : arcId,
          len = _nn[absId];
      if (nth < 0) nth = len + nth;
      if (absId != arcId) nth = len - nth - 1;
      if (nth < 0 || nth >= len) {
        error("[ArcCollection] out-of-range vertex id");
      }
      return _ii[absId] + nth;
    };

    // Tests if arc endpoints have same x, y coords
    // (arc may still have collapsed);
    this.arcIsClosed = function(arcId) {
      var i = this.indexOfVertex(arcId, 0),
          j = this.indexOfVertex(arcId, -1);
      return i != j && _xx[i] == _xx[j] && _yy[i] == _yy[j];
    };

    // Tests if first and last segments mirror each other
    // A 3-vertex arc with same endpoints tests true
    this.arcIsLollipop = function(arcId) {
      var len = this.getArcLength(arcId),
          i, j;
      if (len <= 2 || !this.arcIsClosed(arcId)) return false;
      i = this.indexOfVertex(arcId, 1);
      j = this.indexOfVertex(arcId, -2);
      return _xx[i] == _xx[j] && _yy[i] == _yy[j];
    };

    this.arcIsDegenerate = function(arcId) {
      var iter = this.getArcIter(arcId);
      var i = 0,
          x, y;
      while (iter.hasNext()) {
        if (i > 0) {
          if (x != iter.x || y != iter.y) return false;
        }
        x = iter.x;
        y = iter.y;
        i++;
      }
      return true;
    };

    this.getArcLength = function(arcId) {
      return _nn[absArcId(arcId)];
    };

    this.getArcIter = function(arcId) {
      var fw = arcId >= 0,
          i = fw ? arcId : ~arcId,
          iter = _zz && _zlimit ? _filteredArcIter : _arcIter;
      if (i >= _nn.length) {
        error("#getArcId() out-of-range arc id:", arcId);
      }
      return iter.init(_ii[i], _nn[i], fw, _zlimit);
    };

    this.getShapeIter = function(ids) {
      return new ShapeIter(this).init(ids);
    };

    // Add simplification data to the dataset
    // @thresholds is either a single typed array or an array of arrays of removal thresholds for each arc;
    //
    this.setThresholds = function(thresholds) {
      var n = this.getPointCount(),
          zz = null;
      if (!thresholds) ; else if (thresholds.length == n) {
        zz = thresholds;
      } else if (thresholds.length == this.size()) {
        zz = flattenThresholds(thresholds, n);
      } else {
        error("Invalid threshold data");
      }
      initZData(zz);
      return this;
    };

    function flattenThresholds(arr, n) {
      var zz = new Float64Array(n),
          i = 0;
      arr.forEach(function(arr) {
        for (var j=0, n=arr.length; j<n; i++, j++) {
          zz[i] = arr[j];
        }
      });
      if (i != n) error("Mismatched thresholds");
      return zz;
    }

    // bake in current simplification level, if any
    this.flatten = function() {
      if (_zlimit > 0) {
        var data = getFilteredVertexData();
        this.updateVertexData(data.nn, data.xx, data.yy);
        _zlimit = 0;
      } else {
        _zz = null;
      }
    };

    this.isFlat = function() { return !_zz; };

    this.getRetainedInterval = function() {
      return _zlimit;
    };

    this.setRetainedInterval = function(z) {
      _zlimit = z;
      return this;
    };

    this.getRetainedPct = function() {
      return this.getPctByThreshold(_zlimit);
    };

    this.setRetainedPct = function(pct) {
      if (pct >= 1) {
        _zlimit = 0;
      } else {
        _zlimit = this.getThresholdByPct(pct);
        _zlimit = clampIntervalByPct(_zlimit, pct);
      }
      return this;
    };

    // Return array of z-values that can be removed for simplification
    //
    this.getRemovableThresholds = function(nth) {
      if (!_zz) error("[arcs] Missing simplification data.");
      var skip = nth | 1,
          arr = new Float64Array(Math.ceil(_zz.length / skip)),
          z;
      for (var i=0, j=0, n=this.getPointCount(); i<n; i+=skip) {
        z = _zz[i];
        if (z != Infinity) {
          arr[j++] = z;
        }
      }
      return arr.subarray(0, j);
    };

    this.getArcThresholds = function(arcId) {
      if (!(arcId >= 0 && arcId < this.size())) {
        error("[arcs] Invalid arc id:", arcId);
      }
      var start = _ii[arcId],
          end = start + _nn[arcId];
      return _zz.subarray(start, end);
    };

    // nth (optional): sample every nth threshold (use estimate for speed)
    this.getPctByThreshold = function(val, nth) {
      var arr, rank, pct;
      if (val > 0) {
        arr = this.getRemovableThresholds(nth);
        rank = utils.findRankByValue(arr, val);
        pct = arr.length > 0 ? 1 - (rank - 1) / arr.length : 1;
      } else {
        pct = 1;
      }
      return pct;
    };

    // nth (optional): sample every nth threshold (use estimate for speed)
    this.getThresholdByPct = function(pct, nth) {
      return getThresholdByPct(pct, this, nth);
    };

    this.arcIntersectsBBox = function(i, b1) {
      var b2 = _bb,
          j = i * 4;
      return b2[j] <= b1[2] && b2[j+2] >= b1[0] && b2[j+3] >= b1[1] && b2[j+1] <= b1[3];
    };

    this.arcIsContained = function(i, b1) {
      var b2 = _bb,
          j = i * 4;
      return b2[j] >= b1[0] && b2[j+2] <= b1[2] && b2[j+1] >= b1[1] && b2[j+3] <= b1[3];
    };

    this.arcIsSmaller = function(i, units) {
      var bb = _bb,
          j = i * 4;
      return bb[j+2] - bb[j] < units && bb[j+3] - bb[j+1] < units;
    };

    // TODO: allow datasets in lat-lng coord range to be flagged as planar
    this.isPlanar = function() {
      return !probablyDecimalDegreeBounds(this.getBounds());
    };

    this.size = function() {
      return _ii && _ii.length || 0;
    };

    this.getPointCount = function() {
      return _xx && _xx.length || 0;
    };

    this.getFilteredPointCount = getFilteredPointCount;

    this.getBounds = function() {
      return _allBounds.clone();
    };

    this.getSimpleShapeBounds = function(arcIds, bounds) {
      bounds = bounds || new Bounds();
      for (var i=0, n=arcIds.length; i<n; i++) {
        this.mergeArcBounds(arcIds[i], bounds);
      }
      return bounds;
    };

    this.getSimpleShapeBounds2 = function(arcIds, arr) {
      var bbox = arr || [],
          bb = _bb,
          id = absArcId(arcIds[0]) * 4;
      bbox[0] = bb[id];
      bbox[1] = bb[++id];
      bbox[2] = bb[++id];
      bbox[3] = bb[++id];
      for (var i=1, n=arcIds.length; i<n; i++) {
        id = absArcId(arcIds[i]) * 4;
        if (bb[id] < bbox[0]) bbox[0] = bb[id];
        if (bb[++id] < bbox[1]) bbox[1] = bb[id];
        if (bb[++id] > bbox[2]) bbox[2] = bb[id];
        if (bb[++id] > bbox[3]) bbox[3] = bb[id];
      }
      return bbox;
    };

    // TODO: move this and similar methods out of ArcCollection
    this.getMultiShapeBounds = function(shapeIds, bounds) {
      bounds = bounds || new Bounds();
      if (shapeIds) { // handle null shapes
        for (var i=0, n=shapeIds.length; i<n; i++) {
          this.getSimpleShapeBounds(shapeIds[i], bounds);
        }
      }
      return bounds;
    };

    this.mergeArcBounds = function(arcId, bounds) {
      if (arcId < 0) arcId = ~arcId;
      var offs = arcId * 4;
      bounds.mergeBounds(_bb[offs], _bb[offs+1], _bb[offs+2], _bb[offs+3]);
    };
  }

  // Remove duplicate coords and NaNs
  function dedupArcCoords(src, dest, arcLen, xx, yy, zz) {
    var n = 0, n2 = 0; // counters
    var x, y, i, j, keep;
    while (n < arcLen) {
      j = src + n;
      x = xx[j];
      y = yy[j];
      keep = x == x && y == y && (n2 === 0 || x != xx[j-1] || y != yy[j-1]);
      if (keep) {
        i = dest + n2;
        xx[i] = x;
        yy[i] = y;
        n2++;
      }
      if (zz && n2 > 0 && (keep || zz[j] > zz[i])) {
        zz[i] = zz[j];
      }
      n++;
    }
    return n2 > 1 ? n2 : 0;
  }

  // Get function to Hash an x, y point to a non-negative integer
  function getXYHash(size) {
    var buf = new ArrayBuffer(16),
        floats = new Float64Array(buf),
        uints = new Uint32Array(buf),
        lim = size | 0;
    if (lim > 0 === false) {
      throw new Error("Invalid size param: " + size);
    }

    return function(x, y) {
      var u = uints, h;
      floats[0] = x;
      floats[1] = y;
      h = u[0] ^ u[1];
      h = h << 5 ^ h >> 7 ^ u[2] ^ u[3];
      return (h & 0x7fffffff) % lim;
    };
  }

  // Used for building topology
  //
  function ArcIndex(pointCount) {
    var hashTableSize = Math.floor(pointCount * 0.25 + 1),
        hash = getXYHash(hashTableSize),
        hashTable = new Int32Array(hashTableSize),
        chainIds = [],
        arcs = [],
        arcPoints = 0;

    utils.initializeArray(hashTable, -1);

    this.addArc = function(xx, yy) {
      var end = xx.length - 1,
          key = hash(xx[end], yy[end]),
          chainId = hashTable[key],
          arcId = arcs.length;
      hashTable[key] = arcId;
      arcs.push([xx, yy]);
      arcPoints += xx.length;
      chainIds.push(chainId);
      return arcId;
    };

    // Look for a previously generated arc with the same sequence of coords, but in the
    // opposite direction. (This program uses the convention of CW for space-enclosing rings, CCW for holes,
    // so coincident boundaries should contain the same points in reverse sequence).
    //
    this.findDuplicateArc = function(xx, yy, start, end, getNext, getPrev) {
      // First, look for a reverse match
      var arcId = findArcNeighbor(xx, yy, start, end, getNext);
      if (arcId === null) {
        // Look for forward match
        // (Abnormal topology, but we're accepting it because in-the-wild
        // Shapefiles sometimes have duplicate paths)
        arcId = findArcNeighbor(xx, yy, end, start, getPrev);
      } else {
        arcId = ~arcId;
      }
      return arcId;
    };

    function findArcNeighbor(xx, yy, start, end, getNext) {
      var next = getNext(start),
          key = hash(xx[start], yy[start]),
          arcId = hashTable[key],
          arcX, arcY, len;

      while (arcId != -1) {
        // check endpoints and one segment...
        // it would be more rigorous but slower to identify a match
        // by comparing all segments in the coordinate sequence
        arcX = arcs[arcId][0];
        arcY = arcs[arcId][1];
        len = arcX.length;
        if (arcX[0] === xx[end] && arcX[len-1] === xx[start] && arcX[len-2] === xx[next] &&
            arcY[0] === yy[end] && arcY[len-1] === yy[start] && arcY[len-2] === yy[next]) {
          return arcId;
        }
        arcId = chainIds[arcId];
      }
      return null;
    }

    this.getVertexData = function() {
      var xx = new Float64Array(arcPoints),
          yy = new Float64Array(arcPoints),
          nn = new Uint32Array(arcs.length),
          copied = 0,
          arc, len;
      for (var i=0, n=arcs.length; i<n; i++) {
        arc = arcs[i];
        len = arc[0].length;
        utils.copyElements(arc[0], 0, xx, copied, len);
        utils.copyElements(arc[1], 0, yy, copied, len);
        nn[i] = len;
        copied += len;
      }
      return {
        xx: xx,
        yy: yy,
        nn: nn
      };
    };
  }

  function initPointChains(xx, yy) {
    var chainIds = initHashChains(xx, yy),
        j, next, prevMatchId, prevUnmatchId;

    // disentangle, reverse and close the chains created by initHashChains()
    for (var i = xx.length-1; i>=0; i--) {
      next = chainIds[i];
      if (next >= i) continue;
      prevMatchId = i;
      prevUnmatchId = -1;
      do {
        j = next;
        next = chainIds[j];
        if (yy[j] == yy[i] && xx[j] == xx[i]) {
          chainIds[j] = prevMatchId;
          prevMatchId = j;
        } else {
          if (prevUnmatchId > -1) {
            chainIds[prevUnmatchId] = j;
          }
          prevUnmatchId = j;
        }
      } while (next < j);
      if (prevUnmatchId > -1) {
        // Make sure last unmatched entry is terminated
        chainIds[prevUnmatchId] = prevUnmatchId;
      }
      chainIds[i] = prevMatchId; // close the chain
    }
    return chainIds;
  }

  function initHashChains(xx, yy) {
    // Performance doesn't improve much above ~1.3 * point count
    var n = xx.length,
        m = Math.floor(n * 1.3) || 1,
        hash = getXYHash(m),
        hashTable = new Int32Array(m),
        chainIds = new Int32Array(n), // Array to be filled with chain data
        key, j, i, x, y;

    for (i=0; i<n; i++) {
      x = xx[i];
      y = yy[i];
      if (x != x || y != y) {
        j = -1; // NaN coord: no hash entry, one-link chain
      } else {
        key = hash(x, y);
        j = hashTable[key] - 1; // coord ids are 1-based in hash table; 0 used as null value.
        hashTable[key] = i + 1;
      }
      chainIds[i] = j >= 0 ? j : i; // first item in a chain points to self
    }
    return chainIds;
  }

  // Converts all polygon and polyline paths in a dataset to a topological format
  // (in-place)
  function buildTopology(dataset) {
    if (!dataset.arcs) return;
    var raw = dataset.arcs.getVertexData(),
        cooked = buildPathTopology(raw.nn, raw.xx, raw.yy);
    dataset.arcs.updateVertexData(cooked.nn, cooked.xx, cooked.yy);
    dataset.layers.forEach(function(lyr) {
      if (lyr.geometry_type == 'polyline' || lyr.geometry_type == 'polygon') {
        lyr.shapes = replaceArcIds(lyr.shapes, cooked.paths);
      }
    });
  }

  // buildPathTopology() converts non-topological paths into
  // a topological format
  //
  // Arguments:
  //    xx: [Array|Float64Array],   // x coords of each point in the dataset
  //    yy: [Array|Float64Array],   // y coords ...
  //    nn: [Array]  // length of each path
  //
  // (x- and y-coords of all paths are concatenated into two arrays)
  //
  // Returns:
  // {
  //    xx, yy (array)   // coordinate data
  //    nn: (array)      // points in each arc
  //    paths: (array)   // Paths are arrays of one or more arc id.
  // }
  //
  // Negative arc ids in the paths array indicate a reversal of arc -(id + 1)
  //
  function buildPathTopology(nn, xx, yy) {
    var pointCount = xx.length,
        chainIds = initPointChains(xx, yy),
        pathIds = initPathIds(pointCount, nn),
        index = new ArcIndex(pointCount),
        slice = usingTypedArrays() ? xx.subarray : Array.prototype.slice,
        paths, retn;
    paths = convertPaths(nn);
    retn = index.getVertexData();
    retn.paths = paths;
    return retn;

    function usingTypedArrays() {
      return !!(xx.subarray && yy.subarray);
    }

    function convertPaths(nn) {
      var paths = [],
          pointId = 0,
          pathLen;
      for (var i=0, len=nn.length; i<len; i++) {
        pathLen = nn[i];
        paths.push(pathLen < 2 ? null : convertPath(pointId, pointId + pathLen - 1));
        pointId += pathLen;
      }
      return paths;
    }

    function nextPoint(id) {
      var partId = pathIds[id],
          nextId = id + 1;
      if (nextId < pointCount && pathIds[nextId] === partId) {
        return id + 1;
      }
      var len = nn[partId];
      return sameXY(id, id - len + 1) ? id - len + 2 : -1;
    }

    function prevPoint(id) {
      var partId = pathIds[id],
          prevId = id - 1;
      if (prevId >= 0 && pathIds[prevId] === partId) {
        return id - 1;
      }
      var len = nn[partId];
      return sameXY(id, id + len - 1) ? id + len - 2 : -1;
    }

    function sameXY(a, b) {
      return xx[a] == xx[b] && yy[a] == yy[b];
    }

    // Convert a non-topological path to one or more topological arcs
    // @start, @end are ids of first and last points in the path
    // TODO: don't allow id ~id pairs
    //
    function convertPath(start, end) {
      var arcIds = [],
          firstNodeId = -1,
          arcStartId;

      // Visit each point in the path, up to but not including the last point
      for (var i = start; i < end; i++) {
        if (pointIsArcEndpoint(i)) {
          if (firstNodeId > -1) {
            arcIds.push(addEdge(arcStartId, i));
          } else {
            firstNodeId = i;
          }
          arcStartId = i;
        }
      }

      // Identify the final arc in the path
      if (firstNodeId == -1) {
        // Not in an arc, i.e. no nodes have been found...
        // Assuming that path is either an island or is congruent with one or more rings
        arcIds.push(addRing(start, end));
      }
      else if (firstNodeId == start) {
        // path endpoint is a node;
        if (!pointIsArcEndpoint(end)) {
          error("Topology error"); // TODO: better error handling
        }
        arcIds.push(addEdge(arcStartId, i));
      } else {
        // final arc wraps around
        arcIds.push(addSplitEdge(arcStartId, end, start + 1, firstNodeId));
      }
      return arcIds;
    }

    // Test if a point @id is an endpoint of a topological path
    function pointIsArcEndpoint(id) {
      var id2 = chainIds[id],
          prev = prevPoint(id),
          next = nextPoint(id),
          prev2, next2;
      if (prev == -1 || next == -1) {
        // @id is an endpoint if it is the start or end of an open path
        return true;
      }
      while (id != id2) {
        prev2 = prevPoint(id2);
        next2 = nextPoint(id2);
        if (prev2 == -1 || next2 == -1 || brokenEdge(prev, next, prev2, next2)) {
          // there is a discontinuity at @id -- point is arc endpoint
          return true;
        }
        id2 = chainIds[id2];
      }
      return false;
    }

    // a and b are two vertices with the same x, y coordinates
    // test if the segments on either side of them are also identical
    function brokenEdge(aprev, anext, bprev, bnext) {
      var apx = xx[aprev],
          anx = xx[anext],
          bpx = xx[bprev],
          bnx = xx[bnext],
          apy = yy[aprev],
          any = yy[anext],
          bpy = yy[bprev],
          bny = yy[bnext];
      if (apx == bnx && anx == bpx && apy == bny && any == bpy ||
          apx == bpx && anx == bnx && apy == bpy && any == bny) {
        return false;
      }
      return true;
    }

    function mergeArcParts(src, startId, endId, startId2, endId2) {
      var len = endId - startId + endId2 - startId2 + 2,
          ArrayClass = usingTypedArrays() ? Float64Array : Array,
          dest = new ArrayClass(len),
          j = 0, i;
      for (i=startId; i <= endId; i++) {
        dest[j++] = src[i];
      }
      for (i=startId2; i <= endId2; i++) {
        dest[j++] = src[i];
      }
      return dest;
    }

    function addSplitEdge(start1, end1, start2, end2) {
      var arcId = index.findDuplicateArc(xx, yy, start1, end2, nextPoint, prevPoint);
      if (arcId === null) {
        arcId = index.addArc(mergeArcParts(xx, start1, end1, start2, end2),
            mergeArcParts(yy, start1, end1, start2, end2));
      }
      return arcId;
    }

    function addEdge(start, end) {
      // search for a matching edge that has already been generated
      var arcId = index.findDuplicateArc(xx, yy, start, end, nextPoint, prevPoint);
      if (arcId === null) {
        arcId = index.addArc(slice.call(xx, start, end + 1),
            slice.call(yy, start, end + 1));
      }
      return arcId;
    }

    function addRing(startId, endId) {
      var chainId = chainIds[startId],
          pathId = pathIds[startId],
          arcId;

      while (chainId != startId) {
        if (pathIds[chainId] < pathId) {
          break;
        }
        chainId = chainIds[chainId];
      }

      if (chainId == startId) {
        return addEdge(startId, endId);
      }

      for (var i=startId; i<endId; i++) {
        arcId = index.findDuplicateArc(xx, yy, i, i, nextPoint, prevPoint);
        if (arcId !== null) return arcId;
      }
      error("Unmatched ring; id:", pathId, "len:", nn[pathId]);
    }
  }


  // Create a lookup table for path ids; path ids are indexed by point id
  //
  function initPathIds(size, pathSizes) {
    var pathIds = new Int32Array(size),
        j = 0;
    for (var pathId=0, pathCount=pathSizes.length; pathId < pathCount; pathId++) {
      for (var i=0, n=pathSizes[pathId]; i<n; i++, j++) {
        pathIds[j] = pathId;
      }
    }
    return pathIds;
  }

  function replaceArcIds(src, replacements) {
    return src.map(function(shape) {
      return replaceArcsInShape(shape, replacements);
    });

    function replaceArcsInShape(shape, replacements) {
      if (!shape) return null;
      return shape.map(function(path) {
        return replaceArcsInPath(path, replacements);
      });
    }

    function replaceArcsInPath(path, replacements) {
      return path.reduce(function(memo, id) {
        var abs = absArcId(id);
        var topoPath = replacements[abs];
        if (topoPath) {
          if (id < 0) {
            topoPath = topoPath.concat(); // TODO: need to copy?
            reversePath(topoPath);
          }
          for (var i=0, n=topoPath.length; i<n; i++) {
            memo.push(topoPath[i]);
          }
        }
        return memo;
      }, []);
    }
  }

  var Topology = /*#__PURE__*/Object.freeze({
    __proto__: null,
    buildTopology: buildTopology,
    buildPathTopology: buildPathTopology
  });

  // Merge arcs from one or more source datasets into target dataset
  // return array of layers from the source dataset (instead of adding them to the target dataset)
  function mergeDatasetsIntoDataset(dataset, datasets) {
    var merged = mergeDatasets([dataset].concat(datasets));
    var mergedLayers = datasets.reduce(function(memo, dataset) {
      return memo.concat(dataset.layers);
    }, []);
    dataset.arcs = merged.arcs;
    return mergedLayers;
  }

  // Don't modify input layers (mergeDatasets() updates arc ids in-place)
  function mergeDatasetsForExport(arr) {
    // copy layers but not arcs, which get copied in mergeDatasets()
    var copy = arr.map(function(dataset) {
      return utils.defaults({
        layers: dataset.layers.map(copyLayerShapes)
      }, dataset);
    });
    return mergeDatasets(copy);
  }

  function mergeCommandTargets(targets, catalog) {
    var targetLayers = [];
    var targetDatasets = [];
    var datasetsWithArcs = 0;
    var merged;

    targets.forEach(function(target) {
      targetLayers = targetLayers.concat(target.layers);
      targetDatasets = targetDatasets.concat(target.dataset);
      if (target.dataset.arcs && target.dataset.arcs.size() > 0) datasetsWithArcs++;
    });

    merged = mergeDatasets(targetDatasets);

    // Rebuild topology, if multiple datasets contain arcs
    if (datasetsWithArcs > 1) {
      buildTopology(merged);
    }

    // remove old datasets after merging, so catalog is not affected if merge throws an error
    targetDatasets.forEach(catalog.removeDataset);
    catalog.addDataset(merged); // sets default target to all layers in merged dataset
    catalog.setDefaultTarget(targetLayers, merged); // reset default target
    return [{
      layers: targetLayers,
      dataset: merged
    }];
  }

  // Combine multiple datasets into one using concatenation
  // (any shared topology is ignored)
  function mergeDatasets(arr) {
    var arcSources = [],
        arcCount = 0,
        mergedLayers = [],
        mergedInfo = {},
        mergedArcs;

    // Error if incompatible CRS
    requireDatasetsHaveCompatibleCRS(arr);

    arr.forEach(function(dataset) {
      var n = dataset.arcs ? dataset.arcs.size() : 0;
      if (n > 0) {
        arcSources.push(dataset.arcs);
      }

      mergeDatasetInfo(mergedInfo, dataset);
      dataset.layers.forEach(function(lyr) {
        if (lyr.geometry_type == 'polygon' || lyr.geometry_type == 'polyline') {
          forEachArcId(lyr.shapes, function(id) {
            return id < 0 ? id - arcCount : id + arcCount;
          });
        }
        mergedLayers.push(lyr);
      });
      arcCount += n;
    });

    if (arcSources.length > 0) {
      mergedArcs = mergeArcs(arcSources);
      if (mergedArcs.size() != arcCount) {
        error("[mergeDatasets()] Arc indexing error");
      }
    }

    return {
      info: mergedInfo,
      arcs: mergedArcs,
      layers: mergedLayers
    };
  }

  function mergeDatasetInfo(merged, dataset) {
    var info = dataset.info || {};
    merged.input_files = utils.uniq((merged.input_files || []).concat(info.input_files || []));
    merged.input_formats = utils.uniq((merged.input_formats || []).concat(info.input_formats || []));
    // merge other info properties (e.g. input_geojson_crs, input_delimiter, prj, crs)
    utils.defaults(merged, info);
  }

  function mergeArcs(arr) {
    // Returning the original causes a test to fail
    // if (arr.length < 2) return arr[0];
    var dataArr = arr.map(function(arcs) {
      if (arcs.getRetainedInterval() > 0) {
        verbose("Baking-in simplification setting.");
        arcs.flatten();
      }
      return arcs.getVertexData();
    });
    var xx = mergeArrays(utils.pluck(dataArr, 'xx'), Float64Array),
        yy = mergeArrays(utils.pluck(dataArr, 'yy'), Float64Array),
        nn = mergeArrays(utils.pluck(dataArr, 'nn'), Int32Array);

    return new ArcCollection(nn, xx, yy);
  }

  function countElements(arrays) {
    return arrays.reduce(function(memo, arr) {
      return memo + (arr.length || 0);
    }, 0);
  }

  function mergeArrays(arrays, TypedArr) {
    var size = countElements(arrays),
        Arr = TypedArr || Array,
        merged = new Arr(size),
        offs = 0;
    arrays.forEach(function(src) {
      var n = src.length;
      for (var i = 0; i<n; i++) {
        merged[i + offs] = src[i];
      }
      offs += n;
    });
    return merged;
  }

  var Merging = /*#__PURE__*/Object.freeze({
    __proto__: null,
    mergeDatasetsIntoDataset: mergeDatasetsIntoDataset,
    mergeDatasetsForExport: mergeDatasetsForExport,
    mergeCommandTargets: mergeCommandTargets,
    mergeDatasets: mergeDatasets,
    mergeArcs: mergeArcs
  });

  // Test if the second endpoint of an arc is the endpoint of any path in any layer
  function getPathEndpointTest(layers, arcs) {
    var index = new Uint8Array(arcs.size());
    layers.forEach(function(lyr) {
      if (layerHasPaths(lyr)) {
        lyr.shapes.forEach(addShape);
      }
    });

    function addShape(shape) {
      forEachShapePart(shape, addPath);
    }

    function addPath(path) {
      addEndpoint(~path[0]);
      addEndpoint(path[path.length - 1]);
    }

    function addEndpoint(arcId) {
      var absId = absArcId(arcId);
      var fwd = absId == arcId;
      index[absId] |= fwd ? 1 : 2;
    }

    return function(arcId) {
      var absId = absArcId(arcId);
      var fwd = absId == arcId;
      var code = index[absId];
      return fwd ? (code & 1) == 1 : (code & 2) == 2;
    };
  }

  var PathEndpoints = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getPathEndpointTest: getPathEndpointTest
  });

  // @arcs ArcCollection
  // @filter Optional filter function, arcIds that return false are excluded
  //
  function NodeCollection(arcs, filter) {
    if (Array.isArray(arcs)) {
      arcs = new ArcCollection(arcs);
    }
    var arcData = arcs.getVertexData(),
        nn = arcData.nn,
        xx = arcData.xx,
        yy = arcData.yy,
        nodeData;

    // Accessor function for arcs
    Object.defineProperty(this, 'arcs', {value: arcs});

    this.toArray = function() {
      var chains = getNodeChains(),
          flags = new Uint8Array(chains.length),
          arr = [];
      utils.forEach(chains, function(nextIdx, thisIdx) {
        var node, p;
        if (flags[thisIdx] == 1) return;
        p = getEndpoint(thisIdx);
        if (!p) return; // endpoints of an excluded arc
        node = {coordinates: p, arcs: []};
        arr.push(node);
        while (flags[thisIdx] != 1) {
          node.arcs.push(chainToArcId(thisIdx));
          flags[thisIdx] = 1;
          thisIdx = chains[thisIdx];
        }
      });
      return arr;
    };

    this.size = function() {
      return this.toArray().length;
    };

    this.findDanglingEndpoints = function() {
      var chains = getNodeChains(),
          arr = [], p;
      for (var i=0, n=chains.length; i<n; i++) {
        if (chains[i] != i) continue; // endpoint attaches to a node
        p = getEndpoint(i);
        if (!p) continue; // endpoint belongs to an excluded arc
        arr.push({
          point: p,
          arc: chainToArcId(i)
        });
      }
      return arr;
    };

    this.detachAcyclicArcs = function() {
      var chains = getNodeChains(),
          count = 0,
          fwd, rev;
      for (var i=0, n=chains.length; i<n; i+= 2) {
        fwd = i == chains[i];
        rev = i + 1 == chains[i + 1];
        // detach arcs that are disconnected at one end or the other
        if ((fwd || rev) && !linkIsDetached(i)) {
          this.detachArc(chainToArcId(i));
          count++;
        }
      }
      if (count > 0) {
        // removing one acyclic arc could expose another -- need another pass
        count += this.detachAcyclicArcs();
      }
      return count;
    };

    this.detachArc = function(arcId) {
      unlinkDirectedArc(arcId);
      unlinkDirectedArc(~arcId);
    };

    this.forEachConnectedArc = function(arcId, cb) {
      var nextId = nextConnectedArc(arcId),
          i = 0;
      while (nextId != arcId) {
        cb(nextId, i++);
        nextId = nextConnectedArc(nextId);
      }
    };

    // Receives an arc id for an arc that enters a node.
    // Returns an array of ids of all other arcs that are connected to the same node.
    //    Returned ids lead into the node (as opposed to outwards from it)
    // An optional filter function receives the directed id (positive or negative)
    //    of each connected arc and excludes arcs for which the filter returns false.
    //    The filter is also applied to the initial arc; if false, no arcs are returned.
    //
    this.getConnectedArcs = function(arcId, filter) {
      var ids = [];
      var filtered = !!filter;
      var nextId = nextConnectedArc(arcId);
      if (filtered && !filter(arcId)) ;
      while (nextId != arcId) {
        if (!filtered || filter(nextId)) {
          ids.push(nextId);
        }
        nextId = nextConnectedArc(nextId);
      }
      return ids;
    };

    // Returns the id of the first identical arc or @arcId if none found
    // TODO: find a better function name
    this.findDuplicateArc = function(arcId) {
      var nextId = nextConnectedArc(arcId),
          match = arcId;
      while (nextId != arcId) {
        if (testArcMatch(arcId, nextId)) {
          if (absArcId(nextId) < absArcId(match)) match = nextId;
        }
        nextId = nextConnectedArc(nextId);
      }
      return match;
    };

    // returns null if link has been removed from node collection
    function getEndpoint(chainId) {
      return linkIsDetached(chainId) ? null : [nodeData.xx[chainId], nodeData.yy[chainId]];
    }

    function linkIsDetached(chainId) {
      return isNaN(nodeData.xx[chainId]);
    }

    function unlinkDirectedArc(arcId) {
      var chainId = arcToChainId(arcId),
          chains = getNodeChains(),
          nextId = chains[chainId],
          prevId = prevChainId(chainId);
      nodeData.xx[chainId] = NaN;
      nodeData.yy[chainId] = NaN;
      chains[chainId] = chainId;
      chains[prevId] = nextId;
    }

    function chainToArcId(chainId) {
      var absId = chainId >> 1;
      return chainId & 1 == 1 ? absId : ~absId;
    }

    function arcToChainId(arcId) {
      var fw = arcId >= 0;
      return fw ? arcId * 2 + 1 : (~arcId) * 2; // if fw, use end, if rev, use start
    }

    function getNodeChains() {
      if (!nodeData) {
        nodeData = findNodeTopology(arcs, filter);
        if (nn.length * 2 != nodeData.chains.length) error("[NodeCollection] count error");
      }
      return nodeData.chains;
    }

    function testArcMatch(a, b) {
      var absA = a >= 0 ? a : ~a,
          absB = b >= 0 ? b : ~b,
          lenA = nn[absA];
      if (lenA < 2) {
        // Don't throw error on collapsed arcs -- assume they will be handled
        //   appropriately downstream.
        // error("[testArcMatch() defective arc; len:", lenA);
        return false;
      }
      if (lenA != nn[absB]) return false;
      if (testVertexMatch(a, b, -1) &&
          testVertexMatch(a, b, 1) &&
          testVertexMatch(a, b, -2)) {
        return true;
      }
      return false;
    }

    function testVertexMatch(a, b, i) {
      var ai = arcs.indexOfVertex(a, i),
          bi = arcs.indexOfVertex(b, i);
      return xx[ai] == xx[bi] && yy[ai] == yy[bi];
    }

    // return arcId of next arc in the chain, pointed towards the shared vertex
    function nextConnectedArc(arcId) {
      var chainId = arcToChainId(arcId),
          chains =  getNodeChains(),
          nextChainId = chains[chainId];
      if (!(nextChainId >= 0 && nextChainId < chains.length)) {
        // console.log('arcId:', arcId, 'chainId:', chainId, 'next chain id:', nextChainId)
        error("out-of-range chain id");
      }
      return chainToArcId(nextChainId);
    }

    function prevChainId(chainId) {
      var chains = getNodeChains(),
          prevId = chainId,
          nextId = chains[chainId];
      while (nextId != chainId) {
        prevId = nextId;
        nextId = chains[nextId];
        if (nextId == prevId) error("Node indexing error");
      }
      return prevId;
    }

    // expose functions for testing
    this.internal = {
      testArcMatch: testArcMatch,
      testVertexMatch: testVertexMatch
    };
  }

  function findNodeTopology(arcs, filter) {
    var n = arcs.size() * 2,
        xx2 = new Float64Array(n),
        yy2 = new Float64Array(n),
        ids2 = new Int32Array(n);

    arcs.forEach2(function(i, n, xx, yy, zz, arcId) {
      var start = i,
          end = i + n - 1,
          start2 = arcId * 2,
          end2 = start2 + 1,
          ax = xx[start],
          ay = yy[start],
          bx = xx[end],
          by = yy[end];
      if (filter && !filter(arcId)) {
        ax = ay = bx = by = NaN;
      }

      xx2[start2] = ax;
      yy2[start2] = ay;
      ids2[start2] = arcId;
      xx2[end2] = bx;
      yy2[end2] = by;
      ids2[end2] = arcId;
    });

    var chains = initPointChains(xx2, yy2);
    return {
      xx: xx2,
      yy: yy2,
      ids: ids2,
      chains: chains
    };
  }

  // Dissolve arcs that can be merged without affecting topology of layers
  // remove arcs that are not referenced by any layer; remap arc ids
  // in layers. (dataset.arcs is replaced).
  function dissolveArcs(dataset) {
    var arcs = dataset.arcs,
        layers = dataset.layers.filter(layerHasPaths);

    if (!arcs || !layers.length) {
      dataset.arcs = null;
      return;
    }

    var arcsCanDissolve = getArcDissolveTest(layers, arcs),
        newArcs = [],
        totalPoints = 0,
        arcIndex = new Int32Array(arcs.size()), // maps old arc ids to new ids
        arcStatus = new Uint8Array(arcs.size());
        // arcStatus: 0 = unvisited, 1 = dropped, 2 = remapped, 3 = remapped + reversed
    layers.forEach(function(lyr) {
      // modify copies of the original shapes; original shapes should be unmodified
      // (need to test this)
      lyr.shapes = lyr.shapes.map(function(shape) {
        return editShapeParts(shape && shape.concat(), translatePath);
      });
    });
    dataset.arcs = dissolveArcCollection(arcs, newArcs, totalPoints);

    function translatePath(path) {
      var pointCount = 0;
      var newPath = [];
      var newArc, arcId, absId, arcLen, fw, newArcId;

      for (var i=0, n=path.length; i<n; i++) {
        arcId = path[i];
        absId = absArcId(arcId);
        fw = arcId === absId;

        if (arcs.arcIsDegenerate(arcId)) ; else if (arcStatus[absId] !== 0) {
          // arc has already been translated -- skip
          newArc = null;
        } else {
          arcLen = arcs.getArcLength(arcId);

          if (newArc && arcsCanDissolve(path[i-1], arcId)) {
            if (arcLen > 0) {
              arcLen--; // shared endpoint not counted;
            }
            newArc.push(arcId);  // arc data is appended to previous arc
            arcStatus[absId] = 1; // arc is dropped from output
          } else {
            // start a new dissolved arc
            newArc = [arcId];
            arcIndex[absId] = newArcs.length;
            newArcs.push(newArc);
            arcStatus[absId] = fw ? 2 : 3; // 2: unchanged; 3: reversed
          }
          pointCount += arcLen;
        }

        if (arcStatus[absId] > 1) {
          // arc is retained (and renumbered) in the dissolved path -- add to path
          newArcId = arcIndex[absId];
          if (fw && arcStatus[absId] == 3 || !fw && arcStatus[absId] == 2) {
            newArcId = ~newArcId;
          }
          newPath.push(newArcId);
        }
      }
      totalPoints += pointCount;
      return newPath;
    }
  }

  function dissolveArcCollection(arcs, newArcs, newLen) {
    var nn2 = new Uint32Array(newArcs.length),
        xx2 = new Float64Array(newLen),
        yy2 = new Float64Array(newLen),
        src = arcs.getVertexData(),
        zz2 = src.zz ? new Float64Array(newLen) : null,
        interval = arcs.getRetainedInterval(),
        offs = 0;

    newArcs.forEach(function(newArc, newId) {
      newArc.forEach(function(oldId, i) {
        extendDissolvedArc(oldId, newId);
      });
    });

    return new ArcCollection(nn2, xx2, yy2).setThresholds(zz2).setRetainedInterval(interval);

    function extendDissolvedArc(oldId, newId) {
      var absId = absArcId(oldId),
          rev = oldId < 0,
          n = src.nn[absId],
          i = src.ii[absId],
          n2 = nn2[newId];

      if (n > 0) {
        if (n2 > 0) {
          n--;
          if (!rev) i++;
        }
        utils.copyElements(src.xx, i, xx2, offs, n, rev);
        utils.copyElements(src.yy, i, yy2, offs, n, rev);
        if (zz2) utils.copyElements(src.zz, i, zz2, offs, n, rev);
        nn2[newId] += n;
        offs += n;
      }
    }
  }

  // Test whether two arcs can be merged together
  function getArcDissolveTest(layers, arcs) {
    var nodes = new NodeCollection(arcs, getArcPresenceTest2(layers, arcs)),
        // don't allow dissolving through endpoints of polyline paths
        lineLayers = layers.filter(function(lyr) {return lyr.geometry_type == 'polyline';}),
        testLineEndpoint = getPathEndpointTest(lineLayers, arcs),
        linkCount, lastId;

    return function(id1, id2) {
      if (id1 == id2 || id1 == ~id2) {
        verbose("Unexpected arc sequence:", id1, id2);
        return false; // This is unexpected; don't try to dissolve, anyway
      }
      linkCount = 0;
      nodes.forEachConnectedArc(id1, countLink);
      return linkCount == 1 && lastId == ~id2 && !testLineEndpoint(id1) && !testLineEndpoint(~id2);
    };

    function countLink(arcId, i) {
      linkCount++;
      lastId = arcId;
    }
  }

  var ArcDissolve = /*#__PURE__*/Object.freeze({
    __proto__: null,
    dissolveArcs: dissolveArcs,
    getArcDissolveTest: getArcDissolveTest
  });

  // utility functions for datasets

  // Split into datasets with one layer each
  function splitDataset(dataset) {
    return dataset.layers.map(function(lyr) {
      var split = {
        arcs: dataset.arcs,
        layers: [lyr],
        info: utils.extend({}, dataset.info)
      };
      dissolveArcs(split); // replace arcs with filtered + dissolved copy
      return split;
    });
  }

  function splitApartLayers(dataset, layers) {
    var datasets = [];
    dataset.layers = dataset.layers.filter(function(lyr) {
      if (!layers.includes(lyr)) {
        return true;
      }
      var split = {
        arcs: dataset.arcs,
        layers: [lyr],
        info: utils.extend({}, dataset.info)
      };
      dissolveArcs(split); // replace arcs with filtered + dissolved copy
      datasets.push(split);
      return false;
    });
    if (dataset.layers.length) {
      dissolveArcs(dataset);
      datasets.push(dataset);
    }
    return datasets;
  }

  // clone all layers, make a filtered copy of arcs
  function copyDataset(dataset) {
    var d2 = utils.extend({}, dataset);
    d2.layers = d2.layers.map(copyLayer);
    if (d2.arcs) {
      d2.arcs = d2.arcs.getFilteredCopy();
    }
    return d2;
  }

  // clone coordinate data, shallow-copy attribute data
  function copyDatasetForExport(dataset) {
    var d2 = utils.extend({}, dataset);
    d2.layers = d2.layers.map(copyLayerShapes);
    if (d2.arcs) {
      d2.arcs = d2.arcs.getFilteredCopy();
    }
    return d2;
  }

  // shallow-copy layers, so they can be renamed (for export)
  function copyDatasetForRenaming(dataset) {
    return utils.defaults({
      layers: dataset.layers.map(function(lyr) {return utils.extend({}, lyr);})
    }, dataset);
  }

  function getDatasetBounds(dataset) {
    var bounds = new Bounds();
    dataset.layers.forEach(function(lyr) {
      var lyrbb = getLayerBounds(lyr, dataset.arcs);
      if (lyrbb) bounds.mergeBounds(lyrbb);
    });
    return bounds;
  }

  function datasetHasGeometry(dataset) {
    return utils.some(dataset.layers, function(lyr) {
      return layerHasGeometry(lyr);
    });
  }

  function datasetHasPaths(dataset) {
    return utils.some(dataset.layers, function(lyr) {
      return layerHasPaths(lyr);
    });
  }

  // Remove ArcCollection of a dataset if not referenced by any layer
  // TODO: consider doing arc dissolve, or just removing unreferenced arcs
  // (currently cleanupArcs() is run after every command, so be mindful of performance)
  function cleanupArcs(dataset) {
    if (dataset.arcs && !utils.some(dataset.layers, layerHasPaths)) {
      dataset.arcs = null;
      return true;
    }
  }

  // Remove unused arcs from a dataset
  // Warning: using dissolveArcs() means that adjacent arcs are combined when possible
  function pruneArcs(dataset) {
    cleanupArcs(dataset);
    if (dataset.arcs) {
      dissolveArcs(dataset);
    }
  }

  // replace cut layers in-sequence (to maintain layer indexes)
  // append any additional new layers
  function replaceLayers(dataset, cutLayers, newLayers) {
    // modify a copy in case cutLayers == dataset.layers
    var currLayers = dataset.layers.concat();
    utils.repeat(Math.max(cutLayers.length, newLayers.length), function(i) {
      var cutLyr = cutLayers[i],
          newLyr = newLayers[i],
          idx = cutLyr ? currLayers.indexOf(cutLyr) : currLayers.length;

      if (cutLyr) {
        currLayers.splice(idx, 1);
      }
      if (newLyr) {
        currLayers.splice(idx, 0, newLyr);
      }
    });
    dataset.layers = currLayers;
  }

  // Replace a layer with a layer from a second dataset
  // (in-place)
  // (Typically, the second dataset is imported from dynamically generated GeoJSON and contains one layer)
  function replaceLayerContents(lyr, dataset, dataset2) {
    var lyr2 = mergeOutputLayerIntoDataset(lyr, dataset, dataset2, {});
    if (layerHasPaths(lyr2)) {
      buildTopology(dataset);
    }
  }

  function mergeOutputLayerIntoDataset(lyr, dataset, dataset2, opts) {
    if (!dataset2 || dataset2.layers.length != 1) {
      error('Invalid source dataset');
    }
    if (dataset.layers.includes(lyr) === false) {
      error('Invalid target layer');
    }
    // this command returns merged layers instead of adding them to target dataset
    var outputLayers = mergeDatasetsIntoDataset(dataset, [dataset2]);
    var lyr2 = outputLayers[0];

    // TODO: find a more reliable way of knowing when to copy data
    var copyData = !lyr2.data && lyr.data && getFeatureCount(lyr2) == lyr.data.size();

    if (copyData) {
      lyr2.data = opts.no_replace ? lyr.data.clone() : lyr.data;
    }
    if (opts.no_replace) ; else {
      lyr2 = Object.assign(lyr, {data: null, shapes: null}, lyr2);
      if (layerHasPaths(lyr)) {
        // Remove unused arcs from replaced layer
        // TODO: consider using clean insead of this
        dissolveArcs(dataset);
      }
    }

    lyr2.name = opts.name || lyr2.name;
    return lyr2;
  }

  // Transform the points in a dataset in-place; don't clean up corrupted shapes
  function transformPoints(dataset, f) {
    if (dataset.arcs) {
      dataset.arcs.transformPoints(f);
    }
    dataset.layers.forEach(function(lyr) {
      if (layerHasPoints(lyr)) {
        transformPointsInLayer(lyr, f);
      }
    });
  }

  var DatasetUtils = /*#__PURE__*/Object.freeze({
    __proto__: null,
    splitDataset: splitDataset,
    splitApartLayers: splitApartLayers,
    copyDataset: copyDataset,
    copyDatasetForExport: copyDatasetForExport,
    copyDatasetForRenaming: copyDatasetForRenaming,
    getDatasetBounds: getDatasetBounds,
    datasetHasGeometry: datasetHasGeometry,
    datasetHasPaths: datasetHasPaths,
    cleanupArcs: cleanupArcs,
    pruneArcs: pruneArcs,
    replaceLayers: replaceLayers,
    replaceLayerContents: replaceLayerContents,
    mergeOutputLayerIntoDataset: mergeOutputLayerIntoDataset,
    transformPoints: transformPoints
  });

  function getPathSep(path) {
    // TODO: improve
    return path.indexOf('/') == -1 && path.indexOf('\\') != -1 ? '\\' : '/';
  }

  // Parse the path to a file without using Node
  // Guess if the path is a directory or file
  function parseLocalPath(path) {
    var obj = {
          filename: '',
          directory: '',
          basename: '',
          extension: ''
        },
        sep = getPathSep(path),
        parts = path.split(sep),
        lastPart = parts.pop(),
        // try to match typical extensions but reject directory names with dots
        extRxp = /\.([a-z][a-z0-9]*)$/i,
        extMatch = extRxp.test(lastPart) ? extRxp.exec(lastPart)[0] : '';

    if (extMatch || lastPart.includes('*')) {
      obj.filename = lastPart;
      obj.extension = extMatch ? extMatch.slice(1) : '';
      obj.basename = lastPart.slice(0, lastPart.length - extMatch.length);
      obj.directory = parts.join(sep);
    } else if (!lastPart) { // path ends with separator
      obj.directory = parts.join(sep);
    } else {
      obj.directory = path;
    }
    return obj;
  }

  function getFileBase(path) {
    return parseLocalPath(path).basename;
  }

  function getFileExtension(path) {
    return parseLocalPath(path).extension;
  }

  function getPathBase(path) {
    var info =  parseLocalPath(path);
    if (!info.extension) return path;
    return path.slice(0, path.length - info.extension.length - 1);
  }

  function replaceFileExtension(path, ext) {
    var base = getPathBase(path);
    return ext ? base + '.' + ext : base;
  }

  function toLowerCaseExtension(name) {
    var ext = getFileExtension(name);
    return ext ? getPathBase(name) + '.' + ext.toLowerCase() : name;
  }

  function getCommonFileBase(names) {
    return names.reduce(function(memo, name, i) {
      if (i === 0) {
        memo = getFileBase(name);
      } else {
        memo = utils.mergeNames(memo, name);
      }
      return memo;
    }, "");
  }

  function getOutputFileBase(dataset) {
    var inputFiles = dataset.info && dataset.info.input_files;
    return inputFiles && getCommonFileBase(inputFiles) || 'output';
  }

  var FilenameUtils = /*#__PURE__*/Object.freeze({
    __proto__: null,
    parseLocalPath: parseLocalPath,
    getFileBase: getFileBase,
    getFileExtension: getFileExtension,
    getPathBase: getPathBase,
    replaceFileExtension: replaceFileExtension,
    toLowerCaseExtension: toLowerCaseExtension,
    getCommonFileBase: getCommonFileBase,
    getOutputFileBase: getOutputFileBase
  });

  var decoder;
  try {
  	decoder = new TextDecoder();
  } catch(error) {}
  var src;
  var srcEnd;
  var position$1 = 0;
  var currentUnpackr = {};
  var currentStructures;
  var srcString;
  var srcStringStart = 0;
  var srcStringEnd = 0;
  var bundledStrings$1;
  var referenceMap;
  var currentExtensions = [];
  var dataView;
  var defaultOptions = {
  	useRecords: false,
  	mapsAsObjects: true
  };
  class C1Type {}
  const C1$1 = new C1Type();
  C1$1.name = 'MessagePack 0xC1';
  var sequentialMode = false;
  var inlineObjectReadThreshold = 2;
  var readStruct;
  // no-eval build
  try {
  	new Function('');
  } catch(error) {
  	// if eval variants are not supported, do not create inline object readers ever
  	inlineObjectReadThreshold = Infinity;
  }

  class Unpackr {
  	constructor(options) {
  		if (options) {
  			if (options.useRecords === false && options.mapsAsObjects === undefined)
  				options.mapsAsObjects = true;
  			if (options.sequential && options.trusted !== false) {
  				options.trusted = true;
  				if (!options.structures && options.useRecords != false) {
  					options.structures = [];
  					if (!options.maxSharedStructures)
  						options.maxSharedStructures = 0;
  				}
  			}
  			if (options.structures)
  				options.structures.sharedLength = options.structures.length;
  			else if (options.getStructures) {
  				(options.structures = []).uninitialized = true; // this is what we use to denote an uninitialized structures
  				options.structures.sharedLength = 0;
  			}
  			if (options.int64AsNumber) {
  				options.int64AsType = 'number';
  			}
  		}
  		Object.assign(this, options);
  	}
  	unpack(source, options) {
  		if (src) {
  			// re-entrant execution, save the state and restore it after we do this unpack
  			return saveState(() => {
  				clearSource();
  				return this ? this.unpack(source, options) : Unpackr.prototype.unpack.call(defaultOptions, source, options)
  			})
  		}
  		if (typeof options === 'object') {
  			srcEnd = options.end || source.length;
  			position$1 = options.start || 0;
  		} else {
  			position$1 = 0;
  			srcEnd = options > -1 ? options : source.length;
  		}
  		srcStringEnd = 0;
  		srcString = null;
  		bundledStrings$1 = null;
  		src = source;
  		// this provides cached access to the data view for a buffer if it is getting reused, which is a recommend
  		// technique for getting data from a database where it can be copied into an existing buffer instead of creating
  		// new ones
  		try {
  			dataView = source.dataView || (source.dataView = new DataView(source.buffer, source.byteOffset, source.byteLength));
  		} catch(error) {
  			// if it doesn't have a buffer, maybe it is the wrong type of object
  			src = null;
  			if (source instanceof Uint8Array)
  				throw error
  			throw new Error('Source must be a Uint8Array or Buffer but was a ' + ((source && typeof source == 'object') ? source.constructor.name : typeof source))
  		}
  		if (this instanceof Unpackr) {
  			currentUnpackr = this;
  			if (this.structures) {
  				currentStructures = this.structures;
  				return checkedRead(options)
  			} else if (!currentStructures || currentStructures.length > 0) {
  				currentStructures = [];
  			}
  		} else {
  			currentUnpackr = defaultOptions;
  			if (!currentStructures || currentStructures.length > 0)
  				currentStructures = [];
  		}
  		return checkedRead(options)
  	}
  	unpackMultiple(source, forEach) {
  		let values, lastPosition = 0;
  		try {
  			sequentialMode = true;
  			let size = source.length;
  			let value = this ? this.unpack(source, size) : defaultUnpackr.unpack(source, size);
  			if (forEach) {
  				if (forEach(value) === false) return;
  				while(position$1 < size) {
  					lastPosition = position$1;
  					if (forEach(checkedRead()) === false) {
  						return
  					}
  				}
  			}
  			else {
  				values = [ value ];
  				while(position$1 < size) {
  					lastPosition = position$1;
  					values.push(checkedRead());
  				}
  				return values
  			}
  		} catch(error) {
  			error.lastPosition = lastPosition;
  			error.values = values;
  			throw error
  		} finally {
  			sequentialMode = false;
  			clearSource();
  		}
  	}
  	_mergeStructures(loadedStructures, existingStructures) {
  		loadedStructures = loadedStructures || [];
  		if (Object.isFrozen(loadedStructures))
  			loadedStructures = loadedStructures.map(structure => structure.slice(0));
  		for (let i = 0, l = loadedStructures.length; i < l; i++) {
  			let structure = loadedStructures[i];
  			if (structure) {
  				structure.isShared = true;
  				if (i >= 32)
  					structure.highByte = (i - 32) >> 5;
  			}
  		}
  		loadedStructures.sharedLength = loadedStructures.length;
  		for (let id in existingStructures || []) {
  			if (id >= 0) {
  				let structure = loadedStructures[id];
  				let existing = existingStructures[id];
  				if (existing) {
  					if (structure)
  						(loadedStructures.restoreStructures || (loadedStructures.restoreStructures = []))[id] = structure;
  					loadedStructures[id] = existing;
  				}
  			}
  		}
  		return this.structures = loadedStructures
  	}
  	decode(source, end) {
  		return this.unpack(source, end)
  	}
  }
  function checkedRead(options) {
  	try {
  		if (!currentUnpackr.trusted && !sequentialMode) {
  			let sharedLength = currentStructures.sharedLength || 0;
  			if (sharedLength < currentStructures.length)
  				currentStructures.length = sharedLength;
  		}
  		let result;
  		if (currentUnpackr.randomAccessStructure && src[position$1] < 0x40 && src[position$1] >= 0x20 && readStruct) {
  			result = readStruct(src, position$1, srcEnd, currentUnpackr);
  			src = null; // dispose of this so that recursive unpack calls don't save state
  			if (!(options && options.lazy) && result)
  				result = result.toJSON();
  			position$1 = srcEnd;
  		} else
  			result = read();
  		if (bundledStrings$1) { // bundled strings to skip past
  			position$1 = bundledStrings$1.postBundlePosition;
  			bundledStrings$1 = null;
  		}

  		if (position$1 == srcEnd) {
  			// finished reading this source, cleanup references
  			if (currentStructures && currentStructures.restoreStructures)
  				restoreStructures();
  			currentStructures = null;
  			src = null;
  			if (referenceMap)
  				referenceMap = null;
  		} else if (position$1 > srcEnd) {
  			// over read
  			throw new Error('Unexpected end of MessagePack data')
  		} else if (!sequentialMode) {
  			throw new Error('Data read, but end of buffer not reached ' + JSON.stringify(result).slice(0, 100))
  		}
  		// else more to read, but we are reading sequentially, so don't clear source yet
  		return result
  	} catch(error) {
  		if (currentStructures && currentStructures.restoreStructures)
  			restoreStructures();
  		clearSource();
  		if (error instanceof RangeError || error.message.startsWith('Unexpected end of buffer') || position$1 > srcEnd) {
  			error.incomplete = true;
  		}
  		throw error
  	}
  }

  function restoreStructures() {
  	for (let id in currentStructures.restoreStructures) {
  		currentStructures[id] = currentStructures.restoreStructures[id];
  	}
  	currentStructures.restoreStructures = null;
  }

  function read() {
  	let token = src[position$1++];
  	if (token < 0xa0) {
  		if (token < 0x80) {
  			if (token < 0x40)
  				return token
  			else {
  				let structure = currentStructures[token & 0x3f] ||
  					currentUnpackr.getStructures && loadStructures()[token & 0x3f];
  				if (structure) {
  					if (!structure.read) {
  						structure.read = createStructureReader(structure, token & 0x3f);
  					}
  					return structure.read()
  				} else
  					return token
  			}
  		} else if (token < 0x90) {
  			// map
  			token -= 0x80;
  			if (currentUnpackr.mapsAsObjects) {
  				let object = {};
  				for (let i = 0; i < token; i++) {
  					let key = readKey$1();
  					if (key === '__proto__')
  						key = '__proto_';
  					object[key] = read();
  				}
  				return object
  			} else {
  				let map = new Map();
  				for (let i = 0; i < token; i++) {
  					map.set(read(), read());
  				}
  				return map
  			}
  		} else {
  			token -= 0x90;
  			let array = new Array(token);
  			for (let i = 0; i < token; i++) {
  				array[i] = read();
  			}
  			if (currentUnpackr.freezeData)
  				return Object.freeze(array)
  			return array
  		}
  	} else if (token < 0xc0) {
  		// fixstr
  		let length = token - 0xa0;
  		if (srcStringEnd >= position$1) {
  			return srcString.slice(position$1 - srcStringStart, (position$1 += length) - srcStringStart)
  		}
  		if (srcStringEnd == 0 && srcEnd < 140) {
  			// for small blocks, avoiding the overhead of the extract call is helpful
  			let string = length < 16 ? shortStringInJS(length) : longStringInJS(length);
  			if (string != null)
  				return string
  		}
  		return readFixedString(length)
  	} else {
  		let value;
  		switch (token) {
  			case 0xc0: return null
  			case 0xc1:
  				if (bundledStrings$1) {
  					value = read(); // followed by the length of the string in characters (not bytes!)
  					if (value > 0)
  						return bundledStrings$1[1].slice(bundledStrings$1.position1, bundledStrings$1.position1 += value)
  					else
  						return bundledStrings$1[0].slice(bundledStrings$1.position0, bundledStrings$1.position0 -= value)
  				}
  				return C1$1; // "never-used", return special object to denote that
  			case 0xc2: return false
  			case 0xc3: return true
  			case 0xc4:
  				// bin 8
  				value = src[position$1++];
  				if (value === undefined)
  					throw new Error('Unexpected end of buffer')
  				return readBin(value)
  			case 0xc5:
  				// bin 16
  				value = dataView.getUint16(position$1);
  				position$1 += 2;
  				return readBin(value)
  			case 0xc6:
  				// bin 32
  				value = dataView.getUint32(position$1);
  				position$1 += 4;
  				return readBin(value)
  			case 0xc7:
  				// ext 8
  				return readExt(src[position$1++])
  			case 0xc8:
  				// ext 16
  				value = dataView.getUint16(position$1);
  				position$1 += 2;
  				return readExt(value)
  			case 0xc9:
  				// ext 32
  				value = dataView.getUint32(position$1);
  				position$1 += 4;
  				return readExt(value)
  			case 0xca:
  				value = dataView.getFloat32(position$1);
  				if (currentUnpackr.useFloat32 > 2) {
  					// this does rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
  					let multiplier = mult10[((src[position$1] & 0x7f) << 1) | (src[position$1 + 1] >> 7)];
  					position$1 += 4;
  					return ((multiplier * value + (value > 0 ? 0.5 : -0.5)) >> 0) / multiplier
  				}
  				position$1 += 4;
  				return value
  			case 0xcb:
  				value = dataView.getFloat64(position$1);
  				position$1 += 8;
  				return value
  			// uint handlers
  			case 0xcc:
  				return src[position$1++]
  			case 0xcd:
  				value = dataView.getUint16(position$1);
  				position$1 += 2;
  				return value
  			case 0xce:
  				value = dataView.getUint32(position$1);
  				position$1 += 4;
  				return value
  			case 0xcf:
  				if (currentUnpackr.int64AsType === 'number') {
  					value = dataView.getUint32(position$1) * 0x100000000;
  					value += dataView.getUint32(position$1 + 4);
  				} else if (currentUnpackr.int64AsType === 'string') {
  					value = dataView.getBigUint64(position$1).toString();
  				} else
  					value = dataView.getBigUint64(position$1);
  				position$1 += 8;
  				return value

  			// int handlers
  			case 0xd0:
  				return dataView.getInt8(position$1++)
  			case 0xd1:
  				value = dataView.getInt16(position$1);
  				position$1 += 2;
  				return value
  			case 0xd2:
  				value = dataView.getInt32(position$1);
  				position$1 += 4;
  				return value
  			case 0xd3:
  				if (currentUnpackr.int64AsType === 'number') {
  					value = dataView.getInt32(position$1) * 0x100000000;
  					value += dataView.getUint32(position$1 + 4);
  				} else if (currentUnpackr.int64AsType === 'string') {
  					value = dataView.getBigInt64(position$1).toString();
  				} else
  					value = dataView.getBigInt64(position$1);
  				position$1 += 8;
  				return value

  			case 0xd4:
  				// fixext 1
  				value = src[position$1++];
  				if (value == 0x72) {
  					return recordDefinition(src[position$1++] & 0x3f)
  				} else {
  					let extension = currentExtensions[value];
  					if (extension) {
  						if (extension.read) {
  							position$1++; // skip filler byte
  							return extension.read(read())
  						} else if (extension.noBuffer) {
  							position$1++; // skip filler byte
  							return extension()
  						} else
  							return extension(src.subarray(position$1, ++position$1))
  					} else
  						throw new Error('Unknown extension ' + value)
  				}
  			case 0xd5:
  				// fixext 2
  				value = src[position$1];
  				if (value == 0x72) {
  					position$1++;
  					return recordDefinition(src[position$1++] & 0x3f, src[position$1++])
  				} else
  					return readExt(2)
  			case 0xd6:
  				// fixext 4
  				return readExt(4)
  			case 0xd7:
  				// fixext 8
  				return readExt(8)
  			case 0xd8:
  				// fixext 16
  				return readExt(16)
  			case 0xd9:
  			// str 8
  				value = src[position$1++];
  				if (srcStringEnd >= position$1) {
  					return srcString.slice(position$1 - srcStringStart, (position$1 += value) - srcStringStart)
  				}
  				return readString8(value)
  			case 0xda:
  			// str 16
  				value = dataView.getUint16(position$1);
  				position$1 += 2;
  				if (srcStringEnd >= position$1) {
  					return srcString.slice(position$1 - srcStringStart, (position$1 += value) - srcStringStart)
  				}
  				return readString16(value)
  			case 0xdb:
  			// str 32
  				value = dataView.getUint32(position$1);
  				position$1 += 4;
  				if (srcStringEnd >= position$1) {
  					return srcString.slice(position$1 - srcStringStart, (position$1 += value) - srcStringStart)
  				}
  				return readString32(value)
  			case 0xdc:
  			// array 16
  				value = dataView.getUint16(position$1);
  				position$1 += 2;
  				return readArray$1(value)
  			case 0xdd:
  			// array 32
  				value = dataView.getUint32(position$1);
  				position$1 += 4;
  				return readArray$1(value)
  			case 0xde:
  			// map 16
  				value = dataView.getUint16(position$1);
  				position$1 += 2;
  				return readMap(value)
  			case 0xdf:
  			// map 32
  				value = dataView.getUint32(position$1);
  				position$1 += 4;
  				return readMap(value)
  			default: // negative int
  				if (token >= 0xe0)
  					return token - 0x100
  				if (token === undefined) {
  					let error = new Error('Unexpected end of MessagePack data');
  					error.incomplete = true;
  					throw error
  				}
  				throw new Error('Unknown MessagePack token ' + token)

  		}
  	}
  }
  const validName = /^[a-zA-Z_$][a-zA-Z\d_$]*$/;
  function createStructureReader(structure, firstId) {
  	function readObject() {
  		// This initial function is quick to instantiate, but runs slower. After several iterations pay the cost to build the faster function
  		if (readObject.count++ > inlineObjectReadThreshold) {
  			let readObject = structure.read = (new Function('r', 'return function(){return ' + (currentUnpackr.freezeData ? 'Object.freeze' : '') +
  				'({' + structure.map(key => key === '__proto__' ? '__proto_:r()' : validName.test(key) ? key + ':r()' : ('[' + JSON.stringify(key) + ']:r()')).join(',') + '})}'))(read);
  			if (structure.highByte === 0)
  				structure.read = createSecondByteReader(firstId, structure.read);
  			return readObject() // second byte is already read, if there is one so immediately read object
  		}
  		let object = {};
  		for (let i = 0, l = structure.length; i < l; i++) {
  			let key = structure[i];
  			if (key === '__proto__')
  				key = '__proto_';
  			object[key] = read();
  		}
  		if (currentUnpackr.freezeData)
  			return Object.freeze(object);
  		return object
  	}
  	readObject.count = 0;
  	if (structure.highByte === 0) {
  		return createSecondByteReader(firstId, readObject)
  	}
  	return readObject
  }

  const createSecondByteReader = (firstId, read0) => {
  	return function() {
  		let highByte = src[position$1++];
  		if (highByte === 0)
  			return read0()
  		let id = firstId < 32 ? -(firstId + (highByte << 5)) : firstId + (highByte << 5);
  		let structure = currentStructures[id] || loadStructures()[id];
  		if (!structure) {
  			throw new Error('Record id is not defined for ' + id)
  		}
  		if (!structure.read)
  			structure.read = createStructureReader(structure, firstId);
  		return structure.read()
  	}
  };

  function loadStructures() {
  	let loadedStructures = saveState(() => {
  		// save the state in case getStructures modifies our buffer
  		src = null;
  		return currentUnpackr.getStructures()
  	});
  	return currentStructures = currentUnpackr._mergeStructures(loadedStructures, currentStructures)
  }

  var readFixedString = readStringJS;
  var readString8 = readStringJS;
  var readString16 = readStringJS;
  var readString32 = readStringJS;
  function readStringJS(length) {
  	let result;
  	if (length < 16) {
  		if (result = shortStringInJS(length))
  			return result
  	}
  	if (length > 64 && decoder)
  		return decoder.decode(src.subarray(position$1, position$1 += length))
  	const end = position$1 + length;
  	const units = [];
  	result = '';
  	while (position$1 < end) {
  		const byte1 = src[position$1++];
  		if ((byte1 & 0x80) === 0) {
  			// 1 byte
  			units.push(byte1);
  		} else if ((byte1 & 0xe0) === 0xc0) {
  			// 2 bytes
  			const byte2 = src[position$1++] & 0x3f;
  			units.push(((byte1 & 0x1f) << 6) | byte2);
  		} else if ((byte1 & 0xf0) === 0xe0) {
  			// 3 bytes
  			const byte2 = src[position$1++] & 0x3f;
  			const byte3 = src[position$1++] & 0x3f;
  			units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);
  		} else if ((byte1 & 0xf8) === 0xf0) {
  			// 4 bytes
  			const byte2 = src[position$1++] & 0x3f;
  			const byte3 = src[position$1++] & 0x3f;
  			const byte4 = src[position$1++] & 0x3f;
  			let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;
  			if (unit > 0xffff) {
  				unit -= 0x10000;
  				units.push(((unit >>> 10) & 0x3ff) | 0xd800);
  				unit = 0xdc00 | (unit & 0x3ff);
  			}
  			units.push(unit);
  		} else {
  			units.push(byte1);
  		}

  		if (units.length >= 0x1000) {
  			result += fromCharCode.apply(String, units);
  			units.length = 0;
  		}
  	}

  	if (units.length > 0) {
  		result += fromCharCode.apply(String, units);
  	}

  	return result
  }

  function readArray$1(length) {
  	let array = new Array(length);
  	for (let i = 0; i < length; i++) {
  		array[i] = read();
  	}
  	if (currentUnpackr.freezeData)
  		return Object.freeze(array)
  	return array
  }

  function readMap(length) {
  	if (currentUnpackr.mapsAsObjects) {
  		let object = {};
  		for (let i = 0; i < length; i++) {
  			let key = readKey$1();
  			if (key === '__proto__')
  				key = '__proto_';
  			object[key] = read();
  		}
  		return object
  	} else {
  		let map = new Map();
  		for (let i = 0; i < length; i++) {
  			map.set(read(), read());
  		}
  		return map
  	}
  }

  var fromCharCode = String.fromCharCode;
  function longStringInJS(length) {
  	let start = position$1;
  	let bytes = new Array(length);
  	for (let i = 0; i < length; i++) {
  		const byte = src[position$1++];
  		if ((byte & 0x80) > 0) {
  				position$1 = start;
  				return
  			}
  			bytes[i] = byte;
  		}
  		return fromCharCode.apply(String, bytes)
  }
  function shortStringInJS(length) {
  	if (length < 4) {
  		if (length < 2) {
  			if (length === 0)
  				return ''
  			else {
  				let a = src[position$1++];
  				if ((a & 0x80) > 1) {
  					position$1 -= 1;
  					return
  				}
  				return fromCharCode(a)
  			}
  		} else {
  			let a = src[position$1++];
  			let b = src[position$1++];
  			if ((a & 0x80) > 0 || (b & 0x80) > 0) {
  				position$1 -= 2;
  				return
  			}
  			if (length < 3)
  				return fromCharCode(a, b)
  			let c = src[position$1++];
  			if ((c & 0x80) > 0) {
  				position$1 -= 3;
  				return
  			}
  			return fromCharCode(a, b, c)
  		}
  	} else {
  		let a = src[position$1++];
  		let b = src[position$1++];
  		let c = src[position$1++];
  		let d = src[position$1++];
  		if ((a & 0x80) > 0 || (b & 0x80) > 0 || (c & 0x80) > 0 || (d & 0x80) > 0) {
  			position$1 -= 4;
  			return
  		}
  		if (length < 6) {
  			if (length === 4)
  				return fromCharCode(a, b, c, d)
  			else {
  				let e = src[position$1++];
  				if ((e & 0x80) > 0) {
  					position$1 -= 5;
  					return
  				}
  				return fromCharCode(a, b, c, d, e)
  			}
  		} else if (length < 8) {
  			let e = src[position$1++];
  			let f = src[position$1++];
  			if ((e & 0x80) > 0 || (f & 0x80) > 0) {
  				position$1 -= 6;
  				return
  			}
  			if (length < 7)
  				return fromCharCode(a, b, c, d, e, f)
  			let g = src[position$1++];
  			if ((g & 0x80) > 0) {
  				position$1 -= 7;
  				return
  			}
  			return fromCharCode(a, b, c, d, e, f, g)
  		} else {
  			let e = src[position$1++];
  			let f = src[position$1++];
  			let g = src[position$1++];
  			let h = src[position$1++];
  			if ((e & 0x80) > 0 || (f & 0x80) > 0 || (g & 0x80) > 0 || (h & 0x80) > 0) {
  				position$1 -= 8;
  				return
  			}
  			if (length < 10) {
  				if (length === 8)
  					return fromCharCode(a, b, c, d, e, f, g, h)
  				else {
  					let i = src[position$1++];
  					if ((i & 0x80) > 0) {
  						position$1 -= 9;
  						return
  					}
  					return fromCharCode(a, b, c, d, e, f, g, h, i)
  				}
  			} else if (length < 12) {
  				let i = src[position$1++];
  				let j = src[position$1++];
  				if ((i & 0x80) > 0 || (j & 0x80) > 0) {
  					position$1 -= 10;
  					return
  				}
  				if (length < 11)
  					return fromCharCode(a, b, c, d, e, f, g, h, i, j)
  				let k = src[position$1++];
  				if ((k & 0x80) > 0) {
  					position$1 -= 11;
  					return
  				}
  				return fromCharCode(a, b, c, d, e, f, g, h, i, j, k)
  			} else {
  				let i = src[position$1++];
  				let j = src[position$1++];
  				let k = src[position$1++];
  				let l = src[position$1++];
  				if ((i & 0x80) > 0 || (j & 0x80) > 0 || (k & 0x80) > 0 || (l & 0x80) > 0) {
  					position$1 -= 12;
  					return
  				}
  				if (length < 14) {
  					if (length === 12)
  						return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l)
  					else {
  						let m = src[position$1++];
  						if ((m & 0x80) > 0) {
  							position$1 -= 13;
  							return
  						}
  						return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m)
  					}
  				} else {
  					let m = src[position$1++];
  					let n = src[position$1++];
  					if ((m & 0x80) > 0 || (n & 0x80) > 0) {
  						position$1 -= 14;
  						return
  					}
  					if (length < 15)
  						return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n)
  					let o = src[position$1++];
  					if ((o & 0x80) > 0) {
  						position$1 -= 15;
  						return
  					}
  					return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)
  				}
  			}
  		}
  	}
  }

  function readOnlyJSString() {
  	let token = src[position$1++];
  	let length;
  	if (token < 0xc0) {
  		// fixstr
  		length = token - 0xa0;
  	} else {
  		switch(token) {
  			case 0xd9:
  			// str 8
  				length = src[position$1++];
  				break
  			case 0xda:
  			// str 16
  				length = dataView.getUint16(position$1);
  				position$1 += 2;
  				break
  			case 0xdb:
  			// str 32
  				length = dataView.getUint32(position$1);
  				position$1 += 4;
  				break
  			default:
  				throw new Error('Expected string')
  		}
  	}
  	return readStringJS(length)
  }


  function readBin(length) {
  	return currentUnpackr.copyBuffers ?
  		// specifically use the copying slice (not the node one)
  		Uint8Array.prototype.slice.call(src, position$1, position$1 += length) :
  		src.subarray(position$1, position$1 += length)
  }
  function readExt(length) {
  	let type = src[position$1++];
  	if (currentExtensions[type]) {
  		let end;
  		return currentExtensions[type](src.subarray(position$1, end = (position$1 += length)), (readPosition) => {
  			position$1 = readPosition;
  			try {
  				return read();
  			} finally {
  				position$1 = end;
  			}
  		})
  	}
  	else
  		throw new Error('Unknown extension type ' + type)
  }

  var keyCache = new Array(4096);
  function readKey$1() {
  	let length = src[position$1++];
  	if (length >= 0xa0 && length < 0xc0) {
  		// fixstr, potentially use key cache
  		length = length - 0xa0;
  		if (srcStringEnd >= position$1) // if it has been extracted, must use it (and faster anyway)
  			return srcString.slice(position$1 - srcStringStart, (position$1 += length) - srcStringStart)
  		else if (!(srcStringEnd == 0 && srcEnd < 180))
  			return readFixedString(length)
  	} else { // not cacheable, go back and do a standard read
  		position$1--;
  		return read().toString()
  	}
  	let key = ((length << 5) ^ (length > 1 ? dataView.getUint16(position$1) : length > 0 ? src[position$1] : 0)) & 0xfff;
  	let entry = keyCache[key];
  	let checkPosition = position$1;
  	let end = position$1 + length - 3;
  	let chunk;
  	let i = 0;
  	if (entry && entry.bytes == length) {
  		while (checkPosition < end) {
  			chunk = dataView.getUint32(checkPosition);
  			if (chunk != entry[i++]) {
  				checkPosition = 0x70000000;
  				break
  			}
  			checkPosition += 4;
  		}
  		end += 3;
  		while (checkPosition < end) {
  			chunk = src[checkPosition++];
  			if (chunk != entry[i++]) {
  				checkPosition = 0x70000000;
  				break
  			}
  		}
  		if (checkPosition === end) {
  			position$1 = checkPosition;
  			return entry.string
  		}
  		end -= 3;
  		checkPosition = position$1;
  	}
  	entry = [];
  	keyCache[key] = entry;
  	entry.bytes = length;
  	while (checkPosition < end) {
  		chunk = dataView.getUint32(checkPosition);
  		entry.push(chunk);
  		checkPosition += 4;
  	}
  	end += 3;
  	while (checkPosition < end) {
  		chunk = src[checkPosition++];
  		entry.push(chunk);
  	}
  	// for small blocks, avoiding the overhead of the extract call is helpful
  	let string = length < 16 ? shortStringInJS(length) : longStringInJS(length);
  	if (string != null)
  		return entry.string = string
  	return entry.string = readFixedString(length)
  }

  // the registration of the record definition extension (as "r")
  const recordDefinition = (id, highByte) => {
  	let structure = read().map(property => property.toString()); // ensure that all keys are strings and that the array is mutable
  	let firstByte = id;
  	if (highByte !== undefined) {
  		id = id < 32 ? -((highByte << 5) + id) : ((highByte << 5) + id);
  		structure.highByte = highByte;
  	}
  	let existingStructure = currentStructures[id];
  	if (existingStructure && existingStructure.isShared) {
  		(currentStructures.restoreStructures || (currentStructures.restoreStructures = []))[id] = existingStructure;
  	}
  	currentStructures[id] = structure;
  	structure.read = createStructureReader(structure, firstByte);
  	return structure.read()
  };
  currentExtensions[0] = () => {}; // notepack defines extension 0 to mean undefined, so use that as the default here
  currentExtensions[0].noBuffer = true;

  currentExtensions[0x65] = () => {
  	let data = read();
  	return (globalThis[data[0]] || Error)(data[1])
  };

  currentExtensions[0x69] = (data) => {
  	// id extension (for structured clones)
  	let id = dataView.getUint32(position$1 - 4);
  	if (!referenceMap)
  		referenceMap = new Map();
  	let token = src[position$1];
  	let target;
  	// TODO: handle Maps, Sets, and other types that can cycle; this is complicated, because you potentially need to read
  	// ahead past references to record structure definitions
  	if (token >= 0x90 && token < 0xa0 || token == 0xdc || token == 0xdd)
  		target = [];
  	else
  		target = {};

  	let refEntry = { target }; // a placeholder object
  	referenceMap.set(id, refEntry);
  	let targetProperties = read(); // read the next value as the target object to id
  	if (refEntry.used) // there is a cycle, so we have to assign properties to original target
  		return Object.assign(target, targetProperties)
  	refEntry.target = targetProperties; // the placeholder wasn't used, replace with the deserialized one
  	return targetProperties // no cycle, can just use the returned read object
  };

  currentExtensions[0x70] = (data) => {
  	// pointer extension (for structured clones)
  	let id = dataView.getUint32(position$1 - 4);
  	let refEntry = referenceMap.get(id);
  	refEntry.used = true;
  	return refEntry.target
  };

  currentExtensions[0x73] = () => new Set(read());

  const typedArrays = ['Int8','Uint8','Uint8Clamped','Int16','Uint16','Int32','Uint32','Float32','Float64','BigInt64','BigUint64'].map(type => type + 'Array');

  currentExtensions[0x74] = (data) => {
  	let typeCode = data[0];
  	let typedArrayName = typedArrays[typeCode];
  	if (!typedArrayName)
  		throw new Error('Could not find typed array for code ' + typeCode)
  	// we have to always slice/copy here to get a new ArrayBuffer that is word/byte aligned
  	return new globalThis[typedArrayName](Uint8Array.prototype.slice.call(data, 1).buffer)
  };
  currentExtensions[0x78] = () => {
  	let data = read();
  	return new RegExp(data[0], data[1])
  };
  const TEMP_BUNDLE = [];
  currentExtensions[0x62] = (data) => {
  	let dataSize = (data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3];
  	let dataPosition = position$1;
  	position$1 += dataSize - data.length;
  	bundledStrings$1 = TEMP_BUNDLE;
  	bundledStrings$1 = [readOnlyJSString(), readOnlyJSString()];
  	bundledStrings$1.position0 = 0;
  	bundledStrings$1.position1 = 0;
  	bundledStrings$1.postBundlePosition = position$1;
  	position$1 = dataPosition;
  	return read()
  };

  currentExtensions[0xff] = (data) => {
  	// 32-bit date extension
  	if (data.length == 4)
  		return new Date((data[0] * 0x1000000 + (data[1] << 16) + (data[2] << 8) + data[3]) * 1000)
  	else if (data.length == 8)
  		return new Date(
  			((data[0] << 22) + (data[1] << 14) + (data[2] << 6) + (data[3] >> 2)) / 1000000 +
  			((data[3] & 0x3) * 0x100000000 + data[4] * 0x1000000 + (data[5] << 16) + (data[6] << 8) + data[7]) * 1000)
  	else if (data.length == 12)// TODO: Implement support for negative
  		return new Date(
  			((data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]) / 1000000 +
  			(((data[4] & 0x80) ? -0x1000000000000 : 0) + data[6] * 0x10000000000 + data[7] * 0x100000000 + data[8] * 0x1000000 + (data[9] << 16) + (data[10] << 8) + data[11]) * 1000)
  	else
  		return new Date('invalid')
  }; // notepack defines extension 0 to mean undefined, so use that as the default here
  // registration of bulk record definition?
  // currentExtensions[0x52] = () =>

  function saveState(callback) {
  	let savedSrcEnd = srcEnd;
  	let savedPosition = position$1;
  	let savedSrcStringStart = srcStringStart;
  	let savedSrcStringEnd = srcStringEnd;
  	let savedSrcString = srcString;
  	let savedReferenceMap = referenceMap;
  	let savedBundledStrings = bundledStrings$1;

  	// TODO: We may need to revisit this if we do more external calls to user code (since it could be slow)
  	let savedSrc = new Uint8Array(src.slice(0, srcEnd)); // we copy the data in case it changes while external data is processed
  	let savedStructures = currentStructures;
  	let savedStructuresContents = currentStructures.slice(0, currentStructures.length);
  	let savedPackr = currentUnpackr;
  	let savedSequentialMode = sequentialMode;
  	let value = callback();
  	srcEnd = savedSrcEnd;
  	position$1 = savedPosition;
  	srcStringStart = savedSrcStringStart;
  	srcStringEnd = savedSrcStringEnd;
  	srcString = savedSrcString;
  	referenceMap = savedReferenceMap;
  	bundledStrings$1 = savedBundledStrings;
  	src = savedSrc;
  	sequentialMode = savedSequentialMode;
  	currentStructures = savedStructures;
  	currentStructures.splice(0, currentStructures.length, ...savedStructuresContents);
  	currentUnpackr = savedPackr;
  	dataView = new DataView(src.buffer, src.byteOffset, src.byteLength);
  	return value
  }
  function clearSource() {
  	src = null;
  	referenceMap = null;
  	currentStructures = null;
  }

  const mult10 = new Array(147); // this is a table matching binary exponents to the multiplier to determine significant digit rounding
  for (let i = 0; i < 256; i++) {
  	mult10[i] = +('1e' + Math.floor(45.15 - i * 0.30103));
  }
  var defaultUnpackr = new Unpackr({ useRecords: false });
  const unpack = defaultUnpackr.unpack;
  defaultUnpackr.unpackMultiple;
  defaultUnpackr.unpack;
  let f32Array = new Float32Array(1);
  new Uint8Array(f32Array.buffer, 0, 4);

  let textEncoder;
  try {
  	textEncoder = new TextEncoder();
  } catch (error) {}
  let extensions, extensionClasses;
  const hasNodeBuffer = typeof Buffer !== 'undefined';
  const ByteArrayAllocate = hasNodeBuffer ?
  	function(length) { return Buffer.allocUnsafeSlow(length) } : Uint8Array;
  const ByteArray = hasNodeBuffer ? Buffer : Uint8Array;
  const MAX_BUFFER_SIZE = hasNodeBuffer ? 0x100000000 : 0x7fd00000;
  let target, keysTarget;
  let targetView;
  let position = 0;
  let safeEnd;
  let bundledStrings = null;
  let writeStructSlots;
  const MAX_BUNDLE_SIZE = 0x5500; // maximum characters such that the encoded bytes fits in 16 bits.
  const hasNonLatin = /[\u0080-\uFFFF]/;
  const RECORD_SYMBOL = Symbol('record-id');
  class Packr extends Unpackr {
  	constructor(options) {
  		super(options);
  		this.offset = 0;
  		let start;
  		let hasSharedUpdate;
  		let structures;
  		let referenceMap;
  		let encodeUtf8 = ByteArray.prototype.utf8Write ? function(string, position) {
  			return target.utf8Write(string, position, 0xffffffff)
  		} : (textEncoder && textEncoder.encodeInto) ?
  			function(string, position) {
  				return textEncoder.encodeInto(string, target.subarray(position)).written
  			} : false;

  		let packr = this;
  		if (!options)
  			options = {};
  		let isSequential = options && options.sequential;
  		let hasSharedStructures = options.structures || options.saveStructures;
  		let maxSharedStructures = options.maxSharedStructures;
  		if (maxSharedStructures == null)
  			maxSharedStructures = hasSharedStructures ? 32 : 0;
  		if (maxSharedStructures > 8160)
  			throw new Error('Maximum maxSharedStructure is 8160')
  		if (options.structuredClone && options.moreTypes == undefined) {
  			this.moreTypes = true;
  		}
  		let maxOwnStructures = options.maxOwnStructures;
  		if (maxOwnStructures == null)
  			maxOwnStructures = hasSharedStructures ? 32 : 64;
  		if (!this.structures && options.useRecords != false)
  			this.structures = [];
  		// two byte record ids for shared structures
  		let useTwoByteRecords = maxSharedStructures > 32 || (maxOwnStructures + maxSharedStructures > 64);		
  		let sharedLimitId = maxSharedStructures + 0x40;
  		let maxStructureId = maxSharedStructures + maxOwnStructures + 0x40;
  		if (maxStructureId > 8256) {
  			throw new Error('Maximum maxSharedStructure + maxOwnStructure is 8192')
  		}
  		let recordIdsToRemove = [];
  		let transitionsCount = 0;
  		let serializationsSinceTransitionRebuild = 0;

  		this.pack = this.encode = function(value, encodeOptions) {
  			if (!target) {
  				target = new ByteArrayAllocate(8192);
  				targetView = target.dataView || (target.dataView = new DataView(target.buffer, 0, 8192));
  				position = 0;
  			}
  			safeEnd = target.length - 10;
  			if (safeEnd - position < 0x800) {
  				// don't start too close to the end, 
  				target = new ByteArrayAllocate(target.length);
  				targetView = target.dataView || (target.dataView = new DataView(target.buffer, 0, target.length));
  				safeEnd = target.length - 10;
  				position = 0;
  			} else
  				position = (position + 7) & 0x7ffffff8; // Word align to make any future copying of this buffer faster
  			start = position;
  			referenceMap = packr.structuredClone ? new Map() : null;
  			if (packr.bundleStrings && typeof value !== 'string') {
  				bundledStrings = [];
  				bundledStrings.size = Infinity; // force a new bundle start on first string
  			} else
  				bundledStrings = null;
  			structures = packr.structures;
  			if (structures) {
  				if (structures.uninitialized)
  					structures = packr._mergeStructures(packr.getStructures());
  				let sharedLength = structures.sharedLength || 0;
  				if (sharedLength > maxSharedStructures) {
  					//if (maxSharedStructures <= 32 && structures.sharedLength > 32) // TODO: could support this, but would need to update the limit ids
  					throw new Error('Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to ' + structures.sharedLength)
  				}
  				if (!structures.transitions) {
  					// rebuild our structure transitions
  					structures.transitions = Object.create(null);
  					for (let i = 0; i < sharedLength; i++) {
  						let keys = structures[i];
  						if (!keys)
  							continue
  						let nextTransition, transition = structures.transitions;
  						for (let j = 0, l = keys.length; j < l; j++) {
  							let key = keys[j];
  							nextTransition = transition[key];
  							if (!nextTransition) {
  								nextTransition = transition[key] = Object.create(null);
  							}
  							transition = nextTransition;
  						}
  						transition[RECORD_SYMBOL] = i + 0x40;
  					}
  					this.lastNamedStructuresLength = sharedLength;
  				}
  				if (!isSequential) {
  					structures.nextId = sharedLength + 0x40;
  				}
  			}
  			if (hasSharedUpdate)
  				hasSharedUpdate = false;
  			try {
  				if (packr.randomAccessStructure && value.constructor && value.constructor === Object)
  					writeStruct(value);
  				else
  					pack(value);
  				let lastBundle = bundledStrings;
  				if (bundledStrings)
  					writeBundles(start, pack, 0);
  				if (referenceMap && referenceMap.idsToInsert) {
  					let idsToInsert = referenceMap.idsToInsert.sort((a, b) => a.offset > b.offset ? 1 : -1);
  					let i = idsToInsert.length;
  					let incrementPosition = -1;
  					while (lastBundle && i > 0) {
  						let insertionPoint = idsToInsert[--i].offset + start;
  						if (insertionPoint < (lastBundle.stringsPosition + start) && incrementPosition === -1)
  							incrementPosition = 0;
  						if (insertionPoint > (lastBundle.position + start)) {
  							if (incrementPosition >= 0)
  								incrementPosition += 6;
  						} else {
  							if (incrementPosition >= 0) {
  								// update the bundle reference now
  								targetView.setUint32(lastBundle.position + start,
  									targetView.getUint32(lastBundle.position + start) + incrementPosition);
  								incrementPosition = -1; // reset
  							}
  							lastBundle = lastBundle.previous;
  							i++;
  						}
  					}
  					if (incrementPosition >= 0 && lastBundle) {
  						// update the bundle reference now
  						targetView.setUint32(lastBundle.position + start,
  							targetView.getUint32(lastBundle.position + start) + incrementPosition);
  					}
  					position += idsToInsert.length * 6;
  					if (position > safeEnd)
  						makeRoom(position);
  					packr.offset = position;
  					let serialized = insertIds(target.subarray(start, position), idsToInsert);
  					referenceMap = null;
  					return serialized
  				}
  				packr.offset = position; // update the offset so next serialization doesn't write over our buffer, but can continue writing to same buffer sequentially
  				if (encodeOptions & REUSE_BUFFER_MODE) {
  					target.start = start;
  					target.end = position;
  					return target
  				}
  				return target.subarray(start, position) // position can change if we call pack again in saveStructures, so we get the buffer now
  			} finally {
  				if (structures) {
  					if (serializationsSinceTransitionRebuild < 10)
  						serializationsSinceTransitionRebuild++;
  					let sharedLength = structures.sharedLength || 0;
  					if (structures.length > sharedLength)
  						structures.length = sharedLength;
  					if (transitionsCount > 10000) {
  						// force a rebuild occasionally after a lot of transitions so it can get cleaned up
  						structures.transitions = null;
  						serializationsSinceTransitionRebuild = 0;
  						transitionsCount = 0;
  						if (recordIdsToRemove.length > 0)
  							recordIdsToRemove = [];
  					} else if (recordIdsToRemove.length > 0 && !isSequential) {
  						for (let i = 0, l = recordIdsToRemove.length; i < l; i++) {
  							recordIdsToRemove[i][RECORD_SYMBOL] = 0;
  						}
  						recordIdsToRemove = [];
  					}
  					if (hasSharedUpdate && packr.saveStructures) {
  						// we can't rely on start/end with REUSE_BUFFER_MODE since they will (probably) change when we save
  						let returnBuffer = target.subarray(start, position);
  						let newSharedData = prepareStructures(structures, packr);
  						if (packr.saveStructures(newSharedData, newSharedData.isCompatible) === false) {
  							// get updated structures and try again if the update failed
  							return packr.pack(value)
  						}
  						packr.lastNamedStructuresLength = sharedLength;
  						return returnBuffer
  					}
  				}
  				if (encodeOptions & RESET_BUFFER_MODE)
  					position = start;
  			}
  		};
  		const packArray = (value) => {
  			var length = value.length;
  			if (length < 0x10) {
  				target[position++] = 0x90 | length;
  			} else if (length < 0x10000) {
  				target[position++] = 0xdc;
  				target[position++] = length >> 8;
  				target[position++] = length & 0xff;
  			} else {
  				target[position++] = 0xdd;
  				targetView.setUint32(position, length);
  				position += 4;
  			}
  			for (let i = 0; i < length; i++) {
  				pack(value[i]);
  			}
  		};
  		const pack = (value) => {
  			if (position > safeEnd)
  				target = makeRoom(position);

  			var type = typeof value;
  			var length;
  			if (type === 'string') {
  				let strLength = value.length;
  				if (bundledStrings && strLength >= 4 && strLength < 0x1000) {
  					if ((bundledStrings.size += strLength) > MAX_BUNDLE_SIZE) {
  						let extStart;
  						let maxBytes = (bundledStrings[0] ? bundledStrings[0].length * 3 + bundledStrings[1].length : 0) + 10;
  						if (position + maxBytes > safeEnd)
  							target = makeRoom(position + maxBytes);
  						let lastBundle;
  						if (bundledStrings.position) { // here we use the 0x62 extension to write the last bundle and reserve space for the reference pointer to the next/current bundle
  							lastBundle = bundledStrings;
  							target[position] = 0xc8; // ext 16
  							position += 3; // reserve for the writing bundle size
  							target[position++] = 0x62; // 'b'
  							extStart = position - start;
  							position += 4; // reserve for writing bundle reference
  							writeBundles(start, pack, 0); // write the last bundles
  							targetView.setUint16(extStart + start - 3, position - start - extStart);
  						} else { // here we use the 0x62 extension just to reserve the space for the reference pointer to the bundle (will be updated once the bundle is written)
  							target[position++] = 0xd6; // fixext 4
  							target[position++] = 0x62; // 'b'
  							extStart = position - start;
  							position += 4; // reserve for writing bundle reference
  						}
  						bundledStrings = ['', '']; // create new ones
  						bundledStrings.previous = lastBundle;
  						bundledStrings.size = 0;
  						bundledStrings.position = extStart;
  					}
  					let twoByte = hasNonLatin.test(value);
  					bundledStrings[twoByte ? 0 : 1] += value;
  					target[position++] = 0xc1;
  					pack(twoByte ? -strLength : strLength);
  					return
  				}
  				let headerSize;
  				// first we estimate the header size, so we can write to the correct location
  				if (strLength < 0x20) {
  					headerSize = 1;
  				} else if (strLength < 0x100) {
  					headerSize = 2;
  				} else if (strLength < 0x10000) {
  					headerSize = 3;
  				} else {
  					headerSize = 5;
  				}
  				let maxBytes = strLength * 3;
  				if (position + maxBytes > safeEnd)
  					target = makeRoom(position + maxBytes);

  				if (strLength < 0x40 || !encodeUtf8) {
  					let i, c1, c2, strPosition = position + headerSize;
  					for (i = 0; i < strLength; i++) {
  						c1 = value.charCodeAt(i);
  						if (c1 < 0x80) {
  							target[strPosition++] = c1;
  						} else if (c1 < 0x800) {
  							target[strPosition++] = c1 >> 6 | 0xc0;
  							target[strPosition++] = c1 & 0x3f | 0x80;
  						} else if (
  							(c1 & 0xfc00) === 0xd800 &&
  							((c2 = value.charCodeAt(i + 1)) & 0xfc00) === 0xdc00
  						) {
  							c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);
  							i++;
  							target[strPosition++] = c1 >> 18 | 0xf0;
  							target[strPosition++] = c1 >> 12 & 0x3f | 0x80;
  							target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
  							target[strPosition++] = c1 & 0x3f | 0x80;
  						} else {
  							target[strPosition++] = c1 >> 12 | 0xe0;
  							target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
  							target[strPosition++] = c1 & 0x3f | 0x80;
  						}
  					}
  					length = strPosition - position - headerSize;
  				} else {
  					length = encodeUtf8(value, position + headerSize);
  				}

  				if (length < 0x20) {
  					target[position++] = 0xa0 | length;
  				} else if (length < 0x100) {
  					if (headerSize < 2) {
  						target.copyWithin(position + 2, position + 1, position + 1 + length);
  					}
  					target[position++] = 0xd9;
  					target[position++] = length;
  				} else if (length < 0x10000) {
  					if (headerSize < 3) {
  						target.copyWithin(position + 3, position + 2, position + 2 + length);
  					}
  					target[position++] = 0xda;
  					target[position++] = length >> 8;
  					target[position++] = length & 0xff;
  				} else {
  					if (headerSize < 5) {
  						target.copyWithin(position + 5, position + 3, position + 3 + length);
  					}
  					target[position++] = 0xdb;
  					targetView.setUint32(position, length);
  					position += 4;
  				}
  				position += length;
  			} else if (type === 'number') {
  				if (value >>> 0 === value) {// positive integer, 32-bit or less
  					// positive uint
  					if (value < 0x20 || (value < 0x80 && this.useRecords === false) || (value < 0x40 && !this.randomAccessStructure)) {
  						target[position++] = value;
  					} else if (value < 0x100) {
  						target[position++] = 0xcc;
  						target[position++] = value;
  					} else if (value < 0x10000) {
  						target[position++] = 0xcd;
  						target[position++] = value >> 8;
  						target[position++] = value & 0xff;
  					} else {
  						target[position++] = 0xce;
  						targetView.setUint32(position, value);
  						position += 4;
  					}
  				} else if (value >> 0 === value) { // negative integer
  					if (value >= -0x20) {
  						target[position++] = 0x100 + value;
  					} else if (value >= -0x80) {
  						target[position++] = 0xd0;
  						target[position++] = value + 0x100;
  					} else if (value >= -0x8000) {
  						target[position++] = 0xd1;
  						targetView.setInt16(position, value);
  						position += 2;
  					} else {
  						target[position++] = 0xd2;
  						targetView.setInt32(position, value);
  						position += 4;
  					}
  				} else {
  					let useFloat32;
  					if ((useFloat32 = this.useFloat32) > 0 && value < 0x100000000 && value >= -0x80000000) {
  						target[position++] = 0xca;
  						targetView.setFloat32(position, value);
  						let xShifted;
  						if (useFloat32 < 4 ||
  								// this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
  								((xShifted = value * mult10[((target[position] & 0x7f) << 1) | (target[position + 1] >> 7)]) >> 0) === xShifted) {
  							position += 4;
  							return
  						} else
  							position--; // move back into position for writing a double
  					}
  					target[position++] = 0xcb;
  					targetView.setFloat64(position, value);
  					position += 8;
  				}
  			} else if (type === 'object') {
  				if (!value)
  					target[position++] = 0xc0;
  				else {
  					if (referenceMap) {
  						let referee = referenceMap.get(value);
  						if (referee) {
  							if (!referee.id) {
  								let idsToInsert = referenceMap.idsToInsert || (referenceMap.idsToInsert = []);
  								referee.id = idsToInsert.push(referee);
  							}
  							target[position++] = 0xd6; // fixext 4
  							target[position++] = 0x70; // "p" for pointer
  							targetView.setUint32(position, referee.id);
  							position += 4;
  							return
  						} else 
  							referenceMap.set(value, { offset: position - start });
  					}
  					let constructor = value.constructor;
  					if (constructor === Object) {
  						writeObject(value, true);
  					} else if (constructor === Array) {
  						packArray(value);
  					} else if (constructor === Map) {
  						length = value.size;
  						if (length < 0x10) {
  							target[position++] = 0x80 | length;
  						} else if (length < 0x10000) {
  							target[position++] = 0xde;
  							target[position++] = length >> 8;
  							target[position++] = length & 0xff;
  						} else {
  							target[position++] = 0xdf;
  							targetView.setUint32(position, length);
  							position += 4;
  						}
  						for (let [ key, entryValue ] of value) {
  							pack(key);
  							pack(entryValue);
  						}
  					} else {	
  						for (let i = 0, l = extensions.length; i < l; i++) {
  							let extensionClass = extensionClasses[i];
  							if (value instanceof extensionClass) {
  								let extension = extensions[i];
  								if (extension.write) {
  									if (extension.type) {
  										target[position++] = 0xd4; // one byte "tag" extension
  										target[position++] = extension.type;
  										target[position++] = 0;
  									}
  									let writeResult = extension.write.call(this, value);
  									if (writeResult === value) { // avoid infinite recursion
  										if (Array.isArray(value)) {
  											packArray(value);
  										} else {
  											writeObject(value);
  										}
  									} else {
  										pack(writeResult);
  									}
  									return
  								}
  								let currentTarget = target;
  								let currentTargetView = targetView;
  								let currentPosition = position;
  								target = null;
  								let result;
  								try {
  									result = extension.pack.call(this, value, (size) => {
  										// restore target and use it
  										target = currentTarget;
  										currentTarget = null;
  										position += size;
  										if (position > safeEnd)
  											makeRoom(position);
  										return {
  											target, targetView, position: position - size
  										}
  									}, pack);
  								} finally {
  									// restore current target information (unless already restored)
  									if (currentTarget) {
  										target = currentTarget;
  										targetView = currentTargetView;
  										position = currentPosition;
  										safeEnd = target.length - 10;
  									}
  								}
  								if (result) {
  									if (result.length + position > safeEnd)
  										makeRoom(result.length + position);
  									position = writeExtensionData(result, target, position, extension.type);
  								}
  								return
  							}
  						}
  						// check isArray after extensions, because extensions can extend Array
  						if (Array.isArray(value)) {
  							packArray(value);
  						} else {
  							// no extension found, write as object
  							writeObject(value, !value.hasOwnProperty); // if it doesn't have hasOwnProperty, don't do hasOwnProperty checks
  						}
  					}
  				}
  			} else if (type === 'boolean') {
  				target[position++] = value ? 0xc3 : 0xc2;
  			} else if (type === 'bigint') {
  				if (value < (BigInt(1)<<BigInt(63)) && value >= -(BigInt(1)<<BigInt(63))) {
  					// use a signed int as long as it fits
  					target[position++] = 0xd3;
  					targetView.setBigInt64(position, value);
  				} else if (value < (BigInt(1)<<BigInt(64)) && value > 0) {
  					// if we can fit an unsigned int, use that
  					target[position++] = 0xcf;
  					targetView.setBigUint64(position, value);
  				} else {
  					// overflow
  					if (this.largeBigIntToFloat) {
  						target[position++] = 0xcb;
  						targetView.setFloat64(position, Number(value));
  					} else {
  						throw new RangeError(value + ' was too large to fit in MessagePack 64-bit integer format, set largeBigIntToFloat to convert to float-64')
  					}
  				}
  				position += 8;
  			} else if (type === 'undefined') {
  				if (this.encodeUndefinedAsNil)
  					target[position++] = 0xc0;
  				else {
  					target[position++] = 0xd4; // a number of implementations use fixext1 with type 0, data 0 to denote undefined, so we follow suite
  					target[position++] = 0;
  					target[position++] = 0;
  				}
  			} else if (type === 'function') {
  				pack(this.writeFunction && this.writeFunction()); // if there is a writeFunction, use it, otherwise just encode as undefined
  			} else {
  				throw new Error('Unknown type: ' + type)
  			}
  		};

  		const writeObject = this.useRecords === false ? this.variableMapSize ? (object) => {
  			// this method is slightly slower, but generates "preferred serialization" (optimally small for smaller objects)
  			let keys = Object.keys(object);
  			let length = keys.length;
  			if (length < 0x10) {
  				target[position++] = 0x80 | length;
  			} else if (length < 0x10000) {
  				target[position++] = 0xde;
  				target[position++] = length >> 8;
  				target[position++] = length & 0xff;
  			} else {
  				target[position++] = 0xdf;
  				targetView.setUint32(position, length);
  				position += 4;
  			}
  			let key;
  			for (let i = 0; i < length; i++) {
  				pack(key = keys[i]);
  				pack(object[key]);
  			}
  		} :
  		(object, safePrototype) => {
  			target[position++] = 0xde; // always using map 16, so we can preallocate and set the length afterwards
  			let objectOffset = position - start;
  			position += 2;
  			let size = 0;
  			for (let key in object) {
  				if (safePrototype || object.hasOwnProperty(key)) {
  					pack(key);
  					pack(object[key]);
  					size++;
  				}
  			}
  			target[objectOffset++ + start] = size >> 8;
  			target[objectOffset + start] = size & 0xff;
  		} :
  		(options.progressiveRecords && !useTwoByteRecords) ?  // this is about 2% faster for highly stable structures, since it only requires one for-in loop (but much more expensive when new structure needs to be written)
  		(object, safePrototype) => {
  			let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));
  			let objectOffset = position++ - start;
  			let wroteKeys;
  			for (let key in object) {
  				if (safePrototype || object.hasOwnProperty(key)) {
  					nextTransition = transition[key];
  					if (nextTransition)
  						transition = nextTransition;
  					else {
  						// record doesn't exist, create full new record and insert it
  						let keys = Object.keys(object);
  						let lastTransition = transition;
  						transition = structures.transitions;
  						let newTransitions = 0;
  						for (let i = 0, l = keys.length; i < l; i++) {
  							let key = keys[i];
  							nextTransition = transition[key];
  							if (!nextTransition) {
  								nextTransition = transition[key] = Object.create(null);
  								newTransitions++;
  							}
  							transition = nextTransition;
  						}
  						if (objectOffset + start + 1 == position) {
  							// first key, so we don't need to insert, we can just write record directly
  							position--;
  							newRecord(transition, keys, newTransitions);
  						} else // otherwise we need to insert the record, moving existing data after the record
  							insertNewRecord(transition, keys, objectOffset, newTransitions);
  						wroteKeys = true;
  						transition = lastTransition[key];
  					}
  					pack(object[key]);
  				}
  			}
  			if (!wroteKeys) {
  				let recordId = transition[RECORD_SYMBOL];
  				if (recordId)
  					target[objectOffset + start] = recordId;
  				else
  					insertNewRecord(transition, Object.keys(object), objectOffset, 0);
  			}
  		} :
  		(object, safePrototype) => {
  			let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));
  			let newTransitions = 0;
  			for (let key in object) if (safePrototype || object.hasOwnProperty(key)) {
  				nextTransition = transition[key];
  				if (!nextTransition) {
  					nextTransition = transition[key] = Object.create(null);
  					newTransitions++;
  				}
  				transition = nextTransition;
  			}
  			let recordId = transition[RECORD_SYMBOL];
  			if (recordId) {
  				if (recordId >= 0x60 && useTwoByteRecords) {
  					target[position++] = ((recordId -= 0x60) & 0x1f) + 0x60;
  					target[position++] = recordId >> 5;
  				} else
  					target[position++] = recordId;
  			} else {
  				newRecord(transition, transition.__keys__ || Object.keys(object), newTransitions);
  			}
  			// now write the values
  			for (let key in object)
  				if (safePrototype || object.hasOwnProperty(key))
  					pack(object[key]);
  		};
  		const makeRoom = (end) => {
  			let newSize;
  			if (end > 0x1000000) {
  				// special handling for really large buffers
  				if ((end - start) > MAX_BUFFER_SIZE)
  					throw new Error('Packed buffer would be larger than maximum buffer size')
  				newSize = Math.min(MAX_BUFFER_SIZE,
  					Math.round(Math.max((end - start) * (end > 0x4000000 ? 1.25 : 2), 0x400000) / 0x1000) * 0x1000);
  			} else // faster handling for smaller buffers
  				newSize = ((Math.max((end - start) << 2, target.length - 1) >> 12) + 1) << 12;
  			let newBuffer = new ByteArrayAllocate(newSize);
  			targetView = newBuffer.dataView || (newBuffer.dataView = new DataView(newBuffer.buffer, 0, newSize));
  			end = Math.min(end, target.length);
  			if (target.copy)
  				target.copy(newBuffer, 0, start, end);
  			else
  				newBuffer.set(target.slice(start, end));
  			position -= start;
  			start = 0;
  			safeEnd = newBuffer.length - 10;
  			return target = newBuffer
  		};
  		const newRecord = (transition, keys, newTransitions) => {
  			let recordId = structures.nextId;
  			if (!recordId)
  				recordId = 0x40;
  			if (recordId < sharedLimitId && this.shouldShareStructure && !this.shouldShareStructure(keys)) {
  				recordId = structures.nextOwnId;
  				if (!(recordId < maxStructureId))
  					recordId = sharedLimitId;
  				structures.nextOwnId = recordId + 1;
  			} else {
  				if (recordId >= maxStructureId)// cycle back around
  					recordId = sharedLimitId;
  				structures.nextId = recordId + 1;
  			}
  			let highByte = keys.highByte = recordId >= 0x60 && useTwoByteRecords ? (recordId - 0x60) >> 5 : -1;
  			transition[RECORD_SYMBOL] = recordId;
  			transition.__keys__ = keys;
  			structures[recordId - 0x40] = keys;

  			if (recordId < sharedLimitId) {
  				keys.isShared = true;
  				structures.sharedLength = recordId - 0x3f;
  				hasSharedUpdate = true;
  				if (highByte >= 0) {
  					target[position++] = (recordId & 0x1f) + 0x60;
  					target[position++] = highByte;
  				} else {
  					target[position++] = recordId;
  				}
  			} else {
  				if (highByte >= 0) {
  					target[position++] = 0xd5; // fixext 2
  					target[position++] = 0x72; // "r" record defintion extension type
  					target[position++] = (recordId & 0x1f) + 0x60;
  					target[position++] = highByte;
  				} else {
  					target[position++] = 0xd4; // fixext 1
  					target[position++] = 0x72; // "r" record defintion extension type
  					target[position++] = recordId;
  				}

  				if (newTransitions)
  					transitionsCount += serializationsSinceTransitionRebuild * newTransitions;
  				// record the removal of the id, we can maintain our shared structure
  				if (recordIdsToRemove.length >= maxOwnStructures)
  					recordIdsToRemove.shift()[RECORD_SYMBOL] = 0; // we are cycling back through, and have to remove old ones
  				recordIdsToRemove.push(transition);
  				pack(keys);
  			}
  		};
  		const insertNewRecord = (transition, keys, insertionOffset, newTransitions) => {
  			let mainTarget = target;
  			let mainPosition = position;
  			let mainSafeEnd = safeEnd;
  			let mainStart = start;
  			target = keysTarget;
  			position = 0;
  			start = 0;
  			if (!target)
  				keysTarget = target = new ByteArrayAllocate(8192);
  			safeEnd = target.length - 10;
  			newRecord(transition, keys, newTransitions);
  			keysTarget = target;
  			let keysPosition = position;
  			target = mainTarget;
  			position = mainPosition;
  			safeEnd = mainSafeEnd;
  			start = mainStart;
  			if (keysPosition > 1) {
  				let newEnd = position + keysPosition - 1;
  				if (newEnd > safeEnd)
  					makeRoom(newEnd);
  				let insertionPosition = insertionOffset + start;
  				target.copyWithin(insertionPosition + keysPosition, insertionPosition + 1, position);
  				target.set(keysTarget.slice(0, keysPosition), insertionPosition);
  				position = newEnd;
  			} else {
  				target[insertionOffset + start] = keysTarget[0];
  			}
  		};
  		const writeStruct = (object, safePrototype) => {
  			let newPosition = writeStructSlots(object, target, position, structures, makeRoom, (value, newPosition, notifySharedUpdate) => {
  				if (notifySharedUpdate)
  					return hasSharedUpdate = true;
  				position = newPosition;
  				let startTarget = target;
  				pack(value);
  				if (startTarget !== target) {
  					return { position, targetView, target }; // indicate the buffer was re-allocated
  				}
  				return position;
  			}, this);
  			if (newPosition === 0) // bail and go to a msgpack object
  				return writeObject(object, true);
  			position = newPosition;
  		};
  	}
  	useBuffer(buffer) {
  		// this means we are finished using our own buffer and we can write over it safely
  		target = buffer;
  		targetView = new DataView(target.buffer, target.byteOffset, target.byteLength);
  		position = 0;
  	}
  	clearSharedData() {
  		if (this.structures)
  			this.structures = [];
  		if (this.typedStructs)
  			this.typedStructs = [];
  	}
  }

  extensionClasses = [ Date, Set, Error, RegExp, ArrayBuffer, Object.getPrototypeOf(Uint8Array.prototype).constructor /*TypedArray*/, C1Type ];
  extensions = [{
  	pack(date, allocateForWrite, pack) {
  		let seconds = date.getTime() / 1000;
  		if ((this.useTimestamp32 || date.getMilliseconds() === 0) && seconds >= 0 && seconds < 0x100000000) {
  			// Timestamp 32
  			let { target, targetView, position} = allocateForWrite(6);
  			target[position++] = 0xd6;
  			target[position++] = 0xff;
  			targetView.setUint32(position, seconds);
  		} else if (seconds > 0 && seconds < 0x100000000) {
  			// Timestamp 64
  			let { target, targetView, position} = allocateForWrite(10);
  			target[position++] = 0xd7;
  			target[position++] = 0xff;
  			targetView.setUint32(position, date.getMilliseconds() * 4000000 + ((seconds / 1000 / 0x100000000) >> 0));
  			targetView.setUint32(position + 4, seconds);
  		} else if (isNaN(seconds)) {
  			if (this.onInvalidDate) {
  				allocateForWrite(0);
  				return pack(this.onInvalidDate())
  			}
  			// Intentionally invalid timestamp
  			let { target, targetView, position} = allocateForWrite(3);
  			target[position++] = 0xd4;
  			target[position++] = 0xff;
  			target[position++] = 0xff;
  		} else {
  			// Timestamp 96
  			let { target, targetView, position} = allocateForWrite(15);
  			target[position++] = 0xc7;
  			target[position++] = 12;
  			target[position++] = 0xff;
  			targetView.setUint32(position, date.getMilliseconds() * 1000000);
  			targetView.setBigInt64(position + 4, BigInt(Math.floor(seconds)));
  		}
  	}
  }, {
  	pack(set, allocateForWrite, pack) {
  		let array = Array.from(set);
  		let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
  		if (this.moreTypes) {
  			target[position++] = 0xd4;
  			target[position++] = 0x73; // 's' for Set
  			target[position++] = 0;
  		}
  		pack(array);
  	}
  }, {
  	pack(error, allocateForWrite, pack) {
  		let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
  		if (this.moreTypes) {
  			target[position++] = 0xd4;
  			target[position++] = 0x65; // 'e' for error
  			target[position++] = 0;
  		}
  		pack([ error.name, error.message ]);
  	}
  }, {
  	pack(regex, allocateForWrite, pack) {
  		let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
  		if (this.moreTypes) {
  			target[position++] = 0xd4;
  			target[position++] = 0x78; // 'x' for regeXp
  			target[position++] = 0;
  		}
  		pack([ regex.source, regex.flags ]);
  	}
  }, {
  	pack(arrayBuffer, allocateForWrite) {
  		if (this.moreTypes)
  			writeExtBuffer(arrayBuffer, 0x10, allocateForWrite);
  		else
  			writeBuffer(hasNodeBuffer ? Buffer.from(arrayBuffer) : new Uint8Array(arrayBuffer), allocateForWrite);
  	}
  }, {
  	pack(typedArray, allocateForWrite) {
  		let constructor = typedArray.constructor;
  		if (constructor !== ByteArray && this.moreTypes)
  			writeExtBuffer(typedArray, typedArrays.indexOf(constructor.name), allocateForWrite);
  		else
  			writeBuffer(typedArray, allocateForWrite);
  	}
  }, {
  	pack(c1, allocateForWrite) { // specific 0xC1 object
  		let { target, position} = allocateForWrite(1);
  		target[position] = 0xc1;
  	}
  }];

  function writeExtBuffer(typedArray, type, allocateForWrite, encode) {
  	let length = typedArray.byteLength;
  	if (length + 1 < 0x100) {
  		var { target, position } = allocateForWrite(4 + length);
  		target[position++] = 0xc7;
  		target[position++] = length + 1;
  	} else if (length + 1 < 0x10000) {
  		var { target, position } = allocateForWrite(5 + length);
  		target[position++] = 0xc8;
  		target[position++] = (length + 1) >> 8;
  		target[position++] = (length + 1) & 0xff;
  	} else {
  		var { target, position, targetView } = allocateForWrite(7 + length);
  		target[position++] = 0xc9;
  		targetView.setUint32(position, length + 1); // plus one for the type byte
  		position += 4;
  	}
  	target[position++] = 0x74; // "t" for typed array
  	target[position++] = type;
  	target.set(new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength), position);
  }
  function writeBuffer(buffer, allocateForWrite) {
  	let length = buffer.byteLength;
  	var target, position;
  	if (length < 0x100) {
  		var { target, position } = allocateForWrite(length + 2);
  		target[position++] = 0xc4;
  		target[position++] = length;
  	} else if (length < 0x10000) {
  		var { target, position } = allocateForWrite(length + 3);
  		target[position++] = 0xc5;
  		target[position++] = length >> 8;
  		target[position++] = length & 0xff;
  	} else {
  		var { target, position, targetView } = allocateForWrite(length + 5);
  		target[position++] = 0xc6;
  		targetView.setUint32(position, length);
  		position += 4;
  	}
  	target.set(buffer, position);
  }

  function writeExtensionData(result, target, position, type) {
  	let length = result.length;
  	switch (length) {
  		case 1:
  			target[position++] = 0xd4;
  			break
  		case 2:
  			target[position++] = 0xd5;
  			break
  		case 4:
  			target[position++] = 0xd6;
  			break
  		case 8:
  			target[position++] = 0xd7;
  			break
  		case 16:
  			target[position++] = 0xd8;
  			break
  		default:
  			if (length < 0x100) {
  				target[position++] = 0xc7;
  				target[position++] = length;
  			} else if (length < 0x10000) {
  				target[position++] = 0xc8;
  				target[position++] = length >> 8;
  				target[position++] = length & 0xff;
  			} else {
  				target[position++] = 0xc9;
  				target[position++] = length >> 24;
  				target[position++] = (length >> 16) & 0xff;
  				target[position++] = (length >> 8) & 0xff;
  				target[position++] = length & 0xff;
  			}
  	}
  	target[position++] = type;
  	target.set(result, position);
  	position += length;
  	return position
  }

  function insertIds(serialized, idsToInsert) {
  	// insert the ids that need to be referenced for structured clones
  	let nextId;
  	let distanceToMove = idsToInsert.length * 6;
  	let lastEnd = serialized.length - distanceToMove;
  	while (nextId = idsToInsert.pop()) {
  		let offset = nextId.offset;
  		let id = nextId.id;
  		serialized.copyWithin(offset + distanceToMove, offset, lastEnd);
  		distanceToMove -= 6;
  		let position = offset + distanceToMove;
  		serialized[position++] = 0xd6;
  		serialized[position++] = 0x69; // 'i'
  		serialized[position++] = id >> 24;
  		serialized[position++] = (id >> 16) & 0xff;
  		serialized[position++] = (id >> 8) & 0xff;
  		serialized[position++] = id & 0xff;
  		lastEnd = offset;
  	}
  	return serialized
  }

  function writeBundles(start, pack, incrementPosition) {
  	if (bundledStrings.length > 0) {
  		targetView.setUint32(bundledStrings.position + start, position + incrementPosition - bundledStrings.position - start);
  		bundledStrings.stringsPosition = position - start;
  		let writeStrings = bundledStrings;
  		bundledStrings = null;
  		pack(writeStrings[0]);
  		pack(writeStrings[1]);
  	}
  }
  function prepareStructures(structures, packr) {
  	structures.isCompatible = (existingStructures) => {
  		let compatible = !existingStructures || ((packr.lastNamedStructuresLength || 0) === existingStructures.length);
  		if (!compatible) // we want to merge these existing structures immediately since we already have it and we are in the right transaction
  			packr._mergeStructures(existingStructures);
  		return compatible;
  	};
  	return structures
  }

  let defaultPackr = new Packr({ useRecords: false });
  const pack$1 = defaultPackr.pack;
  defaultPackr.pack;
  const REUSE_BUFFER_MODE = 512;
  const RESET_BUFFER_MODE = 1024;

  // DEFLATE is a complex format; to read this code, you should probably check the RFC first:
  // https://tools.ietf.org/html/rfc1951
  // You may also wish to take a look at the guide I made about this program:
  // https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad
  // Some of the following code is similar to that of UZIP.js:
  // https://github.com/photopea/UZIP.js
  // However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size.
  // Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint
  // is better for memory in most engines (I *think*).
  var ch2 = {};
  var wk = (function (c, id, msg, transfer, cb) {
      var w = new Worker(ch2[id] || (ch2[id] = URL.createObjectURL(new Blob([
          c + ';addEventListener("error",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})'
      ], { type: 'text/javascript' }))));
      w.onmessage = function (e) {
          var d = e.data, ed = d.$e$;
          if (ed) {
              var err = new Error(ed[0]);
              err['code'] = ed[1];
              err.stack = ed[2];
              cb(err, null);
          }
          else
              cb(null, d);
      };
      w.postMessage(msg, transfer);
      return w;
  });

  // aliases for shorter compressed code (most minifers don't do this)
  var u8 = Uint8Array, u16 = Uint16Array, u32 = Uint32Array;
  // fixed length extra bits
  var fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]);
  // fixed distance extra bits
  // see fleb note
  var fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]);
  // code length index map
  var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
  // get base, reverse index map from extra bits
  var freb = function (eb, start) {
      var b = new u16(31);
      for (var i = 0; i < 31; ++i) {
          b[i] = start += 1 << eb[i - 1];
      }
      // numbers here are at max 18 bits
      var r = new u32(b[30]);
      for (var i = 1; i < 30; ++i) {
          for (var j = b[i]; j < b[i + 1]; ++j) {
              r[j] = ((j - b[i]) << 5) | i;
          }
      }
      return [b, r];
  };
  var _a = freb(fleb, 2), fl = _a[0], revfl = _a[1];
  // we can ignore the fact that the other numbers are wrong; they never happen anyway
  fl[28] = 258, revfl[258] = 28;
  var _b = freb(fdeb, 0), fd = _b[0], revfd = _b[1];
  // map of value to reverse (assuming 16 bits)
  var rev = new u16(32768);
  for (var i = 0; i < 32768; ++i) {
      // reverse table algorithm from SO
      var x = ((i & 0xAAAA) >>> 1) | ((i & 0x5555) << 1);
      x = ((x & 0xCCCC) >>> 2) | ((x & 0x3333) << 2);
      x = ((x & 0xF0F0) >>> 4) | ((x & 0x0F0F) << 4);
      rev[i] = (((x & 0xFF00) >>> 8) | ((x & 0x00FF) << 8)) >>> 1;
  }
  // create huffman tree from u8 "map": index -> code length for code index
  // mb (max bits) must be at most 15
  // TODO: optimize/split up?
  var hMap = (function (cd, mb, r) {
      var s = cd.length;
      // index
      var i = 0;
      // u16 "map": index -> # of codes with bit length = index
      var l = new u16(mb);
      // length of cd must be 288 (total # of codes)
      for (; i < s; ++i) {
          if (cd[i])
              ++l[cd[i] - 1];
      }
      // u16 "map": index -> minimum code for bit length = index
      var le = new u16(mb);
      for (i = 0; i < mb; ++i) {
          le[i] = (le[i - 1] + l[i - 1]) << 1;
      }
      var co;
      if (r) {
          // u16 "map": index -> number of actual bits, symbol for code
          co = new u16(1 << mb);
          // bits to remove for reverser
          var rvb = 15 - mb;
          for (i = 0; i < s; ++i) {
              // ignore 0 lengths
              if (cd[i]) {
                  // num encoding both symbol and bits read
                  var sv = (i << 4) | cd[i];
                  // free bits
                  var r_1 = mb - cd[i];
                  // start value
                  var v = le[cd[i] - 1]++ << r_1;
                  // m is end value
                  for (var m = v | ((1 << r_1) - 1); v <= m; ++v) {
                      // every 16 bit value starting with the code yields the same result
                      co[rev[v] >>> rvb] = sv;
                  }
              }
          }
      }
      else {
          co = new u16(s);
          for (i = 0; i < s; ++i) {
              if (cd[i]) {
                  co[i] = rev[le[cd[i] - 1]++] >>> (15 - cd[i]);
              }
          }
      }
      return co;
  });
  // fixed length tree
  var flt = new u8(288);
  for (var i = 0; i < 144; ++i)
      flt[i] = 8;
  for (var i = 144; i < 256; ++i)
      flt[i] = 9;
  for (var i = 256; i < 280; ++i)
      flt[i] = 7;
  for (var i = 280; i < 288; ++i)
      flt[i] = 8;
  // fixed distance tree
  var fdt = new u8(32);
  for (var i = 0; i < 32; ++i)
      fdt[i] = 5;
  // fixed length map
  var flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1);
  // fixed distance map
  var fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1);
  // find max of array
  var max = function (a) {
      var m = a[0];
      for (var i = 1; i < a.length; ++i) {
          if (a[i] > m)
              m = a[i];
      }
      return m;
  };
  // read d, starting at bit p and mask with m
  var bits = function (d, p, m) {
      var o = (p / 8) | 0;
      return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m;
  };
  // read d, starting at bit p continuing for at least 16 bits
  var bits16 = function (d, p) {
      var o = (p / 8) | 0;
      return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7));
  };
  // get end of byte
  var shft = function (p) { return ((p + 7) / 8) | 0; };
  // typed array slice - allows garbage collector to free original reference,
  // while being more compatible than .slice
  var slc = function (v, s, e) {
      if (s == null || s < 0)
          s = 0;
      if (e == null || e > v.length)
          e = v.length;
      // can't use .constructor in case user-supplied
      var n = new (v.BYTES_PER_ELEMENT == 2 ? u16 : v.BYTES_PER_ELEMENT == 4 ? u32 : u8)(e - s);
      n.set(v.subarray(s, e));
      return n;
  };
  // error codes
  var ec = [
      'unexpected EOF',
      'invalid block type',
      'invalid length/literal',
      'invalid distance',
      'stream finished',
      'no stream handler',
      ,
      'no callback',
      'invalid UTF-8 data',
      'extra field too long',
      'date not in range 1980-2099',
      'filename too long',
      'stream finishing',
      'invalid zip data'
      // determined by unknown compression method
  ];
  var err = function (ind, msg, nt) {
      var e = new Error(msg || ec[ind]);
      e.code = ind;
      if (Error.captureStackTrace)
          Error.captureStackTrace(e, err);
      if (!nt)
          throw e;
      return e;
  };
  // expands raw DEFLATE data
  var inflt = function (dat, buf, st) {
      // source length
      var sl = dat.length;
      if (!sl || (st && st.f && !st.l))
          return buf || new u8(0);
      // have to estimate size
      var noBuf = !buf || st;
      // no state
      var noSt = !st || st.i;
      if (!st)
          st = {};
      // Assumes roughly 33% compression ratio average
      if (!buf)
          buf = new u8(sl * 3);
      // ensure buffer can fit at least l elements
      var cbuf = function (l) {
          var bl = buf.length;
          // need to increase size to fit
          if (l > bl) {
              // Double or set to necessary, whichever is greater
              var nbuf = new u8(Math.max(bl * 2, l));
              nbuf.set(buf);
              buf = nbuf;
          }
      };
      //  last chunk         bitpos           bytes
      var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
      // total bits
      var tbts = sl * 8;
      do {
          if (!lm) {
              // BFINAL - this is only 1 when last chunk is next
              final = bits(dat, pos, 1);
              // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman
              var type = bits(dat, pos + 1, 3);
              pos += 3;
              if (!type) {
                  // go to end of byte boundary
                  var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l;
                  if (t > sl) {
                      if (noSt)
                          err(0);
                      break;
                  }
                  // ensure size
                  if (noBuf)
                      cbuf(bt + l);
                  // Copy over uncompressed data
                  buf.set(dat.subarray(s, t), bt);
                  // Get new bitpos, update byte count
                  st.b = bt += l, st.p = pos = t * 8, st.f = final;
                  continue;
              }
              else if (type == 1)
                  lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
              else if (type == 2) {
                  //  literal                            lengths
                  var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
                  var tl = hLit + bits(dat, pos + 5, 31) + 1;
                  pos += 14;
                  // length+distance tree
                  var ldt = new u8(tl);
                  // code length tree
                  var clt = new u8(19);
                  for (var i = 0; i < hcLen; ++i) {
                      // use index map to get real code
                      clt[clim[i]] = bits(dat, pos + i * 3, 7);
                  }
                  pos += hcLen * 3;
                  // code lengths bits
                  var clb = max(clt), clbmsk = (1 << clb) - 1;
                  // code lengths map
                  var clm = hMap(clt, clb, 1);
                  for (var i = 0; i < tl;) {
                      var r = clm[bits(dat, pos, clbmsk)];
                      // bits read
                      pos += r & 15;
                      // symbol
                      var s = r >>> 4;
                      // code length to copy
                      if (s < 16) {
                          ldt[i++] = s;
                      }
                      else {
                          //  copy   count
                          var c = 0, n = 0;
                          if (s == 16)
                              n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];
                          else if (s == 17)
                              n = 3 + bits(dat, pos, 7), pos += 3;
                          else if (s == 18)
                              n = 11 + bits(dat, pos, 127), pos += 7;
                          while (n--)
                              ldt[i++] = c;
                      }
                  }
                  //    length tree                 distance tree
                  var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
                  // max length bits
                  lbt = max(lt);
                  // max dist bits
                  dbt = max(dt);
                  lm = hMap(lt, lbt, 1);
                  dm = hMap(dt, dbt, 1);
              }
              else
                  err(1);
              if (pos > tbts) {
                  if (noSt)
                      err(0);
                  break;
              }
          }
          // Make sure the buffer can hold this + the largest possible addition
          // Maximum chunk size (practically, theoretically infinite) is 2^17;
          if (noBuf)
              cbuf(bt + 131072);
          var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
          var lpos = pos;
          for (;; lpos = pos) {
              // bits read, code
              var c = lm[bits16(dat, pos) & lms], sym = c >>> 4;
              pos += c & 15;
              if (pos > tbts) {
                  if (noSt)
                      err(0);
                  break;
              }
              if (!c)
                  err(2);
              if (sym < 256)
                  buf[bt++] = sym;
              else if (sym == 256) {
                  lpos = pos, lm = null;
                  break;
              }
              else {
                  var add = sym - 254;
                  // no extra bits needed if less
                  if (sym > 264) {
                      // index
                      var i = sym - 257, b = fleb[i];
                      add = bits(dat, pos, (1 << b) - 1) + fl[i];
                      pos += b;
                  }
                  // dist
                  var d = dm[bits16(dat, pos) & dms], dsym = d >>> 4;
                  if (!d)
                      err(3);
                  pos += d & 15;
                  var dt = fd[dsym];
                  if (dsym > 3) {
                      var b = fdeb[dsym];
                      dt += bits16(dat, pos) & ((1 << b) - 1), pos += b;
                  }
                  if (pos > tbts) {
                      if (noSt)
                          err(0);
                      break;
                  }
                  if (noBuf)
                      cbuf(bt + 131072);
                  var end = bt + add;
                  for (; bt < end; bt += 4) {
                      buf[bt] = buf[bt - dt];
                      buf[bt + 1] = buf[bt + 1 - dt];
                      buf[bt + 2] = buf[bt + 2 - dt];
                      buf[bt + 3] = buf[bt + 3 - dt];
                  }
                  bt = end;
              }
          }
          st.l = lm, st.p = lpos, st.b = bt, st.f = final;
          if (lm)
              final = 1, st.m = lbt, st.d = dm, st.n = dbt;
      } while (!final);
      return bt == buf.length ? buf : slc(buf, 0, bt);
  };
  // starting at p, write the minimum number of bits that can hold v to d
  var wbits = function (d, p, v) {
      v <<= p & 7;
      var o = (p / 8) | 0;
      d[o] |= v;
      d[o + 1] |= v >>> 8;
  };
  // starting at p, write the minimum number of bits (>8) that can hold v to d
  var wbits16 = function (d, p, v) {
      v <<= p & 7;
      var o = (p / 8) | 0;
      d[o] |= v;
      d[o + 1] |= v >>> 8;
      d[o + 2] |= v >>> 16;
  };
  // creates code lengths from a frequency table
  var hTree = function (d, mb) {
      // Need extra info to make a tree
      var t = [];
      for (var i = 0; i < d.length; ++i) {
          if (d[i])
              t.push({ s: i, f: d[i] });
      }
      var s = t.length;
      var t2 = t.slice();
      if (!s)
          return [et, 0];
      if (s == 1) {
          var v = new u8(t[0].s + 1);
          v[t[0].s] = 1;
          return [v, 1];
      }
      t.sort(function (a, b) { return a.f - b.f; });
      // after i2 reaches last ind, will be stopped
      // freq must be greater than largest possible number of symbols
      t.push({ s: -1, f: 25001 });
      var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2;
      t[0] = { s: -1, f: l.f + r.f, l: l, r: r };
      // efficient algorithm from UZIP.js
      // i0 is lookbehind, i2 is lookahead - after processing two low-freq
      // symbols that combined have high freq, will start processing i2 (high-freq,
      // non-composite) symbols instead
      // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/
      while (i1 != s - 1) {
          l = t[t[i0].f < t[i2].f ? i0++ : i2++];
          r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++];
          t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r };
      }
      var maxSym = t2[0].s;
      for (var i = 1; i < s; ++i) {
          if (t2[i].s > maxSym)
              maxSym = t2[i].s;
      }
      // code lengths
      var tr = new u16(maxSym + 1);
      // max bits in tree
      var mbt = ln(t[i1 - 1], tr, 0);
      if (mbt > mb) {
          // more algorithms from UZIP.js
          // TODO: find out how this code works (debt)
          //  ind    debt
          var i = 0, dt = 0;
          //    left            cost
          var lft = mbt - mb, cst = 1 << lft;
          t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; });
          for (; i < s; ++i) {
              var i2_1 = t2[i].s;
              if (tr[i2_1] > mb) {
                  dt += cst - (1 << (mbt - tr[i2_1]));
                  tr[i2_1] = mb;
              }
              else
                  break;
          }
          dt >>>= lft;
          while (dt > 0) {
              var i2_2 = t2[i].s;
              if (tr[i2_2] < mb)
                  dt -= 1 << (mb - tr[i2_2]++ - 1);
              else
                  ++i;
          }
          for (; i >= 0 && dt; --i) {
              var i2_3 = t2[i].s;
              if (tr[i2_3] == mb) {
                  --tr[i2_3];
                  ++dt;
              }
          }
          mbt = mb;
      }
      return [new u8(tr), mbt];
  };
  // get the max length and assign length codes
  var ln = function (n, l, d) {
      return n.s == -1
          ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1))
          : (l[n.s] = d);
  };
  // length codes generation
  var lc = function (c) {
      var s = c.length;
      // Note that the semicolon was intentional
      while (s && !c[--s])
          ;
      var cl = new u16(++s);
      //  ind      num         streak
      var cli = 0, cln = c[0], cls = 1;
      var w = function (v) { cl[cli++] = v; };
      for (var i = 1; i <= s; ++i) {
          if (c[i] == cln && i != s)
              ++cls;
          else {
              if (!cln && cls > 2) {
                  for (; cls > 138; cls -= 138)
                      w(32754);
                  if (cls > 2) {
                      w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305);
                      cls = 0;
                  }
              }
              else if (cls > 3) {
                  w(cln), --cls;
                  for (; cls > 6; cls -= 6)
                      w(8304);
                  if (cls > 2)
                      w(((cls - 3) << 5) | 8208), cls = 0;
              }
              while (cls--)
                  w(cln);
              cls = 1;
              cln = c[i];
          }
      }
      return [cl.subarray(0, cli), s];
  };
  // calculate the length of output from tree, code lengths
  var clen = function (cf, cl) {
      var l = 0;
      for (var i = 0; i < cl.length; ++i)
          l += cf[i] * cl[i];
      return l;
  };
  // writes a fixed block
  // returns the new bit pos
  var wfblk = function (out, pos, dat) {
      // no need to write 00 as type: TypedArray defaults to 0
      var s = dat.length;
      var o = shft(pos + 2);
      out[o] = s & 255;
      out[o + 1] = s >>> 8;
      out[o + 2] = out[o] ^ 255;
      out[o + 3] = out[o + 1] ^ 255;
      for (var i = 0; i < s; ++i)
          out[o + i + 4] = dat[i];
      return (o + 4 + s) * 8;
  };
  // writes a block
  var wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) {
      wbits(out, p++, final);
      ++lf[256];
      var _a = hTree(lf, 15), dlt = _a[0], mlb = _a[1];
      var _b = hTree(df, 15), ddt = _b[0], mdb = _b[1];
      var _c = lc(dlt), lclt = _c[0], nlc = _c[1];
      var _d = lc(ddt), lcdt = _d[0], ndc = _d[1];
      var lcfreq = new u16(19);
      for (var i = 0; i < lclt.length; ++i)
          lcfreq[lclt[i] & 31]++;
      for (var i = 0; i < lcdt.length; ++i)
          lcfreq[lcdt[i] & 31]++;
      var _e = hTree(lcfreq, 7), lct = _e[0], mlcb = _e[1];
      var nlcc = 19;
      for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)
          ;
      var flen = (bl + 5) << 3;
      var ftlen = clen(lf, flt) + clen(df, fdt) + eb;
      var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + (2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18]);
      if (flen <= ftlen && flen <= dtlen)
          return wfblk(out, p, dat.subarray(bs, bs + bl));
      var lm, ll, dm, dl;
      wbits(out, p, 1 + (dtlen < ftlen)), p += 2;
      if (dtlen < ftlen) {
          lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;
          var llm = hMap(lct, mlcb, 0);
          wbits(out, p, nlc - 257);
          wbits(out, p + 5, ndc - 1);
          wbits(out, p + 10, nlcc - 4);
          p += 14;
          for (var i = 0; i < nlcc; ++i)
              wbits(out, p + 3 * i, lct[clim[i]]);
          p += 3 * nlcc;
          var lcts = [lclt, lcdt];
          for (var it = 0; it < 2; ++it) {
              var clct = lcts[it];
              for (var i = 0; i < clct.length; ++i) {
                  var len = clct[i] & 31;
                  wbits(out, p, llm[len]), p += lct[len];
                  if (len > 15)
                      wbits(out, p, (clct[i] >>> 5) & 127), p += clct[i] >>> 12;
              }
          }
      }
      else {
          lm = flm, ll = flt, dm = fdm, dl = fdt;
      }
      for (var i = 0; i < li; ++i) {
          if (syms[i] > 255) {
              var len = (syms[i] >>> 18) & 31;
              wbits16(out, p, lm[len + 257]), p += ll[len + 257];
              if (len > 7)
                  wbits(out, p, (syms[i] >>> 23) & 31), p += fleb[len];
              var dst = syms[i] & 31;
              wbits16(out, p, dm[dst]), p += dl[dst];
              if (dst > 3)
                  wbits16(out, p, (syms[i] >>> 5) & 8191), p += fdeb[dst];
          }
          else {
              wbits16(out, p, lm[syms[i]]), p += ll[syms[i]];
          }
      }
      wbits16(out, p, lm[256]);
      return p + ll[256];
  };
  // deflate options (nice << 13) | chain
  var deo = /*#__PURE__*/ new u32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);
  // empty
  var et = /*#__PURE__*/ new u8(0);
  // compresses data into a raw DEFLATE buffer
  var dflt = function (dat, lvl, plvl, pre, post, lst) {
      var s = dat.length;
      var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post);
      // writing to this writes to the output buffer
      var w = o.subarray(pre, o.length - post);
      var pos = 0;
      if (!lvl || s < 8) {
          for (var i = 0; i <= s; i += 65535) {
              // end
              var e = i + 65535;
              if (e >= s) {
                  // write final block
                  w[pos >> 3] = lst;
              }
              pos = wfblk(w, pos + 1, dat.subarray(i, e));
          }
      }
      else {
          var opt = deo[lvl - 1];
          var n = opt >>> 13, c = opt & 8191;
          var msk_1 = (1 << plvl) - 1;
          //    prev 2-byte val map    curr 2-byte val map
          var prev = new u16(32768), head = new u16(msk_1 + 1);
          var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;
          var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; };
          // 24576 is an arbitrary number of maximum symbols per block
          // 424 buffer for last block
          var syms = new u32(25000);
          // length/literal freq   distance freq
          var lf = new u16(288), df = new u16(32);
          //  l/lcnt  exbits  index  l/lind  waitdx  bitpos
          var lc_1 = 0, eb = 0, i = 0, li = 0, wi = 0, bs = 0;
          for (; i < s; ++i) {
              // hash value
              // deopt when i > s - 3 - at end, deopt acceptable
              var hv = hsh(i);
              // index mod 32768    previous index mod
              var imod = i & 32767, pimod = head[hv];
              prev[imod] = pimod;
              head[hv] = imod;
              // We always should modify head and prev, but only add symbols if
              // this data is not yet processed ("wait" for wait index)
              if (wi <= i) {
                  // bytes remaining
                  var rem = s - i;
                  if ((lc_1 > 7000 || li > 24576) && rem > 423) {
                      pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos);
                      li = lc_1 = eb = 0, bs = i;
                      for (var j = 0; j < 286; ++j)
                          lf[j] = 0;
                      for (var j = 0; j < 30; ++j)
                          df[j] = 0;
                  }
                  //  len    dist   chain
                  var l = 2, d = 0, ch_1 = c, dif = (imod - pimod) & 32767;
                  if (rem > 2 && hv == hsh(i - dif)) {
                      var maxn = Math.min(n, rem) - 1;
                      var maxd = Math.min(32767, i);
                      // max possible length
                      // not capped at dif because decompressors implement "rolling" index population
                      var ml = Math.min(258, rem);
                      while (dif <= maxd && --ch_1 && imod != pimod) {
                          if (dat[i + l] == dat[i + l - dif]) {
                              var nl = 0;
                              for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl)
                                  ;
                              if (nl > l) {
                                  l = nl, d = dif;
                                  // break out early when we reach "nice" (we are satisfied enough)
                                  if (nl > maxn)
                                      break;
                                  // now, find the rarest 2-byte sequence within this
                                  // length of literals and search for that instead.
                                  // Much faster than just using the start
                                  var mmd = Math.min(dif, nl - 2);
                                  var md = 0;
                                  for (var j = 0; j < mmd; ++j) {
                                      var ti = (i - dif + j + 32768) & 32767;
                                      var pti = prev[ti];
                                      var cd = (ti - pti + 32768) & 32767;
                                      if (cd > md)
                                          md = cd, pimod = ti;
                                  }
                              }
                          }
                          // check the previous match
                          imod = pimod, pimod = prev[imod];
                          dif += (imod - pimod + 32768) & 32767;
                      }
                  }
                  // d will be nonzero only when a match was found
                  if (d) {
                      // store both dist and len data in one Uint32
                      // Make sure this is recognized as a len/dist with 28th bit (2^28)
                      syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d];
                      var lin = revfl[l] & 31, din = revfd[d] & 31;
                      eb += fleb[lin] + fdeb[din];
                      ++lf[257 + lin];
                      ++df[din];
                      wi = i + l;
                      ++lc_1;
                  }
                  else {
                      syms[li++] = dat[i];
                      ++lf[dat[i]];
                  }
              }
          }
          pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos);
          // this is the easiest way to avoid needing to maintain state
          if (!lst && pos & 7)
              pos = wfblk(w, pos + 1, et);
      }
      return slc(o, 0, pre + shft(pos) + post);
  };
  // CRC32 table
  var crct = /*#__PURE__*/ (function () {
      var t = new Int32Array(256);
      for (var i = 0; i < 256; ++i) {
          var c = i, k = 9;
          while (--k)
              c = ((c & 1) && -306674912) ^ (c >>> 1);
          t[i] = c;
      }
      return t;
  })();
  // CRC32
  var crc = function () {
      var c = -1;
      return {
          p: function (d) {
              // closures have awful performance
              var cr = c;
              for (var i = 0; i < d.length; ++i)
                  cr = crct[(cr & 255) ^ d[i]] ^ (cr >>> 8);
              c = cr;
          },
          d: function () { return ~c; }
      };
  };
  // deflate with opts
  var dopt = function (dat, opt, pre, post, st) {
      return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : (12 + opt.mem), pre, post, !st);
  };
  // Walmart object spread
  var mrg = function (a, b) {
      var o = {};
      for (var k in a)
          o[k] = a[k];
      for (var k in b)
          o[k] = b[k];
      return o;
  };
  // worker clone
  // This is possibly the craziest part of the entire codebase, despite how simple it may seem.
  // The only parameter to this function is a closure that returns an array of variables outside of the function scope.
  // We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization.
  // We will return an object mapping of true variable name to value (basically, the current scope as a JS object).
  // The reason we can't just use the original variable names is minifiers mangling the toplevel scope.
  // This took me three weeks to figure out how to do.
  var wcln = function (fn, fnStr, td) {
      var dt = fn();
      var st = fn.toString();
      var ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/\s+/g, '').split(',');
      for (var i = 0; i < dt.length; ++i) {
          var v = dt[i], k = ks[i];
          if (typeof v == 'function') {
              fnStr += ';' + k + '=';
              var st_1 = v.toString();
              if (v.prototype) {
                  // for global objects
                  if (st_1.indexOf('[native code]') != -1) {
                      var spInd = st_1.indexOf(' ', 8) + 1;
                      fnStr += st_1.slice(spInd, st_1.indexOf('(', spInd));
                  }
                  else {
                      fnStr += st_1;
                      for (var t in v.prototype)
                          fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString();
                  }
              }
              else
                  fnStr += st_1;
          }
          else
              td[k] = v;
      }
      return [fnStr, td];
  };
  var ch = [];
  // clone bufs
  var cbfs = function (v) {
      var tl = [];
      for (var k in v) {
          if (v[k].buffer) {
              tl.push((v[k] = new v[k].constructor(v[k])).buffer);
          }
      }
      return tl;
  };
  // use a worker to execute code
  var wrkr = function (fns, init, id, cb) {
      var _a;
      if (!ch[id]) {
          var fnStr = '', td_1 = {}, m = fns.length - 1;
          for (var i = 0; i < m; ++i)
              _a = wcln(fns[i], fnStr, td_1), fnStr = _a[0], td_1 = _a[1];
          ch[id] = wcln(fns[m], fnStr, td_1);
      }
      var td = mrg({}, ch[id][1]);
      return wk(ch[id][0] + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb);
  };
  // base async inflate fn
  var bInflt = function () { return [u8, u16, u32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, max, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gu8]; };
  var bDflt = function () { return [u8, u16, u32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf]; };
  // gzip extra
  var gze = function () { return [gzh, gzhl, wbytes, crc, crct]; };
  // gunzip extra
  var guze = function () { return [gzs, gzl]; };
  // post buf
  var pbf = function (msg) { return postMessage(msg, [msg.buffer]); };
  // get u8
  var gu8 = function (o) { return o && o.size && new u8(o.size); };
  // async helper
  var cbify = function (dat, opts, fns, init, id, cb) {
      var w = wrkr(fns, init, id, function (err, dat) {
          w.terminate();
          cb(err, dat);
      });
      w.postMessage([dat, opts], opts.consume ? [dat.buffer] : []);
      return function () { w.terminate(); };
  };
  // read 2 bytes
  var b2 = function (d, b) { return d[b] | (d[b + 1] << 8); };
  // read 4 bytes
  var b4 = function (d, b) { return (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16) | (d[b + 3] << 24)) >>> 0; };
  var b8 = function (d, b) { return b4(d, b) + (b4(d, b + 4) * 4294967296); };
  // write bytes
  var wbytes = function (d, b, v) {
      for (; v; ++b)
          d[b] = v, v >>>= 8;
  };
  // gzip header
  var gzh = function (c, o) {
      var fn = o.filename;
      c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; // assume Unix
      if (o.mtime != 0)
          wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1000));
      if (fn) {
          c[3] = 8;
          for (var i = 0; i <= fn.length; ++i)
              c[i + 10] = fn.charCodeAt(i);
      }
  };
  // gzip footer: -8 to -4 = CRC, -4 to -0 is length
  // gzip start
  var gzs = function (d) {
      if (d[0] != 31 || d[1] != 139 || d[2] != 8)
          err(6, 'invalid gzip data');
      var flg = d[3];
      var st = 10;
      if (flg & 4)
          st += d[10] | (d[11] << 8) + 2;
      for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++])
          ;
      return st + (flg & 2);
  };
  // gzip length
  var gzl = function (d) {
      var l = d.length;
      return ((d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16) | (d[l - 1] << 24)) >>> 0;
  };
  // gzip header length
  var gzhl = function (o) { return 10 + ((o.filename && (o.filename.length + 1)) || 0); };
  function deflate(data, opts, cb) {
      if (!cb)
          cb = opts, opts = {};
      if (typeof cb != 'function')
          err(7);
      return cbify(data, opts, [
          bDflt,
      ], function (ev) { return pbf(deflateSync(ev.data[0], ev.data[1])); }, 0, cb);
  }
  /**
   * Compresses data with DEFLATE without any wrapper
   * @param data The data to compress
   * @param opts The compression options
   * @returns The deflated version of the data
   */
  function deflateSync(data, opts) {
      return dopt(data, opts || {}, 0, 0);
  }
  function inflate(data, opts, cb) {
      if (!cb)
          cb = opts, opts = {};
      if (typeof cb != 'function')
          err(7);
      return cbify(data, opts, [
          bInflt
      ], function (ev) { return pbf(inflateSync(ev.data[0], gu8(ev.data[1]))); }, 1, cb);
  }
  /**
   * Expands DEFLATE data with no wrapper
   * @param data The data to decompress
   * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.
   * @returns The decompressed version of the data
   */
  function inflateSync(data, out) {
      return inflt(data, out);
  }
  function gzip(data, opts, cb) {
      if (!cb)
          cb = opts, opts = {};
      if (typeof cb != 'function')
          err(7);
      return cbify(data, opts, [
          bDflt,
          gze,
          function () { return [gzipSync$1]; }
      ], function (ev) { return pbf(gzipSync$1(ev.data[0], ev.data[1])); }, 2, cb);
  }
  /**
   * Compresses data with GZIP
   * @param data The data to compress
   * @param opts The compression options
   * @returns The gzipped version of the data
   */
  function gzipSync$1(data, opts) {
      if (!opts)
          opts = {};
      var c = crc(), l = data.length;
      c.p(data);
      var d = dopt(data, opts, gzhl(opts), 8), s = d.length;
      return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d;
  }
  function gunzip(data, opts, cb) {
      if (!cb)
          cb = opts, opts = {};
      if (typeof cb != 'function')
          err(7);
      return cbify(data, opts, [
          bInflt,
          guze,
          function () { return [gunzipSync$1]; }
      ], function (ev) { return pbf(gunzipSync$1(ev.data[0])); }, 3, cb);
  }
  /**
   * Expands GZIP data
   * @param data The data to decompress
   * @param out Where to write the data. GZIP already encodes the output size, so providing this doesn't save memory.
   * @returns The decompressed version of the data
   */
  function gunzipSync$1(data, out) {
      return inflt(data.subarray(gzs(data), -8), out || new u8(gzl(data)));
  }
  // flatten a directory structure
  var fltn = function (d, p, t, o) {
      for (var k in d) {
          var val = d[k], n = p + k, op = o;
          if (Array.isArray(val))
              op = mrg(o, val[1]), val = val[0];
          if (val instanceof u8)
              t[n] = [val, op];
          else {
              t[n += '/'] = [new u8(0), op];
              fltn(val, n, t, o);
          }
      }
  };
  // text encoder
  var te = typeof TextEncoder != 'undefined' && /*#__PURE__*/ new TextEncoder();
  // text decoder
  var td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder();
  // text decoder stream
  var tds = 0;
  try {
      td.decode(et, { stream: true });
      tds = 1;
  }
  catch (e) { }
  // decode UTF8
  var dutf8 = function (d) {
      for (var r = '', i = 0;;) {
          var c = d[i++];
          var eb = (c > 127) + (c > 223) + (c > 239);
          if (i + eb > d.length)
              return [r, slc(d, i - 1)];
          if (!eb)
              r += String.fromCharCode(c);
          else if (eb == 3) {
              c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)) - 65536,
                  r += String.fromCharCode(55296 | (c >> 10), 56320 | (c & 1023));
          }
          else if (eb & 1)
              r += String.fromCharCode((c & 31) << 6 | (d[i++] & 63));
          else
              r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63));
      }
  };
  /**
   * Converts a string into a Uint8Array for use with compression/decompression methods
   * @param str The string to encode
   * @param latin1 Whether or not to interpret the data as Latin-1. This should
   *               not need to be true unless decoding a binary string.
   * @returns The string encoded in UTF-8/Latin-1 binary
   */
  function strToU8(str, latin1) {
      if (latin1) {
          var ar_1 = new u8(str.length);
          for (var i = 0; i < str.length; ++i)
              ar_1[i] = str.charCodeAt(i);
          return ar_1;
      }
      if (te)
          return te.encode(str);
      var l = str.length;
      var ar = new u8(str.length + (str.length >> 1));
      var ai = 0;
      var w = function (v) { ar[ai++] = v; };
      for (var i = 0; i < l; ++i) {
          if (ai + 5 > ar.length) {
              var n = new u8(ai + 8 + ((l - i) << 1));
              n.set(ar);
              ar = n;
          }
          var c = str.charCodeAt(i);
          if (c < 128 || latin1)
              w(c);
          else if (c < 2048)
              w(192 | (c >> 6)), w(128 | (c & 63));
          else if (c > 55295 && c < 57344)
              c = 65536 + (c & 1023 << 10) | (str.charCodeAt(++i) & 1023),
                  w(240 | (c >> 18)), w(128 | ((c >> 12) & 63)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));
          else
              w(224 | (c >> 12)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));
      }
      return slc(ar, 0, ai);
  }
  /**
   * Converts a Uint8Array to a string
   * @param dat The data to decode to string
   * @param latin1 Whether or not to interpret the data as Latin-1. This should
   *               not need to be true unless encoding to binary string.
   * @returns The original UTF-8/Latin-1 string
   */
  function strFromU8(dat, latin1) {
      if (latin1) {
          var r = '';
          for (var i = 0; i < dat.length; i += 16384)
              r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384));
          return r;
      }
      else if (td)
          return td.decode(dat);
      else {
          var _a = dutf8(dat), out = _a[0], ext = _a[1];
          if (ext.length)
              err(8);
          return out;
      }
  }
  // skip local zip header
  var slzh = function (d, b) { return b + 30 + b2(d, b + 26) + b2(d, b + 28); };
  // read zip header
  var zh = function (d, b, z) {
      var fnl = b2(d, b + 28), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl, bs = b4(d, b + 20);
      var _a = z && bs == 4294967295 ? z64e(d, es) : [bs, b4(d, b + 24), b4(d, b + 42)], sc = _a[0], su = _a[1], off = _a[2];
      return [b2(d, b + 10), sc, su, fn, es + b2(d, b + 30) + b2(d, b + 32), off];
  };
  // read zip64 extra field
  var z64e = function (d, b) {
      for (; b2(d, b) != 1; b += 4 + b2(d, b + 2))
          ;
      return [b8(d, b + 12), b8(d, b + 4), b8(d, b + 20)];
  };
  // extra field length
  var exfl = function (ex) {
      var le = 0;
      if (ex) {
          for (var k in ex) {
              var l = ex[k].length;
              if (l > 65535)
                  err(9);
              le += l + 4;
          }
      }
      return le;
  };
  // write zip header
  var wzh = function (d, b, f, fn, u, c, ce, co) {
      var fl = fn.length, ex = f.extra, col = co && co.length;
      var exl = exfl(ex);
      wbytes(d, b, ce != null ? 0x2014B50 : 0x4034B50), b += 4;
      if (ce != null)
          d[b++] = 20, d[b++] = f.os;
      d[b] = 20, b += 2; // spec compliance? what's that?
      d[b++] = (f.flag << 1) | (c < 0 && 8), d[b++] = u && 8;
      d[b++] = f.compression & 255, d[b++] = f.compression >> 8;
      var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980;
      if (y < 0 || y > 119)
          err(10);
      wbytes(d, b, (y << 25) | ((dt.getMonth() + 1) << 21) | (dt.getDate() << 16) | (dt.getHours() << 11) | (dt.getMinutes() << 5) | (dt.getSeconds() >>> 1)), b += 4;
      if (c != -1) {
          wbytes(d, b, f.crc);
          wbytes(d, b + 4, c < 0 ? -c - 2 : c);
          wbytes(d, b + 8, f.size);
      }
      wbytes(d, b + 12, fl);
      wbytes(d, b + 14, exl), b += 16;
      if (ce != null) {
          wbytes(d, b, col);
          wbytes(d, b + 6, f.attrs);
          wbytes(d, b + 10, ce), b += 14;
      }
      d.set(fn, b);
      b += fl;
      if (exl) {
          for (var k in ex) {
              var exf = ex[k], l = exf.length;
              wbytes(d, b, +k);
              wbytes(d, b + 2, l);
              d.set(exf, b + 4), b += 4 + l;
          }
      }
      if (col)
          d.set(co, b), b += col;
      return b;
  };
  // write zip footer (end of central directory)
  var wzf = function (o, b, c, d, e) {
      wbytes(o, b, 0x6054B50); // skip disk
      wbytes(o, b + 8, c);
      wbytes(o, b + 10, c);
      wbytes(o, b + 12, d);
      wbytes(o, b + 16, e);
  };
  function zip(data, opts, cb) {
      if (!cb)
          cb = opts, opts = {};
      if (typeof cb != 'function')
          err(7);
      var r = {};
      fltn(data, '', r, opts);
      var k = Object.keys(r);
      var lft = k.length, o = 0, tot = 0;
      var slft = lft, files = new Array(lft);
      var term = [];
      var tAll = function () {
          for (var i = 0; i < term.length; ++i)
              term[i]();
      };
      var cbd = function (a, b) {
          mt(function () { cb(a, b); });
      };
      mt(function () { cbd = cb; });
      var cbf = function () {
          var out = new u8(tot + 22), oe = o, cdl = tot - o;
          tot = 0;
          for (var i = 0; i < slft; ++i) {
              var f = files[i];
              try {
                  var l = f.c.length;
                  wzh(out, tot, f, f.f, f.u, l);
                  var badd = 30 + f.f.length + exfl(f.extra);
                  var loc = tot + badd;
                  out.set(f.c, loc);
                  wzh(out, o, f, f.f, f.u, l, tot, f.m), o += 16 + badd + (f.m ? f.m.length : 0), tot = loc + l;
              }
              catch (e) {
                  return cbd(e, null);
              }
          }
          wzf(out, o, files.length, cdl, oe);
          cbd(null, out);
      };
      if (!lft)
          cbf();
      var _loop_1 = function (i) {
          var fn = k[i];
          var _a = r[fn], file = _a[0], p = _a[1];
          var c = crc(), size = file.length;
          c.p(file);
          var f = strToU8(fn), s = f.length;
          var com = p.comment, m = com && strToU8(com), ms = m && m.length;
          var exl = exfl(p.extra);
          var compression = p.level == 0 ? 0 : 8;
          var cbl = function (e, d) {
              if (e) {
                  tAll();
                  cbd(e, null);
              }
              else {
                  var l = d.length;
                  files[i] = mrg(p, {
                      size: size,
                      crc: c.d(),
                      c: d,
                      f: f,
                      m: m,
                      u: s != fn.length || (m && (com.length != ms)),
                      compression: compression
                  });
                  o += 30 + s + exl + l;
                  tot += 76 + 2 * (s + exl) + (ms || 0) + l;
                  if (!--lft)
                      cbf();
              }
          };
          if (s > 65535)
              cbl(err(11, 0, 1), null);
          if (!compression)
              cbl(null, file);
          else if (size < 160000) {
              try {
                  cbl(null, deflateSync(file, p));
              }
              catch (e) {
                  cbl(e, null);
              }
          }
          else
              term.push(deflate(file, p, cbl));
      };
      // Cannot use lft because it can decrease
      for (var i = 0; i < slft; ++i) {
          _loop_1(i);
      }
      return tAll;
  }
  /**
   * Synchronously creates a ZIP file. Prefer using `zip` for better performance
   * with more than one file.
   * @param data The directory structure for the ZIP archive
   * @param opts The main options, merged with per-file options
   * @returns The generated ZIP archive
   */
  function zipSync$1(data, opts) {
      if (!opts)
          opts = {};
      var r = {};
      var files = [];
      fltn(data, '', r, opts);
      var o = 0;
      var tot = 0;
      for (var fn in r) {
          var _a = r[fn], file = _a[0], p = _a[1];
          var compression = p.level == 0 ? 0 : 8;
          var f = strToU8(fn), s = f.length;
          var com = p.comment, m = com && strToU8(com), ms = m && m.length;
          var exl = exfl(p.extra);
          if (s > 65535)
              err(11);
          var d = compression ? deflateSync(file, p) : file, l = d.length;
          var c = crc();
          c.p(file);
          files.push(mrg(p, {
              size: file.length,
              crc: c.d(),
              c: d,
              f: f,
              m: m,
              u: s != fn.length || (m && (com.length != ms)),
              o: o,
              compression: compression
          }));
          o += 30 + s + exl + l;
          tot += 76 + 2 * (s + exl) + (ms || 0) + l;
      }
      var out = new u8(tot + 22), oe = o, cdl = tot - o;
      for (var i = 0; i < files.length; ++i) {
          var f = files[i];
          wzh(out, f.o, f, f.f, f.u, f.c.length);
          var badd = 30 + f.f.length + exfl(f.extra);
          out.set(f.c, f.o + badd);
          wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0);
      }
      wzf(out, o, files.length, cdl, oe);
      return out;
  }
  var mt = typeof queueMicrotask == 'function' ? queueMicrotask : typeof setTimeout == 'function' ? setTimeout : function (fn) { fn(); };
  function unzip(data, opts, cb) {
      if (!cb)
          cb = opts, opts = {};
      if (typeof cb != 'function')
          err(7);
      var term = [];
      var tAll = function () {
          for (var i = 0; i < term.length; ++i)
              term[i]();
      };
      var files = {};
      var cbd = function (a, b) {
          mt(function () { cb(a, b); });
      };
      mt(function () { cbd = cb; });
      var e = data.length - 22;
      for (; b4(data, e) != 0x6054B50; --e) {
          if (!e || data.length - e > 65558) {
              cbd(err(13, 0, 1), null);
              return tAll;
          }
      }
      var lft = b2(data, e + 8);
      if (lft) {
          var c = lft;
          var o = b4(data, e + 16);
          var z = o == 4294967295 || c == 65535;
          if (z) {
              var ze = b4(data, e - 12);
              z = b4(data, ze) == 0x6064B50;
              if (z) {
                  c = lft = b4(data, ze + 32);
                  o = b4(data, ze + 48);
              }
          }
          var fltr = opts && opts.filter;
          var _loop_3 = function (i) {
              var _a = zh(data, o, z), c_1 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);
              o = no;
              var cbl = function (e, d) {
                  if (e) {
                      tAll();
                      cbd(e, null);
                  }
                  else {
                      if (d)
                          files[fn] = d;
                      if (!--lft)
                          cbd(null, files);
                  }
              };
              if (!fltr || fltr({
                  name: fn,
                  size: sc,
                  originalSize: su,
                  compression: c_1
              })) {
                  if (!c_1)
                      cbl(null, slc(data, b, b + sc));
                  else if (c_1 == 8) {
                      var infl = data.subarray(b, b + sc);
                      if (sc < 320000) {
                          try {
                              cbl(null, inflateSync(infl, new u8(su)));
                          }
                          catch (e) {
                              cbl(e, null);
                          }
                      }
                      else
                          term.push(inflate(infl, { size: su }, cbl));
                  }
                  else
                      cbl(err(14, 'unknown compression type ' + c_1, 1), null);
              }
              else
                  cbl(null, null);
          };
          for (var i = 0; i < c; ++i) {
              _loop_3(i);
          }
      }
      else
          cbd(null, {});
      return tAll;
  }
  /**
   * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better
   * performance with more than one file.
   * @param data The raw compressed ZIP file
   * @param opts The ZIP extraction options
   * @returns The decompressed files
   */
  function unzipSync$1(data, opts) {
      var files = {};
      var e = data.length - 22;
      for (; b4(data, e) != 0x6054B50; --e) {
          if (!e || data.length - e > 65558)
              err(13);
      }
      var c = b2(data, e + 8);
      if (!c)
          return {};
      var o = b4(data, e + 16);
      var z = o == 4294967295 || c == 65535;
      if (z) {
          var ze = b4(data, e - 12);
          z = b4(data, ze) == 0x6064B50;
          if (z) {
              c = b4(data, ze + 32);
              o = b4(data, ze + 48);
          }
      }
      var fltr = opts && opts.filter;
      for (var i = 0; i < c; ++i) {
          var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);
          o = no;
          if (!fltr || fltr({
              name: fn,
              size: sc,
              originalSize: su,
              compression: c_2
          })) {
              if (!c_2)
                  files[fn] = slc(data, b, b + sc);
              else if (c_2 == 8)
                  files[fn] = inflateSync(data.subarray(b, b + sc), new u8(su));
              else
                  err(14, 'unknown compression type ' + c_2);
          }
      }
      return files;
  }

  function runningInBrowser() {
    return typeof window !== 'undefined' && typeof window.document !== 'undefined';
  }

  var Env = /*#__PURE__*/Object.freeze({
    __proto__: null,
    runningInBrowser: runningInBrowser
  });

  // Checks if @arg is a Uint8Array containing gzipped data
  function isGzipped(arg) {
    return arg.length > 2 && arg.buffer instanceof ArrayBuffer && arg[0] == 0x1f && arg[1] == 0x8b;
  }

  function gzipSync(content, opts) {
    // TODO: use native module in Node if available
    // require('zlib').
    if (typeof content == 'string') {
      content = strToU8(content);
    }
    if (runningInBrowser()) {
      return gzipSync$1(content, opts);
    }
    return require('zlib').gzipSync(content, opts);
  }

  async function gzipAsync(content, opts) {
    if (typeof content == 'string') {
      content = strToU8(content);
    }
    var gzip$1 = runningInBrowser() ? utils.promisify(gzip) : utils.promisify(require('zlib').gzip);
    return gzip$1(content, opts);
  }

  async function gunzipAsync(buf, opts) {
    if (buf instanceof ArrayBuffer) {
      buf = new Uint8Array(buf);
    }
    opts = opts || {};
    var gunzip$1 = runningInBrowser() ? utils.promisify(gunzip) : utils.promisify(require('zlib').gunzip);
    var out = await gunzip$1(buf, opts);
    if (opts.filename && !isImportableAsBinary(opts.filename)) {
      out = strFromU8(out);
    }
    return out;
  }

  function gunzipSync(buf, filename) {
    if (buf instanceof ArrayBuffer) {
      buf = new Uint8Array(buf);
    }
    var out = gunzipSync$1(buf); // returns Uint8Array
    if (filename && !isImportableAsBinary(filename)) {
      out = strFromU8(out);
    }
    return out;
  }

  var Gzip = /*#__PURE__*/Object.freeze({
    __proto__: null,
    isGzipped: isGzipped,
    gzipSync: gzipSync,
    gzipAsync: gzipAsync,
    gunzipAsync: gunzipAsync,
    gunzipSync: gunzipSync
  });

  // Export in a column-first format
  // Faster than exportTable(), and can handle some data that can't be
  // converted to JSON, like Date objects.
  async function exportTable2(table) {
    var fields = table.getFields();
    var records = table.getRecords();
    var types = [];
    var columns = await Promise.all(fields.map(function(name) {
      var type = getColumnType(name, records);
      types.push(type);
      return exportColumn(name, type, records);
    }));
    return ({
      fields: fields,
      types: types,
      data: columns,
      size: records.length
    });
  }

  // Returns array of records
  function importTable(data) {
    if (looksLikeType2Table(data)) {
      return importTable2(data);
    }
    if (isGzipped(data)) {
      return JSON.parse(strFromU8(gunzipSync(data)));
    }
    if (Array.isArray(data)) {
      return data;
    }
    error('Unknown packed table format');
  }

  function looksLikeType2Table(o) {
    return Array.isArray(o.fields) &&
      Array.isArray(o.types) && Array.isArray(o.data) &&
      o.fields.length == o.types.length && o.fields.length == o.data.length &&
      o.size >= 0;
  }

  function importTable2(obj) {
    var n = obj.size;
    var records = [];
    for (var i=0; i<n; i++) {
      records[i] = {};
    }
    for (var j=0, m=obj.fields.length; j<m; j++) {
      importColumn(obj.fields[j], obj.types[j], obj.data[j], records);
      obj.data[j] = null;
    }
    return records;
  }

  function importColumn(field, type, data, records) {
    var arr, rec;
    if (isGzipped(data)) {
      arr = JSON.parse(strFromU8(gunzipSync(data)));
    } else if (Array.isArray(data)) {
      arr = data;
    } else {
      error('Unexpected packed table format');
    }
    for (var i=0, n=records.length; i<n; i++) {
      rec = records[i];
      rec[field] = arr[i];
    }
  }

  async function exportColumn(name, type, records) {
    if (type == 'number' || type == 'string') {
      return gzipAsync(JSON.stringify(getFieldValues(records, name)), {level: 2, consume: true});
    }
    return getFieldValues(records, name);
  }

  // faster for decimal numbers?
  // function exportNumberField(field, records) {
  //   var arr = new Float64Array(records.length);
  //   for (var i=0, n=records.length; i<n; i++) {
  //     arr[i] = records[i][field];
  //   }
  //   return gzipSync(arr, {level: 2});
  // }

  var PACKAGE_EXT = 'msx';

  // libraries
  // https://msgpack.org/index.html
  //

  // session format (including gui state)
  /*
  {
    version: 1,
    created: 'YYYY-MM-DDTHH:mm:ss.sssZ', // ISO string
    datasets: [],
    gui: {} // see gui-session-snapshot-control.mjs
  }
  */

  async function exportPackedDatasets(datasets, opts) {
    var content = pack(await exportDatasetsToPack(datasets, opts));
    return [{
      content: content,
      filename: opts.file || 'mapshaper_snapshot.' + PACKAGE_EXT
    }];
  }

  function pack(obj) {
    // encode options: see https://github.com/msgpack/msgpack-javascript
    // initialBufferSize  number  2048
    // ignoreUndefined boolean false
    return pack$1(obj, {});
  }

  // gui: (optional) gui instance
  //
  async function exportDatasetsToPack(datasets, opts) {
    var obj = {
      version: 1,
      created: (new Date).toISOString(),
      datasets: await Promise.all(datasets.map(exportDataset))
    };
    if (opts.compact) {
      await applyCompression(obj);
    }
    return obj;
  }

  async function applyCompression(obj, opts) {
    var promises = [];
    obj.datasets.forEach(d => {
      if (d.arcs) promises.push(compressArcs(d.arcs, opts));
    });
    await Promise.all(promises);
  }

  async function compressArcs(obj, opts) {
    var gzipOpts = Object.assign({level: 1, consume: false}, opts);
    var promises = [gzipAsync(obj.nn, gzipOpts), gzipAsync(obj.xx, gzipOpts), gzipAsync(obj.yy, gzipOpts)];
    if (obj.zz) promises.push(gzipAsync(obj.zz, gzipOpts));
    var results = await Promise.all(promises);
    obj.nn = results.shift();
    obj.xx = results.shift();
    obj.yy = results.shift();
    if (obj.zz) obj.zz = results.shift();
  }

  async function exportDataset(dataset, opts) {
    return {
      arcs: dataset.arcs ? exportArcs(dataset.arcs) : null,
      info: dataset.info ? exportInfo(dataset.info) : null,
      layers: await Promise.all((dataset.layers || []).map(exportLayer))
    };
  }

  function typedArrayToBuffer(arr) {
    return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
  }

  function exportArcs(arcs) {
    var data = arcs.getVertexData();
    return {
      nn: typedArrayToBuffer(data.nn),
      xx: typedArrayToBuffer(data.xx),
      yy: typedArrayToBuffer(data.yy),
      zz: data.zz ? typedArrayToBuffer(data.zz) : null,
      zlimit: arcs.getRetainedInterval()
    };
  }

  async function exportLayer(lyr) {
    var data = null;
    if (lyr.data) {
      data = await exportTable2(lyr.data);
    }
    return {
      name: lyr.name || null,
      geometry_type: lyr.geometry_type || null,
      shapes: lyr.shapes || null,
      data: data,
      menu_order: lyr.menu_order || null,
      pinned: lyr.pinned || false,
      active: lyr.active || false
    };
  }

  function exportInfo(info) {
    info = Object.assign({}, info);
    if (info.crs && !info.crs_string && !info.prj) {
      info.crs_string = crsToProj4(info.crs);
    }
    delete info.crs; // proj object cannot be serialized (need to reconstitute in unpack)
    return info;
  }

  var Pack = /*#__PURE__*/Object.freeze({
    __proto__: null,
    PACKAGE_EXT: PACKAGE_EXT,
    exportPackedDatasets: exportPackedDatasets,
    pack: pack,
    exportDatasetsToPack: exportDatasetsToPack,
    applyCompression: applyCompression,
    exportDataset: exportDataset
  });

  // Guess the type of a data file from file extension, or return null if not sure
  function guessInputFileType(file) {
    var ext = getFileExtension(file || '').toLowerCase(),
        type = null;
    if (ext == 'dbf' || ext == 'shp' || ext == 'prj' || ext == 'shx' || ext == 'kml' || ext == 'cpg') {
      type = ext;
    } else if (/json$/.test(ext)) {
      type = 'json';
    } else if (ext == 'csv' || ext == 'tsv' || ext == 'txt' || ext == 'tab') {
      type = 'text';
    } else if (ext == PACKAGE_EXT) {
      type = PACKAGE_EXT;
    }
    return type;
  }

  function guessInputContentType(content) {
    var type = null;
    if (utils.isString(content)) {
      type = stringLooksLikeJSON(content) && 'json' ||
        stringLooksLikeKML(content) && 'kml' || 'text';
    } else if (utils.isObject(content) && content.type || utils.isArray(content)) {
      type = 'json';
    }
    return type;
  }

  function guessInputType(file, content) {
    return guessInputFileType(file) || guessInputContentType(content);
  }

  function stringLooksLikeJSON(str) {
    return /^\s*[{[]/.test(String(str));
  }

  function stringLooksLikeKML(str) {
    str = String(str);
    return str.includes('<kml ') && str.includes('xmlns="http://www.opengis.net/kml/');
  }

  function couldBeDsvFile(name) {
    var ext = getFileExtension(name).toLowerCase();
    return /csv|tsv|txt$/.test(ext);
  }

  // File looks like an importable file type
  // name: filename or path
  function looksLikeImportableFile(name) {
    return !!guessInputFileType(name);
  }

  // File looks like a directly readable data file type
  // name: filename or path
  function looksLikeContentFile(name) {
    var type = guessInputFileType(name);
    return !!type && type != 'gz' && type != 'zip';
  }

  function isPackageFile(file) {
    return file.endsWith('.' + PACKAGE_EXT);
  }

  function isZipFile(file) {
    return /\.zip$/i.test(file);
  }

  function isKmzFile(file) {
    return /\.kmz$/i.test(file);
  }

  function isGzipFile(file) {
    return /\.gz/i.test(file);
  }

  function isSupportedOutputFormat(fmt) {
    var types = ['geojson', 'topojson', 'json', 'dsv', 'dbf', 'shapefile', 'svg', 'kml', PACKAGE_EXT];
    return types.indexOf(fmt) > -1;
  }

  function getFormatName(fmt) {
    return {
      geojson: 'GeoJSON',
      topojson: 'TopoJSON',
      json: 'JSON records',
      dsv: 'CSV',
      dbf: 'DBF',
      kml: 'KML',
      kmz: 'KMZ',
      [PACKAGE_EXT]: 'Snapshot file',
      shapefile: 'Shapefile',
      svg: 'SVG'
    }[fmt] || '';
  }

  // Assumes file at @path is one of Mapshaper's supported file types
  function isSupportedBinaryInputType(path) {
    var ext = getFileExtension(path).toLowerCase();
    return ext == 'shp' || ext == 'shx' || ext == 'dbf' || ext == PACKAGE_EXT; // GUI also supports zip files
  }

  function isImportableAsBinary(path) {
    var type = guessInputFileType(path);
    return isSupportedBinaryInputType(path) || isZipFile(path) ||
      isGzipFile(path) || isKmzFile(path) || isPackageFile(path) ||
      type == 'json' || type == 'text';
  }

  // Detect extensions of some unsupported file types, for cmd line validation
  function filenameIsUnsupportedOutputType(file) {
    var rxp = /\.(shx|prj|xls|xlsx|gdb|sbn|sbx|xml)$/i;
    return rxp.test(file);
  }

  var FileTypes = /*#__PURE__*/Object.freeze({
    __proto__: null,
    guessInputFileType: guessInputFileType,
    guessInputContentType: guessInputContentType,
    guessInputType: guessInputType,
    stringLooksLikeJSON: stringLooksLikeJSON,
    stringLooksLikeKML: stringLooksLikeKML,
    couldBeDsvFile: couldBeDsvFile,
    looksLikeImportableFile: looksLikeImportableFile,
    looksLikeContentFile: looksLikeContentFile,
    isPackageFile: isPackageFile,
    isZipFile: isZipFile,
    isKmzFile: isKmzFile,
    isGzipFile: isGzipFile,
    isSupportedOutputFormat: isSupportedOutputFormat,
    getFormatName: getFormatName,
    isSupportedBinaryInputType: isSupportedBinaryInputType,
    isImportableAsBinary: isImportableAsBinary,
    filenameIsUnsupportedOutputType: filenameIsUnsupportedOutputType
  });

  // input: A file path or a buffer
  function unzipSync(input) {
    if (input instanceof ArrayBuffer) {
      input = new Uint8Array(input);
    }
    if (!runningInBrowser()) {
      return unzipSyncNode(input);
    }
    var obj = unzipSync$1(input, {filter: fflateFilter});
    return fflatePostprocess(obj);
  }

  function unzipAsync(buf, cb) {
    if (!runningInBrowser()) {
      error('Async unzipping only supported in the browser');
    }
    if (buf instanceof ArrayBuffer) {
      buf = new Uint8Array(buf);
    }
    unzip(buf, {filter: fflateFilter}, function(err, data) {
      if (err) cb(err);
      cb(null, fflatePostprocess(data));
    });
  }

  function zipSync(files) {
    if (runningInBrowser()) {
      return zipSync$1(fflatePreprocess(files));
    }
    return zipSyncNode(files);
  }

  function zipAsync(files, cb) {
    zip(fflatePreprocess(files), {}, cb);
  }

  function fflateFilter(file) {
    return isImportableZipPath(file.name);
  }

  function fflatePostprocess(output) {
    return Object.keys(output).reduce(function(memo, path) {
      var file = parseLocalPath(path).filename;
      var content = output[path];
      if (!isImportableAsBinary(file)) {
        content = strFromU8(content);
      }
      memo[file] = content;
      return memo;
    }, {});
  }

  function isImportableZipPath(name) {
    var info = parseLocalPath(name);
    return looksLikeContentFile(name) &&
      !/^__MACOSX/.test(name) && // ignore "resource-fork" files
      info.filename[0] != '.'; // ignore dot files
  }

  // input: input file path or a Buffer containing .zip file bytes
  function unzipSyncNode(input) {
    var zip = new require('adm-zip')(input);
    var index = {};
    zip.getEntries().forEach(function(entry) {
      // entry.entryName // path, including filename
      // entry.name      // filename
      var file = toLowerCaseExtension(entry.name);
      if (isImportableZipPath(file)) {
        index[file] = entry.getData();
      }
    });
    return index;
  }

  function zipSyncNode(files) {
    var zip = new require('adm-zip')();
    files.forEach(function(o) {
      var buf = o.content;
      if (buf instanceof ArrayBuffer) {
        buf = new Uint8Array(buf);
      } else if (!(buf instanceof Buffer || buf instanceof Uint8Array)) {
        buf = Buffer.from(o.content);
      }
      zip.addFile(o.filename, buf);
      // delete o.content; // for gc?
    });
    return zip.toBuffer();
  }

  // Convert array of output file data to input format used by fflate zip
  function fflatePreprocess(files) {
    var obj = {};
    files.forEach(function(file) {
      if (typeof file.content == 'string') {
        file.content = strToU8(file.content);
      } else if (file.content instanceof ArrayBuffer) {
        file.content = new Uint8Array(file.content);
      }
      obj[file.filename] = file.content;
    });
    return obj;
  }

  var Zip = /*#__PURE__*/Object.freeze({
    __proto__: null,
    unzipSync: unzipSync,
    unzipAsync: unzipAsync,
    zipSync: zipSync,
    zipAsync: zipAsync,
    isImportableZipPath: isImportableZipPath
  });

  var cli = {};

  cli.isFile = function(path, cache) {
    if (cache && (path in cache)) return true;
    if (runningInBrowser()) return false;
    var ss = cli.statSync(path);
    return ss && ss.isFile() || false;
  };

  cli.checkCommandEnv = function(cname) {
    var blocked = ['i', 'include', 'require', 'external'];
    if (runningInBrowser() && blocked.includes(cname)) {
      stop('The -' + cname + ' command cannot be run in the browser');
    }
  };

  // cli.fileSize = function(path) {
  //   var ss = cli.statSync(path);
  //   return ss && ss.size || 0;
  // };

  cli.isDirectory = function(path) {
    if (runningInBrowser()) return false;
    var ss = cli.statSync(path);
    return ss && ss.isDirectory() || false;
  };

  // @encoding (optional) e.g. 'utf8'
  cli.readFile = function(fname, encoding, cache) {
    var content;
    if (cache && (fname in cache)) {
      content = cache[fname];
      delete cache[fname];
    } else if (fname == '/dev/stdin') {
      content = require$1('rw').readFileSync(fname);
    } else {
      // kludge to prevent overwriting of input files
      (getStashedVar('input_files') || []).push(fname);
      content = require$1('fs').readFileSync(fname);
    }
    if (encoding && B$3.isBuffer(content)) {
      content = trimBOM(decodeString(content, encoding));
    }
    return content;
  };

  cli.createDirIfNeeded = function(fname) {
    var odir = parseLocalPath(fname).directory;
    if (!odir || cli.isDirectory(odir) || fname == '/dev/stdout') return;
    try {
      require$1('fs').mkdirSync(odir, {recursive: true});
      message('Created output directory:', odir);
    } catch(e) {
      stop('Unable to create output directory:', odir);
    }
  };

  // content: Buffer or string
  cli.writeFile = function(fname, content, cb) {
    var fs = require$1('rw');
    cli.createDirIfNeeded(fname);
    if (cb) {
      fs.writeFile(fname, content, cb);
    } else {
      fs.writeFileSync(fname, content);
    }
  };

  // Returns Node Buffer
  cli.convertArrayBuffer = function(buf) {
    var src = new Uint8Array(buf),
        dest = utils.createBuffer(src.length);
    for (var i = 0, n=src.length; i < n; i++) {
      dest[i] = src[i];
    }
    return dest;
  };

  // Expand any "*" wild cards in file name
  // (For the Windows command line; unix shells do this automatically)
  cli.expandFileName = function(name) {
    var info = parseLocalPath(name),
        rxp = utils.wildcardToRegExp(info.filename),
        dir = info.directory || '.',
        files = [];

    try {
      require$1('fs').readdirSync(dir).forEach(function(item) {
        var path = require$1('path').join(dir, item);
        if (rxp.test(item) && cli.isFile(path)) {
          files.push(path);
        }
      });
    } catch(e) {}

    if (files.length === 0) {
      stop('No files matched (' + name + ')');
    }
    return files;
  };

  // Expand any wildcards.
  cli.expandInputFiles = function(files) {
    return files.reduce(function(memo, name) {
      if (name.indexOf('*') > -1) {
        memo = memo.concat(cli.expandFileName(name));
      } else {
        memo.push(name);
      }
      return memo;
    }, []);
  };

  cli.validateOutputDir = function(name) {
    if (!cli.isDirectory(name) && !runningInBrowser()) {
      error("Output directory not found:", name);
    }
  };

  // TODO: rename and improve
  // Want to test if a path is something readable (e.g. file or stdin)
  cli.checkFileExists = function(path, cache) {
    if (!cli.isFile(path, cache) && path != '/dev/stdin') {
      stop("File not found (" + path + ")");
    }
  };

  cli.statSync = function(fpath) {
    var obj = null;
    try {
      obj = require$1('fs').statSync(fpath);
    } catch(e) {}
    return obj;
  };

  function writeFiles(exports, opts, cb) {
    cb = cb || function() {};
    return _writeFiles(exports, opts, cb);
  }

  // Used by GUI to replace the CLI version of writeFiles()
  // (so -o can work in the browser console)
  function replaceWriteFiles(func) {
    _writeFiles = func;
  }

  var _writeFiles = function(exports, opts, cb) {
    if (exports.length > 0 === false) {
      message("No files to save");
    } else if (opts.dry_run) ; else if (opts.stdout) {
      // Pass callback for asynchronous output (synchronous output to stdout can
      // trigger EAGAIN error, e.g. when piped to less)
      return cli.writeFile('/dev/stdout', exports[0].content, cb);
    } else {
      if (opts.zip) {
        exports = [{
          // TODO: add output subdirectory, if relevant
          filename: opts.zipfile || 'output.zip',
          content: zipSync(exports)
        }];
      }
      var paths = getOutputPaths(utils.pluck(exports, 'filename'), opts);
      var inputFiles = getStashedVar('input_files');
      exports.forEach(function(obj, i) {
        var path = paths[i];
        if (obj.content instanceof ArrayBuffer) {
          // replacing content so ArrayBuffers can be gc'd
          obj.content = cli.convertArrayBuffer(obj.content); // convert to Buffer
        }
        if (opts.output) {
          opts.output.push({filename: path, content: obj.content});
          return;
        }
        if (!opts.force && inputFiles.indexOf(path) > -1) {
          stop('Need to use the "-o force" option to overwrite input files.');
        }
        cli.writeFile(path, obj.content);
        message("Wrote " + path);
      });
    }
    if (cb) cb(null);
  };

  function getOutputPaths(files, opts) {
    var odir = opts.directory;
    if (odir) {
      files = files.map(function(file) {
        return require$1('path').join(odir, file);
      });
    }
    return files;
  }

  var FileExport = /*#__PURE__*/Object.freeze({
    __proto__: null,
    writeFiles: writeFiles,
    replaceWriteFiles: replaceWriteFiles,
    getOutputPaths: getOutputPaths
  });

  // Returns a search function
  // Receives array of objects to index; objects must have a 'bounds' member
  //    that is a Bounds object.
  function getBoundsSearchFunction(boxes) {
    var index, Flatbush;
    if (!boxes.length) {
      // Unlike rbush, flatbush doesn't allow size 0 indexes; workaround
      return function() {return [];};
    }
    Flatbush = require$1('flatbush');
    index = new Flatbush(boxes.length);
    boxes.forEach(function(ring) {
      var b = ring.bounds;
      index.add(b.xmin, b.ymin, b.xmax, b.ymax);
    });
    index.finish();

    function idxToObj(i) {
      return boxes[i];
    }

    // Receives xmin, ymin, xmax, ymax parameters
    // Returns subset of original @bounds array
    return function(a, b, c, d) {
      return index.search(a, b, c, d).map(idxToObj);
    };
  }

  // @xx array of x coords
  // @ids an array of segment endpoint ids [a0, b0, a1, b1, ...]
  // Sort @ids in place so that xx[a(n)] <= xx[b(n)] and xx[a(n)] <= xx[a(n+1)]
  function sortSegmentIds(xx, ids) {
    orderSegmentIds(xx, ids);
    quicksortSegmentIds(xx, ids, 0, ids.length-2);
  }

  function orderSegmentIds(xx, ids, spherical) {
    function swap(i, j) {
      var tmp = ids[i];
      ids[i] = ids[j];
      ids[j] = tmp;
    }
    for (var i=0, n=ids.length; i<n; i+=2) {
      if (xx[ids[i]] > xx[ids[i+1]]) {
        swap(i, i+1);
      }
    }
  }

  function insertionSortSegmentIds(arr, ids, start, end) {
    var id, id2;
    for (var j = start + 2; j <= end; j+=2) {
      id = ids[j];
      id2 = ids[j+1];
      for (var i = j - 2; i >= start && arr[id] < arr[ids[i]]; i-=2) {
        ids[i+2] = ids[i];
        ids[i+3] = ids[i+1];
      }
      ids[i+2] = id;
      ids[i+3] = id2;
    }
  }

  function quicksortSegmentIds (a, ids, lo, hi) {
    var i = lo,
        j = hi,
        pivot, tmp;
    while (i < hi) {
      pivot = a[ids[(lo + hi >> 2) << 1]]; // avoid n^2 performance on sorted arrays
      while (i <= j) {
        while (a[ids[i]] < pivot) i+=2;
        while (a[ids[j]] > pivot) j-=2;
        if (i <= j) {
          tmp = ids[i];
          ids[i] = ids[j];
          ids[j] = tmp;
          tmp = ids[i+1];
          ids[i+1] = ids[j+1];
          ids[j+1] = tmp;
          i+=2;
          j-=2;
        }
      }

      if (j - lo < 40) insertionSortSegmentIds(a, ids, lo, j);
      else quicksortSegmentIds(a, ids, lo, j);
      if (hi - i < 40) {
        insertionSortSegmentIds(a, ids, i, hi);
        return;
      }
      lo = i;
      j = hi;
    }
  }

  // PolygonIndex indexes the coordinates in one polygon feature for efficient
  // point-in-polygon tests

  function PolygonIndex(shape, arcs, opts) {
    var data = arcs.getVertexData(),
        polygonBounds = arcs.getMultiShapeBounds(shape),
        boundsLeft,
        xminIds, xmaxIds, // vertex ids of segment endpoints
        bucketCount,
        bucketOffsets,
        bucketWidth;

    init();

    // Return 0 if outside, 1 if inside, -1 if on boundary
    this.pointInPolygon = function(x, y) {
      if (!polygonBounds.containsPoint(x, y)) {
        return false;
      }
      var bucketId = getBucketId(x);
      var count = countCrosses(x, y, bucketId);
      if (bucketId > 0) {
        count += countCrosses(x, y, bucketId - 1);
      }
      count += countCrosses(x, y, bucketCount); // check oflo bucket
      if (isNaN(count)) return -1;
      return count % 2 == 1 ? 1 : 0;
    };

    function countCrosses(x, y, bucketId) {
      var offs = bucketOffsets[bucketId],
          count = 0,
          xx = data.xx,
          yy = data.yy,
          n, a, b;
      if (bucketId == bucketCount) { // oflo bucket
        n = xminIds.length - offs;
      } else {
        n = bucketOffsets[bucketId + 1] - offs;
      }
      for (var i=0; i<n; i++) {
        a = xminIds[i + offs];
        b = xmaxIds[i + offs];
        count += geom.testRayIntersection(x, y, xx[a], yy[a], xx[b], yy[b]);
      }
      return count;
    }

    function getBucketId(x) {
      var i = Math.floor((x - boundsLeft) / bucketWidth);
      if (i < 0) i = 0;
      if (i >= bucketCount) i = bucketCount - 1;
      return i;
    }

    function getBucketCount(segCount) {
      // default is this many segs per bucket (average)
      // var buckets = opts && opts.buckets > 0 ? opts.buckets : segCount / 200;
      // using more segs/bucket for more complex shapes, based on trial and error
      var buckets = Math.pow(segCount, 0.75) / 10;
      return Math.ceil(buckets);
    }

    function init() {
      var xx = data.xx,
          segCount = 0,
          segId = 0,
          bucketId = -1,
          prevBucketId,
          segments,
          head, tail,
          a, b, i, j, xmin, xmax;

      // get array of segments as [s0p0, s0p1, s1p0, s1p1, ...], sorted by xmin coordinate
      forEachSegmentInShape(shape, arcs, function() {
        segCount++;
      });
      segments = new Uint32Array(segCount * 2);
      i = 0;
      forEachSegmentInShape(shape, arcs, function(a, b, xx, yy) {
        segments[i++] = a;
        segments[i++] = b;
      });
      sortSegmentIds(xx, segments);

      // assign segments to buckets according to xmin coordinate
      xminIds = new Uint32Array(segCount);
      xmaxIds = new Uint32Array(segCount);
      bucketCount = getBucketCount(segCount);
      bucketOffsets = new Uint32Array(bucketCount + 1); // add an oflo bucket
      boundsLeft = xx[segments[0]]; // xmin of first segment
      bucketWidth = (xx[segments[segments.length - 2]] - boundsLeft) / bucketCount;
      head = 0; // insertion index for next segment in the current bucket
      tail = segCount - 1; // insertion index for next segment in oflo bucket

      while (segId < segCount) {
        j = segId * 2;
        a = segments[j];
        b = segments[j+1];
        xmin = xx[a];
        xmax = xx[b];
        prevBucketId = bucketId;
        bucketId = getBucketId(xmin);

        while (bucketId > prevBucketId) {
          prevBucketId++;
          bucketOffsets[prevBucketId] = head;
        }

        if (xmax - xmin >= 0 === false) error("Invalid segment");
        if (getBucketId(xmax) - bucketId > 1) {
          // if segment extends to more than two buckets, put it in the oflo bucket
          xminIds[tail] = a;
          xmaxIds[tail] = b;
          tail--; // oflo bucket fills from right to left
        } else {
          // else place segment in a bucket based on x coord of leftmost endpoint
          xminIds[head] = a;
          xmaxIds[head] = b;
          head++;
        }
        segId++;
      }
      bucketOffsets[bucketCount] = head;
      if (head != tail + 1) error("Segment indexing error");
    }
  }

  // PathIndex supports several kinds of spatial query on a layer of polyline or polygon shapes
  function PathIndex(shapes, arcs) {
    var boundsQuery = getBoundsSearchFunction(getRingData(shapes, arcs));
    var totalArea = getPathBounds(shapes, arcs).area();

    function getRingData(shapes, arcs) {
      var arr = [];
      shapes.forEach(function(shp, shpId) {
        var n = shp ? shp.length : 0;
        for (var i=0; i<n; i++) {
          arr.push({
            ids: shp[i],
            id: shpId,
            bounds: arcs.getSimpleShapeBounds(shp[i])
          });
        }
      });
      return arr;
    }

    // Returns shape ids of all polygons that intersect point p
    // (p is inside a ring or on the boundary)
    this.findEnclosingShapes = function(p) {
      var ids = [];
      var cands = findPointHitCandidates(p);
      var groups = groupItemsByShapeId(cands);
      groups.forEach(function(group) {
        if (testPointInRings(p, group)) {
          ids.push(group[0].id);
        }
      });
      return ids;
    };

    // Returns shape id of a polygon that intersects p or -1
    // (If multiple intersections, returns one of the polygons)
    this.findEnclosingShape = function(p) {
      var shpId = -1;
      var groups = groupItemsByShapeId(findPointHitCandidates(p));
      groups.forEach(function(group) {
        if (testPointInRings(p, group)) {
          shpId = group[0].id;
        }
      });
      return shpId;
    };

    // Returns shape ids of polygons that contain an arc
    // (arcs that are )
    // Assumes that input arc is either inside, outside or coterminous with indexed
    // arcs (i.e. input arc does not cross an indexed arc)
    this.findShapesEnclosingArc = function(arcId) {
      var p = getTestPoint([arcId]);
      return this.findEnclosingShapes(p);
    };

    this.findPointEnclosureCandidates = function(p, buffer) {
      var items = findPointHitCandidates(p, buffer);
      return utils.pluck(items, 'id');
    };

    this.pointIsEnclosed = function(p) {
      return testPointInRings(p, findPointHitCandidates(p));
    };

    // Finds the polygon containing the smallest ring that entirely contains @ring
    // Assumes ring boundaries do not cross.
    // Unhandled edge case:
    //   two rings share at least one segment but are not congruent.
    // @ring: array of arc ids
    // Returns id of enclosing polygon or -1 if none found
    this.findSmallestEnclosingPolygon = function(ring) {
      var bounds = arcs.getSimpleShapeBounds(ring);
      var p = getTestPoint(ring);
      var smallest;
      var cands = findPointHitCandidates(p);
      cands.forEach(function(cand) {
        if (cand.bounds.contains(bounds) && // skip partially intersecting bboxes (can't be enclosures)
          !cand.bounds.sameBounds(bounds) && // skip self, congruent and reversed-congruent rings
          !(smallest && smallest.bounds.area() < cand.bounds.area())) {
              if (testPointInRing(p, cand)) {
                smallest = cand;
              }
            }
      });

      return smallest ? smallest.id : -1;
    };

    this.arcIsEnclosed = function(arcId) {
      return this.pointIsEnclosed(getTestPoint([arcId]));
    };

    // Test if a polygon ring is contained within an indexed ring
    // Not a true polygon-in-polygon test
    // Assumes that the target ring does not cross an indexed ring at any point
    // or share a segment with an indexed ring. (Intersecting rings should have
    // been detected previously).
    //
    this.pathIsEnclosed = function(pathIds) {
      return this.pointIsEnclosed(getTestPoint(pathIds));
    };

    // return array of paths that are contained within a path, or null if none
    // @pathIds Array of arc ids comprising a closed path
    this.findEnclosedPaths = function(pathIds) {
      var b = arcs.getSimpleShapeBounds(pathIds),
          cands = boundsQuery(b.xmin, b.ymin, b.xmax, b.ymax),
          paths = [],
          index;

      if (cands.length > 6) {
        index = new PolygonIndex([pathIds], arcs);
      }
      cands.forEach(function(cand) {
        var p = getTestPoint(cand.ids);
        var isEnclosed = b.containsPoint(p[0], p[1]) && (index ?
          index.pointInPolygon(p[0], p[1]) : geom.testPointInRing(p[0], p[1], pathIds, arcs));
        if (isEnclosed) {
          paths.push(cand.ids);
        }
      });
      return paths.length > 0 ? paths : null;
    };

    this.findPathsInsideShape = function(shape) {
      var paths = []; // list of enclosed paths
      shape.forEach(function(ids) {
        var enclosed = this.findEnclosedPaths(ids);
        if (enclosed) {
          // any paths that are enclosed by an even number of rings are removed from list
          // (given normal topology, such paths are inside holes)
          paths = xorArrays(paths, enclosed);
        }
      }, this);
      return paths.length > 0 ? paths : null;
    };

    function testPointInRing(p, cand) {
      if (!cand.bounds.containsPoint(p[0], p[1])) return false;
      if (!cand.index && cand.bounds.area() > totalArea * 0.01) {
        // index larger polygons (because they are slower to test via pointInRing()
        //    and they are more likely to be involved in repeated hit tests).
        cand.index = new PolygonIndex([cand.ids], arcs);
      }
      return cand.index ?
          cand.index.pointInPolygon(p[0], p[1]) :
          geom.testPointInRing(p[0], p[1], cand.ids, arcs);
    }

    //
    function testPointInRings(p, cands) {
      var isOn = false,
          isIn = false;
      cands.forEach(function(cand) {
        var inRing = testPointInRing(p, cand);
        if (inRing == -1) {
          isOn = true;
        } else if (inRing == 1) {
          isIn = !isIn;
        }
      });
      return isOn || isIn;
    }

    function groupItemsByShapeId(items) {
      var groups = [],
          group, item;
      if (items.length > 0) {
        items.sort(function(a, b) {return a.id - b.id;});
        for (var i=0; i<items.length; i++) {
          item = items[i];
          if (i === 0 || item.id != items[i-1].id) {
            groups.push(group=[]);
          }
          group.push(item);
        }
      }
      return groups;
    }

    function findPointHitCandidates(p, buffer) {
      var b = buffer > 0 ? buffer : 0;
      p[0]; p[1];
      return boundsQuery(p[0] - b, p[1] - b, p[0] + b, p[1] + b);
    }

    // Find a point on a ring to use for point-in-polygon testing
    function getTestPoint(ring) {
      // Use the point halfway along first segment rather than an endpoint
      // (because ring might still be enclosed if a segment endpoint touches an indexed ring.)
      // The returned point should work for point-in-polygon testing if two rings do not
      // share any common segments (which should be true for topological datasets)
      // TODO: consider alternative of finding an internal point of @ring (slower but
      //   potentially more reliable).
      var arcId = ring[0],
          p0 = arcs.getVertex(arcId, 0),
          p1 = arcs.getVertex(arcId, 1);
      return [(p0.x + p1.x) / 2, (p0.y + p1.y) / 2];
    }

    // concatenate arrays, removing elements that are in both
    function xorArrays(a, b) {
      var xor = [], i;
      for (i=0; i<a.length; i++) {
        if (b.indexOf(a[i]) == -1) xor.push(a[i]);
      }
      for (i=0; i<b.length; i++) {
        if (a.indexOf(b[i]) == -1) xor.push(b[i]);
      }
      return xor;
    }
  }

  // Delete rings that are nested directly inside an enclosing ring with the same winding direction
  // Does not remove unenclosed CCW rings (currently this causes problems when
  //   rounding coordinates for SVG and TopoJSON output)
  // Assumes ring boundaries do not overlap (should be true after e.g. dissolving)
  //
  function fixNestingErrors(rings, arcs) {
    if (rings.length <= 1) return rings;
    var ringData = getPathMetadata(rings, arcs, 'polygon');
    // convert rings to shapes for PathIndex
    var shapes = rings.map(function(ids) {return [ids];});
    var index = new PathIndex(shapes, arcs);
    return rings.filter(ringIsValid);

    function ringIsValid(ids, i) {
      var containerId = index.findSmallestEnclosingPolygon(ids);
      var ringIsCW, containerIsCW;
      var valid = true;
      if (containerId > -1) {
        ringIsCW = ringData[i].area > 0;
        containerIsCW = ringData[containerId].area > 0;
        if (containerIsCW == ringIsCW) {
          // reject rings with same chirality as their containing ring
          valid = false;
        }
      }
      return valid;
    }
  }

  // Set winding order of polygon rings so that outer rings are CW, first-order
  // nested rings are CCW, etc.
  function rewindPolygons(lyr, arcs) {
    lyr.shapes = lyr.shapes.map(function(shp) {
      if (!shp) return null;
      return rewindPolygon(shp, arcs);
    });
  }

  // Update winding order of rings in a polygon so that outermost rings are
  // CW and nested rings alternate between CCW and CW.
  function rewindPolygon(rings, arcs) {
    var ringData = getPathMetadata(rings, arcs, 'polygon');

    // Sort rings by area, from large to small
    ringData.sort(function(a, b) {
      return Math.abs(b.area) - Math.abs(a.area);
    });
    // If a ring is contained by one or more rings, set it to the opposite
    //   direction as its immediate parent
    // If a ring is not contained, make it CW.
    ringData.forEach(function(ring, i) {
      var shouldBeCW = true;
      var j = i;
      var largerRing;
      while (--j >= 0) {
        largerRing = ringData[j];
        if (testRingInRing(ring, largerRing, arcs)) {
          // set to opposite of containing ring
          shouldBeCW = largerRing.area > 0 ? false : true;
          break;
        }
      }
      setRingWinding(ring, shouldBeCW);
    });
    return ringData.map(function(data) { return data.ids; });
  }

  // data: a ring data object
  function setRingWinding(data, cw) {
    var isCW = data.area > 0;
    if (isCW != cw) {
      data.area = -data.area;
      reversePath(data.ids);
    }
  }

  // a, b: two ring data objects (from getPathMetadata);
  function testRingInRing(a, b, arcs) {
    if (b.bounds.contains(a.bounds) === false) return false;
    // Don't test with first point -- this may return false if a hole intersects
    // the containing ring at the first vertex.
    // Instead, use the midpoint of the first segment
    var p = getFirstMidpoint(a.ids[0], arcs);
    //// test with first point in the ring
    // var p = arcs.getVertex(a.ids[0], 0);
    return geom.testPointInRing(p.x, p.y, b.ids, arcs) == 1;
  }

  function getFirstMidpoint(arcId, arcs) {
    var p1 = arcs.getVertex(arcId, 0);
    var p2 = arcs.getVertex(arcId, 1);
    return {
      x: (p1.x + p2.x) / 2,
      y: (p1.y + p2.y) / 2
    };
  }

  // Bundle holes with their containing rings for Topo/GeoJSON polygon export.
  // Assumes outer rings are CW and inner (hole) rings are CCW, unless
  //   the reverseWinding flag is set.
  // @paths array of objects with path metadata -- see internal.exportPathData()
  //
  function groupPolygonRings(paths, arcs, reverseWinding) {
    var holes = [],
        groups = [],
        sign = reverseWinding ? -1 : 1,
        boundsQuery;

    (paths || []).forEach(function(path) {
      if (path.area * sign > 0) {
        groups.push([path]);
      } else if (path.area * sign < 0) {
        holes.push(path);
      } else ;
    });

    if (holes.length === 0) {
      return groups;
    }

    // Using a spatial index to improve performance when the current feature
    // contains many holes and space-filling rings.
    // (Thanks to @simonepri for providing an example implementation in PR #248)
    boundsQuery = getBoundsSearchFunction(groups.map(function(group, i) {
      return {
        bounds: group[0].bounds,
        idx: i
      };
    }));

    // Group each hole with its containing ring
    holes.forEach(function(hole) {
      var containerId = -1,
          containerArea = 0,
          holeArea = hole.area * -sign,
          b = hole.bounds,
          // Find rings that might contain this hole
          candidates = boundsQuery(b.xmin, b.ymin, b.xmax, b.ymax),
          ring, ringId, ringArea, isContained;

      // Group this hole with the smallest-area ring that contains it.
      // (Assumes that if a ring's bbox contains a hole, then the ring also
      //  contains the hole).
      for (var i=0, n=candidates.length; i<n; i++) {
        ringId = candidates[i].idx;
        ring = groups[ringId][0];
        ringArea = ring.area * sign;
        isContained = ring.bounds.contains(hole.bounds) && ringArea > holeArea;
        if (isContained && candidates.length > 1 && !testRingInRing(hole, ring, arcs)) {
          // Using a more precise ring-in-ring test in the unusual case that
          // this hole is contained within the bounding box of multiple rings.
          // TODO: consider doing a ring-in-ring test even when there is only one
          // candidate ring, based on bbox-in-bbox test (this may affect performance
          // with some datasets).
          continue;
        }
        if (isContained && (containerArea === 0 || ringArea < containerArea)) {
          containerArea = ringArea;
          containerId = ringId;
        }
      }
      if (containerId == -1) {
        debug("[groupPolygonRings()] polygon hole is missing a containing ring, dropping.");
      } else {
        groups[containerId].push(hole);
      }
    });

    return groups;
  }

  function exportPointData(points) {
    var data, path;
    if (!points || points.length === 0) {
      data = {partCount: 0, pointCount: 0};
    } else {
      path = {
        points: points,
        pointCount: points.length,
        bounds: geom.getPathBounds(points)
      };
      data = {
        bounds: path.bounds,
        pathData: [path],
        partCount: 1,
        pointCount: path.pointCount
      };
    }
    return data;
  }

  // TODO: remove duplication with internal.getPathMetadata()
  function exportPathData(shape, arcs, type) {
    // kludge until Shapefile exporting is refactored
    if (type == 'point') return exportPointData(shape);

    var pointCount = 0,
        bounds = new Bounds(),
        paths = [];

    if (shape && (type == 'polyline' || type == 'polygon')) {
      shape.forEach(function(arcIds, i) {
        var iter = arcs.getShapeIter(arcIds),
            path = exportPathCoords(iter),
            valid = true;
        path.ids = arcIds;
        if (type == 'polygon') {
          path.area = geom.getPlanarPathArea2(path.points);
          valid = path.pointCount > 3 && path.area !== 0;
        } else if (type == 'polyline') {
          valid = path.pointCount > 1;
        }
        if (valid) {
          pointCount += path.pointCount;
          path.bounds = geom.getPathBounds(path.points);
          bounds.mergeBounds(path.bounds);
          paths.push(path);
        } else {
          verbose("Skipping a collapsed", type, "path");
        }
      });
    }

    return {
      pointCount: pointCount,
      pathData: paths,
      pathCount: paths.length,
      bounds: bounds
    };
  }

  function exportPathCoords(iter) {
    var points = [],
        i = 0,
        x, y, prevX, prevY;
    while (iter.hasNext()) {
      x = iter.x;
      y = iter.y;
      if (i === 0 || prevX != x || prevY != y) {
        points.push([x, y]);
        i++;
      }
      prevX = x;
      prevY = y;
    }
    return {
      points: points,
      pointCount: points.length
    };
  }

  var PathExport = /*#__PURE__*/Object.freeze({
    __proto__: null,
    exportPointData: exportPointData,
    exportPathData: exportPathData
  });

  function stringifyAsNDJSON(o) {
    var str = JSON.stringify(o);
    return str.replace(/\n/g, '\n').replace(/\r/g, '\r');
  }

  function getFormattedStringify(numArrayKeys) {
    var keyIndex = utils.arrayToIndex(numArrayKeys);
    var sentinel = '\u1000\u2FD5\u0310';
    var stripRxp = new RegExp('"' + sentinel + '|' + sentinel + '"', 'g');
    var indentChars = '  ';

    function replace(key, val) {
      // We want to format numerical arrays like [1, 2, 3] instead of
      // the way JSON.stringify() behaves when applying indentation.
      // This kludge converts arrays to strings with sentinel strings inside the
      // surrounding quotes. At the end, the sentinel strings and quotes
      // are replaced by array brackets.
      if (key in keyIndex && utils.isArray(val)) {
        var str = JSON.stringify(val);
        // make sure the array does not contain any strings
        if (str.indexOf('"' == -1)) {
          return sentinel + str.replace(/,/g, ', ') + sentinel;
        }
      }
      return val;
    }

    return function(obj) {
      var json = JSON.stringify(obj, replace, indentChars);
      return json.replace(stripRxp, '');
    };
  }

  var Stringify = /*#__PURE__*/Object.freeze({
    __proto__: null,
    stringifyAsNDJSON: stringifyAsNDJSON,
    getFormattedStringify: getFormattedStringify
  });

  function isValidArc(arcId, arcs) {
    // check for arcs with no vertices
    // TODO: also check for other kinds of degenerate arcs
    // (e.g. collapsed arcs consisting of identical points)
    return arcs.getArcLength(arcId) > 1;
  }

  // Return id of rightmost connected arc in relation to @fromArcId
  // Return @fromArcId if no arcs can be found
  function getRightmostArc(fromArcId, nodes, filter) {
    var arcs = nodes.arcs,
        coords = arcs.getVertexData(),
        xx = coords.xx,
        yy = coords.yy,
        ids = nodes.getConnectedArcs(fromArcId),
        toArcId = fromArcId; // initialize to fromArcId -- an error condition

    if (filter) {
      ids = ids.filter(filter);
    }

    if (!isValidArc(fromArcId, arcs) || ids.length === 0) {
      return fromArcId;
    }

    var inode = arcs.indexOfVertex(fromArcId, -1),
        nodeX = xx[inode],
        nodeY = yy[inode],
        ifrom = arcs.indexOfVertex(fromArcId, -2),
        fromX = xx[ifrom],
        fromY = yy[ifrom],
        ito, candId, icand, code, j;

    /*if (x == ax && y == ay) {
      error("Duplicate point error");
    }*/


    for (j=0; j<ids.length; j++) {
      candId = ids[j];
      if (!isValidArc(candId, arcs)) {
        // skip empty arcs
        continue;
      }
      icand = arcs.indexOfVertex(candId, -2);

      if (toArcId == fromArcId) {
        // first valid candidate
        ito = icand;
        toArcId = candId;
        continue;
      }

      code = chooseRighthandPath(fromX, fromY, nodeX, nodeY, xx[ito], yy[ito], xx[icand], yy[icand]);
      if (code == 2) {
        ito = icand;
        toArcId = candId;
      }
    }

    if (toArcId == fromArcId) {
      // This shouldn't occur, assuming that other arcs are present
      error("Pathfinder error");
    }
    return toArcId;
  }

  // TODO: consider using simpler internal.chooseRighthandPath2()
  // Returns 1 if node->a, return 2 if node->b, else return 0
  // TODO: better handling of identical angles (better -- avoid creating them)
  function chooseRighthandPath(fromX, fromY, nodeX, nodeY, ax, ay, bx, by) {
    var angleA = geom.signedAngle(fromX, fromY, nodeX, nodeY, ax, ay);
    var angleB = geom.signedAngle(fromX, fromY, nodeX, nodeY, bx, by);
    var code;
    if (angleA <= 0 || angleB <= 0) {
      debug("[chooseRighthandPath()] 0 angle(s):", angleA, angleB);
      if (angleA <= 0) {
        debug('  A orient2D:', geom.orient2D(fromX, fromY, nodeX, nodeY, ax, ay));
      }
      if (angleB <= 0) {
        debug('  B orient2D:', geom.orient2D(fromX, fromY, nodeX, nodeY, bx, by));
      }
      // TODO: test against "from" segment
      if (angleA > 0) {
        code = 1;
      } else if (angleB > 0) {
        code = 2;
      } else {
        code = 0;
      }
    } else if (angleA < angleB) {
      code = 1;
    } else if (angleB < angleA) {
      code = 2;
    } else if (isNaN(angleA) || isNaN(angleB)) {
      // probably a duplicate point, which should not occur
      error('Invalid node geometry');
    } else {
      // Equal angles: use fallback test that is less sensitive to rounding error
      code = chooseRighthandVector(ax - nodeX, ay - nodeY, bx - nodeX, by - nodeY);
      debug('[chooseRighthandPath()] equal angles:', angleA, 'fallback test:', code);
    }
    return code;
  }

  function chooseRighthandVector(ax, ay, bx, by) {
    var orient = geom.orient2D(ax, ay, 0, 0, bx, by);
    var code;
    if (orient > 0) {
      code = 2;
    } else if (orient < 0) {
      code = 1;
    } else {
      code = 0;
    }
    return code;
  }

  var PathfinderUtils = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getRightmostArc: getRightmostArc,
    chooseRighthandVector: chooseRighthandVector
  });

  function setBits(bits, arcBits, mask) {
    return (bits & ~mask) | (arcBits & mask);
  }

  function andBits(bits, arcBits, mask) {
    return bits & (~mask | arcBits);
  }

  function setRouteBits(arcBits, arcId, routesArr) {
    var idx = absArcId(arcId), // get index of path in
        mask;
    if (idx == arcId) { // arcBits controls fwd path
      mask = ~3; // target fwd bits
    } else { // arcBits controls rev. path
      mask = ~0x30; // target rev bits
      arcBits = arcBits << 4; // shift code to target rev path
    }
    routesArr[idx] &= (arcBits | mask);
  }

  function getRouteBits(arcId, routesArr) {
    var idx = absArcId(arcId),
        bits = routesArr[idx];
    if (idx != arcId) bits = bits >> 4;
    return bits & 7;
  }

  // Open arc pathways in a single shape or array of shapes
  //
  function openArcRoutes(paths, arcColl, routesArr, fwd, rev, dissolve, orBits) {
    forEachArcId(paths, function(arcId) {
      var isInv = arcId < 0,
          idx = isInv ? ~arcId : arcId,
          currBits = routesArr[idx],
          openFwd = isInv ? rev : fwd,
          openRev = isInv ? fwd : rev,
          newBits = currBits;

      // error condition: lollipop arcs can cause problems; ignore these
      if (arcColl.arcIsLollipop(arcId)) {
        debug('lollipop');
        newBits = 0; // unset (i.e. make invisible)
      } else {
        if (openFwd) {
          newBits |= 3; // set fwd path to visible and open
        }
        if (openRev) {
          newBits |= 0x30; // set rev. path to visible and open
        }

        // placing this in front of dissolve - dissolve has to be able to hide
        // pathways that are made visible by orBits
        if (orBits > 0) {
          newBits |= orBits;
        }

        // dissolve hides arcs that have both fw and rev pathways open
        // (these arcs represent shared borders and will not be part of the dissolved path)
        //
        if (dissolve && (newBits & 0x22) === 0x22) {
          newBits &= ~0x11; // make invisible
        }
      }

      routesArr[idx] = newBits;
    });
  }

  function closeArcRoutes(arcIds, arcs, routesArr, fwd, rev, hide) {
    forEachArcId(arcIds, function(arcId) {
      var isInv = arcId < 0,
          idx = isInv ? ~arcId : arcId,
          currBits = routesArr[idx],
          mask = 0xff,
          closeFwd = isInv ? rev : fwd,
          closeRev = isInv ? fwd : rev;

      if (closeFwd) {
        if (hide) mask &= ~1;
        mask ^= 0x2;
      }
      if (closeRev) {
        if (hide) mask &= ~0x10;
        mask ^= 0x20;
      }
      routesArr[idx] = currBits & mask;
    });
  }

  // Return a function for generating a path across a graph of connected arcs
  // useRoute: function(arcId) {}
  //           Tries to extend path to the given arc
  //           Returns true and extends path by one arc on success
  //           Returns false and rejects the entire path on failure
  // routeIsUsable (optional): function(arcId) {}
  //           An optional filter function; pathfinder ignores the given arc if
  //           this function returns false;
  // TODO: add option to use spherical geometry for lat-lng coords
  //
  function getPathFinder(nodes, useRoute, routeIsUsable) {
    var testArc = null;
    if (routeIsUsable) {
      testArc = function(arcId) {
        return routeIsUsable(~arcId); // outward path must be traversable
      };
    }

    function getNextArc(prevId) {
      // reverse arc to point onwards
      return ~getRightmostArc(prevId, nodes, testArc);
    }

    function isEmptyArc(id) {
      return nodes.arcs.getArcLength(id) > 1 === false;
    }

    return function(startId) {
      var path = [],
          nextId, candId = startId;

      if (isEmptyArc(startId)) {
        return null;
      }

      do {
        if (useRoute(candId)) {
          path.push(candId);
          nextId = candId;
          candId = getNextArc(nextId);
        } else {
          return null;
        }

        if (candId == ~nextId) {
          // TODO: handle or prevent this error condition
          debug("Pathfinder warning: dead-end path");
          return null;
        }
      } while (candId != startId);
      return path.length === 0 ? null : path;
    };
  }

  // Returns a function for flattening or dissolving a collection of rings
  // Assumes rings are oriented in CW direction
  //
  function getRingIntersector(nodes, flagsArr) {
    var arcs = nodes.arcs;
    var findPath = getPathFinder(nodes, useRoute, routeIsActive);
    flagsArr = flagsArr || new Uint8Array(arcs.size());

    // types: "dissolve" "flatten"
    return function(rings, type) {
      var dissolve = type == 'dissolve',
          openFwd = true,
          openRev = type == 'flatten',
          output;
      // even single rings get transformed (e.g. to remove spikes)
      if (rings.length > 0) {
        output = [];
        openArcRoutes(rings, arcs, flagsArr, openFwd, openRev, dissolve);
        forEachShapePart(rings, function(ids) {
          var path;
          for (var i=0, n=ids.length; i<n; i++) {
            path = findPath(ids[i]);
            if (path) {
              output.push(path);
            }
          }
        });
        closeArcRoutes(rings, arcs, flagsArr, openFwd, openRev, true);
      } else {
        output = rings;
      }
      return output;
    };

    function routeIsActive(arcId) {
      var bits = getRouteBits(arcId, flagsArr);
      return (bits & 1) == 1;
    }

    function useRoute(arcId) {
      var route = getRouteBits(arcId, flagsArr),
          isOpen = false;
      if (route == 3) {
        isOpen = true;
        setRouteBits(1, arcId, flagsArr); // close the path, leave visible
      }
      return isOpen;
    }
  }

  // function debugFlags(flags) {
  //   var arr = [];
  //   utils.forEach(flags, function(flag) {
  //     arr.push(bitsToString(flag));
  //   });
  //   message(arr);

  //   function bitsToString(bits) {
  //     var str = "";
  //     for (var i=0; i<8; i++) {
  //       str += (bits & (1 << i)) > 0 ? "1" : "0";
  //       if (i < 7) str += ' ';
  //       if (i == 3) str += ' ';
  //     }
  //     return str;
  //   }
  // }

  var Pathfinder = /*#__PURE__*/Object.freeze({
    __proto__: null,
    setBits: setBits,
    andBits: andBits,
    setRouteBits: setRouteBits,
    getRouteBits: getRouteBits,
    openArcRoutes: openArcRoutes,
    closeArcRoutes: closeArcRoutes,
    getPathFinder: getPathFinder,
    getRingIntersector: getRingIntersector
  });

  function roundToSignificantDigits(n, d) {
    return +n.toPrecision(d);
  }


  function roundToDigits(n, d) {
    return +n.toFixed(d); // string conversion makes this slow
  }

  // Used in mapshaper-expression-utils.js
  // TODO: choose between this and the above function
  function roundToDigits2(n, d) {
    var k = 1;
    if (!n && n !== 0) return n; // don't coerce null to 0
    d = d | 0;
    while (d-- > 0) k *= 10;
    return Math.round(n * k) / k;
  }

  function roundToTenths(n) {
    return (Math.round(n * 10)) / 10;
  }

  // inc: Rounding increment (e.g. 0.001 rounds to thousandths)
  function getRoundingFunction(inc) {
    if (!utils.isNumber(inc) || inc === 0) {
      error("Rounding increment must be a non-zero number.");
    }
    var inv = 1 / inc;
    if (inv > 1) inv = Math.round(inv);
    return function(x) {
      return Math.round(x * inv) / inv;
      // these alternatives show rounding error after JSON.stringify()
      // return Math.round(x / inc) / inv;
      // return Math.round(x / inc) * inc;
      // return Math.round(x * inv) * inc;
    };
  }

  function getBoundsPrecisionForDisplay(bbox) {
    var w = Math.abs(bbox[2] - bbox[0]),
        h = Math.abs(bbox[3] - bbox[1]),
        // switched to max bound, based on experience with shift-drag box info
        // range = Math.min(w, h) + 1e-8,
        range = Math.max(w, h) + 1e-8,
        digits = 0;
    while (range < 2000) {
      range *= 10;
      digits++;
    }
    return digits;
  }

  function getRoundedCoordString(coords, decimals) {
    return coords.map(function(n) {return n.toFixed(decimals);}).join(',');
  }

  function getRoundedCoords(coords, decimals) {
    return getRoundedCoordString(coords, decimals).split(',').map(parseFloat);
  }

  function roundPoints(lyr, round) {
    forEachPoint(lyr.shapes, function(p) {
      p[0] = round(p[0]);
      p[1] = round(p[1]);
    });
  }

  function setCoordinatePrecision(dataset, precision) {
    var round = getRoundingFunction(precision);
    // var dissolvePolygon, nodes;
    transformPoints(dataset, function(x, y) {
      return [round(x), round(y)];
    });
    // v0.4.52 removing polygon dissolve - see issue #219
    /*
    if (dataset.arcs) {
      nodes = internal.addIntersectionCuts(dataset);
      dissolvePolygon = internal.getPolygonDissolver(nodes);
    }
    dataset.layers.forEach(function(lyr) {
      if (lyr.geometry_type == 'polygon' && dissolvePolygon) {
        // clean each polygon -- use dissolve function to remove spikes
        // TODO: better handling of corrupted polygons
        lyr.shapes = lyr.shapes.map(dissolvePolygon);
      }
    });
    */
    return dataset;
  }

  var Rounding = /*#__PURE__*/Object.freeze({
    __proto__: null,
    roundToSignificantDigits: roundToSignificantDigits,
    roundToDigits: roundToDigits,
    roundToDigits2: roundToDigits2,
    roundToTenths: roundToTenths,
    getRoundingFunction: getRoundingFunction,
    getBoundsPrecisionForDisplay: getBoundsPrecisionForDisplay,
    getRoundedCoordString: getRoundedCoordString,
    getRoundedCoords: getRoundedCoords,
    roundPoints: roundPoints,
    setCoordinatePrecision: setCoordinatePrecision
  });

  var UNITS_LOOKUP = {
    m: 'meters',
    meter: 'meters',
    meters: 'meters',
    mi: 'miles',
    mile: 'miles',
    miles: 'miles',
    km: 'kilometers',
    ft: 'feet',
    feet: 'feet'
  };

  // From pj_units.js in mapshaper-proj
  var TO_METERS = {
    meters: 1,
    kilometers: 1000,
    feet: 0.3048, // International Standard Foot
    miles: 1609.344 // International Statute Mile
  };

  // Return coeff. for converting a distance measure to dataset coordinates
  // @paramUnits: units code of distance param, or null if units are not specified
  // @crs: Proj.4 CRS object, or null (unknown latlong CRS);
  //
  function getIntervalConversionFactor(paramUnits, crs) {
    var fromParam = 0,
        fromCRS = 0,
        k;

    if (crs) {
      if (crs.is_latlong) {
        // calculations on latlong coordinates typically use meters
        fromCRS = 1;
      } else if (crs.to_meter > 0) {
        fromCRS = crs.to_meter;
      } else {
        error('Invalid CRS');
      }
    }
    if (paramUnits) {
      fromParam = TO_METERS[paramUnits];
      if (!fromParam) error('Unknown units:', paramUnits);
    }

    if (fromParam && fromCRS) {
      // known param units, known CRS conversion
      k = fromParam / fromCRS;
    } else if (!fromParam && !fromCRS) {
      // unknown param units, unknown (projected) CRS -- no scaling
      k = 1;
    } else if (fromParam && !fromCRS) {
      // known param units, unknown CRS -- error condition, not convertible
      stop('Unable to convert', paramUnits, 'to unknown coordinates');
    } else if (!fromParam && fromCRS) {
      // unknown param units, known CRS -- assume param in meters (bw compatibility)
      k = 1 / fromCRS;
    }
    return k;
  }

  // throws an error if measure is non-parsable
  function parseMeasure(m) {
    var o = parseMeasure2(m);
    if (isNaN(o.value)) {
      stop('Invalid parameter:', m);
    }
    return o;
  }

  // returns NaN value if value is non-parsable
  function parseMeasure2(m) {
    var s = utils.isString(m) ? m : '';
    var match = /(sq|)([a-z]+)(2|)$/i.exec(s); // units rxp
    var o = {};
    if (utils.isNumber(m)) {
      o.value = m;
    } else if (s === '') {
      o.value = NaN;
    } else if (match) {
      o.units = UNITS_LOOKUP[match[2].toLowerCase()];
      o.areal = !!(match[1] || match[3]);
      o.value = Number(s.substring(0, s.length - match[0].length));
      if (!o.units && !isNaN(o.value)) {
        // throw error if string contains a number followed by unrecognized units string
        stop('Unknown units: ' + match[0]);
      }
    } else {
      o.value = Number(s);
    }
    return o;
  }

  function convertAreaParam(opt, crs) {
    var o = parseMeasure(opt);
    var k = getIntervalConversionFactor(o.units, crs);
    return o.value * k * k;
  }

  function convertDistanceParam(opt, crs) {
    var o = parseMeasure(opt);
    var k = getIntervalConversionFactor(o.units, crs);
    if (o.areal) {
      stop('Expected a distance, received an area:', opt);
    }
    return o.value * k;
  }

  // Same as convertDistanceParam(), except:
  //   in the case of latlong datasets, coordinates are unitless (instead of meters),
  //   and parameters with units trigger an error
  function convertIntervalParam(opt, crs) {
    var o = parseMeasure(opt);
    var k = getIntervalConversionFactor(o.units, crs);
    if (o.units && crs && crs.is_latlong) {
      stop('Parameter does not support distance units with latlong datasets');
    }
    if (o.areal) {
      stop('Expected a distance, received an area:', opt);
    }
    return o.value * k;
  }

  function convertIntervalPair(opt, crs) {
    var a, b;
    if (!Array.isArray(opt) || opt.length != 2) {
      stop('Expected two distance parameters, received', opt);
    }
    a = parseMeasure(opt[0]);
    b = parseMeasure(opt[1]);
    if (a.units && !b.units || b.units && !a.units) {
      stop('Both parameters should have units:', opt);
    }
    return [convertIntervalParam(opt[0], crs),
            convertIntervalParam(opt[1], crs)];
  }

  // Accepts a single value or a list of four values. List order is l,b,t,r
  function convertFourSides(opt, crs, bounds) {
    var arr = opt.split(',');
    if (arr.length == 1) {
      arr = [arr[0], arr[0], arr[0], arr[0]];
    } else if (arr.length != 4) {
      stop("Expected a distance parameter or a list of four params");
    }
    return arr.map(function(param, i) {
      var tmp;
      if (param.indexOf('%') > 0) {
        tmp = parseFloat(param) / 100 || 0;
        return tmp * (i == 1 || i == 3 ? bounds.height() : bounds.width());
      }
      return convertIntervalParam(opt, crs);
    });
  }

  // Convert an area measure to a label in sqkm or sqm
  function getAreaLabel(area, crs) {
    var sqm = crs && crs.to_meter ? area * crs.to_meter * crs.to_meter : area;
    var sqkm = sqm / 1e6;
    return sqkm < 0.01 ? Math.round(sqm) + ' sqm' : sqkm + ' sqkm';
  }

  var Units = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getIntervalConversionFactor: getIntervalConversionFactor,
    parseMeasure: parseMeasure,
    parseMeasure2: parseMeasure2,
    convertAreaParam: convertAreaParam,
    convertDistanceParam: convertDistanceParam,
    convertIntervalParam: convertIntervalParam,
    convertIntervalPair: convertIntervalPair,
    convertFourSides: convertFourSides,
    getAreaLabel: getAreaLabel
  });

  // Used by -clean -dissolve2 -filter-slivers -filter-islands to generate area filters
  // for removing small polygon rings.
  // Assumes lyr is a polygon layer.
  function getSliverFilter(lyr, dataset, opts) {
    var areaArg = opts.min_gap_area || opts.min_area || opts.gap_fill_area;
    if (+areaArg == 0) {
      return {
        filter: function() {return false;}, // don't fill any gaps
        threshold: 0
      };
    }
    var sliverControl = opts.sliver_control >= 0 ? opts.sliver_control : 0; // 0 is default
    var crs = getDatasetCRS(dataset);
    var threshold = areaArg ?
        convertAreaParam(areaArg, crs) :
        getDefaultSliverThreshold(lyr, dataset.arcs);
    var filter = sliverControl > 0 ?
        getSliverTest(dataset.arcs, threshold, sliverControl) :
        getMinAreaTest(threshold, dataset);
    var label = getSliverLabel(getAreaLabel(threshold, crs), sliverControl > 0);
    return {
      threshold: threshold,
      filter: filter,
      label: label
    };
  }

  function getSliverLabel(areaStr, variable) {
    if (variable) {
      areaStr = areaStr.replace(' ', '+ ') + ' variable';
    }
    return areaStr + ' threshold';
  }

  function getMinAreaTest(minArea, dataset) {
    var pathArea = dataset.arcs.isPlanar() ? geom.getPlanarPathArea : geom.getSphericalPathArea;
    return function(path) {
      var area = pathArea(path, dataset.arcs);
      return Math.abs(area) < minArea;
    };
  }

  function getSliverTest(arcs, threshold, strength) {
    if (strength >= 0 === false) {
      strength = 1; // default is 1 (full-strength)
    }
    if (strength > 1 || threshold >= 0 === false) {
      error('Invalid parameter');
    }
    var calcEffectiveArea = getSliverAreaFunction(arcs, strength);
    return function(ring) {
      return Math.abs(calcEffectiveArea(ring)) < threshold;
    };
  }

  // Strength: 0-1
  function getSliverAreaFunction(arcs, strength) {
    var k = Math.sqrt(strength); // more sensible than linear weighted avg.
    return function(ring) {
      var area = geom.getPathArea(ring, arcs);
      var perim = geom.getPathPerimeter(ring, arcs);
      var compactness = geom.calcPolsbyPopperCompactness(area, perim);
      var effectiveArea = area * (k * compactness + 1 - k);
      return effectiveArea;
    };
  }

  // Calculate a default area threshold using average segment length,
  // but increase the threshold for high-detail datasets and decrease it for
  // low-detail datasets (using segments per ring as a measure of detail).
  //
  function getDefaultSliverThreshold(lyr, arcs) {
    var ringCount = 0;
    var calcLen = arcs.isPlanar() ? geom.distance2D : geom.greatCircleDistance;
    var avgSegLen = 0;
    var segCount = 0;
    var onSeg = function(i, j, xx, yy) {
      var len = calcLen(xx[i], yy[i], xx[j], yy[j]);
      segCount++;
      avgSegLen += (len - avgSegLen) / segCount;
    };
    editShapes(lyr.shapes, function(path) {
      ringCount++;
      forEachSegmentInPath(path, arcs, onSeg);
    });
    var segPerRing = segCount / ringCount || 0;
    var complexityFactor = Math.pow(segPerRing, 0.75); // use seg/ring as a proxy for complexity
    var threshold = avgSegLen * avgSegLen / 50 * complexityFactor;
    threshold = roundToSignificantDigits(threshold, 2); // round for display
    return threshold;
  }


  // Original function for calculating default area threshold
  function calcMaxSliverArea(arcs) {
    var k = 2,
        dxMax = arcs.getBounds().width() / k,
        dyMax = arcs.getBounds().height() / k,
        count = 0,
        mean = 0;
    arcs.forEachSegment(function(i, j, xx, yy) {
      var dx = Math.abs(xx[i] - xx[j]),
          dy = Math.abs(yy[i] - yy[j]);
      if (dx < dxMax && dy < dyMax) {
        // TODO: write utility function for calculating mean this way
        mean += (Math.sqrt(dx * dx + dy * dy) - mean) / ++count;
      }
    });
    return mean * mean;
  }

  var Slivers = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getSliverFilter: getSliverFilter,
    getSliverTest: getSliverTest,
    getSliverAreaFunction: getSliverAreaFunction,
    getDefaultSliverThreshold: getDefaultSliverThreshold,
    calcMaxSliverArea: calcMaxSliverArea
  });

  // Returns undefined if not found
  function lookupColorName(str) {
    return colors$1[str.toLowerCase().replace(/[ -]+/g, '')];
  }

  var colors$1 = {
    aliceblue: '#f0f8ff',
    antiquewhite: '#faebd7',
    aqua: '#00ffff',
    aquamarine: '#7fffd4',
    azure: '#f0ffff',
    beige: '#f5f5dc',
    bisque: '#ffe4c4',
    black: '#000000',
    blanchedalmond: '#ffebcd',
    blue: '#0000ff',
    blueviolet: '#8a2be2',
    brown: '#a52a2a',
    burlywood: '#deb887',
    cadetblue: '#5f9ea0',
    chartreuse: '#7fff00',
    chocolate: '#d2691e',
    coral: '#ff7f50',
    cornflowerblue: '#6495ed',
    cornsilk: '#fff8dc',
    crimson: '#dc143c',
    cyan: '#00ffff',
    darkblue: '#00008b',
    darkcyan: '#008b8b',
    darkgoldenrod: '#b8860b',
    darkgray: '#a9a9a9',
    darkgreen: '#006400',
    darkgrey: '#a9a9a9',
    darkkhaki: '#bdb76b',
    darkmagenta: '#8b008b',
    darkolivegreen: '#556b2f',
    darkorange: '#ff8c00',
    darkorchid: '#9932cc',
    darkred: '#8b0000',
    darksalmon: '#e9967a',
    darkseagreen: '#8fbc8f',
    darkslateblue: '#483d8b',
    darkslategray: '#2f4f4f',
    darkslategrey: '#2f4f4f',
    darkturquoise: '#00ced1',
    darkviolet: '#9400d3',
    deeppink: '#ff1493',
    deepskyblue: '#00bfff',
    dimgray: '#696969',
    dimgrey: '#696969',
    dodgerblue: '#1e90ff',
    firebrick: '#b22222',
    floralwhite: '#fffaf0',
    forestgreen: '#228b22',
    fuchsia: '#ff00ff',
    gainsboro: '#dcdcdc',
    ghostwhite: '#f8f8ff',
    gold: '#ffd700',
    goldenrod: '#daa520',
    gray: '#808080',
    green: '#008000',
    greenyellow: '#adff2f',
    grey: '#808080',
    honeydew: '#f0fff0',
    hotpink: '#ff69b4',
    indianred: '#cd5c5c',
    indigo: '#4b0082',
    ivory: '#fffff0',
    khaki: '#f0e68c',
    lavender: '#e6e6fa',
    lavenderblush: '#fff0f5',
    lawngreen: '#7cfc00',
    lemonchiffon: '#fffacd',
    lightblue: '#add8e6',
    lightcoral: '#f08080',
    lightcyan: '#e0ffff',
    lightgoldenrodyellow: '#fafad2',
    lightgray: '#d3d3d3',
    lightgreen: '#90ee90',
    lightgrey: '#d3d3d3',
    lightpink: '#ffb6c1',
    lightsalmon: '#ffa07a',
    lightseagreen: '#20b2aa',
    lightskyblue: '#87cefa',
    lightslategray: '#778899',
    lightslategrey: '#778899',
    lightsteelblue: '#b0c4de',
    lightyellow: '#ffffe0',
    lime: '#00ff00',
    limegreen: '#32cd32',
    linen: '#faf0e6',
    magenta: '#ff00ff',
    maroon: '#800000',
    mediumaquamarine: '#66cdaa',
    mediumblue: '#0000cd',
    mediumorchid: '#ba55d3',
    mediumpurple: '#9370db',
    mediumseagreen: '#3cb371',
    mediumslateblue: '#7b68ee',
    mediumspringgreen: '#00fa9a',
    mediumturquoise: '#48d1cc',
    mediumvioletred: '#c71585',
    midnightblue: '#191970',
    mintcream: '#f5fffa',
    mistyrose: '#ffe4e1',
    moccasin: '#ffe4b5',
    navajowhite: '#ffdead',
    navy: '#000080',
    oldlace: '#fdf5e6',
    olive: '#808000',
    olivedrab: '#6b8e23',
    orange: '#ffa500',
    orangered: '#ff4500',
    orchid: '#da70d6',
    palegoldenrod: '#eee8aa',
    palegreen: '#98fb98',
    paleturquoise: '#afeeee',
    palevioletred: '#db7093',
    papayawhip: '#ffefd5',
    peachpuff: '#ffdab9',
    peru: '#cd853f',
    pink: '#ffc0cb',
    plum: '#dda0dd',
    powderblue: '#b0e0e6',
    purple: '#800080',
    rebeccapurple: '#663399',
    red: '#ff0000',
    rosybrown: '#bc8f8f',
    royalblue: '#4169e1',
    saddlebrown: '#8b4513',
    salmon: '#fa8072',
    sandybrown: '#f4a460',
    seagreen: '#2e8b57',
    seashell: '#fff5ee',
    sienna: '#a0522d',
    silver: '#c0c0c0',
    skyblue: '#87ceeb',
    slateblue: '#6a5acd',
    slategray: '#708090',
    slategrey: '#708090',
    snow: '#fffafa',
    springgreen: '#00ff7f',
    steelblue: '#4682b4',
    tan: '#d2b48c',
    teal: '#008080',
    thistle: '#d8bfd8',
    tomato: '#ff6347',
    turquoise: '#40e0d0',
    violet: '#ee82ee',
    wheat: '#f5deb3',
    white: '#ffffff',
    whitesmoke: '#f5f5f5',
    yellow: '#ffff00',
    yellowgreen: '#9acd32'
  };

  var rgbaRxp = /^rgba?\(([^)]+)\)/;
  var hexRxp = /^#([a-f0-9]{3,8})/i;

  function parseColor(arg) {
    arg = arg ? String(arg) : '';
    var hexStr = hexRxp.test(arg) ? arg : lookupColorName(arg);
    var rgb = null;
    if (hexStr) {
      rgb = parseHexColor(hexStr);
    } else if (rgbaRxp.test(arg)) {
      rgb = parseRGBA(arg);
    }
    if (rgb && !testRGB(rgb)) {
      rgb = null;
    }
    return rgb;
  }

  function validateColor(arg) {
    if (!parseColor(arg)) {
      stop("Unsupported color:", arg);
    }
    return true;
  }

  function testRGB(o) {
    return !!o && testChannel(o.r) && testChannel(o.g) && testChannel(o.b) &&
      testAlpha(o.a);
  }

  function testAlpha(a) {
    return a >= 0 && a <= 1;
  }

  function testChannel(c) {
    return c >= 0 && c < 256; // allow fractional values
  }

  function parseRGBA(arg) {
    var str = rgbaRxp.exec(arg)[1];
    var parts = str.split(',').map(function(part) { return parseFloat(part); });
    return {
      r: parts[0],
      g: parts[1],
      b: parts[2],
      a: parts[3] >= 0 ? parts[3] : 1
    };
  }

  function formatColor(o) {
    return o.a < 1 ? formatRGBA(o) : formatHexColor(o);
  }

  function formatHexColor(o) {
    return "#" + formatHexChannel(o.r) + formatHexChannel(o.g) + formatHexChannel(o.b);

  }

  function formatRGBA(o) {
    var rgb = snapHexChannel(o.r) + ',' + snapHexChannel(o.g) + ',' + snapHexChannel(o.b);
    return o.a < 1 ?
      'rgba(' + rgb + ',' + snapAlpha(o.a) + ')' :
      'rgb(' + rgb + ')';
  }

  function snapAlpha(a) {
    a = +a || 0;
    a = Math.round(a * 1000) / 1000; // round to thousandths
    return utils.clamp(a, 0, 1);
  }

  function snapHexChannel(arg) {
    return Math.round(utils.clamp(+arg || 0, 0, 255));
  }

  // arg: should be number in 0-255 range
  function formatHexChannel(arg) {
    return snapHexChannel(arg).toString(16).padStart(2, '0');
  }

  // returns {r, g, b} object
  function parseHexColor(str) {
    var hex = hexRxp.exec(str)[1];
    if (hex.length == 3 || hex.length == 4) {
      hex = hex.split('').map(function(c) { return c + c; });
    }
    if (hex.length != 6 && hex.length != 8) return null;
    return {
      r: parseInt(hex.substr(0, 2), 16),
      g: parseInt(hex.substr(2, 2), 16),
      b: parseInt(hex.substr(4, 2), 16),
      a: hex.length == 8 ? parseInt(hex.substr(7, 2), 16) / 255 : 1
    };
  }

  function blend(a, b) {
    var colors, weights, args;
    if (Array.isArray(a)) {
      colors = a;
      weights = b;
    } else {
      colors = [];
      weights = [];
      args = Array.from(arguments);
      for (var i=0; i<args.length; i+= 2) {
        colors.push(args[i]);
        weights.push(args[i + 1]);
      }
    }
    weights = normalizeWeights(weights);
    if (!weights) return '#eee';
    var blended = colors.reduce(function(memo, col, i) {
      var rgb = validateColor(col) && parseColor(col);
      var w = +weights[i] || 0;
      memo.r += rgb.r * w;
      memo.g += rgb.g * w;
      memo.b += rgb.b * w;
      return memo;
    }, {r: 0, g: 0, b: 0});
    return formatColor(blended);
  }


  function normalizeWeights(weights) {
    var sum = utils.sum(weights);
    if (sum > 0 === false) {
      return null;
    }
    return weights.map(function(w) {
      return w / sum;
    });
  }

  function cleanExpression(exp) {
    // workaround for problem in GNU Make v4: end-of-line backslashes inside
    // quoted strings are left in the string (other shell environments remove them)
    return exp.replace(/\\\n/g, ' ');
  }

  function addFeatureExpressionUtils(env) {
    Object.assign(env, {
      round: roundToDigits2,
      int_median: interpolated_median,
      sprintf: utils.format,
      blend: blend
    });
  }

  // piecewise linear interpolation (for a special project)
  function interpolated_median(counts, breaks) {
    if (!counts || !breaks || counts.length != breaks.length - 1) return null;
    var total = utils.sum(counts);
    var medianIdx = Math.floor(total / 2);
    var lowerCount = 0, upperCount, lowerValue, upperValue, t;
    for (var i=1; i<breaks.length; i++) {
      lowerValue = breaks[i-1];
      upperValue = breaks[i];
      upperCount = lowerCount + counts[i-1];
      if (medianIdx <= upperCount) {
        t = (medianIdx - lowerCount) / (upperCount - lowerCount);
        return lowerValue + t * (upperValue - lowerValue);
      }
      lowerCount = upperCount;
    }
    return null;
  }

  function addGetters(obj, getters) {
    Object.keys(getters).forEach(function(name) {
      var val = getters[name];
      var o = typeof val == 'function' ?
        {get: val} :
        {value: val, writable: false};
      Object.defineProperty(obj, name, o);
    });
  }

  function simplifyArcsFast(arcs, dist) {
    var xx = [],
        yy = [],
        nn = [],
        count;
    for (var i=0, n=arcs.size(); i<n; i++) {
      count = simplifyPathFast([i], arcs, dist, xx, yy);
      if (count == 1) {
        count = 0;
        xx.pop();
        yy.pop();
      }
      nn.push(count);
    }
    return new ArcCollection(nn, xx, yy);
  }

  function simplifyPolygonFast(shp, arcs, dist) {
    if (!shp || !dist) return null;
    var xx = [],
        yy = [],
        nn = [],
        shp2 = [];

    shp.forEach(function(path) {
      var count = simplifyPathFast(path, arcs, dist, xx, yy);
      while (count < 4 && count > 0) {
        xx.pop();
        yy.pop();
        count--;
      }
      if (count > 0) {
        shp2.push([nn.length]);
        nn.push(count);
      }
    });
    return {
      shape: shp2.length > 0 ? shp2 : null,
      arcs: new ArcCollection(nn, xx, yy)
    };
  }

  function simplifyPathFast(path, arcs, dist, xx, yy) {
    var iter = arcs.getShapeIter(path),
        count = 0,
        prevX, prevY, x, y;
    while (iter.hasNext()) {
      x = iter.x;
      y = iter.y;
      if (count === 0 || geom.distance2D(x, y, prevX, prevY) > dist) {
        xx.push(x);
        yy.push(y);
        prevX = x;
        prevY = y;
        count++;
      }
    }
    if (x != prevX || y != prevY) {
      xx.push(x);
      yy.push(y);
      count++;
    }
    return count;
  }

  var SimplifyFast = /*#__PURE__*/Object.freeze({
    __proto__: null,
    simplifyArcsFast: simplifyArcsFast,
    simplifyPolygonFast: simplifyPolygonFast
  });

  // Find a point inside a polygon and located away from the polygon edge
  // Method:
  // - get the largest ring of the polygon
  // - get an array of x-values distributed along the horizontal extent of the ring
  // - for each x:
  //     intersect a vertical line with the polygon at x
  //     find midpoints of each intersecting segment
  // - for each midpoint:
  //     adjust point vertically to maximize weighted distance from polygon edge
  // - return the adjusted point having the maximum weighted distance from the edge
  //
  // (distance is weighted to slightly favor points near centroid)
  //
  function findAnchorPoint(shp, arcs) {
    var maxPath = shp && geom.getMaxPath(shp, arcs),
        pathBounds = maxPath && arcs.getSimpleShapeBounds(maxPath),
        thresh, simple;
    if (!pathBounds || !pathBounds.hasBounds() || pathBounds.area() === 0) {
      return null;
    }
    // Optimization: quickly simplify using a relatively small distance threshold.
    // (testing multiple candidate points can be very slow for large and detailed
    //   polgons; simplification alleviates this)
    // Caveat: In rare cases this could cause poor point placement, e.g. if
    //   simplification causes small holes to be removed.
    thresh = Math.sqrt(pathBounds.area()) * 0.01;
    simple = simplifyPolygonFast(shp, arcs, thresh);
    if (!simple.shape) {
      return null; // collapsed shape
    }
    return findAnchorPoint2(simple.shape, simple.arcs);
  }

  // Assumes: shp is a polygon with at least one space-enclosing ring
  function findAnchorPoint2(shp, arcs) {
    var maxPath = geom.getMaxPath(shp, arcs);
    var pathBounds = arcs.getSimpleShapeBounds(maxPath);
    var centroid = geom.getPathCentroid(maxPath, arcs);
    var weight = getPointWeightingFunction(centroid, pathBounds);
    var area = geom.getPlanarPathArea(maxPath, arcs);
    var hrange, lbound, rbound, focus, htics, hstep, p, p2;

    // Limit test area if shape is simple and squarish
    if (shp.length == 1 && area * 1.2 > pathBounds.area()) {
      htics = 5;
      focus = 0.2;
    } else if (shp.length == 1 && area * 1.7 > pathBounds.area()) {
      htics = 7;
      focus = 0.4;
    } else {
      htics = 11;
      focus = 0.5;
    }
    hrange = pathBounds.width() * focus;
    lbound = centroid.x - hrange / 2;
    rbound = lbound + hrange;
    hstep = hrange / htics;

    // Find a best-fit point
    p = probeForBestAnchorPoint(shp, arcs, lbound, rbound, htics, weight);
    if (!p) {
      verbose("[points inner] failed, falling back to centroid");
     p = centroid;
    } else {
      // Look for even better fit close to best-fit point
      p2 = probeForBestAnchorPoint(shp, arcs, p.x - hstep / 2,
          p.x + hstep / 2, 2, weight);
      if (p2.distance > p.distance) {
        p = p2;
      }
    }
    return p;
  }

  function getPointWeightingFunction(centroid, pathBounds) {
    // Get a factor for weighting a candidate point
    // Points closer to the centroid are slightly preferred
    var referenceDist = Math.max(pathBounds.width(), pathBounds.height()) / 2;
    return function(x, y) {
      var offset = geom.distance2D(centroid.x, centroid.y, x, y);
      return 1 - Math.min(0.6 * offset / referenceDist, 0.25);
    };
  }

  function findAnchorPointCandidates(shp, arcs, xx) {
    var ymin = arcs.getBounds().ymin - 1;
    return xx.reduce(function(memo, x) {
      var cands = findHitCandidates(x, ymin, shp, arcs);
      return memo.concat(cands);
    }, []);
  }

  function probeForBestAnchorPoint(shp, arcs, lbound, rbound, htics, weight) {
    var tics = getInnerTics(lbound, rbound, htics);
    var interval = (rbound - lbound) / htics;
    // Get candidate points, distributed along x-axis
    var candidates = findAnchorPointCandidates(shp, arcs, tics);
    var bestP, adjustedP, candP;

    // Sort candidates so points at the center of longer segments are tried first
    candidates.forEach(function(p) {
      p.interval *= weight(p.x, p.y);
    });
    candidates.sort(function(a, b) {
      return b.interval - a.interval;
    });

    for (var i=0; i<candidates.length; i++) {
      candP = candidates[i];
      // Optimization: Stop searching if weighted half-segment length of remaining
      //   points is less than the weighted edge distance of the best candidate
      if (bestP && bestP.distance > candP.interval) {
        break;
      }
      adjustedP = getAdjustedPoint(candP.x, candP.y, shp, arcs, interval, weight);

      if (!bestP || adjustedP.distance > bestP.distance) {
        bestP = adjustedP;
      }
    }
    return bestP;
  }

  // [x, y] is a point assumed to be inside a polygon @shp
  // Try to move the point farther from the polygon edge
  function getAdjustedPoint(x, y, shp, arcs, vstep, weight) {
    var p = {
      x: x,
      y: y,
      distance: geom.getPointToShapeDistance(x, y, shp, arcs) * weight(x, y)
    };
    scanForBetterPoint(p, shp, arcs, vstep, weight); // scan up
    scanForBetterPoint(p, shp, arcs, -vstep, weight); // scan down
    return p;
  }

  // Try to find a better-fit point than @p by scanning vertically
  // Modify p in-place
  function scanForBetterPoint(p, shp, arcs, vstep, weight) {
    var x = p.x,
        y = p.y,
        dmax = p.distance,
        d;

    while (true) {
      y += vstep;
      d = geom.getPointToShapeDistance(x, y, shp, arcs) * weight(x, y);
      // overcome vary small local minima
      if (d > dmax * 0.90 && geom.testPointInPolygon(x, y, shp, arcs)) {
        if (d > dmax) {
          p.distance = dmax = d;
          p.y = y;
        }
      } else {
        break;
      }
    }
  }

  // Return array of points at the midpoint of each line segment formed by the
  //   intersection of a vertical ray at [x, y] and a polygon shape
  function findHitCandidates(x, y, shp, arcs) {
    var yy = findRayShapeIntersections(x, y, shp, arcs);
    var cands = [], y1, y2, interval;

    // sorting by y-coord organizes y-intercepts into interior segments
    utils.genericSort(yy);
    for (var i=0; i<yy.length; i+=2) {
      y1 = yy[i];
      y2 = yy[i+1];
      interval = (y2 - y1) / 2;
      if (interval > 0) {
        cands.push({
          y: (y1 + y2) / 2,
          x: x,
          interval: interval
        });
      }
    }
    return cands;
  }

  // Return array of y-intersections between vertical ray with origin at [x, y]
  //   and a polygon
  function findRayShapeIntersections(x, y, shp, arcs) {
    if (!shp) return [];
    return shp.reduce(function(memo, path) {
      var yy = findRayRingIntersections(x, y, path, arcs);
      return memo.concat(yy);
    }, []);
  }

  // Return array of y-intersections between vertical ray and a polygon ring
  function findRayRingIntersections(x, y, path, arcs) {
    var yints = [];
    forEachSegmentInPath(path, arcs, function(a, b, xx, yy) {
      var result = geom.getRayIntersection(x, y, xx[a], yy[a], xx[b], yy[b]);
      if (result > -Infinity) {
        yints.push(result);
      }
    });
    // Ignore odd number of intersections -- probably caused by a ray that touches
    //   but doesn't cross the ring
    // TODO: improve method to handle edge case with two touches and no crosses.
    if (yints.length % 2 === 1) {
      yints = [];
    }
    return yints;
  }

  // TODO: find better home + name for this
  function getInnerTics(min, max, steps) {
    var range = max - min,
        step = range / (steps + 1),
        arr = [];
    for (var i = 1; i<=steps; i++) {
      arr.push(min + step * i);
    }
    return arr;
  }

  var AnchorPoints = /*#__PURE__*/Object.freeze({
    __proto__: null,
    findAnchorPoint: findAnchorPoint
  });

  // Returns a function for calculating the percentage of a shape's perimeter by length that
  // is composed of inner (shared) boundaries
  function getInnerPctCalcFunction(arcs, shapes) {
    var calcSegLen = arcs.isPlanar() ? geom.distance2D : geom.greatCircleDistance;
    var arcIndex = new ArcTopologyIndex(arcs, shapes);
    var outerLen, innerLen, arcLen; // temp variables

    return function(shp) {
      outerLen = 0;
      innerLen = 0;
      if (shp) shp.forEach(procRing);
      return innerLen > 0 ? innerLen / (innerLen + outerLen) : 0;
    };

    function procRing(ids) {
      ids.forEach(procArc);
    }

    function procArc(id) {
      arcLen = 0;
      arcs.forEachArcSegment(id, addSegLen);
      if (arcIndex.isInnerArc(id)) {
        innerLen += arcLen;
      } else {
        outerLen += arcLen;
      }
    }

    function addSegLen(i, j, xx, yy) {
      arcLen += calcSegLen(xx[i], yy[i], xx[j], yy[j]);
    }
  }

  function ArcTopologyIndex(arcs, shapes) {
    var index = new Uint8Array(arcs.size());
    forEachArcId(shapes, function(arcId) {
      if (arcId < 0) index[~arcId] |= 2;
      else (index[arcId] |= 1);
    });

    this.isInnerArc = function(arcId) {
      var i = absArcId(arcId);
      return index[i] == 3;
    };
  }

  // convert targets from [{layers: [...], dataset: <>}, ...] format to
  // [{layer: <>, dataset: <>}, ...] format
  function expandCommandTargets(targets) {
    return targets.reduce(function(memo, target) {
      target.layers.forEach(function(lyr) {
        memo.push({layer: lyr, dataset: target.dataset});
      });
      return memo;
    }, []);
  }


  function findCommandTargets(layers, pattern, type) {
    var matches = findMatchingLayers(layers, pattern, true);
    if (type) {
      matches = matches.filter(function(o) {return o.layer.geometry_type == type;});
    }
    // assign target_id to matched layers
    // (kludge so layers can be sorted in the order that they match; used by -o command)
    layers.forEach(function(o) {o.layer.target_id = -1;});
    matches.forEach(function(o, i) {o.layer.target_id = i;});
    return groupLayersByDataset(matches);
  }

  // arr: array of {layer: <>, dataset: <>} objects
  function groupLayersByDataset(arr) {
    var datasets = [];
    var targets = [];
    arr.forEach(function(o) {
      var i = datasets.indexOf(o.dataset);
      if (i == -1) {
        datasets.push(o.dataset);
        targets.push({layers: [o.layer], dataset: o.dataset});
      } else {
        targets[i].layers.push(o.layer);
      }
    });
    return targets;
  }

  // layers: array of {layer: <>, dataset: <>} objects
  // pattern: is a layer identifier or a comma-sep. list of identifiers.
  // An identifier is a literal name, a pattern containing "*" wildcard or
  // a 1-based index (1..n)
  function findMatchingLayers(layers, pattern, throws) {
    var matchedLayers = [];
    var unmatchedIds = [];
    var index = {};
    pattern.split(',').forEach(function(subpattern, i) {
      var test = getLayerMatch(subpattern);
      var matched = false;
      layers.forEach(function(o, layerId) {
        // if (matchedLayers.indexOf(lyr) > -1) return; // performance bottleneck with 1000s of layers
        if (layerId in index) {
          matched = true;
        } else if (test(o.layer, layerId + 1)) {  // layers are 1-indexed
          matchedLayers.push(o);
          index[layerId] = true;
          matched = true;
        }
      });
      if (matched == false) {
        unmatchedIds.push(subpattern);
      }
    });
    if (throws && unmatchedIds.length) {
      stop(utils.format('Missing layer%s: %s', unmatchedIds.length == 1 ? '' : 's', unmatchedIds.join(',')));
    }
    return matchedLayers;
  }

  function getLayerMatch(pattern) {
    var isIndex = utils.isInteger(Number(pattern));
    var nameRxp = isIndex ? null : utils.wildcardToRegExp(pattern);
    return function(lyr, i) {
      return isIndex ? String(i) == pattern : nameRxp.test(lyr.name || '');
    };
  }

  function countTargetLayers(targets) {
    return targets.reduce(function(memo, target) {
      return memo + target.layers.length;
    }, 0);
  }

  // get an identifier for a layer that can be used in a target= option
  // (returns name if layer has a unique name, or a numerical id)
  function getLayerTargetId(catalog, lyr) {
    var nameCount = 0;
        lyr.name;
        var id;
    catalog.getLayers().forEach(function(o, i) {
      if (lyr.name && o.layer.name == lyr.name) nameCount++;
      if (lyr == o.layer) id = String(i + 1);
    });
    if (!id) error('Layer not found');
    return nameCount == 1 ? lyr.name : id;
  }

  var TargetUtils = /*#__PURE__*/Object.freeze({
    __proto__: null,
    expandCommandTargets: expandCommandTargets,
    findCommandTargets: findCommandTargets,
    groupLayersByDataset: groupLayersByDataset,
    findMatchingLayers: findMatchingLayers,
    getLayerMatch: getLayerMatch,
    countTargetLayers: countTargetLayers,
    getLayerTargetId: getLayerTargetId
  });

  function getNullLayerProxy(targets) {
    var obj = {};
    var n = countTargetLayers(targets);
    var getters = {
      name: error,
      data: error,
      type: error,
      size: error,
      empty: error,
      bbox: error
    };
    addGetters(obj, getters);
    obj.field_exists = error;
    obj.field_type = error;
    obj.field_includes = error;
    return obj;
    function error() {
      throw Error(`This expression requires a single target layer; Received ${n} layers.`);
    }
  }



  // Returns an object representing a layer in a JS expression
  function getLayerProxy(lyr, arcs) {
    var obj = {};
    var records = lyr.data ? lyr.data.getRecords() : null;
    var getters = {
      name: lyr.name,
      data: records,
      type: lyr.geometry_type,
      size: getFeatureCount(lyr),
      empty: getFeatureCount(lyr) === 0,
      bbox: getBBoxGetter(obj, lyr, arcs)
    };
    addGetters(obj, getters);
    obj.field_exists = function(name) {
      return lyr.data && lyr.data.fieldExists(name) ? true : false;
    };
    obj.field_type = function(name) {
      return lyr.data && getColumnType(name, lyr.data.getRecords()) || null;
    };
    obj.field_includes = function(name, val) {
      if (!lyr.data) return false;
      return lyr.data.getRecords().some(function(rec) {
        return rec && (rec[name] === val);
      });
    };
    return obj;
  }

  function addLayerGetters(ctx, lyr, arcs) {
    var layerProxy;
    addGetters(ctx, {
      layer_name: lyr.name || '', // consider removing this
      layer: function() {
        // init on first access (to avoid overhead if not used)
        if (!layerProxy) layerProxy = getLayerProxy(lyr, arcs);
        return layerProxy;
      }
    });
    return ctx;
  }

  function getBBoxGetter(obj, lyr, arcs) {
    var bbox;
    return function() {
      if (!bbox) {
        bbox = getBBox$1(lyr, arcs);
      }
      return bbox;
    };
  }

  function getBBox$1(lyr, arcs) {
    var bounds = getLayerBounds(lyr, arcs); // TODO: avoid this overhead if bounds is not used
    if (!bounds) return null;
    var bbox = bounds.toArray();
    Object.assign(bbox, {
      cx: bounds.centerX(),
      cy: bounds.centerY(),
      height: bounds.height(),
      width: bounds.width(),
      left: bounds.xmin,
      bottom: bounds.ymin,
      top: bounds.ymax,
      right: bounds.xmax
    });
    return bbox;
  }

  // Returns a function to return a feature proxy by id
  // (the proxy appears as "this" or "$" in a feature expression)
  function initFeatureProxy(lyr, arcs, optsArg) {
    var opts = optsArg || {},
        hasPoints = layerHasPoints(lyr),
        hasPaths = arcs && layerHasPaths(lyr),
        _records = lyr.data ? lyr.data.getRecords() : null,
        _isPlanar = hasPaths && arcs.isPlanar(),
        ctx = {},
        calcInnerPct,
        _bounds, _centroid, _innerXY, _xy, _ids, _id;

    // all contexts have this.id and this.layer
    addGetters(ctx, {
      id: function() { return _id; }
    });
    addLayerGetters(ctx, lyr, arcs);

    if (opts.geojson_editor) {
      Object.defineProperty(ctx, 'geojson', {
        set: function(o) {
          opts.geojson_editor.set(o, _id);
        },
        get: function() {
          return opts.geojson_editor.get(_id);
        }
      });
    }

    if (_records) {
      // add r/w member "properties"
      Object.defineProperty(ctx, 'properties',
        {set: function(obj) {
          if (utils.isObject(obj)) {
            _records[_id] = obj;
          } else {
            stop("Can't assign non-object to $.properties");
          }
        }, get: function() {
          var rec = _records[_id];
          if (!rec) {
            rec = _records[_id] = {};
          }
          return rec;
        }});
    }

    if (hasPaths) {

      ctx.bboxContainsPoint = function(x, y) {
        var bounds = arcs.getMultiShapeBounds(_ids);
        return bounds.containsPoint(x, y);
      };

      ctx.bboxIntersectsRectangle = function(a, b, c, d) {
        var bbox = arcs.getMultiShapeBounds(_ids);
        var rect = Bounds.from(a, b, c, d);
        return rect.intersects(bbox);
      };

      ctx.bboxContainsRectangle = function(a, b, c, d) {
        var bbox = arcs.getMultiShapeBounds(_ids);
        var rect = Bounds.from(a, b, c, d);
        return bbox.contains(rect);
      };

      ctx.bboxContainedByRectangle = function(a, b, c, d) {
        var bbox = arcs.getMultiShapeBounds(_ids);
        var rect = Bounds.from(a, b, c, d);
        return rect.contains(bbox);
      };

      // TODO
      // ctx.intersectsRectangle = function(a, b, c, d) {}; // paths... points too?
      // ctx.containsPoint = function(x, y) {}; // polygon only
      // ctx.containedByRectangle(a, b, c, d); // paths and points... how do multipart points work?

      addGetters(ctx, {
        // TODO: count hole/s + containing ring as one part
        partCount: function() {
          return _ids ? _ids.length : 0;
        },
        isNull: function() {
          return ctx.partCount === 0;
        },
        bounds: function() {
          return shapeBounds().toArray();
        },
        height: function() {
          return shapeBounds().height();
        },
        width: function() {
          return shapeBounds().width();
        }
      });

      if (lyr.geometry_type == 'polyline') {
        addGetters(ctx, {
          'length': function() {
            return geom.getShapePerimeter(_ids, arcs);
          }
        });
      }

      if (lyr.geometry_type == 'polygon') {
        addGetters(ctx, {
          area: function() {
            return _isPlanar ? ctx.planarArea : geom.getSphericalShapeArea(_ids, arcs);
          },
          // area2: function() {
          //   return _isPlanar ? ctx.planarArea : geom.getSphericalShapeArea(_ids, arcs, WGS84.SEMIMINOR_RADIUS);
          // },
          // area3: function() {
          //   return _isPlanar ? ctx.planarArea : geom.getSphericalShapeArea(_ids, arcs, WGS84.AUTHALIC_RADIUS);
          // },
          perimeter: function() {
            return geom.getShapePerimeter(_ids, arcs);
          },
          compactness: function() {
            return geom.calcPolsbyPopperCompactness(ctx.area, ctx.perimeter);
          },
          planarArea: function() {
            return geom.getPlanarShapeArea(_ids, arcs);
          },
          innerPct: function() {
            if (!calcInnerPct) calcInnerPct = getInnerPctCalcFunction(arcs, lyr.shapes);
            return calcInnerPct(_ids);
          },
          originalArea: function() {
            // Get area
            var i = arcs.getRetainedInterval(),
                area;
            arcs.setRetainedInterval(0);
            area = ctx.area;
            arcs.setRetainedInterval(i);
            return area;
          },
          centroidX: function() {
            var p = centroid();
            return p ? p.x : null;
          },
          centroidY: function() {
            var p = centroid();
            return p ? p.y : null;
          },
          innerX: function() {
            var p = innerXY();
            return p ? p.x : null;
          },
          innerY: function() {
            var p = innerXY();
            return p ? p.y : null;
          }
        });
      }

    } else if (hasPoints) {
      // TODO: add functions like bounds, isNull, pointCount
      Object.defineProperty(ctx, 'coordinates',
        {set: function(obj) {
          if (!obj || utils.isArray(obj)) {
            lyr.shapes[_id] = obj || null;
          } else {
            stop("Can't assign non-array to $.coordinates");
          }
        }, get: function() {
          return lyr.shapes[_id] || null;
        }});
      Object.defineProperty(ctx, 'x', {
        get: function() { xy(); return _xy ? _xy[0] : null;},
        set: function(val) { xy(); if (_xy) _xy[0] = Number(val);}
      });
      Object.defineProperty(ctx, 'y', {
        get: function() { xy(); return _xy ? _xy[1] : null;},
        set: function(val) { xy(); if (_xy) _xy[1] = Number(val);}
      });
    }

    function xy() {
      var shape = lyr.shapes[_id];
      if (!_xy) {
        _xy = shape && shape[0] || null;
      }
    }

    function centroid() {
      _centroid = _centroid || geom.getShapeCentroid(_ids, arcs);
      return _centroid;
    }

    function innerXY() {
      _innerXY = _innerXY || findAnchorPoint(_ids, arcs);
      return _innerXY;
    }

    function shapeBounds() {
      if (!_bounds) {
        _bounds = arcs.getMultiShapeBounds(_ids);
      }
      return _bounds;
    }

    return function(id) {
      _id = id;
      // reset stored values
      if (hasPaths) {
        _bounds = null;
        _centroid = null;
        _innerXY = null;
        _ids = lyr.shapes[id];
      }
      if (hasPoints) {
        _xy = null;
      }
      return ctx;
    };
  }

  // Compiled expression returns a value
  function compileValueExpression(exp, lyr, arcs, opts) {
    opts = opts || {};
    opts.returns = true;
    return compileFeatureExpression(exp, lyr, arcs, opts);
  }


  function compileFeaturePairFilterExpression(exp, lyr, arcs) {
    var func = compileFeaturePairExpression(exp, lyr, arcs);
    return function(idA, idB) {
      var val = func(idA, idB);
      if (val !== true && val !== false) {
        stop("where expression must return true or false");
      }
      return val;
    };
  }

  function compileFeaturePairExpression(rawExp, lyr, arcs) {
    var exp = cleanExpression(rawExp);
    // don't add layer data to the context
    // (fields are not added to the pair expression context)
    var ctx = getExpressionContext({});
    var getA = getProxyFactory(lyr, arcs);
    var getB = getProxyFactory(lyr, arcs);
    var vars = getAssignedVars(exp);
    var functionBody = "with($$env){with($$record){return " + exp + "}}";
    var func;

    try {
      func = new Function("$$record,$$env", functionBody);
    } catch(e) {
      console.error(e);
      stop(e.name, "in expression [" + exp + "]");
    }

    // protect global object from assigned values
    nullifyUnsetProperties(vars, ctx);

    function getProxyFactory(lyr, arcs) {
      var records = lyr.data ? lyr.data.getRecords() : [];
      var getFeatureById = initFeatureProxy(lyr, arcs);
      function Proxy() {}

      return function(id) {
        var proxy;
        if (id == -1) return null;
        Proxy.prototype = records[id] || {};
        proxy = new Proxy();
        proxy.$ = getFeatureById(id);
        return proxy;
      };
    }

    // idA - id of a record
    // idB - id of a record, or -1
    // rec - optional data record
    return function(idA, idB, rec) {
      var val;
      ctx.A = getA(idA);
      ctx.B = getB(idB);
      if (rec) {
        // initialize new fields to null so assignments work
        nullifyUnsetProperties(vars, rec);
      }
      try {
        val = func.call(ctx, rec || {}, ctx);
      } catch(e) {
        stop(e.name, "in expression [" + exp + "]:", e.message);
      }
      return val;
    };
  }

  function compileFeatureExpression(rawExp, lyr, arcs, opts_) {
    var opts = utils.extend({}, opts_),
        exp = cleanExpression(rawExp || ''),
        mutable = !opts.no_assign, // block assignment expressions
        vars = getAssignedVars(exp),
        func, records;

    if (mutable && vars.length > 0 && !lyr.data) {
      initDataTable(lyr);
    }

    if (!mutable) {
      // protect global object from assigned values
      opts.context = opts.context || {};
      nullifyUnsetProperties(vars, opts.context);
    }

    records = lyr.data ? lyr.data.getRecords() : [];
    func = getExpressionFunction(exp, lyr, arcs, opts);

    // @destRec (optional) substitute for records[recId] (used by -calc)
    return function(recId, destRec) {
      var record;
      if (destRec) {
        record = destRec;
      } else {
        record = records[recId] || (records[recId] = {});
      }

      // initialize new fields to null so assignments work
      if (mutable) {
        nullifyUnsetProperties(vars, record);
      }
      return func(record, recId);
    };
  }

  // Return array of variables on the left side of assignment operations
  // @hasDot (bool) Return property assignments via dot notation
  function getAssignedVars(exp, hasDot) {
    var rxp = /[a-z_$][.a-z0-9_$]*(?= *=[^>=])/ig; // ignore arrow functions and comparisons
    var matches = exp.match(rxp) || [];
    var f = function(s) {
      var i = s.indexOf('.');
      return hasDot ? i > -1 : i == -1;
    };
    var vars = utils.uniq(matches.filter(f));
    return vars;
  }

  // Return array of objects with properties assigned via dot notation
  // e.g.  'd.value = 45' ->  ['d']
  function getAssignmentObjects(exp) {
    var matches = getAssignedVars(exp, true),
        names = [];
    matches.forEach(function(s) {
      var match = /^([^.]+)\.[^.]+$/.exec(s);
      var name = match ? match[1] : null;
      if (name && name != 'this') {
        names.push(name);
      }
    });
    return utils.uniq(names);
  }

  function compileExpressionToFunction(exp, opts) {
    // $$ added to avoid duplication with data field variables (an error condition)
    var functionBody, func;
    if (opts.returns) {
      // functionBody = 'return ' + functionBody;
      functionBody = 'var $$retn = ' + exp + '; return $$retn;';
    } else {
      functionBody = exp;
    }
    functionBody = 'with($$env){with($$record){ ' + functionBody + '}}';
    try {
      func = new Function('$$record,$$env',  functionBody);
    } catch(e) {
      // if (opts.quiet) throw e;
      stop(e.name, 'in expression [' + exp + ']');
    }
    return func;
  }

  function getExpressionFunction(exp, lyr, arcs, opts) {
    var getFeatureById = initFeatureProxy(lyr, arcs, opts);
    var layerOnlyProxy = addLayerGetters({}, lyr, arcs);
    var ctx = getExpressionContext(lyr, opts.context, opts);
    var func = compileExpressionToFunction(exp, opts);
    return function(rec, i) {
      var val;
      // Assigning feature/layer proxy to '$' -- maybe this should be removed,
      // since it is also exposed as "this".
      // (kludge) i is undefined in calc expressions ... we still
      //   may need layer data (but not single-feature data)
      ctx.$ = i >= 0 ? getFeatureById(i) : layerOnlyProxy;
      ctx._ = ctx; // provide access to functions when masked by variable names
      ctx.d = rec || null; // expose data properties a la d3 (also exposed as this.properties)
      try {
        val = func.call(ctx.$, rec, ctx);
      } catch(e) {
        // if (opts.quiet) throw e;
        stop(e.name, "in expression [" + exp + "]:", e.message);
      }
      return val;
    };
  }

  function nullifyUnsetProperties(vars, obj) {
    for (var i=0; i<vars.length; i++) {
      if (vars[i] in obj === false) {
        obj[vars[i]] = null;
      }
    }
  }

  function getExpressionContext(lyr, mixins, opts) {
    var defs = getStashedVar('defs');
    var env = getBaseContext();
    var ctx = {};
    var fields = lyr.data ? lyr.data.getFields() : [];
    opts = opts || {};
    addFeatureExpressionUtils(env); // mix in round(), sprintf(), etc.
    if (fields.length > 0) {
      // default to null values, so assignments to missing data properties
      // are applied to the data record, not the global object
      nullifyUnsetProperties(fields, env);
    }
    // Add global 'defs' to the expression context
    mixins = utils.defaults(mixins || {}, defs);
    // also add defs as 'global' object
    env.global = defs;
    Object.keys(mixins).forEach(function(key) {
      // Catch name collisions between data fields and user-defined functions
      var d = Object.getOwnPropertyDescriptor(mixins, key);
      if (d.get) {
        // copy accessor function from mixins to context
        Object.defineProperty(ctx, key, {get: d.get}); // copy getter function to context
      } else {
        // copy regular property from mixins to context, but make it non-writable
        Object.defineProperty(ctx, key, {value: mixins[key]});
      }
    });
    // make context properties non-writable, so they can't be replaced by an expression
    return Object.keys(env).reduce(function(memo, key) {
      if (key in memo) {
        // property has already been set (probably by a mixin, above): skip
        // "no_warn" option used in calc= expressions
        if (!opts.no_warn) {
          if (typeof memo[key] == 'function' && fields.indexOf(key) > -1) {
            message('Warning: ' + key + '() function is hiding a data field with the same name');
          } else {
            message('Warning: "' + key + '" has multiple definitions');
          }
        }
      } else {
        Object.defineProperty(memo, key, {value: env[key]}); // writable: false is default
      }
      return memo;
    }, ctx);
  }

  function getBaseContext() {
    // Mask global properties (is this effective/worth doing?)
    var obj = {globalThis: void 0}; // some globals are not iterable
    (function() {
      for (var key in this) {
        obj[key] = void 0;
      }
    }());
    obj.console = console;
    return obj;
  }

  var Expressions = /*#__PURE__*/Object.freeze({
    __proto__: null,
    compileValueExpression: compileValueExpression,
    compileFeaturePairFilterExpression: compileFeaturePairFilterExpression,
    compileFeaturePairExpression: compileFeaturePairExpression,
    compileFeatureExpression: compileFeatureExpression,
    getAssignedVars: getAssignedVars,
    getAssignmentObjects: getAssignmentObjects,
    compileExpressionToFunction: compileExpressionToFunction,
    getBaseContext: getBaseContext
  });

  function getMode(values) {
    var data = getModeData(values);
    return data.modes[0];
  }

  function getValueCountData(values) {
    var uniqValues = [],
        uniqIndex = {},
        counts = [];
    var i, val;
    for (i=0; i<values.length; i++) {
      val = values[i];
      if (val in uniqIndex === false) {
        uniqIndex[val] = uniqValues.length;
        uniqValues.push(val);
        counts.push(1);
      } else {
        counts[uniqIndex[val]]++;
      }
    }
    return {
      values: uniqValues,
      counts: counts
    };
  }

  function getMaxValue(values) {
    var max = -Infinity;
    var i;
    for (i=0; i<values.length; i++) {
      if (values[i] > max) max = values[i];
    }
    return max;
  }

  function getCountDataSummary(o) {
    var counts = o.counts;
    var values = o.values;
    var maxCount = counts.length > 0 ? getMaxValue(counts) : 0;
    var nextCount = 0;
    var modes = [];
    var i, count;
    for (i=0; i<counts.length; i++) {
      count = counts[i];
      if (count === maxCount) {
        modes.push(values[i]);
      } else if (count > nextCount) {
        nextCount = count;
      }
    }
    return {
      modes: modes,
      margin: modes.length > 1 ? 0 : maxCount - nextCount,
      count: maxCount
    };
  }

  function getModeData(values, verbose) {
    var counts = getValueCountData(values);
    var modes = getCountDataSummary(counts);
    if (verbose) {
      modes.counts = counts.counts;
      modes.values = counts.values;
    }
    return modes;
  }

  var CalcUtils = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getMode: getMode,
    getModeData: getModeData
  });

  var cmd = {}; // command functions get added to this object

  // Get a copy of a layer containing a subset of the layer's features,
  // given a "where" expression in the options object
  function getLayerSelection(lyr, arcs, opts) {
    var lyr2 = utils.extend({}, lyr);
    var filterOpts = {
          expression: opts.where,
          invert: !!opts.invert,
          verbose: false,   // don't print status message
          no_replace: opts.no_replace // copy features if original features will be retained
        };
    return cmd.filterFeatures(lyr2, arcs, filterOpts);
  }

  // Used to run -dissolve with the where= option; could be generalized to support
  // other commands
  function applyCommandToLayerSelection(commandFunc, lyr, arcs, opts) {
    if (!opts || !opts.where) {
      error('Missing required "where" parameter');
    }
    var subsetLyr = getLayerSelection(lyr, arcs, opts);
    var cmdOpts = utils.defaults({where: null}, opts); // prevent infinite recursion
    var outputLyr = commandFunc(subsetLyr, arcs, cmdOpts);
    var filterOpts = utils.defaults({invert: true}, opts);
    var filteredLyr = getLayerSelection(lyr, arcs, filterOpts);
    var merged = cmd.mergeLayers([filteredLyr, outputLyr], {verbose: false, force: true});
    return merged[0];
  }

  // Calculate an expression across a group of features, print and return the result
  // Supported functions include sum(), average(), max(), min(), median(), count()
  // Functions receive an expression to be applied to each feature (like the -each command)
  // Examples: 'sum($.area)' 'min(income)'
  // opts.expression  Expression to evaluate
  // opts.where  Optional filter expression (see -filter command)
  //
  cmd.calc = function(lyr, arcs, opts) {
    var msg = opts.expression,
        result, compiled, defs;
    if (opts.where) {
      // TODO: implement no_replace option for filter() instead of this
      lyr = getLayerSelection(lyr, arcs, opts);
      msg += ' where ' + opts.where;
    }
    // Save any assigned variables to the defs object, so they will be available
    // for later -each expressions to use.
    defs = getStashedVar('defs');
    compiled = compileCalcExpression(lyr, arcs, opts.expression);
    result = compiled(null, defs);
    message(msg + ":  " + result);
    return result;
  };

  function evalCalcExpression(lyr, arcs, exp) {
    return compileCalcExpression(lyr, arcs, exp)();
  }

  function compileCalcExpression(lyr, arcs, exp) {
    var rowNo = 0, colNo = 0, cols = [];
    var ctx1 = { // context for first phase (capturing values for each feature)
          count: assign,
          sum: captureNum,
          sums: capture,
          average: captureNum,
          mean: captureNum,
          median: captureNum,
          quantile: captureNum,
          iqr: captureNum,
          quartile1: captureNum,
          quartile2: captureNum,
          quartile3: captureNum,
          min: captureNum,
          max: captureNum,
          mode: capture,
          collect: capture,
          first: assignOnce,
          every: every,
          some: some,
          last: assign
        },
        ctx2 = { // context for second phase (calculating results)
          count: wrap(function() {return rowNo;}, 0),
          sum: wrap(utils.sum, 0),
          sums: wrap(sums),
          median: wrap(utils.findMedian),
          quantile: wrap2(utils.findQuantile),
          iqr: wrap(function(arr) {
            return utils.findQuantile(arr, 0.75) - utils.findQuantile(arr, 0.25);
          }),
          quartile1: wrap(function(arr) { return utils.findQuantile(arr, 0.25); }),
          quartile2: wrap(utils.findMedian),
          quartile3: wrap(function(arr) { return utils.findQuantile(arr, 0.75); }),
          min: wrap(min),
          max: wrap(max),
          average: wrap(utils.mean),
          mean: wrap(utils.mean),
          mode: wrap(getMode),
          collect: wrap(pass),
          first: wrap(pass),
          every: wrap(pass, false),
          some: wrap(pass, false),
          last: wrap(pass)
        },
        len = getFeatureCount(lyr),
        calc1, calc2;

    if (lyr.geometry_type) {
      // add functions related to layer geometry (e.g. for subdivide())
      ctx1.width = ctx1.height = noop;
      ctx2.width = function() {return getLayerBounds(lyr, arcs).width();};
      ctx2.height = function() {return getLayerBounds(lyr, arcs).height();};
    }

    calc1 = compileFeatureExpression(exp, lyr, arcs, {context: ctx1,
        no_assign: true, no_warn: true});
    // changed data-only layer to full layer to expose layer geometry, etc
    // (why not do this originally?)
    // calc2 = compileFeatureExpression(exp, {data: lyr.data}, null,
    //     {returns: true, context: ctx2, no_warn: true});
    calc2 = compileFeatureExpression(exp, lyr, arcs,
        {returns: true, context: ctx2, no_warn: true});

    // @destRec: optional destination record for assignments
    return function(ids, destRec) {
      var result;
      // phase 1: capture data
      if (ids) procRecords(ids);
      else procAll();
      // phase 2: calculate
      result = calc2(undefined, destRec);
      reset();
      return result;
    };

    function pass(o) {return o;}

    function max(arr) {
      return utils.getArrayBounds(arr).max;
    }

    function sums(arr) {
      var n = arr && arr.length ? arr[0].length : 0;
      var output = utils.initializeArray(Array(n), 0);
      arr.forEach(function(arr) {
        if (!arr || !arr.length) return;
        for (var i=0; i<n; i++) {
          output[i] += +arr[i] || 0;
        }
      });
      return output;
    }

    function min(arr) {
      return utils.getArrayBounds(arr).min;
    }

    // process captured data, or return nodata value if no records have been captured
    function wrap(proc, nullVal) {
      var nodata = arguments.length > 1 ? nullVal : null;
      return function() {
        var c = colNo++;
        return rowNo > 0 ? proc(cols[c]) : nodata;
      };
    }

    function wrap2(proc) {
      return function(arg1, arg2) {
        var c = colNo++;
        return rowNo > 0 ? proc(cols[c], arg2) : null;
      };
    }

    function procAll() {
      for (var i=0; i<len; i++) {
        procRecord(i);
      }
    }

    function procRecords(ids) {
      ids.forEach(procRecord);
    }

    function procRecord(i) {
      if (i < 0 || i >= len) error("Invalid record index");
      calc1(i);
      rowNo++;
      colNo = 0;
    }

    function noop() {}

    function reset() {
      rowNo = 0;
      colNo = 0;
      cols = [];
    }

    function captureNum(val) {
      if (isNaN(val) && val) { // accepting falsy values (be more strict?)
        stop("Expected a number, received:", val);
      }
      return capture(val);
    }

    function assignOnce(val) {
      if (rowNo === 0) cols[colNo] = val;
      colNo++;
      return val;
    }

    function every(val) {
      val = !!val;
      cols[colNo] = rowNo === 0 ? val : cols[colNo] && val;
      colNo++;
    }

    function some(val) {
      val = !!val;
      cols[colNo] = cols[colNo] || val;
      colNo++;
    }

    function assign(val) {
      cols[colNo++] = val;
      return val;
    }
    /*
    function captureArr(val) {
      capture(val);
      return [];
    }
    */

    function capture(val) {
      var col;
      if (rowNo === 0) {
        cols[colNo] = [];
      }
      col = cols[colNo];
      if (col.length != rowNo) {
        // make sure all functions are called each time
        // (if expression contains a condition, it will throw off the calculation)
        // TODO: allow conditions
        stop("Evaluation failed");
      }
      col.push(val);
      colNo++;
      return val;
    }
  }

  var Calc = /*#__PURE__*/Object.freeze({
    __proto__: null,
    evalCalcExpression: evalCalcExpression,
    compileCalcExpression: compileCalcExpression
  });

  // get function that returns an object containing calculated values
  function getJoinCalc(src, exp) {
    var calc = compileCalcExpression({data: src}, null, exp);
    return function(ids, destRec) {
      if (!ids) ids = [];
      calc(ids, destRec);
    };
  }

  var JoinCalc = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getJoinCalc: getJoinCalc
  });

  // Return a function to convert indexes of original features into indexes of grouped features
  // Uses categorical classification (a different id for each unique combination of values)
  function getCategoryClassifier(fields, data) {
    if (!fields || fields.length === 0) return function() {return 0;};
    fields.forEach(function(f) {
      requireDataField(data, f);
    });
    var index = {},
        count = 0,
        records = data.getRecords(),
        getKey = getMultiFieldKeyFunction(fields);
    return function(i) {
      var key = getKey(records[i]);
      if (key in index === false) {
        index[key] = count++;
      }
      return index[key];
    };
  }

  function getMultiFieldKeyFunction(fields) {
    return fields.reduce(function(partial, field) {
      // TODO: consider using JSON.stringify for fields that contain objects
      var strval = function(rec) {return String(rec[field]);};
      return partial ? function(rec) {return partial(rec) + '~~' + strval(rec);} : strval;
    }, null);
  }

  // Performs many-to-one data record aggregation on an array of data records
  // Returns an array of data records for a set of aggregated features
  //
  // @records input records
  // @getGroupId()  converts input record id to id of aggregated record
  //
  function aggregateDataRecords(records, getGroupId, opts) {
    var groups = groupIds(getGroupId, records.length);
    return aggregateDataRecords2(records, groups, opts);
  }

  // Performs many-to-many data record aggregation on an array of data records
  // (used by the -mosaic command)
  // getSourceIds()  receives the id of an output record and returns
  //    an array of input record ids
  //
  function recombineDataRecords(records, getSourceIds, n, opts) {
    var groups = [];
    for (var i=0; i<n; i++) {
      groups.push(getSourceIds(i));
    }
    return aggregateDataRecords2(records, groups, opts);
  }

  function aggregateDataRecords2(records, groups, opts) {
    var sumFields = opts.sum_fields || [],
        copyFields = opts.copy_fields || [],
        calc;

    if (opts.fields) {
      copyFields = copyFields.concat(opts.fields);
    }

    if (opts.calc) {
      calc = getJoinCalc(new DataTable(records), opts.calc);
    }

    function sum(field, group) {
      var tot = 0, rec;
      for (var i=0; i<group.length; i++) {
        rec = records[group[i]];
        tot += rec && rec[field] || 0;
      }
      return tot;
    }

    return groups.map(function(group) {
      var rec = {},
          j, first;
      group = group || [];
      first = records[group[0]];
      for (j=0; j<sumFields.length; j++) {
        rec[sumFields[j]] = sum(sumFields[j], group);
      }
      for (j=0; j<copyFields.length; j++) {
        rec[copyFields[j]] = first ? first[copyFields[j]] : null;
      }
      if (calc) {
        calc(group, rec);
      }
      return rec;
    });
  }

  // Returns array containing groups of feature indexes
  // @getId() (function) converts feature index into group index
  // @n number of features
  //
  function groupIds(getId, n) {
    var groups = [], id;
    for (var i=0; i<n; i++) {
      id = getId(i);
      if (id in groups) {
        groups[id].push(i);
      } else {
        groups[id] = [i];
      }
    }
    return groups;
  }

  var DataAggregation = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getCategoryClassifier: getCategoryClassifier,
    getMultiFieldKeyFunction: getMultiFieldKeyFunction,
    aggregateDataRecords: aggregateDataRecords,
    recombineDataRecords: recombineDataRecords
  });

  function dissolvePointGeometry(lyr, getGroupId, opts) {
    var useSph = !opts.planar && probablyDecimalDegreeBounds(getLayerBounds(lyr));
    var getWeight = opts.weight ? compileValueExpression(opts.weight, lyr) : null;
    var groups = [];

    // TODO: support multipoints
    if (countMultiPartFeatures(lyr.shapes) !== 0) {
      stop("Dissolving multi-part points is not supported");
    }

    lyr.shapes.forEach(function(shp, i) {
      var groupId = getGroupId(i);
      var weight = getWeight ? getWeight(i) : 1;
      var p = shp && shp[0]; // Using first point (TODO: handle multi-point features)
      var tmp;
      if (!p) return;
      if (useSph) {
        tmp = [];
        geom.lngLatToXYZ(p[0], p[1], tmp);
        p = tmp;
      }
      groups[groupId] = reducePointCentroid(groups[groupId], p, weight);
    });

    return groups.map(function(memo) {
      var p1, p2;
      if (!memo) return null;
      if (useSph) {
        p1 = memo.centroid;
        p2 = [];
        geom.xyzToLngLat(p1[0], p1[1], p1[2], p2);
      } else {
        p2 = memo.centroid;
      }
      return memo ? [p2] : null;
    });
  }

  function reducePointCentroid(memo, p, weight) {
    var x = p[0],
        y = p[1],
        sum, k;

    if (x == x && y == y && weight > 0) {
      if (!memo) {
        memo = {sum: weight, centroid: p.concat()};
      } else {
        sum = memo.sum + weight;
        k = memo.sum / sum;
        memo.centroid[0] = k * memo.centroid[0] + weight * x / sum;
        memo.centroid[1] = k * memo.centroid[1] + weight * y / sum;
        if (p.length == 3) {
          memo.centroid[2] = k * memo.centroid[2] + weight * p[2] / sum;
        }
        memo.sum = sum;
      }
    }
    return memo;
  }

  // Dissolve polyline features
  function dissolvePolylineGeometry(lyr, getGroupId, arcs, opts) {
    var groups = getPolylineDissolveGroups(lyr.shapes, getGroupId);
    var dissolve = getPolylineDissolver(arcs);
    return groups.map(dissolve);
  }

  // Create one array of arc ids for each group
  function getPolylineDissolveGroups(shapes, getGroupId) {
    var groups = [];
    traversePaths(shapes, function(o) {
      var groupId = getGroupId(o.shapeId);
      if (groupId in groups === false) {
        groups[groupId] = [];
      }
      groups[groupId].push(o.arcId);
    });
    return groups;
  }

  function getPolylineDissolver(arcs) {
    var flags = new Uint8Array(arcs.size());
    var testArc = function(id) {return flags[absArcId(id)] > 0;};
    var useArc = function(id) {flags[absArcId(id)] = 0;};
    var nodes = new NodeCollection(arcs);
    return function(ids) {
      ids.forEach(function(id) {flags[absArcId(id)] = 1;});
      var ends = findPolylineEnds(ids, nodes, testArc);
      var straightParts = collectPolylineArcs(ends, nodes, testArc, useArc);
      var ringParts = collectPolylineArcs(ids, nodes, testArc, useArc);
      var allParts = straightParts.concat(ringParts);
      ids.forEach(function(id) {flags[absArcId(id)] = 0;}); // may not be necessary
      return allParts;
    };
  }

  /*



  */

  // TODO: use polygon pathfinder shared code
  function collectPolylineArcs(ids, nodes, testArc, useArc) {
    var parts = [];
    ids.forEach(function(startId) {
      var part = [];
      var nextId = startId;
      var nextIds;
      while (testArc(nextId)) {
        part.push(nextId);
        nextIds = testArc(nextId) ? nodes.getConnectedArcs(nextId, testArc) : [];
        useArc(nextId); // use (unset) arc after connections have been found
        if (nextIds.length > 0) {
          nextId = ~nextIds[0]; // switch arc direction to lead away from node
        } else {
          break;
        }
      }
      if (part.length > 0) parts.push(part);
    });
    return parts;
  }

  // Return array of dead-end arcs for a dissolved group.
  function findPolylineEnds(ids, nodes, filter) {
    var ends = [];
    ids.forEach(function(arcId) {
      if (nodes.getConnectedArcs(arcId, filter).length === 0) {
        ends.push(~arcId); // arc points away from terminus
      }
      if (nodes.getConnectedArcs(~arcId, filter).length === 0) {
        ends.push(arcId);
      }
    });
    return ends;
  }

  function dissolvePolygonGeometry(shapes, getGroupId) {
    var segments = dissolveFirstPass(shapes, getGroupId);
    return dissolveSecondPass(segments, shapes, getGroupId);
  }

  // First pass -- identify pairs of segments that can be dissolved
  function dissolveFirstPass(shapes, getGroupId) {
    var groups = [],
        largeGroups = [],
        segments = [],
        ids = shapes.map(function(shp, i) {
          return getGroupId(i);
        });

    traversePaths(shapes, procArc);
    largeGroups.forEach(splitGroup);
    return segments;

    function procArc(obj) {
      var arcId = obj.arcId,
          idx = arcId < 0 ? ~arcId : arcId,
          segId = segments.length,
          group = groups[idx];
      if (!group) {
        group = [];
        groups[idx] = group;
      }
      group.push(segId);
      obj.group = group;
      segments.push(obj);

      // Three or more segments sharing the same arc is abnormal topology...
      // Need to try to identify pairs of matching segments in each of these
      // groups.
      //
      if (group.length == 3) {
        largeGroups.push(group);
      }
    }

    function findMatchingPair(group, cb) {
      var arc1, arc2;
      for (var i=0; i<group.length - 1; i++) {
        arc1 = segments[group[i]];
        for (var j=i+1; j<group.length; j++) {
          arc2 = segments[group[j]];
          if (cb(arc1, arc2)) {
            return [arc1.segId, arc2.segId];
          }
        }
      }
      return null;
    }

    function checkFwExtension(arc1, arc2) {
      return getNextSegment(arc1, segments, shapes).arcId ===
          ~getNextSegment(arc2, segments, shapes).arcId;
    }

    function checkBwExtension(arc1, arc2) {
      return getPrevSegment(arc1, segments, shapes).arcId ===
          ~getPrevSegment(arc2, segments, shapes).arcId;
    }

    function checkDoubleExtension(arc1, arc2) {
      return checkPairwiseMatch(arc1, arc2) &&
          checkFwExtension(arc1, arc2) &&
          checkBwExtension(arc1, arc2);
    }

    function checkSingleExtension(arc1, arc2) {
      return checkPairwiseMatch(arc1, arc2) &&
          (checkFwExtension(arc1, arc2) ||
          checkBwExtension(arc1, arc2));
    }

    function checkPairwiseMatch(arc1, arc2) {
      return arc1.arcId === ~arc2.arcId && ids[arc1.shapeId] ===
          ids[arc2.shapeId];
    }

    function updateGroupIds(ids) {
      ids.forEach(function(id) {
        segments[id].group = ids;
      });
    }

    // split a group of segments into pairs of matching segments + a residual group
    // @group Array of segment ids
    //
    function splitGroup(group) {
      // find best-match segment pair
      var group2 = findMatchingPair(group, checkDoubleExtension) ||
          findMatchingPair(group, checkSingleExtension) ||
          findMatchingPair(group, checkPairwiseMatch);
      if (group2) {
        group = group.filter(function(i) {
          return !utils.contains(group2, i);
        });
        updateGroupIds(group);
        updateGroupIds(group2);
        // Split again if reduced group is still large
        if (group.length > 2) splitGroup(group);
      }
    }
  }

  // Second pass -- generate dissolved shapes
  //
  function dissolveSecondPass(segments, shapes, getGroupId) {
    var dissolveShapes = [];
    segments.forEach(procSegment);
    return dissolveShapes;

    // @obj is an arc instance
    function procSegment(obj) {
      if (obj.used) return;
      var match = findDissolveArc(obj);
      if (!match) buildRing(obj);
    }

    function addRing(arcs, i) {
      if (i in dissolveShapes === false) {
        dissolveShapes[i] = [];
      }
      dissolveShapes[i].push(arcs);
    }

    // Generate a dissolved ring
    // @firstArc the first arc instance in the ring
    //
    function buildRing(firstArc) {
      var newArcs = [firstArc.arcId],
          nextArc = getNextArc(firstArc);
          firstArc.used = true;

      while (nextArc && nextArc != firstArc) {
        newArcs.push(nextArc.arcId);
        nextArc.used = true;
        nextArc = getNextArc(nextArc);
        if (nextArc && nextArc != firstArc && nextArc.used) error("buildRing() topology error");
      }

      if (!nextArc) error("buildRing() traversal error");
      firstArc.used = true;
      addRing(newArcs, getGroupId(firstArc.shapeId));
    }

    // Get the next arc in a dissolved polygon ring
    // @obj an undissolvable arc instance
    //
    function getNextArc(obj, depth) {
      var next = getNextSegment(obj, segments, shapes),
          match;
      depth = depth || 0;
      if (next != obj) {
        match = findDissolveArc(next);
        if (match) {
          if (depth > 100) {
            error ('deep recursion -- unhandled topology problem');
          }
          // if (match.part.arcs.length == 1) {
          if (shapes[match.shapeId][match.partId].length == 1) {
            // case: @obj has an island inclusion -- keep traversing @obj
            // TODO: test case if @next is first arc in the ring
            next = getNextArc(next, depth + 1);
          } else {
            next = getNextArc(match, depth + 1);
          }
        }
      }
      return next;
    }

    // Look for an arc instance that can be dissolved with segment @obj
    // (must be going the opposite direction and have same dissolve key, etc)
    // Return matching segment or null if no match
    //
    function findDissolveArc(obj) {
      var dissolveId = getGroupId(obj.shapeId), // obj.shape.dissolveKey,
          match, matchId;
      matchId = utils.find(obj.group, function(i) {
        var a = obj,
            b = segments[i];
        if (a == b ||
            b.used ||
            getGroupId(b.shapeId) !== dissolveId ||
            // don't prevent rings from dissolving with themselves (risky?)
            // a.shapeId == b.shapeId && a.partId == b.partId ||
            a.arcId != ~b.arcId) return false;
        return true;
      });
      match = matchId === null ? null : segments[matchId];
      return match;
    }
  }

  function getNextSegment(seg, segments, shapes) {
    return getSegmentByOffs(seg, segments, shapes, 1);
  }

  function getPrevSegment(seg, segments, shapes) {
    return getSegmentByOffs(seg, segments, shapes, -1);
  }

  function getSegmentByOffs(seg, segments, shapes, offs) {
    var arcs = shapes[seg.shapeId][seg.partId],
        partLen = arcs.length,
        nextOffs = (seg.i + offs) % partLen,
        nextSeg;
    if (nextOffs < 0) nextOffs += partLen;
    nextSeg = segments[seg.segId - seg.i + nextOffs];
    if (!nextSeg || nextSeg.shapeId != seg.shapeId) error("index error");
    return nextSeg;
  }

  var PolygonDissolve = /*#__PURE__*/Object.freeze({
    __proto__: null,
    dissolvePolygonGeometry: dissolvePolygonGeometry
  });

  // Generate a dissolved layer
  // @opts.fields (optional) names of data fields (dissolves all if falsy)
  // @opts.sum-fields (Array) (optional)
  // @opts.copy-fields (Array) (optional)
  //
  cmd.dissolve = function(lyr, arcs, opts) {
    var dissolveShapes, getGroupId;
    opts = utils.extend({}, opts);
    if (opts.where) {
      return applyCommandToLayerSelection(cmd.dissolve, lyr, arcs, opts);
    }
    if (opts.field) opts.fields = [opts.field]; // support old "field" parameter
    getGroupId = getCategoryClassifier(opts.fields, lyr.data);
    if (opts.multipart || opts.group_points) {
      dissolveShapes = makeMultipartShapes(lyr, getGroupId);
    } else if (lyr.geometry_type == 'polygon') {
      dissolveShapes = dissolvePolygonGeometry(lyr.shapes, getGroupId);
    } else if (lyr.geometry_type == 'polyline') {
      dissolveShapes = dissolvePolylineGeometry(lyr, getGroupId, arcs);
    } else if (lyr.geometry_type == 'point') {
      dissolveShapes = dissolvePointGeometry(lyr, getGroupId, opts);
    }
    return composeDissolveLayer(lyr, dissolveShapes, getGroupId, opts);
  };

  function makeMultipartShapes(lyr, getGroupId) {
    if (!lyr.shapes || !lyr.geometry_type) {
      stop('Layer is missing geometry');
    }
    cloneShapes(lyr.shapes);
    var shapes2 = [];
    lyr.shapes.forEach(function(shp, i) {
      var groupId = getGroupId(i);
      if (!shp) return;
      if (!shapes2[groupId]) {
        shapes2[groupId] = shp;
      } else {
        shapes2[groupId].push.apply(shapes2[groupId], shp);
      }
    });
    return shapes2;
  }

  // @lyr: original undissolved layer
  // @shapes: dissolved shapes
  function composeDissolveLayer(lyr, shapes, getGroupId, opts) {
    var records = null;
    var lyr2;
    if (lyr.data) {
      records = aggregateDataRecords(lyr.data.getRecords(), getGroupId, opts);
      // replace missing shapes with nulls
      for (var i=0, n=records.length; i<n; i++) {
        if (shapes && !shapes[i]) {
          shapes[i] = null;
        }
      }
    }
    lyr2 = {
      name: opts.no_replace ? null : lyr.name,
      shapes: shapes,
      data: records ? new DataTable(records) : null,
      geometry_type: lyr.geometry_type
    };
    if (!opts.silent) {
      printDissolveMessage(lyr, lyr2);
    }
    return lyr2;
  }

  function printDissolveMessage(pre, post) {
    var n1 = getFeatureCount(pre),
        n2 = getFeatureCount(post),
        msg = utils.format('Dissolved %,d feature%s into %,d feature%s',
          n1, utils.pluralSuffix(n1), n2,
          utils.pluralSuffix(n2));
    message(msg);
  }

  // Maps tile ids to shape ids (both are non-negative integers). Supports
  //    one-to-many mapping (a tile may belong to multiple shapes)
  // Also maps shape ids to tile ids. A shape may contain multiple tiles
  // Also supports 'flattening' -- removing one-to-many tile-shape mappings by
  //    removing all but one shape from a tile.
  // Supports one-to-many mapping
  function TileShapeIndex(mosaic, opts) {
    // indexes for mapping tile ids to shape ids
    var singleIndex = new Int32Array(mosaic.length);
    utils.initializeArray(singleIndex, -1);
    var multipleIndex = [];
    // index that maps shape ids to tile ids
    var shapeIndex = [];

    this.getTileIdsByShapeId = function(shapeId) {
      var ids = shapeIndex[shapeId];
      // need to filter out tile ids that have been set to -1 (indicating removal)
      return ids ? ids.filter(function(id) {return id >= 0;}) : [];
    };

    // assumes index has been flattened
    this.getShapeIdByTileId = function(id) {
      var shapeId = singleIndex[id];
      return shapeId >= 0 ? shapeId : -1;
    };

    // return ids of all shapes that include a tile
    this.getShapeIdsByTileId = function(id) {
      var singleId = singleIndex[id];
      if (singleId >= 0) {
        return [singleId];
      }
      if (singleId == -1) {
        return [];
      }
      return multipleIndex[id];
    };

    this.indexTileIdsByShapeId = function(shapeId, tileIds, weightFunction) {
      shapeIndex[shapeId] = [];
      for (var i=0; i<tileIds.length; i++) {
        indexShapeIdByTileId(shapeId, tileIds[i], weightFunction);
      }
    };

    // remove many-to-one tile=>shape mappings
    this.flatten = function() {
      multipleIndex.forEach(function(shapeIds, tileId) {
        flattenStackedTile(tileId);
      });
      multipleIndex = [];
    };

    this.getUnusedTileIds = function() {
      var ids = [];
      for (var i=0, n=singleIndex.length; i<n; i++) {
        if (singleIndex[i] == -1) ids.push(i);
      }
      return ids;
    };

    // used by gap fill; assumes that flatten() has been called
    this.addTileToShape = function(shapeId, tileId) {
      if (shapeId in shapeIndex === false || singleIndex[tileId] != -1) {
        error('Internal error');
      }
      singleIndex[tileId] = shapeId;
      shapeIndex[shapeId].push(tileId);
    };

    // add a shape id to a tile
    function indexShapeIdByTileId(shapeId, tileId, weightFunction) {
      var singleId = singleIndex[tileId];
      if (singleId != -1 && opts.flat) {
        // pick the best shape if we have a weight function
        if (weightFunction && weightFunction(shapeId) > weightFunction(singleId)) {
          // replace existing shape reference
          removeTileFromShape(tileId, singleId); // bottleneck when overlaps are many
          singleIndex[tileId] = singleId;
          singleId = -1;
        } else {
          // keep existing shape reference
          return;
        }
      }
      if (singleId == -1) {
        singleIndex[tileId] = shapeId;
      } else if (singleId == -2) {
        multipleIndex[tileId].push(shapeId);
      } else {
        multipleIndex[tileId] = [singleId, shapeId];
        singleIndex[tileId] = -2;
      }
      shapeIndex[shapeId].push(tileId);
    }


    function flattenStackedTile(tileId) {
      // TODO: select the best shape (using some metric)
      var shapeIds = multipleIndex[tileId];
      // if (!shapeIds || shapeIds.length > 1 === false) error('flattening error');
      var selectedId = shapeIds[0];
      var shapeId;
      singleIndex[tileId] = selectedId; // add shape to single index
      // remove tile from other stacked shapes
      for (var i=0; i<shapeIds.length; i++) {
        shapeId = shapeIds[i];
        if (shapeId != selectedId) {
          removeTileFromShape(tileId, shapeId);
        }
      }
    }

    function removeTileFromShape(tileId, shapeId) {
      var tileIds = shapeIndex[shapeId];
      for (var i=0; i<tileIds.length; i++) {
        if (tileIds[i] === tileId) {
          tileIds[i] = -1;
          break;
        }
      }
    }
  }

  // Keep track of whether positive or negative integer ids are 'used' or not.

  function IdTestIndex(n) {
    var index = new Uint8Array(n);
    var setList = [];

    this.setId = function(id) {
      if (!this.hasId(id)) {
        setList.push(id);
      }
      if (id < 0) {
        index[~id] |= 2;
      } else {
        index[id] |= 1;
      }
    };

    this.clear = function() {
      var index = this;
      setList.forEach(function(id) {
        index.clearId(id);
      });
      setList = [];
    };

    this.hasId = function(id) {
      return id < 0 ? (index[~id] & 2) == 2 : (index[id] & 1) == 1;
    };

    // clear a signed id
    this.clearId = function(id) {
      if (id < 0) {
        index[~id] &= 1; // clear reverse arc, preserve fwd arc
      } else {
        index[id] &= 2; // clear fwd arc, preserve rev arc
      }
    };

    this.getIds = function() {
      return setList;
    };

    this.setIds = function(ids) {
      for (var i=0; i<ids.length; i++) {
        this.setId(ids[i]);
      }
    };
  }

  // Clean polygon or polyline shapes (in-place)
  //
  function cleanShapes(shapes, arcs, type) {
    for (var i=0, n=shapes.length; i<n; i++) {
      shapes[i] = cleanShape(shapes[i], arcs, type);
    }
  }

  // Remove defective arcs and zero-area polygon rings
  // Remove simple polygon spikes of form: [..., id, ~id, ...]
  // Don't remove duplicate points
  // Don't check winding order of polygon rings
  function cleanShape(shape, arcs, type) {
    return editShapeParts(shape, function(path) {
      var cleaned = cleanPath(path, arcs);
      if (type == 'polygon' && cleaned) {
        removeSpikesInPath(cleaned); // assumed by addIntersectionCuts()
        if (geom.getPlanarPathArea(cleaned, arcs) === 0) {
          cleaned = null;
        }
      }
      return cleaned;
    });
  }

  function cleanPath(path, arcs) {
    var nulls = 0;
    for (var i=0, n=path.length; i<n; i++) {
      if (arcs.arcIsDegenerate(path[i])) {
        nulls++;
        path[i] = null;
      }
    }
    return nulls > 0 ? path.filter(function(id) {return id !== null;}) : path;
  }


  // Remove pairs of ids where id[n] == ~id[n+1] or id[0] == ~id[n-1];
  // (in place)
  function removeSpikesInPath(ids) {
    var n = ids.length;
    if (n >= 2) {
      if (ids[0] == ~ids[n-1]) {
        ids.pop();
        ids.shift();
      } else {
        for (var i=1; i<n; i++) {
          if (ids[i-1] == ~ids[i]) {
            ids.splice(i-1, 2);
            break;
          }
        }
      }
      if (ids.length < n) {
        removeSpikesInPath(ids);
      }
    }
  }


  // Returns a function for splitting self-intersecting polygon rings
  // The splitter function receives a single polygon ring represented as an array
  // of arc ids, and returns an array of split-apart rings.
  //
  // Self-intersections in the input ring are assumed to occur at vertices, not along segments.
  // This requires that internal.addIntersectionCuts() has already been run.
  //
  // The rings output by this function may overlap each other, but each ring will
  // be non-self-intersecting. For example, a figure-eight shaped ring will be
  // split into two rings that touch each other where the original ring crossed itself.
  //
  function getSelfIntersectionSplitter(nodes) {
    var pathIndex = new IdTestIndex(nodes.arcs.size(), true);
    var filter = function(arcId) {
      return pathIndex.hasId(~arcId);
    };
    return function(path) {
      pathIndex.setIds(path);
      var paths = dividePath(path);
      pathIndex.clear();
      return paths;
    };

    // Returns array of 0 or more divided paths
    function dividePath(path) {
      var subPaths = null;
      for (var i=0, n=path.length; i < n - 1; i++) { // don't need to check last arc
        subPaths = dividePathAtNode(path, path[i]);
        if (subPaths !== null) {
          return subPaths;
        }
      }
      // indivisible path -- clean it by removing any spikes
      removeSpikesInPath(path);
      return path.length > 0 ? [path] : [];
    }

    // If arc @enterId enters a node with more than one open routes leading out:
    //   return array of sub-paths
    // else return null
    function dividePathAtNode(path, enterId) {
      var nodeIds = nodes.getConnectedArcs(enterId, filter),
          exitArcIndexes, exitArcId, idx;
      if (nodeIds.length < 2) return null;
      exitArcIndexes = [];
      for (var i=0; i<nodeIds.length; i++) {
        exitArcId = ~nodeIds[i];
        idx = indexOf(path, exitArcId);
        if (idx > -1) { // repeated scanning may be bottleneck
          // important optimization (TODO: explain this)
          // TODO: test edge case: exitArcId occurs twice in the path
          pathIndex.clearId(exitArcId);
          exitArcIndexes.push(idx);
        }
      }
      if (exitArcIndexes.length < 2) {
        return null;
      }
      // path forks -- recursively subdivide
      var subPaths = splitPathByIds(path, exitArcIndexes);
      return subPaths.reduce(accumulatePaths, null);
    }

    function accumulatePaths(memo, path) {
      var subPaths = dividePath(path);
      if (memo === null) {
        return subPaths;
      }
      memo.push.apply(memo, subPaths);
      return memo;
    }

    // Added as an optimization -- faster than using Array#indexOf()
    function indexOf(arr, el) {
      for (var i=0, n=arr.length; i<n; i++) {
        if (arr[i] === el) return i;
      }
      return -1;
    }

  }

  // Function returns an array of split-apart rings
  // @path An array of arc ids describing a self-intersecting polygon ring
  // @ids An array of two or more indexes of arcs that originate from a single vertex
  //      where @path intersects itself -- assumes indexes are in ascending sequence
  function splitPathByIds(path, indexes) {
    var subPaths = [];
    utils.genericSort(indexes, true); // sort ascending
    if (indexes[0] > 0) {
      subPaths.push(path.slice(0, indexes[0]));
    }
    for (var i=0, n=indexes.length; i<n; i++) {
      if (i < n-1) {
        subPaths.push(path.slice(indexes[i], indexes[i+1]));
      } else {
        subPaths.push(path.slice(indexes[i]));
      }
    }
    // handle case where first subring is split across endpoint of @path
    if (subPaths.length > indexes.length) {
      utils.merge(subPaths[0], subPaths.pop());
    }
    return subPaths;
  }

  var PathRepair = /*#__PURE__*/Object.freeze({
    __proto__: null,
    cleanShapes: cleanShapes,
    removeSpikesInPath: removeSpikesInPath,
    getSelfIntersectionSplitter: getSelfIntersectionSplitter,
    splitPathByIds: splitPathByIds
  });

  // TODO: also delete positive-space rings nested inside holes
  function deleteHoles(lyr, arcs) {
    editShapes(lyr.shapes, function(path) {
      if (geom.getPathArea(path, arcs) <= 0) {
        return null; // null deletes the path
      }
    });
  }

  // Returns a function that separates rings in a polygon into space-enclosing rings
  // and holes. Also fixes self-intersections.
  //
  function getHoleDivider(nodes, spherical) {
    var split = getSelfIntersectionSplitter(nodes);
    // var split = internal.getSelfIntersectionSplitter_v1(nodes); console.log('split')

    return function(rings, cw, ccw) {
      var pathArea = spherical ? geom.getSphericalPathArea : geom.getPlanarPathArea;
      forEachShapePart(rings, function(ringIds) {
        var splitRings = split(ringIds);
        if (splitRings.length === 0) {
          debug("[getRingDivider()] Defective path:", ringIds);
        }
        splitRings.forEach(function(ringIds, i) {
          var ringArea = pathArea(ringIds, nodes.arcs);
          if (ringArea > 0) {
            cw.push(ringIds);
          } else if (ringArea < 0) {
            ccw.push(ringIds);
          }
        });
      });
    };
  }

  var PolygonHoles = /*#__PURE__*/Object.freeze({
    __proto__: null,
    deleteHoles: deleteHoles,
    getHoleDivider: getHoleDivider
  });

  // Convert an array of intersections into an ArcCollection (for display)
  //

  function getIntersectionPoints(intersections) {
    return intersections.map(function(obj) {
          return [obj.x, obj.y];
        });
  }

  // Identify intersecting segments in an ArcCollection
  //
  // To find all intersections:
  // 1. Assign each segment to one or more horizontal stripes/bins
  // 2. Find intersections inside each stripe
  // 3. Concat and dedup
  //
  // Re-use buffer for temp data -- Chrome's gc starts bogging down
  // if large buffers are repeatedly created.
  var buf;
  function getUint32Array(count) {
    var bytes = count * 4;
    if (!buf || buf.byteLength < bytes) {
      buf = new ArrayBuffer(bytes);
    }
    return new Uint32Array(buf, 0, count);
  }

  function findSegmentIntersections(arcs, optArg) {
    var opts = utils.extend({}, optArg),
        bounds = arcs.getBounds();
        // TODO: handle spherical bounds
        !arcs.isPlanar() &&
            geom.containsBounds(getWorldBounds(), bounds.toArray());
        var ymin = bounds.ymin,
        yrange = bounds.ymax - ymin,
        stripeCount = opts.stripes || calcSegmentIntersectionStripeCount(arcs),
        stripeSizes = new Uint32Array(stripeCount),
        stripeId = stripeCount > 1 && yrange > 0 ? multiStripeId : singleStripeId,
        i, j;

    if (opts.tolerance >= 0 === false) {
      // by default, use a small tolerance when detecting segment intersections
      // (intended to overcome the effects of floating point rounding errors in geometrical formulas)
      opts.tolerance = getHighPrecisionSnapInterval(bounds.toArray());
    }

    function multiStripeId(y) {
      return Math.floor((stripeCount-1) * (y - ymin) / yrange);
    }

    function singleStripeId(y) {return 0;}
    // Count segments in each stripe
    arcs.forEachSegment(function(id1, id2, xx, yy) {
      var s1 = stripeId(yy[id1]),
          s2 = stripeId(yy[id2]);
      while (true) {
        stripeSizes[s1] = stripeSizes[s1] + 2;
        if (s1 == s2) break;
        s1 += s2 > s1 ? 1 : -1;
      }
    });

    // Allocate arrays for segments in each stripe
    var stripeData = getUint32Array(utils.sum(stripeSizes)),
        offs = 0;
    var stripes = [];
    utils.forEach(stripeSizes, function(stripeSize) {
      var start = offs;
      offs += stripeSize;
      stripes.push(stripeData.subarray(start, offs));
    });
    // Assign segment ids to each stripe
    utils.initializeArray(stripeSizes, 0);

    arcs.forEachSegment(function(id1, id2, xx, yy) {
      var s1 = stripeId(yy[id1]),
          s2 = stripeId(yy[id2]),
          count, stripe;
      while (true) {
        count = stripeSizes[s1];
        stripeSizes[s1] = count + 2;
        stripe = stripes[s1];
        stripe[count] = id1;
        stripe[count+1] = id2;
        if (s1 == s2) break;
        s1 += s2 > s1 ? 1 : -1;
      }
    });

    // Detect intersections among segments in each stripe.
    var raw = arcs.getVertexData(),
        intersections = [],
        arr;
    for (i=0; i<stripeCount; i++) {
      arr = intersectSegments(stripes[i], raw.xx, raw.yy, opts);
      for (j=0; j<arr.length; j++) {
        intersections.push(arr[j]);
      }
    }
    return dedupIntersections(intersections, opts.unique ? getUniqueIntersectionKey : null);
  }


  function sortIntersections(arr) {
    arr.sort(function(a, b) {
      return a.x - b.x || a.y - b.y;
    });
  }



  function dedupIntersections(arr, keyFunction) {
    var index = {};
    var getKey = keyFunction || getIntersectionKey;
    return arr.filter(function(o) {
      var key = getKey(o);
      if (key in index) {
        return false;
      }
      index[key] = true;
      return true;
    });
  }

  // Get an indexable key from an intersection object
  // Assumes that vertex ids of o.a and o.b are sorted
  function getIntersectionKey(o) {
    return o.a.join(',') + ';' + o.b.join(',');
  }

  function getUniqueIntersectionKey(o) {
    return o.x + ',' + o.y;
  }

  // Fast method
  // TODO: measure performance using a range of input data
  function calcSegmentIntersectionStripeCount2(arcs) {
    var segs = arcs.getFilteredPointCount() - arcs.size();
    var stripes = Math.pow(segs, 0.4) * 2;
    return Math.ceil(stripes) || 1;
  }

  // Alternate fast method
  function calcSegmentIntersectionStripeCount(arcs) {
    var segs = arcs.getFilteredPointCount() - arcs.size();
    var stripes = Math.ceil(Math.pow(segs * 10, 0.6) / 40);
    return stripes > 0 ? stripes : 1;
  }

  // Find intersections among a group of line segments
  //
  // TODO: handle case where a segment starts and ends at the same point (i.e. duplicate coords);
  //
  // @ids: Array of indexes: [s0p0, s0p1, s1p0, s1p1, ...] where xx[sip0] <= xx[sip1]
  // @xx, @yy: Arrays of x- and y-coordinates
  //
  function intersectSegments(ids, xx, yy, optsArg) {
    var lim = ids.length - 2,
        opts = optsArg || {},
        intersections = [],
        tolerance = opts.tolerance, // may be undefined
        s1p1, s1p2, s2p1, s2p2,
        s1p1x, s1p2x, s2p1x, s2p2x,
        s1p1y, s1p2y, s2p1y, s2p2y,
        hit, seg1, seg2, i, j;

    // Sort segments by xmin, to allow efficient exclusion of segments with
    // non-overlapping x extents.
    sortSegmentIds(xx, ids); // sort by ascending xmin

    i = 0;
    while (i < lim) {
      s1p1 = ids[i];
      s1p2 = ids[i+1];
      s1p1x = xx[s1p1];
      s1p2x = xx[s1p2];
      s1p1y = yy[s1p1];
      s1p2y = yy[s1p2];
      // count++;

      j = i;
      while (j < lim) {
        j += 2;
        s2p1 = ids[j];
        s2p1x = xx[s2p1];

        if (s1p2x < s2p1x) break; // x extent of seg 2 is greater than seg 1: done with seg 1
        //if (s1p2x <= s2p1x) break; // this misses point-segment intersections when s1 or s2 is vertical

        s2p1y = yy[s2p1];
        s2p2 = ids[j+1];
        s2p2x = xx[s2p2];
        s2p2y = yy[s2p2];

        // skip segments with non-overlapping y ranges
        if (s1p1y >= s2p1y) {
          if (s1p1y > s2p2y && s1p2y > s2p1y && s1p2y > s2p2y) continue;
        } else {
          if (s1p1y < s2p2y && s1p2y < s2p1y && s1p2y < s2p2y) continue;
        }

        // skip segments that are adjacent in a path (optimization)
        // TODO: consider if this eliminates some cases that should
        // be detected, e.g. spikes formed by unequal segments
        if (s1p1 == s2p1 || s1p1 == s2p2 || s1p2 == s2p1 || s1p2 == s2p2) {
          continue;
        }

        // test two candidate segments for intersection
        hit = geom.segmentIntersection(s1p1x, s1p1y, s1p2x, s1p2y,
            s2p1x, s2p1y, s2p2x, s2p2y, tolerance);
        if (hit) {
          seg1 = [s1p1, s1p2];
          seg2 = [s2p1, s2p2];
          intersections.push(formatIntersection(hit, seg1, seg2, xx, yy));
          if (hit.length == 4) {
            // two collinear segments may have two endpoint intersections
            intersections.push(formatIntersection(hit.slice(2), seg1, seg2, xx, yy));
          }
        }
      }
      i += 2;
    }
    return intersections;
  }

  function formatIntersection(xy, s1, s2, xx, yy) {
    var x = xy[0],
        y = xy[1],
        a, b;
    s1 = formatIntersectingSegment(x, y, s1[0], s1[1], xx, yy);
    s2 = formatIntersectingSegment(x, y, s2[0], s2[1], xx, yy);
    a = s1[0] < s2[0] ? s1 : s2;
    b = a == s1 ? s2 : s1;
    return {x: x, y: y, a: a, b: b};
  }

  // Receives:
  //   x, y: coordinates of intersection
  //   i, j: two segment endpoints, as indexes in xx and yy arrays
  // Returns:
  //   if x,y falls within the segment, returns ascending indexes
  //   if x,y coincides with an endpoint, returns the id of that endpoint twice
  function formatIntersectingSegment(x, y, i, j, xx, yy) {
    if (xx[i] == x && yy[i] == y) {
      return [i, i];
    }
    if (xx[j] == x && yy[j] == y) {
      return [j, j];
    }
    return i < j ? [i, j] : [j, i];
  }

  var SegmentIntersection = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getIntersectionPoints: getIntersectionPoints,
    findSegmentIntersections: findSegmentIntersections,
    sortIntersections: sortIntersections,
    dedupIntersections: dedupIntersections,
    calcSegmentIntersectionStripeCount2: calcSegmentIntersectionStripeCount2,
    calcSegmentIntersectionStripeCount: calcSegmentIntersectionStripeCount,
    intersectSegments: intersectSegments,
    formatIntersection: formatIntersection,
    formatIntersectingSegment: formatIntersectingSegment
  });

  // Functions for dividing polygons and polygons at points where arc-segments intersect

  // TODO:
  //    Consider inserting cut points on import, when building initial topology
  //    Improve efficiency (e.g. only update ArcCollection once)
  //    Remove junk arcs (collapsed and duplicate arcs) instead of just removing
  //       references to them

  // Divide a collection of arcs at points where segments intersect
  // and re-index the paths of all the layers that reference the arc collection.
  // (in-place)
  function addIntersectionCuts(dataset, _opts) {
    var opts = _opts || {};
    var arcs = dataset.arcs;
    var arcBounds = arcs && arcs.getBounds();
    var snapDist, nodes;
    if (!arcBounds || !arcBounds.hasBounds()) {
      return new NodeCollection([]);
    }

    if (opts.snap_interval) {
      snapDist = convertIntervalParam(opts.snap_interval, getDatasetCRS(dataset));
    } else if (!opts.no_snap && arcBounds.hasBounds()) {
      snapDist = getHighPrecisionSnapInterval(arcBounds.toArray());
    } else {
      snapDist = 0;
    }
    debug('addIntersectionCuts() snap dist:', snapDist);

    // bake-in any simplification (bug fix; before, -simplify followed by dissolve2
    // used to reset simplification)
    arcs.flatten();

    var changed = snapAndCut(dataset, snapDist);
    // Detect topology again if coordinates have changed
    if (changed || opts.rebuild_topology) {
      buildTopology(dataset);
    }

    // Clean shapes by removing collapsed arc references, etc.
    // TODO: consider alternative -- avoid creating degenerate arcs
    // in insertCutPoints()
    dataset.layers.forEach(function(lyr) {
      if (layerHasPaths(lyr)) {
        cleanShapes(lyr.shapes, arcs, lyr.geometry_type);
      }
    });

    // Further clean-up -- remove duplicate and missing arcs
    nodes = cleanArcReferences(dataset);
    return nodes;
  }

  function snapAndCut(dataset, snapDist) {
    var arcs = dataset.arcs;
    var cutOpts = snapDist > 0 ? {} : {tolerance: 0};
    var coordsHaveChanged = false;
    var snapCount, dupeCount, cutCount;
    snapCount = snapCoordsByInterval(arcs, snapDist);
    dupeCount = arcs.dedupCoords();

    // why was topology built here previously????
    // if (snapCount > 0 || dupeCount > 0) {
    //   // Detect topology again if coordinates have changed
    //   internal.buildTopology(dataset);
    // }

    // cut arcs at points where segments intersect
    cutCount = cutPathsAtIntersections(dataset, cutOpts);
    if (cutCount > 0 || snapCount > 0 || dupeCount > 0) {
      coordsHaveChanged = true;
    }
    // perform a second snap + cut pass if needed
    if (cutCount > 0) {
      cutCount = 0;
      snapCount = snapCoordsByInterval(arcs, snapDist);
      arcs.dedupCoords(); // need to do this here?
      if (snapCount > 0) {
        cutCount = cutPathsAtIntersections(dataset, cutOpts);
      }
      if (cutCount > 0) {
        arcs.dedupCoords(); // need to do this here?
        debug('Second-pass vertices added:', cutCount, 'consider third pass?');
      }
    }
    return coordsHaveChanged;
  }


  // Remap any references to duplicate arcs in paths to use the same arcs
  // Remove any unused arcs from the dataset's ArcCollection.
  // Return a NodeCollection
  function cleanArcReferences(dataset) {
    var nodes = new NodeCollection(dataset.arcs);
    var map = findDuplicateArcs(nodes);
    var dropCount;
    if (map) {
      replaceIndexedArcIds(dataset, map);
    }
    dropCount = deleteUnusedArcs(dataset);
    if (dropCount > 0) {
      // rebuild nodes if arcs have changed
      nodes = new NodeCollection(dataset.arcs);
    }
    return nodes;
  }


  // @map an Object mapping old to new ids
  function replaceIndexedArcIds(dataset, map) {
    var remapPath = function(ids) {
      var arcId, absId, id2;
      for (var i=0; i<ids.length; i++) {
        arcId = ids[i];
        absId = absArcId(arcId);
        id2 = map[absId];
        ids[i] = arcId == absId ? id2 : ~id2;
      }
      return ids;
    };
    dataset.layers.forEach(function(lyr) {
      if (layerHasPaths(lyr)) {
        editShapes(lyr.shapes, remapPath);
      }
    });
  }

  function findDuplicateArcs(nodes) {
    var map = new Int32Array(nodes.arcs.size()),
        count = 0,
        i2;
    for (var i=0, n=nodes.arcs.size(); i<n; i++) {
      i2 = nodes.findDuplicateArc(i);
      map[i] = i2;
      if (i != i2) count++;
    }
    return count > 0 ? map : null;
  }

  function deleteUnusedArcs(dataset) {
    var test = getArcPresenceTest2(dataset.layers, dataset.arcs);
    var count1 = dataset.arcs.size();
    var map = dataset.arcs.deleteArcs(test); // condenses arcs
    var count2 = dataset.arcs.size();
    var deleteCount = count1 - count2;
    if (deleteCount > 0) {
      replaceIndexedArcIds(dataset, map);
    }
    return deleteCount;
  }

  // Return a function for updating a path (array of arc ids)
  // @map array generated by insertCutPoints()
  // @arcCount number of arcs in divided collection (kludge)
  function getDividedArcUpdater(map, arcCount) {
    return function(ids) {
      var ids2 = [];
      for (var j=0; j<ids.length; j++) {
        remapArcId2(ids[j], ids2);
      }
      return ids2;
    };

    function remapArcId2(id, ids) {
      var rev = id < 0,
          absId = rev ? ~id : id,
          min = map[absId],
          max = (absId >= map.length - 1 ? arcCount : map[absId + 1]) - 1,
          id2;
      do {
        if (rev) {
          id2 = ~max;
          max--;
        } else {
          id2 = min;
          min++;
        }
        ids.push(id2);
      } while (max - min >= 0);
    }
  }

  // Divides a collection of arcs at points where arc paths cross each other
  // Returns array for remapping arc ids
  function divideArcs(arcs, opts) {
    var points = findClippingPoints(arcs, opts);
    // TODO: avoid the following if no points need to be added
    var map = insertCutPoints(points, arcs);
    // segment-point intersections currently create duplicate points
    // TODO: consider dedup in a later cleanup pass?
    // arcs.dedupCoords();
    return map;
  }

  function cutPathsAtIntersections(dataset, opts) {
    var n = dataset.arcs.getPointCount();
    var map = divideArcs(dataset.arcs, opts);
    var n2 = dataset.arcs.getPointCount();
    remapDividedArcs(dataset, map);
    return n2 - n;
  }

  function remapDividedArcs(dataset, map) {
    var remapPath = getDividedArcUpdater(map, dataset.arcs.size());
    dataset.layers.forEach(function(lyr) {
      if (layerHasPaths(lyr)) {
        editShapes(lyr.shapes, remapPath);
      }
    });
  }

  // Inserts array of cutting points into an ArcCollection
  // Returns array for remapping arc ids
  function insertCutPoints(unfilteredPoints, arcs) {
    var data = arcs.getVertexData(),
        xx0 = data.xx,
        yy0 = data.yy,
        nn0 = data.nn,
        i0 = 0,
        i1 = 0,
        nn1 = [],
        srcArcTotal = arcs.size(),
        map = new Uint32Array(srcArcTotal),
        points = filterSortedCutPoints(sortCutPoints(unfilteredPoints, xx0, yy0), arcs),
        destPointTotal = arcs.getPointCount() + points.length * 2,
        xx1 = new Float64Array(destPointTotal),
        yy1 = new Float64Array(destPointTotal),
        n0, n1, arcLen, p;

    points.reverse(); // reverse sorted order to use pop()
    p = points.pop();

    for (var srcArcId=0, destArcId=0; srcArcId < srcArcTotal; srcArcId++) {
      // start merging an arc
      arcLen = nn0[srcArcId];
      map[srcArcId] = destArcId;
      n0 = 0;
      n1 = 0;
      while (n0 < arcLen) {
        // copy another point
        xx1[i1] = xx0[i0];
        yy1[i1] = yy0[i0];
        i1++;
        n1++;
        while (p && p.i == i0) {
          // interpolate any clip points that fall within the current segment
          xx1[i1] = p.x;
          yy1[i1] = p.y;
          i1++;
          n1++;
          nn1[destArcId++] = n1; // end current arc at intersection
          n1 = 0; // begin new arc
          xx1[i1] = p.x;
          yy1[i1] = p.y;
          i1++;
          n1++;
          p = points.pop();
        }
        n0++;
        i0++;
      }
      nn1[destArcId++] = n1;
    }

    if (i1 != destPointTotal) error("[insertCutPoints()] Counting error");
    arcs.updateVertexData(nn1, xx1, yy1, null);
    return map;
  }

  function convertIntersectionsToCutPoints(intersections, xx, yy) {
    var points = [], ix, a, b;
    for (var i=0, n=intersections.length; i<n; i++) {
      ix = intersections[i];
      a = getCutPoint(ix.x, ix.y, ix.a[0], ix.a[1]);
      b = getCutPoint(ix.x, ix.y, ix.b[0], ix.b[1]);
      if (a) points.push(a);
      if (b) points.push(b);
    }
    return points;
  }

  // i, j: indexes of segment endpoints in xx, yy, or of a single endpoint
  //   if point x,y falls on an endpoint
  // Assumes: i <= j
  function getCutPoint(x, y, i, j, xx, yy) {
    if (j < i || j > i + 1) {
      error("Out-of-sequence arc ids:", i, j);
    }

    // Removed out-of-range check: small out-of-range intersection points are now allowed.
    // (Such points may occur due to fp rounding, when intersections occur along
    // vertical or horizontal segments)
    // if (geom.outsideRange(x, ix, jx) || geom.outsideRange(y, iy, jy)) {
      // return null;
    // }

    // Removed endpoint check: intersecting arcs need to be cut both at vertices
    // and between vertices, so pathfinding functions will work correctly.
    // if (x == ix && y == iy || x == jx && y == jy) {
      // return null;
    // }
    return {x: x, y: y, i: i};
  }

  // Sort insertion points in order of insertion
  // Insertion order: ascending id of first endpoint of containing segment and
  //   ascending distance from same endpoint.
  function sortCutPoints(points, xx, yy) {
    points.sort(function(a, b) {
      if (a.i != b.i) return a.i - b.i;
      return geom.distanceSq(xx[a.i], yy[a.i], a.x, a.y) - geom.distanceSq(xx[b.i], yy[b.i], b.x, b.y);
      // The old code below is no longer reliable, now that out-of-range intersection
      // points are allowed.
      // return Math.abs(a.x - xx[a.i]) - Math.abs(b.x - xx[b.i]) ||
      // Math.abs(a.y - yy[a.i]) - Math.abs(b.y - yy[b.i]);
    });
    return points;
  }

  // Removes duplicate points and arc endpoints
  function filterSortedCutPoints(points, arcs) {
    var filtered = [],
        pointId = 0;
    arcs.forEach2(function(i, n, xx, yy) {
      var j = i + n - 1,
          x0 = xx[i],
          y0 = yy[i],
          xn = xx[j],
          yn = yy[j],
          p, pp;

      while (pointId < points.length && points[pointId].i <= j) {
        p = points[pointId];
        pp = filtered[filtered.length - 1]; // previous point
        if (p.x == x0 && p.y == y0 || p.x == xn && p.y == yn) ; else if (pp && pp.x == p.x && pp.y == p.y && pp.i == p.i) ; else {
          filtered.push(p);
        }
        pointId++;
      }
    });
    return filtered;
  }

  function findClippingPoints(arcs, opts) {
    var intersections = findSegmentIntersections(arcs, opts),
        data = arcs.getVertexData();
    return convertIntersectionsToCutPoints(intersections, data.xx, data.yy);
  }

  var IntersectionCuts = /*#__PURE__*/Object.freeze({
    __proto__: null,
    addIntersectionCuts: addIntersectionCuts,
    divideArcs: divideArcs,
    cutPathsAtIntersections: cutPathsAtIntersections,
    remapDividedArcs: remapDividedArcs,
    insertCutPoints: insertCutPoints,
    getCutPoint: getCutPoint,
    sortCutPoints: sortCutPoints,
    filterSortedCutPoints: filterSortedCutPoints,
    findClippingPoints: findClippingPoints
  });

  // Support for timing using T.start() and T.stop()
  var T$1 = {
    stack: [],
    start: function() {
      T$1.stack.push(Date.now());
    },
    stop: function() {
      return (Date.now() - T$1.stack.pop()) + 'ms';
    }
  };

  // Create a mosaic layer from a dataset (useful for debugging commands like -clean
  //    that create a mosaic as an intermediate data structure)
  // Create additional layers if the "debug" flag is present
  //
  function mosaic(dataset, opts) {
    var layers2 = [];
    var nodes, output;
    if (!dataset.arcs) stop("Dataset is missing path data");
    nodes = addIntersectionCuts(dataset, opts);
    output = buildPolygonMosaic(nodes);
    layers2.push({
      name: 'mosaic',
      shapes: output.mosaic,
      geometry_type: 'polygon'
    });
    if (opts.debug) {
      layers2.push({
        geometry_type: 'polygon',
        name: 'mosaic-enclosure',
        shapes: output.enclosures
      });

      if (output.lostArcs.length > 0) {
        layers2 = layers2.concat(getLostArcLayers(output.lostArcs, nodes.arcs));
      }
    }
    return layers2;

    function getLostArcLayers(lostArcs, arcs) {
      var arcLyr = {geometry_type: 'polyline', name: 'lost-arcs', shapes: []};
      var pointLyr = {geometry_type: 'point', name: 'lost-arc-endpoints', shapes: []};
      var arcData = [];
      var pointData = [];
      lostArcs.forEach(function(arcId) {
        var first = arcs.getVertex(arcId, 0);
        var last = arcs.getVertex(arcId, -1);
        arcData.push({ARCID: arcId});
        arcLyr.shapes.push([[arcId]]);
        pointData.push({ARCID: arcId}, {ARCID: arcId});
        pointLyr.shapes.push([[first.x, first.y]], [[last.x, last.y]]);
      });
      arcLyr.data = new DataTable(arcData);
      pointLyr.data = new DataTable(pointData);
      return [arcLyr, pointLyr];
    }
  }

  // Process arc-node topology to generate a layer of indivisible mosaic "tiles" {mosaic}
  //   ... also return a layer of outer-boundary polygons {enclosures}
  //   ... also return an array of arcs that were dropped from the mosaic {lostArcs}
  //
  // Assumes that the arc-node topology of @nodes NodeCollection meets several
  //    conditions (expected to be true if addIntersectionCuts() has just been run)
  // 1. Arcs only touch at endpoints.
  // 2. The angle between any two segments that meet at a node is never zero.
  //      (this should follow from 1... but may occur due to FP errors)
  // TODO: a better job of handling FP errors
  //
  function buildPolygonMosaic(nodes) {
    T$1.start();
    // Detach any acyclic paths (spikes) from arc graph (these would interfere with
    //    the ring finding operation). This modifies @nodes -- a side effect.
    nodes.detachAcyclicArcs();
    var data = findMosaicRings(nodes);

    // Process CW rings: these are indivisible space-enclosing boundaries of mosaic tiles
    var mosaic = data.cw.map(function(ring) {return [ring];});
    debug('Find mosaic rings', T$1.stop());
    T$1.start();

    // Process CCW rings: these are either holes or enclosure
    // TODO: optimize -- testing CCW path of every island is costly
    var enclosures = [];
    var index = new PathIndex(mosaic, nodes.arcs); // index CW rings to help identify holes
    data.ccw.forEach(function(ring) {
      var id = index.findSmallestEnclosingPolygon(ring);
      if (id > -1) {
        // Enclosed CCW rings are holes in the enclosing mosaic tile
        mosaic[id].push(ring);
      } else {
        // Non-enclosed CCW rings are outer boundaries -- add to enclosures layer
        reversePath(ring);
        enclosures.push([ring]);
      }
    });
    debug(utils.format("Detect holes (holes: %d, enclosures: %d)", data.ccw.length - enclosures.length, enclosures.length), T$1.stop());

    return {mosaic: mosaic, enclosures: enclosures, lostArcs: data.lostArcs};
  }

  function findMosaicRings(nodes) {
    var arcs = nodes.arcs,
        cw = [],
        ccw = [],
        empty = [],
        lostArcs = [];

    var flags = new Uint8Array(arcs.size());
    var findPath = getPathFinder(nodes, useRoute);

    for (var i=0, n=flags.length; i<n; i++) {
      tryPath(i);
      // TODO: consider skipping detection of island ccw paths here (if possible)
      tryPath(~i);
    }
    return {
      cw: cw,
      ccw: ccw,
      empty: empty,
      lostArcs: lostArcs
    };

    function tryPath(arcId) {
      var ring, area;
      if (!routeIsOpen(arcId)) return;
      ring = findPath(arcId);
      if (!ring) {
        // arc is unused, but can not be extended to a complete ring
        lostArcs.push(arcId);
        debug("Dead-end arc:", arcId);
        return;
      }
      area = geom.getPlanarPathArea(ring, arcs);
      if (area > 0) {
        cw.push(ring);
      } else if (area < 0) {
        ccw.push(ring);
      } else {
        empty.push(ring);
      }
    }

    function useRoute(arcId) {
      return routeIsOpen(arcId, true);
    }

    function routeIsOpen(arcId, closeRoute) {
      var absId = absArcId(arcId);
      var bit = absId == arcId ? 1 : 2;
      var isOpen = (flags[absId] & bit) === 0;
      if (closeRoute && isOpen) flags[absId] |= bit;
      return isOpen;
    }
  }

  var PolygonMosaic = /*#__PURE__*/Object.freeze({
    __proto__: null,
    mosaic: mosaic,
    buildPolygonMosaic: buildPolygonMosaic
  });

  // Map positive or negative integer ids to non-negative integer ids
  function IdLookupIndex(n, clearable) {
    var fwdIndex = new Int32Array(n);
    var revIndex = new Int32Array(n);
    var index = this;
    var setList = [];
    utils.initializeArray(fwdIndex, -1);
    utils.initializeArray(revIndex, -1);

    this.setId = function(id, val) {
      if (clearable && !index.hasId(id)) {
        setList.push(id);
      }
      if (id < 0) {
        revIndex[~id] = val;
      } else {
        fwdIndex[id] = val;
      }
    };

    this.clear = function() {
      if (!clearable) {
        error('Index is not clearable');
      }
      setList.forEach(function(id) {
        index.setId(id, -1);
      });
      setList = [];
    };

    this.clearId = function(id) {
      if (!index.hasId(id)) {
        error('Tried to clear an unset id');
      }
      index.setId(id, -1);
    };

    this.hasId = function(id) {
      var val = index.getId(id);
      return val > -1;
    };

    this.getId = function(id) {
      var idx = id < 0 ? ~id : id;
      if (idx >= n) {
        return -1; // TODO: consider throwing an error?
      }
      return id < 0 ? revIndex[idx] : fwdIndex[idx];
    };
  }

  // Associate mosaic tiles with shapes (i.e. identify the groups of tiles that
  //   belong to each shape)
  //
  function PolygonTiler(mosaic, arcTileIndex, nodes, opts) {
    var arcs = nodes.arcs;
    var visitedTileIndex = new IdTestIndex(mosaic.length, true);
    var divide = getHoleDivider(nodes);
    // temp vars
    var currHoles; // arc ids of all holes in shape
    var currRingBbox;
    var tilesInShape; // accumulator for tile ids of tiles in current shape
    var ringIndex = new IdTestIndex(arcs.size(), true);
    var holeIndex = new IdTestIndex(arcs.size(), true);

    // return ids of tiles in shape
    this.getTilesInShape = function(shp, shapeId) {
      var cw = [], ccw = [], retn;
      tilesInShape = [];
      currHoles = [];
      if (opts.no_holes) {
        divide(shp, cw, ccw);
        // ccw.forEach(internal.reversePath);
        // cw = cw.concat(ccw);
      } else {
        // divide shape into rings and holes (splits self-intersecting rings)
        // TODO: rewrite divide() -- it is a performance bottleneck and can convert
        //   space-filling areas into ccw holes
        divide(shp, cw, ccw);
        ccw.forEach(procShapeHole);
        holeIndex.setIds(currHoles);
      }
      cw.forEach(procShapeRing);
      retn = tilesInShape;
      // reset tmp vars, etc
      tilesInShape = null;
      holeIndex.clear();
      currHoles = null;
      return retn;
    };

    function procShapeHole(path) {
      currHoles = currHoles ? currHoles.concat(path) : path;
    }

    function procShapeRing(path) {
      currRingBbox = arcs.getSimpleShapeBounds2(path);
      ringIndex.setIds(path);
      procArcIds(path);
      ringIndex.clear();
      // allow overlapping rings to visit the same tiles
      visitedTileIndex.clear();
    }

    // optimized version: traversal without recursion (to avoid call stack oflo, excessive gc, etc)
    function procArcIds(ids) {
      var stack = ids.concat();
      var arcId, tileId;
      while (stack.length > 0) {
        arcId = stack.pop();
        tileId = procRingArc(arcId);
        if (tileId >= 0) {
          accumulateTraversibleArcIds(stack, mosaic[tileId]);
        }
      }
    }

    function accumulateTraversibleArcIds(ids, tile) {
      var arcId, ring;
      for (var j=0, n=tile.length; j<n; j++) {
        ring = tile[j];
        for (var i=0, m=ring.length; i<m; i++) {
          arcId = ring[i];
          if (arcIsTraversible(arcId)) {
            ids.push(~arcId);
          }
        }
      }
    }

    function arcIsTraversible(tileArc) {
      var neighborArc = ~tileArc;
      var traversible = !(ringIndex.hasId(tileArc) || ringIndex.hasId(neighborArc) || holeIndex.hasId(tileArc) || holeIndex.hasId(neighborArc));
      return traversible;
    }

    function procRingArc(arcId) {
      var tileId = arcTileIndex.getShapeIdByArcId(arcId);
      if (tileId == -1 || visitedTileIndex.hasId(tileId)) return -1;
      if (arcs.arcIsContained(absArcId(arcId), currRingBbox) === false) {
        // don't cross boundary of the current ring or of any hole in the current shape
        // TODO: this indicates a geometry bug that should be fixed
        debug('Out-of-bounds ring arc', arcId);
        return -1;
      }
      visitedTileIndex.setId(tileId);
      tilesInShape.push(tileId);
      return tileId;
    }
  }

  var PolygonTiler$1 = /*#__PURE__*/Object.freeze({
    __proto__: null,
    PolygonTiler: PolygonTiler
  });

  function MosaicIndex(lyr, nodes, optsArg) {
    var opts = optsArg || {};
    var shapes = lyr.shapes;
    getHoleDivider(nodes);
    var mosaic = buildPolygonMosaic(nodes).mosaic;
    // map arc ids to tile ids
    var arcTileIndex = new ShapeArcIndex(mosaic, nodes.arcs);
    // keep track of which tiles have been assigned to shapes
    var fetchedTileIndex = new IdTestIndex(mosaic.length, true);
    // bidirection index of tile ids <=> shape ids
    var tileShapeIndex = new TileShapeIndex(mosaic, opts);
    // assign tiles to shapes
    var shapeTiler = new PolygonTiler(mosaic, arcTileIndex, nodes, opts);
    var weightFunction = null;
    if (!opts.simple && opts.flat) {
      // opts.simple is an optimization when dissolving everything into one polygon
      // using -dissolve2. In this situation, we don't need a weight function.
      // Otherwise, if polygons are being dissolved into multiple groups,
      // we use a function to assign tiles in overlapping areas to a single shape.
      weightFunction = getOverlapPriorityFunction(lyr.shapes, nodes.arcs, opts.overlap_rule);
    }
    this.mosaic = mosaic;
    this.nodes = nodes; // kludge
    this.getSourceIdsByTileId = tileShapeIndex.getShapeIdsByTileId; // expose for -mosaic command
    this.getTileIdsByShapeId = tileShapeIndex.getTileIdsByShapeId;

    // Assign shape ids to mosaic tile shapes.
    shapes.forEach(function(shp, shapeId) {
      var tileIds = shapeTiler.getTilesInShape(shp, shapeId);
      tileShapeIndex.indexTileIdsByShapeId(shapeId, tileIds, weightFunction);
    });

    // ensure each tile is assigned to only one shape
    if (opts.flat) {
      tileShapeIndex.flatten();
    }

    // fill gaps
    // (assumes that tiles have been allocated to shapes and mosaic has been flattened)
    this.removeGaps = function(filter) {
      if (!opts.flat) {
        error('MosaicIndex#removeGaps() should only be called with a flat mosaic');
      }
      var remainingIds = tileShapeIndex.getUnusedTileIds();
      var filledIds = remainingIds.filter(function(tileId) {
        var tile = mosaic[tileId];
        return filter(tile[0]); // test tile ring, ignoring any holes (does this matter?)
      });
      filledIds.forEach(assignTileToAdjacentShape);
      return {
        removed: filledIds.length,
        remaining: remainingIds.length - filledIds.length
      };
    };

    this.getUnusedTiles = function() {
      return tileShapeIndex.getUnusedTileIds().map(tileIdToTile);
    };

    this.getTilesByShapeIds = function(shapeIds) {
      return getTileIdsByShapeIds(shapeIds).map(tileIdToTile);
    };

    function getOverlapPriorityFunction(shapes, arcs, rule) {
      var f;
      if (!rule || rule == 'max-area') {
        f = getAreaWeightFunction(shapes, arcs, false);
      } else if (rule == 'min-area') {
        f = getAreaWeightFunction(shapes, arcs, true);
      } else if (rule == 'max-id') {
        f = function(shapeId) {
          return shapeId; };
      } else if (rule == 'min-id') {
        f = function(shapeId) { return -shapeId; };
      } else {
        stop('Unknown overlap rule:', rule);
      }
      return f;
    }

    function getAreaWeightFunction(shapes, arcs, invert) {
      var index = [];
      var sign = invert ? -1 : 1;
      return function(shpId) {
        var weight;
        if (shpId in index) {
          weight = index[shpId];
        } else {
          weight = sign * Math.abs(geom.getShapeArea(shapes[shpId], arcs));
          index[shpId] = weight;
        }
        return weight;
      };
    }

    function tileIdToTile(id, i) {
      return mosaic[id];
    }

    function assignTileToAdjacentShape(tileId) {
      var ring = mosaic[tileId][0];
      var arcs = nodes.arcs;
      var arcId, neighborShapeId, neighborTileId, arcLen;
      var shapeId = -1, maxArcLen = 0;
      for (var i=0; i<ring.length; i++) {
        arcId = ring[i];
        neighborTileId = arcTileIndex.getShapeIdByArcId(~arcId);
        if (neighborTileId < 0) continue;
        neighborShapeId = tileShapeIndex.getShapeIdByTileId(neighborTileId);
        if (neighborShapeId < 0) continue;
        arcLen = geom.getPathPerimeter([arcId], arcs);
        if (arcLen > maxArcLen) {
          shapeId = neighborShapeId;
          maxArcLen = arcLen;
        }
      }
      if (shapeId > -1) {
        tileShapeIndex.addTileToShape(shapeId, tileId);
      }
    }

    function getTileIdsByShapeIds(shapeIds) {
      var uniqIds = [];
      var tileId, tileIds, i, j;
      for (i=0; i<shapeIds.length; i++) {
        tileIds = tileShapeIndex.getTileIdsByShapeId(shapeIds[i]);
        for (j=0; j<tileIds.length; j++) {
          tileId = tileIds[j];
          // uniqify tile ids (in case the shape contains overlapping rings)
          if (fetchedTileIndex.hasId(tileId)) continue;
          fetchedTileIndex.setId(tileId);
          uniqIds.push(tileId);
        }
      }
      // clearing this index allows duplicate tile ids between calls to this function
      // (should not happen in a typical dissolve)
      fetchedTileIndex.clear();
      return uniqIds;
    }
  }

  // Map arc ids to shape ids, assuming perfect topology
  // (an arcId maps to at most one shape)
  // Supports looking up a shape id using an arc id.
  function ShapeArcIndex(shapes, arcs) {
    var n = arcs.size();
    var index = new IdLookupIndex(n);
    var shapeId;
    shapes.forEach(onShape);

    function onShape(shp, i) {
      shapeId = i;
      shp.forEach(onPart);
    }
    function onPart(path) {
      var arcId;
      for (var i=0, n=path.length; i<n; i++) {
        arcId = path[i];
        index.setId(arcId, shapeId);
      }
    }

    // returns -1 if shape has not been indexed
    this.getShapeIdByArcId = function(arcId) {
      return index.getId(arcId);
    };
  }

  var MosaicIndex$1 = /*#__PURE__*/Object.freeze({
    __proto__: null,
    MosaicIndex: MosaicIndex,
    ShapeArcIndex: ShapeArcIndex
  });

  // Assumes that arcs do not intersect except at endpoints
  function dissolvePolygonLayer2(lyr, dataset, opts) {
    opts = utils.extend({}, opts);
    if (opts.field) {
      opts.fields = [opts.field]; // support old "field" parameter
    }
    var getGroupId = getCategoryClassifier(opts.fields, lyr.data);
    var groups = groupPolygons2(lyr, getGroupId);
    var shapes2 = dissolvePolygonGroups2(groups, lyr, dataset, opts);
    return composeDissolveLayer(lyr, shapes2, getGroupId, opts);
  }

  function composeMosaicLayer(lyr, shapes2) {
    var records = shapes2.map(function(shp, i) {
      return {tile_id: i};
    });
    return utils.defaults({
      shapes: shapes2,
      data: new DataTable(records)
    }, lyr);
  }

  function groupPolygons2(lyr, getGroupId) {
    return lyr.shapes.reduce(function(groups, shape, shapeId) {
      var groupId = getGroupId(shapeId);
      if (groupId in groups === false) {
        groups[groupId] = [];
      }
      groups[groupId].push(shapeId);
      return groups;
    }, []);
  }

  function getGapRemovalMessage(removed, retained, areaLabel) {
    if (removed > 0 === false) return '';
    return utils.format('Removed %,d / %,d sliver%s using %s',
        removed, removed + retained, utils.pluralSuffix(removed), areaLabel);
  }

  function dissolvePolygonGroups2(groups, lyr, dataset, opts) {
    var arcFilter = getArcPresenceTest(lyr.shapes, dataset.arcs);
    var nodes = new NodeCollection(dataset.arcs, arcFilter);
    var mosaicOpts = {
      flat: !opts.allow_overlaps,
      simple: groups.length == 1,
      overlap_rule: opts.overlap_rule
    };
    var mosaicIndex = new MosaicIndex(lyr, nodes, mosaicOpts);
    var fillGaps = !opts.allow_overlaps; // gap fill doesn't work yet with overlapping shapes
    var cleanupData, filterData;
    if (fillGaps) {
      var sliverOpts = utils.extend({sliver_control: 1}, opts);
      filterData = getSliverFilter(lyr, dataset, sliverOpts);
      cleanupData = mosaicIndex.removeGaps(filterData.filter);
    }
    var pathfind = getRingIntersector(mosaicIndex.nodes);
    var dissolvedShapes = groups.map(function(shapeIds) {
      var tiles = mosaicIndex.getTilesByShapeIds(shapeIds);
      if (opts.tiles) {
        return tiles.reduce(function(memo, tile) {
          return memo.concat(tile);
        }, []);
      }
      return dissolveTileGroup2(tiles, pathfind);
    });
    // convert self-intersecting rings to outer/inner rings, for OGC
    // Simple Features compliance
    dissolvedShapes = fixTangentHoles(dissolvedShapes, pathfind);

    if (fillGaps && !opts.quiet) {
      var msg = getGapRemovalMessage(cleanupData.removed, cleanupData.remaining, filterData.label);
      if (msg) message(msg);
    }
    return dissolvedShapes;
  }

  function dissolveTileGroup2(tiles, pathfind) {
    var rings = [],
        holes = [],
        dissolved, tile;
    for (var i=0, n=tiles.length; i<n; i++) {
      tile = tiles[i];
      rings.push(tile[0]);
      if (tile.length > 1) {
        holes = holes.concat(tile.slice(1));
      }
    }
    dissolved = pathfind(rings.concat(holes), 'dissolve');
    if (dissolved.length > 1) ;
    return dissolved.length > 0 ? dissolved : null;
  }

  function fixTangentHoles(shapes, pathfind) {
    var onRing = function(memo, ring) {
      reversePath(ring);
      var fixed = pathfind([ring], 'flatten');
      if (fixed.length > 1) {
        fixed.forEach(reversePath);
        memo = memo.concat(fixed);
      } else {
        memo.push(reversePath(ring));
      }
      return memo;
    };
    return shapes.map(function(rings) {
      if (!rings) return null;
      return rings.reduce(onRing, []);
    });
  }

  var PolygonDissolve2 = /*#__PURE__*/Object.freeze({
    __proto__: null,
    dissolvePolygonLayer2: dissolvePolygonLayer2,
    composeMosaicLayer: composeMosaicLayer,
    dissolvePolygonGroups2: dissolvePolygonGroups2
  });

  // Assumes intersection cuts have been added and duplicated points removed
  // TODO: consider closing undershoots (see mapshaper-undershoots.js)
  function cleanPolylineLayerGeometry(lyr, dataset, opts) {
    var arcs = dataset.arcs;
    var filter = getArcPresenceTest(lyr.shapes, arcs);
    var nodes = new NodeCollection(arcs, filter);
    var arcIndex = new IdLookupIndex(arcs.size(), true);
    lyr.shapes = lyr.shapes.map(function(shp, i) {
      if (!shp) return null;
      // split parts at nodes (where multiple arcs intersect)
      shp = divideShapeAtNodes(shp, nodes);

      // remove multiple references to the same arc within the same part
      // (this could happen if the path doubles back to form a spike)
      // TODO: remove spikes within a single arc
      arcIndex.clear();
      shp = uniqifyArcs(shp, arcIndex);

      // try to combine parts that form a contiguous line
      // (some datasets may use a separate part for each segment)
      arcIndex.clear();
      shp = combineContiguousParts(shp, nodes, arcIndex);
      return shp;
    });
  }

  function uniqifyArcs(shp, index) {
    var shp2 = shp.reduce(function(memo, ids) {
      addUnusedArcs(memo, ids, index);
      return memo;
    }, []);
    return shp2.length > 0 ? shp2 : null;
  }

  function addUnusedArcs(shp, ids, index) {
    var part = [], arcId;
    for (var i=0; i<ids.length; i++) {
      arcId = ids[i];
      if (!index.hasId(arcId)) {
        part.push(arcId);
      } else if (part.length > 0) {
        shp.push(part);
        part = [];
      }
      index.setId(arcId, i);
      index.setId(~arcId, i);
    }
    if (part.length > 0) shp.push(part);
  }


  function divideShapeAtNodes(shp, nodes) {
    var shp2 = [];
    forEachShapePart(shp, onPart);
    return shp2;

    function onPart(ids) {
      var n = ids.length;
      var id;
      var ids2 = [];
      for (var i=0; i<n; i++) {
        // check each segment of the current part (equivalent to a LineString)
        id = ids[i];
        ids2.push(id);
        if (i < n-1 && nodes.getConnectedArcs(id).length > 1) {
          // divide the current part if the front endpoint of the current segment
          // touches any other segment than the next segment in this part
          // TODO: consider not dividing if the intersection does not involve
          // the current feature (ie. it is not a self-intersection).
          shp2.push(ids2);
          ids2 = [];
        }
      }
      if (ids2.length > 0) shp2.push(ids2);
    }
  }

  function combineContiguousParts(parts, nodes, endpointIndex) {
    if (!parts || parts.length < 2) return parts;

    // Index the terminal arcs of this group of polyline parts
    parts.forEach(function(ids, i) {
      var tailId = ~ids[0]; // index the reversed arc (so it points outwards)
      var headId = ids[ids.length - 1];
      // edge case: an endpoint arc is shared by multiple parts
      // only processing the first of such parts, skipping subsequent parts
      // (this should be an exceptional case... should probably investigate
      // why this happens and handle this better)
      if (endpointIndex.hasId(tailId) || endpointIndex.hasId(headId)) {
        error('Indexing error');
      }
      endpointIndex.setId(tailId, i);
      endpointIndex.setId(headId, i);
      procEndpoint(tailId, i);
      procEndpoint(headId, i);
    });

    return parts.filter(function(ids) { return !!ids; });

    function procEndpoint(endpointId, sourcePartId) {
      var joins = 0;
      var partId2 = -1;
      var endpointId2;
      var indexedPartId = endpointIndex.getId(endpointId);
      nodes.forEachConnectedArc(endpointId, function(arcId) {
        if (endpointIndex.hasId(arcId)) {
          partId2 = endpointIndex.getId(arcId);
          endpointId2 = arcId;
        }
        joins++;
      });
      if (joins == 1 && partId2 > -1 && partId2 < sourcePartId) {
        extendPolylinePart(parts, partId2, endpointId2, indexedPartId, endpointId);
        // update indexed part id of joining endpoint
        endpointIndex.setId(endpointId, partId2);
        // update indexed part id of other endpoint
        var ids = parts[indexedPartId];
        var otherEndpointId = getOtherEndpointId(ids, endpointId);
        endpointIndex.setId(otherEndpointId, partId2);
        if (indexedPartId != partId2) {
          parts[indexedPartId] = null;
        }
      }
    }
  }

  function getOtherEndpointId(ids, endpointId) {
    var headId = ~ids[0];
    var tailId = ids[ids.length-1];
    if (endpointId == headId) return tailId;
    else if (endpointId == tailId) return headId;
    error('Indexing error');
  }

  function extendPolylinePart(parts, partId1, endpoint1, partId2, endpoint2) {
    var ids1 = parts[partId1];
    var ids2 = parts[partId2];
    var joinToTail, joinFromTail;
    if (~endpoint1 == ids1[0]) {
      joinToTail = true;
    } else if (endpoint1 == ids1[ids1.length-1]) {
      joinToTail = false;
    } else {
      error('Index error');
    }
    if (~endpoint2 == ids2[0]) {
      joinFromTail = true;
    } else if (endpoint2 == ids2[ids2.length-1]) {
      joinFromTail = false;
    } else {
      error('Index error 2');
    }
    if (!joinFromTail) {
      ids2 = reversePath(ids2.concat());
    }
    if (joinToTail) {
      prependPath(ids1, ids2);
    } else {
      appendPath(ids1, ids2);
    }
  }

  function prependPath(target, source) {
    source = reversePath(source.concat());
    var args = [0, 0].concat(source);
    target.splice.apply(target, args);
  }

  function appendPath(target, source) {
    target.push.apply(target, source);
  }

  cmd.cleanLayers = cleanLayers;

  function cleanLayers(layers, dataset, optsArg) {
    var opts = optsArg || {};
    var deepClean = !opts.only_arcs;
    var pathClean = utils.some(layers, layerHasPaths);
    var nodes;
    if (opts.debug) {
      addIntersectionCuts(dataset, opts);
      return;
    }
    layers.forEach(function(lyr) {
      if (!layerHasGeometry(lyr)) return;
      if (lyr.geometry_type == 'polygon' && opts.rewind) {
        rewindPolygons(lyr, dataset.arcs);
      }
      if (deepClean) {
        if (!nodes) {
          nodes = addIntersectionCuts(dataset, opts);
        }
        if (lyr.geometry_type == 'polygon') {
          cleanPolygonLayerGeometry(lyr, dataset, opts);
        } else if (lyr.geometry_type == 'polyline') {
          cleanPolylineLayerGeometry(lyr, dataset);
        } else if (lyr.geometry_type == 'point') {
          cleanPointLayerGeometry(lyr);
        }
      }
      if (!opts.allow_empty) {
        cmd.filterFeatures(lyr, dataset.arcs, {remove_empty: true, verbose: opts.verbose});
      }
    });

    if (!opts.no_arc_dissolve && pathClean && dataset.arcs) {
      // remove leftover endpoints within contiguous lines
      dissolveArcs(dataset);
    }
  }

  function cleanPolygonLayerGeometry(lyr, dataset, opts) {
    // clean polygons by apply the 'dissolve2' function to each feature
    var groups = lyr.shapes.map(function(shp, i) {
      return [i];
    });
    lyr.shapes = dissolvePolygonGroups2(groups, lyr, dataset, opts);
  }

  // Remove duplicate points from multipoint geometries
  // TODO: consider checking for invalid coordinates
  function cleanPointLayerGeometry(lyr, dataset, opts) {
    var index, parts;
    lyr.shapes = lyr.shapes.map(function(shp, i) {
      if (!shp || shp.length > 0 === false) {
        return null;
      }
      if (shp.length == 1) {
        return shp; // single part
      }
      // remove duplicate points from multipoint geometry
      index = {};
      parts = [];
      shp.forEach(onPoint);
      if (parts.length === 0) {
        return null;
      }
      return parts;
    });

    function onPoint(p) {
      var key = p.join('~');
      if (key in index) return;
      index[key] = true;
      parts.push(p);
    }
  }

  // Support the opts.flatten option (for removing polygon overlaps)
  cmd.mergeAndFlattenLayers = function(layers, dataset, opts) {
    if (!opts.flatten) return cmd.mergeLayers(layers, opts);
    layers.forEach(function(lyr) {
      requirePolygonLayer(lyr, 'the flatten option requires polygon layers');
    });
    var output = cmd.mergeLayers(layers, opts);
    replaceLayers(dataset, layers, output);
    cleanLayers(output, dataset, {
      overlap_rule: 'max-id' // later shapes get inlaid in earlier shapes
    });
    replaceLayers(dataset, output, layers);
    return output;
  };

  // Merge layers, checking for incompatible geometries and data fields.
  // Assumes that input layers are members of the same dataset (and therefore
  // share the same ArcCollection, if layers have paths).
  cmd.mergeLayers = function(layersArg, opts) {
    var layers = layersArg.filter(getFeatureCount); // ignore empty layers
    var merged = {};
    opts = opts || {};
    if (!layers.length) return null;
    if (layers.length == 1) {
      message('Use the target= option to specify multiple layers for merging');
      return layers.concat();
    }
    merged.data = mergeDataFromLayers(layers, opts);
    merged.name = mergeLayerNames(layers);
    merged.geometry_type = getMergedLayersGeometryType(layers);
    if (merged.geometry_type) {
      merged.shapes = mergeShapesFromLayers(layers);
    }
    if (merged.shapes && merged.data && merged.shapes.length != merged.data.size()) {
      error("Mismatch between geometry and attribute data");
    }
    return [merged];
  };

  function getMergedLayersGeometryType(layers) {
    var geoTypes = utils.uniq(utils.pluck(layers, 'geometry_type'))
      .filter(function(type) {return !!type;}); // ignore null-type layers
    if (geoTypes.length > 1) {
      stop("Incompatible geometry types:", geoTypes.join(', '));
    }
    return geoTypes[0] || null;
  }

  function mergeShapesFromLayers(layers) {
    return layers.reduce(function(memo, lyr) {
      var shapes = lyr.shapes || [];
      var n = getFeatureCount(lyr);
      var i = -1;
      while (++i < n) memo.push(shapes[i] || null); // add null shapes if layer has no shapes
      return memo;
    }, []);
  }

  function mergeDataFromLayers(layers, opts) {
    var allFields = utils.uniq(layers.reduce(function(memo, lyr) {
      return memo.concat(lyr.data ? lyr.data.getFields() : []);
    }, []));
    if (allFields.length === 0) return null; // no data in any fields
    var mergedRecords = layers.reduce(function(memo, lyr) {
      var records = lyr.data ? lyr.data.getRecords() : new DataTable(getFeatureCount(lyr)).getRecords();
      return memo.concat(records);
    }, []);
    var missingFields = findInconsistentFields(allFields, layers);
    handleMissingFields(missingFields, opts);
    checkInconsistentFieldTypes(allFields, layers);
    if (missingFields.length > 0) {
      fixInconsistentFields(mergedRecords);
    }
    return new DataTable(mergedRecords);
  }

  // handle fields that are missing from one or more layers
  // (warn if force-merging, else error)
  function handleMissingFields(missingFields, opts) {
    var msg;
    if (missingFields.length > 0) {
      msg = '[' + missingFields.join(', ') + ']';
      msg = (missingFields.length == 1 ? 'Field ' + msg + ' is missing' : 'Fields ' + msg + ' are missing') + ' from one or more layers';
      if (!opts.force) {
        stop(msg);
      } else if (opts.verbose !== false) {
        message('Warning: ' + msg);
      }
    }
  }

  function findInconsistentFields(allFields, layers) {
    var missingFields = utils.uniq(layers.reduce(function(memo, lyr) {
      return memo.concat(utils.difference(allFields, lyr.data ? lyr.data.getFields() : []));
    }, []));
    return missingFields;
  }

  // check for fields with incompatible data types (e.g. number, string)
  function checkInconsistentFieldTypes(fields, layers) {
    fields.forEach(function(key) {
      var types = findFieldTypes(key, layers);
      if (types.length > 1) {
        stop("Inconsistent data types in \"" + key + "\" field:", types.join(', '));
      }
    });
  }

  function findFieldTypes(key, layers) {
    // ignores empty-type fields
    return layers.reduce(function(memo, lyr) {
      var type = lyr.data ? getColumnType(key, lyr.data.getRecords()) : null;
      if (type && memo.indexOf(type) == -1) {
        memo.push(type);
      }
      return memo;
    }, []);
  }

  function mergeLayerNames(layers) {
    return layers.reduce(function(memo, lyr) {
      if (memo === null) {
        memo = lyr.name || null;
      } else if (memo && lyr.name) {
        memo = utils.mergeNames(memo, lyr.name);
      }
      return memo;
    }, null) || '';
  }

  var GeoJSON = {};

  GeoJSON.ID_FIELD = "FID"; // default field name of imported *JSON feature ids

  GeoJSON.typeLookup = {
    LineString: 'polyline',
    MultiLineString: 'polyline',
    Polygon: 'polygon',
    MultiPolygon: 'polygon',
    Point: 'point',
    MultiPoint: 'point'
  };

  GeoJSON.translateGeoJSONType = function(type) {
    return GeoJSON.typeLookup[type] || null;
  };

  GeoJSON.pathIsRing = function(coords) {
    var first = coords[0],
        last = coords[coords.length - 1];
    // TODO: consider detecting collapsed rings
    return coords.length >= 4 && first[0] == last[0] && first[1] == last[1];
  };

  GeoJSON.toFeature = function(obj, properties) {
    var type = obj ? obj.type : null;
    var feat;
    if (type == 'Feature') {
      feat = obj;
    } else if (type in GeoJSON.typeLookup) {
      feat = {
        type: 'Feature',
        geometry: obj,
        properties: properties || null
      };
    } else {
      feat = {
        type: 'Feature',
        geometry: null,
        properties: properties || null
      };
    }
    return feat;
  };

  // switch to RFC 7946-compatible output (while retaining the original export function,
  // so numerous tests will continue to work)
  function exportGeoJSON2(dataset, opts) {
    opts = utils.extend({}, opts);
    opts.v2 = !opts.gj2008; // use RFC 7946 as the default
    return exportGeoJSON(dataset, opts);
  }

  function exportGeoJSON(dataset, opts) {
    opts = opts || {};
    var extension = opts.extension || "json";
    var layerGroups, warn;

    // Apply coordinate precision
    // rfc7946 flag is deprecated (default output is now RFC 7946 compatible)
    // the flag is used here to preserve backwards compatibility
    // (the rfc7946 flag applies a default precision threshold, even though rounding
    // coordinates is only a recommendation, not a requirement of RFC 7946)
    if (opts.precision || opts.rfc7946) {
      dataset = copyDatasetForExport(dataset);
      setCoordinatePrecision(dataset, opts.precision || 0.000001);
    }

    if (opts.v2 || opts.rfc7946) {
      warn = getRFC7946Warnings(dataset);
      if (warn) message(warn);
    }

    if (opts.file) {
      // Override default output extension if output filename is given
      extension = getFileExtension(opts.file);
    }
    if (opts.combine_layers) {
      layerGroups = [dataset.layers];
    } else {
      layerGroups = dataset.layers.map(function(lyr) {
        return [lyr];
      });
    }
    return layerGroups.map(function(layers) {
      // Use common part of layer names if multiple layers are being merged
      var name = mergeLayerNames(layers) || 'output';
      var d = utils.defaults({layers: layers}, dataset);
      return {
        content: exportDatasetAsGeoJSON(d, opts, 'geojson'),
        filename: name + '.' + extension
      };
    });
  }

  // Return an array of Features or Geometries as objects or strings
  //
  function exportLayerAsGeoJSON(lyr, dataset, opts, asFeatures, ofmt) {
    var properties = exportProperties(lyr.data, opts),
        shapes = lyr.shapes,
        ids = exportIds(lyr.data, opts),
        stringify;

    if (opts.ndjson) {
      stringify = stringifyAsNDJSON;
    } else if (opts.prettify) {
      stringify = getFormattedStringify(['bbox', 'coordinates']);
    } else {
      stringify = JSON.stringify;
    }

    if (properties && shapes && properties.length !== shapes.length) {
      error("Mismatch between number of properties and number of shapes");
    }

    return (shapes || properties || []).reduce(function(memo, o, i) {
      var shape = shapes ? shapes[i] : null,
          exporter = GeoJSON.exporters[lyr.geometry_type],
          geom = shape ? exporter(shape, dataset.arcs, opts) : null,
          obj = null;
      if (asFeatures) {
        obj = GeoJSON.toFeature(geom, properties ? properties[i] : null);
        if (ids) {
          obj.id = ids[i];
        }
      } else if (!geom) {
        return memo; // don't add null objects to GeometryCollection
      } else {
        obj = geom;
      }
      if (ofmt) {
        // stringify features as soon as they are generated, to reduce the
        // number of JS objects in memory (so larger files can be exported)
        obj = stringify(obj);
        if (ofmt == 'buffer') {
          obj = encodeString(obj, 'utf8');
          // obj = stringToBuffer(obj);
          // obj = new Buffer(obj, 'utf8');
        }
      }
      memo.push(obj);
      return memo;
    }, []);
  }


  function getRFC7946Warnings(dataset) {
    var P = getDatasetCRS(dataset);
    var str;
    if (!P || !isLatLngCRS(P)) {
      str = 'RFC 7946 warning: non-WGS84 GeoJSON output.';
      if (P) str += ' Tip: use "-proj wgs84" to convert.';
    }
    return str;
  }

  function getDatasetBbox(dataset, rfc7946) {
    var P = getDatasetCRS(dataset),
        wrapped = rfc7946 && P && isLatLngCRS(P),
        westBounds = new Bounds(),
        eastBounds = new Bounds(),
        mergedBounds, gutter, margins, bbox;

    dataset.layers.forEach(function(lyr) {
      if (layerHasPaths(lyr)) {
        traversePaths(lyr.shapes, null, function(o) {
          var bounds = dataset.arcs.getSimpleShapeBounds(o.arcs);
          (bounds.centerX() < 0 ? westBounds : eastBounds).mergeBounds(bounds);
        });
      } else if (layerHasPoints(lyr)) {
        forEachPoint(lyr.shapes, function(p) {
          (p[0] < 0 ? westBounds : eastBounds).mergePoint(p[0], p[1]);
        });
      }
    });
    mergedBounds = (new Bounds()).mergeBounds(eastBounds).mergeBounds(westBounds);
    if (mergedBounds.hasBounds()) {
      bbox = mergedBounds.toArray();
    }
    if (wrapped && eastBounds.hasBounds() && westBounds.hasBounds()) {
      gutter = eastBounds.xmin - westBounds.xmax;
      margins = 360 + westBounds.xmin - eastBounds.xmax;
      if (gutter > 0 && gutter > margins) {
        bbox[0] = eastBounds.xmin;
        bbox[2] = westBounds.xmax;
      }
    }
    return bbox || null;
  }

  function exportDatasetAsGeoJSON(dataset, opts, ofmt) {
    var geojson = {};
    var layers = dataset.layers;
    var useFeatures = useFeatureCollection(layers, opts);
    var collection, bbox;

    if (useFeatures) {
      geojson.type = 'FeatureCollection';
    } else {
      geojson.type = 'GeometryCollection';
    }

    if (opts.gj2008) {
      preserveOriginalCRS(dataset, geojson);
    }

    if (opts.bbox) {
      bbox = getDatasetBbox(dataset, opts.rfc7946 || opts.v2);
      if (bbox) {
        geojson.bbox = bbox;
      }
    }

    collection = layers.reduce(function(memo, lyr, i) {
      var items = exportLayerAsGeoJSON(lyr, dataset, opts, useFeatures, ofmt);
      return memo.length > 0 ? memo.concat(items) : items;
    }, []);

    if (opts.geojson_type == 'Feature' && collection.length == 1) {
      return collection[0];
    } else if (opts.ndjson) {
      return GeoJSON.formatCollectionAsNDJSON(collection);
    } else if (ofmt) {
      return GeoJSON.formatCollection(geojson, collection);
    } else {
      geojson[collectionName(geojson.type)] = collection;
      return geojson;
    }
  }

  function collectionName(type) {
    if (type == 'FeatureCollection') return 'features';
    if (type == 'GeometryCollection') return 'geometries';
    error('Invalid collection type:', type);
  }

  // collection: an array of Buffers, one per feature
  GeoJSON.formatCollectionAsNDJSON = function(collection) {
    var delim = utils.createBuffer('\n', 'utf8');
    var parts = collection.reduce(function(memo, buf, i) {
      if (i > 0) memo.push(delim);
      memo.push(buf);
      return memo;
    }, []);
    return B$3.concat(parts);
  };

  // collection: an array of individual GeoJSON Features or geometries as strings or buffers
  GeoJSON.formatCollection = function(container, collection) {
    var head = JSON.stringify(container).replace(/\}$/, ', "' + collectionName(container.type) + '": [\n');
    var tail = '\n]}';
    if (utils.isString(collection[0])) {
      return head + collection.join(',\n') + tail;
    }
    // assume buffers
    return GeoJSON.joinOutputBuffers(head, tail, collection);
  };

  GeoJSON.joinOutputBuffers = function(head, tail, collection) {
    var comma = utils.createBuffer(',\n', 'utf8');
    var parts = collection.reduce(function(memo, buf, i) {
      if (i > 0) memo.push(comma);
      memo.push(buf);
      return memo;
    }, [utils.createBuffer(head, 'utf8')]);
    parts.push(utils.createBuffer(tail, 'utf8'));
    return B$3.concat(parts);
  };

  // export GeoJSON or TopoJSON point geometry
  GeoJSON.exportPointGeom = function(points, arcs) {
    var geom = null;
    if (points.length == 1) {
      geom = {
        type: "Point",
        coordinates: points[0]
      };
    } else if (points.length > 1) {
      geom = {
        type: "MultiPoint",
        coordinates: points
      };
    }
    return geom;
  };

  GeoJSON.exportLineGeom = function(ids, arcs) {
    var obj = exportPathData(ids, arcs, "polyline");
    if (obj.pointCount === 0) return null;
    var coords = obj.pathData.map(function(path) {
      return path.points;
    });
    return coords.length == 1 ? {
      type: "LineString",
      coordinates: coords[0]
    } : {
      type: "MultiLineString",
      coordinates: coords
    };
  };

  GeoJSON.exportPolygonGeom = function(ids, arcs, opts) {
    var obj = exportPathData(ids, arcs, "polygon");
    if (obj.pointCount === 0) return null;
    var groups = groupPolygonRings(obj.pathData, arcs, opts.invert_y);
    // invert_y is used internally for SVG generation
    // mapshaper's internal winding order is the opposite of RFC 7946
    var reverse = (opts.rfc7946 || opts.v2) && !opts.invert_y;
    var coords = groups.map(function(paths) {
      return paths.map(function(path) {
        if (reverse) path.points.reverse();
        return path.points;
      });
    });
    return coords.length == 1 ? {
      type: "Polygon",
      coordinates: coords[0]
    } : {
      type: "MultiPolygon",
      coordinates: coords
    };
  };

  GeoJSON.exporters = {
    polygon: GeoJSON.exportPolygonGeom,
    polyline: GeoJSON.exportLineGeom,
    point: GeoJSON.exportPointGeom
  };

  // To preserve some backwards compatibility with old-style GeoJSON files,
  // pass through any original CRS object if the crs has not been set by mapshaper
  // jsonObj: a top-level GeoJSON or TopoJSON object
  //
  function preserveOriginalCRS(dataset, jsonObj) {
    var info = dataset.info || {};
    if (!info.crs && 'input_geojson_crs' in info) {
      // use input geojson crs if available and coords have not changed
      jsonObj.crs = info.input_geojson_crs;

    }

    // Removing the following (seems ineffectual at best)
    // else if (info.crs && !isLatLngCRS(info.crs)) {
    //   // Setting output crs to null if coords have been projected
    //   // "If the value of CRS is null, no CRS can be assumed"
    //   // source: http://geojson.org/geojson-spec.html#coordinate-reference-system-objects
    //   jsonObj.crs = null;
    // }
  }

  function useFeatureCollection(layers, opts) {
    var type = opts.geojson_type || '';
    if (type == 'Feature' || type == 'FeatureCollection') {
      return true;
    } else if (type == 'GeometryCollection') {
      return false;
    } else if (type) {
      stop("Unsupported GeoJSON type:", opts.geojson_type);
    }
    // default is true iff layers contain attributes
    return utils.some(layers, function(lyr) {
      var fields = lyr.data ? lyr.data.getFields() : [];
      var haveData = useFeatureProperties(fields, opts);
      var haveId = !!getIdField(fields, opts);
      return haveData || haveId;
    });
  }

  function useFeatureProperties(fields, opts) {
    return !(opts.drop_table || opts.cut_table || fields.length === 0 ||
        fields.length == 1 && fields[0] == GeoJSON.ID_FIELD);
  }

  function exportProperties(table, opts) {
    var fields = table ? table.getFields() : [],
        idField = getIdField(fields, opts),
        properties, records;
    if (!useFeatureProperties(fields, opts)) {
      return null;
    }
    records = table.getRecords();
    if (idField == GeoJSON.ID_FIELD) {// delete default id field, not user-set fields
      properties = records.map(function(rec) {
        rec = utils.extend({}, rec); // copy rec;
        delete rec[idField];
        return rec;
      });
    } else {
      properties = records;
    }
    return properties;
  }

  // @opt value of id-field option (empty, string or array of strings)
  // @fields array
  function getIdField(fields, opts) {
    var ids = [];
    var opt = opts.id_field;
    if (utils.isString(opt)) {
      ids.push(opt);
    } else if (utils.isArray(opt)) {
      ids = opt;
    }
    ids.push(GeoJSON.ID_FIELD); // default id field
    return utils.find(ids, function(name) {
      return utils.contains(fields, name);
    });
  }

  function exportIds(table, opts) {
    var fields = table ? table.getFields() : [],
        idField = getIdField(fields, opts);
    if (!idField) return null;
    return table.getRecords().map(function(rec) {
      return idField in rec ? rec[idField] : null;
    });
  }

  var GeojsonExport = /*#__PURE__*/Object.freeze({
    __proto__: null,
    'default': GeoJSON,
    exportGeoJSON2: exportGeoJSON2,
    exportGeoJSON: exportGeoJSON,
    exportLayerAsGeoJSON: exportLayerAsGeoJSON,
    getRFC7946Warnings: getRFC7946Warnings,
    getDatasetBbox: getDatasetBbox,
    exportDatasetAsGeoJSON: exportDatasetAsGeoJSON,
    preserveOriginalCRS: preserveOriginalCRS,
    useFeatureCollection: useFeatureCollection,
    exportProperties: exportProperties,
    getIdField: getIdField,
    exportIds: exportIds
  });

  var furnitureRenderers = {};

  // @lyr a layer in a dataset
  function layerHasFurniture(lyr) {
    var type = getFurnitureLayerType(lyr);
    return !!type && (type in furnitureRenderers);
  }

  // @mapLayer a map layer object
  function isFurnitureLayer(mapLayer) {
    return !!mapLayer.furniture;
  }

  // @lyr dataset layer
  function getFurnitureLayerType(lyr) {
    var rec = lyr.data && lyr.data.getReadOnlyRecordAt(0);
    return rec && rec.type || null;
  }

  function getFurnitureLayerData(lyr) {
    return lyr.data && lyr.data.getReadOnlyRecordAt(0);
  }

  function importFurniture(d, frame) {
    var renderer = furnitureRenderers[d.type];
    if (!renderer) {
      stop('Missing renderer for', d.type, 'element');
    }
    return renderer(d, frame) || [];
  }

  var Furniture = /*#__PURE__*/Object.freeze({
    __proto__: null,
    furnitureRenderers: furnitureRenderers,
    layerHasFurniture: layerHasFurniture,
    isFurnitureLayer: isFurnitureLayer,
    getFurnitureLayerType: getFurnitureLayerType,
    getFurnitureLayerData: getFurnitureLayerData,
    importFurniture: importFurniture
  });

  /*
  {
    width: size[0],
    height: size[1],
    bbox: bounds.toArray(),
    type: 'frame'
  }
  */
  function getFrameData(dataset, exportOpts) {
    var frameLyr = findFrameLayerInDataset(dataset);
    var frameData;
    if (frameLyr) {
      frameData = Object.assign({}, getFrameLayerData(frameLyr));
    } else {
      frameData = calcFrameData(dataset, exportOpts);
    }
    frameData.crs = getDatasetCRS(dataset);
    return frameData;
  }

  function calcFrameData(dataset, opts) {
    var bounds = getDatasetBounds(dataset);
    var bounds2 = calcOutputSizeInPixels(bounds, opts);
    return {
      bbox: bounds.toArray(),
      width: Math.round(bounds2.width()),
      height: Math.round(bounds2.height()) || 1,
      type: 'frame'
    };
  }

  function getFrameLayerData(lyr) {
    return lyr.data && lyr.data.getReadOnlyRecordAt(0);
  }

  // Used by mapshaper-frame and mapshaper-pixel-transform. TODO: refactor
  function getFrameSize(bounds, opts) {
    var aspectRatio = bounds.width() / bounds.height();
    var height, width;
    if (opts.pixels) {
      width = Math.sqrt(+opts.pixels * aspectRatio);
    } else {
      width = +opts.width;
    }
    height = width / aspectRatio;
    return [Math.round(width), Math.round(height)];
  }


  // @lyr dataset layer
  function isFrameLayer(lyr) {
    return getFurnitureLayerType(lyr) == 'frame';
  }

  function findFrameLayerInDataset(dataset) {
    return utils.find(dataset.layers, function(lyr) {
      return isFrameLayer(lyr);
    });
  }

  function findFrameDataset(catalog) {
    var target = utils.find(catalog.getLayers(), function(o) {
      return isFrameLayer(o.layer);
    });
    return target ? target.dataset : null;
  }

  function findFrameLayer(catalog) {
    var target = utils.find(catalog.getLayers(), function(o) {
      return isFrameLayer(o.layer);
    });
    return target && target.layer || null;
  }

  function getFrameLayerBounds(lyr) {
    return new Bounds(getFrameLayerData(lyr).bbox);
  }

  // @data frame data, including crs property if available
  // Returns a single value: the ratio or
  function getMapFrameMetersPerPixel(data) {
    var bounds = new Bounds(data.bbox);
    var k, toMeters, metersPerPixel;
    if (data.crs) {
      // TODO: handle CRS without inverse projections
      // scale factor is the ratio of coordinate distance to true distance at a point
      k = getScaleFactorAtXY(bounds.centerX(), bounds.centerY(), data.crs);
      toMeters = data.crs.to_meter;
    } else {
      // Assuming coordinates are meters and k is 1 (not safe)
      // A warning should be displayed when relevant furniture element is created
      k = 1;
      toMeters = 1;
    }
    metersPerPixel = bounds.width() / k * toMeters / data.width;
    return metersPerPixel;
  }


  // bounds: Bounds object containing bounds of content in geographic coordinates
  // returns Bounds object containing bounds of pixel output
  // side effect: bounds param is modified to match the output frame
  function calcOutputSizeInPixels(bounds, opts) {
    var padX = 0,
        padY = 0,
        offX = 0,
        offY = 0,
        width = bounds.width(),
        height = bounds.height(),
        margins = parseMarginOption(opts.margin),
        marginX = margins[0] + margins[2],
        marginY = margins[1] + margins[3],
        // TODO: add option to tweak alignment of content when both width and height are given
        wx = 0.5, // how padding is distributed horizontally (0: left aligned, 0.5: centered, 1: right aligned)
        wy = 0.5, // vertical padding distribution
        widthPx, heightPx, size, kx, ky;

    if (opts.fit_bbox) {
      // scale + shift content to fit within a bbox
      offX = opts.fit_bbox[0];
      offY = opts.fit_bbox[1];
      widthPx = opts.fit_bbox[2] - offX;
      heightPx = opts.fit_bbox[3] - offY;
      if (width / height > widthPx / heightPx) {
        // data is wider than fit box...
        // scale the data to fit widthwise
        heightPx = 0;
      } else {
        widthPx = 0; // fit the data to the height
      }
      marginX = marginY = 0; // TODO: support margins

    } else if (opts.svg_scale > 0) {
      // alternative to using a fixed width (e.g. when generating multiple files
      // at a consistent geographic scale)
      widthPx = width / opts.svg_scale + marginX;
      heightPx = 0;
    } else if (+opts.pixels) {
      size = getFrameSize(bounds, opts);
      widthPx = size[0];
      heightPx = size[1];
    } else {
      heightPx = opts.height || 0;
      widthPx = opts.width || (heightPx > 0 ? 0 : 800); // 800 is default width
    }

    if (heightPx > 0) {
      // vertical meters per pixel to fit height param
      ky = (height || width || 1) / (heightPx - marginY);
    }
    if (widthPx > 0) {
      // horizontal meters per pixel to fit width param
      kx = (width || height || 1) / (widthPx - marginX);
    }

    if (!widthPx) { // heightPx and ky are defined, set width to match
      kx = ky;
      widthPx = width > 0 ? marginX + width / kx : heightPx; // export square graphic if content has 0 width (reconsider this?)
    } else if (!heightPx) { // widthPx and kx are set, set height to match
      ky = kx;
      heightPx = height > 0 ? marginY + height / ky : widthPx;
      // limit height if max_height is defined
      if (opts.max_height > 0 && heightPx > opts.max_height) {
        ky = kx * heightPx / opts.max_height;
        heightPx = opts.max_height;
      }
    }

    if (kx > ky) { // content is wide -- need to pad vertically
      ky = kx;
      padY = ky * (heightPx - marginY) - height;
    } else if (ky > kx) { // content is tall -- need to pad horizontally
      kx = ky;
      padX = kx * (widthPx - marginX) - width;
    }

    bounds.padBounds(
      margins[0] * kx + padX * wx,
      margins[1] * ky + padY * wy,
      margins[2] * kx + padX * (1 - wx),
      margins[3] * ky + padY * (1 - wy));

    if (!(widthPx > 0 && heightPx > 0)) {
      error("Missing valid height and width parameters");
    }
    if (!(kx === ky && kx > 0)) {
      error("Missing valid margin parameters");
    }

    return new Bounds(offX, offY, widthPx + offX, heightPx + offY);
  }

  function parseMarginOption(opt) {
    var str = utils.isNumber(opt) ? String(opt) : opt || '';
    var margins = str.trim().split(/[, ] */);
    if (margins.length == 1) margins.push(margins[0]);
    if (margins.length == 2) margins.push(margins[0], margins[1]);
    if (margins.length == 3) margins.push(margins[2]);
    return margins.map(function(str) {
      var px = parseFloat(str);
      return isNaN(px) ? 1 : px; // 1 is default
    });
  }

  var FrameData = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getFrameData: getFrameData,
    getFrameLayerData: getFrameLayerData,
    getFrameSize: getFrameSize,
    findFrameLayerInDataset: findFrameLayerInDataset,
    findFrameDataset: findFrameDataset,
    findFrameLayer: findFrameLayer,
    getFrameLayerBounds: getFrameLayerBounds,
    getMapFrameMetersPerPixel: getMapFrameMetersPerPixel,
    calcOutputSizeInPixels: calcOutputSizeInPixels,
    parseMarginOption: parseMarginOption
  });

  // Apply rotation, scale and/or shift to some or all of the features in a dataset
  //
  cmd.affine = function(targetLayers, dataset, opts) {
    // Need to separate the targeted shapes from any other shapes that share
    // the same topology. So we duplicate any arcs that are shared by the targeted
    // shapes and their topological neighbors and remap arc references in the
    // neighbors to point to the copies.
    // TODO: explore alternative: if some arcs are shared between transformed and
    //   non-transformed shapes, first remove topology, then tranform, then rebuild topology
    //
    var rotateArg = opts.rotate || 0;
    var scaleArg = opts.scale || 1;
    var shiftArg = opts.shift ? convertIntervalPair(opts.shift, getDatasetCRS(dataset)) : [0, 0];
    var arcs = dataset.arcs;
    var targetShapes = [];
    var otherShapes = [];
    var targetPoints = [];
    var targetFlags, otherFlags, transform;
    dataset.layers.filter(layerHasGeometry).forEach(function(lyr) {
      var hits = [],
          misses = [],
          test;
      if (targetLayers.indexOf(lyr) == -1) {
        misses = lyr.shapes;
      } else if (opts.where) {
        test = compileValueExpression(opts.where, lyr, dataset.arcs);
        lyr.shapes.forEach(function(shp, i) {
          (test(i) ? hits : misses).push(shp);
        });
      } else {
        hits = lyr.shapes;
      }
      if (lyr.geometry_type == 'point') {
        targetPoints = targetPoints.concat(hits);
      } else {
        targetShapes = targetShapes.concat(hits);
        otherShapes = otherShapes.concat(misses);
      }
    });
    var anchorArg = getAffineAnchor({arcs: dataset.arcs, layers: [{
      geometry_type: 'point', shapes: targetPoints}, {geometry_type: 'polyline',
      shapes: targetShapes}]}, opts);
    transform = getAffineTransform(rotateArg, scaleArg, shiftArg, anchorArg);
    if (targetShapes.length > 0) {
      targetFlags = new Uint8Array(arcs.size());
      otherFlags = new Uint8Array(arcs.size());
      countArcsInShapes(targetShapes, targetFlags);
      if (otherShapes.length > 0) {
        countArcsInShapes(otherShapes, otherFlags);
        applyArrayMask(otherFlags, targetFlags);
        dataset.arcs = duplicateSelectedArcs(otherShapes, arcs, otherFlags);
      }
      dataset.arcs.transformPoints(function(x, y, arcId) {
        if (arcId < targetFlags.length && targetFlags[arcId] > 0) {
          return transform(x, y);
        }
      });
    }
    forEachPoint(targetPoints, function(p) {
      var p2 = transform(p[0], p[1]);
      p[0] = p2[0];
      p[1] = p2[1];
    });
  };

  function getAffineAnchor(dataset, opts) {
    var anchor, bounds;
    if (opts.anchor) {
      anchor = opts.anchor;
    } else {
      // get bounds of selected shapes to calculate center of rotation/scale
      bounds = getDatasetBounds(dataset);
      anchor = [bounds.centerX(), bounds.centerY()];
    }
    return anchor;
  }

  // TODO: handle problems with unprojected datasets
  //   option 1: don't allow affine transformation of unprojected data
  //   option 2: error if transformed data exceeds valid coordinate range
  // source: http://mathworld.wolfram.com/AffineTransformation.html
  function getAffineTransform(rotation, scale, shift, anchor) {
    var angle = rotation * Math.PI / 180;
    var a = scale * Math.cos(angle);
    var b = -scale * Math.sin(angle);
    return function(x, y) {
      var x2 = a * (x - anchor[0]) - b * (y - anchor[1]) + shift[0] + anchor[0];
      var y2 = b * (x - anchor[0]) + a * (y - anchor[1]) + shift[1] + anchor[1];
      return [x2, y2];
    };
  }

  function applyArrayMask(destArr, maskArr) {
    for (var i=0, n=destArr.length; i<n; i++) {
      if (maskArr[i] === 0) destArr[i] = 0;
    }
  }

  function duplicateSelectedArcs(shapes, arcs, flags) {
    var arcCount = 0;
    var vertexCount = 0;
    var data = arcs.getVertexData();
    var xx = [], yy = [], nn = [], map = [], n;
    for (var i=0, len=flags.length; i<len; i++) {
      if (flags[i] > 0) {
        map[i] = arcs.size() + arcCount;
        n = data.nn[i];
        utils.copyElements(data.xx, data.ii[i], xx, vertexCount, n);
        utils.copyElements(data.yy, data.ii[i], yy, vertexCount, n);
        nn.push(n);
        vertexCount += n;
        arcCount++;
      }
    }
    forEachArcId(shapes, function(id) {
      var absId = absArcId(id);
      if (flags[absId] > 0) {
        return id < 0 ? ~map[absId] : map[absId];
      }
    });
    return mergeArcs([arcs, new ArcCollection(nn, xx, yy)]);
  }

  var roundCoord$2 = getRoundingFunction(0.01);

  function stringifyVertex(p) {
    return ' ' + roundCoord$2(p[0]) + ' ' + roundCoord$2(p[1]);
  }

  function isCubicCtrl(p) {
    return p.length > 2 && p[2] == 'C';
  }

  function stringifyPolygonCoords(coords) {
    var parts = [];
    for (var i=0; i<coords.length; i++) {
      parts.push(stringifyLineStringCoords(coords[i]) + ' Z');
    }
    return parts.length > 0 ? parts.join(' ') : '';
  }

  function stringifyLineStringCoords(coords) {
    if (coords.length === 0) return '';
    var d = 'M';
    var fromCurve = false;
    var p, i, n;
    for (i=0, n=coords.length; i<n; i++) {
      p = coords[i];
      if (isCubicCtrl(p)) {
        // TODO: add defensive check
        d += ' C' + stringifyVertex(p) + stringifyVertex(coords[++i]) + stringifyVertex(coords[++i]);
        fromCurve = true;
      } else if (fromCurve) {
        d += ' L' + stringifyVertex(p);
        fromCurve = false;
      } else {
        d += stringifyVertex(p);
      }
    }
    return d;
  }

  var SvgPathUtils = /*#__PURE__*/Object.freeze({
    __proto__: null,
    stringifyPolygonCoords: stringifyPolygonCoords,
    stringifyLineStringCoords: stringifyLineStringCoords
  });

  /* example patterns
  hatches 1px black 1px red 1px white
  1px black 1px red 1px white // same as above (hatches is default)
  45deg 2px black 2px red     // hatch direction
  dots 2px black 5px white    // 2px black dots with 5px spacing on white
  dots 2px blue 2px red 5px white  // blue and red alternating dots
  */
  function parsePattern(str) {
    if (!str) return null;
    var parts = splitPattern(str);
    var first = parts[0] || '';
    var obj = null;
    // accept variations on type names (dot, dots, square, squares, hatch, hatches, hatched)
    if (first.startsWith('dot')) {
      parts[0] = 'dots';
      obj = parseDots(parts);
    } else if (first.startsWith('square')) {
      parts[0] = 'squares';
      obj = parseDots(parts);
    } else if (first.startsWith('hatch')) {
      parts[0] = 'hatches';
      obj = parseHatches(parts);
    } else if (first.startsWith('dash')) {
      obj = parseDashes(parts);
    } else if (!isNaN(parseFloat(first))) {
      parts.unshift('hatches');
      obj = parseHatches(parts); // hatches is the default, name can be omitted
    }
    if (!obj) {
      // consider
      message('Invalid pattern, ignoring:', str);
    }
    return obj;
  }

  function parseDashes(parts) {
    // format:
    // "dashes" dash-len dash-space width color1 [color2...] space bg-color
    // examples:
    // dashes 4px 3px 1px black 4px white
    parts.shift();
    var colors = [];
    var background = parts.pop();
    var spacing = parseInt(parts.pop());
    var tmp;
    while (parts.length > 0) {
      tmp = parts.pop();
      if (isSize(tmp)) {
        parts.push(tmp);
        break;
      } else {
        colors.push(tmp);
      }
    }
    var width = parseInt(parts.pop());
    var dashes = [parseInt(parts.pop()), parseInt(parts.pop())].reverse();
    var rotation = 45;
    if (parts.length > 0) {
      rotation = parseInt(parts.pop());
    }
    if (parts.length > 0) {
      return null;
    }
    if (width > 0 === false) return null;
    return {
      type: 'dashes',
      tileSize: [colors.length * (width + spacing), utils.sum(dashes)],
      colors: colors,
      width: width,
      dashes: dashes,
      spacing: spacing,
      background: background,
      rotation: rotation
    };
  }

  function parseHatches(parts) {
    // format:
    // [hatches] [rotation] width1 color1 [width2 color2 ...]
    // examples:
    // 1px red 1px white 1px black
    // -45deg 3 #eee 3 rgb(0,0,0)
    parts.shift();
    var rot = parts.length % 2 == 1 ? parseInt(parts.shift()) : 45, // default is 45
        colors = [], widths = [];
    for (var i=0; i<parts.length; i+=2) {
      widths.push(parseInt(parts[i]));
      colors.push(parts[i+1]);
    }
    if (Math.min.apply(null, widths) > 0 === false) return null;
    return {
      tileSize: [utils.sum(widths), 10],
      type: 'hatches',
      colors: colors,
      widths: widths,
      rotation: rot
    };
  }

  function isSize(str) {
    return parseInt(str) > 0;
  }

  function parseDots(parts) {
    // format:
    // "dots"|"squares" [rotation] size color1 [color2 ...] spacing bg-color
    // examples:
    // dots 45deg 2px red blue 5px white
    // squares 3px black 1px white
    var colors = [];
    var type = parts.shift();
    var rot = 0;
    if (isSize(parts[1])) { // if rotation is present, there are two numbers
      rot = parseInt(parts.shift());
    }
    var size = parseInt(parts.shift());
    var bg = parts.pop();
    var spacing = parseInt(parts.pop());
    while (parts.length > 0) {
      colors.push(parts.shift());
    }
    if (size > 0 === false || spacing >= 0 === false) return null;
    if (colors.length === 0) return null;
    var side = colors.length * (size + spacing);
    return {
      type: type,
      tileSize: [side, side],
      colors: colors,
      size: size,
      spacing: spacing,
      background: bg,
      rotation: rot
    };
  }

  function splitPattern(str) {
    // split apart space and comma-delimited tokens
    // ... but don't split rgb(...) colors
    var splitRxp = /[, ]+(?![^(]*\))/;
    return String(str).trim().split(splitRxp);
  }

  function getHashId(str) {
    return ('hash_' + str).replace(/[()# ,_]+/g, '_'); // replace some chars that occur in colors
  }

  // properties: properties object of a path data object (prior to conversion to SVG)
  // defs: array of definition objects
  //
  function convertFillPattern(properties, defs) {
    var hatchStr = properties['fill-pattern'];
    var hashId = getHashId(hatchStr);
    var hash = utils.find(defs, function(o) { return o.id == hashId; });
    delete properties['fill-pattern'];
    if (!hash) {
      hash = makeSVGPatternFill(hatchStr, hashId);
      if (!hash) return;
      defs.push(hash);
    }
    properties.fill = hash.href;
  }

  function makeSVGPatternFill(str, id) {
    var o = parsePattern(str);
    var svg;
    if (!o) return null;
    if (o.type == 'hatches') {
      svg = makeHatchPatternSVG(o);
    } else if (o.type == 'dots' || o.type == 'squares') {
      svg = makeDotPatternSVG(o);
    } else if (o.type == 'dashes') {
      svg = makeDashPatternSVG(o);
    }
    return {
      svg: wrapSVGPattern(o, id, svg),
      id: id,
      href: `url(#${ id })`
    };
  }

  function wrapSVGPattern(o, id, str) {
    var w = o.tileSize[0];
    var h = o.tileSize[1];
    var svg = `<pattern id="${id}" patternUnits="userSpaceOnUse" width="${ w }" height="${ h }" patternTransform="rotate(${ o.rotation })">`;
    if (o.background) {
      svg += `<rect x="0" y="0" width="${ w }" height="${ h }" fill="${ o.background }"></rect>`;
    }
    return svg + str + '</pattern>';
  }

  function makeDashPatternSVG(o) {
    var svg = '';
    for (var i=0, x=0; i<o.colors.length; i++) {
      svg += `<rect x="${ x }" y="0" width="${ o.width }" height="${ o.dashes[0] }" fill="${ o.colors[i] }"></rect>`;
      x += o.width + o.spacing;
    }
    return svg;
  }

  function makeHatchPatternSVG(o) {
    var h = o.tileSize[1];
    var svg = '';
    for (var i=0, x=0; i<o.widths.length; i++) {
      svg += `<rect x="${ x }" y="0" width="${ o.widths[i] }" height="${ h }" fill="${ o.colors[i] }"></rect>`;
      x += o.widths[i];
    }
    return svg;
  }

  function makeDotPatternSVG(o) {
    var dotSize = o.size;
    var colorCount = o.colors.length;
    var dotDist = dotSize + o.spacing;
    var dotsPerTile = colorCount * colorCount;
    var makeSymbol = o.type == 'squares' ? makeSquare : makeCircle$1;
    var svg = '';
    for (var i=0, x=0, y=0; i<dotsPerTile; i++) {
      svg += makeSymbol(x, y, dotSize, o.colors[(i + Math.floor(i / colorCount)) % colorCount]);
      x = ((i + 1) % colorCount) * dotDist;
      if (x === 0) y += dotDist;
    }
    return svg;
  }

  function makeCircle$1(x, y, size, fill) {
    const r = size / 2;
    return `<circle cx="${x + r}" cy="${y + r}" r="${r}" fill="${ fill }"></circle>`;
  }

  function makeSquare(x, y, size, fill) {
    return `<rect x="${x}" y="${y}" width="${ size }" height="${ size }" fill="${ fill }"></rect>`;
  }

  var SvgHatch = /*#__PURE__*/Object.freeze({
    __proto__: null,
    parsePattern: parsePattern,
    parseDashes: parseDashes,
    parseHatches: parseHatches,
    parseDots: parseDots,
    convertFillPattern: convertFillPattern
  });

  // parsing hints for -style command cli options
  // null values indicate the lack of a function for parsing/identifying this property
  // (in which case a heuristic is used for distinguishing a string literal from an expression)
  var stylePropertyTypes = {
    css: null,
    class: 'classname',
    dx: 'measure',
    dy: 'measure',
    fill: 'color',
    'fill-pattern': 'pattern',
    'font-family': null,
    'font-size': null,
    'font-style': null,
    'font-weight': null,
    'label-text': null,  // leaving this null
    'letter-spacing': 'measure',
    'line-height': 'measure',
    opacity: 'number',
    r: 'number',
    stroke: 'color',
    'stroke-dasharray': 'dasharray',
    'stroke-width': 'number',
    'stroke-opacity': 'number',
    'stroke-miterlimit': 'number',
    'fill-opacity': 'number',
    'vector-effect': null,
    'text-anchor': null
  };

  // The -symbols command accepts some options that are not supported by -style
  // (different symbol types accept different combinations of properties...)
  var symbolPropertyTypes = utils.extend({
    type: null,
    length: 'number', // e.g. arrow length
    rotation: 'number',
    radius: 'number',
    radii: null, // string, parsed by function
    flipped: 'boolean',
    rotated: 'boolean',
    direction: 'number',
    sides: 'number', // polygons and stars
    points: 'number', // polygons and stars
    anchor: null, // arrows; takes start, middle, end
    'head-angle': 'number',
    'head-width': 'number',
    'head-length': 'number',
    'stem-width': 'number',
    'stem-curve': 'number', // degrees of arc
    'stem-taper': 'number',
    'stem-length': 'number',
    'min-stem-ratio': 'number',
    'arrow-scaling': 'number',
    effect: null // e.g. "fade"
  }, stylePropertyTypes);

  var commonProperties = 'css,class,opacity,stroke,stroke-width,stroke-dasharray,stroke-opacity,fill-opacity,vector-effect'.split(',');

  var propertiesBySymbolType = {
    polygon: utils.arrayToIndex(commonProperties.concat('fill', 'fill-pattern')),
    polyline: utils.arrayToIndex(commonProperties.concat('stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit')),
    point: utils.arrayToIndex(commonProperties.concat('fill', 'r')),
    label: utils.arrayToIndex(commonProperties.concat(
      'fill,font-family,font-size,text-anchor,font-weight,font-style,letter-spacing,dominant-baseline'.split(',')))
  };

  // symType: point, polygon, polyline, label
  function applyStyleAttributes(svgObj, symType, rec, filter) {
    var fields = findPropertiesBySymbolGeom(Object.keys(rec || {}), symType);
    for (var i=0, n=fields.length; i<n; i++) {
      if (filter && !filter(fields[i])) continue;
      setAttribute(svgObj, fields[i], rec[fields[i]]);
    }
  }

  function setAttribute(obj, k, v) {
    if (!obj.properties) obj.properties = {};
    obj.properties[k] = v;
    if (k == 'stroke-dasharray' && v) {
      // kludge for cleaner dashes... make butt the default?
      obj.properties['stroke-linecap'] = 'butt';
    }
  }

  function isSupportedSvgStyleProperty(name) {
    return name in stylePropertyTypes;
  }

  function isSupportedSvgSymbolProperty(name) {
    return name in symbolPropertyTypes;
  }

  function findPropertiesBySymbolGeom(fields, type) {
    var index = propertiesBySymbolType[type] || {};
    return fields.filter(function(name) {
      return name in index;
    });
  }

  // Returns a function that returns an object containing property values for a single record
  // opts: parsed command line options for the -symbols command
  //
  function getSymbolDataAccessor(lyr, opts) {
    var functions = {};
    var properties = [];
    lyr.data ? lyr.data.getFields() : [];

    Object.keys(opts).forEach(function(optName) {
      var svgName = optName.replace(/_/g, '-');
      if (!isSupportedSvgSymbolProperty(svgName)) {
        return;
      }
      var val = opts[optName];
      functions[svgName] = getSymbolPropertyAccessor(val, svgName, lyr);
      properties.push(svgName);
    });

    // TODO: consider applying values of existing fields with names of symbol properties

    return function(id) {
      var d = {}, name;
      for (var i=0; i<properties.length; i++) {
        name = properties[i];
        d[name] = functions[name](id);
      }
      return d;
    };
  }

  // need a test that identifies any expression but doesn't get triggered by:
  // * invalid patterns: dots 45deg black 3px red
  // * ???
  //
  function mightBeExpression(str, fields) {
    fields = fields || [];
    if (fields.indexOf(str.trim()) > -1) return true;
    return /[(){}./*?:&|=[+-]/.test(str);
  }

  function getSymbolPropertyAccessor(val, svgName, lyr) {
    var strVal = String(val).trim();
    var typeHint = symbolPropertyTypes[svgName];
    var fields = lyr.data ? lyr.data.getFields() : [];
    var literalVal = null;
    var accessor;

    if (typeHint && fields.indexOf(strVal) === -1) {
      literalVal = parseSvgLiteralValue(strVal, typeHint);
    }
    if (literalVal === null && mightBeExpression(strVal, fields)) {
      accessor = parseStyleExpression(strVal, lyr); // no longer throws an error
    }
    if (!accessor && literalVal === null && !typeHint) {
      // We don't have a type rule for detecting an invalid value, so we're
      // treating the string as a literal value
      literalVal = strVal;
    }
    if (accessor) return accessor;
    if (literalVal !== null) return function(id) {return literalVal;};
    stop('Unexpected value for', svgName + ':', strVal);
  }

  function parseStyleExpression(strVal, lyr) {
    var func;
    try {
      func = compileValueExpression(strVal, lyr, null, {no_warn: true});
      func(0); // check for runtime errors (e.g. undefined variables)
    } catch(e) {
      func = null;
    }
    return func;
  }

  // returns parsed value or null if @strVal is not recognized as a valid literal value
  function parseSvgLiteralValue(strVal, type) {
    var val = null;
    if (type == 'number') {
      // TODO: handle values with units, like "13px"
      val = isSvgNumber(strVal) ? Number(strVal) : null;
    } else if (type == 'color') {
      val = isSvgColor(strVal) ? strVal : null;
    } else if (type == 'classname') {
      val = isSvgClassName(strVal) ? strVal : null;
    } else if (type == 'measure') { // SVG/CSS length (e.g. 12px, 1em, 4)
      val = isSvgMeasure(strVal) ? parseSvgMeasure(strVal) : null;
    } else if (type == 'dasharray') {
      val = isDashArray(strVal) ? strVal : null;
    } else if (type == 'pattern') {
      val = isPattern(strVal) ? strVal : null;
    } else if (type == 'boolean') {
      val = parseBoolean(strVal);
    }
    //  else {
    //   // unknown type -- assume literal value
    //   val = strVal;
    // }
    return val;
  }

  function isPattern(str) {
    return !!parsePattern(str);
  }

  function isDashArray(str) {
    return /^[0-9]+( [0-9]+)*$/.test(str);
  }

  function isSvgClassName(str) {
    return /^( ?[_a-z][-_a-z0-9]*\b)+$/i.test(str);
  }


  function isSvgNumber(o) {
    return utils.isFiniteNumber(o) || utils.isString(o) && /^-?[.0-9]+$/.test(o);
  }

  function parseBoolean(o) {
    if (o === true || o === 'true') return true;
    if (o === false || o === 'false') return false;
    return null;
  }

  function isSvgMeasure(o) {
    return utils.isFiniteNumber(o) || utils.isString(o) && /^-?[.0-9]+[a-z]*$/.test(o);
  }

  // Can be a number or a string
  function parseSvgMeasure(str) {
    return utils.isString(str) && /[a-z]/.test(str) ? str : Number(str);
  }

  function isSvgColor(str) {
    return /^[a-z]+$/i.test(str) ||
      /^#[0-9a-f]+$/i.test(str) || /^rgba?\([0-9,. ]+\)$/.test(str);
  }

  var SvgProperties = /*#__PURE__*/Object.freeze({
    __proto__: null,
    applyStyleAttributes: applyStyleAttributes,
    isSupportedSvgStyleProperty: isSupportedSvgStyleProperty,
    findPropertiesBySymbolGeom: findPropertiesBySymbolGeom,
    getSymbolDataAccessor: getSymbolDataAccessor,
    mightBeExpression: mightBeExpression,
    getSymbolPropertyAccessor: getSymbolPropertyAccessor,
    isSvgClassName: isSvgClassName,
    isSvgNumber: isSvgNumber,
    parseBoolean: parseBoolean,
    isSvgMeasure: isSvgMeasure,
    parseSvgMeasure: parseSvgMeasure,
    isSvgColor: isSvgColor
  });

  var geojsonImporters = {
    Point: importPoint,
    Polygon: importPolygon,
    LineString: importLineString,
    MultiPoint: importMultiPoint,
    MultiLineString: importMultiLineString,
    MultiPolygon: importMultiPolygon
  };

  function importGeoJSONFeatures(features, opts) {
    opts = opts || {};
    return features.map(function(obj) {
      var geom = obj.type == 'Feature' ? obj.geometry : obj; // could be null
      var geomType = geom && geom.type;
      var msType = GeoJSON.translateGeoJSONType(geomType);
      var d = obj.properties || {};
      var svgObj = null;
      if (geomType && geom.coordinates) {
        svgObj = geojsonImporters[geomType](geom.coordinates, d);
      }
      if (!svgObj) {
        return {tag: 'g'}; // empty element
      } else if (msType == 'polyline' || msType == 'polygon') {
        applyStyleAttributes(svgObj, msType, d);
      } else if (msType == 'point' && isSimpleCircle(d)) {
        // kludge -- maintains bw compatibility/passes tests -- style attributes
        // are applied to the <g> container, 'r' property is applied to circle
        applyStyleAttributes(svgObj, msType, d, simpleCircleFilter);
      } else ;
      if ('id' in obj) {
        if (!svgObj.properties) {
          svgObj.properties = {};
        }
        svgObj.properties.id = (opts.id_prefix || '') + obj.id;
      }
      return svgObj;
    });
  }

  function importPoint(coords, rec) {
    rec = rec || {};
    if (isSimpleCircle(rec)) {
      return {
        tag: 'circle',
        properties: {
          cx: coords[0],
          cy: coords[1],
          r: rec.r
        }
      };
    }
    var o = renderPoint(rec);
    if (o) o.properties.transform = getTransform(coords);
    return o;
  }

  function simpleCircleFilter(k) {
    return k != 'r';
  }

  // just a dot, no label or icon
  function isSimpleCircle(rec) {
    return rec && (rec.r > 0 && !rec['svg-symbol'] && !rec['label-text']);
  }

  function importMultiPoint(coords, rec) {
    var children = [], p;
    for (var i=0; i<coords.length; i++) {
      p = importPoint(coords[i], rec);
      if (!p) continue;
      if (p.tag == 'g' && p.children) {
        children = children.concat(p.children);
      } else {
        children.push(p);
      }
    }
    return children.length > 0 ? {tag: 'g', children: children} : null;
  }

  function importLineString(coords) {
    var d = stringifyLineStringCoords(coords);
    return {
      tag: 'path',
      properties: {d: d}
    };
  }

  function importMultiLineString(coords) {
    var d = coords.map(stringifyLineStringCoords).join(' ');
    return {
      tag: 'path',
      properties: {d: d}
    };
  }

  function importMultiPolygon(coords) {
   return importPolygon(flattenMultiPolygonCoords(coords));
  }

  function flattenMultiPolygonCoords(coords) {
    return coords.reduce(function(memo, poly) {
      return memo.concat(poly);
    }, []);
  }

  function importPolygon(coords) {
    if (coords.length === 0) return null;
    var o = {
      tag: 'path',
      properties: {
        d: stringifyPolygonCoords(coords)
      }
    };
    if (coords.length > 1) {
      o.properties['fill-rule'] = 'evenodd'; // support polygons with holes
    }
    return o;
  }

  var GeojsonToSvg = /*#__PURE__*/Object.freeze({
    __proto__: null,
    importGeoJSONFeatures: importGeoJSONFeatures,
    importPoint: importPoint,
    importLineString: importLineString,
    importMultiLineString: importMultiLineString,
    importMultiPolygon: importMultiPolygon,
    flattenMultiPolygonCoords: flattenMultiPolygonCoords,
    importPolygon: importPolygon
  });

  function toLabelString(val) {
    if (val || val === 0 || val === false) return String(val);
    return '';
  }

  // Kludge for applying fill and other styles to a <text> element
  // (for rendering labels in the GUI with the dot in Canvas, not SVG)
  function renderStyledLabel(rec) {
    var o = renderLabel(rec);
    applyStyleAttributes(o, 'label', rec);
    return o;
  }

  function renderLabel(rec) {
    var line = toLabelString(rec['label-text']);
    var morelines, obj;
    // Accepting \n (two chars) as an alternative to the newline character
    // (sometimes, '\n' is not converted to newline, e.g. in a Makefile)
    // Also accepting <br>
    var newline = /\n|\\n|<br>/i;
    var dx = rec.dx || 0;
    var dy = rec.dy || 0;
    var properties = {
      // using x, y instead of dx, dy for shift, because Illustrator doesn't apply
      // dx value when importing text with text-anchor=end
      y: dy,
      x: dx
    };
    if (newline.test(line)) {
      morelines = line.split(newline);
      line = morelines.shift();
    }
    obj = {
      tag: 'text',
      value: line,
      properties: properties
    };
    if (morelines) {
      // multiline label
      obj.children = [];
      morelines.forEach(function(line) {
        var tspan = {
          tag: 'tspan',
          value: line,
          properties: {
            x: dx,
            dy: rec['line-height'] || '1.1em'
          }
        };
        obj.children.push(tspan);
      });
    }
    return obj;
  }

  var SvgLabels = /*#__PURE__*/Object.freeze({
    __proto__: null,
    renderStyledLabel: renderStyledLabel,
    renderLabel: renderLabel
  });

  // convert data records (properties like svg-symbol, label-text, fill, r) to svg symbols

  function getTransform(xy, scale) {
    var str = 'translate(' + roundToTenths(xy[0]) + ' ' + roundToTenths(xy[1]) + ')';
    if (scale && scale != 1) {
      str += ' scale(' + scale + ')';
    }
    return str;
  }

  var symbolRenderers = {
    line: line,
    polygon: polygon,
    polyline: polyline,
    circle: circle,
    square: square,
    image: image,
    group: group,
    label: label,
    offset: offset
  };

  // render label and/or point symbol
  function renderPoint(rec) {
    var children = [];
    // var halfSize = rec.r || 0; // radius or half of symbol size
    if (featureHasSvgSymbol(rec)) {
      children.push(renderSymbol(rec));
    }
    if (featureHasLabel(rec)) {
      children.push(renderStyledLabel(rec));
    }
    var o = children.length > 1 ? {tag: 'g', children: children} : children[0];
    if (!o) return null;
    o.properties = o.properties || {};
    return o;
  }

  function renderSymbol(d) {
    if (d['svg-symbol']) {
      return renderComplexSymbol(d['svg-symbol']);
    }
    if (d.r > 0) {
      return circle(d);
    }
    return empty();
  }

  function renderComplexSymbol(sym, x, y) {
    if (utils.isString(sym)) {
      sym = JSON.parse(sym);
    }
    if (sym.tag) {
      // symbol appears to already use mapshaper's svg notation... pass through
      return sym;
    }
    var renderer = symbolRenderers[sym.type];
    if (!renderer) {
      message(sym.type ? 'Unknown symbol type: ' + sym.type : 'Symbol is missing a type property');
      return empty();
    }
    var o = renderer(sym, x || 0, y || 0);
    if (sym.opacity) {
      o.properties.opacity = sym.opacity;
    }
    return o;
  }

  function empty() {
    return {tag: 'g', properties: {}, children: []};
  }

  function circle(d, x, y) {
    var o = {
      tag: 'circle',
      properties: {
        cx: x || 0,
        cy: y || 0
      }
    };
    applyStyleAttributes(o, 'point', d);
    return o;
  }

  function label(d, x, y) {
    var o = renderStyledLabel(d);
    if (x || y) {
      // set x, y here, rather than adding to dx, dy -- so dy, dy can
      // have CSS units (like ems)
      o.properties.transform = getTransform([x, y]);
    }
    return o;
  }

  function image(d, x, y) {
    var w = d.width || 20,
        h = d.height || 20;
    var o = {
      tag: 'image',
      properties: {
        width: w,
        height: h,
        x: (x || 0) - w / 2,
        y: (y || 0) - h / 2,
        href: d.href || ''
      }
    };
    if (d.fill) o.properties.fill = d.fill;
    return o;
  }

  function square(d, x, y) {
    var r = d.r || 0;
    var o = {
      tag: 'rect',
      properties: {
        x: x - r,
        y: y - r,
        width: r * 2,
        height: r * 2
      }
    };
    applyStyleAttributes(o, 'point', d);
    return o;
  }

  function line(d, x, y) {
    var coords, o;
    coords = [[x, y], [x + (d.dx || 0), y + (d.dy || 0)]];
    o = importLineString(coords);
    applyStyleAttributes(o, 'polyline', d);
    return o;
  }

  // polyline coords are like GeoJSON MultiLineString coords: an array of 0 or more paths
  function polyline(d) {
    var coords = d.coordinates || [];
    var o = importMultiLineString(coords);
    applyStyleAttributes(o, 'polyline', d);
    return o;
  }

  // polygon coords are an array of rings (and holes), like flattened MultiPolygon coords
  function polygon(d) {
    var coords = d.coordinates || [];
    var o = importPolygon(coords);
    applyStyleAttributes(o, 'polygon', d);
    return o;
  }

  function offset(d, x, y) {
    var dx = (x || 0) + (d.dx || 0);
    var dy = (y || 0) + (d.dy || 0);
    return {
      tag: 'g',
      properties: {
        transform: getTransform([dx, dy])
      },
      children: []
    };
  }

  function group(d, x, y) {
    var o = {
      tag: 'g',
      children: []
    };
    var children = o.children;
    (d.parts || []).forEach(function(o) {
      var sym = renderComplexSymbol(o, x, y);
      children.push(sym);
      //if (d.chained) {
      //if (o.chained) {
      if (o.type == 'line') {
        x += (o.dx || 0);
        y += (o.dy || 0);
      }
      if (o.type == 'offset') {
        children = sym.children;
        x = y = 0;
      }
    });
    if (o.children.length == 1 && !o.properties) return o.children[0];
    return o;
  }

  var SvgSymbols = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getTransform: getTransform,
    symbolRenderers: symbolRenderers,
    renderPoint: renderPoint
  });

  cmd.scalebar = function(catalog, opts) {
    var frame = findFrameDataset(catalog);
    var lyr;
    if (!frame) {
      stop('Missing a map frame');
    }
    lyr = getScalebarLayer(opts);
    frame.layers.push(lyr);
  };

  function getScalebarLayer(opts) {
    var obj = utils.defaults({type: 'scalebar'}, opts);
    return {
      name: opts.name || 'scalebar',
      data: new DataTable([obj])
    };
  }

  // TODO: generalize to other kinds of furniture as they are developed
  function getScalebarPosition(d) {
    var opts = { // defaults
      valign: 'top',
      halign: 'left',
      voffs: 10,
      hoffs: 10
    };
    if (+d.left > 0) {
      opts.hoffs = +d.left;
    }
    if (+d.top > 0) {
      opts.voffs = +d.top;
    }
    if (+d.right > 0) {
      opts.hoffs = +d.right;
      opts.halign = 'right';
    }
    if (+d.bottom > 0) {
      opts.voffs = +d.bottom;
      opts.valign = 'bottom';
    }
    return opts;
  }

  furnitureRenderers.scalebar = renderScalebar;

  function renderScalebar(d, frame) {
    var pos = getScalebarPosition(d);
    var metersPerPx = getMapFrameMetersPerPixel(frame);
    var label = d.label_text || getAutoScalebarLabel(frame.width, metersPerPx);
    var scalebarKm = parseScalebarLabelToKm(label);
    var barHeight = 3;
    var labelOffs = 4;
    var fontSize = +d.font_size || 12;
    var width = Math.round(scalebarKm / metersPerPx * 1000);
    var height = Math.round(barHeight + labelOffs + fontSize * 0.8);
    var labelPos = d.label_position == 'top' ? 'top' : 'bottom';
    var anchorX = pos.halign == 'left' ? 0 : width;
    var anchorY = barHeight + labelOffs;
    var dx = pos.halign == 'right' ? frame.width - width - pos.hoffs : pos.hoffs;
    var dy = pos.valign == 'bottom' ? frame.height - height - pos.voffs : pos.voffs;

    if (!frame.crs) {
      message('Unable to render a scalebar: unknown CRS.');
      return [];
    }

    if (labelPos == 'top') {
      anchorY = -labelOffs;
      dy += Math.round(labelOffs + fontSize * 0.8);
    }

    if (width > 0 === false) {
      stop("Null scalebar length");
    }
    var barObj = {
      tag: 'rect',
      properties: {
        fill: 'black',
        x: 0,
        y: 0,
        width: width,
        height: barHeight
      }
    };
    var labelOpts = {
        'label-text': label,
        'font-size': fontSize,
        'text-anchor': pos.halign == 'left' ? 'start': 'end',
        'dominant-baseline': labelPos == 'top' ? 'auto' : 'hanging'
        //// 'dominant-baseline': labelPos == 'top' ? 'text-after-edge' : 'text-before-edge'
        // 'text-after-edge' is buggy in Safari and unsupported by Illustrator,
        // so I'm using 'hanging' and 'auto', which seem to be well supported.
        // downside: requires a kludgy multiplier to calculate scalebar height (see above)
      };
    var labelObj = symbolRenderers.label(labelOpts, anchorX, anchorY);
    var g = {
      tag: 'g',
      children: [barObj, labelObj],
      properties: {
        transform: 'translate(' + dx + ' ' + dy + ')'
      }
    };
    return [g];
  }

  function getAutoScalebarLabel(mapWidth, metersPerPx) {
    var minWidth = 70; // 100; // TODO: vary min size based on map width
    var minKm = metersPerPx * minWidth / 1000;
    // note: removed 1.5 12 and 1,200
    var options = ('1/8 1/5 1/4 1/2 1 2 3 4 5 8 10 15 20 25 30 40 50 75 ' +
      '100 150 200 250 300 350 400 500 750 1,000 1,500 2,000 ' +
      '2,500 3,000 4,000 5,000').split(' ');
    return options.reduce(function(memo, str) {
      if (memo) return memo;
      var label = formatDistanceLabelAsMiles(str);
      if (parseScalebarLabelToKm(label) > minKm) {
         return label;
      }
    }, null) || '';
  }

  function formatDistanceLabelAsMiles(str) {
    var num = parseScalebarNumber(str);
    return str + (num > 1 ? ' MILES' : ' MILE');
  }

  // See test/mapshaper-scalebar.js for examples of supported formats
  function parseScalebarLabelToKm(str) {
    var units = parseScalebarUnits(str);
    var value = parseScalebarNumber(str);
    if (!units || !value) return NaN;
    return units == 'mile' ? value * 1.60934 : value;
  }

  function parseScalebarUnits(str) {
    var isMiles = /miles?$/.test(str.toLowerCase());
    var isKm = /(km|kilometers?|kilometres?)$/.test(str.toLowerCase());
    return isMiles && 'mile' || isKm && 'km' || '';
  }

  function parseScalebarNumber(str) {
    var fractionRxp = /^([0-9]+) ?\/ ?([0-9]+)/;
    var match, value;
    str = str.replace(/[\s]/g, '').replace(/,/g, '');
    if (fractionRxp.test(str)) {
      match = fractionRxp.exec(str);
      value = +match[1] / +match[2];
    } else {
      value = parseFloat(str);
    }
    return value > 0 && value < Infinity ? value : NaN;
  }

  var Scalebar = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getScalebarLayer: getScalebarLayer,
    renderScalebar: renderScalebar,
    formatDistanceLabelAsMiles: formatDistanceLabelAsMiles,
    parseScalebarLabelToKm: parseScalebarLabelToKm
  });

  function transformDatasetToPixels(dataset, opts) {
    var frame = getFrameData(dataset, opts);
    fitDatasetToFrame(dataset, frame, opts);
    return [frame.width, frame.height];
  }

  function fitDatasetToFrame(dataset, frame, opts) {
    var bounds = new Bounds(frame.bbox);
    var bounds2 = new Bounds(0, 0, frame.width, frame.height);
    var fwd = bounds.getTransform(bounds2, opts.invert_y);
    transformPoints(dataset, function(x, y) {
      return fwd.transform(x, y);
    });
  }

  var PixelTransform = /*#__PURE__*/Object.freeze({
    __proto__: null,
    transformDatasetToPixels: transformDatasetToPixels,
    fitDatasetToFrame: fitDatasetToFrame
  });

  function stringify(obj) {
    var svg, joinStr;
    if (!obj || !obj.tag) return '';
    svg = '<' + obj.tag;
    // w.s. is significant in text elements
    if (obj.properties) {
      svg += stringifyProperties(obj.properties);
    }
    if (obj.children || obj.value) {
      joinStr = obj.tag == 'text' || obj.tag == 'tspan' ? '' : '\n';
      svg += '>' + joinStr;
      if (obj.value) {
        svg += stringEscape(obj.value);
      }
      if (obj.children) {
        svg += obj.children.map(stringify).join(joinStr);
      }
      svg += joinStr + '</' + obj.tag + '>';
    } else {
      svg += '/>';
    }
    return svg;
  }

  // Replace some chars with XML "predefined entities" to avoid parsing errors
  // https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Predefined_entities_in_XML
  var rxp = /[&<>"']/g,
      map = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&apos;'
      };
  function stringEscape(s) {
    return String(s).replace(rxp, function(match, i) {
      var entity = map[match];
      // don't replace &amp; with &amp;amp;
      if (match == '&' && s.substr(i, entity.length) == entity) {
        return '&';
      }
      return entity;
    });
  }

  function stringifyProperties(o) {
    return Object.keys(o).reduce(function(memo, key) {
      var val = o[key],
          strval;
      if (!val && val !== 0) return memo; // omit undefined / empty / null values
      strval = utils.isString(val) ? val : JSON.stringify(val);
      if (key == 'href') {
        key = 'xlink:href';
      }
      if (key == 'css') {
        key = 'style'; // inline style
      }
      return memo + ' ' + key + '="' + stringEscape(strval) + '"';
    }, '');
  }

  var SvgStringify = /*#__PURE__*/Object.freeze({
    __proto__: null,
    stringify: stringify,
    stringEscape: stringEscape,
    stringifyProperties: stringifyProperties
  });

  // public domain implementation
  // source: https://github.com/jbt/js-crypto
  function sha1(str1){
    for (
      var blockstart = 0,
        i = 0,
        W = [],
        A, B, C, D, F, G,
        H = [A=0x67452301, B=0xEFCDAB89, ~A, ~B, 0xC3D2E1F0],
        word_array = [],
        temp2,
        s = unescape(encodeURI(str1)),
        str_len = s.length;

      i <= str_len;
    ){
      word_array[i >> 2] |= (s.charCodeAt(i)||128) << (8 * (3 - i++ % 4));
    }
    word_array[temp2 = ((str_len + 8) >> 2) | 15] = str_len << 3;

    for (; blockstart <= temp2; blockstart += 16) {
      A = H; i = 0;

      for (; i < 80;
        A = [[
          (G = ((s = A[0]) << 5 | s >>> 27) + A[4] + (W[i] = (i<16) ? ~~word_array[blockstart + i] : G << 1 | G >>> 31) + 1518500249) + ((B = A[1]) & (C = A[2]) | ~B & (D = A[3])),
          F = G + (B ^ C ^ D) + 341275144,
          G + (B & C | B & D | C & D) + 882459459,
          F + 1535694389
        ][0|((i++) / 20)] | 0, s, B << 30 | B >>> 2, C, D]
      ) {
        G = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];
      }

      for(i = 5; i; ) H[--i] = H[i] + A[i] | 0;
    }

    for(str1 = ''; i < 40; )str1 += (H[i >> 3] >> (7 - i++ % 8) * 4 & 15).toString(16);
    return str1;
  }

  var cache = {};
  function fetchFileSync(url) {
    if (url in cache) return cache[url];
    var res  = require$1('sync-request')('GET', url, {timeout: 2000});
    var content = res.getBody().toString();
    cache[url] = content;
    return content;
  }

  // convert object properties to definitions for images and hatch fills
  function convertPropertiesToDefinitions(obj, defs) {
    procNode(obj);

    function procNode(obj) {
      if (obj.tag == 'path' && obj.properties['fill-pattern']) {
        convertFillPattern(obj.properties, defs);
      }
      if (obj.tag == 'image') {
        if (/\.svg/.test(obj.properties.href || '')) {
          convertSvgImage(obj, defs);
        }
      } else if (obj.children) {
        obj.children.forEach(procNode);
      }
    }
  }

  function convertSvgImage(obj, defs) {
    // Same-origin policy prevents embedding images in the web UI
    var href = obj.properties.href;
    // look for a previously added definition to use
    // (assumes that images that share the same href can also use the same defn)
    var item = utils.find(defs, function(item) {return item.href == href;});
    if (!item) {
      item = {
        href: href,
        id: urlToId(href) // generating id from href, to try to support multiple inline svgs on page
      };
      item.svg = serializeSvgImage(href, item.id);
      defs.push(item);
    }
    if (item.svg) {
      obj.tag = 'use';
      obj.properties.href = '#' + item.id;
    }
  }

  // Returns the content of an SVG file from a local path or URL
  // Returns '' if unable to get the content (e.g. due to cross-domain security rules)
  function serializeSvgImage(href, id) {
    var svg = '';
    try {
      // try to download the SVG content and use that
      svg = convertSvgToDefn(getSvgContent(href), id) + '\n';
      svg = '<!-- ' + href + '-->\n' + svg; // add href as a comment, to aid in debugging
    } catch(e) {
      // tried creating a symbol as a fallback... encounted problems with icon
      // size and placement, giving up on this for now
      // svg = `<symbol><image xlink:href="${obj.properties.href}" id="${id}"></image></symbol>`;
    }
    return svg;
  }

  // href: A URL or a local path
  // TODO: download SVG files asynchronously
  // (currently, files are downloaded synchronously, which is obviously undesirable)
  //
  function getSvgContent(href) {
    var content;
    if (href.indexOf('http') === 0) {
      content = fetchFileSync(href);
    } else if (require$1('fs').existsSync(href)) {
      content = require$1('fs').readFileSync(href, 'utf8');
    } else {
      stop("Invalid SVG location:", href);
    }
    return content;
  }

  function convertSvgToDefn(svg, id) {
    // Remove stuff before <svg> tag
    svg = svg.replace(/[^]*<svg/, '<svg');
    return svg.replace(/^<svg[^>]*>/, function(a) {
      // set id property of <svg>
      a = a.replace(/ id="[^"]*"/, '');
      a = a.replace(/<svg/, '<svg id="' + id + '"');
      return a;
    });
  }

  function urlToId(url) {
    return sha1(url).substr(0, 12);
  }

  /*
  function convertSvgToSymbol(svg, id) {
    svg = svg.replace(/[^]*<svg/, '<svg');
    // Remove inkscape tags (there were errors caused when namespaces were
    // stripped when converting <svg> to <symbol> ... this may be futile, may
    // have to go back to embedding entire SVG document instead of using symbols)
    svg = svg.replace(/<metadata[^]*?metadata>/, '');
    svg = svg.replace(/<sodipodi[^>]*>/, '');
    // convert <svg> to <symbol>
    svg = svg.replace(/^<svg[^>]*>/, function(a) {
      var viewBox = a.match(/viewBox=".*?"/)[0];
      return '<symbol id="' + id + '" ' + viewBox + '>';
    });
    svg = svg.replace('svg>', 'symbol>');
    return svg;
  }
  */

  //
  function exportSVG(dataset, opts) {
    var namespace = 'xmlns="http://www.w3.org/2000/svg"';
    var defs = [];
    var frame, svg, layers;
    var style = '';

    // kludge for map keys
    if (opts.crisp_paths) {
      style = `
<style>
  path {shape-rendering: crispEdges;}
</style>`;
    }

    // TODO: consider moving this logic to mapshaper-export.js
    if (opts.final) {
      if (dataset.arcs) dataset.arcs.flatten();
    } else {
      dataset = copyDataset(dataset); // Modify a copy of the dataset
    }

    // invert_y setting for screen coordinates and geojson polygon generation
    utils.extend(opts, {invert_y: true});
    frame = getFrameData(dataset, opts);
    fitDatasetToFrame(dataset, frame, opts);
    setCoordinatePrecision(dataset, opts.precision || 0.0001);

    // error if one or more svg_data fields are not present in any layers
    if (opts.svg_data) validateSvgDataFields(dataset.layers, opts.svg_data);

    layers = dataset.layers;
    if (opts.scalebar) {
      layers.push(getScalebarLayer({})); // default options
    }
    svg = layers.map(function(lyr) {
      var obj;
      if (layerHasFurniture(lyr)) {
        obj = exportFurnitureForSVG(lyr, frame, opts);
      } else {
        obj = exportLayerForSVG(lyr, dataset, opts);
      }
      convertPropertiesToDefinitions(obj, defs);
      return stringify(obj);
    }).join('\n');

    if (defs.length > 0) {
      svg = '<defs>\n' + utils.pluck(defs, 'svg').join('') + '</defs>\n' + svg;
    }

    if (svg.includes('xlink:')) {
      namespace += ' xmlns:xlink="http://www.w3.org/1999/xlink"';
    }

    // default line style properties
    var capStyle = opts.default_linecap || 'round';
    var lineProps = `stroke-linecap="${capStyle}" stroke-linejoin="round"`;
    if (svg.includes('stroke-linejoin="miter"')) {
      // the default limit in Illustrator seems to be 10 -- too large for mapping
      // (Mapbox uses 2 as the default in their styles)
      lineProps += ' stroke-miterlimit="2"';
    }
    var template = `<?xml version="1.0"?>
<svg ${namespace} version="1.2" baseProfile="tiny" width="%d" height="%d" viewBox="%s %s %s %s" ${lineProps}>${style}
${svg}
</svg>`;
    svg = utils.format(template, frame.width, frame.height, 0, 0, frame.width, frame.height);
    return [{
      content: svg,
      filename: opts.file || getOutputFileBase(dataset) + '.svg'
    }];
  }

  function exportFurnitureForSVG(lyr, frame, opts) {
    var layerObj = getEmptyLayerForSVG(lyr, opts);
    layerObj.children = importFurniture(getFurnitureLayerData(lyr), frame);
    return layerObj;
  }

  function exportLayerForSVG(lyr, dataset, opts) {
    var layerObj = getEmptyLayerForSVG(lyr, opts);
    layerObj.children = exportSymbolsForSVG(lyr, dataset, opts);
    return layerObj;
  }

  function exportSymbolsForSVG(lyr, dataset, opts) {
    // TODO: convert geojson features one at a time
    var d = utils.defaults({layers: [lyr]}, dataset);
    var geojson = exportDatasetAsGeoJSON(d, opts);
    var features = geojson.features || geojson.geometries || (geojson.type ? [geojson] : []);
    var children = importGeoJSONFeatures(features, opts);
    if (opts.svg_data && lyr.data) {
      addDataAttributesToSVG(children, lyr.data, opts.svg_data);
    }
    return children;
  }

  function validateSvgDataFields(layers, fieldsArg) {
    var missingFields = fieldsArg.reduce(function(memo, field) {
      if (!fieldExists(layers, field)) {
        memo.push(field);
      }
      return memo;
    }, []);

    if (missingFields.length && missingFields.indexOf('*') == -1) {
      stop("Missing data field(s):", missingFields.join(', '));
    }

    function fieldExists(layers, field) {
      return utils.some(layers, function(lyr) {
        return lyr.data && lyr.data.fieldExists(field) || false;
      });
    }
  }

  function addDataAttributesToSVG(children, table, fieldsArg) {
    var allFields = table.getFields();
    var dataFields = fieldsArg.indexOf('*') > -1 ? allFields.concat() : fieldsArg;
    var missingFields = utils.difference(dataFields, allFields);
    if (missingFields.length > 0) {
      dataFields = utils.difference(dataFields, missingFields);
      // stop("Missing data field(s):", missingFields.join(', '));
    }
    var records = table.getRecords();
    var data = exportDataAttributesForSVG(records, dataFields);
    if (children.length != data.length) {
      error("Mismatch between number of SVG symbols and data attributes");
    }
    children.forEach(function(child, i) {
      utils.extend(child.properties || {}, data[i]);
    });
  }

  function exportDataAttributesForSVG(records, fields) {
    var validRxp = /^[a-z_][a-z0-9_-]*$/i;
    var invalidRxp = /^xml/;
    var validFields = fields.filter(function(name) {
      return validRxp.test(name) && !invalidRxp.test(name);
    });
    var invalidFields = utils.difference(fields, validFields);
    if (invalidFields.length > 0) {
      message("Unable to add data-* attributes for field(s):", invalidFields.join(', '));
      message("data-* names should match pattern [a-z_][a-z0-9_-]*");
    }
    return records.map(function(rec) {
      var obj = {};
      for (var i=0; i<validFields.length; i++) {
        obj['data-' + validFields[i].toLowerCase()] =
          validDataAttributeValue(rec[validFields[i]]);
      }
      return obj;
    });
  }

  function validDataAttributeValue(val) {
    // TODO: consider converting some falsy values to empty strings
    // (e.g. null, undefined, NaN)
    return String(val);
  }

  // internal.validDataAttributeNames = function(names) {
  //   return utils.uniqifyNames(names.map(internal.validDataAttributeName));
  // };

  // There are restrictions on data-* attribute names
  // This function modifies names so they can be used
  // See: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/data-*
  // Mapshaper's rules are a bit more restrictive than the spec -- e.g.
  //   the first character after "data-" is restricted to "_" | [a-z]
  //
  // internal.validDataAttributeName = function(name) {
  //   name = name.toLowerCase();
  //   name = name.replace(/[^a-z0-9_-]/g, ''); // accept only these letters
  //   if (/^([0-9-]|xml)/.test(name) || name === '') {
  //     name = '_' + name; // prepend underscore if needed
  //   }
  //   return name;
  // };

  function getEmptyLayerForSVG(lyr, opts) {
    var id = (opts.id_prefix || '') + (lyr.name || utils.getUniqueName('layer'));
    var layerObj = {
      tag: 'g',
      properties: {id: id},
      children: []
    };

    // override default black fill for layers that might have open paths
    // TODO: set fill="none" in SVG symbols, not on the container
    //   (setting fill=none on the container overrides the default black fill
    //   on paths, which may alter the appearance of SVG icons loaded from external URLs).
    if (lyr.geometry_type == 'polyline' || layerHasSvgSymbols(lyr)) {
      layerObj.properties.fill = 'none';
    }

    // add default display properties to line layers
    // (these are overridden by feature-level styles set via -style)
    if (lyr.geometry_type == 'polyline') {
      layerObj.properties.stroke = 'black';
      layerObj.properties['stroke-width'] = 1;
    }


    // add default text properties to layers with labels
    if (layerHasLabels(lyr) || layerHasSvgSymbols(lyr) || layerHasFurniture(lyr)) {
      layerObj.properties['font-family'] = 'sans-serif';
      layerObj.properties['font-size'] = '12';
      layerObj.properties['text-anchor'] = 'middle';
    }

    return layerObj;
  }

  function featureHasSvgSymbol(d) {
    return !!(d && (d['svg-symbol'] || d.r));
  }

  function featureHasLabel(d) {
    var text = d && d['label-text'];
    return text || text === 0; // accept numerical 0 as label text
  }

  function layerHasSvgSymbols(lyr) {
    return lyr.geometry_type == 'point' && lyr.data && lyr.data.fieldExists('svg-symbol');
  }

  function layerHasLabels(lyr) {
    var hasLabels = lyr.geometry_type == 'point' && lyr.data && lyr.data.fieldExists('label-text');
    //if (hasLabels && internal.findMaxPartCount(lyr.shapes) > 1) {
    //  console.error('Multi-point labels are not fully supported');
    //}
    return hasLabels;
  }

  var Svg = /*#__PURE__*/Object.freeze({
    __proto__: null,
    exportSVG: exportSVG,
    exportFurnitureForSVG: exportFurnitureForSVG,
    exportLayerForSVG: exportLayerForSVG,
    validateSvgDataFields: validateSvgDataFields,
    exportDataAttributesForSVG: exportDataAttributesForSVG,
    getEmptyLayerForSVG: getEmptyLayerForSVG,
    featureHasSvgSymbol: featureHasSvgSymbol,
    featureHasLabel: featureHasLabel,
    layerHasSvgSymbols: layerHasSvgSymbols,
    layerHasLabels: layerHasLabels
  });

  // import { isKmzFile } from '../io/mapshaper-file-types';

  function exportKML(dataset, opts) {
    var toKML = require("@placemarkio/tokml").toKML;
    var geojsonOpts = Object.assign({combine_layers: true, geojson_type: 'FeatureCollection'}, opts);
    var geojson = exportDatasetAsGeoJSON(dataset, geojsonOpts);
    var kml = toKML(geojson);
    // TODO: add KMZ output
    // var useKmz = opts.file && isKmzFile(opts.file);
    var ofile = opts.file || getOutputFileBase(dataset) + '.kml';
    return [{
      content: kml,
      filename: ofile
    }];
  }

  function buffersAreIdentical(a, b) {
    var alen = BinArray.bufferSize(a);
    var blen = BinArray.bufferSize(b);
    if (alen != blen) {
      return false;
    }
    for (var i=0; i<alen; i++) {
      if (a[i] !== b[i]) {
        return false;
      }
    }
    return true;
  }

  // Wrapper for DataView class for more convenient reading and writing of
  //   binary data; Remembers endianness and read/write position.
  // Has convenience methods for copying from buffers, etc.
  //
  function BinArray(buf, le) {
    if (utils.isNumber(buf)) {
      buf = new ArrayBuffer(buf);
    } else if (buf instanceof ArrayBuffer) ; else if (typeof B$3 == 'function' && buf instanceof B$3 || buf instanceof Uint8Array) {
      if (buf.buffer && buf.buffer.byteLength == buf.length) {
        buf = buf.buffer;
      } else {
        buf = BinArray.copyToArrayBuffer(buf);
      }
    } else {
      error("BinArray constructor takes an integer, ArrayBuffer or Buffer argument");
    }
    this._buffer = buf;
    this._bytes = new Uint8Array(buf);
    this._view = new DataView(buf);
    this._idx = 0;
    this._le = le !== false;
  }

  BinArray.bufferToUintArray = function(buf, wordLen) {
    if (wordLen == 4) return new Uint32Array(buf);
    if (wordLen == 2) return new Uint16Array(buf);
    if (wordLen == 1) return new Uint8Array(buf);
    error("BinArray.bufferToUintArray() invalid word length:", wordLen);
  };

  BinArray.uintSize = function(i) {
    return i & 1 || i & 2 || 4;
  };

  BinArray.bufferCopy = function(dest, destId, src, srcId, bytes) {
    srcId = srcId || 0;
    bytes = bytes || src.byteLength - srcId;
    if (dest.byteLength - destId < bytes)
      error("Buffer overflow; tried to write:", bytes);

    // When possible, copy buffer data in multi-byte chunks... Added this for faster copying of
    // shapefile data, which is aligned to 32 bits.
    var wordSize = Math.min(BinArray.uintSize(bytes), BinArray.uintSize(srcId),
        BinArray.uintSize(dest.byteLength), BinArray.uintSize(destId),
        BinArray.uintSize(src.byteLength));

    var srcArr = BinArray.bufferToUintArray(src, wordSize),
        destArr = BinArray.bufferToUintArray(dest, wordSize),
        count = bytes / wordSize,
        i = srcId / wordSize,
        j = destId / wordSize;

    while (count--) {
      destArr[j++] = srcArr[i++];
    }
    return bytes;
  };

  BinArray.copyToArrayBuffer = function(src) {
    var n = src.length,
        dest = new ArrayBuffer(n),
        view = new Uint8Array(dest);
    for (var i=0; i<n; i++) {
        view[i] = src[i];
    }
    return dest;
  };

  // Return length in bytes of an ArrayBuffer or Buffer
  //
  BinArray.bufferSize = function(buf) {
    return (buf instanceof ArrayBuffer ?  buf.byteLength : buf.length | 0);
  };

  BinArray.prototype = {
    size: function() {
      return this._buffer.byteLength;
    },

    littleEndian: function() {
      this._le = true;
      return this;
    },

    bigEndian: function() {
      this._le = false;
      return this;
    },

    buffer: function() {
      return this._buffer;
    },

    bytesLeft: function() {
      return this._buffer.byteLength - this._idx;
    },

    skipBytes: function(bytes) {
      this._idx += (bytes + 0);
      return this;
    },

    readUint8: function() {
      return this._bytes[this._idx++];
    },

    writeUint8: function(val) {
      this._bytes[this._idx++] = val;
      return this;
    },

    readInt8: function() {
      return this._view.getInt8(this._idx++);
    },

    writeInt8: function(val) {
      this._view.setInt8(this._idx++, val);
      return this;
    },

    readUint16: function() {
      var val = this._view.getUint16(this._idx, this._le);
      this._idx += 2;
      return val;
    },

    writeUint16: function(val) {
      this._view.setUint16(this._idx, val, this._le);
      this._idx += 2;
      return this;
    },

    readUint32: function() {
      var val = this._view.getUint32(this._idx, this._le);
      this._idx += 4;
      return val;
    },

    writeUint32: function(val) {
      this._view.setUint32(this._idx, val, this._le);
      this._idx += 4;
      return this;
    },

    readInt32: function() {
      var val = this._view.getInt32(this._idx, this._le);
      this._idx += 4;
      return val;
    },

    writeInt32: function(val) {
      this._view.setInt32(this._idx, val, this._le);
      this._idx += 4;
      return this;
    },

    readFloat64: function() {
      var val = this._view.getFloat64(this._idx, this._le);
      this._idx += 8;
      return val;
    },

    writeFloat64: function(val) {
      this._view.setFloat64(this._idx, val, this._le);
      this._idx += 8;
      return this;
    },

    // Returns a Float64Array containing @len doubles
    //
    readFloat64Array: function(len) {
      var bytes = len * 8,
          i = this._idx,
          buf = this._buffer,
          arr;
      // Inconsistent: first is a view, second a copy...
      if (i % 8 === 0) {
        arr = new Float64Array(buf, i, len);
      } else if (buf.slice) {
        arr = new Float64Array(buf.slice(i, i + bytes));
      } else { // ie10, etc
        var dest = new ArrayBuffer(bytes);
        BinArray.bufferCopy(dest, 0, buf, i, bytes);
        arr = new Float64Array(dest);
      }
      this._idx += bytes;
      return arr;
    },

    readUint32Array: function(len) {
      var arr = [];
      for (var i=0; i<len; i++) {
        arr.push(this.readUint32());
      }
      return arr;
    },

    peek: function(i) {
      return this._view.getUint8(i >= 0 ? i : this._idx);
    },

    position: function(i) {
      if (i != null) {
        this._idx = i;
        return this;
      }
      return this._idx;
    },

    readCString: function(fixedLen, asciiOnly) {
      var str = "",
          count = fixedLen >= 0 ? fixedLen : this.bytesLeft();
      while (count > 0) {
        var byteVal = this.readUint8();
        count--;
        if (byteVal == 0) {
          break;
        } else if (byteVal > 127 && asciiOnly) {
          str = null;
          break;
        }
        str += String.fromCharCode(byteVal);
      }

      if (fixedLen > 0 && count > 0) {
        this.skipBytes(count);
      }
      return str;
    },

    writeString: function(str, maxLen) {
      var bytesWritten = 0,
          charsToWrite = str.length,
          cval;
      if (maxLen) {
        charsToWrite = Math.min(charsToWrite, maxLen);
      }
      for (var i=0; i<charsToWrite; i++) {
        cval = str.charCodeAt(i);
        if (cval > 127) {
          // Unicode value beyond ascii range
          cval = '?'.charCodeAt(0);
        }
        this.writeUint8(cval);
        bytesWritten++;
      }
      return bytesWritten;
    },

    writeCString: function(str, fixedLen) {
      var maxChars = fixedLen ? fixedLen - 1 : null,
          bytesWritten = this.writeString(str, maxChars);

      this.writeUint8(0); // terminator
      bytesWritten++;

      if (fixedLen) {
        while (bytesWritten < fixedLen) {
          this.writeUint8(0);
          bytesWritten++;
        }
      }
      return this;
    },

    writeBuffer: function(buf, bytes, startIdx) {
      this._idx += BinArray.bufferCopy(this._buffer, this._idx, buf, startIdx, bytes);
      return this;
    }
  };

  var BinArray$1 = /*#__PURE__*/Object.freeze({
    __proto__: null,
    buffersAreIdentical: buffersAreIdentical,
    BinArray: BinArray
  });

  var Dbf = {};
  var MAX_STRING_LEN = 254;

  Dbf.MAX_STRING_LEN = MAX_STRING_LEN;
  Dbf.convertValueToString = convertValueToString;
  Dbf.convertFieldNames = convertFieldNames;
  Dbf.discoverFieldType = discoverFieldType;
  Dbf.getDecimalFormatter = getDecimalFormatter;
  Dbf.getNumericFieldInfo = getNumericFieldInfo;
  Dbf.truncateEncodedString = truncateEncodedString;
  Dbf.getFieldInfo = getFieldInfo;
  Dbf.exportRecords = exportRecords;

  function BufferPool() {
    var n = 5000,
        pool, i;
    newPool();

    function newPool() {
      pool = new Uint8Array(n);
      i = 0;
    }

    return {
      reserve: function(bytes) {
        if (i + bytes > n) newPool();
        i += bytes;
        return pool.subarray(i - bytes, i);
      },
      putBack: function(bytes) {
        i -= bytes;
      }
    };
  }

  var bufferPool = new BufferPool();

  function exportRecords(records, encoding, fieldOrder) {
    var rows = records.length;
    var fields = findFieldNames(records, fieldOrder);
    var dataEncoding = encoding || 'utf8';
    var headerEncoding = stringIsAscii(fields.join('')) ? 'ascii' : dataEncoding;
    var fieldNames = convertFieldNames(fields, headerEncoding);
    var fieldBuffers = encodeFieldNames(fieldNames, headerEncoding); // array of 11-byte buffers
    var fieldData = fields.map(function(name, i) {
      var info = getFieldInfo(records, name, dataEncoding);
      if (info.warning) {
        message('[' + name + '] ' + info.warning);
      }
      return info;
    });

    var headerBytes = getHeaderSize(fieldData.length),
        recordBytes = getRecordSize(utils.pluck(fieldData, 'size')),
        fileBytes = headerBytes + rows * recordBytes + 1;

    var buffer = new ArrayBuffer(fileBytes);
    var bin = new BinArray(buffer).littleEndian();
    var now = new Date();

    // write header
    bin.writeUint8(3);
    bin.writeUint8(now.getFullYear() - 1900);
    bin.writeUint8(now.getMonth() + 1);
    bin.writeUint8(now.getDate());
    bin.writeUint32(rows);
    bin.writeUint16(headerBytes);
    bin.writeUint16(recordBytes);
    bin.skipBytes(17);
    bin.writeUint8(0); // language flag; TODO: improve this
    bin.skipBytes(2);


    // field subrecords
    fieldData.reduce(function(recordOffset, obj, i) {
      // bin.writeCString(obj.name, 11);
      bin.writeBuffer(fieldBuffers[i], 11, 0);
      bin.writeUint8(obj.type.charCodeAt(0));
      bin.writeUint32(recordOffset);
      bin.writeUint8(obj.size);
      bin.writeUint8(obj.decimals);
      bin.skipBytes(14);
      return recordOffset + obj.size;
    }, 1);

    bin.writeUint8(0x0d); // "field descriptor terminator"
    if (bin.position() != headerBytes) {
      error("Dbf#exportRecords() header size mismatch; expected:", headerBytes, "written:", bin.position());
    }

    records.forEach(function(rec, i) {
      var start = bin.position();
      bin.writeUint8(0x20); // delete flag; 0x20 valid 0x2a deleted
      for (var j=0, n=fieldData.length; j<n; j++) {
        fieldData[j].write(i, bin);
      }
      if (bin.position() - start != recordBytes) {
        error("#exportRecords() Error exporting record:", rec);
      }
    });

    bin.writeUint8(0x1a); // end-of-file

    if (bin.position() != fileBytes) {
      error("Dbf#exportRecords() file size mismatch; expected:", fileBytes, "written:", bin.position());
    }
    return buffer;
  }

  function getHeaderSize(numFields) {
    return 33 + numFields * 32;
  }

  function getRecordSize(fieldSizes) {
    return utils.sum(fieldSizes) + 1; // delete byte plus data bytes
  }

  function initNumericField(info, arr, name) {
    var MAX_FIELD_SIZE = 18,
        data, size;

    data = getNumericFieldInfo(arr, name);
    info.decimals = data.decimals;
    size = Math.max(data.max.toFixed(info.decimals).length,
        data.min.toFixed(info.decimals).length);
    if (size > MAX_FIELD_SIZE) {
      size = MAX_FIELD_SIZE;
      info.decimals -= size - MAX_FIELD_SIZE;
      if (info.decimals < 0) {
        error ("Dbf#getFieldInfo() Out-of-range error.");
      }
    }
    info.size = size;

    var formatter = getDecimalFormatter(size, info.decimals);
    info.write = function(i, bin) {
      var rec = arr[i],
          str = formatter(rec[name]);
      if (str.length < size) {
        str = utils.lpad(str, size, ' ');
      }
      bin.writeString(str, size);
    };
  }

  function initBooleanField(info, arr, name) {
    info.size = 1;
    info.write = function(i, bin) {
      var val = arr[i][name],
          c;
      if (val === true) c = 'T';
      else if (val === false) c = 'F';
      else c = '?';
      bin.writeString(c);
    };
  }

  function initDateField(info, arr, name) {
    info.size = 8;
    info.write = function(i, bin) {
      var d = arr[i][name],
          str;
      if (d instanceof Date === false) {
        str = '00000000';
      } else {
        str = utils.lpad(d.getUTCFullYear(), 4, '0') +
              utils.lpad(d.getUTCMonth() + 1, 2, '0') +
              utils.lpad(d.getUTCDate(), 2, '0');
      }
      bin.writeString(str);
    };
  }

  function convertValueToString(s) {
    return s === undefined || s === null ? '' : String(s);
  }

  function initStringField(info, arr, name, encoding) {
    var formatter = encoding == 'ascii' ? encodeValueAsAscii : getStringWriterEncoded(encoding);
    // Set minimum field size to 1 byte, for interoperability with PostGIS
    // (see https://github.com/mbloch/mapshaper/issues/541)
    var size = 1;
    var truncated = 0;
    var buffers = arr.map(function(rec) {
      var strval = convertValueToString(rec[name]);
      var buf = formatter(strval);
      if (buf.length > MAX_STRING_LEN) {
        if (encoding == 'ascii') {
          buf = buf.subarray(0, MAX_STRING_LEN);
        } else {
          buf = truncateEncodedString(buf, encoding, MAX_STRING_LEN);
        }
        truncated++;
      }
      size = Math.max(size, buf.length);
      return buf;
    });
    info.size = size;
    info.write = function(i, bin) {
      var buf = buffers[i],
          n = Math.min(size, buf.length),
          dest = bin._bytes,
          pos = bin.position(),
          j;
      for (j=0; j<n; j++) {
        dest[j + pos] = buf[j];
      }
      bin.position(pos + size);
    };
    if (truncated > 0) {
      info.warning = 'Truncated ' + truncated + ' string' + (truncated == 1 ? '' : 's') + ' to fit the 254-byte limit';
    }
  }

  // Convert string names to 11-byte buffers terminated by 0
  function encodeFieldNames(names, encoding) {
    return names.map(function(name) {
      var encoded = encodeString(name, encoding);
      var encLen = encoded.length;
      var buf = utils.createBuffer(11);
      for (var i=0; i < 11; i++) {
        buf[i] = i < 10 && encLen >= i - 1 ? encoded[i] : 0;
      }
      return buf;
    });
  }

  // Truncate and dedup field names
  //
  function convertFieldNames(names, encoding) {
    var names2 = getUniqFieldNames(names.map(cleanFieldName), 10, encoding);
    names2.forEach(function(name2, i) {
      if (names[i] != name2) {
        message('Changed field name from "' + names[i] + '" to "' + name2 + '"');
      }
    });
    return names2;
  }

  // Support non-ascii field names
  function cleanFieldName(name) {
    return name.replace(/[-\s]+/g, '_');
  }

  function getFieldInfo(arr, name, encoding) {
    var type = discoverFieldType(arr, name),
        info = {
          type: type,
          decimals: 0
        };
    if (type == 'N') {
      initNumericField(info, arr, name);
    } else if (type == 'C') {
      initStringField(info, arr, name, encoding);
    } else if (type == 'L') {
      initBooleanField(info, arr, name);
    } else if (type == 'D') {
      initDateField(info, arr, name);
    } else {
      // Treat null fields as empty numeric fields; this way, they will be imported
      // again as nulls.
      info.size = 0;
      info.type = 'N';
      if (type) {
        info.warning = 'Unable to export ' + type + '-type data, writing null values';
      }
      info.write = function() {};
    }
    return info;
  }

  function discoverFieldType(arr, name) {
    var val;
    for (var i=0, n=arr.length; i<n; i++) {
      val = arr[i][name];
      if (utils.isString(val)) return "C";
      if (utils.isNumber(val)) return "N";
      if (utils.isBoolean(val)) return "L";
      if (val instanceof Date) return "D";
      if (val) return (typeof val);
    }
    return null;
  }

  function getDecimalFormatter(size, decimals) {
    // TODO: find better way to handle nulls
    var nullValue = ' '; // ArcGIS may use 0
    return function(val) {
      // TODO: handle invalid values better
      var valid = utils.isFiniteNumber(val),
          strval = valid ? val.toFixed(decimals) : String(nullValue);
      return utils.lpad(strval, size, ' ');
    };
  }

  function getNumericFieldInfo(arr, name) {
    var min = 0,
        max = 0,
        k = 1,
        power = 1,
        decimals = 0,
        eps = 1e-15,
        val;
    for (var i=0, n=arr.length; i<n; i++) {
      val = arr[i][name];
      if (!utils.isFiniteNumber(val)) {
        continue;
      }
      if (val < min || val > max) {
        if (val < min) min = val;
        if (val > max) max = val;
        while (Math.abs(val) >= power) {
          power *= 10;
          eps *= 10;
        }
      }
      while (Math.abs(Math.round(val * k) - val * k) > eps) {
        if (decimals == 15) { // dbf limit
          // TODO: round overflowing values ?
          break;
        }
        decimals++;
        eps *= 10;
        k *= 10;
      }
    }
    return {
      decimals: decimals,
      min: min,
      max: max
    };
  }

  // return an array buffer or null if value contains non-ascii chars
  function encodeValueAsAscii(val, strict) {
    var str = String(val),
        n = str.length,
        view = bufferPool.reserve(n),
        i, c;
    for (i=0; i<n; i++) {
      c = str.charCodeAt(i);
      if (c > 127) {
        if (strict) {
          view = null;
          i = 0; // return all bytes to pool
          break;
        }
        c = '?'.charCodeAt(0);
      }
      view[i] = c;
    }
    bufferPool.putBack(n-i);
    return view ? view.subarray(0, i) : null;
  }

  function getStringWriterEncoded(encoding) {
    return function(val) {
      // optimization -- large majority of strings in real-world datasets are
      // ascii. Try (faster) ascii encoding first, fall back to text encoder.
      var buf = encodeValueAsAscii(val, true);
      if (buf === null) {
        buf = encodeString(String(val), encoding);
      }
      return buf;
    };
  }

  // try to remove partial multi-byte characters from the end of an encoded string.
  function truncateEncodedString(buf, encoding, maxLen) {
    var truncated = buf.slice(0, maxLen);
    var len = maxLen;
    var tmp, str;
    while (len > 0 && len >= maxLen - 3) {
      tmp = len == maxLen ? truncated : buf.slice(0, len);
      str = decodeString(tmp, encoding);
      if (str.charAt(str.length-1) != '\ufffd') {
        truncated = tmp;
        break;
      }
      len--;
    }
    return truncated;
  }

  function exportDbf(dataset, opts) {
    return dataset.layers.reduce(function(files, lyr) {
      if (lyr.data) {
        files = files.concat(exportDbfFile(lyr, dataset, opts));
      }
      return files;
    }, []);
  }

  function exportDbfFile(lyr, dataset, opts) {
    var data = lyr.data,
        buf;
    // create empty data table if missing a table or table is being cut out
    if (!data || opts.cut_table || opts.drop_table) {
      data = new DataTable(lyr.shapes ? lyr.shapes.length : 0);
    }
    // dbfs should have at least one column; add id field if none
    if (data.isEmpty()) {
      data.addIdField();
    }
    if (data.exportAsDbf) {
      buf = data.exportAsDbf(opts);
    } else {
      buf = Dbf.exportRecords(data.getRecords(), opts.encoding, opts.field_order);
    }
    if (utils.isInteger(opts.ldid)) {
      new Uint8Array(buf)[29] = opts.ldid; // set language driver id
    }
    // TODO: also export .cpg page
    return [{
      content: buf,
      filename: lyr.name + '.dbf'
    }];
  }

  function exportRecordsAsFixedWidthString(fields, records, opts) {
    var rows = [], col;
    for (var i=0; i<fields.length; i++) {
      col = formatFixedWidthColumn(fields[i], records, opts);
      if (i === 0) {
        rows = col;
      } else for (var j=0; j<rows.length; j++) {
        rows[j] += ' ' + col[j];
      }
    }
    return rows.join('\n');
  }

  function formatFixedWidthColumn(field, records, opts) {
    var arr = [],
        maxLen = field.length,
        n = records.length,
        i, val;
    arr.push(field);
    for (i=0; i<n; i++) {
      val = formatFixedWidthValue(records[i][field], opts);
      maxLen = Math.max(maxLen, val.length);
      arr.push(val);
    }
    for (i=0; i<arr.length; i++) {
      arr[i] = arr[i].padEnd(maxLen, ' ');
    }
    return arr;
  }

  function formatFixedWidthValue(val, opts) {
    // TODO: remove duplication with mapshaper-delim-export.js
    var s;
    if (val == null) {
      s = '';
    } else if (utils.isString(val)) {
      s = val; // TODO: handle wide characters, newlines etc.
    } else if (utils.isNumber(val)) {
      s = opts.decimal_comma ? utils.formatIntlNumber(val) : utils.formatNumber(val);
    } else if (utils.isObject(val)) {
      s = JSON.stringify(val);
    } else {
      s = val + '';
    }
    return s;
  }


  function readFixedWidthRecords(reader, opts) {
    var str = reader.toString(opts.encoding || 'ascii');
    return readFixedWidthRecordsFromString(str);
  }

  function readFixedWidthRecordsFromString(str) {
    var fields = parseFixedWidthInfo(str.substring(0, 2000));
    if (!fields) return [];
    var lines = utils.splitLines(str);
    if (lines[lines.length - 1] === '') lines.pop(); // handle newline at end of string
    var records = [];
    for (var i=1; i<lines.length; i++) {
      records.push(parseFixedWidthLine(lines[i], fields));
    }
    return records;
  }

  function parseFixedWidthInfo(sample) {
    var lines = utils.splitLines(sample);
    if (lines.length > 2) lines.pop(); // remove possible partial line
    var n = getMaxLineLength(lines);
    var headerLine = lines[0];
    var colInfo = [];
    var colStart = 0;
    var inContent = false;
    var inHeader = false;
    var isContentChar, isHeaderChar, isColStart, colEnd;
    for (var i=0; i<=n; i++) {
      isHeaderChar = testContentChar(headerLine, i);
      isContentChar = !testEmptyCol(lines, i);
      isColStart = isHeaderChar && !inHeader;
      if (isColStart && inContent) {
        // all lines should have a space char in the position right before a header starts
        return null;
      }
      if (i == n || i > 0 && isColStart) {
        colEnd = i == n ? undefined : i-1;
        colInfo.push({
          name: readValue$1(headerLine, colStart, colEnd),
          end: colEnd,
          start: colStart
        });
        colStart = i;
      }
      inContent = isContentChar;
      inHeader = isHeaderChar;
    }
    return colInfo.length > 0 ? colInfo : null;
  }

  function getMaxLineLength(lines) {
    var max = 0;
    for (var i=0; i<lines.length; i++) {
      max = Math.max(max, lines[i].length);
    }
    return max;
  }

  function readValue$1(line, start, end) {
    return line.substring(start, end).trim();
  }

  function parseFixedWidthLine(str, fields) {
    var obj = {}, field;
    for (var i=0; i<fields.length; i++) {
      field = fields[i];
      obj[field.name] = readValue$1(str, field.start, field.end);
    }
    return obj;
  }

  function testContentChar(str, i) {
    return i < str.length && str[i] !== ' ';
  }

  // return true iff all samples are blank at index i
  function testEmptyCol(samples, i) {
    var line;
    for (var j=0; j<samples.length; j++) {
      line = samples[j];
      if (testContentChar(line, i)) return false;
    }
    return true;
  }

  // Generate output content from a dataset object
  function exportDelim(dataset, opts) {
    var delim = getExportDelimiter(dataset.info, opts),
        ext = getDelimFileExtension(delim, opts);
    return dataset.layers.reduce(function(arr, lyr) {
      if (lyr.data){
        arr.push({
          // TODO: consider supporting encoding= option
          content: exportLayerAsDSV(lyr, delim, opts),
          filename: (lyr.name || 'output') + '.' + ext
        });
      }
      return arr;
    }, []);
  }

  function exportLayerAsDSV(lyr, delim, optsArg) {
    var opts = optsArg || {};
    var encoding = opts.encoding || 'utf8';
    var records = lyr.data.getRecords();
    var fields = findFieldNames(records, opts.field_order);
    if (delim == ' ') {
      return exportRecordsAsFixedWidthString(fields, records, opts);
    }
    var formatRow = getDelimRowFormatter(fields, delim, opts);
    // exporting utf8 and ascii text as string by default (for now)
    var exportAsString = encodingIsUtf8(encoding) && !opts.to_buffer &&
        (records.length < 10000 || opts.to_string);
    if (exportAsString) {
      return exportRecordsAsString(fields, records, formatRow);
    } else {
      return exportRecordsAsBuffer(fields, records, formatRow, encoding);
    }
  }

  function exportRecordsAsString(fields, records, formatRow) {
    var header = formatHeader(fields, formatRow);
    if (!records.length) return header;
    return header + '\n' + records.map(formatRow).join('\n');
  }

  function exportRecordsAsBuffer(fields, records, formatRow, encoding) {
    var str = formatHeader(fields, formatRow);
    var buffers = [encodeString(str, encoding)];
    var tmp = [];
    var n = records.length;
    var i = 0;
    while (i < n) {
      tmp.push(formatRow(records[i]));
      i++;
      if (i % 1000 === 0 || i == n) {
        str = '\n' + tmp.join('\n');
        tmp = [];
        buffers.push(encodeString(str, encoding));
      }
    }
    return B$3.concat(buffers);
  }

  function formatHeader(fields, formatRow) {
    var rec = fields.reduce(function(memo, f) {
      memo[f] = f;
      return memo;
    }, {});
    return formatRow(rec);
  }

  function getDelimRowFormatter(fields, delim, opts) {
    var formatValue = getDelimValueFormatter(delim, opts);
    return function(rec) {
      return fields.map(function(f) {
        return formatValue(rec[f]);
      }).join(delim);
    };
  }

  function getDelimValueFormatter(delim, opts) {
    var dquoteRxp = new RegExp('["\n\r' + delim + ']');
    var decimalComma = opts && opts.decimal_comma || false;
    function formatString(s) {
      if (dquoteRxp.test(s)) {
        s = '"' + s.replace(/"/g, '""') + '"';
      }
      return s;
    }
    return function(val) {
      var s;
      if (val == null) {
        s = '';
      } else if (utils.isString(val)) {
        s = formatString(val);
      } else if (utils.isNumber(val)) {
        s = decimalComma ? utils.formatIntlNumber(val) : utils.formatNumber(val);
      } else if (utils.isObject(val)) {
        s = formatString(JSON.stringify(val));
      } else {
        s = val + '';
      }
      return s;
    };
  }

  function getExportDelimiter(info, opts) {
    var delim = ','; // default
    var outputExt = opts.file ? getFileExtension(opts.file) : '';
    if (opts.delimiter) {
      delim = opts.delimiter;
    } else if (outputExt == 'tsv') {
      delim = '\t';
    } else if (outputExt == 'csv') {
      delim = ',';
    } else if (info.input_delimiter) {
      delim = info.input_delimiter;
    }
    return delim;
  }

  // If output filename is not specified, use the delimiter char to pick
  // an extension.
  function getDelimFileExtension(delim, opts) {
    var ext = 'txt'; // default
    if (opts.file) {
      ext = getFileExtension(opts.file);
    } else if (delim == '\t') {
      ext = 'tsv';
    } else if (delim == ',') {
      ext = 'csv';
    }
    return ext;
  }

  var DelimExport = /*#__PURE__*/Object.freeze({
    __proto__: null,
    exportDelim: exportDelim,
    exportLayerAsDSV: exportLayerAsDSV,
    getDelimValueFormatter: getDelimValueFormatter
  });

  var ShpType = {
    NULL: 0,
    POINT: 1,
    POLYLINE: 3,
    POLYGON: 5,
    MULTIPOINT: 8,
    POINTZ: 11,
    POLYLINEZ: 13,
    POLYGONZ: 15,
    MULTIPOINTZ: 18,
    POINTM: 21,
    POLYLINEM: 23,
    POLYGONM: 25,
    MULIPOINTM: 28,
    MULTIPATCH: 31 // not supported
  };

  ShpType.isPolygonType = function(t) {
    return t == 5 || t == 15 || t == 25;
  };

  ShpType.isPolylineType = function(t) {
    return t == 3 || t == 13 || t == 23;
  };

  ShpType.isMultiPartType = function(t) {
    return ShpType.isPolygonType(t) || ShpType.isPolylineType(t);
  };

  ShpType.isMultiPointType = function(t) {
    return t == 8 || t == 18 || t == 28;
  };

  ShpType.isZType = function(t) {
    return [11,13,15,18].includes(t);
  };

  ShpType.isMType = function(t) {
    return ShpType.isZType(t) || [21,23,25,28].includes(t);
  };

  ShpType.hasBounds = function(t) {
    return ShpType.isMultiPartType(t) || ShpType.isMultiPointType(t);
  };

  // Convert a dataset to Shapefile files
  function exportShapefile(dataset, opts) {
    return dataset.layers.reduce(function(files, lyr) {
      var prj = exportPrjFile(lyr, dataset);
      files = files.concat(exportShpAndShxFiles(lyr, dataset));
      files = files.concat(exportDbfFile(lyr, dataset, opts));
      if (prj) files.push(prj);
      return files;
    }, []);
  }

  function exportPrjFile(lyr, dataset) {
    var info = dataset.info || {};
    var prj = info.prj;
    if (!prj) {
      try {
        prj = crsToPrj(getDatasetCRS(dataset));
      } catch(e) {}
    }
    if (!prj) {
      message("Unable to generate .prj file for", lyr.name + '.shp');
    }
    return prj ? {
      content: prj,
      filename: lyr.name + '.prj'
    } : null;
  }

  function getShapefileExportType(lyr) {
    var type = lyr.geometry_type;
    var shpType;
    if (type == 'point') {
      shpType = findMaxPartCount(lyr.shapes || []) <= 1 ? ShpType.POINT : ShpType.MULTIPOINT;
    } else if (type == 'polygon') {
      shpType = ShpType.POLYGON;
    } else if (type == 'polyline') {
      shpType = ShpType.POLYLINE;
    } else {
      shpType = ShpType.NULL;
    }
    return shpType;
  }

  function exportShpAndShxFiles(layer, dataset, opts) {
    var shapes = layer.shapes || utils.initializeArray(new Array(getFeatureCount(layer)), null);
    var bounds = new Bounds();
    var shpType = getShapefileExportType(layer);
    var fileBytes = 100;
    var shxBytes = 100 + shapes.length * 8;
    var shxBin = new BinArray(shxBytes).bigEndian().position(100); // jump to record section
    var shpBin;

    // TODO: consider writing records to an expanding buffer instead of generating
    // individual buffers for each record (for large point datasets,
    // creating millions of buffers impacts performance significantly)
    var shapeBuffers = shapes.map(function(shape, i) {
      var pathData = exportPathData(shape, dataset.arcs, layer.geometry_type);
      var rec = exportShpRecord(pathData, i+1, shpType);
      var recBytes = rec.buffer.byteLength;

      // add shx record
      shxBin.writeInt32(fileBytes / 2); // record offset in 16-bit words
      // alternative to below: shxBin.writeBuffer(rec.buffer, 4, 4)
      shxBin.writeInt32(recBytes / 2 - 4); // record content length in 16-bit words

      fileBytes += recBytes;
      if (rec.bounds) bounds.mergeBounds(rec.bounds);
      return rec.buffer;
    });

    // write .shp header section
    shpBin = new BinArray(fileBytes, false)
      .writeInt32(9994)
      .skipBytes(5 * 4)
      .writeInt32(fileBytes / 2)
      .littleEndian()
      .writeInt32(1000)
      .writeInt32(shpType);

    if (bounds.hasBounds()) {
      shpBin.writeFloat64(bounds.xmin || 0) // using 0s as empty value
        .writeFloat64(bounds.ymin || 0)
        .writeFloat64(bounds.xmax || 0)
        .writeFloat64(bounds.ymax || 0);
    } else {
      // no bounds -- assume no shapes or all null shapes -- using 0s as bbox
      shpBin.skipBytes(4 * 8);
    }
    shpBin.skipBytes(4 * 8); // skip Z & M type bounding boxes;

    // write records section of .shp
    shapeBuffers.forEach(function(buf) {
      shpBin.writeBuffer(buf);
    });

    // write .shx header
    shxBin.position(0)
      .writeBuffer(shpBin.buffer(), 100) // copy .shp header to .shx
      .position(24) // substitute shx file size for shp file size
      .writeInt32(shxBytes / 2);

    return [{
        content: shpBin.buffer(),
        filename: layer.name + ".shp"
      }, {
        content: shxBin.buffer(),
        filename: layer.name + ".shx"
      }];
  }

  // Returns an ArrayBuffer containing a Shapefile record for one shape
  //   and the bounding box of the shape.
  // TODO: remove collapsed rings, convert to null shape if necessary
  //
  function exportShpRecord(data, id, shpType) {
    var multiPartType = ShpType.isMultiPartType(shpType),
        singlePointType = !multiPartType && !ShpType.isMultiPointType(shpType),
        isNull = data.pointCount > 0 === false,
        bounds = isNull ? null : data.bounds,
        bin = null;

    if (isNull) {
      bin = new BinArray(12, false)
        .writeInt32(id)
        .writeInt32(2)
        .littleEndian()
        .writeInt32(0);

    } else if (singlePointType) {
      bin = new BinArray(28, false)
        .writeInt32(id)
        .writeInt32(10)
        .littleEndian()
        .writeInt32(shpType)
        .writeFloat64(data.pathData[0].points[0][0])
        .writeFloat64(data.pathData[0].points[0][1]);

    } else {
      var partIndexIdx = 52,
          pointsIdx = multiPartType ? partIndexIdx + 4 * data.pathCount : 48,
          recordBytes = pointsIdx + 16 * data.pointCount,
          pointCount = 0;

      bin = new BinArray(recordBytes, false)
        .writeInt32(id)
        .writeInt32((recordBytes - 8) / 2)
        .littleEndian()
        .writeInt32(shpType)
        .writeFloat64(bounds.xmin)
        .writeFloat64(bounds.ymin)
        .writeFloat64(bounds.xmax)
        .writeFloat64(bounds.ymax);

      if (multiPartType) {
        bin.writeInt32(data.pathCount);
      }

      bin.writeInt32(data.pointCount);
      data.pathData.forEach(function(path, i) {
        if (multiPartType) {
          bin.position(partIndexIdx + i * 4).writeInt32(pointCount);
        }
        bin.position(pointsIdx + pointCount * 16);
        for (var j=0, len=path.points.length; j<len; j++) {
          bin.writeFloat64(path.points[j][0]);
          bin.writeFloat64(path.points[j][1]);
        }
        pointCount += j;
      });
      if (data.pointCount != pointCount) {
        error("Shp record point count mismatch; pointCount:",
            pointCount, "data.pointCount:", data.pointCount);
      }
    }

    return {bounds: bounds, buffer: bin.buffer()};
  }

  var ShpExport = /*#__PURE__*/Object.freeze({
    __proto__: null,
    exportShapefile: exportShapefile
  });

  var TopoJSON = {};

  // Iterate over all arrays of arc is in a geometry object
  // @cb callback: function(ids)
  // callback returns undefined or an array of replacement ids
  //
  TopoJSON.forEachShapePart = function forEachShapePart(obj, cb) {
    var iterators = {
          GeometryCollection: function(o) {o.geometries.forEach(eachGeom);},
          LineString: function(o) {
            var retn = cb(o.arcs);
            if (retn) o.arcs = retn;
          },
          MultiLineString: function(o) {eachMultiPath(o.arcs);},
          Polygon: function(o) {eachMultiPath(o.arcs);},
          MultiPolygon: function(o) {o.arcs.forEach(eachMultiPath);}
        };

    eachGeom(obj);

    function eachGeom(o) {
      if (o.type in iterators) {
        iterators[o.type](o);
      }
    }

    function eachMultiPath(arr) {
      var retn;
      for (var i=0; i<arr.length; i++) {
        retn = cb(arr[i]);
        if (retn) arr[i] = retn;
      }
    }
  };

  TopoJSON.forEachArc = function forEachArc(obj, cb) {
    TopoJSON.forEachShapePart(obj, function(ids) {
      var retn;
      for (var i=0; i<ids.length; i++) {
        retn = cb(ids[i]);
        if (utils.isInteger(retn)) {
          ids[i] = retn;
        }
      }
    });
  };

  function getPresimplifyFunction(width) {
    var quanta = 10000,  // enough resolution for pixel-level detail at 1000px width and 10x zoom
        k = quanta / width;
    return function(z) {
      // could substitute a rounding function with decimal precision
      return z === Infinity ? 0 : Math.ceil(z * k);
    };
  }

  function importMetadata(dataset, obj) {
    if (obj.proj4) {
      setDatasetCrsInfo(dataset, getCrsInfo(obj.proj4));
    }
  }

  function exportMetadata(dataset) {
    var crs = getDatasetCRS(dataset);
    var proj4 = null;
    if (crs) {
      proj4 = crsToProj4(crs);
    }
    return {
      proj4: proj4
    };
  }

  cmd.explodeFeatures = function(lyr, arcs, opts) {
    var properties = lyr.data ? lyr.data.getRecords() : null,
        explodedProperties = properties ? [] : null,
        explodedShapes = [],
        explodedLyr = utils.extend({}, lyr);

    lyr.shapes.forEach(function(shp, shpId) {
      var exploded;
      if (!shp) {
        explodedShapes.push(null);
      } else {
        if (lyr.geometry_type == 'polygon' && shp.length > 1) {
          if (opts && opts.naive) {
            exploded = explodePolygonNaive(shp, arcs);
          } else {
            exploded = explodePolygon(shp, arcs);
          }
        } else {
          exploded = explodeShape(shp);
        }
        utils.merge(explodedShapes, exploded);
      }
      if (explodedProperties !== null) {
        for (var i=0, n=exploded ? exploded.length : 1; i<n; i++) {
          explodedProperties.push(cloneProperties(properties[shpId]));
        }
      }
    });

    explodedLyr.shapes = explodedShapes;
    if (explodedProperties !== null) {
      explodedLyr.data = new DataTable(explodedProperties);
    }

    printMessage(lyr, explodedLyr);

    return explodedLyr;
  };

  function printMessage(pre, post) {
  var n1 = getFeatureCount(pre),
      n2 = getFeatureCount(post),
      msg = utils.format('Exploded %,d feature%s into %,d feature%s',
        n1, utils.pluralSuffix(n1), n2,
        utils.pluralSuffix(n2));
    message(msg);
  }

  function explodeShape(shp) {
    return shp.map(function(part) {
      return [part.concat()];
    });
  }

  function explodePolygon(shape, arcs, reverseWinding) {
    var paths = getPathMetadata(shape, arcs, "polygon");
    var groups = groupPolygonRings(paths, arcs, reverseWinding);
    return groups.map(function(group) {
      return group.map(function(ring) {
        return ring.ids;
      });
    });
  }

  function explodePolygonNaive(shape, arcs) {
    var paths = getPathMetadata(shape, arcs, "polygon");
    return paths.map(function(path) {
      if (path.area < 0) {
        reversePath(path.ids);
      }
      return [path.ids];
    });
  }

  function cloneProperties(obj) {
    return Object.assign({}, obj);
  }

  var Explode = /*#__PURE__*/Object.freeze({
    __proto__: null,
    explodePolygon: explodePolygon
  });

  TopoJSON.getPresimplifyFunction = getPresimplifyFunction;

  function exportTopoJSON(dataset, opts) {
    var extension = '.' + (opts.extension || 'json'),
        needCopy = !opts.final || datasetHasPaths(dataset) && dataset.arcs.getRetainedInterval() > 0,
        stringify = JSON.stringify;

    if (needCopy) {
      dataset = copyDatasetForExport(dataset);
    }

    if (opts.prettify) {
      stringify = getFormattedStringify('coordinates,arcs,bbox,translate,scale'.split(','));
    }

    if (opts.width > 0 || opts.height > 0) {
      opts = utils.defaults({invert_y: true}, opts);
      transformDatasetToPixels(dataset, opts);
    } else if (opts.fit_bbox) {
      transformDatasetToPixels(dataset, {fit_bbox: opts.fit_bbox});
    }

    if (opts.precision) {
      setCoordinatePrecision(dataset, opts.precision);
    }

    if (opts.singles) {
      return splitDataset(dataset).map(function(dataset) {
        return {
          content: stringify(TopoJSON.exportTopology(dataset, opts)),
          filename: (dataset.layers[0].name || 'output') + extension
        };
      });
    } else {
      return [{
        filename: opts.file || getOutputFileBase(dataset) + extension,
        content: stringify(TopoJSON.exportTopology(dataset, opts))
      }];
    }
  }

  // Convert a dataset object to a TopoJSON topology object
  // Careful -- arcs must be a copy if further processing will occur.
  TopoJSON.exportTopology = function(dataset, opts) {
    var topology = {type: "Topology", arcs: []},
        hasPaths = datasetHasPaths(dataset),
        bounds = getDatasetBounds(dataset);

    if (opts.bbox && bounds.hasBounds()) {
      topology.bbox = bounds.toArray();
    }

    if (hasPaths && opts.presimplify && !dataset.arcs.getVertexData().zz) {
      // Calculate simplification thresholds if needed
      cmd.simplify(dataset, opts);
    }
    // auto-detect quantization if arcs are present
    if (!opts.no_quantization && (opts.quantization || hasPaths)) {
      topology.transform = TopoJSON.transformDataset(dataset, bounds, opts);
    }
    if (hasPaths) {
      dissolveArcs(dataset); // dissolve/prune arcs for more compact output
      topology.arcs = TopoJSON.exportArcs(dataset.arcs, bounds, opts);
      if (topology.transform) {
        TopoJSON.deltaEncodeArcs(topology.arcs);
      }
    }

    // export layers as TopoJSON named objects
    topology.objects = dataset.layers.reduce(function(objects, lyr, i) {
      var name = lyr.name || "layer" + (i + 1);
      objects[name] = TopoJSON.exportLayer(lyr, dataset.arcs, opts);
      return objects;
    }, {});

    if (opts.metadata) {
      topology.metadata = exportMetadata(dataset);
    }
    return topology;
  };

  TopoJSON.transformDataset = function(dataset, bounds, opts) {
    var bounds2 = TopoJSON.calcExportBounds(bounds, dataset.arcs, opts),
        fw = bounds.getTransform(bounds2),
        inv = fw.invert();

    function transform(x, y) {
      var p = fw.transform(x, y);
      return [Math.round(p[0]), Math.round(p[1])];
    }

    if (dataset.arcs) {
      dataset.arcs.transformPoints(transform);
    }
    // support non-standard format with quantized arcs and non-quantized points
    if (!opts.no_point_quantization) {
      dataset.layers.filter(layerHasPoints).forEach(function(lyr) {
        transformPointsInLayer(lyr, transform);
      });
    }

    // TODO: think about handling geometrical errors introduced by quantization,
    // e.g. segment intersections and collapsed polygon rings.
    return {
      scale: [inv.mx, inv.my],
      translate: [inv.bx, inv.by]
    };
  };

  // Export arcs as arrays of [x, y] and possibly [z] coordinates
  TopoJSON.exportArcs = function(arcs, bounds, opts) {
    var fromZ = null,
        output = [];
    if (opts.presimplify) {
      fromZ = getPresimplifyFunction(bounds.width());
    }
    arcs.forEach2(function(i, n, xx, yy, zz) {
      var arc = [], p;
      for (var j=i + n; i<j; i++) {
        p = [xx[i], yy[i]];
        if (fromZ) {
          p.push(fromZ(zz[i]));
        }
        arc.push(p);
      }
      output.push(arc.length > 1 ? arc : null);
    });
    return output;
  };

  // Apply delta encoding in-place to an array of topojson arcs
  TopoJSON.deltaEncodeArcs = function(arcs) {
    arcs.forEach(function(arr) {
      var ax, ay, bx, by, p;
      for (var i=0, n=arr.length; i<n; i++) {
        p = arr[i];
        bx = p[0];
        by = p[1];
        if (i > 0) {
          p[0] = bx - ax;
          p[1] = by - ay;
        }
        ax = bx;
        ay = by;
      }
    });
  };

  // Calculate the x, y extents that map to an integer unit in topojson output
  // as a fraction of the x- and y- extents of the average segment.
  TopoJSON.calcExportResolution = function(arcs, k) {
    // TODO: think about the effect of long lines, e.g. from polar cuts.
    var xy = getAvgSegment2(arcs);
    return [xy[0] * k, xy[1] * k];
  };

  // Calculate the bounding box of quantized topojson coordinates using one
  // of several methods.
  TopoJSON.calcExportBounds = function(bounds, arcs, opts) {
    var unitXY, xmax, ymax;
    if (opts.topojson_precision > 0) {
      unitXY = TopoJSON.calcExportResolution(arcs, opts.topojson_precision);
    } else if (opts.quantization > 0) {
      unitXY = [bounds.width() / (opts.quantization-1), bounds.height() / (opts.quantization-1)];
    } else if (opts.precision > 0) {
      unitXY = [opts.precision, opts.precision];
    } else {
      // default -- auto quantization at 0.02 of avg. segment len
      unitXY = TopoJSON.calcExportResolution(arcs, 0.02);
    }
    xmax = Math.ceil(bounds.width() / unitXY[0]) || 0;
    ymax = Math.ceil(bounds.height() / unitXY[1]) || 0;
    return new Bounds(0, 0, xmax, ymax);
  };

  TopoJSON.exportProperties = function(geometries, table, opts) {
    var properties = exportProperties(table, opts),
        ids = exportIds(table, opts);
    geometries.forEach(function(geom, i) {
      if (properties) {
        geom.properties = properties[i];
      }
      if (ids) {
        geom.id = ids[i];
      }
    });
  };

  // Export a mapshaper layer as a TopoJSON GeometryCollection
  TopoJSON.exportLayer = function(lyr, arcs, opts) {
    var n = getFeatureCount(lyr),
        geometries = [],
        exporter = TopoJSON.exporters[lyr.geometry_type] || null,
        shp;
    for (var i=0; i<n; i++) {
      shp = exporter && lyr.shapes[i];
      if (shp) {
        geometries[i] = exporter(shp, arcs, opts);
      } else {
        geometries[i] = {type: null};
      }
    }
    if (lyr.data) {
      TopoJSON.exportProperties(geometries, lyr.data, opts);
    }
    return {
      type: "GeometryCollection",
      geometries: geometries
    };
  };

  TopoJSON.exportPolygonGeom = function(shape, coords, opts) {
    var geom = {};
    shape = filterEmptyArcs(shape, coords);
    if (!shape || shape.length === 0) {
      geom.type = null;
    } else if (shape.length > 1) {
      geom.arcs = explodePolygon(shape, coords, opts.invert_y);
      if (geom.arcs.length == 1) {
        geom.arcs = geom.arcs[0];
        geom.type = "Polygon";
      } else {
        geom.type = "MultiPolygon";
      }
    } else {
      geom.arcs = shape;
      geom.type = "Polygon";
    }
    return geom;
  };

  TopoJSON.exportLineGeom = function(shape, coords) {
    var geom = {};
    shape = filterEmptyArcs(shape, coords);
    if (!shape || shape.length === 0) {
      geom.type = null;
    } else if (shape.length == 1) {
      geom.type = "LineString";
      geom.arcs = shape[0];
    } else {
      geom.type = "MultiLineString";
      geom.arcs = shape;
    }
    return geom;
  };

  TopoJSON.exporters = {
    polygon: TopoJSON.exportPolygonGeom,
    polyline: TopoJSON.exportLineGeom,
    point: GeoJSON.exportPointGeom
  };

  var TopojsonExport = /*#__PURE__*/Object.freeze({
    __proto__: null,
    exportTopoJSON: exportTopoJSON
  });

  function importJSONTable(arr) {
    fixInconsistentFields(arr);
    return {
      layers: [{
        data: new DataTable(arr)
      }],
      info: {}
    };
  }

  function exportJSON(dataset, opts) {
    return dataset.layers.reduce(function(arr, lyr) {
      if (lyr.data){
        arr.push({
          content: exportJSONTable(lyr, opts),
          filename: (lyr.name || 'output') + '.json'
        });
      }
      return arr;
    }, []);
  }

  function exportJSONTable(lyr, opts) {
    opts = opts || {};
    var records = lyr.data.getRecords();
    if (opts.ndjson) {
      return records.map(stringifyAsNDJSON).join('\n');
    }
    if (opts.prettify) {
      return getFormattedStringify([])(records);
    }
    return JSON.stringify(records);
  }

  var JsonTable = /*#__PURE__*/Object.freeze({
    __proto__: null,
    importJSONTable: importJSONTable,
    exportJSON: exportJSON,
    exportJSONTable: exportJSONTable
  });

  function getOutputFormat(dataset, opts) {
    var outFile = opts.file || null,
        inFmt = dataset.info && dataset.info.input_formats && dataset.info.input_formats[0],
        outFmt = null;

    // if user has specified a format, use that
    if (opts.format) {
      return opts.format;
    }

    // if an output filename is given, try to infer format from filename etc.
    if (outFile) {
      outFmt = inferOutputFormat(outFile, inFmt);
    } else if (inFmt) {
      outFmt = inFmt;
    }

    if (outFmt == 'json' && datasetHasGeometry(dataset)) {
      // special case: inferred output format is a json table (either because
      // the output file has a .json extension or because the input file was a
      // json table), but the output dataset contains shapes
      outFmt = 'geojson';
    }

    return outFmt || null;
  }

  // Infer output format by considering file name and (optional) input format
  function inferOutputFormat(file, inputFormat) {
    var ext = getFileExtension(file).toLowerCase(),
        format = null;
    if (ext == 'gz') {
      return inferOutputFormat(replaceFileExtension(file, ''), inputFormat);
    } else if (ext == PACKAGE_EXT) {
      format = PACKAGE_EXT;
    } else if (ext == 'shp') {
      format = 'shapefile';
    } else if (ext == 'dbf') {
      format = 'dbf';
    } else if (ext == 'svg') {
      format = 'svg';
    } else if (ext == 'kml' || ext == 'kmz') {
      format = 'kml';
    } else if (/json$/.test(ext)) {
      format = 'geojson';
      if (ext == 'topojson' || inputFormat == 'topojson' && ext != 'geojson') {
        format = 'topojson';
      } else if (ext == 'json' && inputFormat == 'json') {
        // .json -> json table is not always the best inference...
        // additional logic should be applied downstream
        format = 'json'; // JSON table
      }
    } else if (couldBeDsvFile(file)) {
      format = 'dsv';
    } else if (inputFormat) {
      format = inputFormat;
    }
    return format;
  }

  var OutputFormat = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getOutputFormat: getOutputFormat,
    inferOutputFormat: inferOutputFormat
  });

  // @targets - non-empty output from Catalog#findCommandTargets()
  //
  async function exportTargetLayers(targets, opts) {
    // convert target fmt to dataset fmt
    var datasets = targets.map(function(target) {
      return utils.defaults({layers: target.layers}, target.dataset);
    });
    return exportDatasets(datasets, opts);
  }

  //
  //
  async function exportDatasets(datasets, opts) {
    var format = getOutputFormat(datasets[0], opts);
    var files;
    if (format == PACKAGE_EXT) {
      opts = utils.defaults({compact: true}, opts);
      return exportPackedDatasets(datasets, opts);
    }
    if (format == 'kml' || format == 'svg' || format == 'topojson' || format == 'geojson' && opts.combine_layers) {
      // multi-layer formats: combine multiple datasets into one
      if (datasets.length > 1) {
        datasets = [mergeDatasetsForExport(datasets)];
        if (format == 'topojson') {
          // Build topology, in case user has loaded several
          // files derived from the same source, with matching coordinates
          // (Downsides: useless work if geometry is unrelated;
          // could create many small arcs if layers are partially related)
          buildTopology(datasets[0]);
        }
        // KLUDGE let exporter know that copying is not needed
        // (because shape data was deep-copied during merge)
        opts = utils.defaults({final: true}, opts);
      }
    } else {
      datasets = datasets.map(copyDatasetForRenaming);
      assignUniqueLayerNames2(datasets);
    }
    files = datasets.reduce(function(memo, dataset) {
      if (runningInBrowser()) {
        utils.sortOn(dataset.layers, 'menu_order', true);
      } else {
        // kludge to export layers in order that target= option or previous
        // -target command matched them (useful mainly for SVG output)
        // target_id was assigned to each layer by findCommandTargets()
        utils.sortOn(dataset.layers, 'target_id', true);
      }
      return memo.concat(exportFileContent(dataset, opts));
    }, []);
    // need unique names for multiple output files
    assignUniqueFileNames(files);

    if (opts.gzip) {
      files.forEach(function(obj) {
        obj.filename += '.gz';
        obj.content = gzipSync(obj.content);
      });
    }
    return files;
  }

  // Return an array of objects with "filename" and "content" members.
  //
  function exportFileContent(dataset, opts) {
    var outFmt = opts.format = getOutputFormat(dataset, opts),
        exporter = exporters[outFmt],
        files = [];

    if (!outFmt) {
      error("Missing output format");
    } else if (!exporter) {
      error("Unknown output format:", outFmt);
    }

    // shallow-copy dataset and layers, so layers can be renamed for export
    dataset = utils.defaults({
      layers: dataset.layers.map(function(lyr) {return utils.extend({}, lyr);})
    }, dataset);

    // Adjust layer names, so they can be used as output file names
    // (except for multi-layer formats TopoJSON, SVG, KML)
    if (opts.file && outFmt != 'topojson' && outFmt != 'svg'&& outFmt != 'kml') {
      dataset.layers.forEach(function(lyr) {
        lyr.name = getFileBase(opts.file);
      });
    }
    assignUniqueLayerNames(dataset.layers);

    // apply coordinate precision, except:
    //   svg precision is applied by the SVG exporter, after rescaling
    //   GeoJSON precision is applied by the exporter, to handle default precision
    //   TopoJSON precision is applied to avoid redundant copying
    if (opts.precision && outFmt != 'svg' && outFmt != 'geojson' && outFmt != 'topojson') {
      dataset = copyDatasetForExport(dataset);
      setCoordinatePrecision(dataset, opts.precision);
    }

    if (opts.cut_table) {
      files = exportDataTables(dataset.layers).concat(files);
    }

    if (opts.extension) {
      opts.extension = fixFileExtension(opts.extension);
    }

    validateLayerData(dataset.layers);

    files = exporter(dataset, opts).concat(files);
    // If rounding or quantization are applied during export, bounds may
    // change somewhat... consider adding a bounds property to each layer during
    // export when appropriate.
    if (opts.bbox_index) {
      files.push(createIndexFile(dataset));
    }

    validateFileNames(files);
    return files;
  }

  var exporters = {
    // [PACKAGE_EXT]: exportPackedDatasets, // handled as a special case
    geojson: exportGeoJSON2,
    topojson: exportTopoJSON,
    shapefile: exportShapefile,
    dsv: exportDelim,
    dbf: exportDbf,
    json: exportJSON,
    svg: exportSVG,
    kml: exportKML
  };


  // Generate json file with bounding boxes and names of each export layer
  // TODO: consider making this a command, or at least make format settable
  //
  function createIndexFile(dataset) {
    var index = dataset.layers.map(function(lyr) {
      var bounds = getLayerBounds(lyr, dataset.arcs);
      return {
        bbox: bounds.toArray(),
        name: lyr.name
      };
    });

    return {
      content: JSON.stringify(index),
      filename: "bbox-index.json"
    };
  }

  // Throw errors for various error conditions
  function validateLayerData(layers) {
    layers.forEach(function(lyr) {
      if (!lyr.geometry_type) {
        // allowing data-only layers
        if (lyr.shapes && utils.some(lyr.shapes, function(o) {
          return !!o;
        })) {
          error("A layer contains shape records and a null geometry type");
        }
      } else {
        if (!utils.contains(['polygon', 'polyline', 'point'], lyr.geometry_type)) {
          error ("A layer has an invalid geometry type:", lyr.geometry_type);
        }
        if (!lyr.shapes) {
          error ("A layer is missing shape data");
        }
      }
    });
  }

  function validateFileNames(files) {
    var index = {};
    files.forEach(function(file, i) {
      var filename = file.filename;
      if (!filename) error("Missing a filename for file" + i);
      if (filename in index) error("Duplicate filename", filename);
      index[filename] = true;
    });
  }

  function assignUniqueLayerNames(layers) {
    var names = layers.map(function(lyr) {
      return lyr.name || "layer";
    });
    var uniqueNames = utils.uniqifyNames(names);
    layers.forEach(function(lyr, i) {
      lyr.name = uniqueNames[i];
    });
  }

  // Assign unique layer names across multiple datasets
  function assignUniqueLayerNames2(datasets) {
    var layers = datasets.reduce(function(memo, dataset) {
      return memo.concat(dataset.layers);
    }, []);
    assignUniqueLayerNames(layers);
  }

  function assignUniqueFileNames(output) {
    var names = output.map(function(o) {return o.filename;});
    var uniqnames = utils.uniqifyNames(names, formatVersionedFileName);
    output.forEach(function(o, i) {o.filename = uniqnames[i];});
  }

  // TODO: remove this -- format=json creates the same output
  //   (but need to make sure there's a way to prevent names of json data files
  //    from colliding with names of GeoJSON or TopoJSON files)
  function exportDataTables(layers, opts) {
    var tables = [];
    layers.forEach(function(lyr) {
      if (lyr.data) {
        tables.push({
          content: JSON.stringify(lyr.data),
          filename: (lyr.name ? lyr.name + '-' : '') + 'table.json'
        });
      }
    });
    return tables;
  }

  function formatVersionedFileName(filename, i) {
    var parts = filename.split('.');
    var ext, base;
    if (parts.length < 2) {
      return utils.formatVersionedName(filename, i);
    }
    ext = parts.pop();
    base = parts.join('.');
    return utils.formatVersionedName(base, i) + '.' + ext;
  }

  function fixFileExtension(ext, fmt) {
    // TODO: use fmt to validate
    return ext.replace(/^\.+/, '');
  }

  var Export = /*#__PURE__*/Object.freeze({
    __proto__: null,
    exportTargetLayers: exportTargetLayers,
    exportFileContent: exportFileContent,
    assignUniqueLayerNames: assignUniqueLayerNames,
    assignUniqueFileNames: assignUniqueFileNames,
    formatVersionedFileName: formatVersionedFileName
  });

  function readFirstChars(reader, n) {
    return bufferToString(reader.readSync(0, Math.min(n || 1000, reader.size())));
  }

  // Wraps a BufferReader or FileReader with an API that keeps track of position in the file
  function Reader2(reader) {
    var offs = 0; // read-head position in bytes

    this.position = function() {return offs;};

    this.remaining = function() {
      return Math.max(reader.size() - offs, 0);
    };

    this.advance = function(i) {
      offs += i;
    };

    this.readSync = function() {
      return reader.readSync(offs);
    };

    this.expandBuffer = function() {
      reader.expandBuffer();
    };
  }

  // Same interface as FileReader, for reading from a Buffer or ArrayBuffer instead of a file.
  function BufferReader(src) {
    var bufSize = src.byteLength || src.length,
        binArr, buf;

    this.readToBinArray = function(start, length) {
      if (bufSize < start + length) {
        error("Out-of-range error");
      }
      if (!binArr) binArr = new BinArray(src);
      binArr.position(start);
      return binArr;
    };

    this.toString = function(enc) {
      return bufferToString(buffer(), enc);
    };

    this.readSync = function(start, length) {
      // TODO: consider using a default length like FileReader
      return buffer().slice(start, length ? start + length : bufSize);
    };

    function buffer() {
      if (!buf) {
        // buf = (src instanceof ArrayBuffer) ? utils.createBuffer(src) : src;
        buf = utils.toBuffer(src);
      }
      return buf;
    }

    this.findString = FileReader.prototype.findString;
    this.expandBuffer = function() {return this;};
    this.size = function() {return bufSize;};
    this.close = function() {};
  }

  function FileReader(path, opts) {
    var fs = require$1('fs'),
        fileLen = fs.statSync(path).size,
        DEFAULT_CACHE_LEN = opts && opts.cacheSize || 0x1000000, // 16MB
        DEFAULT_BUFFER_LEN = opts && opts.bufferSize || 0x40000, // 256K
        fd, cacheOffs, cache, binArr;
    // kludge to let us check if input files are being overwritten
    (getStashedVar('input_files') || []).push(path);

    // Double the default size of the Buffer returned by readSync()
    this.expandBuffer = function() {
      DEFAULT_BUFFER_LEN *= 2;
      if (DEFAULT_BUFFER_LEN * 2 > DEFAULT_CACHE_LEN) {
        // Keep the file cache larger than the default buffer size.
        // This fixes a performance bug caused when the size of the buffer returned by
        // readSync() grows as large as the file cache, causing each subsequent
        // call to readSync() to trigger a call to fs.readFileSync()
        DEFAULT_CACHE_LEN = DEFAULT_BUFFER_LEN * 2;
      }
      return this;
    };

    // Read to BinArray (for compatibility with ShpReader)
    this.readToBinArray = function(start, length) {
      if (updateCache(start, length)) {
        binArr = new BinArray(cache);
      }
      binArr.position(start - cacheOffs);
      return binArr;
    };

    // Returns a Buffer containing a string of bytes read from the file
    // start: file offset of the first byte
    // length: (optional) length of the returned Buffer
    this.readSync = function(start, length) {
      if (length > 0 === false) {
        // use default size if length is not specified
        length = DEFAULT_BUFFER_LEN;
      }

      if (start + length > fileLen) {
        length = fileLen - start; // truncate at eof
      }
      if (length === 0) {
        return utils.createBuffer(0); // kludge to allow reading up to eof
      }
      updateCache(start, length);
      return cache.slice(start - cacheOffs, start - cacheOffs + length);
    };

    this.size = function() {
      return fileLen;
    };

    this.toString = function(enc) {
      // TODO: use fd
      return cli.readFile(path, enc || 'utf8');
    };

    this.close = function() {
      if (fd) {
        fs.closeSync(fd);
        fd = null;
        cache = null;
      }
    };

    // Update the file cache (if necessary) so that a given range of bytes is available.
    // Receive: offset and length of byte string that must be read
    // Returns: true if cache was updated, or false
    function updateCache(fileOffs, bytesNeeded) {
      var headroom = fileLen - fileOffs,
          bytesRead, bytesToRead;
      if (headroom < bytesNeeded || headroom < 0) {
        error("Tried to read past end-of-file");
      }
      if (cache && fileOffs >= cacheOffs && cacheOffs + cache.length >= fileOffs + bytesNeeded) {
        // cache contains enough data to satisfy the request (no need to read from disk)
        return false;
      }
      bytesToRead = Math.max(DEFAULT_CACHE_LEN, bytesNeeded);
      if (headroom < bytesToRead) {
        bytesToRead = headroom;
      }
      if (!cache || bytesToRead != cache.length) {
        cache = utils.createBuffer(bytesToRead);
      }
      if (!fd) {
        fd = fs.openSync(path, 'r');
      }
      bytesRead = fs.readSync(fd, cache, 0, bytesToRead, fileOffs);
      cacheOffs = fileOffs;
      if (bytesRead != bytesToRead) error("Error reading file");
      return true;
    }
  }

  FileReader.prototype.findString = function (str, maxLen) {
    var len = Math.min(this.size(), maxLen || this.size());
    var buf = this.readSync(0, len);
    var strLen = str.length;
    var n = buf.length - strLen;
    var firstByte = str.charCodeAt(0);
    var i;
    for (i=0; i < n; i++) {
      if (buf[i] == firstByte && buf.toString('utf8', i, i + strLen) == str) {
        return {
          offset: i + strLen,
          text: buf.toString('utf8', 0, i)
        };
      }
    }
    return null;
  };

  var FileReader$1 = /*#__PURE__*/Object.freeze({
    __proto__: null,
    readFirstChars: readFirstChars,
    Reader2: Reader2,
    BufferReader: BufferReader,
    FileReader: FileReader
  });

  // Read and parse a DSV file
  // This version performs field filtering before fields are extracted (faster)
  // (tested with a 40GB CSV)
  //
  // TODO: confirm compatibility with all supported encodings
  function readDelimRecords(reader, delim, optsArg) {
    var opts = optsArg || {};
    if (delim == ' ') return readFixedWidthRecords(reader, opts);
    var reader2 = new Reader2(reader),
        headerStr = readLinesAsString(reader2, getDelimHeaderLines(opts), opts.encoding),
        header = parseDelimHeaderSection(headerStr, delim, opts),
        convertRowArr = getRowConverter(header.import_fields),
        batchSize = opts.batch_size || 1000,
        records = [],
        str, batch;
    if (header.import_fields.length === 0) return []; // e.g. empty file
    // read in batches (faster than line-by-line)
    while ((str = readLinesAsString(reader2, batchSize, opts.encoding))) {
      batch = parseDelimText(str, delim, convertRowArr, header.column_filter || false, header.row_filter || false);
      records.push.apply(records, batch);
      if (opts.csv_lines && records.length >= opts.csv_lines) {
        return records.slice(0, opts.csv_lines);
      }
    }
    return records;
  }

  // Fallback for readDelimRecords(), for encodings that do not use ascii values
  // for delimiter characters and newlines. Input size is limited by the maximum
  // string size.
  function readDelimRecordsFromString(str, delim, opts) {
    if (delim == ' ') return readFixedWidthRecordsFromString(str);
    var header = parseDelimHeaderSection(str, delim, opts);
    if (header.import_fields.length === 0 || !header.remainder) return [];
    var convert = getRowConverter(header.import_fields);
    var records = parseDelimText(header.remainder, delim, convert, header.column_filter, header.row_filter);
    if (opts.csv_lines > 0) {
      // TODO: don't parse unneeded rows
      records = records.slice(0, opts.csv_lines);
    }
    return records;
  }

  // Get index in string of the nth line
  // line numbers are 1-based (first line is 1)
  function indexOfLine(str, nth) {
    var rxp = /\r\n|[\r\n]|.$/g; // dot prevents matching end of string twice
    var i = 1;
    if (nth === 1) return 0;
    if (nth > 1 === false) return -1;
    while (rxp.exec(str)) {
      i++;
      if (i < nth === false) return rxp.lastIndex;
    }
    return -1;
  }

  function getDelimHeaderLines(opts) {
    var skip = opts.csv_skip_lines || 0;
    if (!opts.csv_field_names) skip++;
    return skip;
  }

  // Adapted from https://github.com/d3/d3-dsv
  function getRowConverter(fields) {
    return new Function('arr', 'return {' + fields.map(function(name, i) {
      return JSON.stringify(name) + ': arr[' + i + '] || ""';
    }).join(',') + '}');
  }

  function parseDelimHeaderSection(str, delim, opts) {
    var nodata = {headers: [], import_fields: []},
        retn = {},
        i;
    str = str || '';
    if (opts.csv_skip_lines > 0) {
      i = indexOfLine(str, opts.csv_skip_lines + 1);
      if (i === -1) return nodata;
      str = str.substr(i);
    }
    if (opts.csv_field_names) {
      retn.headers = opts.csv_field_names;
    } else {
      i = indexOfLine(str, 2);
      if (i === -1) return nodata;
      retn.headers = parseDelimText(str.slice(0, i), delim)[0];
      str = str.substr(i);
    }
    if (opts.csv_dedup_fields) {
      retn.headers = utils.uniqifyNames(retn.headers);
    }
    if (opts.csv_filter) {
      retn.row_filter = getDelimRecordFilterFunction(opts.csv_filter);
    }
    if (opts.csv_fields) {
      retn.column_filter = getDelimFieldFilter(retn.headers, opts.csv_fields);
      retn.import_fields = retn.headers.filter(function(name, i) {return retn.column_filter(i);});
    } else {
      retn.import_fields = retn.headers;
    }
    retn.remainder = str;
    return retn;
  }

  // Returns a function for filtering records
  // TODO: look into using more code from standard expressions.
  function getDelimRecordFilterFunction(expression) {
    var rowFilter = compileExpressionToFunction(expression, {returns: true});
    var ctx = getBaseContext();
    return function(rec) {
      var val;
      try {
        val = rowFilter.call(null, rec, ctx);
      } catch(e) {
        stop(e.name, "in expression [" + expression + "]:", e.message);
      }
      if (val !== true && val !== false) {
        stop("Filter expression must return true or false");
      }
      return val;
    };
  }

  // Returns a function for filtering fields by column index
  // The function returns true for retained fields and false for excluded fields
  function getDelimFieldFilter(header, fieldsToKeep) {
    var index = utils.arrayToIndex(fieldsToKeep);
    var map = header.map(function(name) {
      return name in index;
    });
    var missing = utils.difference(fieldsToKeep, header);
    if (missing.length > 0) {
      var foundStr = [''].concat(header).join('\n  ');
      var missingStr = [''].concat(missing).join('\n  ');
      stop('csv-fields option has', missing.length == 1 ? 'a name' : missing.length + ' names',  'not found in the file\nFields:', foundStr, '\nMissing:', missingStr);
    }
    return function(colIdx) {
      return map[colIdx];
    };
  }

  function readLinesAsString(reader, lines, encoding) {
    var buf = reader.readSync();
    var retn = readLinesFromBuffer(buf, lines);
    var str;
    if (retn.bytesRead == buf.length && retn.bytesRead < reader.remaining()) {
      // buffer overflow -- enlarge buffer and read lines again
      reader.expandBuffer();
      return readLinesAsString(reader, lines, encoding);
    }
    // str = retn.bytesRead > 0 ? retn.buffer.toString('ascii', 0, retn.bytesRead) : '';
    str = retn.bytesRead > 0 ? decodeString(retn.buffer, encoding) : '';
    if (reader.position() === 0) {
     str = trimBOM(str);
    }
    reader.advance(retn.bytesRead);
    return str;
  }

  function readLinesFromBuffer(buf, linesToRead) {
    var CR = 13, LF = 10, DQUOTE = 34,
        inQuotedText = false,
        lineCount = 0,
        bufLen = buf.length,
        i, c;

    lineCount++;
    for (i=0; i < bufLen && lineCount <= linesToRead; i++) {
      c = buf[i];
      if (c == DQUOTE) {
        inQuotedText = !inQuotedText;
      } else if ((c == CR || c == LF) && !inQuotedText) {
        if (c == CR && i + 1 < bufLen && buf[i + 1] == LF) {
          // first half of CRLF pair: advance one byte
          i++;
        }
        lineCount++;
      }
    }
    return {
      bytesRead: i,
      buffer: buf.slice(0, i)
    };
  }

  // Convert a string of CSV data into an array of data records
  // convert: optional function for converting an array record to an object record (values indexed by field names)
  // colFilter: optional function for filtering columns by numerical column id (0-based); accepts an array record and an id
  // rowFilter: optional function for filtering rows; accepts a record in object format
  function parseDelimText(text, delim, convert, colFilter, rowFilter) {
    var CR = 13, LF = 10, DQUOTE = 34,
        DELIM = delim.charCodeAt(0),
        inQuotedText = false,
        capturing = false,
        srcCol = -1,
        records = [],
        fieldStart, i, c, len, record;

    if (!convert) convert = function(d) {return d;};

    function endLine() {
      var rec = convert ? convert(record) : record;
      if (!rowFilter || rowFilter(rec)) records.push(rec);
      srcCol = -1;
    }

    function startFieldAt(j) {
      fieldStart = j;
      srcCol++;
      if (srcCol === 0) record = [];
      if (!colFilter || colFilter(srcCol)) {
        capturing = true;
      }
    }

    function captureField(start, end) {
      var s;
      if (!capturing) return;
      capturing = false;
      if (start === end) {
        s = '';
      } else if (text.charCodeAt(start) == DQUOTE) {
        s = text.slice(start+1, end-1).replace(/""/g, '"');
      } else {
        s = text.slice(start, end);
      }
      record.push(s);
    }

    startFieldAt(0);
    for (i=0, len=text.length; i < len; i++) {
      c = text.charCodeAt(i);
      if (c == DQUOTE) {
        inQuotedText = !inQuotedText;
      } else if (inQuotedText) ; else if (c == DELIM) {
        captureField(fieldStart, i);
        startFieldAt(i + 1);
      } else if (c == CR || c == LF) {
        captureField(fieldStart, i);
        endLine();
        if (c == CR && text.charCodeAt(i+1) == LF) {
          i++; // first half of CRLF pair; skip a char
        }
        if (i + 1 < len) startFieldAt(i+1);
      }
    }

    if (srcCol > -1) { // finish last line (if file ends without newline)
      if (capturing) captureField(fieldStart, i);
      endLine();
    }

    return records;
  }

  var DelimReader = /*#__PURE__*/Object.freeze({
    __proto__: null,
    readDelimRecords: readDelimRecords,
    readDelimRecordsFromString: readDelimRecordsFromString,
    indexOfLine: indexOfLine,
    getRowConverter: getRowConverter,
    parseDelimHeaderSection: parseDelimHeaderSection,
    getDelimFieldFilter: getDelimFieldFilter,
    readLinesAsString: readLinesAsString,
    parseDelimText: parseDelimText
  });

  function detectEncodingFromBOM(bytes) {
    // utf8 EF BB BF
    // utf16be FE FF
    // utf16le FF FE
    var n = bytes.length;
    if (n >= 2 && bytes[0] == 0xFE && bytes[1] == 0xFF) return 'utf16be';
    if (n >= 2 && bytes[0] == 0xFF && bytes[1] == 0xFE) return 'utf16le';
    if (n >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF) return 'utf8';
    return '';
  }

  // Try to detect the encoding of some sample text.
  // Returns an encoding name or null.
  // @samples Array of buffers containing sample text fields
  // TODO: Improve reliability and number of detectable encodings.
  function detectEncoding(samples) {
    var encoding = null;
    var utf8 = looksLikeUtf8(samples);
    var win1252 = looksLikeWin1252(samples);
    if (utf8 == 2 || utf8 > win1252) {
      encoding = 'utf8';
    } else if (win1252 > 0) {
      encoding = 'win1252';
    } else {
      encoding = 'latin1'; // the original Shapefile encoding, using as an (imperfect) fallback
    }

    return {
      encoding: encoding,
      confidence: Math.max(utf8, win1252)
    };
  }

  // Convert an array of text samples to a single string using a given encoding
  function decodeSamples(enc, samples) {
    return samples.map(function(buf) {
      return decodeString(buf, enc).trim();
    }).join('\n');
  }

  // Win1252 is the same as Latin1, except it replaces a block of control
  // characters with n-dash, Euro and other glyphs. Encountered in-the-wild
  // in Natural Earth (airports.dbf uses n-dash).
  //
  // Quick-and-dirty win1251 detection: decoded string contains mostly common ascii
  // chars and almost no chars other than word chars + punctuation.
  // This excludes encodings like Greek, Cyrillic or Thai, but
  // is susceptible to false positives with encodings like codepage 1250 ("Eastern
  // European").
  //
  function looksLikeWin1252(samples) {
        //common l.c. ascii chars
    var ascii = 'abcdefghijklmnopqrstuvwxyz0123456789.()\'"?+-\n,:;/|_$% ',
        // common extended + NBS (found in the wild)
        extended = 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ°–±’‘' + '\xA0',
        str = decodeSamples('win1252', samples),
        asciiScore = getCharScore(str, ascii),
        totalScore = getCharScore(str, extended + ascii);
    return totalScore > 0.98 && asciiScore >= 0.8 && 2 ||
      totalScore > 0.97 && asciiScore >= 0.6 && 1 || 0;
  }

  // Reject string if it contains the "replacement character" after decoding to UTF-8
  function looksLikeUtf8(samples) {
    // Remove the byte sequence for the utf-8-encoded replacement char before decoding,
    // in case the file is in utf-8, but contains some previously corrupted text.
    // samples = samples.map(internal.replaceUtf8ReplacementChar);
    var str = decodeSamples('utf8', samples);
    var count = (str.match(/\ufffd/g) || []).length;
    var score = 1 - count / str.length;
    return score == 1 && 2 || score > 0.97 && 1 || 0;
  }

  // function replaceUtf8ReplacementChar(buf) {
  //   var isCopy = false;
  //   for (var i=0, n=buf.length; i<n; i++) {
  //     // Check for UTF-8 encoded replacement char (0xEF 0xBF 0xBD)
  //     if (buf[i] == 0xef && i + 2 < n && buf[i+1] == 0xbf && buf[i+2] == 0xbd) {
  //       if (!isCopy) {
  //         buf = utils.createBuffer(buf);
  //         isCopy = true;
  //       }
  //       buf[i] = buf[i+1] = buf[i+2] = 63; // ascii question mark
  //     }
  //   }
  //   return buf;
  // }

  // Calc percentage of chars in a string that are present in a second string
  // @chars String of chars to look for in @str
  function getCharScore(str, chars) {
    var index = {},
        count = 0;
    str = str.toLowerCase();
    for (var i=0, n=chars.length; i<n; i++) {
      index[chars[i]] = 1;
    }
    for (i=0, n=str.length; i<n; i++) {
      count += index[str[i]] || 0;
    }
    return count / str.length;
  }

  // Convert a string containing delimited text data into a dataset object
  function importDelim(str, opts) {
    return importDelim2({content: str}, opts);
  }

  // Convert a string, buffer or file containing delimited text into a dataset obj.
  function importDelim2(data, opts) {
    // TODO: remove duplication with importJSON()
    var readFromFile = !data.content && data.content !== '',
        content = data.content,
        reader, records, delimiter, table, encoding;
    opts = opts || {};

    // // read content of all but very large files into a buffer
    // if (readFromFile && cli.fileSize(data.filename) < 2e9) {
    //   content = cli.readFile(data.filename);
    //   readFromFile = false;
    // }

    if (readFromFile) {
      reader = new FileReader(data.filename);
    } else if (content instanceof ArrayBuffer || content instanceof B$3 || content instanceof Uint8Array) {
      // Web API may import as ArrayBuffer, to support larger files
      reader = new BufferReader(content);
      content = null;
    } else if (utils.isString(content)) ; else {
      error("Unexpected object type");
    }

    if (reader) {
      encoding = detectEncodingFromBOM(reader.readSync(0, Math.min(reader.size(), 3)));
      // Files in some encodings have to be converted to strings before parsing
      // Other encodings are similar enough to ascii that CSV can be parsed
      // byte-by-byte.
      if (encoding == 'utf16be' || encoding == 'utf16le') {
        content = trimBOM(reader.toString(encoding));
        reader = null;
      } else if (opts.encoding && !encodingIsAsciiCompat(opts.encoding)) {
        content = reader.toString(opts.encoding);
        reader = null;
      }
    }

    if (reader) {
      delimiter = guessDelimiter(readFirstChars(reader, 2000));
      records = readDelimRecords(reader, delimiter, opts);
    } else {
      delimiter = guessDelimiter(content);
      records = readDelimRecordsFromString(content, delimiter, opts);
    }
    if (records.length === 0) {
      message("Unable to read any data records");
    }
    adjustRecordTypes(records, opts);
    table = new DataTable(records);
    deleteFields(table, isInvalidFieldName);
    return {
      layers: [{data: table}],
      info: {input_delimiter: delimiter}
    };
  }

  var supportedDelimiters = ['|', '\t', ',', ';', ' '];

  function isSupportedDelimiter(d) {
    return utils.contains(supportedDelimiters, d);
  }

  function guessDelimiter(content) {
    return utils.find(supportedDelimiters, function(delim) {
      var rxp = getDelimiterRxp(delim);
      return rxp.test(content);
    }) || ',';
  }

  // Get RegExp to test for a delimiter before first line break of a string
  // Assumes that the first line does not contain alternate delim chars (this will
  // be true if the first line has field headers composed of word characters).
  function getDelimiterRxp(delim) {
    var rxp = "^[^\\n\\r]+" + utils.regexEscape(delim);
    return new RegExp(rxp);
  }

  function getFieldTypeHints(opts) {
    var hints = {};
    opts = opts || {};
    if (opts.string_fields) {
      opts.string_fields.forEach(function(f) {
        hints[f] = 'string';
      });
    }
    if (opts.field_types) {
      opts.field_types.forEach(function(raw) {
        var parts, name, type;
        if (raw.indexOf(':') != -1) {
          parts = raw.split(':');
          name = parts[0];
          type = validateFieldType(parts[1]);
        } else if (raw[0] === '+') { // d3-style type hint: unary plus
          name = raw.substr(1);
          type = 'number';
        }
        if (type) {
          hints[name] = type;
        } else {
          message("Invalid type hint (expected :str or :num) [" + raw + "]");
        }
      });
    }
    return hints;
  }


  // Detect and convert data types of data from csv files.
  // TODO: decide how to handle records with inconstent properties. Mapshaper
  //    currently assumes tabular data
  function adjustRecordTypes(records, optsArg) {
    var opts = optsArg || {},
        typeIndex = getFieldTypeHints(opts),
        singleType = typeIndex['*'], // support for setting all fields to a single type
        fields = Object.keys(records[0] || []),
        detectedNumFields = [],
        parseNumber = opts.decimal_comma ? utils.parseIntlNumber : utils.parseNumber,
        replacements = {};
    fields.forEach(function(key) {
      var typeHint = typeIndex[key];
      var values = null;
      if (typeHint == 'number' || singleType == 'number') {
        values = convertDataField(key, records, parseNumber);
      } else if (typeHint == 'string' || singleType == 'string') {
        // We should be able to assume that imported CSV fields are strings,
        //   so parsing + replacement is not required
        // values = internal.convertDataField(key, records, utils.parseString);
        values = null;
      } else {
        values = tryNumericField(key, records, parseNumber);
        if (values) detectedNumFields.push(key);
      }
      if (values) replacements[key] = values;
    });
    if (Object.keys(replacements).length > 0) {
      updateFieldsInRecords(fields, records, replacements);
    }
    if (detectedNumFields.length > 0) {
      message(utils.format("Auto-detected number field%s: %s",
          detectedNumFields.length == 1 ? '' : 's', detectedNumFields.join(', ')));
    }
  }

  // Copy original data properties and replacements to a new set of records
  // (Better performance in v8 than making in-place replacements)
  function updateFieldsInRecords(fields, records, replacements) {
    // Use object-literal syntax (faster than alternative)
    var convertBody = 'return {' + fields.map(function(name) {
        var key = JSON.stringify(name);
        return key + ': ' + (replacements[name] ? 'replacements[' + key + '][i]' : 'rec[' + key + ']');
      }).join(', ') + '}';
    var convert = new Function('rec', 'replacements', 'i', convertBody);
    records.forEach(function(rec, i) {
      records[i] = convert(rec, replacements, i);
    });
  }

  function tryNumericField(key, records, parseNumber) {
    var arr = [],
        count = 0,
        raw, str, num;
    for (var i=0, n=records.length; i<n; i++) {
      raw = records[i][key];
      num = parseNumber(raw);
      if (num === null) {
        str = raw ? raw.trim() : '';
        if (str.length > 0 && str != 'NA' && str != 'NaN') { // ignore NA values ("NA" seen in R output)
          return null; // unparseable value -- fail
        }
      } else {
        count++;
      }
      arr.push(num);
    }
    return count > 0 ? arr : null;
  }

  function convertDataField(name, records, f) {
    var values = [];
    for (var i=0, n=records.length; i<n; i++) {
      values.push(f(records[i][name]));
    }
    return values;
  }

  // Accept a type hint from a header like "FIPS:str"
  // Return standard type name (number|string) or null if hint is not recognized
  function validateFieldType(hint) {
    var str = hint.toLowerCase(),
        type = null;
    if (str[0] == 'n') {
      type = 'number';
    } else if (str[0] == 's') {
      type = 'string';
    }
    return type;
  }

  var DelimImport = /*#__PURE__*/Object.freeze({
    __proto__: null,
    importDelim: importDelim,
    importDelim2: importDelim2,
    isSupportedDelimiter: isSupportedDelimiter,
    guessDelimiter: guessDelimiter,
    getFieldTypeHints: getFieldTypeHints,
    adjustRecordTypes: adjustRecordTypes
  });

  function validateInputOpts(cmd) {
    var o = cmd.options,
        _ = cmd._;

    if (_.length > 0 && !o.files) {
      o.files = _;
    }
    if (o.files) {
      o.files = cli.expandInputFiles(o.files);
      if (o.files[0] == '-' || o.files[0] == '/dev/stdin') {
        delete o.files;
        o.stdin = true;
      }
    }

    if ("precision" in o && o.precision > 0 === false) {
      error("precision= option should be a positive number");
    }

    if (o.encoding) {
      o.encoding = validateEncoding(o.encoding);
    }
  }

  function validateSimplifyOpts(cmd) {
    var o = cmd.options,
        arg = cmd._[0];

    if (arg) {
      if (/^[0-9.]+%?$/.test(arg)) {
        o.percentage = utils.parsePercent(arg);
      } else {
        error("Unparsable option:", arg);
      }
    }

    if (!o.interval && !o.percentage && !o.resolution) {
      error("Command requires an interval, percentage or resolution parameter");
    }
  }

  function validateProjOpts(cmd) {
    var _ = cmd._;

    if (_.length > 0 && !cmd.options.crs) {
      cmd.options.crs = _.join(' ');
      _ = [];
    }

    if (_.length > 0) {
      error("Received one or more unexpected parameters: " + _.join(', '));
    }

    if (!(cmd.options.crs || cmd.options.match || cmd.options.init)) {
      stop("Missing projection data");
    }
  }

  function validateGridOpts(cmd) {
    var o = cmd.options;
    if (cmd._.length == 1) {
      var tmp = cmd._[0].split(',');
      o.cols = parseInt(tmp[0], 10);
      o.rows = parseInt(tmp[1], 10) || o.cols;
    }
  }

  function validateExpressionOpt(cmd) {
    if (!cmd.options.expression) {
      error("Command requires a JavaScript expression");
    }
  }

  function validateOutputOpts(cmd) {
    var _ = cmd._,
        o = cmd.options,
        arg = _[0] || "",
        pathInfo = parseLocalPath(arg);

    if (_.length > 1) {
      error("Command takes one file or directory argument");
    }

    if (arg == '-' || arg == '/dev/stdout') {
      o.stdout = true;
    } else if (arg && !pathInfo.extension) {
      if (!cli.isDirectory(arg)) {
        error("Unknown output option:", arg);
      }
      o.directory = arg;
    } else if (arg) {
      if (pathInfo.directory) {
        o.directory = pathInfo.directory;
        // no longer checking for missing directory
        // (cli.writeFile() now creates directories that don't exist)
        // cli.validateOutputDir(o.directory);
      }
      if (/gz/i.test(pathInfo.extension)) {
        // handle arguments like -o out.json.gz (the preferred format)
        if (parseLocalPath(pathInfo.basename).extension) {
          o.file = pathInfo.basename;
        } else {
          // handle arguments like -o out.gz
          o.file = pathInfo.filename;
        }
        o.gzip = true;
      } else if (/zip/i.test(pathInfo.extension)) {
        o.file = null;
        o.zipfile = pathInfo.filename;
        o.zip = true;
      } else {
        o.file = pathInfo.filename;
      }

      if (filenameIsUnsupportedOutputType(o.file)) {
        error("Output file looks like an unsupported file type:", o.file);
      }
    }

    if (o.format) {
      o.format = o.format.toLowerCase();
      if (o.format == 'csv') {
        o.format = 'dsv';
        o.delimiter = o.delimiter || ',';
      } else if (o.format == 'tsv') {
        o.format = 'dsv';
        o.delimiter = o.delimiter || '\t';
      }
      if (!isSupportedOutputFormat(o.format)) {
        error("Unsupported output format:", o.format);
      }
    }

    if (o.delimiter) {
      // convert "\t" '\t' \t to tab
      o.delimiter = o.delimiter.replace(/^["']?\\t["']?$/, '\t');
      if (!isSupportedDelimiter(o.delimiter)) {
        error("Unsupported delimiter:", o.delimiter);
      }
    }

    if (o.encoding) {
      o.encoding = validateEncoding(o.encoding);
    }

    if (o.field_order && o.field_order != 'ascending') {
      error('Unsupported field order:', o.field_order);
    }

    // topojson-specific
    if ("quantization" in o && o.quantization > 0 === false) {
      error("quantization= option should be a nonnegative integer");
    }

    if ("topojson_precision" in o && o.topojson_precision > 0 === false) {
      error("topojson-precision= option should be a positive number");
    }
  }

  var assignmentRxp = /^([a-z0-9_+-]+)=(?!=)(.*)$/i; // exclude ==

  function splitShellTokens(str) {
    var BAREWORD = `([^'"\\s])+`;
    var DOUBLE_QUOTE = `"((\\\\"|[^"])*?)"`;
    var SINGLE_QUOTE = `'((\\\\'|[^'])*?)'`;
    var rxp = new RegExp('(' + BAREWORD + '|' + SINGLE_QUOTE + '|' + DOUBLE_QUOTE + ')*', 'g');
    var matches = str.match(rxp) || [];
    var chunks = matches.filter(function(chunk) {
      // single backslashes may be present in multiline commands pasted from a makefile, e.g.
      return !!chunk && chunk != '\\';
    }).map(utils.trimQuotes);
    return chunks;
  }

  function parseNumberList(token) {
    return token.split(',').map(parseFloat);
  }

  // Split comma-delimited list, trim quotes from entire list and
  // individual members
  function parseStringList(token) {
    var delim = ',';
    var list = splitOptionList(token, delim);
    if (list.length == 1) {
      list = splitOptionList(list[0], delim);
    }
    return list;
  }

  // Accept spaces and/or commas as delimiters
  function parseColorList(token) {
    var delim = ', ';
    // accept rgb(0 0 0) rgb(0,0,0) rgb(0, 0, 0)
    var token2 = token.replace(/[ ,] *(?=[^(]*\))/g, '~~~'); // kludge: protect rgba() functions from being split apart
    var list = splitOptionList(token2, delim);
    if (list.length == 1) {
      list = splitOptionList(list[0], delim);
    }
    list = list.map(function(str) {
      return str.replace(/~~~/g, ',');
    });
    return list;
  }

  function cleanArgv(argv) {
    // Note: original trim caused some quoted spaces to be removed
    // (e.g. bash shell seems to convert [delimiter=" "] to [delimiter= ],
    //  which then got trimmed to [delimiter=] below)
    //// argv = argv.map(function(s) {return s.trim();}); // trim whitespace

    // Updated: don't trim space from tokens like [delimeter= ]
    argv = argv.map(function(s) {
      if (!/= $/.test(s)) {
        s = utils.rtrim(s);
      }
      s = utils.ltrim(s);
      return s;
    });
    argv = argv.filter(function(s) {return s !== '';}); // remove empty tokens
    // Note: removing trimQuotes() call... now, strings like 'name="Meg"' will no longer
    // be parsed the same way as name=Meg and name="Meg"
    //// argv = argv.map(utils.trimQuotes); // remove one level of single or dbl quotes
    return argv;
  }

  function splitOptionList(str, delimChars) {
    var BAREWORD = '([^' + delimChars + '\'"][^' + delimChars + ']*)'; // TODO: make safer
    var DOUBLE_QUOTE = '"((\\\\"|[^"])*?)"';
    var SINGLE_QUOTE = '\'((\\\\\'|[^\'])*?)\'';
    var rxp = new RegExp('^(' + BAREWORD + '|' + SINGLE_QUOTE + '|' + DOUBLE_QUOTE + ')([' + delimChars + ']+|$)');
    var chunks = [];
    var match;
    while ((match = rxp.exec(str)) !== null) {
      chunks.push(match[1]);
      str = str.substr(match[0].length);
    }
    return chunks.filter(function(chunk) {
      return !!chunk && chunk != '\\';
    }).map(utils.trimQuotes);
  }

  // Prepare a value to be used as an option value.
  // Places quotes around strings containing spaces.
  // e.g. converts   Layer 1 -> "Layer 1"
  //   for use in contexts like: name="Layer 1"
  function formatOptionValue(val) {
    val = String(val);
    if (val.indexOf(' ') > -1) {
      val = JSON.stringify(val); // quote ids with spaces
    }
    return val;
  }

  function isAssignment(token) {
    return assignmentRxp.test(token);
  }

  function splitAssignment(token) {
    var match = assignmentRxp.exec(token),
        name = match[1],
        val = utils.trimQuotes(match[2]);
    return [name, val];
  }

  var OptionParsingUtils = /*#__PURE__*/Object.freeze({
    __proto__: null,
    splitShellTokens: splitShellTokens,
    parseNumberList: parseNumberList,
    parseStringList: parseStringList,
    parseColorList: parseColorList,
    cleanArgv: cleanArgv,
    formatOptionValue: formatOptionValue,
    isAssignment: isAssignment,
    splitAssignment: splitAssignment
  });

  function CommandParser() {
    var commandRxp = /^--?([a-z][\w-]*)$/i,
        invalidCommandRxp = /^--?[a-z][\w-]*[=]/i, // e.g. -target=A // could be more general
        _usage = "",
        _examples = [],
        _commands = [],
        _default = null,
        _note;

    if (this instanceof CommandParser === false) return new CommandParser();

    this.usage = function(str) {
      _usage = str;
      return this;
    };

    this.note = function(str) {
      _note = str;
      return this;
    };

    // set a default command; applies to command line args preceding the first
    // explicit command
    this.default = function(str) {
      _default = str;
    };

    this.example = function(str) {
      _examples.push(str);
    };

    this.command = function(name) {
      var opts = new CommandOptions(name);
      // support 'verbose' and 'debug' flags for each command, without help entries
      opts.option('verbose', {type: 'flag'});
      opts.option('debug', {type: 'flag'});
      _commands.push(opts);
      return opts;
    };

    this.section = function(name) {
      return this.command("").title(name);
    };

    this.isCommandName = tokenIsCommandName;

    this.parseArgv = function(raw) {
      var commandDefs = getCommands(),
          commands = [], cmd,
          argv = cleanArgv(raw),
          cmdName, cmdDef;

      if (argv.length == 1 && tokenIsCommandName(argv[0])) {
        // show help if only a command name is given
        argv.unshift('-help'); // kludge (assumes -help <command> syntax)
      } else if (argv.length > 0 && !tokenLooksLikeCommand(argv[0]) && _default) {
        // if there are arguments before the first explicit command, use the default command
        argv.unshift('-' + _default);
      }

      while (argv.length > 0) {
        cmdName = readCommandName(argv);
        if (!cmdName) {
          stop("Invalid command:", argv[0]);
        }
        cmdDef = findCommandDefn(cmdName, commandDefs);
        if (!cmdDef) {
          // In order to support adding commands at runtime, unknown commands
          // are parsed without options (tokens get stored for later parsing)
          // stop("Unknown command:", cmdName);
          cmdDef = {name: cmdName, options: [], multi_arg: true};
        }
        cmd = {
          name: cmdDef.name,
          options: {},
          _: []
        };

        while (argv.length > 0 && !tokenLooksLikeCommand(argv[0])) {
          readOption(cmd, argv, cmdDef);
        }

        try {
          if (cmd._.length > 0 && cmdDef.no_arg) {
            error("Received one or more unexpected parameters:", cmd._.join(' '));
          }
          if (cmd._.length > 1 && !cmdDef.multi_arg) {
            error("Command expects a single value. Received:", cmd._.join(' '));
          }
          if (cmdDef.default && cmd._.length == 1) {
            // TODO: support multiple-token values, like -i filenames
            readDefaultOptionValue(cmd, cmdDef);
          }
          if (cmdDef.validate) {
            cmdDef.validate(cmd);
          }
        } catch(e) {
          stop("[" + cmdName + "] " + e.message);
        }
        commands.push(cmd);
      }
      return commands;

      function tokenLooksLikeCommand(s) {
        if (invalidCommandRxp.test(s)) {
          stop('Invalid command syntax:', s);
        }
        return commandRxp.test(s);
      }

      // Try to read an option for command @cmdDef from @argv
      function readOption(cmd, argv, cmdDef) {
        var token = argv.shift(),
            optName, optDef, parts;

        if (isAssignment(token)) {
          // token looks like name=value style option
          parts = splitAssignment(token);
          optDef = findOptionDefn(parts[0], cmdDef);
          if (!optDef) ; else if (optDef.type == 'flag' || optDef.assign_to) {
            stop("-" + cmdDef.name + " " + parts[0] + " option doesn't take a value");
          } else {
            argv.unshift(parts[1]);
          }
        } else {
          // try to parse as a flag option,
          // or as a space-delimited assignment option (for backwards compatibility)
          optDef = findOptionDefn(token, cmdDef);
        }

        if (!optDef) {
          // REMOVING quote trimming -- it prevents the use of quoted commands in -run (for example)
          // token is not a defined option; add it to _ array for later processing
          // Stripping surrounding quotes here, although this may not be necessary since
          // (some, most, all?) shells seem to remove quotes.
          // cmd._.push(utils.trimQuotes(token));
          cmd._.push(token);
          return;
        }

        if (optDef.alias_to) {
          optDef = findOptionDefn(optDef.alias_to, cmdDef);
        }

        optName = optDef.name;
        optName = optName.replace(/-/g, '_');

        if (optDef.assign_to) {
          cmd.options[optDef.assign_to] = optDef.name;
        } else if (optDef.type == 'flag') {
          cmd.options[optName] = true;
        } else {
          cmd.options[optName] = readOptionValue(argv, optDef);
        }
      }

      // Read an option value for @optDef from @argv
      function readOptionValue(argv, optDef) {
        if (argv.length === 0 || tokenLooksLikeCommand(argv[0])) {
          stop("Missing value for " + optDef.name + " option");
        }
        return parseOptionValue(argv.shift(), optDef); // remove token from argv
      }

      function readDefaultOptionValue(cmd, cmdDef) {
        var optDef = findOptionDefn(cmdDef.default, cmdDef);
        cmd.options[cmdDef.default] = readOptionValue(cmd._, optDef);
      }

      function parseOptionValue(token, optDef) {
        var type = optDef.type;
        var val, err;
        if (type == 'number') {
          val = Number(token);
        } else if (type == 'integer') {
          val = Math.round(Number(token));
        } else if (type == 'colors') {
          val = parseColorList(token);
        } else if (type == 'strings') {
          val = parseStringList(token);
        } else if (type == 'bbox' || type == 'numbers') {
          val = parseNumberList(token);
        } else if (type == 'percent') {
          // val = utils.parsePercent(token);
          val = token; // string value is parsed by command function
        } else if (type == 'distance' || type == 'area') {
          val = token; // string value is parsed by command function
        } else {
          val = token; // assume string type
        }

        if (val !== val) {
          err = "Invalid numeric value";
        }

        if (err) {
          stop(err + " for " + optDef.name + " option");
        }
        return val;
      }

      // Check first element of an array of tokens; remove and return if it looks
      // like a command name, else return null;
      function readCommandName(args) {
        var match = commandRxp.exec(args[0]);
        if (match) {
          args.shift();
          return match[1];
        }
        return null;
      }

    };

    this.getHelpMessage = function(cmdName) {
      var helpCommands, singleCommand, lines;

      if (cmdName) {
        singleCommand = findCommandDefn(cmdName, getCommands());
        if (!singleCommand) {
          stop(cmdName, "is not a known command");
        }
        lines = getSingleCommandLines(singleCommand);
      } else {
        helpCommands = getCommands().filter(function(cmd) {return cmd.name && cmd.describe || cmd.title;});
        lines = getMultiCommandLines(helpCommands);
      }

      return formatLines(lines);

      function formatLines(lines) {
        var colWidth = calcColWidth(lines);
        var gutter = '  ';
        var indent = runningInBrowser() ? '' : '  ';
        var helpStr = lines.map(function(line) {
          if (Array.isArray(line)) {
            line = indent + utils.rpad(line[0], colWidth, ' ') + gutter + line[1];
          }
          return line;
        }).join('\n');
        return helpStr;
      }

      function getSingleCommandLines(cmd) {
        var lines = [];
        // command name
        lines.push('COMMAND', getCommandLine(cmd));

        // options
        if (cmd.options.length > 0) {
          lines.push('', 'OPTIONS');
          cmd.options.forEach(function(opt) {
            lines = lines.concat(getOptionLines(opt, cmd));
          });
        }

        // examples
        if (cmd.examples) {
          lines.push('', 'EXAMPLE' + (cmd.examples.length > 1 ? 'S' : ''));
          cmd.examples.forEach(function(ex, i) {
            if (i > 0) lines.push('');
            ex.split('\n').forEach(function(line, i) {
              lines.push('  ' + line);
            });
          });
        }
        return lines;
      }

      function getOptionLines(opt, cmd) {
        var lines = [];
        var description = opt.describe;
        var label;
        if (!description) ; else if (opt.label) {
          lines.push([opt.label, description]);
        } else if (opt.name == cmd.default) {
          label = opt.name + '=';
          lines.push(['<' + opt.name + '>', 'shortcut for ' + label]);
          lines.push([label, description]);
        } else {
          label = opt.name;
          if (opt.alias) label += ', ' + opt.alias;
          if (opt.type != 'flag' && !opt.assign_to) label += '=';
          lines.push([label, description]);
        }
        return lines;
      }

      function getCommandLine(cmd) {
        var name = cmd.name ? "-" + cmd.name : '';
        if (cmd.alias) name += ', -' + cmd.alias;
        return [name, cmd.describe || '(undocumented command)'];
      }

      function getMultiCommandLines(commands) {
        var lines = [];
        // usage
        if (_usage) lines.push(_usage);

        // list of commands
        commands.forEach(function(cmd) {
          if (cmd.title) {
            lines.push('', cmd.title);
          } else {
            lines.push(getCommandLine(cmd));
          }
        });

        // examples
        if (_examples.length > 0) {
          lines.push('', 'Examples');
          _examples.forEach(function(str) {
            lines.push('', str);
          });
        }

        // note
        if (_note) {
          lines.push('', _note);
        }
        return lines;
      }


      function calcColWidth(lines) {
        var w = 0;
        lines.forEach(function(line) {
          if (Array.isArray(line)) {
            w = Math.max(w, line[0].length);
          }
        });
        return w;
      }
    };

    this.printHelp = function(command) {
      print(this.getHelpMessage(command));
    };

    function getCommands() {
      return _commands.map(function(cmd) {
        return cmd.done();
      });
    }

    function tokenIsCommandName(s) {
      var cmd = findCommandDefn(s, getCommands());
      return !!cmd;
    }

    function findCommandDefn(name, arr) {
      return utils.find(arr, function(cmd) {
        return cmd.name === name || cmd.alias === name || cmd.old_alias === name;
      });
    }

    function findOptionDefn(name, cmdDef) {
      return utils.find(cmdDef.options, function(o) {
        return o.name === name || o.alias === name || o.old_alias === name;
      });
    }
  }

  function CommandOptions(name) {
    var _command = {
      name: name,
      options: []
    };

    this.validate = function(f) {
      _command.validate = f;
      return this;
    };

    this.describe = function(str) {
      _command.describe = str;
      return this;
    };

    this.example = function(str) {
      if (!_command.examples) {
        _command.examples = [];
      }
      _command.examples.push(str);
      return this;
    };

    this.alias = function(name) {
      _command.alias = name;
      return this;
    };

    // define an alias command name that doesn't appear in command line help
    // (to support old versions of renamed commands)
    this.oldAlias = function(name) {
      _command.old_alias = name;
      return this;
    };

    this.title = function(str) {
      _command.title = str;
      return this;
    };

    this.flag = function(name) {
      _command[name] = true;
      return this;
    };

    this.option = function(name, opts) {
      opts = utils.extend({}, opts); // accept just a name -- some options don't need properties
      if (!utils.isString(name) || !name) error("Missing option name");
      if (!utils.isObject(opts)) error("Invalid option definition:", opts);
      // default option -- assign unnamed argument to this option
      if (opts.DEFAULT) _command.default = name;
      opts.name = name;
      _command.options.push(opts);
      return this;
    };

    this.options = function(o) {
      Object.keys(o).forEach(function(key) {
        this.option(key, o[key]);
      }, this);
      return this;
    };

    this.done = function() {
      return _command;
    };
  }

  function getOptionParser() {
    // definitions of options shared by more than one command
    var targetOpt = {
          describe: 'layer(s) to target (comma-sep. list)'
        },
        nameOpt = {
          describe: 'rename the edited layer(s)'
        },
        noReplaceOpt = {
          alias: '+',
          type: 'flag',
          label: '+, no-replace', // show alias as primary option
          // describe: 'retain the original layer(s) instead of replacing'
          describe: 'retain both input and output layer(s)'
        },
        noSnapOpt = {
          // describe: 'don't snap points before applying command'
          type: 'flag'
        },
        encodingOpt = {
          describe: 'text encoding (applies to .dbf and delimited text files)'
        },
        snapIntervalOpt = {
          describe: 'snapping distance in source units (default is tiny)',
          type: 'distance'
        },
        minGapAreaOpt = {
          old_alias: 'min-gap-area',
          describe: 'threshold for filling gaps, e.g. 1.5km2 (default is small)',
          type: 'area'
        },
        sliverControlOpt = {
          describe: 'boost gap-fill-area of slivers (0-1, default is 1)',
          type: 'number'
        },
        calcOpt = {
          describe: 'use a JS expression to aggregate data values'
        },
        sumFieldsOpt = {
          describe: 'fields to sum when dissolving  (comma-sep. list)',
          type: 'strings'
        },
        copyFieldsOpt = {
          describe: 'fields to copy when dissolving (comma-sep. list)',
          type: 'strings'
        },
        dissolveFieldsOpt = {
          DEFAULT: true,
          type: 'strings',
          describe: '(optional) field(s) to dissolve on (comma-sep. list)'
        },
        fieldTypesOpt = {
          describe: 'type hints for csv source files, e.g. FIPS:str,ZIPCODE:str',
          type: 'strings'
        },
        stringFieldsOpt = {
          describe: 'csv field(s) to import as strings, e.g. FIPS,ZIPCODE',
          type: 'strings'
        },
        bboxOpt = {
          type: 'bbox',
          describe: 'comma-sep. bounding box: xmin,ymin,xmax,ymax'
        },
        invertOpt = {
          type: 'flag',
          describe: 'retain only features that would have been deleted'
        },
        whereOpt = {
          describe: 'use a JS expression to select a subset of features'
        },
        whereOpt2 = {
          describe: 'filter polygon boundaries using a JS expression (with A and B)'
        },
        eachOpt2 = {
          describe: 'apply a JS expression to each polygon boundary (with A and B)'
        },
        aspectRatioOpt = {
          describe: 'aspect ratio as a number or range (e.g. 2 0.8,1.6 ,2)'
        },
        offsetOpt = {
          describe: 'padding as distance or pct of h/w (single value or list)',
          type: 'distance'
        };

    var parser = new CommandParser();
    parser.usage('Usage:  mapshaper -<command> [options] ...');

    /*
    parser.example('Fix minor topology errors, simplify to 10%, convert to GeoJSON\n' +
        '$ mapshaper states.shp snap -simplify 10% -o format=geojson');

    parser.example('Aggregate census tracts to counties\n' +
        '$ mapshaper tracts.shp -each \'CTY_FIPS=FIPS.substr(0, 5)\' -dissolve CTY_FIPS');
    */

    parser.note('Enter mapshaper -help <command> to view options for a single command');

    parser.section('I/O commands');

    parser.default('i');

    parser.command('i')
      .describe('input one or more files')
      .validate(validateInputOpts)
      .flag('multi_arg')
      .option('files', {
        DEFAULT: true,
        type: 'strings',
        describe: 'one or more files to import, or - to use stdin'
      })
      .option('combine-files', {
        describe: 'import files to separate layers with shared topology',
        type: 'flag'
      })
      .option('merge-files', {
        // describe: 'merge features from compatible files into the same layer',
        type: 'flag'
      })
      .option('no-topology', {
        describe: 'treat each shape as topologically independent',
        type: 'flag'
      })
      .option('precision', {
        describe: 'coordinate precision in source units, e.g. 0.001',
        type: 'number'
      })
      .option('snap', {
        type: 'flag',
        describe: 'snap nearly identical points to fix minor topology errors'
      })
      .option('auto-snap', {alias_to: 'snap'})
      .option('snap-interval', snapIntervalOpt)
      .option('encoding', encodingOpt)
      /*
      .option('fields', {
        describe: 'attribute fields to import (comma-sep.) (default is all fields)',
        type: 'strings'
      }) */
      .option('id-field', {
        describe: 'import Topo/GeoJSON id property to this field'
      })
      .option('string-fields', stringFieldsOpt)
      .option('field-types', fieldTypesOpt)
      .option('name', {
        describe: 'Rename the imported layer(s)'
      })
      .option('geometry-type', {
        // undocumented; GeoJSON import rejects all but one kind of geometry
        // describe: '[GeoJSON] Import one kind of geometry (point|polygon|polyline)'
      })
      .option('json-path', {
        // describe: path to an array of data values
      })
      .option('csv-skip-lines', {
        type: 'integer',
        describe: '[CSV] number of lines to skip at the beginning of the file'
      })
      .option('csv-lines', {
        type: 'integer',
        describe: '[CSV] number of data records to read'
      })
      .option('csv-field-names', {
        type: 'strings',
        describe: '[CSV] comma-sep. list of field names to assign each column'
      })
      .option('csv-dedup-fields', {
        type: 'flag',
        describe: '[CSV] rename fields with duplicate names'
      })
      .option('csv-filter', {
        describe: '[CSV] JS expression for filtering records'
      })
      .option('csv-fields', {
        type: 'strings',
        describe: '[CSV] comma-sep. list of fields to import'
      })
      // .option('csv-comment', {
      //   describe: '[CSV] comment line character(s)'
      // })
      .option('decimal-comma', {
        type: 'flag',
        describe: '[CSV] import numbers formatted like 1.000,01 or 1 000,01'
      })
      .option('json-path', {
        old_alias: 'json-subtree',
        describe: '[JSON] path to JSON input data; separator is /'
      })
      .option('single-part', {
        type: 'flag',
        // describe: '[GeoJSON] split multi-part features into single-part features'
      });

    parser.command('o')
      .describe('output edited content')
      .validate(validateOutputOpts)
      .option('_', {
        label: '<file|directory>',
        describe: '(optional) name of output file or directory, - for stdout'
      })
      .option('format', {
        describe: 'options: shapefile,geojson,topojson,json,dbf,csv,tsv,svg'
      })
      .option('target', targetOpt)
      .option('force', {
        describe: 'allow overwriting input files',
        type: 'flag'
      })
      .option('gzip', {
        describe: 'apply gzip compression to output files',
        type: 'flag'
      })
     .option('zip', {
        describe: 'save all output files in a single .zip file',
        type: 'flag'
      })
      .option('dry-run', {
        // describe: 'do not output any files'
        type: 'flag'
      })
      .option('ldid', {
        // describe: 'language driver id of dbf file',
        type: 'number'
      })
      .option('precision', {
        describe: 'coordinate precision in source units, e.g. 0.001',
        type: 'number'
      })
      .option('bbox-index', {
        describe: 'export a .json file with bbox of each layer',
        type: 'flag'
      })
      .option('cut-table', {
        describe: 'detach data attributes from shapes and save as a JSON file',
        type: 'flag'
      })
      .option('drop-table', {
        describe: 'remove data attributes from output',
        type: 'flag'
      })
      .option('encoding', {
        describe: '[Shapefile/CSV] text encoding (default is utf8)'
      })
      .option('field-order', {
        describe: '[Shapefile/CSV] field-order=ascending sorts columns A-Z'
      })
      .option('id-field', {
        describe: '[Topo/GeoJSON/SVG] field to use for id property',
        type: 'strings'
      })
      .option('bbox', {
        type: 'flag',
        describe: '[Topo/GeoJSON] add bbox property'
      })
      .option('extension', {
        describe: '[Topo/GeoJSON] set file extension (default is ".json")'
      })
      .option('prettify', {
        type: 'flag',
        describe: '[Topo/GeoJSON/JSON] format output for readability'
      })
      .option('singles', {
        describe: '[TopoJSON] save each target layer as a separate file',
        type: 'flag'
      })
      .option('quantization', {
        describe: '[TopoJSON] specify quantization (auto-set by default)',
        type: 'integer'
      })
      .option('no-quantization', {
        describe: '[TopoJSON] export coordinates without quantization',
        type: 'flag'
      })
      .option('no-point-quantization', {
        // describe: '[TopoJSON] export point coordinates without quantization',
        type: 'flag'
      })
      .option('presimplify', {
        describe: '[TopoJSON] add per-vertex data for dynamic simplification',
        type: 'flag'
      })
      .option('topojson-precision', {
        // describe: 'pct of avg segment length for rounding (0.02 is default)',
        type: 'number'
      })
      .option('rfc7946', {
        // obsolete -- rfc 7946 compatible outptu is now the default.
        // This option also rounds coordinates to 7 decimals. I'm retaining the
        // option for backwards compatibility.
        // describe: '[GeoJSON] follow RFC 7946 (CCW outer ring order, etc.)',
        type: 'flag'
      })
      // .option('winding', {
      //   describe: '[GeoJSON] set polygon winding order (use CW with d3-geo)'
      // })
      .option('gj2008', {
        describe: '[GeoJSON] use original GeoJSON spec (not RFC 7946)',
        type: 'flag'
      })
      .option('combine-layers', {
        describe: '[GeoJSON] output layers as a single file',
        type: 'flag'
      })
      .option('geojson-type', {
        describe: '[GeoJSON] FeatureCollection, GeometryCollection or Feature'
      })
      .option('ndjson', {
        describe: '[GeoJSON/JSON] output newline-delimited features or records',
        type: 'flag'
      })
      .option('width', {
        describe: '[SVG/TopoJSON] pixel width of output (SVG default is 800)',
        type: 'number'
      })
      .option('height', {
        describe: '[SVG/TopoJSON] pixel height of output (optional)',
        type: 'number'
      })
      .option('max-height', {
        describe: '[SVG/TopoJSON] max pixel height of output (optional)',
        type: 'number'
      })
      .option('margin', {
        describe: '[SVG/TopoJSON] space betw. data and viewport (default is 1)'
      })
      .option('pixels', {
        describe: '[SVG/TopoJSON] output area in pix. (alternative to width=)',
        type: 'number'
      })
      .option('fit-bbox', {
        type: 'bbox',
        describe: '[TopoJSON] scale and shift coordinates to fit a bbox'
      })
      .option('svg-scale', {
        describe: '[SVG] source units per pixel (alternative to width= option)',
        type: 'number'
      })
      .option('point-symbol', {
        describe: '[SVG] circle or square (default is circle)'
      })
      .option('svg-data', {
        type: 'strings',
        describe: '[SVG] fields to export as data-* attributes'
      })
      .option('id-prefix', {
        describe: '[SVG] prefix for namespacing layer and feature ids'
      })
      .option('scalebar', {
        type: 'flag',
        // describe: '[SVG] add a scalebar showing scale at the center of the map'
      })
      .option('delimiter', {
        describe: '[CSV] field delimiter'
      })
      .option('decimal-comma', {
        type: 'flag',
        describe: '[CSV] export numbers with decimal commas not points'
      })
      .option('final', {
        type: 'flag' // for testing
      })
      .option('metadata', {
        // describe: '[TopoJSON] add a metadata object',
        type: 'flag'
      });

    parser.section('Editing commands');

    parser.command('affine')
      .describe('transform coordinates by shifting, scaling and rotating')
      .flag('no_args')
      .option('shift', {
        type: 'strings',
        describe: 'x,y offsets in source units (e.g. 5000,-5000)'
      })
      .option('scale', {
        type: 'number',
        describe: 'scale (default is 1)'
      })
      .option('rotate', {
        type: 'number',
        describe: 'angle of rotation in degrees (default is 0)'
      })
      .option('anchor', {
        type: 'numbers',
        describe: 'center of rotation/scaling (default is center of selected shapes)'
      })
      .option('where', whereOpt)
      .option('target', targetOpt);

    parser.command('buffer')
      // .describe('')
      .option('radius', {
        describe: 'radius of buffer, as an expression or a constant',
        DEFAULT: true
      })
      .option('tolerance', {
        // describe: 'acceptable deviation for approximating curves'
      })
      .option('vertices', {
        // describe: 'number of vertices to use when buffering points',
        type: 'integer'
      })
      .option('backtrack', {
        type: 'integer'
      })
      .option('type', {
        // left, right, outer, inner (default is full buffer)
      })
      .option('planar', {
        type: 'flag'
      })
      .option('v2', { // use v2 method
        type: 'flag'
      })
      .option('debug-division', {
        type: 'flag'
      })
      .option('debug-mosaic', {
        type: 'flag'
      })
      .option('no-cleanup', {
        type: 'flag'
      })
      .option('units', {
        describe: 'distance units (meters|miles|km|feet) (default is meters)'
      })
      .option('name', nameOpt)
      .option('target', targetOpt)
      .option('no-replace', noReplaceOpt);

    parser.command('classify')
      // .describe('apply sequential or categorical classification')
      .describe('assign colors or values using one of several methods')
      .option('field', {
        describe: 'name of field to classify',
        DEFAULT: true
      })
      .option('save-as', {
          describe: 'name of output field (default is fill|stroke|class)'
      })
      .option('colors', {
        describe: 'list of CSS colors or color scheme name (see -colors)',
        type: 'colors'
      })
      .option('values', {
        describe: 'values to assign to classes (alternative to colors=)',
        type: 'strings'
      })
      .option('color-scheme', {
        // deprecated in favor of colors=
        // describe: 'name of a predefined color scheme (see -colors command)'
      })
      .option('non-adjacent', {
        describe: 'assign non-adjacent colors to a polygon layer',
        assign_to: 'method'
      })
      .option('stops', {
        describe: 'a pair of values (0-100) for limiting a color ramp',
        type: 'numbers'
      })
      .option('range', {
        // describe: 'a pair of numbers defining the effective data range',
        type: 'numbers'
      })
      .option('null-value', {
        describe: 'value (or color) to use for invalid or missing data'
      })
      .option('method', {
        describe: 'quantile, nice, equal-interval, categorical, etc.'
      })
      .option('quantile', {
        //describe: 'shortcut for method=quantile (the default)',
        assign_to: 'method'
      })
      .option('equal-interval', {
        //describe: 'short for method=equal-interval',
        assign_to: 'method'
      })
      .option('hybrid', {
        // describe: 'short for method=hybrid (equal-interval inner breaks + quantile outliers)',
        assign_to: 'method'
      })
      .option('nice', {
        //describe: 'short for method=nice (rounded, equal inner breaks)',
        assign_to: 'method'
      })
      .option('breaks', {
        describe: 'user-defined sequential class breaks',
        type: 'numbers'
      })
      .option('classes', {
        describe: 'number of classes (can be inferred from other options)',
        type: 'integer'
      })
      .option('invert', {
        describe: 'reverse the order of colors/values',
        type: 'flag'
      })
      .option('continuous', {
        describe: 'output continuous interpolated values (experimental)',
        type: 'flag'
      })
      .option('index-field', {
        describe: 'apply pre-calculated classes (0 ... n-1, -1)'
      })
      .option('precision', {
        describe: 'round data values before classification (e.g. 0.1)',
        type: 'number'
      })
      .option('categories', {
        describe: 'list of data values for categorical color scheme',
        type: 'strings'
      })
      .option('other', {
        describe: 'default value for categorical scheme'
      })
      .option('key', {type: 'flag'})
      .option('key-style', {
        describe: 'one of: simple, gradient, dataviz'
      })
      .option('key-name', {
        describe: 'name of output SVG file'
      })
      .option('key-width', {
        describe: 'width of key in pixels',
        type: 'number'
      })
      .option('key-font-size', {
        describe: 'label size in pixels',
        type: 'number'
      })
      .option('key-tile-height', {
        describe: 'height of color tiles in pixels',
        type: 'number'
      })
      .option('key-tic-length', {
        describe: 'length of tic mark in pixels'
      })
      .option('key-label-suffix', {
        describe: 'string to append to each label'
      })
      .option('key-last-suffix', {
        describe: 'string to append to last label'
      })
      .option('target', targetOpt);

    parser.command('clean')
      .describe('fixes geometry issues, such as polygon overlaps and gaps')
      .option('gap-fill-area', minGapAreaOpt)
      .option('sliver-control', sliverControlOpt)
      .option('snap-interval', snapIntervalOpt)
      .option('no-snap', noSnapOpt)
      .option('allow-overlaps', {
        describe: 'allow polygons to overlap (disables gap fill)',
        type: 'flag'
      })
      .option('overlap-rule', {
        describe: 'how to resolve overlaps: min-id|max-id|min-area|[max-area]'
      })
      .option('allow-empty', {
        describe: 'keep null geometries (removed by default)',
        type: 'flag'
      })
      .option('rewind', {
        describe: 'fix errors in the CW/CCW winding order of polygon rings',
        type: 'flag'
      })
      // TODO: consider making this the standard way of removing null geometry
      // (currently there's -filter remove-empty)
      // .option('empty', {
      //   describe: 'remove features with null geometry',
      //   type: 'flag'
      // })
      .option('arcs', { // old name for arcs-only
        alias_to: 'only-arcs'
      })
      .option('only-arcs', {
        describe: 'delete unused arcs but don\'t remove gaps and overlaps',
        type: 'flag'
      })
      .option('no-arc-dissolve', {
        type: 'flag' // no description
      })
      .option('target', targetOpt);

    parser.command('clip')
      .describe('use a polygon layer to clip another layer')
      .example('$ mapshaper states.shp -clip land_area.shp -o clipped.shp')
      .option('source', {
        DEFAULT: true,
        describe: 'file or layer containing clip polygons'
      })
      .option('remove-slivers', {
        describe: 'remove sliver polygons created by clipping',
        type: 'flag'
      })
      .option('bbox', bboxOpt)
      .option('bbox2', {
          type: 'bbox',
          describe: 'experimental fast bbox clipping'
        })
      .option('name', nameOpt)
      .option('no-snap', noSnapOpt)
      .option('target', targetOpt)
      .option('no-replace', noReplaceOpt);

    parser.command('colorizer')
      .describe('define a function to convert data values to color classes')
      .flag('no_arg')
      .option('colors', {
        describe: 'comma-separated list of CSS colors',
        type: 'colors'
      })
      .option('breaks', {
        describe: 'ascending-order list of breaks for sequential color scheme',
        type: 'numbers'
      })
      .option('categories', {
        describe: 'comma-sep. list of keys for categorical color scheme',
        type: 'strings'
      })
      .option('random', {
        describe: 'randomly assign colors',
        type: 'flag'
      })
      .option('other', {
        describe: 'default color for categorical scheme (defaults to no-data color)'
      })
      .option('nodata', {
        describe: 'color to use for invalid or missing data (default is white)'
      })
      .option('name', {
        describe: 'function name to use in -each and -svg-style commands'
      })
      .option('precision', {
        describe: 'rounding precision to apply before classification (e.g. 0.1)',
        type: 'number'
      })
      .example('Define a sequential color scheme and use it to create a new field\n' +
          '$ mapshaper data.json -colorizer name=getColor nodata=#eee breaks=20,40 \\\n' +
          '  colors=#e0f3db,#a8ddb5,#43a2ca -each \'fill = getColor(RATING)\' -o output.json');

    parser.command('dashlines')
      .describe('split lines into sections, with or without a gap')
      .oldAlias('split-lines')
      .option('dash-length', {
        type: 'distance',
        describe: 'length of split-apart lines (e.g. 200km)'
      })
      .option('gap-length', {
        type: 'distance',
        describe: 'length of gaps between dashes (default is 0)'
      })
      .option('scaled', {
        type: 'flag',
        describe: 'scale dashes and gaps to prevent partial dashes'
      })
      .option('planar', {
        type: 'flag',
        describe: 'use planar geometry'
      })
      .option('where', whereOpt)
      .option('target', targetOpt);

    parser.command('define')
      // .describe('define expression variables')
      .option('expression', {
        DEFAULT: true,
        describe: 'one or more assignment expressions (comma-sep.)'
      });

    parser.command('dissolve')
      .describe('merge features within a layer')
      .example('Dissolve all polygons in a feature layer into a single polygon\n' +
        '$ mapshaper states.shp -dissolve -o country.shp')
      .example('Generate state-level polygons by dissolving a layer of counties\n' +
        '(STATE_FIPS, POPULATION and STATE_NAME are attribute field names)\n' +
        '$ mapshaper counties.shp -dissolve STATE_FIPS copy-fields=STATE_NAME sum-fields=POPULATION -o states.shp')
      .option('field', {}) // old arg handled by dissolve function
      .option('fields', dissolveFieldsOpt)
      .option('calc', calcOpt)
      .option('sum-fields', sumFieldsOpt)
      .option('copy-fields', copyFieldsOpt)
      .option('multipart', {
        type: 'flag',
        describe: 'make multipart features instead of dissolving'
      })
      .option('where', whereOpt)
      .option('group-points', {
        type: 'flag',
        describe: '[points] group points instead of converting to centroids'
      })
      .option('weight', {
        describe: '[points] field or expression to use for weighting centroid'
      })
      .option('planar', {
        type: 'flag',
        describe: '[points] use 2D math to find centroids of latlong points'
      })
      .option('name', nameOpt)
      .option('target', targetOpt)
      .option('no-replace', noReplaceOpt);


    parser.command('dissolve2')
      .describe('merge adjacent polygons (repairs overlaps and gaps)')
      .option('field', {}) // old arg handled by dissolve function
      .option('fields', dissolveFieldsOpt)
      // UPDATE: Use -mosaic command for debugging
      //.option('mosaic', {type: 'flag'}) // debugging option
      //.option('arcs', {type: 'flag'}) // debugging option
      //.option('tiles', {type: 'flag'}) // debugging option
      .option('calc', calcOpt)
      .option('sum-fields', sumFieldsOpt)
      .option('copy-fields', copyFieldsOpt)
      .option('gap-fill-area', minGapAreaOpt)
      .option('sliver-control', sliverControlOpt)
      .option('allow-overlaps', {
        describe: 'allow dissolved polygons to overlap (disables gap fill)',
        type: 'flag'
      })
      .option('name', nameOpt)
      .option('no-snap', noSnapOpt)
      .option('target', targetOpt)
      .option('no-replace', noReplaceOpt);

    parser.command('divide')
      .describe('divide lines by polygons, copy polygon data to lines')
      .option('fields', {
        describe: 'fields to copy (comma-sep.) (default is all but key field)',
        type: 'strings'
      })
      .option('calc', {
        describe: 'use a JS expression to assign values (for many-to-one joins)'
      })
      .option('force', {
        describe: 'replace values from same-named fields',
        type: 'flag'
      })
      .option('source', {
        DEFAULT: true,
        describe: 'file or layer containing polygons'
      })
      .option('target', targetOpt);
      // .option('no-replace', noReplaceOpt);

    parser.command('dots')
      .describe('fill polygons with dots of one or more colors')
      .option('fields', {
        DEFAULT: true,
        describe: 'one or more fields containing numbers of dots',
        type: 'strings'
      })
      .option('colors', {
        describe: 'one or more colors',
        type: 'strings'
      })
      .option('values', {
        describe: 'values to assign to dot classes (alternative to colors=)',
        type: 'strings'
      })
      .option('save-as', {
        describe: 'name of color/value output field (default is fill)'
      })
      .option('progressive', {
        // describe: 'fill in points progressively',
        type: 'flag'
      })
      .option('r', {
        describe: 'radius of each dot in pixels',
        type: 'number'
      })
      .option('evenness', {
        describe: '(0-1) dot spacing, from random to even (default is 1)',
        type: 'number'
      })
      .option('per-dot', {
        describe: 'number for scaling data values (e.g. 10 per dot)',
        type: 'number'
      })
      .option('copy-fields', {
        describe: 'list of fields to copy from polygons to dots',
        type: 'strings'
      })
      .option('multipart', {
        describe: 'combine groups of same-color dots into multi-part features',
        type: 'flag'
      })
      .option('target', targetOpt)
      .option('name', nameOpt)
      .option('no-replace', noReplaceOpt);

    parser.command('drop')
      .describe('delete layer(s) or elements within the target layer(s)')
      .flag('no_arg') // prevent trying to pass a list of layer names as default option
      .option('geometry', {
        describe: 'delete all geometry from the target layer(s)',
        type: 'flag'
      })
      .option('holes', {
        describe: 'delete holes from polygons',
        type: 'flag'
      })
      .option('fields', {
        type: 'strings',
        describe: 'delete a list of attribute data fields, e.g. \'id,name\' \'*\''
      })
      .option('target', targetOpt);

    parser.command('each')
      .describe('create/update/delete data fields using a JS expression')
      .example('Add two calculated data fields to a layer of U.S. counties\n' +
          '$ mapshaper counties.shp -each \'STATE_FIPS=CNTY_FIPS.substr(0, 2), AREA=$.area\'')
      .option('expression', {
        DEFAULT: true,
        describe: 'JS expression to apply to each target feature'
      })
      .option('where', whereOpt)
      .option('target', targetOpt);

    parser.command('erase')
      .describe('use a polygon layer to erase another layer')
      .example('$ mapshaper land_areas.shp -erase water_bodies.shp -o erased.shp')
      .option('source', {
        DEFAULT: true,
        describe: 'file or layer containing erase polygons'
      })
      .option('remove-slivers', {
        describe: 'remove sliver polygons created by erasing',
        type: 'flag'
      })
      .option('bbox', bboxOpt)
      .option('name', nameOpt)
      .option('no-snap', noSnapOpt)
      .option('target', targetOpt)
      .option('no-replace', noReplaceOpt);

    parser.command('explode')
      .describe('divide multi-part features into single-part features')
      .option('naive', {type: 'flag'}) // testing
      .option('target', targetOpt);

    parser.command('filter')
      .describe('delete features using a JS expression')
      .option('expression', {
        DEFAULT: true,
        describe: 'delete features that evaluate to false'
      })
      .option('bbox', {
        describe: 'delete features outside bbox (xmin,ymin,xmax,ymax)',
        type: 'bbox'
      })
      .option('invert', invertOpt)
      .option('remove-empty', {
        type: 'flag',
        describe: 'delete features with null geometry'
      })
      .option('keep-shapes', {
        type: 'flag'
      })
      .option('ids', {
        // describe: 'filter on a list of feature ids',
        type: 'numbers'
      })
      .option('cleanup', {type: 'flag'}) // TODO: document
      .option('name', nameOpt)
      .option('target', targetOpt)
      .option('no-replace', noReplaceOpt);

    parser.command('filter-fields')
      .describe('retain a subset of data fields')
      .option('fields', {
        DEFAULT: true,
        type: 'strings',
        describe: 'fields to retain (comma-sep.), e.g. \'fips,name\''
      })
      .option('target', targetOpt);

    parser.command('filter-geom')
      .describe('')
      .option('bbox', {
        type: 'bbox',
        describe: 'remove non-intersecting geometry (xmin,ymin,xmax,ymax)'
      })
      .option('target', targetOpt);

    parser.command('filter-islands2')
      // .describe('remove small detached polygon rings (islands)')
      .option('min-area', {
        type: 'area',
        describe: 'remove small-area islands (e.g. 10km2)'
      })
      .option('min-vertices', {
        type: 'integer',
        describe: 'remove low-vertex-count islands'
      })
      .option('keep-shapes', {
        type: 'flag',
        describe: 'only filter smaller parts of multipart polygons',
      })
      .option('remove-empty', {
        type: 'flag',
        describe: 'delete features with null geometry'
      })
      .option('target', targetOpt);

    parser.command('filter-islands')
      .describe('remove small detached polygon rings (islands)')
      .option('min-area', {
        type: 'area',
        describe: 'remove small-area islands (e.g. 10km2)'
      })
      .option('min-vertices', {
        type: 'integer',
        describe: 'remove low-vertex-count islands'
      })
      .option('remove-empty', {
        type: 'flag',
        describe: 'delete features with null geometry'
      })
      .option('target', targetOpt);

    parser.command('filter-slivers')
      .describe('remove small polygon rings')
      .option('min-area', {
        type: 'area',
        describe: 'area threshold (e.g. 2sqkm)'
      })
      .option('sliver-control', {
        describe: 'boost area threshold of slivers (0-1, default is 1)',
        type: 'number'
      })
      .option('weighted', {
        // describe: 'multiply min-area by Polsby-Popper compactness (0-1)'
        type: 'flag',
      })
      /*
      .option('remove-empty', {
        type: 'flag',
        describe: 'delete features with null geometry'
      })
      */
      .option('target', targetOpt);

    parser.command('graticule')
      .describe('create a graticule layer')
      .option('interval', {
        describe: 'size of grid cells in degrees (options: 5 10 15 30 45, default is 10)',
        type: 'number'
      })
      .option('polygon', {
        describe: 'create a polygon to match the outline of the graticule',
        type: 'flag'
      });

    parser.command('grid')
      .describe('create a grid of square or hexagonal polygons')
      .option('type', {
        describe: 'square, hex or hex2 (default is square)'
      })
      .option('interval', {
        describe: 'side length (e.g. 500m, 12km)',
        type: 'distance'
      })
      // .option('cols', {
      //   type: 'integer'
      // })
      // .option('rows', {
      //   type: 'integer'
      // })
      // .option('bbox', {
      //   type: 'bbox',
      //   describe: 'xmin,ymin,xmax,ymax (default is bbox of data)'
      // })
      .option('name', nameOpt)
      .option('target', targetOpt)
      .option('no-replace', noReplaceOpt);

    parser.command('include')
      .describe('import JS data and functions for use in JS expressions')
      .option('file', {
        DEFAULT: true,
        describe: 'file containing a JS object with key:value pairs to import'
      });

    parser.command('inlay')
      .describe('inscribe a polygon layer inside another polygon layer')
      .option('source', {
        DEFAULT: true,
        describe: 'file or layer containing polygons to inlay'
      })
      .option('target', targetOpt);

    parser.command('innerlines')
      .describe('convert polygons to polylines along shared edges')
      .flag('no_arg')
      .option('where', whereOpt2)
      // .option('each', eachOpt2)
      .option('name', nameOpt)
      .option('target', targetOpt)
      .option('no-replace', noReplaceOpt);

    parser.command('join')
      .describe('join data records from a file or layer to a layer')
      .example('Join a csv table to a Shapefile (don\'t auto-convert FIPS column to numbers)\n' +
        '$ mapshaper states.shp -join data.csv keys=STATE_FIPS,FIPS string-fields=FIPS -o joined.shp')
      .validate(function(cmd) {
        if (!cmd.options.source) {
          error('Command requires the name of a layer or file to join');
        }
      })
      .option('source', {
        DEFAULT: true,
        describe: 'file or layer containing data records'
      })
      .option('keys', {
        describe: 'join by matching target,source key fields, e.g. keys=FID,id',
        type: 'strings'
      })
      .option('calc', {
        describe: 'use a JS expression to assign values (for many-to-one joins)'
      })
      .option('where', {
        describe: 'use a JS expression to filter source records'
      })
      .option('fields', {
        describe: 'fields to copy (comma-sep.) (default is all but key field)',
        type: 'strings'
      })
      .option('prefix', {
        describe: 'prefix for renaming fields joined from the source table'
      })
      .option('interpolate', {
        describe: '(polygon-polygon join) list of area-interpolated fields',
        type: 'strings'
      })
      .option('point-method', {
        describe: '(polygon-polygon join) join polygons via inner points',
        type: 'flag'
      })
      .option('largest-overlap', {
        describe: '(polygon-polygon join) use max overlap to join one polygon',
        type: 'flag'
      })
      // .option('nearest-point', {
      //   describe: '(point-point join)',
      //   type: 'flag'
      // })
      .option('max-distance', {
        describe: '(point-point join) join source points within this radius',
        type: 'distance'
      })
      .option('planar', {
        // describe: 'use planar geometry when interpolating by area' // useful for testing
        type: 'flag'
      })
      .option('duplication', {
        describe: 'duplicate target features on many-to-one joins',
        type: 'flag'
      })
      .option('string-fields', stringFieldsOpt)
      .option('field-types', fieldTypesOpt)
      .option('sum-fields', {
        describe: 'fields to sum in a many-to-one join (or use calc= for this)',
        type: 'strings'
      })
      .option('force', {
        describe: 'replace values from same-named fields',
        type: 'flag'
      })
      .option('unjoined', {
        describe: 'copy unjoined records from source table to "unjoined" layer',
        type: 'flag'
      })
      .option('unmatched', {
        describe: 'copy unmatched records in target table to "unmatched" layer',
        type: 'flag'
      })
      .option('encoding', encodingOpt)
      .option('target', targetOpt);

    parser.command('lines')
      .describe('convert a polygon or point layer to a polyline layer')
      .option('fields', {
        DEFAULT: true,
        describe: 'field(s) to create a hierarchy of boundary lines',
        type: 'strings'
      })
      .option('where', whereOpt2)
      .option('each', eachOpt2)
      .option('segments', {
        describe: 'convert paths to segments, for debugging',
        type: 'flag'
      })
      .option('callouts', {
        // describe: 'convert points to lines for editing in the GUI',
        type: 'flag'
      })
      .option('arcs', {
        describe: 'convert paths to arcs, for debugging',
        type: 'flag'
      })
      .option('groupby', {
        describe: 'field for grouping point input into multiple lines'
      })
      .option('name', nameOpt)
      .option('target', targetOpt)
      .option('no-replace', noReplaceOpt);

    parser.command('merge-layers')
      .describe('merge multiple layers into as few layers as possible')
      .flag('no_arg')
      .option('force', {
        type: 'flag',
        describe: 'merge layers with inconsistent data fields'
      })
      .option('flatten', {
        describe: 'remove polygon overlaps; higher-id polygons take priority',
        type: 'flag'
      })
      .option('name', nameOpt)
      .option('target', targetOpt);

    parser.command('mosaic')
      .describe('convert a polygon layer with overlaps into a flat mosaic')
      .option('calc', calcOpt)
      .option('name', nameOpt)
      .option('target', targetOpt)
      .option('no-replace', noReplaceOpt);

    parser.command('point-grid')
      .describe('create a rectangular grid of points')
      .validate(validateGridOpts)
      .option('-', {
        label: '<cols,rows>',
        describe: 'size of the grid, e.g. -point-grid 100,100'
      })
      .option('interval', {
        describe: 'distance between adjacent points, in source units',
        type: 'distance'
      })
      .option('cols', {
        type: 'integer'
      })
      .option('rows', {
        type: 'integer'
      })
      .option('bbox', {
        type: 'bbox',
        describe: 'xmin,ymin,xmax,ymax (default is bbox of data)'
      })
      .option('name', nameOpt)
      .option('target', targetOpt)
      .option('no-replace', noReplaceOpt);

    parser.command('points')
      .describe('create a point layer from a different layer type')
      .flag('no_arg')
      .option('x', {
        describe: 'field containing x coordinate'
      })
      .option('y', {
        describe: 'field containing y coordinate'
      })
      .option('inner', {
        describe: 'create an interior point for each polygon\'s largest ring',
        type: 'flag'
      })
      .option('centroid', {
        describe: 'create a centroid point for each polygon\'s largest ring',
        type: 'flag'
      })
      .option('vertices', {
        describe: 'capture unique vertices of polygons and polylines',
        type: 'flag'
      })
      .option('vertices2', {
        describe: 'like vertices, but without removal of duplicate coordinates',
        type: 'flag'
      })
      .option('endpoints', {
        describe: 'capture unique endpoints of polygons and polylines',
        type: 'flag'
      })
      .option('midpoints', {
        describe: 'find the (planar) midpoint of each polyline',
        type: 'flag'
      })
      // WORK IN PROGRESS todo: create a point layer containing segment intersections
      .option('intersections', {
       // describe: 'capture line segment intersections of polygons and polylines',
       type: 'flag'
      })
      .option('interpolated', {
        describe: 'interpolate points along polylines; requires interval=',
        type: 'flag'
      })
      .option('interval', {
        describe: 'distance between interpolated points (meters or projected units)',
        type: 'distance'
      })
      .option('name', nameOpt)
      .option('target', targetOpt)
      .option('no-replace', noReplaceOpt);

    parser.command('polygons')
      .describe('convert polylines to polygons')
      .option('gap-tolerance', {
        describe: 'specify gap tolerance in source units',
        type: 'distance'
      })
      .option('from-rings', {
        describe: 'do simple conversion from a layer of closed paths',
        type: 'flag'
      })
      .option('target', targetOpt);

    parser.command('proj')
      .describe('project your data (using Proj.4)')
      .flag('multi_arg')
      .option('crs', {
        DEFAULT: true,
        describe: 'set destination CRS using a Proj.4 definition or alias'
      })
      .option('projection', {
        alias_to: 'crs'
      })
      .option('match', {
        describe: 'set destination CRS using a .prj file or layer id'
      })
      .option('source', {
        // describe: '(deprecated) alias for match',
        alias_to: 'match'
      })
      .option('from', {
        alias_to: 'init',
        describe: '(deprecated) alias for init='
      })
      .option('init', {
        describe: 'set source CRS (if unset) using a string, .prj or layer id'
      })
      .option('densify', {
        type: 'flag',
        describe: 'add points along straight segments to approximate curves'
      })
      .option('clip-angle', {
        describe: 'use a custom clipping radius (for azimuthal projections)',
        type: 'number'
      })
      .option('clip-bbox', {
        describe: 'clip to a lat-long bounding box before projecting',
        type: 'bbox'
      })
      .option('target', targetOpt)
      .validate(validateProjOpts);

    parser.command('rectangle')
      .describe('create a rectangle from a bbox or target layer extent')
      .option('bbox', {
        describe: 'rectangle coordinates (xmin,ymin,xmax,ymax)',
        type: 'bbox'
      })
      .option('offset', offsetOpt)
      .option('aspect-ratio', aspectRatioOpt)
      .option('source', {
        describe: 'name of layer to enclose'
      })
      .option('name', nameOpt)
      .option('target', targetOpt)
      .option('no-replace', noReplaceOpt);

    parser.command('rectangles')
      .describe('create a rectangle around each feature in a layer')
      .option('offset', offsetOpt)
      .option('aspect-ratio', aspectRatioOpt)
      .option('name', nameOpt)
      .option('target', targetOpt)
      .option('no-replace', noReplaceOpt);

    parser.command('rename-fields')
      .describe('rename data fields')
      .option('fields', {
        DEFAULT: true,
        type: 'strings',
        describe: 'list of replacements (comma-sep.), e.g. \'fips=STATE_FIPS,st=state\''
      })
      .option('target', targetOpt);

    parser.command('rename-layers')
      .describe('assign new names to layers')
      .option('names', {
        DEFAULT: true,
        type: 'strings',
        describe: 'list of replacements (comma-sep.)'
      })
      .option('target', targetOpt);


    parser.command('simplify')
      .validate(validateSimplifyOpts)
      .example('Retain 10% of removable vertices\n$ mapshaper input.shp -simplify 10%')
      .describe('simplify the geometry of polygon and polyline features')
      .option('percentage', {
        DEFAULT: true,
        alias: 'p',
        type: 'percent',
        describe: 'percentage of removable points to retain, e.g. 10%'
      })
      .option('dp', {
        alias: 'rdp',
        describe: 'use Ramer-Douglas-Peucker simplification',
        assign_to: 'method'
      })
      .option('visvalingam', {
        describe: 'use Visvalingam simplification with "effective area" metric',
        assign_to: 'method'
      })
      .option('weighted', {
        describe: 'use weighted Visvalingam simplification (default)',
        assign_to: 'method'
      })
      .option('method', {
        // hidden option
      })
      .option('weighting', {
        type: 'number',
        describe: 'weighted Visvalingam coefficient (default is 0.7)'
      })
      .option('resolution', {
        describe: 'output resolution as a grid (e.g. 1000x500)'
      })
      .option('interval', {
        // alias: 'i',
        describe: 'output resolution as a distance (e.g. 100)',
        type: 'distance'
      })
      /*
      .option('value', {
        // for testing
        // describe: 'raw value of simplification threshold',
        type: 'number'
      })
      */
      .option('variable', {
        // describe: 'expect an expression with interval=, percentage= or resolution=',
        describe: 'JS expr. assigning to one of: interval= percentage= resolution=',
        type: 'flag'
      })
      .option('planar', {
        describe: 'simplify decimal degree coords in 2D space (default is 3D)',
        type: 'flag'
      })
      .option('cartesian', {
        // describe: '(deprecated) alias for planar',
        alias_to: 'planar'
      })
      .option('keep-shapes', {
        describe: 'prevent small polygon features from disappearing',
        type: 'flag'
      })
      .option('lock-box', {
        // describe: 'don't remove vertices along bbox edges'
        type: 'flag'
      })
      .option('no-repair', {
        describe: 'don\'t remove intersections introduced by simplification',
        type: 'flag'
      })
      .option('stats', {
        describe: 'display simplification statistics',
        type: 'flag'
      })
      .option('target', targetOpt);

    parser.command('slice')
      // .describe('slice a layer using polygons in another layer')
      .option('source', {
        DEFAULT: true,
        describe: 'file or layer containing clip polygons'
      })
      /*
      .option('remove-slivers', {
        describe: 'remove sliver polygons created by clipping',
        type: 'flag'
      }) */
      .option('id-field', {
        describe: 'slice id field (from source layer)'
      })
      .option('name', nameOpt)
      .option('no-snap', noSnapOpt)
      .option('target', targetOpt)
      .option('no-replace', noReplaceOpt);

    parser.command('snap')
      .describe('snap together nearby vertices')
      .option('interval', {
        describe: 'snap together vertices within a tolerance (default is small)',
        DEFAULT: true,
        type: 'distance'
      })
      .option('endpoints', {
        describe: 'only snap together the endpoints of lines',
        type: 'flag'
      })
      .option('precision', {
        describe: 'round all coordinates to a given decimal precision (e.g. 0.000001)',
        type: 'number'
      })
      .option('target', targetOpt);

    parser.command('sort')
      .describe('sort features using a JS expression')
      .option('expression', {
        DEFAULT: true,
        describe: 'JS expression to generate a sort key for each feature'
      })
      .option('ascending', {
        describe: 'sort in ascending order (default)',
        type: 'flag'
      })
      .option('descending', {
        describe: 'sort in descending order',
        type: 'flag'
      })
      .option('target', targetOpt);

    parser.command('split')
      .describe('split a layer into single-feature or multi-feature layers')
      .option('field', {
        // former name
        alias_to: 'expression'
      })
      .option('expression', {
        DEFAULT: true,
        describe: 'expression or field for grouping features and naming split layers'
      })
      .option('ids', {
        // used by gui history to split on selected features
        // describe: 'split on a list of feature ids',
        type: 'numbers'
      })
      .option('apart', {
        describe: 'save output layers to independent datasets',
        type: 'flag'
      })
      .option('target', targetOpt)
      .option('no-replace', noReplaceOpt);

    parser.command('split-on-grid')
      .describe('split features into separate layers using a grid')
      .validate(validateGridOpts)
      .option('-', {
        label: '<cols,rows>',
        describe: 'size of the grid, e.g. -split-on-grid 12,10'
      })
      .option('cols', {
        type: 'integer'
      })
      .option('rows', {
        type: 'integer'
      })
      .option('id-field', {
        describe: 'assign each feature a cell id instead of splitting layer'
      })
      // .option('no-replace', noReplaceOpt)
      .option('target', targetOpt);

    parser.command('style')
      .oldAlias('svg-style')
      .describe('set SVG style properties using JS or literal values')
      .option('where', whereOpt)
      .option('class', {
        describe: 'name of CSS class or classes (space-separated)'
      })
      // .option('css', {
      //   describe: 'inline css style'
      // })
      .option('fill', {
        describe: 'fill color; examples: #eee pink rgba(0, 0, 0, 0.2)'
      })
      .option('fill-pattern', {
        describe: 'pattern fill, ex: "hatches 2px grey 2px blue"'
      })
      .option('fill-opacity', {
        describe: 'fill opacity'
      })
      .option('fill-hatch', {
        alias_to: 'fill-pattern'
      })
      .option('stroke', {
        describe: 'stroke color'
      })
      .option('stroke-width', {
        describe: 'stroke width'
      })
      .option('stroke-dasharray', {
        describe: 'stroke dashes. Examples: "4" "2 4"'
      })
      .option('stroke-opacity', {
        describe: 'stroke opacity'
      })
      .option('opacity', {
        describe: 'opacity; example: 0.5'
      })
      .option('r', {
        describe: 'symbol radius (set this to export points as circles)',
      })
      .option('label-text', {
        describe: 'label text (set this to export points as labels)'
      })
      .option('text-anchor', {
        describe: 'label alignment; one of: start, end, middle (default)'
      })
      .option('dx', {
        describe: 'x offset of labels (default is 0)'
      })
      .option('dy', {
        describe: 'y offset of labels (default is 0/baseline-aligned)'
      })
      .option('font-size', {
        describe: 'size of label text (default is 12)'
      })
      .option('font-family', {
        describe: 'CSS font family of labels (default is sans-serif)'
      })
      .option('font-weight', {
        describe: 'CSS font weight property of labels (e.g. bold, 700)'
      })
      .option('font-style', {
        describe: 'CSS font style property of labels (e.g. italic)'
      })
       .option('letter-spacing', {
        describe: 'CSS letter-spacing property of labels'
      })
       .option('line-height', {
        describe: 'line spacing of multi-line labels (default is 1.1em)'
      })
     .option('target', targetOpt);

    parser.command('symbols')
      .describe('symbolize points as arrows, circles, stars, polygons, etc.')
      .option('type', {
        describe: 'symbol type (e.g. arrow, circle, square, star, polygon, ring)'
      })
      .option('stroke', {})
      .option('stroke-width', {})
      .option('fill', {
        describe: 'symbol fill color (filled symbols only)'
      })
      .option('stroke', {
        describe: 'symbol line color (linear symbols only)'
      })
      .option('stroke-width', {
        describe: 'symbol line width (linear symbols only)'
      })
      .option('geographic', {
        old_alias: 'polygons',
         describe: 'make geographic shapes instead of SVG objects',
        type: 'flag'
      })
      .option('pixel-scale', {
        describe: 'set symbol scale in meters per pixel (geographic option)',
        type: 'number',
      })
      // .option('flipped', {
      //   type: 'flag',
      //   describe: 'symbol is vertically flipped'
      // })
      .option('rotated', {
        type: 'flag',
        describe: 'symbol is rotated to an alternate orientation'
      })
      .option('rotation', {
        describe: 'rotation of symbol in degrees'
      })
      .option('scale', {
        describe: 'scale symbols by a multiplier',
        type: 'number'
      })
      .option('radius', {
        describe: 'distance from center to farthest point on the symbol',
        type: 'distance'
      })
      .option('sides', {
        describe: '(polygon) number of sides of a (regular) polygon symbol',
        type: 'number'
      })
      .option('points', {
        describe: '(star) number of points'
      })
      .option('point-ratio', {
        old_alias: 'star-ratio',
        describe: '(star) ratio of minor to major radius of star',
        type: 'number'
      })
      .option('radii', {
        describe: '(ring) comma-sep. list of concentric radii, ascending order'
      })
      .option('arrow-style', {
        describe: '(arrow) options: stick, standard (default is standard)'
      })
      .option('length', {
        old_alias: 'arrow-length',
        describe: '(arrow) length of arrow in pixels'
      })
      .option('direction', {
        old_alias: 'arrow-direction',
        describe: '(arrow) angle off of vertical (-90 = left-pointing)'
      })
      .option('head-angle', {
        old_alias: 'arrow-head-angle',
        describe: '(arrow) angle of tip of arrow (default is 40 degrees)'
      })
      .option('head-width', {
        old_alias: 'arrow-head-width',
        describe: '(arrow) width of arrow head from side to side'
      })
      .option('head-length', {
        old_alias: 'arrow-head-width',
        describe: '(arrow) length of head (alternative to head-angle)'
      })
      .option('head-shape', {
        // describe: 'options: a b c'
      })
      .option('stem-width', {
        old_alias: 'arrow-stem-width',
        describe: '(arrow) width of stem at its widest point'
      })
      .option('stem-length', {
        old_alias: 'arrow-stem-length',
        describe: '(arrow) alternative to length'
      })
      .option('stem-taper', {
        old_alias: 'arrow-stem-taper',
        describe: '(arrow) factor for tapering the width of the stem (0-1)'
      })
      .option('stem-curve', {
        old_alias: 'arrow-stem-curve',
        describe: '(arrow) curvature in degrees (default is 0)'
      })
      .option('min-stem-ratio', {
        old_alias: 'arrow-min-stem',
        describe: '(arrow) minimum ratio of stem to total length',
        type: 'number'
      })
      .option('anchor', {
        describe: '(arrow) takes one of: start, middle, end (default is start)'
      })
      .option('effect', {})
      // .option('where', whereOpt)
      .option('name', nameOpt)
      .option('target', targetOpt)
      .option('no-replace', noReplaceOpt);
      // .option('name', nameOpt);


    parser.command('target')
      .describe('set active layer (or layers)')
      .option('target', {
        DEFAULT: true,
        describe: 'name or index of layer to target'
      })
      .option('type', {
        describe: 'type of layer to target (polygon|polyline|point)'
      })
      .option('name', {
        describe: 'rename the target layer'
      });

    parser.command('union')
      .describe('create a flat mosaic from two or more polygon layers')
      // .option('add-fid', {
      //   describe: 'add FID_A, FID_B, ... fields to output layer',
      //   type: 'flag'
      // })
      .option('fields', {
        type: 'strings',
        describe: 'fields to retain (comma-sep.) (default is all fields)',
      })
      .option('name', nameOpt)
      .option('target', {
        describe: 'specify layers to target (comma-sep. list)'
      })
      .option('no-replace', noReplaceOpt);

    parser.command('uniq')
      .describe('delete features with the same id as a previous feature')
      .option('expression', {
        DEFAULT: true,
        describe: 'JS expression to obtain the id of a feature'
      })
      .option('max-count', {
        type: 'number',
        describe: 'max features with the same id (default is 1)'
      })
      .option('index', {
        // describe: 'add an index instead of filtering'
        type: 'flag'
      })
      .option('invert', invertOpt)
      .option('verbose', {
        describe: 'print each removed feature',
        type: 'flag'
      })
      .option('target', targetOpt);

    // Experimental commands
    parser.section('Experimental commands (may give unexpected results)');

    parser.command('add-shape')
      .describe('')
      .option('geojson', {

      })
      .option('coordinates', {

      })
      .option('properties', {

      })
      .option('name', nameOpt)
      .option('target', targetOpt)
      .option('no-replace', noReplaceOpt);

    parser.command('alpha-shapes')
      // .describe('convert points to alpha shapes (aka concave hulls)')
      .option('interval', {
        describe: 'alpha parameter',
        type: 'number'
      })
      .option('keep-points', {
        // describe: 'replace single points with tiny triangles',
        type: 'flag'
      })
      .option('name', nameOpt)
      .option('target', targetOpt)
      .option('no-replace', noReplaceOpt);

    parser.command('cluster')
      .describe('group polygons into compact clusters')
      .option('id-field', {
        describe: 'field name of cluster id (default is "cluster")'
      })
      .option('pct', {
        alias: 'p',
        type: 'percent',
        describe: 'percentage of shapes to retain, e.g. 50%'
      })
      .option('max-width', {
        describe: 'max width of cluster bounding box',
        type: 'number'
      })
      .option('max-height', {
        describe: 'max height of cluster bounding box',
        type: 'number'
      })
      .option('max-area', {
        describe: 'max area of a cluster',
        type: 'number'
      })
      .option('group-by', {
        describe: 'field name; only same-value shapes will be grouped'
      })
      .option('target', targetOpt);

    parser.command('data-fill')
      .describe('fill in missing values in a polygon layer')
      .option('field', {
        describe: 'name of field to fill in'
      })
      .option('postprocess', {alias_to: 'contiguous'})
      .option('contiguous', {
        describe: 'remove non-contiguous data islands',
        type: 'flag'
      })
      // .option('min-weight-pct', {
      //   describe: 'retain data islands weighted more than this pct'
      // })
      .option('weight-field', {
        describe: 'use field values to calculate data island weights'
      });

    parser.command('external')
      .option('module', {
        DEFAULT: true,
        describe: 'name of Node module containing the command'
      });

    parser.command('filter-points')
      // .describe('remove points that are not part of a group')
      // .option('min-group-size', {
      //   // describe: 'drop points with fewer points in the vicinity',
      //   type: 'number'
      // })
      .option('group-interval', {
        // describe: max interval separating a point from other points
        type: 'number'
      });

    parser.command('frame')
      // .describe('create a map frame at a given size')
      .option('bbox', {
        describe: 'frame coordinates (xmin,ymin,xmax,ymax)',
        type: 'bbox'
      })
      .option('offset', offsetOpt)
      .option('width', {
        describe: 'pixel width of output (default is 800)'
      })
      .option('height', {
        describe: 'pixel height of output (may be a range)'
      })
      .option('pixels', {
        describe: 'area of output in pixels (alternative to width and height)',
        type: 'number'
      })
      .option('source', {
        describe: 'name of layer to enclose'
      })
      .option('name', nameOpt);

    parser.command('fuzzy-join')
      .describe('join points to polygons, with data fill and fuzzy match')
      .option('source', {
        DEFAULT: true,
        describe: 'file or layer containing data records'
      })
      .option('field', {
        describe: 'field to join'
      })
      .option('dedup-points', {
        describe: 'uniqify points with the same location and field value',
        type: 'flag'
      })
      .option('no-dropouts', {
        describe: 'try to retain all values from the point layer',
        type: 'flag'
      })
      .option('postprocess', {alias_to: 'contiguous'})
      .option('contiguous', {
        describe: 'remove non-contiguous data islands',
        type: 'flag'
      })
      .option('target', targetOpt);

    parser.command('point-to-grid')
      .option('interval', {
        // describe: size of grid in projected units
        type: 'number'
      })
      .option('radius', {
        // describe: radius to assign each point
        type: 'number'
      })
      .option('circles', {
        // describe: create a grid of circles instead of squares
        type: 'flag'
      })
      .option('cell-margin', {
        // describe: (0-1) inset grid shapes by a percentage
        type: 'number'
      })
      .option('aligned', {
        // describe: all grids of a given cell size will be aligned
        type: 'flag'
      })
      .option('calc', calcOpt)
      .option('name', nameOpt)
      .option('target', targetOpt)
      .option('no-replace', noReplaceOpt);

    parser.command('require')
      .describe('require a Node module for use in -each expressions')
      .option('module', {
        DEFAULT: true,
        describe: 'name of Node module or path to module file'
      })
      .option('alias', {
        describe: 'Set the module name to an alias'
      })
      .option('init', {
        describe: 'JS expression to run after the module loads'
      });

    parser.command('rotate')
      // .describe('apply d3-style 3-axis rotation to a lat-long dataset')
      .option('rotation', {
        // describe: 'two or three angles of rotation',
        DEFAULT: true,
        type: 'numbers'
      })
      .option('invert', {
        type: 'flag'
      });

    parser.command('run')
      .describe('create commands on-the-fly and run them')
      .option('include', {
        // TODO: remove this option
      })
      .option('commands', {
        DEFAULT: true,
        describe: 'command string or JS expresson to generate command(s)'
      })
      .option('target', targetOpt);

    parser.command('scalebar')
      // .describe()
      .option('top', {})
      .option('right', {})
      .option('bottom', {})
      .option('left', {})
      .option('font-size', {})
      // .option('font-family', {})
      .option('label-position', {}) // top or bottom
      .option('label-text', {});

    parser.command('shape')
      .describe('create a polyline or polygon from coordinates')
      .option('coordinates', {
        describe: 'list of vertices as x,y,x,y...',
        type: 'numbers'
      })
      .option('offsets', {
        describe: 'list of vertices as offsets from coordinates list',
        type: 'numbers'
      })
      .option('closed', {
        describe: 'close an open path to create a polygon',
        type: 'flag'
      })
      .option('type', {
        // describe: 'circle or ???'
        DEFAULT: true,
      })
      .option('center', {
        //describe: 'center of the circle (default is 0,0)',
        type: 'numbers'
      })
      .option('radius', {
        //describe: 'radius of the circle in meters',
        type: 'number'
      })
      .option('radius-angle', {
        //describe: 'radius of the circle in degrees',
        type: 'number'
      })
      .option('bbox', {
        // describe: 'rectangle bounding box',
        type: 'numbers'
      })
      .option('geometry', {
        //describe: 'polygon or polyline'
      })
      .option('rotation', {
        // describe: 'two or three angles of rotation',
        type: 'numbers'
      })
      .option('name', nameOpt);

    parser.command('subdivide')
      .describe('recursively split a layer using a JS expression')
      .validate(validateExpressionOpt)
      .option('expression', {
        DEFAULT: true,
        describe: 'boolean JS expression'
      })
      .option('target', targetOpt);

    parser.section('Control flow commands');

    var ifOpts = {
      expression: {
        DEFAULT: true,
        describe: 'JS expression'
      },
      // empty: {
      //   describe: 'run if layer is empty',
      //   type: 'flag'
      // },
      // 'not-empty': {
      //   describe: 'run if layer is not empty',
      //   type: 'flag'
      // },
      layer: {
        describe: 'name or id of layer to test (default is current target)'
      },
      target: targetOpt
    };

    parser.command('if')
      .describe('run the following commands if a condition is met')
      .options(ifOpts);

    parser.command('elif')
      .describe('test an alternate condition; used after -if')
      .options(ifOpts);

    parser.command('else')
      .describe('run commands if all preceding -if/-elif conditions are false');

    parser.command('endif')
      .describe('mark the end of an -if sequence');

    parser.command('ignore')
      // .describe('stop processing if a condition is met')
      .option('empty', {
        describe: 'ignore empty files',
        type: 'flag'
      })
      .option('target', targetOpt);

    parser.command('stop')
      .describe('stop processing (skip remaining commands)');

    parser.section('Informational commands');

    parser.command('calc')
      .describe('calculate statistics about the features in a layer')
      .example('Calculate the total area of a polygon layer\n' +
        '$ mapshaper polygons.shp -calc \'sum($.area)\'')
      .example('Count census blocks in NY with zero population\n' +
        '$ mapshaper ny-census-blocks.shp -calc \'count()\' where=\'POPULATION == 0\'')
      .validate(validateExpressionOpt)
      .option('expression', {
        DEFAULT: true,
        describe: 'functions: sum() average() median() max() min() count()'
      })
      .option('where', whereOpt)
      .option('target', targetOpt);

    parser.command('colors')
      .describe('print list of color scheme names');

    parser.command('comment')
      .describe('add a comment to the sequence of commands')
      .flag('multi_arg');

    parser.command('encodings')
      .describe('print list of supported text encodings (for .dbf import)');

    parser.command('help')
      .alias('h')
      .describe('print help; takes optional command name')
      .option('command', {
        DEFAULT: true,
        describe: 'view detailed information about a command'
      });

    parser.command('info')
      .describe('print information about data layers')
      .option('save-to', {
        describe: 'name of file to save info in JSON format'
      })
      .option('target', targetOpt);

    parser.command('inspect')
      .describe('print information about a feature')
      .option('expression', {
        DEFAULT: true,
        describe: 'boolean JS expression for selecting a feature'
      })
      .option('target', targetOpt)
      .validate(validateExpressionOpt);

    parser.command('print')
      .describe('print a message to stdout')
      .flag('multi_arg');

    parser.command('projections')
      .describe('print list of supported projections');

    parser.command('quiet')
      .describe('inhibit console messages');

    parser.command('verbose')
      .describe('print verbose processing messages');

    parser.command('version')
      .alias('v')
      .describe('print mapshaper version');

    parser.command('debug');

    return parser;
  }

  // DBF format references:
  // http://www.dbf2002.com/dbf-file-format.html
  // http://www.digitalpreservation.gov/formats/fdd/fdd000325.shtml
  // http://www.clicketyclick.dk/databases/xbase/format/index.html
  // http://www.clicketyclick.dk/databases/xbase/format/data_types.html
  // esri docs:
  // https://support.esri.com/en/technical-article/000007920
  // https://desktop.arcgis.com/en/arcmap/latest/manage-data/shapefiles/geoprocessing-considerations-for-shapefile-output.htm

  // source: http://webhelp.esri.com/arcpad/8.0/referenceguide/index.htm#locales/task_code.htm
  var languageIds = [0x01,'437',0x02,'850',0x03,'1252',0x08,'865',0x09,'437',0x0A,'850',0x0B,'437',0x0D,'437',0x0E,'850',0x0F,'437',0x10,'850',0x11,'437',0x12,'850',0x13,'932',0x14,'850',0x15,'437',0x16,'850',0x17,'865',0x18,'437',0x19,'437',0x1A,'850',0x1B,'437',0x1C,'863',0x1D,'850',0x1F,'852',0x22,'852',0x23,'852',0x24,'860',0x25,'850',0x26,'866',0x37,'850',0x40,'852',0x4D,'936',0x4E,'949',0x4F,'950',0x50,'874',0x57,'1252',0x58,'1252',0x59,'1252',0x64,'852',0x65,'866',0x66,'865',0x67,'861',0x6A,'737',0x6B,'857',0x6C,'863',0x78,'950',0x79,'949',0x7A,'936',0x7B,'932',0x7C,'874',0x86,'737',0x87,'852',0x88,'857',0xC8,'1250',0xC9,'1251',0xCA,'1254',0xCB,'1253',0xCC,'1257'];

  // Language & Language family names for some code pages
  var encodingNames = {
    '932': "Japanese",
    '936': "Simplified Chinese",
    '950': "Traditional Chinese",
    '1252': "Western European",
    '949': "Korean",
    '874': "Thai",
    '1250': "Eastern European",
    '1251': "Russian",
    '1254': "Turkish",
    '1253': "Greek",
    '1257': "Baltic"
  };

  var ENCODING_PROMPT =
    "To set the text encoding, re-import using the \"encoding=\" option.\n" +
    "To list the supported encodings, run the \"encodings\" command.";

  function lookupCodePage(lid) {
    var i = languageIds.indexOf(lid);
    return i == -1 ? null : languageIds[i+1];
  }

  // function readAsciiString(bin, size) {
  //   var require7bit = true;
  //   var str = bin.readCString(size, require7bit);
  //   if (str === null) {
  //     stop("DBF file contains non-ascii text.\n" + ENCODING_PROMPT);
  //   }
  //   return utils.trim(str);
  // }

  function readStringBytes(bin, size, buf) {
    var start = bin.position();
    var count = 0, c;
    for (var i=0; i<size; i++) {
      c = bin.readUint8();
      // treating 0 as C-style string terminator (observed in-the-wild)
      // TODO: in some encodings (e.g. utf-16) the 0-byte occurs in other
      //   characters than the NULL character (ascii 0). The following code
      //   should be changed to support non-ascii-compatible encodings
      if (c === 0) break;
      if (count > 0 || c != 32) { // ignore leading spaces (e.g. DBF numbers)
        buf[count++] = c;
      }
    }
    // ignore trailing spaces (DBF string fields are typically r-padded w/ spaces)
    while (count > 0 && buf[count-1] == 32) {
      count--;
    }
    bin.position(start + size);
    return count;
  }


  function getStringReader(arg) {
    var encoding = arg || 'ascii';
    var slug = standardizeEncodingName(encoding);
    var buf = utils.createBuffer(256);
    var inNode = typeof module == 'object';

    // optimization -- use (fast) native Node conversion if available
    if (inNode && (slug == 'utf8' || slug == 'ascii')) {
      return function(bin, size) {
        var n = readStringBytes(bin, size, buf);
        return buf.toString(slug, 0, n);
      };
    }

    return function readEncodedString(bin, size) {
      var n = readStringBytes(bin, size, buf),
          str = '', i, c;
      // optimization: fall back to text decoder only if string contains non-ascii bytes
      // (data files of any encoding typically contain mostly ascii fields)
      // TODO: verify this assumption - some supported encodings may not be ascii-compatible
      for (i=0; i<n; i++) {
        c = buf[i];
        if (c > 127) {
          return bufferToString(buf, encoding, 0, n);
        }
        str += String.fromCharCode(c);
      }
      return str;
    };
  }

  function bufferContainsHighBit(buf, n) {
    for (var i=0; i<n; i++) {
      if (buf[i] >= 128) return true;
    }
    return false;
  }

  function getNumberReader() {
    var read = getStringReader('ascii');
    return function readNumber(bin, size) {
      var str = read(bin, size);
      var val;
      if (str.indexOf(',') >= 0) {
        str = str.replace(',', '.'); // handle comma decimal separator
      }
      val = parseFloat(str);
      return isNaN(val) ? null : val;
    };
  }

  function readInt(bin, size) {
    return bin.readInt32();
  }

  function readBool(bin, size) {
    var c = bin.readCString(size),
        val = null;
    if (/[ty]/i.test(c)) val = true;
    else if (/[fn]/i.test(c)) val = false;
    return val;
  }

  function readDate(bin, size) {
    var str = bin.readCString(size),
        yr = str.substr(0, 4),
        mo = str.substr(4, 2),
        day = str.substr(6, 2);
    return new Date(Date.UTC(+yr, +mo - 1, +day));
  }

  // cf. http://code.google.com/p/stringencoding/
  //
  // @src is a Buffer or ArrayBuffer or filename
  //
  function DbfReader(src, encodingArg) {
    var opts = {
      cacheSize: 0x2000000, // 32MB
      bufferSize: 0x400000 // 4MB
    };
    var dbfFile = utils.isString(src) ? new FileReader(src, opts) : new BufferReader(src);
    var header = readHeader(dbfFile);

    // encoding and fields are set on first access
    var fields;
    var encoding;

    this.size = function() {return header.recordCount;};

    this.readRow = function(i) {
      // create record reader on-the-fly
      // (delays encoding detection until we need to read data)
      return getRecordReader()(i);
    };

    this.getFields = getFieldNames;

    // TODO: switch to streaming output under Node.js
    this.getBuffer = function() {
      return dbfFile.readSync(0, dbfFile.size());
    };

    this.deleteField = function(f) {
      prepareToRead();
      fields = fields.filter(function(field) {
        return field.name != f;
      });
    };

    this.readRows = function() {
      var reader = getRecordReader();
      var data = [];
      for (var r=0, n=this.size(); r<n; r++) {
        data.push(reader(r));
      }
      return data;
    };

    // Prepare to read from table:
    // * determine encoding
    // * convert encoded field names to strings
    //   (DBF standard is ascii names, but ArcGIS etc. support encoded names)
    //
    function prepareToRead() {
      if (fields) return; // already initialized
      var headerEncoding = 'ascii';
      initEncoding();
      if (getNonAsciiHeaders().length > 0) {
        headerEncoding = getEncoding();
      }
      fields = header.fields.map(function(f) {
        var copy = utils.extend({}, f);
        copy.name = decodeString(f.namebuf, headerEncoding);
        return copy;
      });
      // Uniqify header names
      getUniqFieldNames(utils.pluck(fields, 'name')).forEach(function(name2, i) {
        fields[i].name = name2;
      });
    }

    function readHeader(reader) {
      // fetch enough bytes to accomodate any header
      var maxHeaderLen = 32 * 256 + 1; // 255 fields * fieldRecSize + headerRecSize + terminator
      var bin = reader.readToBinArray(0, Math.min(maxHeaderLen, reader.size()));
      bin.position(0).littleEndian();
      var header = {
        version: bin.readInt8(),
        updateYear: bin.readUint8(),
        updateMonth: bin.readUint8(),
        updateDay: bin.readUint8(),
        recordCount: bin.readUint32(),
        dataOffset: bin.readUint16(),
        recordSize: bin.readUint16(),
        incompleteTransaction: bin.skipBytes(2).readUint8(),
        encrypted: bin.readUint8(),
        mdx: bin.skipBytes(12).readUint8(),
        ldid: bin.readUint8()
      };
      var colOffs = 1; // first column starts on second byte of record
      var field;
      bin.skipBytes(2);
      header.fields = [];

      // Detect header terminator (LF is standard, CR has been seen in the wild)
      while (bin.peek() != 0x0D && bin.peek() != 0x0A && bin.position() < header.dataOffset - 1) {
        field = readFieldHeader(bin);
        field.columnOffset = colOffs;
        header.fields.push(field);
        colOffs += field.size;
      }
      if (colOffs != header.recordSize) {
        error("Record length mismatch; header:", header.recordSize, "detected:", colOffs);
      }
      if (bin.peek() != 0x0D) {
        message('Found a non-standard DBF header terminator (' + bin.peek() + '). DBF file may be corrupted.');
      }

      return header;
    }

    function readFieldHeader(bin) {
      var buf = utils.createBuffer(11);
      var chars = readStringBytes(bin, 11, buf);
      return {
        // name: bin.readCString(11),
        namebuf: utils.createBuffer(buf.slice(0, chars)),
        type: String.fromCharCode(bin.readUint8()),
        address: bin.readUint32(),
        size: bin.readUint8(),
        decimals: bin.readUint8(),
        id: bin.skipBytes(2).readUint8(),
        position: bin.skipBytes(2).readUint8(),
        indexFlag: bin.skipBytes(7).readUint8()
      };
    }

    function getFieldNames() {
      prepareToRead();
      return utils.pluck(fields, 'name');
    }

    function getRowOffset(r) {
      return header.dataOffset + header.recordSize * r;
    }

    function initEncoding() {
      if (encoding) return;
      encoding = encodingArg || findStringEncoding();
    }

    function getEncoding() {
      initEncoding();
      return encoding;
    }

    // Create new record objects using object literal syntax
    // (Much faster in v8 and other engines than assigning a series of properties
    //  to an object)
    function getRecordConstructor() {
      var args = getFieldNames().map(function(name, i) {
            return JSON.stringify(name) + ': arguments[' + i + ']';
          });
      return new Function('return {' + args.join(',') + '};');
    }

    // function findEofPos(bin) {
    //   var pos = bin.size() - 1;
    //   if (bin.peek(pos) != 0x1A) { // last byte may or may not be EOF
    //     pos++;
    //   }
    //   return pos;
    // }

    function getRecordReader() {
      prepareToRead();
      var readers = fields.map(getFieldReader),
          create = getRecordConstructor(),
          values = [];

      return function readRow(r) {
        var bin = dbfFile.readToBinArray(getRowOffset(r), header.recordSize),
            rowOffs = bin.position(),
            fieldOffs, field;
        if (bin.bytesLeft() < header.recordSize ||
            bin.bytesLeft() == header.recordSize && bin.peek(bin.size() - 1) == 0x1A) {
          // check for observed data error: last data byte contains EOF
          stop('Invalid DBF file: encountered end-of-file while reading data');
        }
        for (var c=0, cols=fields.length; c<cols; c++) {
          field = fields[c];
          fieldOffs = rowOffs + field.columnOffset;
          bin.position(fieldOffs);
          values[c] = readers[c](bin, field.size);
        }
        return create.apply(null, values);
      };
    }

    // @f Field metadata from dbf header
    function getFieldReader(f) {
      var type = f.type,
          r = null;
      if (type == 'I') {
        r = readInt;
      } else if (type == 'F' || type == 'N') {
        r = getNumberReader();
      } else if (type == 'L') {
        r = readBool;
      } else if (type == 'D') {
        r = readDate;
      } else if (type == 'C') {
        r = getStringReader(getEncoding());
      } else {
        message("Field \"" + f.name + "\" has an unsupported type (" + f.type + ") -- converting to null values");
        r = function() {return null;};
      }
      return r;
    }

    function findStringEncoding() {
      var ldid = header.ldid,
          codepage = lookupCodePage(ldid),
          samples = getNonAsciiSamples(),
          only7bit = samples.length === 0,
          encoding, msg;

      // First, check the ldid (language driver id) (an obsolete way to specify which
      // codepage to use for text encoding.)
      // ArcGIS up to v.10.1 sets ldid and encoding based on the 'locale' of the
      // user's Windows system :P
      //
      if (codepage && ldid != 87) {
        // if 8-bit data is found and codepage is detected, use the codepage,
        // except ldid 87, which some GIS software uses regardless of encoding.
        encoding = codepage;
      } else if (only7bit) {
        // Text with no 8-bit chars should be compatible with 7-bit ascii
        // (Most encodings are supersets of ascii)
        encoding = 'ascii';
      }

      // As a last resort, try to guess the encoding:
      if (!encoding) {
        var info = detectEncoding(samples);
        encoding = info.encoding;
        if (info.confidence < 2) {
          msg = 'Warning: Unable to auto-detect the text encoding of a DBF file with high confidence.';
          msg += '\n\nDefaulting to: ' + encoding + (encoding in encodingNames ? ' (' + encodingNames[encoding] + ')' : '');
          msg += '\n\nSample of how non-ascii text was imported:';
          msg += '\n' + formatStringsAsGrid(decodeSamples(encoding, samples).split('\n'));
          msg += decodeSamples(encoding, samples);
          msg += '\n\n' + ENCODING_PROMPT + '\n';
          message(msg);
        }
      }

      // Show a sample of decoded text if non-ascii-range text has been found
      // if (encoding && samples.length > 0) {
      //   msg = "Detected DBF text encoding: " + encoding + (encoding in encodingNames ? " (" + encodingNames[encoding] + ")" : "");
      //   message(msg);
      //   msg = decodeSamples(encoding, samples);
      //   msg = formatStringsAsGrid(msg.split('\n'));
      //   msg = "\nSample text containing non-ascii characters:" + (msg.length > 60 ? '\n' : '') + msg;
      //   verbose(msg);
      // }
      return encoding;
    }

    function getNonAsciiHeaders() {
      var arr = [];
      header.fields.forEach(function(f) {
        if (bufferContainsHighBit(f.namebuf, f.namebuf.length)) {
          arr.push(f.namebuf);
        }
      });
      return arr;
    }

    // Return an array of buffers containing text samples
    // with at least one byte outside the 7-bit ascii range.
    function getNonAsciiSamples() {
      var samples = [];
      var stringFields = header.fields.filter(function(f) {
        return f.type == 'C';
      });
      var cols = stringFields.length;
      // don't scan all the rows in large files (slow)
      var rows = Math.min(header.recordCount, 10000);
      var maxSamples = 50;
      var buf = utils.createBuffer(256);
      var index = {};
      var f, chars, sample, hash, bin, rowOffs;
      // include non-ascii field names, if any
      samples = getNonAsciiHeaders();
      for (var r=0; r<rows; r++) {
        bin = dbfFile.readToBinArray(getRowOffset(r), header.recordSize);
        rowOffs = bin.position();
        for (var c=0; c<cols; c++) {
          if (samples.length >= maxSamples) break;
          f = stringFields[c];
          // bin.position(getRowOffset(r) + f.columnOffset);
          bin.position(rowOffs + f.columnOffset);
          chars = readStringBytes(bin, f.size, buf);
          if (chars > 0 && bufferContainsHighBit(buf, chars)) {
            sample = utils.createBuffer(buf.slice(0, chars)); //
            hash = sample.toString('hex');
            if (hash in index === false) { // avoid duplicate samples
              index[hash] = true;
              samples.push(sample);
            }
          }
        }
      }
      return samples;
    }
  }

  function importDbfTable(src, o) {
    var opts = o || {};
    return new ShapefileTable(src, opts.encoding);
  }

  // Implements the DataTable api for DBF file data.
  // We avoid touching the raw DBF field data if possible. This way, we don't need
  // to parse the DBF at all in common cases, like importing a Shapefile, editing
  // just the shapes and exporting in Shapefile format.
  // TODO: consider accepting just the filename, so buffer doesn't consume memory needlessly.
  //
  function ShapefileTable(src, encoding) {
    var reader = new DbfReader(src, encoding),
        altered = false,
        table;

    function getTable() {
      if (!table) {
        // export DBF records on first table access
        table = new DataTable(reader.readRows());
        reader = null;
        src = null; // null out references to DBF data for g.c.
      }
      return table;
    }

    this.exportAsDbf = function(opts) {
      // export original dbf bytes if possible
      // (e.g. if the data attributes haven't changed)
      var useOriginal = !!reader && !altered && !opts.field_order && !opts.encoding;
      if (useOriginal) {
        try {
          // Maximum Buffer in current Node.js is 2GB
          // We fall back to import-export if getBuffer() fails.
          // This may produce a buffer that does not exceed the maximum size.
          return reader.getBuffer();
        } catch(e) {}
      }
      return Dbf.exportRecords(getTable().getRecords(), opts.encoding, opts.field_order);
    };

    this.getReadOnlyRecordAt = function(i) {
      return reader ? reader.readRow(i) : table.getReadOnlyRecordAt(i);
    };

    this.deleteField = function(f) {
      if (table) {
        table.deleteField(f);
      } else {
        altered = true;
        reader.deleteField(f);
      }
    };

    this.getRecords = function() {
      return getTable().getRecords();
    };

    this.getFields = function() {
      return reader ? reader.getFields() : table.getFields();
    };

    this.isEmpty = function() {
      return reader ? this.size() === 0 : table.isEmpty();
    };

    this.size = function() {
      return reader ? reader.size() : table.size();
    };
  }

  Object.assign(ShapefileTable.prototype, DataTable.prototype);

  var DbfImport = /*#__PURE__*/Object.freeze({
    __proto__: null,
    importDbfTable: importDbfTable,
    ShapefileTable: ShapefileTable
  });

  function translateShapefileType(shpType) {
    if ([ShpType.POLYGON, ShpType.POLYGONM, ShpType.POLYGONZ].includes(shpType)) {
      return 'polygon';
    } else if ([ShpType.POLYLINE, ShpType.POLYLINEM, ShpType.POLYLINEZ].includes(shpType)) {
      return 'polyline';
    } else if ([ShpType.POINT, ShpType.POINTM, ShpType.POINTZ,
        ShpType.MULTIPOINT, ShpType.MULTIPOINTM, ShpType.MULTIPOINTZ].includes(shpType)) {
      return 'point';
    }
    return null;
  }

  function isSupportedShapefileType(t) {
    return [0,1,3,5,8,11,13,15,18,21,23,25,28].includes(t);
  }

  var ShpCommon = /*#__PURE__*/Object.freeze({
    __proto__: null,
    translateShapefileType: translateShapefileType,
    isSupportedShapefileType: isSupportedShapefileType
  });

  function getNullRecord(id) {
    return {
      id: id,
      isNull: true,
      pointCount: 0,
      partCount: 0,
      byteLength: 12
    };
  }

  // Returns a constructor function for a shape record class with
  //   properties and methods for reading coordinate data.
  //
  // Record properties
  //   type, isNull, byteLength, pointCount, partCount (all types)
  //
  // Record methods
  //   read(), readPoints() (all types)
  //   readBounds(), readCoords()  (all but single point types)
  //   readPartSizes() (polygon and polyline types)
  //   readZBounds(), readZ() (Z types except POINTZ)
  //   readMBounds(), readM(), hasM() (M and Z types, except POINT[MZ])
  //
  function ShpRecordClass(type) {
    var hasBounds = ShpType.hasBounds(type),
        hasParts = ShpType.isMultiPartType(type),
        hasZ = ShpType.isZType(type),
        hasM = ShpType.isMType(type),
        singlePoint = !hasBounds,
        mzRangeBytes = singlePoint ? 0 : 16,
        constructor, proto;

    // @bin is a BinArray set to the first data byte of a shape record
    constructor = function ShapeRecord(bin, bytes) {
      var pos = bin.position();
      this.id = bin.bigEndian().readUint32();
      this.type = bin.littleEndian().skipBytes(4).readUint32();
      if (this.type === 0 || type === 0) {
        return getNullRecord(this.id);
      }
      if (bytes > 0 !== true || (this.type != type && this.type !== 0)) {
        error("Unable to read a shape -- .shp file may be corrupted");
      }
      this.byteLength = bytes; // bin.readUint32() * 2 + 8; // bytes in content section + 8 header bytes
      if (singlePoint) {
        this.pointCount = 1;
        this.partCount = 1;
      } else {
        bin.skipBytes(32); // skip bbox
        this.partCount = hasParts ? bin.readUint32() : 1;
        this.pointCount = bin.readUint32();
      }
      this._data = function() {
        return bin.position(pos);
      };
    };

    // base prototype has methods shared by all Shapefile types except NULL type
    // (Type-specific methods are mixed in below)
    var baseProto = {
      // return offset of [x, y] point data in the record
      _xypos: function() {
        var offs = 12; // skip header & record type
        if (!singlePoint) offs += 4; // skip point count
        if (hasBounds) offs += 32;
        if (hasParts) offs += 4 * this.partCount + 4; // skip part count & index
        return offs;
      },

      readCoords: function() {
        if (this.pointCount === 0) return null;
        var partSizes = this.readPartSizes(),
            xy = this._data().skipBytes(this._xypos());

        return partSizes.map(function(pointCount) {
          return xy.readFloat64Array(pointCount * 2);
        });
      },

      readXY: function() {
        if (this.pointCount === 0) return new Float64Array(0);
        return this._data().skipBytes(this._xypos()).readFloat64Array(this.pointCount * 2);
      },

      readPoints: function() {
        var xy = this.readXY(),
            zz = hasZ ? this.readZ() : null,
            mm = hasM && this.hasM() ? this.readM() : null,
            points = [], p;

        for (var i=0, n=xy.length / 2; i<n; i++) {
          p = [xy[i*2], xy[i*2+1]];
          if (zz) p.push(zz[i]);
          if (mm) p.push(mm[i]);
          points.push(p);
        }
        return points;
      },

      // Return an array of point counts in each part
      // Parts containing zero points are skipped (Shapefiles with zero-point
      // parts are out-of-spec but exist in the wild).
      readPartSizes: function() {
        var sizes = [];
        var partLen, startId, bin;
        if (this.pointCount === 0) ; else if (this.partCount == 1) {
          // single-part type or multi-part type with one part
          sizes.push(this.pointCount);
        } else {
          // more than one part
          startId = 0;
          bin = this._data().skipBytes(56); // skip to second entry in part index
          for (var i=0, n=this.partCount; i<n; i++) {
            partLen = (i < n - 1 ? bin.readUint32() : this.pointCount) - startId;
            if (partLen > 0) {
              sizes.push(partLen);
              startId += partLen;
            }
          }
        }
        return sizes;
      }
    };

    var singlePointProto = {
      read: function() {
        var n = 2;
        if (hasZ) n++;
        if (this.hasM()) n++;
        return this._data().skipBytes(12).readFloat64Array(n);
      },

      stream: function(sink) {
        var src = this._data().skipBytes(12);
        sink.addPoint(src.readFloat64(), src.readFloat64());
        sink.endPath();
      }
    };

    var multiCoordProto = {
      readBounds: function() {
        return this._data().skipBytes(12).readFloat64Array(4);
      },

      stream: function(sink) {
        var sizes = this.readPartSizes(),
            xy = this.readXY(),
            i = 0, j = 0, n;
        while (i < sizes.length) {
          n = sizes[i];
          while (n-- > 0) {
            sink.addPoint(xy[j++], xy[j++]);
          }
          sink.endPath();
          i++;
        }
        if (xy.length != j) error('Counting error');
      },

      // TODO: consider switching to this simpler functino
      stream2: function(sink) {
        var sizes = this.readPartSizes(),
            bin = this._data().skipBytes(this._xypos()),
            i = 0, n;
        while (i < sizes.length) {
          n = sizes[i];
          while (n-- > 0) {
            sink.addPoint(bin.readFloat64(), bin.readFloat64());
          }
          sink.endPath();
          i++;
        }
      },

      read: function() {
        var parts = [],
            sizes = this.readPartSizes(),
            points = this.readPoints();
        for (var i=0, n = sizes.length - 1; i<n; i++) {
          parts.push(points.splice(0, sizes[i]));
        }
        parts.push(points);
        return parts;
      }
    };

    var mProto = {
      _mpos: function() {
        var pos = this._xypos() + this.pointCount * 16;
        if (hasZ) {
          pos += this.pointCount * 8 + mzRangeBytes;
        }
        return pos;
      },

      readMBounds: function() {
        return this.hasM() ? this._data().skipBytes(this._mpos()).readFloat64Array(2) : null;
      },

      // TODO: group into parts, like readCoords()
      readM: function() {
        return this.hasM() ? this._data().skipBytes(this._mpos() + mzRangeBytes).readFloat64Array(this.pointCount) : null;
      },

      // Test if this record contains M data
      // (according to the Shapefile spec, M data is optional in a record)
      //
      hasM: function() {
        var bytesWithoutM = this._mpos(),
            bytesWithM = bytesWithoutM + this.pointCount * 8 + mzRangeBytes;
        if (this.byteLength == bytesWithoutM) {
          return false;
        } else if (this.byteLength == bytesWithM) {
          return true;
        } else {
          error("#hasM() Counting error");
        }
      }
    };

    var zProto = {
      _zpos: function() {
        return this._xypos() + this.pointCount * 16;
      },

      readZBounds: function() {
        return this._data().skipBytes(this._zpos()).readFloat64Array(2);
      },

      // TODO: group into parts, like readCoords()
      readZ: function() {
        return this._data().skipBytes(this._zpos() + mzRangeBytes).readFloat64Array(this.pointCount);
      }
    };

    if (type === 0) {
      proto = {};
    } else if (singlePoint) {
      proto = Object.assign(baseProto, singlePointProto);
    } else {
      proto = Object.assign(baseProto, multiCoordProto);
    }
    if (hasZ) Object.assign(proto, zProto);
    if (hasM) Object.assign(proto, mProto);

    constructor.prototype = proto;
    proto.constructor = constructor;
    return constructor;
  }

  // Read data from a .shp file
  // @src is an ArrayBuffer, Node.js Buffer or filename
  //
  //    // Example: iterating using #nextShape()
  //    var reader = new ShpReader(buf), s;
  //    while (s = reader.nextShape()) {
  //      // process the raw coordinate data yourself...
  //      var coords = s.readCoords(); // [[x,y,x,y,...], ...] Array of parts
  //      var zdata = s.readZ();  // [z,z,...]
  //      var mdata = s.readM();  // [m,m,...] or null
  //      // .. or read the shape into nested arrays
  //      var data = s.read();
  //    }
  //
  //    // Example: reading records using a callback
  //    var reader = new ShpReader(buf);
  //    reader.forEachShape(function(s) {
  //      var data = s.read();
  //    });
  //
  function ShpReader(shpSrc, shxSrc) {
    if (this instanceof ShpReader === false) {
      return new ShpReader(shpSrc, shxSrc);
    }
    var shpFile = utils.isString(shpSrc) ? new FileReader(shpSrc) : new BufferReader(shpSrc);
    var header = parseHeader(shpFile.readToBinArray(0, 100));
    var shpType = header.type;
    var shpOffset = 100; // used when reading .shp without .shx
    var recordCount = 0;
    var badRecordNumberCount = 0;
    var RecordClass = new ShpRecordClass(shpType);
    var shxBin, shxFile;

    if (shxSrc) {
      shxFile = utils.isString(shxSrc) ? new FileReader(shxSrc) : new BufferReader(shxSrc);
      shxBin = shxFile.readToBinArray(0, shxFile.size()).bigEndian();
    }

    this.header = function() {
      return header;
    };

    // Callback interface: for each record in a .shp file, pass a
    //   record object to a callback function
    //
    this.forEachShape = function(callback) {
      var shape = this.nextShape();
      while (shape) {
        callback(shape);
        shape = this.nextShape();
      }
    };

    // Iterator interface for reading shape records
    this.nextShape = function() {
      var shape;
      if (!shpFile) {
        error('Tried to read from a used ShpReader');
        // return null; // this reader was already used
      }
      shape = readNextShape(recordCount);
      if (!shape) {
        done();
        return null;
      }
      recordCount++;
      return shape;
    };

    // Returns a shape record or null if no more shapes can be read
    // i: Expected 0-based index of the next record
    //
    function readNextShape(i) {
      return shxBin ?
        readIndexedShape(shpFile, shxBin, i) :
        readNonIndexedShape(shpFile, shpOffset, i);
    }

    function done() {
      shpFile.close();
      shpFile = shxFile = shxBin = null;
      if (badRecordNumberCount > 0) {
        message(`Warning: ${badRecordNumberCount}/${recordCount} features have non-standard record numbers in the .shp file.`);
      }
    }

    function parseHeader(bin) {
      var header = {
        signature: bin.bigEndian().readUint32(),
        byteLength: bin.skipBytes(20).readUint32() * 2,
        version: bin.littleEndian().readUint32(),
        type: bin.readUint32(),
        bounds: bin.readFloat64Array(4), // xmin, ymin, xmax, ymax
        zbounds: bin.readFloat64Array(2),
        mbounds: bin.readFloat64Array(2)
      };

      if (header.signature != 9994) {
        error("Not a valid .shp file");
      }

      if (!isSupportedShapefileType(header.type)) {
        error("Unsupported .shp type:", header.type);
      }

      if (header.byteLength != shpFile.size()) {
        error("File size of .shp doesn't match size in header");
      }

      return header;
    }


    function readShapeAtOffset(shpFile, offset) {
      var fileSize = shpFile.size();
      if (offset + 12 > fileSize) return null; // reached end-of-file
      var bin = shpFile.readToBinArray(offset, 12);
      bin.bigEndian().readUint32();
      // record size is bytes in content section + 8 header bytes
      var recordSize = bin.readUint32() * 2 + 8;
      var recordType = bin.littleEndian().readUint32();
      var goodSize = offset + recordSize <= fileSize && recordSize >= 12;
      var goodType = recordType === 0 || recordType == shpType;
      if (!goodSize || !goodType) {
        return null;
      }
      bin = shpFile.readToBinArray(offset, recordSize);
      return new RecordClass(bin, recordSize);
    }

    function readIndexedShape(shpFile, shxBin, i) {
      if (shxBin.size() <= 100 + i * 8) return null; // done
      shxBin.position(100 + i * 8);
      var expectedId = i + 1;
      var offset = shxBin.readUint32() * 2;
      shxBin.readUint32() * 2; // TODO: match this to recLen in .shp
      var shape = readShapeAtOffset(shpFile, offset);
      if (!shape) {
        stop('Index of Shapefile record', expectedId, 'in the .shx file is invalid.');
      }
      if (shape.id != expectedId) {
        badRecordNumberCount++;
        verbose(`Warning: A feature has a different record number in .shx (${expectedId}) and .shp (${shape.id}).`);
      }
      // TODO: consider printing verbose message if a .shp file contains garbage bytes
      // example files:
      // ne_10m_admin_0_boundary_lines_land.shp
      // ne_110m_admin_0_scale_rank.shp
      return shape;
    }

    // The Shapefile specification does not require records to be densely packed or
    // in consecutive sequence in the .shp file. This is a problem when the .shx
    // index file is not present.
    //
    // Here, we try to scan past any invalid content to find the next record.
    // Records are required to be in sequential order.
    //
    function readNonIndexedShape(shpFile, start, i) {
      var expectedId = i + 1, // Shapefile ids are 1-based
          offset = start,
          fileSize = shpFile.size(),
          shape = null,
          bin, recordId, recordType, isValidType;
      while (offset + 12 <= fileSize) {
        bin = shpFile.readToBinArray(offset, 12);
        recordId = bin.bigEndian().readUint32();
        recordType = bin.littleEndian().skipBytes(4).readUint32();
        isValidType = recordType == shpType || recordType === 0;
        if (!isValidType || recordId != expectedId && recordType === 0) {
          offset += 4; // keep scanning -- try next integer position
          continue;
        }
        shape = readShapeAtOffset(shpFile, offset);
        if (!shape) break; // probably ran into end of file
        shpOffset = offset + shape.byteLength; // update
        if (recordId == expectedId) break; // found an apparently valid shape
        if (recordId < expectedId) {
          message("Found a Shapefile record with the same id as a previous record (" + shape.id + ") -- skipping.");
          offset += shape.byteLength;
        } else {
          stop("Shapefile contains an out-of-sequence record. Possible data corruption -- bailing.");
        }
      }
      if (shape && offset > start) {
        verbose("Skipped over " + (offset - start) + " non-data bytes in the .shp file.");
      }
      return shape;
    }
  }

  ShpReader.prototype.type = function() {
    return this.header().type;
  };

  // Apply snapping, remove duplicate coords and clean up defective paths in a dataset
  // Assumes that any CRS info has been added to the dataset
  // @opts: import options
  function cleanPathsAfterImport(dataset, opts) {
    var arcs = dataset.arcs;
    var snapDist;
    if (opts.snap || opts.auto_snap || opts.snap_interval) { // auto_snap is older name
      if (opts.snap_interval) {
        snapDist = convertIntervalParam(opts.snap_interval, getDatasetCRS(dataset));
      }
      if (arcs) {
        snapCoords(arcs, snapDist);
      }
    }
    dataset.layers.forEach(function(lyr) {
      if (layerHasPaths(lyr)) {
        cleanShapes(lyr.shapes, arcs, lyr.geometry_type);
      }
    });
  }

  function pointHasValidCoords(p) {
    // The Shapefile spec states that "measures" less then -1e38 indicate null values
    // This should not apply to coordinate data, but in-the-wild Shapefiles have been
    // seen with large negative values indicating null coordinates.
    // This test catches these and also NaNs, but does not detect other kinds of
    // invalid coords
    return p[0] > -1e38 && p[1] > -1e38;
  }

  // Accumulates points in buffers until #endPath() is called
  // @drain callback: function(xarr, yarr, size) {}
  //
  function PathImportStream(drain) {
    var buflen = 10000,
        xx = new Float64Array(buflen),
        yy = new Float64Array(buflen),
        i = 0;

    this.endPath = function() {
      drain(xx, yy, i);
      i = 0;
    };

    this.addPoint = function(x, y) {
      if (i >= buflen) {
        buflen = Math.ceil(buflen * 1.3);
        xx = utils.extendBuffer(xx, buflen);
        yy = utils.extendBuffer(yy, buflen);
      }
      xx[i] = x;
      yy[i] = y;
      i++;
    };
  }

  // Import path data from a non-topological source (Shapefile, GeoJSON, etc)
  // in preparation for identifying topology.
  // @opts.reserved_points -- estimate of points in dataset, for pre-allocating buffers
  //
  function PathImporter(opts) {
    var bufSize = opts.reserved_points > 0 ? opts.reserved_points : 20000,
        xx = new Float64Array(bufSize),
        yy = new Float64Array(bufSize),
        shapes = [],
        properties = [],
        nn = [],
        types = [],
        collectionType = opts.type || null, // possible values: polygon, polyline, point
        round = null,
        pathId = -1,
        shapeId = -1,
        pointId = 0,
        dupeCount = 0,
        openRingCount = 0;

    if (opts.precision) {
      round = getRoundingFunction(opts.precision);
    }

    // mix in #addPoint() and #endPath() methods
    utils.extend(this, new PathImportStream(importPathCoords));

    this.startShape = function(d) {
      shapes[++shapeId] = null;
      if (d) properties[shapeId] = d;
    };

    this.importLine = function(points) {
      if (points.length < 2) {
        verbose("Skipping a defective line");
        return;
      }
      setShapeType('polyline');
      this.importPath(points);
    };

    this.importPoints = function(points) {
      setShapeType('point');
      points = points.filter(pointHasValidCoords);
      if (round) {
        points.forEach(function(p) {
          p[0] = round(p[0]);
          p[1] = round(p[1]);
        });
      }
      points.forEach(appendToShape);
    };

    this.importRing = function(points, isHole) {
      var area = geom.getPlanarPathArea2(points);
      if (!area || points.length < 4) {
        verbose("Skipping a defective ring");
        return;
      }
      setShapeType('polygon');
      if (isHole === true && area > 0 || isHole === false && area < 0) {
        // GeoJSON rings may be either direction -- no point in logging reversal
        // verbose("Reversing", isHole ? "a CW hole" : "a CCW ring");
        points.reverse();
      }
      this.importPath(points);
    };

    // Import an array of [x, y] Points
    this.importPath = function importPath(points) {
      var p;
      for (var i=0, n=points.length; i<n; i++) {
        p = points[i];
        this.addPoint(p[0], p[1]);
      }
      this.endPath();
    };

    // Return imported dataset
    // Apply any requested snapping and rounding
    // Remove duplicate points, check for ring inversions
    //
    this.done = function() {
      var arcs;
      var layers;
      var lyr = {name: ''};

      if (dupeCount > 0) {
        verbose(utils.format("Removed %,d duplicate point%s", dupeCount, utils.pluralSuffix(dupeCount)));
      }
      if (openRingCount > 0) {
        message(utils.format("Closed %,d open polygon ring%s", openRingCount, utils.pluralSuffix(openRingCount)));
      }
      if (pointId > 0) {
         if (pointId < xx.length) {
          xx = xx.subarray(0, pointId);
          yy = yy.subarray(0, pointId);
        }
        arcs = new ArcCollection(nn, xx, yy);

        //if (opts.snap || opts.auto_snap || opts.snap_interval) { // auto_snap is older name
        //  internal.snapCoords(arcs, opts.snap_interval);
        //}
      }

      if (collectionType == 'mixed') {
        layers = divideFeaturesByType(shapes, properties, types);

      } else {
        lyr = {geometry_type: collectionType};
        if (collectionType) {
          lyr.shapes = shapes;
        }
        if (properties.length > 0) {
          lyr.data = new DataTable(properties);
        }
        layers = [lyr];
      }

      layers.forEach(function(lyr) {
        //if (internal.layerHasPaths(lyr)) {
          //internal.cleanShapes(lyr.shapes, arcs, lyr.geometry_type);
        //}
        if (lyr.data) {
          fixInconsistentFields(lyr.data.getRecords());
        }
      });

      return {
        arcs: arcs || null,
        info: {},
        layers: layers
      };
    };

    function setShapeType(t) {
      var currType = shapeId < types.length ? types[shapeId] : null;
      if (!currType) {
        types[shapeId] = t;
        if (!collectionType) {
          collectionType = t;
        } else if (t != collectionType) {
          collectionType = 'mixed';
        }
      } else if (currType != t) {
        stop("Unable to import mixed-geometry features");
      }
    }

    function checkBuffers(needed) {
      if (needed > xx.length) {
        var newLen = Math.max(needed, Math.ceil(xx.length * 1.5));
        xx = utils.extendBuffer(xx, newLen, pointId);
        yy = utils.extendBuffer(yy, newLen, pointId);
      }
    }

    function appendToShape(part) {
      var currShape = shapes[shapeId] || (shapes[shapeId] = []);
      currShape.push(part);
    }

    function appendPath(n) {
      pathId++;
      nn[pathId] = n;
      appendToShape([pathId]);
    }

    function importPathCoords(xsrc, ysrc, n) {
      var count = 0;
      var x, y, prevX, prevY;
      checkBuffers(pointId + n);
      for (var i=0; i<n; i++) {
        x = xsrc[i];
        y = ysrc[i];
        if (round) {
          x = round(x);
          y = round(y);
        }
        if (i > 0 && x == prevX && y == prevY) {
          dupeCount++;
        } else {
          xx[pointId] = x;
          yy[pointId] = y;
          pointId++;
          count++;
        }
        prevY = y;
        prevX = x;
      }

      // check for open rings
      if (collectionType == 'polygon' && count > 0) {
        if (xsrc[0] != xsrc[n-1] || ysrc[0] != ysrc[n-1]) {
          checkBuffers(pointId + 1);
          xx[pointId] = xsrc[0];
          yy[pointId] = ysrc[0];
          openRingCount++;
          pointId++;
          count++;
        }
      }

      appendPath(count);
    }
  }

  var PathImport = /*#__PURE__*/Object.freeze({
    __proto__: null,
    cleanPathsAfterImport: cleanPathsAfterImport,
    pointHasValidCoords: pointHasValidCoords,
    PathImporter: PathImporter
  });

  // Read Shapefile data from a file, ArrayBuffer or Buffer
  // @shp, @shx: filename or buffer
  function importShp(shp, shx, opts) {
    var reader = new ShpReader(shp, shx),
        shpType = reader.type(),
        type = translateShapefileType(shpType),
        importOpts = utils.defaults({
          type: type,
          reserved_points: Math.round(reader.header().byteLength / 16)
        }, opts),
        importer = new PathImporter(importOpts);

    if (!isSupportedShapefileType(shpType)) {
      stop("Unsupported Shapefile type:", shpType);
    }
    if (ShpType.isZType(shpType)) {
      verbose("Warning: Shapefile Z data will be lost.");
    } else if (ShpType.isMType(shpType)) {
      verbose("Warning: Shapefile M data will be lost.");
    }

    // TODO: test cases: null shape; non-null shape with no valid parts
    reader.forEachShape(function(shp) {
      importer.startShape();
      if (shp.isNull) ; else if (type == 'point') {
        importer.importPoints(shp.readPoints());
      } else {
        shp.stream(importer);
        // shp.stream2(importer);
      }
    });

    return importer.done();
  }

  var ShpImport = /*#__PURE__*/Object.freeze({
    __proto__: null,
    importShp: importShp
  });

  function importGeoJSON(src, optsArg) {
    var opts = optsArg || {};
    var supportedGeometries = Object.keys(GeoJSON.pathImporters),
        srcObj = utils.isString(src) ? JSON.parse(src) : src,
        importer = new GeoJSONParser(opts),
        srcCollection, dataset;

    // Convert single feature or geometry into a collection with one member
    if (srcObj.type == 'Feature') {
      srcCollection = {
        type: 'FeatureCollection',
        features: [srcObj]
      };
    } else if (supportedGeometries.includes(srcObj.type)) {
      srcCollection = {
        type: 'GeometryCollection',
        geometries: [srcObj]
      };
    } else {
      srcCollection = srcObj;
    }
    (srcCollection.features || srcCollection.geometries || []).forEach(importer.parseObject);
    dataset = importer.done();
    importCRS(dataset, srcObj); // TODO: remove this
    return dataset;
  }

  function GeoJSONParser(opts) {
    var idField = opts.id_field || GeoJSON.ID_FIELD,
        importer = new PathImporter(opts);

    this.parseObject = function(o) {
      var geom, rec;
      if (!o || !o.type) {
        // not standard GeoJSON -- importing as null record
        // (useful when parsing GeoJSON generated internally)
        geom = null;
      } else if (o.type == 'Feature') {
        geom = o.geometry;
        rec = o.properties || {};
        if ('id' in o) {
          rec[idField] = o.id;
        }
      } else {
        geom = o;
      }
      // TODO: improve so geometry_type option skips features instead of creating null geometries
      if (geom && geom.type == 'GeometryCollection') {
        GeoJSON.importComplexFeature(importer, geom, rec, opts);
      } else if (opts.single_part && isMultiPartGeometry(geom)) {
        GeoJSON.importMultiAsSingles(importer, geom, rec, opts);
      } else {
        GeoJSON.importSimpleFeature(importer, geom, rec, opts);
      }
    };

    this.done = function() {
      return importer.done();
    };
  }

  GeoJSON.importComplexFeature = function(importer, geom, rec, opts) {
    var types = divideGeometriesByType(geom.geometries || []);
    if (types.length === 0) {
      importer.startShape(rec); // import a feature with null geometry
      return;
    }
    types.forEach(function(geometries, i) {
      importer.startShape(copyRecord(rec));
      geometries.forEach(function(geom) {
        GeoJSON.importSimpleGeometry(importer, geom, opts);
      });
    });
  };

  function divideGeometriesByType(geometries, index) {
    index = index || {};
    geometries.forEach(function(geom) {
      if (!geom) return;
      var mtype = GeoJSON.translateGeoJSONType(geom.type);
      if (mtype) {
        if (mtype in index === false) {
          index[mtype] = [];
        }
        index[mtype].push(geom);
      } else if (geom.type == 'GeometryCollection') {
        divideGeometriesByType(geom.geometries || [], index);
      }
    });
    return Object.values(index);
  }

  function isMultiPartGeometry(geom) {
    return geom && geom.type && geom.type.indexOf('Multi') === 0;
  }

  GeoJSON.importSimpleFeature = function(importer, geom, rec, opts) {
    importer.startShape(rec);
    GeoJSON.importSimpleGeometry(importer, geom, opts);
  };

  // Split a multi-part feature into several single features
  GeoJSON.importMultiAsSingles = function(importer, geom, rec, opts) {
    geom.coordinates.forEach(function(coords, i) {
      var geom2 = {
        type: geom.type.substr(5),
        coordinates: coords
      };
      var rec2 = i === 0 ? rec : copyRecord(rec);
      GeoJSON.importSimpleFeature(importer, geom2, rec2, opts);
    });
  };

  GeoJSON.importSimpleGeometry = function(importer, geom, opts) {
    var type = geom ? geom.type : null;
    if (type === null) ; else if (type in GeoJSON.pathImporters) {
      if (opts.geometry_type && opts.geometry_type != GeoJSON.translateGeoJSONType(type)) {
        // kludge to filter out all but one type of geometry
        return;
      }
      GeoJSON.pathImporters[type](geom.coordinates, importer);
    } else {
      verbose("Unsupported geometry type:", geom.type);
    }
  };


  // Functions for importing geometry coordinates using a PathImporter
  //
  GeoJSON.pathImporters = {
    LineString: function(coords, importer) {
      importer.importLine(coords);
    },
    MultiLineString: function(coords, importer) {
      for (var i=0; i<coords.length; i++) {
        GeoJSON.pathImporters.LineString(coords[i], importer);
      }
    },
    Polygon: function(coords, importer) {
      for (var i=0; i<coords.length; i++) {
        importer.importRing(coords[i], i > 0);
      }
    },
    MultiPolygon: function(coords, importer) {
      for (var i=0; i<coords.length; i++) {
        GeoJSON.pathImporters.Polygon(coords[i], importer);
      }
    },
    Point: function(coord, importer) {
      importer.importPoints([coord]);
    },
    MultiPoint: function(coords, importer) {
      importer.importPoints(coords);
    }
  };


  function importCRS(dataset, jsonObj) {
    if ('crs' in jsonObj) {
      dataset.info.input_geojson_crs = jsonObj.crs;
    }
  }

  var GeojsonImport = /*#__PURE__*/Object.freeze({
    __proto__: null,
    importGeoJSON: importGeoJSON,
    GeoJSONParser: GeoJSONParser,
    importCRS: importCRS
  });

  // Convert a TopoJSON topology into mapshaper's internal format
  // Side-effect: data in topology is modified
  //
  function importTopoJSON(topology, opts) {
    var dataset, arcs, layers;

    if (utils.isString(topology)) {
      topology = JSON.parse(topology);
    }

    if (topology.arcs && topology.arcs.length > 0) {
      // TODO: apply transform to ArcCollection, not input arcs
      if (topology.transform) {
        TopoJSON.decodeArcs(topology.arcs, topology.transform);
      }

      if (opts && opts.precision) {
        TopoJSON.roundCoords(topology.arcs, opts.precision);
      }

      arcs = new ArcCollection(topology.arcs);
    }

    layers = Object.keys(topology.objects).reduce(function(memo, name) {
      var layers = TopoJSON.importObject(topology.objects[name], arcs, opts),
          lyr;
      for (var i=0, n=layers.length; i<n; i++) {
        lyr = layers[i];
        lyr.name = name; // TODO: consider type-suffixes if different-typed layers
        memo.push(lyr);
      }
      return memo;
    }, []);

    layers.forEach(function(lyr) {
      if (layerHasPaths(lyr)) {
        // Cleaning here may be unnecessary
        // (cleanPathsAfterImport() is called in mapshaper-import.js)
        cleanShapes(lyr.shapes, arcs, lyr.geometry_type);
      }
      if (lyr.geometry_type == 'point' && topology.transform) {
        TopoJSON.decodePoints(lyr.shapes, topology.transform);
      }
      if (lyr.data) {
        fixInconsistentFields(lyr.data.getRecords());
      }
    });

    dataset = {
      layers: layers,
      arcs: arcs,
      info: {}
    };
    importCRS(dataset, topology);
    if (topology.metadata) {
      importMetadata(dataset, topology.metadata);
    }
    return dataset;
  }

  TopoJSON.decodePoints = function(shapes, transform) {
    forEachPoint(shapes, function(p) {
      p[0] = p[0] * transform.scale[0] + transform.translate[0];
      p[1] = p[1] * transform.scale[1] + transform.translate[1];
    });
  };

  TopoJSON.decodeArcs = function(arcs, transform) {
    var mx = transform.scale[0],
        my = transform.scale[1],
        bx = transform.translate[0],
        by = transform.translate[1];

    arcs.forEach(function(arc) {
      var prevX = 0,
          prevY = 0,
          xy, x, y;
      for (var i=0, len=arc.length; i<len; i++) {
        xy = arc[i];
        x = xy[0] + prevX;
        y = xy[1] + prevY;
        xy[0] = x * mx + bx;
        xy[1] = y * my + by;
        prevX = x;
        prevY = y;
      }
    });
  };

  // TODO: consider removing dupes...
  TopoJSON.roundCoords = function(arcs, precision) {
    var round = getRoundingFunction(precision),
        p;
    arcs.forEach(function(arc) {
      for (var i=0, len=arc.length; i<len; i++) {
        p = arc[i];
        p[0] = round(p[0]);
        p[1] = round(p[1]);
      }
    });
  };

  TopoJSON.importObject = function(obj, arcs, opts) {
    var importer = new TopoJSON.GeometryImporter(arcs, opts);
    var geometries = obj.type == 'GeometryCollection' ? obj.geometries : [obj];
    geometries.forEach(importer.addGeometryObject, importer);
    return importer.done();
  };

  //
  //
  TopoJSON.GeometryImporter = function(arcs, opts) {
    var idField = opts && opts.id_field || GeoJSON.ID_FIELD,
        properties = [],
        shapes = [], // topological ids
        types = [],
        dataNulls = 0,
        collectionType = null,
        shapeId;

    this.addGeometryObject = function(geom) {
      var rec = geom.properties || null;
      shapeId = shapes.length;
      shapes[shapeId] = null;
      if ('id' in geom) {
        rec = rec || {};
        rec[idField] = geom.id;
      }
      properties[shapeId] = rec;
      if (!rec) dataNulls++;
      if (geom.type) {
        this.addShape(geom);
      }
    };

    this.addShape = function(geom) {
      var curr = shapes[shapeId];
      var type = GeoJSON.translateGeoJSONType(geom.type);
      var shape;
      if (geom.type == "GeometryCollection") {
        geom.geometries.forEach(this.addShape, this);
      } else if (type) {
        this.setGeometryType(type);
        shape = TopoJSON.shapeImporters[geom.type](geom, arcs);
        // TODO: better shape validation
        if (!shape || !shape.length) ; else if (!Array.isArray(shape[0])) {
          stop("Invalid TopoJSON", geom.type, "geometry");
        } else {
          shapes[shapeId] = curr ? curr.concat(shape) : shape;
        }
      } else if (geom.type) {
        stop("Invalid TopoJSON geometry type:", geom.type);
      }
    };

    this.setGeometryType = function(type) {
      var currType = shapeId < types.length ? types[shapeId] : null;
      if (!currType) {
        types[shapeId] = type;
        this.updateCollectionType(type);
      } else if (currType != type) {
        stop("Unable to import mixed-type TopoJSON geometries");
      }
    };

    this.updateCollectionType = function(type) {
      if (!collectionType) {
        collectionType = type;
      } else if (type && collectionType != type) {
        collectionType = 'mixed';
      }
    };

    this.done = function() {
      var layers;
      if (collectionType == 'mixed') {
        layers = divideFeaturesByType(shapes, properties, types);
      } else {
        layers = [{
          geometry_type: collectionType,
          shapes : collectionType ? shapes : null,
          data: dataNulls < shapes.length ? new DataTable(properties) : null
        }];
      }
      return layers;
    };
  };

  // TODO: check that interior ring bboxes are contained in external ring
  // TODO: check that rings are closed
  TopoJSON.importPolygonArcs = function(rings, arcs) {
    var ring = rings[0],
        imported = null, area;
    if (!arcs) stop("Invalid TopoJSON file: missing arc data.");
    area = ring ? geom.getPlanarPathArea(ring, arcs) : null;
    if (!area) {
      return null;
    }
    if (area < 0) reversePath(ring);
    imported = [ring];
    for (var i=1; i<rings.length; i++) {
      ring = rings[i];
      area = geom.getPlanarPathArea(ring, arcs);
      if (!area) continue;
      if (area > 0) reversePath(ring);
      imported.push(ring);
    }
    return imported;
  };

  TopoJSON.shapeImporters = {
    Point: function(geom) {
      return [geom.coordinates];
    },
    MultiPoint: function(geom) {
      return geom.coordinates;
    },
    LineString: function(geom) {
      return [geom.arcs];
    },
    MultiLineString: function(geom) {
      return geom.arcs;
    },
    Polygon: function(geom, arcColl) {
      return TopoJSON.importPolygonArcs(geom.arcs, arcColl);
    },
    MultiPolygon: function(geom, arcColl) {
      return geom.arcs.reduce(function(memo, arr) {
        var rings = TopoJSON.importPolygonArcs(arr, arcColl);
        if (rings) {
          memo = memo ? memo.concat(rings) : rings;
        }
        return memo;
      }, null);
    }
  };

  var TopojsonImport = /*#__PURE__*/Object.freeze({
    __proto__: null,
    importTopoJSON: importTopoJSON
  });

  // This is a JSON parser optimized for GeoJSON files.
  //
  // The native JSON parser, JSON.parse(), is limited by the maximum string
  // size, about ~536.8M chars in Node.
  // (See https://github.com/v8/v8/blob/ea56bf5513d0cbd2a35a9035c5c2996272b8b728/src/objects/string.h#L365).
  // This parser can parse much larger files -- it is limited by available memory.
  //
  // Performance:
  // In Node, this parser is about twice as fast as JSON.parse() when parsing
  // GeoJSON files containing mostly coordinate data and when coordinate precision
  // is less than the float64 maximum. Similar files with full-precision
  // coordinates see a smaller improvement. Files that contain mostly attribute
  // data (e.g. a typical Point feature file) may be parsed a bit slower than
  // JSON.parse().
  //
  // JSON parsing reference: https://www.json.org/json-en.html
  //
  var
    LBRACE = 123,
    RBRACE = 125,
    LBRACK = 91,
    RBRACK = 93,
    DQUOTE = 34,
    COMMA = 44;

  var EOF; // undefined is used as an EOF marker

  var RESERVE = 0X1000; // RESERVE is the number of bytes to keep in read buffer
  var BUFLEN = 1e7; // buffer chunk size
  var MAX_STRLEN = 5e6; // max byte len of a value string (object keys are shorter)

  // Parse from a Buffer -- similar to JSON.parse(), used for testing
  function parse(buf) {
    var reader = new BufferReader(buf);
    var src = ByteReader(reader, 0);
    skipWS(src);
    var val = readValue(src);
    skipWS(src);
    if (src.peek() != EOF) {
      unexpectedCharAt(src.peek(), src.index());
    }
    return val;
  }

  // Read and parse JSON objects from a FileReader
  function parseObjects(reader, offset, cb) {
    var src = ByteReader(reader, offset);
    seekObjectStart(src);
    while (src.peek() == LBRACE) {
      cb(readObject(src));
      readToken(src, COMMA);
    }
  }

  function parseError(msg, i) {
    if (i >= 0) {
      msg += ' at position ' + i;
    }
    stop(msg);
  }

  function unexpectedCharAt(tok, i) {
    var msg;
    if (tok == EOF) {
      return parseError('Unexpected end of JSON input');
    }
    if (tok == DQUOTE) {
      msg = 'Unexpected string in JSON';
    } else if (tok < 33 || tok > 126) { // not ascii glyph
      msg = 'Unexpected token in JSON';
    } else {
      msg = 'Unexpected token ' + String.fromCharCode(tok) + ' in JSON';
    }
    parseError(msg, i);
  }

  function stringOverflow(i, c) {
    if (c == EOF) {
      parseError('Unterminated string in JSON', i);
    }
    parseError('Too-long string in JSON', i);
  }

  function seekObjectStart(src) {
    var c = src.getChar();
    var i = 0;
    while (c != EOF && i < RESERVE) {
      i++;
      if (c == LBRACE) {
        src.back();
        return true;
      }
      c = src.getChar();
    }
    return false;
  }

  function isWS(c) {
    return c == 32 || c == 10 || c == 13 || c == 9;
  }

  function skipWS(src) {
    while (isWS(src.peek())) src.advance();
  }

  function readArray(src) {
    var arr = [], c;
    eatChar(src, LBRACK);
    c = readToken(src, RBRACK);
    while (c != RBRACK) {
      src.refresh();
      arr.push(readArrayElement(src));
      c = readAorB(src, COMMA, RBRACK);
    }
    return arr;
  }

  // Using this function instead of readValue() to read array elements
  // gives up to a 25% reduction in overall processing time when parsing
  // coordinate-heavy GeoJSON files.
  function readArrayElement(src) {
    var i = src.index();
    var x, y, a, b;
    if (src.getChar() == LBRACK && isFirstNumChar(src.peek())) {
      x = readNumber(src);
      a = src.getChar();
      skipWS(src);
      if (a == COMMA && isFirstNumChar(src.peek())) {
        y = readNumber(src);
        b = src.getChar();
        if (b == RBRACK) {
          return [x, y];
        } else if (b == COMMA) {
          return extendArray(src, [x, y]);
        }
      }
    }
    // Fall back to general-purpose value reader
    src.index(i);
    return readValue(src);
  }

  function extendArray(src, arr) {
    skipWS(src);
    do {
      src.refresh(); // make make sure long arrays of numbers don't overflow
      arr.push(readValue(src));
    } while(readAorB(src, COMMA, RBRACK) == COMMA);
    return arr;
  }

  function eatChars(src, str) {
    for (var i = 0; i < str.length; i++) {
      eatChar(src, str.charCodeAt(i));
    }
    return true;
  }

  function eatChar(src, char) {
    var c = src.getChar();
    if (c != char) {
      unexpectedCharAt(c, src.index() - 1);
    }
  }

  // Reads and returns tok if tok is the next non-whitespace byte,
  // else returns null.
  // Scans past WS chars, both before and after tok
  function readToken(src, tok) {
    skipWS(src);
    var c = src.peek();
    if (c === tok) {
      src.advance();
      skipWS(src);
      return tok;
    }
    return null;
  }

  // assumes no leading WS
  function readValue(src) {
    var c = src.peek();
    var val;
    if (isFirstNumChar(c)) val = readNumber(src);
    else if (c == LBRACK) val = readArray(src);
    else if (c == DQUOTE) val = readString(src);
    else if (c == LBRACE) val = readObject(src);
    else if (c == 110) val = eatChars(src, "null") && null;
    else if (c == 116) val = eatChars(src, "true") && true;
    else if (c == 102) val = eatChars(src, "false") && false;
    else unexpectedCharAt(c, src.index());
    return val;
  }

  function readAorB(src, a, b) {
    skipWS(src);
    var c = src.getChar();
    if (c != a && c != b) unexpectedCharAt(c, src.index() - 1);
    skipWS(src);
    return c;
  }

  function readObject(src) {
    var o = {};
    var key, c;
    eatChar(src, LBRACE);
    c = readToken(src, RBRACE);
    while (c != RBRACE) {
      src.refresh();
      key = readKey(src); // use caching for faster key parsing
      skipWS(src);
      eatChar(src, 58);
      skipWS(src);
      // use caching with GeoJSON "type" params
      o[key] = key == 'type' && src.peek() == DQUOTE ?
        readKey(src) : readValue(src);
      c = readAorB(src, COMMA, RBRACE);
    }
    return o;
  }

  function growReserve() {
    RESERVE *= 2;
    return RESERVE <= MAX_STRLEN;
  }

  // Uses caching to speed up parsing of repeated strings.
  // The caching scheme used here can give a 20% overall speed improvement
  // when parsing files consisting mostly of attribute data (e.g. typical Point features)
  function readKey(src) {
    var MAXLEN = 2000; // must be less than RESERVE
    var i = src.index();
    var cache = src.cache;
    var escapeNext = false;
    var n = 0;
    eatChar(src, DQUOTE);
    var c = src.getChar();
    while (c != DQUOTE || escapeNext === true) {
      n++;
      if (n > MAXLEN) {
        stringOverflow(i, c);
      }
      if (escapeNext) {
        escapeNext = false;
      } else if (c == 92) {
        escapeNext = true;
      }
      if (!cache[c]) {
        cache[c] = [];
      }
      cache = cache[c];
      c = src.getChar();
    }
    if (cache[0]) {
      return cache[0];
    }
    src.index(i);
    cache[0] = readString(src);
    return cache[0];
  }

  // Fast path for reading strings.
  // A slower fallback is used to read strings that are longer, non-ascii or
  // contain escaped chars
  function readString(src) {
    var i = src.index();
    eatChar(src, DQUOTE);
    var LIMIT = 256;
    var n = 0;
    var str = '';
    var c = src.getChar();
    while (c != DQUOTE) {
      n++;
      if (n > LIMIT || c == 92 || c < 32 || c > 126) {
        src.index(i);
        return readString_slow(src);
      }
      // String concatenation is faster than Buffer#toString()
      // (as tested with typical strings found in GeoJSON)
      str += String.fromCharCode(c);
      c = src.getChar();
    }
    return str;
  }

  // Fallback for reading long strings, escaped strings, non-ascii strings, etc.
  function readString_slow(src) {
    src.refresh();
    var LIMIT = RESERVE - 2;
    var i = src.index();
    var n = 0;
    var escapeNext = false;
    eatChar(src, DQUOTE);
    var c = src.getChar();
    var str;
    while (c != DQUOTE || escapeNext === true) {
      n++;
      if (n > LIMIT) {
        // we've exceeded the number of reserved bytes
        // expand the limit and try reading this string again
        if (c == EOF || !growReserve()) {
          stringOverflow(i, c);
        }
        src.index(i);
        return readString_slow(src);
      }
      if (escapeNext) {
        escapeNext = false;
      } else if (c == 92) {
        escapeNext = true;
      }
      c = src.getChar();
    }
    // skipping JSON.parse() is faster, but doesn't work when strings contain
    // escapes or a handful of ascii control characters.
    // str = src.toString(i + 1, n);
    str = JSON.parse(src.toString(i, n + 2));
    src.refresh();
    return str;
  }

  function isDigit(c) {
    return c >= 48 && c <= 57;
  }

  function isFirstNumChar(c) {
    return c >= 48 && c <= 57 || c == 45;
  }

  function isNumChar(c) {
    return c >= 48 && c <= 57 || c == 45 || c == 46 || c == 43 || c == 69 || c == 101;
  }


  // Correctly parses any valid JSON number
  // This function gives the correctly rounded result for numbers that are
  // incorrectly rounded using the fast method (a subset of numbers with >15 digits).
  function readNumber_slow(src) {
    var i = src.index();
    var n = 0;
    while (isNumChar(src.getChar())) {
      n++;
    }
    src.back();
    var str = src.toString(i, n);
    var num = Number(str);
    if (isNaN(num)) parseError('Invalid number in JSON', i);
    return num;
  }

  // Parses numbers quickly, falls back to a slower method when
  // correct fp rounding is not assured.
  function readNumber(src) {
    var i = src.index();
    var num = 0;
    var den = 1;
    var sign = 1;
    var oflo = false;
    var invalid = false;
    var c = src.getChar();
    var d0, d;
    if (c === 45) {
      sign = -1;
      c = src.getChar();
    }
    d0 = c;
    while (isDigit(c)) {
      d = c - 48;
      num = num * 10 + d;
      c = src.getChar();
    }
    if (num > 0 && d0 === 48) {
      // catch "01" "-01" etc.
      invalid = true;
    }
    if (c == 46) { // "."
      while (isDigit(c = src.getChar())) {
        d = c - 48;
        den *= 10;
        num = num * 10 + d;
      }
      if (den == 1 || d0 == 46) {
        // catch "1." "1.e" "-.1"
        invalid = true;
      }
    }
    if (num === 0 && d0 != 48) {
      invalid = true; // catch "-";
    }
    if (invalid) parseError('Invalid number in JSON', i);
    if (den > 1e22) oflo = true; // denominator gets rounded above this limit
    if (num >= 0x20000000000000) { // 2^53
      // Some numerators get rounded with > 52 bits of mantissa
      // (When numerator or denominator are rounded, dividing them may
      // not have the same result as JSON.parse() and the IEEE standard)
      // See: https://www.exploringbinary.com/fast-path-decimal-to-floating-point-conversion/
      if (num >= 0x40000000000000 || (d & 1) === 1) {
        // We don't need to fall back to the slow routine
        // for even integers with 53 bits
        // This optimization can reduce overall processing time by 15% for
        // GeoJSON files with full-precision coordinates.
        oflo = true;
      }
    }
    if (oflo || c == 69 || c == 101) { // e|E
      // Exponents are uncommon in GeoJSON... simpler to use slow function
      // than to parse manually and check for overflow and rounding errors
      src.index(i);
      return readNumber_slow(src);
    }
    src.back();
    return sign * num / den;
  }

  // Wrap a FileReader to support reading files one byte at a time.
  function ByteReader(reader, start) {
    var fileLen = reader.size();
    var bufOffs = start;
    var buf = reader.readSync(bufOffs, BUFLEN);
    var i = 0;
    var obj = { peek, getChar, advance, back, toString, index, refresh };
    obj.cache = []; // kludgy place to put the key cache
    refresh();
    return obj;

    // This function should be called to make sure that the buffer has enough
    // bytes remaining to read any reasonable JSON content.
    function refresh() {
      // if RESERVE bytes are still available in the buffer, no update is required
      if (buf.length - i >= RESERVE) return;

      // CHANGE: now using undefined as an EOF marker, so a bounds check is unneeded
      // // if we're close to the end of the file, start checking for overflow
      // // (we don't do this all the time because the bounds check on every read
      // // causes a significant slowdown, as much as 20%)
      // if (fileLen - (bufOffs + i) < RESERVE) {
      //   obj.peek = safePeek;
      //   obj.getChar = safeGetChar;
      // }

      // if buffer reaches the end of the file, no update is required
      if (bufOffs + buf.length >= fileLen) return;

      // fewer than RESERVE bytes are unread in buffer -- update the buffer
      bufOffs += i;
      i = 0;
      buf = reader.readSync(bufOffs, BUFLEN);
    }
    function peek() {
      return buf[i];
    }
    function getChar() {
      return buf[i++];
    }
    function advance() {
      i++;
    }
    function back() {
      i--;
    }
    function index(idx) {
      if (idx >= 0 === false) return i + bufOffs;
      i = idx - bufOffs;
    }
    function toString(idx, n) {
      var i = idx - bufOffs;
      return buf.toString("utf8", i, i + n);
    }
  }

  // Read GeoJSON Features or geometry objects from a file
  // @reader: a FileReader
  function GeoJSONReader(reader) {

    // Read objects synchronously, with callback
    this.readObjects = function(onObject) {
      // Search first x bytes of file for features|geometries key
      // 300 bytes not enough... GeoJSON files can have additional non-standard properties, e.g. 'metadata'
      // var bytesToSearch = 300;
      var bytesToSearch = 5000;
      var start = reader.findString('"features"', bytesToSearch) ||
          reader.findString('"geometries"', bytesToSearch);
      // Assume single Feature or geometry if collection not found
      // (this works for ndjson files too)
      var offset = start ? start.offset : 0;
      T$1.start();
      parseObjects(reader, offset, onObject);
      // parseObjects_native(reader, offset, onObject);
      debug('Parse GeoJSON', T$1.stop());
    };
  }

  // Identify JSON type from the initial subset of a JSON string
  function identifyJSONString(str, opts) {
    var maxChars = 1000;
    var fmt = null;
    if (str.length > maxChars) str = str.substr(0, maxChars);
    str = str.replace(/\s/g, '');
    if (opts && opts.json_path) {
      fmt = 'json'; // TODO: make json_path compatible with other types
    } else if (/^\[[{\]]/.test(str)) {
      // empty array or array of objects
      fmt = 'json';
    } else if (/"arcs":\[|"objects":\{|"transform":\{/.test(str)) {
      fmt =  'topojson';
    } else if (/^\{"/.test(str)) {
      fmt = 'geojson';
    }
    return fmt;
  }

  function identifyJSONObject(o) {
    var fmt = null;
    if (!o) ; else if (o.type == 'Topology') {
      fmt = 'topojson';
    } else if (o.type) {
      fmt = 'geojson';
    } else if (utils.isArray(o)) {
      fmt = 'json';
    }
    return fmt;
  }

  function importGeoJSONFile(fileReader, opts) {
    var importer = new GeoJSONParser(opts);
    new GeoJSONReader(fileReader).readObjects(importer.parseObject);
    return importer.done();
  }

  // Parse GeoJSON directly from a binary data source (supports parsing larger files
  // than the maximum JS string length) or return a string with the entire
  // contents of the file.
  // reader: a binary file reader
  //
  function readJSONFile(reader, opts) {
    var str = readFirstChars(reader, 1000);
    var type = identifyJSONString(str, opts);
    var dataset, retn;
    if (type == 'geojson') { // consider only for larger files
      dataset = importGeoJSONFile(reader, opts);
      retn = {
        dataset: dataset,
        format: 'geojson'
      };
    } else {
      retn = {
        // content: cli.readFile(path, 'utf8')}
        content: reader.toString('utf8')
      };
    }
    reader.close();
    return retn;
  }

  function importJSON(data, opts) {
    var content = data.content,
        filename = data.filename,
        retn = {filename: filename},
        reader, fmt;

    if (!content) {
      reader = new FileReader(filename);
    } else if (content instanceof ArrayBuffer || content instanceof B$3 || content instanceof Uint8Array) {
      // Web API imports JSON as ArrayBuffer, to support larger files
      if ((content.byteLength || content.length) < 1e7) {
        // content = utils.createBuffer(content).toString();
        content = bufferToString(utils.createBuffer(content));
      } else {
        reader = new BufferReader(content);
        content = null;
      }
    }

    if (reader) {
      data = readJSONFile(reader, opts);
      if (data.dataset) {
        retn.dataset = data.dataset;
        retn.format = data.format;
      } else {
        content = data.content;
      }
    }

    if (content) {
      if (utils.isString(content)) {
        try {
          content = JSON.parse(content); // ~3sec for 100MB string
        } catch(e) {
          // stop("Unable to parse JSON");
          stop('JSON parsing error:', e.message);
        }
      }
      if (opts.json_path) {
        content = selectFromObject(content, opts.json_path);
        fmt = identifyJSONObject(content);
        if (!fmt) {
          stop('Unexpected object type at JSON path:', opts.json_path);
        }
      } else {
        fmt = identifyJSONObject(content);
      }
      if (fmt == 'topojson') {
        retn.dataset = importTopoJSON(content, opts);
      } else if (fmt == 'geojson') {
        retn.dataset = importGeoJSON(content, opts);
      } else if (fmt == 'json') {
        retn.dataset = importJSONTable(content);
      } else {
        stop("Unknown JSON format");
      }
      retn.format = fmt;
    }

    return retn;
  }

  // path: path from top-level to the target object
  function selectFromObject(o, path) {
    var arrayRxp = /(.*)\[([0-9]+)\]$/; // array bracket notation w/ index
    var separator = path.indexOf('/') > 0 ? '/' : '.';
    var parts = path.split(separator);
    var subpath, array, match;
    while (parts.length > 0) {
      subpath = parts.shift();
      match = arrayRxp.exec(subpath);
      if (match) {
        array = o[match[1]];
        o = array && array[+match[2]] || null;
      } else {
        o = o[subpath];
      }
      if (!o) return null;
    }
    return o;
  }

  var JsonImport = /*#__PURE__*/Object.freeze({
    __proto__: null,
    identifyJSONString: identifyJSONString,
    identifyJSONObject: identifyJSONObject,
    importGeoJSONFile: importGeoJSONFile,
    importJSON: importJSON
  });

  function importKML(str, opts) {
    var togeojson = require$1("@tmcw/togeojson");
    var Parser = typeof DOMParser == 'undefined' ? require$1("@xmldom/xmldom").DOMParser : DOMParser;
    var geojson = togeojson.kml(new Parser().parseFromString(str, "text/xml"));
    return importGeoJSON(geojson, opts || {});
  }

  // Parse content of one or more input files and return a dataset
  // @obj: file data, indexed by file type
  // File data objects have two properties:
  //    content: Uint8Array, Buffer, ArrayBuffer, String or Object
  //    filename: String or null
  //
  function importContent(obj, opts) {
    var dataset, fileFmt, data;
    opts = opts || {};
    if (obj.json) {
      data = importJSON(obj.json, opts);
      fileFmt = data.format;
      dataset = data.dataset;
      cleanPathsAfterImport(dataset, opts);

    } else if (obj.text) {
      fileFmt = 'dsv';
      data = obj.text;
      dataset = importDelim2(data, opts);

    } else if (obj.shp) {
      fileFmt = 'shapefile';
      data = obj.shp;
      dataset = importShapefile(obj, opts);
      cleanPathsAfterImport(dataset, opts);

    } else if (obj.dbf) {
      fileFmt = 'dbf';
      data = obj.dbf;
      dataset = importDbf(obj, opts);

    } else if (obj.prj) {
      // added for -proj command source
      fileFmt = 'prj';
      data = obj.prj;
      dataset = {layers: [], info: {prj: data.content}};

    } else if (obj.kml) {
      fileFmt = 'kml';
      data = obj.kml;
      dataset = importKML(data.content, opts);
    }

    if (!dataset) {
      stop("Missing an expected input type");
    }

    // Convert to topological format, if needed
    if (dataset.arcs && !opts.no_topology && fileFmt != 'topojson') {
      buildTopology(dataset);
    }

    // Use file basename for layer name, except TopoJSON, which uses object names
    if (fileFmt != 'topojson') {
      dataset.layers.forEach(function(lyr) {
        if (!lyr.name) {
          lyr.name = filenameToLayerName(data.filename || '');
        }
      });
    }

    // Add input filename and format to the dataset's 'info' object
    // (this is useful when exporting if format or name has not been specified.)
    if (data.filename) {
      dataset.info.input_files = [data.filename];
    }
    dataset.info.input_formats = [fileFmt];
    return dataset;
  }

  // Deprecated (included for compatibility with older tests)
  function importFileContent(content, filename, opts) {
    var type = guessInputType(filename, content),
        input = {};
    input[type] = {filename: filename, content: content};
    return importContent(input, opts);
  }


  function importShapefile(obj, opts) {
    var shpSrc = obj.shp.content || obj.shp.filename, // read from a file if (binary) content is missing
        shxSrc = obj.shx ? obj.shx.content || obj.shx.filename : null,
        dataset = importShp(shpSrc, shxSrc, opts),
        lyr = dataset.layers[0],
        dbf;
    if (obj.dbf) {
      dbf = importDbf(obj, opts);
      utils.extend(dataset.info, dbf.info);
      lyr.data = dbf.layers[0].data;
      if (lyr.shapes && lyr.data.size() != lyr.shapes.length) {
        message("Mismatched .dbf and .shp record count -- possible data loss.");
      }
    }
    if (obj.prj) {
      dataset.info.prj = obj.prj.content;
    }
    if (obj.cpg) {
      // TODO: consider using the input encoding as the default output encoding
      dataset.info.cpg = obj.cpg.content;
      if (typeof dataset.info.cpg != 'string') {
        error('Invalid encoding argument, expected a string');
      }
    }
    return dataset;
  }

  function importDbf(input, opts) {
    var table;
    opts = utils.extend({}, opts);
    if (input.cpg && !opts.encoding) {
      opts.encoding = input.cpg.content;
    }
    table = importDbfTable(input.dbf.content || input.dbf.filename, opts);
    return {
      info: {},
      layers: [{data: table}]
    };
  }

  function filenameToLayerName(path) {
    var name = 'layer1';
    var obj = parseLocalPath(path);
    if (obj.basename && obj.extension) { // exclude paths like '/dev/stdin'
      name = obj.basename;
    }
    return name;
  }

  var Import = /*#__PURE__*/Object.freeze({
    __proto__: null,
    importContent: importContent,
    importFileContent: importFileContent
  });

  // Import datasets contained in a BSON blob
  // Return command target as a dataset
  //
  async function unpackSessionData(buf) {
    return restoreSessionData(unpack(buf, {}));
  }

  async function restoreSessionData(obj) {
    if (!isValidSession(obj)) {
      stop('Invalid mapshaper session data object');
    }
    var datasets = await Promise.all(obj.datasets.map(importDataset));
    return Object.assign(obj, {datasets: datasets});
  }

  function isValidSession(obj) {
    if (!Array.isArray(obj.datasets)) {
      return false;
    }
    return true;
  }

  async function importDataset(obj) {
    var arcs = null;
    if (obj.arcs) arcs = await importArcs(obj.arcs);
    return {
      info: importInfo(obj.info || {}),
      layers: (obj.layers || []).map(importLayer),
      arcs: arcs
    };
  }

  function bufferToDataView(buf, constructor) {
    return new constructor(BinArray.copyToArrayBuffer(buf));
    // this doesn't work: "RangeError: start offset of Float64Array should be a multiple of 8"
    // return new constructor(buf.buffer, buf.byteOffset, buf.byteLength);
  }

  async function importArcs(obj) {
    if (isGzipped(obj.xx)) {
      var promises = [];
      promises.push(gunzipAsync(obj.nn));
      promises.push(gunzipAsync(obj.xx));
      promises.push(gunzipAsync(obj.yy));
      if (obj.zz) {
        promises.push(gunzipAsync(obj.zz));
      }
      var data = await Promise.all(promises);
      obj.nn = data.shift();
      obj.xx = data.shift();
      obj.yy = data.shift();
      if (obj.zz) {
        obj.zz = data.shift();
      }
    }
    var nn = bufferToDataView(obj.nn, Uint32Array);
    var xx = bufferToDataView(obj.xx, Float64Array);
    var yy = bufferToDataView(obj.yy, Float64Array);
    var arcs = new ArcCollection(nn, xx, yy);
    if (obj.zz) {
      arcs.setThresholds(bufferToDataView(obj.zz, Float64Array));
      arcs.setRetainedInterval(obj.zlimit);
    }
    return arcs;
  }

  function importInfo(o) {
    if (o.crs_string) {
      o.crs = parseCrsString(o.crs_string);
    } else if (o.prj) {
      o.crs = parsePrj(o.prj);
    }
    return o;
  }

  function importLayer(lyr) {
    var data = lyr.data;
    if (data) {
      data = importTable(data);
    }
    return Object.assign(lyr, {
      data: lyr.data ? new DataTable(data) : null
    });
  }

  var Unpack = /*#__PURE__*/Object.freeze({
    __proto__: null,
    unpackSessionData: unpackSessionData,
    restoreSessionData: restoreSessionData
  });

  cmd.importFiles = async function(catalog, opts) {
    var files = opts.files || [];
    var dataset;

    cli.checkCommandEnv('i');
    if (opts.stdin) {
      return importFile('/dev/stdin', opts);
    }

    if (files.length > 0 === false) {
      stop('Missing input file(s)');
    }

    verbose("Importing: " + files.join(' '));

    // copy opts, so parameters can be modified within this command
    opts = Object.assign({}, opts);
    opts.input = Object.assign({}, opts.input); // make sure we have a cache

    files = expandFiles(files, opts.input);

    if (files.length === 0) {
      stop('Missing importable files');
    }

    // special case: package file
    if (files.some(isPackageFile)) {
      if (files.length > 1) {
        stop('Expected a single package file');
      }
      dataset = await importMshpFile(files[0], catalog, opts);
      return dataset;
    }

    if (files.length == 1) {
      dataset = importFile(files[0], opts);
    } else {
      dataset = importFilesTogether(files, opts);
    }

    if (opts.merge_files && files.length > 1) {
      // TODO: deprecate and remove this option (use -merge-layers cmd instead)
      dataset.layers = cmd.mergeLayers(dataset.layers);
    }

    catalog.addDataset(dataset);
    return dataset;
  };

  async function importMshpFile(file, catalog, opts) {
    var buf = cli.readFile(file, null, opts.input);
    var obj = await unpackSessionData(buf);
    obj.datasets.forEach(catalog.addDataset, catalog);
    return obj.target;
  }

  function expandFiles(files, cache) {
    var files2 = [];
    files.forEach(function(file) {
      var expanded;
      if (isZipFile(file)) {
        expanded = expandZipFile(file, cache);
      } else if (isKmzFile(file)) {
        expanded = expandKmzFile(file, cache);
      } else {
        expanded = [file]; // ordinary file, no change
      }
      files2 = files2.concat(expanded);
    });
    return files2;
  }

  function expandKmzFile(file, cache) {
    var files = expandZipFile(file, cache);
    var name = replaceFileExtension(parseLocalPath(file).filename, 'kml');
    if (files[0] == 'doc.kml') {
      files[0] = name;
      cache[name] = cache['doc.kml'];
    }
    return files;
  }

  function expandZipFile(file, cache) {
    var input;
    if (file in cache) {
      input = cache[file];
    } else {
      input = file;
      cli.checkFileExists(file);
    }
    var index = unzipSync(input);
    Object.assign(cache, index);
    return findPrimaryFiles(index);
  }

  // Return the names of primary files in a file cache
  // (exclude auxiliary files, which can't be converted into datasets)
  function findPrimaryFiles(cache) {
    return Object.keys(cache).filter(function(filename) {
      var type = guessInputFileType(filename);
      if (type == 'dbf') {
        // don't import .dbf separately if .shp is present
        if (replaceFileExtension(filename, 'shp') in cache) return false;
      }
      return type == 'text' || type == 'json' || type == 'shp' || type == 'dbf' || type == 'kml';
    });
  }

  // Let the web UI replace importFile() with a browser-friendly version
  function replaceImportFile(func) {
    _importFile = func;
  }

  function importFile(path, opts) {
    return _importFile(path, opts);
  }

  var _importFile = function(path, opts) {
    var fileType = guessInputFileType(path),
        input = {},
        encoding = opts && opts.encoding || null,
        cache = opts && opts.input || null,
        cached = cache && (path in cache),
        content;

    cli.checkFileExists(path, cache);

    if ((fileType == 'shp' || fileType == 'json' || fileType == 'text' || fileType == 'dbf') && !cached) {
      // these file types are read incrementally
      content = null;

    } else if (fileType && isSupportedBinaryInputType(path)) {
      content = cli.readFile(path, null, cache);
      if (utils.isString(content)) {
        // Fix for issue #264 (applyCommands() input is file path instead of binary content)
        stop('Expected binary content, received a string');
      }

    } else if (fileType) { // string type, e.g. kml, geojson
      content = cli.readFile(path, encoding || 'utf-8', cache);

    } else if (getFileExtension(path) == 'gz') {
      var pathgz = path;
      path = pathgz.replace(/\.gz$/, '');
      fileType = guessInputFileType(path);
      if (!fileType) {
        stop('Unrecognized file type:', path);
      }
      content = gunzipSync(cli.readFile(pathgz, null, cache), path);

    } else { // type can't be inferred from filename -- try reading as text
      content = cli.readFile(path, encoding || 'utf-8', cache);
      fileType = guessInputContentType(content);
      if (fileType == 'text' && content.indexOf('\ufffd') > -1) {
        // invalidate string data that contains the 'replacement character'
        fileType = null;
      }
    }

    if (!fileType) {
      stop(getUnsupportedFileMessage(path));
    }
    input[fileType] = {filename: path, content: content};
    content = null; // for g.c.
    if (fileType == 'shp' || fileType == 'dbf') {
      readShapefileAuxFiles(path, input, cache);
    }
    if (fileType == 'shp' && !input.dbf) {
      message(utils.format("[%s] .dbf file is missing - shapes imported without attribute data.", path));
    }
    return importContent(input, opts);
  };

  // Import multiple files to a single dataset
  function importFilesTogether(files, opts) {
    var unbuiltTopology = false;
    var datasets = files.map(function(fname) {
      // import without topology or snapping
      var importOpts = utils.defaults({no_topology: true, snap: false, snap_interval: null, files: [fname]}, opts);
      var dataset = importFile(fname, importOpts);
      // check if dataset contains non-topological paths
      // TODO: may also need to rebuild topology if multiple topojson files are merged
      if (dataset.arcs && dataset.arcs.size() > 0 && dataset.info.input_formats[0] != 'topojson') {
        unbuiltTopology = true;
      }
      return dataset;
    });
    var combined = mergeDatasets(datasets);
    // Build topology, if needed
    // TODO: consider updating topology of TopoJSON files instead of concatenating arcs
    // (but problem of mismatched coordinates due to quantization in input files.)
    if (unbuiltTopology && !opts.no_topology) {
      cleanPathsAfterImport(combined, opts);
      buildTopology(combined);
    }
    return combined;
  }

  function getUnsupportedFileMessage(path) {
    var ext = getFileExtension(path);
    var msg = 'Unable to import ' + path;
    if (ext.toLowerCase() == 'zip') {
      msg += ' (ZIP files must be unpacked before running mapshaper)';
    } else {
      msg += ' (unknown file type)';
    }
    return msg;
  }

  function readShapefileAuxFiles(path, obj, cache) {
    var dbfPath = replaceFileExtension(path, 'dbf');
    var shxPath = replaceFileExtension(path, 'shx');
    var cpgPath = replaceFileExtension(path, 'cpg');
    var prjPath = replaceFileExtension(path, 'prj');
    if (cli.isFile(prjPath, cache)) {
      obj.prj = {filename: prjPath, content: cli.readFile(prjPath, 'utf-8', cache)};
    }
    if (cli.isFile(shxPath, cache)) {
      obj.shx = {filename: shxPath, content: cli.readFile(shxPath, null, cache)};
    }
    if (!obj.dbf && cli.isFile(dbfPath, cache)) {
      // obj.dbf = {filename: dbfPath, content: cli.readFile(dbfPath, null, cache)};
      obj.dbf = {
        filename: dbfPath,
        content: (cache && (dbfPath in cache)) ? cli.readFile(dbfPath, null, cache) : null
      };
    }
    if (obj.dbf && cli.isFile(cpgPath, cache)) {
      obj.cpg = {filename: cpgPath, content: cli.readFile(cpgPath, 'utf-8', cache).trim()};
    }
  }

  var FileImport = /*#__PURE__*/Object.freeze({
    __proto__: null,
    replaceImportFile: replaceImportFile,
    importFile: importFile,
    importFilesTogether: importFilesTogether
  });

  function convertSourceName(name, targets) {
    if (!nameIsInterpolated(name)) return name;
    if (targets.length > 1 || targets[0].layers.length != 1) {
      stop("Interpolated names are not compatible with multiple targets.");
    }
    return convertInterpolatedName(name, targets[0].layers[0]);
  }

  function convertInterpolatedName(name, lyr) {
    var ctx = {target: lyr.name || ''};
    var body = 'with($$ctx) { return `' + name + '`; }';
    var func;
    try {
      func = new Function("$$ctx", body);
      name = func(ctx);
    } catch(e) {
      stop("Unable to interpolate [" + name + "]");
    }
    return name;
  }

  function nameIsInterpolated(name) {
    return /[$][{]/.test(name);
  }

  function findCommandSource(sourceName, catalog, opts) {
    var source = catalog.findSingleLayer(sourceName);
    var sourceDataset;
    if (!source) {
      // assuming opts.source is a filename
      // don't need to build topology, because:
      //    join -- don't need topology
      //    clip/erase -- topology is built later, when datasets are combined
      sourceDataset = importFile(sourceName, utils.defaults({no_topology: true}, opts));
      if (!sourceDataset) {
        stop(utils.format('Unable to find source [%s]', sourceName));
      } else if (sourceDataset.layers.length > 1) {
        stop('Multiple-layer sources are not supported');
      }
      // mark as disposable to indicate that data can be mutated
      source = {dataset: sourceDataset, layer: sourceDataset.layers[0], disposable: true};
    }
    return source;
  }

  var SourceUtils = /*#__PURE__*/Object.freeze({
    __proto__: null,
    convertSourceName: convertSourceName,
    convertInterpolatedName: convertInterpolatedName,
    findCommandSource: findCommandSource
  });

  // Catalog contains zero or more multi-layer datasets
  // One layer is always "active", corresponding to the currently selected
  //   layer in the GUI or the current target in the CLI
  function Catalog() {
    var datasets = [],
        defaultTargets = [];// saved default command targets [{layers:[], dataset}, ...]

    this.forEachLayer = function(cb) {
      var i = 0;
      datasets.forEach(function(dataset) {
        dataset.layers.forEach(function(lyr) {
          cb(lyr, dataset, i++);
        });
      });
    };

    // remove a layer from a dataset
    this.deleteLayer = function(lyr, dataset) {
      // if deleting first target layer (selected in gui) -- switch to some other layer
      if (this.getActiveLayer().layer == lyr) {
        defaultTargets = [];
      }

      // remove layer from its dataset
      dataset.layers.splice(dataset.layers.indexOf(lyr), 1);
      if (dataset.layers.length === 0) {
        this.removeDataset(dataset);
      }

      // remove layer from defaultTargets
      defaultTargets = defaultTargets.filter(function(targ) {
        var i = targ.layers.indexOf(lyr);
        if (i == -1) return true;
        targ.layers.splice(i, 1);
        return targ.layers.length > 0;
      });
    };

    // @arg: a layer object or a test function
    this.findLayer = function(arg) {
      var test = typeof arg == 'function' ? arg : null;
      var found = null;
      this.forEachLayer(function(lyr, dataset) {
        if (test ? test(lyr, dataset) : lyr == arg) {
          found = layerObject(lyr, dataset);
        }
      });
      return found;
    };

    this.findCommandTargets = function(pattern, type) {
      if (!pattern) return this.getDefaultTargets() || [];
      return findCommandTargets(this.getLayers(), pattern, type);
    };

    this.findSingleLayer = function(pattern) {
      var matches = findMatchingLayers(this.getLayers(), pattern);
      if (matches.length > 1) {
        stop('Ambiguous pattern (multiple layers were matched):', pattern);
      }
      return matches[0] || null;
    };

    this.clear = function() {
      datasets = [];
      defaultTargets = [];
    };

    this.removeDataset = function(dataset) {
      defaultTargets = defaultTargets.filter(function(targ) {
        return targ.dataset != dataset;
      });
      datasets = datasets.filter(function(d) {
        return d != dataset;
      });
    };

    this.getDatasets = function() {
      return datasets;
    };

    this.getLayers = function() {
      var layers = [];
      this.forEachLayer(function(lyr, dataset) {
        layers.push(layerObject(lyr, dataset));
      });
      return layers;
    };

    this.addDataset = function(dataset) {
      this.setDefaultTarget(dataset.layers, dataset);
      return this;
    };

    this.addDatasets = function(datasets) {
      datasets.forEach(function(dataset) {
        this.addDataset(dataset);
      }, this);
    };

    this.findNextLayer = function(lyr) {
      var layers = this.getLayers(),
          idx = indexOfLayer(lyr, layers);
      return idx > -1 ? layers[(idx + 1) % layers.length] : null;
    };

    this.findPrevLayer = function(lyr) {
      var layers = this.getLayers(),
          idx = indexOfLayer(lyr, layers);
      return idx > -1 ? layers[(idx - 1 + layers.length) % layers.length] : null;
    };

    this.isEmpty = function() {
      return datasets.length === 0;
    };

    this.getDefaultTargets = function() {
      if (defaultTargets.length === 0 && !this.isEmpty()) {
        defaultTargets = [{dataset: datasets[0], layers: datasets[0].layers.slice(0, 1)}];
      }
      return defaultTargets;
    };

    this.setDefaultTarget = function(layers, dataset) {
      if (datasets.indexOf(dataset) == -1) {
        datasets.push(dataset);
      }
      defaultTargets = [{
        // Copy layers array, in case layers is a reference to dataset.layers.
        // This prevents layers that are added to the dataset inside a command from
        //  being added to the next command's target, e.g. debugging layers added
        //  by '-join unmatched unjoined'.
        layers: layers.concat(),
        dataset: dataset
      }];
    };

    this.setDefaultTargets = function(arr) {
      defaultTargets = arr;
    };

    // should be in gui-model.js, moved here for testing
    this.getActiveLayer = function() {
      var targ = (this.getDefaultTargets() || [])[0];
      // var lyr = targ.layers[0];
      // Reasons to select the last layer of a multi-layer target:
      // * This layer was imported last
      // * This layer is displayed on top of other layers
      // * This layer is at the top of the layers list
      // * In TopoJSON input, it makes sense to think of the last object/layer
      //   as the topmost one -- it corresponds to the painter's algorithm and
      //   the way that objects are ordered in SVG.
      var lyr = targ.layers[targ.layers.length - 1];
      return targ ? {layer: lyr, dataset: targ.dataset} : null;
    };

    function layerObject(lyr, dataset) {
      return {
        layer: lyr,
        dataset: dataset
      };
    }

    function indexOfLayer(lyr, layers) {
      var idx = -1;
      layers.forEach(function(o, i) {
        if (o.layer == lyr) idx = i;
      });
      return idx;
    }
  }

  function getFormattedLayerList(catalog) {
    var lines = [];
    catalog.forEachLayer(function(lyr, dataset, i) {
      lines.push('  [' + (i+1) + ']  ' + (lyr.name || '[unnamed]'));
    });
    return lines.length > 0 ? lines.join('\n') : '[none]';
  }

  var Catalog$1 = /*#__PURE__*/Object.freeze({
    __proto__: null,
    Catalog: Catalog,
    getFormattedLayerList: getFormattedLayerList
  });

  function Job(catalog) {
    var currentCmd;

    var job = {
      catalog: catalog || new Catalog(),
      defs: {},
      settings: {},
      input_files: []
    };

    job.initSettings = function(o) {
      job.settings = o;
      stashVars(job, {});
    };

    job.startCommand = function(cmd) {
      currentCmd = cmd;
      stashVars(job, cmd);
    };

    // Rejected the idea of passing a command reference to compare with the initial command
    // (for error checking) ... the "-run" command inserts other commands before this call
    job.endCommand = function() {
      currentCmd = null;
      clearStash();
    };

    job.resumeCommand = function() {
      stashVars(job, currentCmd);
    };

    return job;
  }

  function stashVars(job, cmd) {
    clearStash();  // prevent errors from overwriting stash
    stashVar('current_command', cmd.name);
    stashVar('DEBUG', job.settings.DEBUG || cmd.debug);
    stashVar('VERBOSE', job.settings.VERBOSE || cmd.verbose);
    stashVar('QUIET', job.settings.QUIET || cmd.quiet);
    stashVar('defs', job.defs);
    stashVar('input_files', job.input_files);
  }

  cmd.addShape = addShape;

  function addShape(targetLayers, targetDataset, opts) {
    if (targetLayers.length > 1) {
      stop('Command expects a single target layer');
    }
    var targetLyr = targetLayers[0]; // may be undefined
    var targetType = !opts.no_replace && targetLyr && targetLyr.geometry_type || null;
    var dataset = importGeoJSON(toFeature(opts, targetType));
    var outputLyr = mergeDatasetsIntoDataset(targetDataset, [dataset])[0];
    if (opts.no_replace || !targetLyr) {
      // create new layer
      setOutputLayerName(outputLyr, targetLyr && targetLyr.name, null, opts);
      return [outputLyr];
    }
    // merge into target layer
    return cmd.mergeLayers([targetLyr, outputLyr], {force: true});
  }

  function toFeature(opts, geomType) {
    if (opts.geojson) {
      return parseArg(opts.geojson);
    }

    var geom = opts.coordinates && parseCoordsAsGeometry(opts.coordinates) || null;

    if (!geom) {
      stop('Missing required shape coordinates');
    }

    if (geomType == 'point' && geom.type != 'Point') {
      stop('Expected point coordinates, received', geom.type);
    }

    if (geomType == 'polygon' && geom.type != 'Polygon') {
      stop('Expected polygon coordinates, received', geom.type);
    }

    if (geomType == 'polyline') {
      if (geom.type == 'Polygon') {
        geom.coordinates = geom.coordinates[0];
        geom.type = 'LineString';
      } else {
        stop('Expected polyline coordinates, received', geom.type);
      }
    }

    return {
      type: 'Feature',
      properties: parseProperties(opts.properties),
      geometry: geom
    };
  }

  function parseArg(obj) {
    return typeof obj == 'string' ? JSON.parse(obj) : obj;
  }

  function parseProperties(arg) {
    if (!arg) return null;
    return parseArg(arg);
  }

  function isArrayOfNumbers(arr) {
    return arr.length >= 2 && arr.every(utils.isNumber);
  }

  function isClosedPath$1(arr) {
    return isArrayOfPoints(arr) && arr.length > 3 && samePoint$1(arr[0], arr[arr.length - 1]);
  }

  function samePoint$1(a, b) {
    return a[0] == b[0] && a[1] == b[1];
  }

  function isArrayOfPoints(arr) {
    return arr.every(isPoint);
  }

  function isPoint(arr) {
    return arr && arr.length == 2 && isArrayOfNumbers(arr);
  }

  function transposeCoords(arr) {
    var coords = [];
    for (var i=0; i<arr.length; i+=2) {
      coords.push([arr[i], arr[i+1]]);
    }
    if (!isArrayOfPoints(coords)) {
      stop('Unable to parse x,y,x,y... coordinates');
    }
    return coords;
  }

  function parseCoordsAsGeometry(arg) {
    if (typeof arg == 'string') {
      arg = arg.trim();
      if (!arg.startsWith('[') && !arg.endsWith(']')) {
        arg = '[' + arg + ']';
      }
    }
    var arr = parseArg(arg);
    if (isPoint(arr)) {
      return {
        type: 'Point',
        coordinates: arr
      };
    }

    if (isArrayOfNumbers(arr)) {
      arr = transposeCoords(arr);
    }

    if (isClosedPath$1(arr)) {
      return {
        type: 'Polygon',
        coordinates: [arr]
      };
    }

    if (isArrayOfPoints(arr)) {
      return {
        type: 'LineString',
        coordinates: arr
      };
    }

    stop('Unable to import coordinates');
  }

  const epsilon = 1.1102230246251565e-16;
  const splitter = 134217729;
  const resulterrbound = (3 + 8 * epsilon) * epsilon;

  // fast_expansion_sum_zeroelim routine from oritinal code
  function sum(elen, e, flen, f, h) {
      let Q, Qnew, hh, bvirt;
      let enow = e[0];
      let fnow = f[0];
      let eindex = 0;
      let findex = 0;
      if ((fnow > enow) === (fnow > -enow)) {
          Q = enow;
          enow = e[++eindex];
      } else {
          Q = fnow;
          fnow = f[++findex];
      }
      let hindex = 0;
      if (eindex < elen && findex < flen) {
          if ((fnow > enow) === (fnow > -enow)) {
              Qnew = enow + Q;
              hh = Q - (Qnew - enow);
              enow = e[++eindex];
          } else {
              Qnew = fnow + Q;
              hh = Q - (Qnew - fnow);
              fnow = f[++findex];
          }
          Q = Qnew;
          if (hh !== 0) {
              h[hindex++] = hh;
          }
          while (eindex < elen && findex < flen) {
              if ((fnow > enow) === (fnow > -enow)) {
                  Qnew = Q + enow;
                  bvirt = Qnew - Q;
                  hh = Q - (Qnew - bvirt) + (enow - bvirt);
                  enow = e[++eindex];
              } else {
                  Qnew = Q + fnow;
                  bvirt = Qnew - Q;
                  hh = Q - (Qnew - bvirt) + (fnow - bvirt);
                  fnow = f[++findex];
              }
              Q = Qnew;
              if (hh !== 0) {
                  h[hindex++] = hh;
              }
          }
      }
      while (eindex < elen) {
          Qnew = Q + enow;
          bvirt = Qnew - Q;
          hh = Q - (Qnew - bvirt) + (enow - bvirt);
          enow = e[++eindex];
          Q = Qnew;
          if (hh !== 0) {
              h[hindex++] = hh;
          }
      }
      while (findex < flen) {
          Qnew = Q + fnow;
          bvirt = Qnew - Q;
          hh = Q - (Qnew - bvirt) + (fnow - bvirt);
          fnow = f[++findex];
          Q = Qnew;
          if (hh !== 0) {
              h[hindex++] = hh;
          }
      }
      if (Q !== 0 || hindex === 0) {
          h[hindex++] = Q;
      }
      return hindex;
  }

  function estimate(elen, e) {
      let Q = e[0];
      for (let i = 1; i < elen; i++) Q += e[i];
      return Q;
  }

  function vec(n) {
      return new Float64Array(n);
  }

  const ccwerrboundA = (3 + 16 * epsilon) * epsilon;
  const ccwerrboundB = (2 + 12 * epsilon) * epsilon;
  const ccwerrboundC = (9 + 64 * epsilon) * epsilon * epsilon;

  const B$2 = vec(4);
  const C1 = vec(8);
  const C2 = vec(12);
  const D$1 = vec(16);
  const u = vec(4);

  function orient2dadapt(ax, ay, bx, by, cx, cy, detsum) {
      let acxtail, acytail, bcxtail, bcytail;
      let bvirt, c, ahi, alo, bhi, blo, _i, _j, _0, s1, s0, t1, t0, u3;

      const acx = ax - cx;
      const bcx = bx - cx;
      const acy = ay - cy;
      const bcy = by - cy;

      s1 = acx * bcy;
      c = splitter * acx;
      ahi = c - (c - acx);
      alo = acx - ahi;
      c = splitter * bcy;
      bhi = c - (c - bcy);
      blo = bcy - bhi;
      s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
      t1 = acy * bcx;
      c = splitter * acy;
      ahi = c - (c - acy);
      alo = acy - ahi;
      c = splitter * bcx;
      bhi = c - (c - bcx);
      blo = bcx - bhi;
      t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
      _i = s0 - t0;
      bvirt = s0 - _i;
      B$2[0] = s0 - (_i + bvirt) + (bvirt - t0);
      _j = s1 + _i;
      bvirt = _j - s1;
      _0 = s1 - (_j - bvirt) + (_i - bvirt);
      _i = _0 - t1;
      bvirt = _0 - _i;
      B$2[1] = _0 - (_i + bvirt) + (bvirt - t1);
      u3 = _j + _i;
      bvirt = u3 - _j;
      B$2[2] = _j - (u3 - bvirt) + (_i - bvirt);
      B$2[3] = u3;

      let det = estimate(4, B$2);
      let errbound = ccwerrboundB * detsum;
      if (det >= errbound || -det >= errbound) {
          return det;
      }

      bvirt = ax - acx;
      acxtail = ax - (acx + bvirt) + (bvirt - cx);
      bvirt = bx - bcx;
      bcxtail = bx - (bcx + bvirt) + (bvirt - cx);
      bvirt = ay - acy;
      acytail = ay - (acy + bvirt) + (bvirt - cy);
      bvirt = by - bcy;
      bcytail = by - (bcy + bvirt) + (bvirt - cy);

      if (acxtail === 0 && acytail === 0 && bcxtail === 0 && bcytail === 0) {
          return det;
      }

      errbound = ccwerrboundC * detsum + resulterrbound * Math.abs(det);
      det += (acx * bcytail + bcy * acxtail) - (acy * bcxtail + bcx * acytail);
      if (det >= errbound || -det >= errbound) return det;

      s1 = acxtail * bcy;
      c = splitter * acxtail;
      ahi = c - (c - acxtail);
      alo = acxtail - ahi;
      c = splitter * bcy;
      bhi = c - (c - bcy);
      blo = bcy - bhi;
      s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
      t1 = acytail * bcx;
      c = splitter * acytail;
      ahi = c - (c - acytail);
      alo = acytail - ahi;
      c = splitter * bcx;
      bhi = c - (c - bcx);
      blo = bcx - bhi;
      t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
      _i = s0 - t0;
      bvirt = s0 - _i;
      u[0] = s0 - (_i + bvirt) + (bvirt - t0);
      _j = s1 + _i;
      bvirt = _j - s1;
      _0 = s1 - (_j - bvirt) + (_i - bvirt);
      _i = _0 - t1;
      bvirt = _0 - _i;
      u[1] = _0 - (_i + bvirt) + (bvirt - t1);
      u3 = _j + _i;
      bvirt = u3 - _j;
      u[2] = _j - (u3 - bvirt) + (_i - bvirt);
      u[3] = u3;
      const C1len = sum(4, B$2, 4, u, C1);

      s1 = acx * bcytail;
      c = splitter * acx;
      ahi = c - (c - acx);
      alo = acx - ahi;
      c = splitter * bcytail;
      bhi = c - (c - bcytail);
      blo = bcytail - bhi;
      s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
      t1 = acy * bcxtail;
      c = splitter * acy;
      ahi = c - (c - acy);
      alo = acy - ahi;
      c = splitter * bcxtail;
      bhi = c - (c - bcxtail);
      blo = bcxtail - bhi;
      t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
      _i = s0 - t0;
      bvirt = s0 - _i;
      u[0] = s0 - (_i + bvirt) + (bvirt - t0);
      _j = s1 + _i;
      bvirt = _j - s1;
      _0 = s1 - (_j - bvirt) + (_i - bvirt);
      _i = _0 - t1;
      bvirt = _0 - _i;
      u[1] = _0 - (_i + bvirt) + (bvirt - t1);
      u3 = _j + _i;
      bvirt = u3 - _j;
      u[2] = _j - (u3 - bvirt) + (_i - bvirt);
      u[3] = u3;
      const C2len = sum(C1len, C1, 4, u, C2);

      s1 = acxtail * bcytail;
      c = splitter * acxtail;
      ahi = c - (c - acxtail);
      alo = acxtail - ahi;
      c = splitter * bcytail;
      bhi = c - (c - bcytail);
      blo = bcytail - bhi;
      s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
      t1 = acytail * bcxtail;
      c = splitter * acytail;
      ahi = c - (c - acytail);
      alo = acytail - ahi;
      c = splitter * bcxtail;
      bhi = c - (c - bcxtail);
      blo = bcxtail - bhi;
      t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
      _i = s0 - t0;
      bvirt = s0 - _i;
      u[0] = s0 - (_i + bvirt) + (bvirt - t0);
      _j = s1 + _i;
      bvirt = _j - s1;
      _0 = s1 - (_j - bvirt) + (_i - bvirt);
      _i = _0 - t1;
      bvirt = _0 - _i;
      u[1] = _0 - (_i + bvirt) + (bvirt - t1);
      u3 = _j + _i;
      bvirt = u3 - _j;
      u[2] = _j - (u3 - bvirt) + (_i - bvirt);
      u[3] = u3;
      const Dlen = sum(C2len, C2, 4, u, D$1);

      return D$1[Dlen - 1];
  }

  function orient2d(ax, ay, bx, by, cx, cy) {
      const detleft = (ay - cy) * (bx - cx);
      const detright = (ax - cx) * (by - cy);
      const det = detleft - detright;

      if (detleft === 0 || detright === 0 || (detleft > 0) !== (detright > 0)) return det;

      const detsum = Math.abs(detleft + detright);
      if (Math.abs(det) >= ccwerrboundA * detsum) return det;

      return -orient2dadapt(ax, ay, bx, by, cx, cy, detsum);
  }

  const EPSILON = Math.pow(2, -52);
  const EDGE_STACK = new Uint32Array(512);

  class Delaunator {

      static from(points, getX = defaultGetX, getY = defaultGetY) {
          const n = points.length;
          const coords = new Float64Array(n * 2);

          for (let i = 0; i < n; i++) {
              const p = points[i];
              coords[2 * i] = getX(p);
              coords[2 * i + 1] = getY(p);
          }

          return new Delaunator(coords);
      }

      constructor(coords) {
          const n = coords.length >> 1;
          if (n > 0 && typeof coords[0] !== 'number') throw new Error('Expected coords to contain numbers.');

          this.coords = coords;

          // arrays that will store the triangulation graph
          const maxTriangles = Math.max(2 * n - 5, 0);
          this._triangles = new Uint32Array(maxTriangles * 3);
          this._halfedges = new Int32Array(maxTriangles * 3);

          // temporary arrays for tracking the edges of the advancing convex hull
          this._hashSize = Math.ceil(Math.sqrt(n));
          this._hullPrev = new Uint32Array(n); // edge to prev edge
          this._hullNext = new Uint32Array(n); // edge to next edge
          this._hullTri = new Uint32Array(n); // edge to adjacent triangle
          this._hullHash = new Int32Array(this._hashSize).fill(-1); // angular edge hash

          // temporary arrays for sorting points
          this._ids = new Uint32Array(n);
          this._dists = new Float64Array(n);

          this.update();
      }

      update() {
          const {coords, _hullPrev: hullPrev, _hullNext: hullNext, _hullTri: hullTri, _hullHash: hullHash} =  this;
          const n = coords.length >> 1;

          // populate an array of point indices; calculate input data bbox
          let minX = Infinity;
          let minY = Infinity;
          let maxX = -Infinity;
          let maxY = -Infinity;

          for (let i = 0; i < n; i++) {
              const x = coords[2 * i];
              const y = coords[2 * i + 1];
              if (x < minX) minX = x;
              if (y < minY) minY = y;
              if (x > maxX) maxX = x;
              if (y > maxY) maxY = y;
              this._ids[i] = i;
          }
          const cx = (minX + maxX) / 2;
          const cy = (minY + maxY) / 2;

          let minDist = Infinity;
          let i0, i1, i2;

          // pick a seed point close to the center
          for (let i = 0; i < n; i++) {
              const d = dist(cx, cy, coords[2 * i], coords[2 * i + 1]);
              if (d < minDist) {
                  i0 = i;
                  minDist = d;
              }
          }
          const i0x = coords[2 * i0];
          const i0y = coords[2 * i0 + 1];

          minDist = Infinity;

          // find the point closest to the seed
          for (let i = 0; i < n; i++) {
              if (i === i0) continue;
              const d = dist(i0x, i0y, coords[2 * i], coords[2 * i + 1]);
              if (d < minDist && d > 0) {
                  i1 = i;
                  minDist = d;
              }
          }
          let i1x = coords[2 * i1];
          let i1y = coords[2 * i1 + 1];

          let minRadius = Infinity;

          // find the third point which forms the smallest circumcircle with the first two
          for (let i = 0; i < n; i++) {
              if (i === i0 || i === i1) continue;
              const r = circumradius(i0x, i0y, i1x, i1y, coords[2 * i], coords[2 * i + 1]);
              if (r < minRadius) {
                  i2 = i;
                  minRadius = r;
              }
          }
          let i2x = coords[2 * i2];
          let i2y = coords[2 * i2 + 1];

          if (minRadius === Infinity) {
              // order collinear points by dx (or dy if all x are identical)
              // and return the list as a hull
              for (let i = 0; i < n; i++) {
                  this._dists[i] = (coords[2 * i] - coords[0]) || (coords[2 * i + 1] - coords[1]);
              }
              quicksort(this._ids, this._dists, 0, n - 1);
              const hull = new Uint32Array(n);
              let j = 0;
              for (let i = 0, d0 = -Infinity; i < n; i++) {
                  const id = this._ids[i];
                  if (this._dists[id] > d0) {
                      hull[j++] = id;
                      d0 = this._dists[id];
                  }
              }
              this.hull = hull.subarray(0, j);
              this.triangles = new Uint32Array(0);
              this.halfedges = new Uint32Array(0);
              return;
          }

          // swap the order of the seed points for counter-clockwise orientation
          if (orient2d(i0x, i0y, i1x, i1y, i2x, i2y) < 0) {
              const i = i1;
              const x = i1x;
              const y = i1y;
              i1 = i2;
              i1x = i2x;
              i1y = i2y;
              i2 = i;
              i2x = x;
              i2y = y;
          }

          const center = circumcenter(i0x, i0y, i1x, i1y, i2x, i2y);
          this._cx = center.x;
          this._cy = center.y;

          for (let i = 0; i < n; i++) {
              this._dists[i] = dist(coords[2 * i], coords[2 * i + 1], center.x, center.y);
          }

          // sort the points by distance from the seed triangle circumcenter
          quicksort(this._ids, this._dists, 0, n - 1);

          // set up the seed triangle as the starting hull
          this._hullStart = i0;
          let hullSize = 3;

          hullNext[i0] = hullPrev[i2] = i1;
          hullNext[i1] = hullPrev[i0] = i2;
          hullNext[i2] = hullPrev[i1] = i0;

          hullTri[i0] = 0;
          hullTri[i1] = 1;
          hullTri[i2] = 2;

          hullHash.fill(-1);
          hullHash[this._hashKey(i0x, i0y)] = i0;
          hullHash[this._hashKey(i1x, i1y)] = i1;
          hullHash[this._hashKey(i2x, i2y)] = i2;

          this.trianglesLen = 0;
          this._addTriangle(i0, i1, i2, -1, -1, -1);

          for (let k = 0, xp, yp; k < this._ids.length; k++) {
              const i = this._ids[k];
              const x = coords[2 * i];
              const y = coords[2 * i + 1];

              // skip near-duplicate points
              if (k > 0 && Math.abs(x - xp) <= EPSILON && Math.abs(y - yp) <= EPSILON) continue;
              xp = x;
              yp = y;

              // skip seed triangle points
              if (i === i0 || i === i1 || i === i2) continue;

              // find a visible edge on the convex hull using edge hash
              let start = 0;
              for (let j = 0, key = this._hashKey(x, y); j < this._hashSize; j++) {
                  start = hullHash[(key + j) % this._hashSize];
                  if (start !== -1 && start !== hullNext[start]) break;
              }

              start = hullPrev[start];
              let e = start, q;
              while (q = hullNext[e], orient2d(x, y, coords[2 * e], coords[2 * e + 1], coords[2 * q], coords[2 * q + 1]) >= 0) {
                  e = q;
                  if (e === start) {
                      e = -1;
                      break;
                  }
              }
              if (e === -1) continue; // likely a near-duplicate point; skip it

              // add the first triangle from the point
              let t = this._addTriangle(e, i, hullNext[e], -1, -1, hullTri[e]);

              // recursively flip triangles from the point until they satisfy the Delaunay condition
              hullTri[i] = this._legalize(t + 2);
              hullTri[e] = t; // keep track of boundary triangles on the hull
              hullSize++;

              // walk forward through the hull, adding more triangles and flipping recursively
              let n = hullNext[e];
              while (q = hullNext[n], orient2d(x, y, coords[2 * n], coords[2 * n + 1], coords[2 * q], coords[2 * q + 1]) < 0) {
                  t = this._addTriangle(n, i, q, hullTri[i], -1, hullTri[n]);
                  hullTri[i] = this._legalize(t + 2);
                  hullNext[n] = n; // mark as removed
                  hullSize--;
                  n = q;
              }

              // walk backward from the other side, adding more triangles and flipping
              if (e === start) {
                  while (q = hullPrev[e], orient2d(x, y, coords[2 * q], coords[2 * q + 1], coords[2 * e], coords[2 * e + 1]) < 0) {
                      t = this._addTriangle(q, i, e, -1, hullTri[e], hullTri[q]);
                      this._legalize(t + 2);
                      hullTri[q] = t;
                      hullNext[e] = e; // mark as removed
                      hullSize--;
                      e = q;
                  }
              }

              // update the hull indices
              this._hullStart = hullPrev[i] = e;
              hullNext[e] = hullPrev[n] = i;
              hullNext[i] = n;

              // save the two new edges in the hash table
              hullHash[this._hashKey(x, y)] = i;
              hullHash[this._hashKey(coords[2 * e], coords[2 * e + 1])] = e;
          }

          this.hull = new Uint32Array(hullSize);
          for (let i = 0, e = this._hullStart; i < hullSize; i++) {
              this.hull[i] = e;
              e = hullNext[e];
          }

          // trim typed triangle mesh arrays
          this.triangles = this._triangles.subarray(0, this.trianglesLen);
          this.halfedges = this._halfedges.subarray(0, this.trianglesLen);
      }

      _hashKey(x, y) {
          return Math.floor(pseudoAngle(x - this._cx, y - this._cy) * this._hashSize) % this._hashSize;
      }

      _legalize(a) {
          const {_triangles: triangles, _halfedges: halfedges, coords} = this;

          let i = 0;
          let ar = 0;

          // recursion eliminated with a fixed-size stack
          while (true) {
              const b = halfedges[a];

              /* if the pair of triangles doesn't satisfy the Delaunay condition
               * (p1 is inside the circumcircle of [p0, pl, pr]), flip them,
               * then do the same check/flip recursively for the new pair of triangles
               *
               *           pl                    pl
               *          /||\                  /  \
               *       al/ || \bl            al/    \a
               *        /  ||  \              /      \
               *       /  a||b  \    flip    /___ar___\
               *     p0\   ||   /p1   =>   p0\---bl---/p1
               *        \  ||  /              \      /
               *       ar\ || /br             b\    /br
               *          \||/                  \  /
               *           pr                    pr
               */
              const a0 = a - a % 3;
              ar = a0 + (a + 2) % 3;

              if (b === -1) { // convex hull edge
                  if (i === 0) break;
                  a = EDGE_STACK[--i];
                  continue;
              }

              const b0 = b - b % 3;
              const al = a0 + (a + 1) % 3;
              const bl = b0 + (b + 2) % 3;

              const p0 = triangles[ar];
              const pr = triangles[a];
              const pl = triangles[al];
              const p1 = triangles[bl];

              const illegal = inCircle(
                  coords[2 * p0], coords[2 * p0 + 1],
                  coords[2 * pr], coords[2 * pr + 1],
                  coords[2 * pl], coords[2 * pl + 1],
                  coords[2 * p1], coords[2 * p1 + 1]);

              if (illegal) {
                  triangles[a] = p1;
                  triangles[b] = p0;

                  const hbl = halfedges[bl];

                  // edge swapped on the other side of the hull (rare); fix the halfedge reference
                  if (hbl === -1) {
                      let e = this._hullStart;
                      do {
                          if (this._hullTri[e] === bl) {
                              this._hullTri[e] = a;
                              break;
                          }
                          e = this._hullPrev[e];
                      } while (e !== this._hullStart);
                  }
                  this._link(a, hbl);
                  this._link(b, halfedges[ar]);
                  this._link(ar, bl);

                  const br = b0 + (b + 1) % 3;

                  // don't worry about hitting the cap: it can only happen on extremely degenerate input
                  if (i < EDGE_STACK.length) {
                      EDGE_STACK[i++] = br;
                  }
              } else {
                  if (i === 0) break;
                  a = EDGE_STACK[--i];
              }
          }

          return ar;
      }

      _link(a, b) {
          this._halfedges[a] = b;
          if (b !== -1) this._halfedges[b] = a;
      }

      // add a new triangle given vertex indices and adjacent half-edge ids
      _addTriangle(i0, i1, i2, a, b, c) {
          const t = this.trianglesLen;

          this._triangles[t] = i0;
          this._triangles[t + 1] = i1;
          this._triangles[t + 2] = i2;

          this._link(t, a);
          this._link(t + 1, b);
          this._link(t + 2, c);

          this.trianglesLen += 3;

          return t;
      }
  }

  // monotonically increases with real angle, but doesn't need expensive trigonometry
  function pseudoAngle(dx, dy) {
      const p = dx / (Math.abs(dx) + Math.abs(dy));
      return (dy > 0 ? 3 - p : 1 + p) / 4; // [0..1]
  }

  function dist(ax, ay, bx, by) {
      const dx = ax - bx;
      const dy = ay - by;
      return dx * dx + dy * dy;
  }

  function inCircle(ax, ay, bx, by, cx, cy, px, py) {
      const dx = ax - px;
      const dy = ay - py;
      const ex = bx - px;
      const ey = by - py;
      const fx = cx - px;
      const fy = cy - py;

      const ap = dx * dx + dy * dy;
      const bp = ex * ex + ey * ey;
      const cp = fx * fx + fy * fy;

      return dx * (ey * cp - bp * fy) -
             dy * (ex * cp - bp * fx) +
             ap * (ex * fy - ey * fx) < 0;
  }

  function circumradius(ax, ay, bx, by, cx, cy) {
      const dx = bx - ax;
      const dy = by - ay;
      const ex = cx - ax;
      const ey = cy - ay;

      const bl = dx * dx + dy * dy;
      const cl = ex * ex + ey * ey;
      const d = 0.5 / (dx * ey - dy * ex);

      const x = (ey * bl - dy * cl) * d;
      const y = (dx * cl - ex * bl) * d;

      return x * x + y * y;
  }

  function circumcenter(ax, ay, bx, by, cx, cy) {
      const dx = bx - ax;
      const dy = by - ay;
      const ex = cx - ax;
      const ey = cy - ay;

      const bl = dx * dx + dy * dy;
      const cl = ex * ex + ey * ey;
      const d = 0.5 / (dx * ey - dy * ex);

      const x = ax + (ey * bl - dy * cl) * d;
      const y = ay + (dx * cl - ex * bl) * d;

      return {x, y};
  }

  function quicksort(ids, dists, left, right) {
      if (right - left <= 20) {
          for (let i = left + 1; i <= right; i++) {
              const temp = ids[i];
              const tempDist = dists[temp];
              let j = i - 1;
              while (j >= left && dists[ids[j]] > tempDist) ids[j + 1] = ids[j--];
              ids[j + 1] = temp;
          }
      } else {
          const median = (left + right) >> 1;
          let i = left + 1;
          let j = right;
          swap(ids, median, i);
          if (dists[ids[left]] > dists[ids[right]]) swap(ids, left, right);
          if (dists[ids[i]] > dists[ids[right]]) swap(ids, i, right);
          if (dists[ids[left]] > dists[ids[i]]) swap(ids, left, i);

          const temp = ids[i];
          const tempDist = dists[temp];
          while (true) {
              do i++; while (dists[ids[i]] < tempDist);
              do j--; while (dists[ids[j]] > tempDist);
              if (j < i) break;
              swap(ids, i, j);
          }
          ids[left + 1] = ids[j];
          ids[j] = temp;

          if (right - i + 1 >= j - left) {
              quicksort(ids, dists, i, right);
              quicksort(ids, dists, left, j - 1);
          } else {
              quicksort(ids, dists, left, j - 1);
              quicksort(ids, dists, i, right);
          }
      }
  }

  function swap(arr, i, j) {
      const tmp = arr[i];
      arr[i] = arr[j];
      arr[j] = tmp;
  }

  function defaultGetX(p) {
      return p[0];
  }
  function defaultGetY(p) {
      return p[1];
  }

  cmd.alphaShapes = function(pointLyr, targetDataset, opts) {
    requirePointLayer(pointLyr);
    if (opts.interval > 0 === false) {
      stop('Expected a non-negative interval parameter');
    }
    var filter = getAlphaDistanceFilter(targetDataset, opts.interval);
    var dataset = getPolygonDataset$2(pointLyr, filter, opts);
    var merged = mergeDatasets([targetDataset, dataset]);
    var lyr = merged.layers.pop();
    targetDataset.arcs = merged.arcs;
    setOutputLayerName(lyr, pointLyr, null, opts);
    return lyr;
  };

  function getAlphaDistanceFilter(dataset, interval) {
    return isLatLngDataset(dataset) ? getSphericalFilter(interval) : getPlanarFilter(interval);
  }

  function getPlanarFilter(interval) {
    return function(a, b) {
      return distance2D(a[0], a[1], b[0], b[1]) <= interval;
    };
  }

  // TODO: switch to real distance metric (don't assume meters, use CRS data)
  function getSphericalFilter(interval) {
    return function(a, b) {
      return greatCircleDistance(a[0], a[1], b[0], b[1]) <= interval;
    };
  }


  function getTriangleDataset(lyr, filter, opts) {
    var points = getPointsInLayer(lyr);
    var del = Delaunator.from(points);
    var index = opts.keep_points ? new Uint8Array(points.length) : null;
    var triangles = del.triangles;
    var geojson = {
      type: 'MultiPolygon',
      coordinates: []
    };
    var a, b, c, ai, bi, ci;
    for (var i=0, n=triangles.length; i<n; i+=3) {
      // a, b, c: triangle verticies in CCW order
      ai = triangles[i];
      bi = triangles[i+1];
      ci = triangles[i+2];
      a = points[ai];
      b = points[bi];
      c = points[ci];
      if (!(filter(a, b) && filter(b, c) && filter(a, c))) continue;
      geojson.coordinates.push([[c, b, a, c]]);
      if (index) {
        index[ai] = 1;
        index[bi] = 1;
        index[ci] = 1;
      }
    }
    if (index) {
      addPointSymbols(geojson, points, index);
    }
    return importGeoJSON(geojson);
  }

  function addPointSymbols(geom, points, index) {
    for (var i=0, n=index.length; i<n; i++) {
      if (index[i] === 0) {
        geom.coordinates.push(getPointSymbolCoords(points[i]));
      }
    }
  }

  function getPointSymbolCoords(p) {
    var d = 0.0001,
        x = p[0],
        y = p[1];
    return [[[x, y], [x, y+d], [x+d, y+d], [x+d, y], [x, y]]];
  }

  function getPolygonDataset$2(lyr, filter, opts) {
    var dataset = getTriangleDataset(lyr, filter, opts);
    buildTopology(dataset);
    if (!opts.debug) {
      cleanLayers(dataset.layers, dataset, {quiet: true});
    }
    return dataset;
  }

  function dissolveBufferDataset(dataset, optsArg) {
    var opts = optsArg || {};
    var lyr = dataset.layers[0];
    var tmp;
    var nodes = addIntersectionCuts(dataset, {});
    if (opts.debug_division) {
      return debugBufferDivision(lyr, nodes);
    }
    var mosaicIndex = new MosaicIndex(lyr, nodes, {flat: false, no_holes: false});
    if (opts.debug_mosaic) {
      tmp = composeMosaicLayer(lyr, mosaicIndex.mosaic);
      lyr.shapes = tmp.shapes;
      lyr.data = tmp.data;
      return;
    }
    var pathfind = getRingIntersector(mosaicIndex.nodes);
    var shapes2 = lyr.shapes.map(function(shp, shapeId) {
      var tiles = mosaicIndex.getTilesByShapeIds([shapeId]);
      var rings = [];
      for (var i=0; i<tiles.length; i++) {
        rings.push(tiles[i][0]);
      }
      return pathfind(rings, 'dissolve');
    });
    lyr.shapes = shapes2;
    if (!opts.no_dissolve) {
      dissolveArcs(dataset);
    }
  }

  function debugBufferDivision(lyr, nodes) {
    var divide = getHoleDivider(nodes);
    var shapes2 = [];
    var records = [];
    lyr.shapes.forEach(divideShape);
    lyr.shapes = shapes2;
    lyr.data = new DataTable(records);
    return lyr;

    function divideShape(shp) {
      var cw = [], ccw = [];
      divide(shp, cw, ccw);
      cw.forEach(function(ring) {
        shapes2.push([ring]);
        records.push({type: 'ring'});
      });
      ccw.forEach(function(hole) {
        shapes2.push([reversePath(hole)]);
        records.push({type: 'hole'});
      });
    }
  }

  // n = number of segments used to approximate a circle
  // Returns tolerance as a percent of circle radius
  function getBufferToleranceFromCircleSegments(n) {
    return 1 - Math.cos(Math.PI / n);
  }

  function getArcDegreesFromTolerancePct(pct) {
    return 360 * Math.acos(1 - pct) / Math.PI;
  }

  // n = number of segments used to approximate a circle
  // Returns tolerance as a percent of circle radius
  function getBufferToleranceFromCircleSegments2(n) {
    return 1 / Math.cos(Math.PI / n) - 1;
  }

  function getArcDegreesFromTolerancePct2(pct) {
    return 360 * Math.acos(1 / (pct + 1)) / Math.PI;
  }

  // return constant distance in meters, or return null if unparsable
  function parseConstantBufferDistance(str, crs) {
    var parsed = parseMeasure2(str);
    if (!parsed.value) return null;
    return convertDistanceParam(str, crs) || null;
  }

  function getBufferToleranceFunction(dataset, opts) {
    var crs = getDatasetCRS(dataset);
    var constTol = opts.tolerance ? parseConstantBufferDistance(opts.tolerance, crs) : 0;
    var pctOfRadius = 1/100;
    return function(meterDist) {
      if (constTol) return constTol;
      return constTol ? constTol : meterDist * pctOfRadius;
    };
  }

  function getBufferDistanceFunction(lyr, dataset, opts) {
    if (!opts.radius) {
      stop('Missing expected radius parameter');
    }
    var unitStr = opts.units || '';
    var crs = getDatasetCRS(dataset);
    var constDist = parseConstantBufferDistance(opts.radius + unitStr, crs);
    if (constDist) return function() {return constDist;};
    var expr = compileValueExpression(opts.radius, lyr, null, {}); // no arcs
    return function(shpId) {
      var val = expr(shpId);
      if (!val) return 0;
      // TODO: optimize common case that expression returns a number
      var dist = parseConstantBufferDistance(val + unitStr, crs);
      return dist || 0;
    };
  }

  var BufferCommon = /*#__PURE__*/Object.freeze({
    __proto__: null,
    dissolveBufferDataset: dissolveBufferDataset,
    getBufferToleranceFromCircleSegments: getBufferToleranceFromCircleSegments,
    getArcDegreesFromTolerancePct: getArcDegreesFromTolerancePct,
    getBufferToleranceFromCircleSegments2: getBufferToleranceFromCircleSegments2,
    getArcDegreesFromTolerancePct2: getArcDegreesFromTolerancePct2,
    parseConstantBufferDistance: parseConstantBufferDistance,
    getBufferToleranceFunction: getBufferToleranceFunction,
    getBufferDistanceFunction: getBufferDistanceFunction
  });

  // Returns a function for generating GeoJSON geometries (MultiLineString or MultiPolygon)
  function getPolylineBufferMaker(arcs, geod, getBearing, opts) {
    var maker = getPathBufferMaker(arcs, geod, getBearing, opts);
    var geomType = opts.geometry_type;
    // polyline output could be used for debugging
    var outputGeom = opts.output_geometry == 'polyline' ? 'polyline' : 'polygon';

    function pathBufferCoords(pathArcs, dist) {
      var pathCoords = maker(pathArcs, dist);
      var revPathArcs;
      if (geomType == 'polyline') {
        revPathArcs = reversePath(pathArcs.concat());
        pathCoords = pathCoords.concat(maker(revPathArcs, dist));
      }
      pathCoords.push(pathCoords[0]); // close path
      return outputGeom == 'polyline' ? pathCoords : [pathCoords];
    }

    return function(shape, dist) {
      var geom = {
        type: outputGeom == 'polyline' ? 'MultiLineString' : 'MultiPolygon',
        coordinates: []
      };
      for (var i=0; i<shape.length; i++) {
        geom.coordinates.push(pathBufferCoords(shape[i], dist));
      }
      return geom.coordinates.length == 0 ? null : geom;
    };
  }


  function getPathBufferMaker(arcs, geod, getBearing, opts) {

    var backtrackSteps = opts.backtrack >= 0 ? opts.backtrack : 50;
    var pathIter = new ShapeIter(arcs);
    var capStyle = opts.cap_style || 'round'; // expect 'round' or 'flat'
    // var tolerance;
    // TODO: implement other join styles than round

    function addRoundJoin(arr, x, y, startDir, angle, dist) {
      var increment = 10;
      var endDir = startDir + angle;
      var dir = startDir + increment;
      while (dir < endDir) {
        addBufferVertex(arr, geod(x, y, dir, dist), backtrackSteps);
        dir += increment;
      }
    }

    // function addRoundJoin2(arr, x, y, startDir, angle, dist) {
    //   var increment = 10;
    //   var endDir = startDir + angle;
    //   var dir = startDir + increment;
    //   while (dir < endDir) {
    //     addBufferVertex(arr, geod(x, y, dir, dist), backtrackSteps);
    //     dir += increment;
    //   }
    // }

    // Test if two points are within a snapping tolerance
    // TODO: calculate the tolerance more sensibly
    function veryClose(x1, y1, x2, y2, tol) {
      var dist = geom.distance2D(x1, y1, x2, y2);
      return dist < tol;
    }

    function veryCloseToPrevPoint(arr, x, y) {
      var prev = arr[arr.length - 1];
      return veryClose(prev[0], prev[1], x, y, 0.000001);
    }

    function appendPoint(arr, p) {
      var prev = arr[arr.length - 1];
      if (!veryClose(prev[0], prev[1], p[0], p[1], 1e-10)) {
        arr.push(p);
      }
    }

    function makeCap(x, y, direction, dist) {
      if (capStyle == 'flat') {
        return [[x, y]];
      }
      return makeRoundCap(x, y, direction, dist);
    }

    function makeRoundCap(x, y, segmentDir, dist) {
      var points = [];
      var increment = 10;
      var startDir = segmentDir - 90;
      var angle = increment;
      while (angle < 180) {
        points.push(geod(x, y, startDir + angle, dist));
        angle += increment;
      }
      return points;
    }

    // get angle between two extruded segments in degrees
    // positive angle means join in convex (range: 0-180 degrees)
    // negative angle means join is concave (range: -180-0 degrees)
    function getJoinAngle(direction1, direction2) {
      var delta = direction2 - direction1;
      if (delta > 180) {
        delta -= 360;
      }
      if (delta < -180) {
        delta += 360;
      }
      return delta;
    }

    function addBufferVertex(arr, d, maxBacktrack) {
      var a, b, c, hit;
      for (var i=0, idx = arr.length - 3; i<maxBacktrack && idx >= 0; i++, idx--) {
        c = arr[arr.length - 1];
        a = arr[idx];
        b = arr[idx + 1];
        // TODO: consider using a geodetic intersection function for lat-long datasets
        hit = bufferIntersection(a[0], a[1], b[0], b[1], c[0], c[1], d[0], d[1]);
        if (hit) {
          // TODO: handle collinear segments
          // if (hit.length != 2) console.log('COLLINEAR', hit)
          // segments intersect -- replace two internal segment endpoints with xx point
          while (arr.length > idx + 1) arr.pop();
          appendPoint(arr, hit);
        }
      }

      appendPoint(arr, d);
    }

    return function(path, dist) {
      var left = [];
      var x0, y0, x1, y1, x2, y2;
      var p1, p2;
      var bearing, prevBearing, firstBearing, joinAngle;
      var i = 0;
      pathIter.init(path);

      while (pathIter.hasNext()) {
        // TODO: use a tolerance
        if (pathIter.x === x2 && pathIter.y === y2) continue; // skip duplicate points
        x1 = x2;
        y1 = y2;
        x2 = pathIter.x;
        y2 = pathIter.y;
        if (i >= 1) {
          prevBearing = bearing;
          bearing = getBearing(x1, y1, x2, y2);
          p1 = geod(x1, y1, bearing - 90, dist);
          p2 = geod(x2, y2, bearing - 90, dist);
          // left.push([x1, y1], p1) // debug extrusion lines
          // left.push([x2, y2], p2) // debug extrusion lines
        }
        if (i == 1) {
          firstBearing = bearing;
          x0 = x1;
          y0 = y1;
          left.push(p1, p2);
        }
        if (i > 1) {
          joinAngle = getJoinAngle(prevBearing, bearing);
          if (veryCloseToPrevPoint(left, p1[0], p1[1])) {
            // skip first point
            addBufferVertex(left, p2, backtrackSteps);
          } else if (joinAngle > 0) {
            addRoundJoin(left, x1, y1, prevBearing - 90, joinAngle, dist);
            addBufferVertex(left, p1, backtrackSteps);
            addBufferVertex(left, p2, backtrackSteps);
          } else {
            addBufferVertex(left, p1, backtrackSteps);
            addBufferVertex(left, p2, backtrackSteps);
          }
        }
        i++;
      }
      // TODO: handle defective polylines

      if (x2 == x0 && y2 == y0) {
        // add join to finish closed path
        joinAngle = getJoinAngle(bearing, firstBearing);
        if (joinAngle > 0) {
          addRoundJoin(left, x2, y2, bearing - 90, joinAngle, dist);
        }
      } else {
        // add a cap to finish open path
        left.push.apply(left, makeCap(x2, y2, bearing, dist));
      }
      return left;
    };
  }

  function addBufferVertex(arr, d, maxBacktrack) {
    var a, b, c, hit;
    for (var i=0, idx = arr.length - 3; i<maxBacktrack && idx >= 0; i++, idx--) {
      c = arr[arr.length - 1];
      a = arr[idx];
      b = arr[idx + 1];
      // TODO: consider using a geodetic intersection function for lat-long datasets
      hit = bufferIntersection(a[0], a[1], b[0], b[1], c[0], c[1], d[0], d[1]);
      if (hit) {
        // TODO: handle collinear segments
        if (hit.length != 2) ;
        // segments intersect -- replace two internal segment endpoints with xx point
        while (arr.length > idx + 1) arr.pop();
        // TODO: check proximity of hit to several points
        arr.push(hit);
      }
    }

    // TODO: check proximity to previous point
    arr.push(d); // add new point
  }

  // Exclude segments with non-intersecting bounding boxes before
  // calling intersection function
  // Possibly slightly faster than direct call... not worth it?
  function bufferIntersection(ax, ay, bx, by, cx, cy, dx, dy) {
    if (ax < cx && ax < dx && bx < cx && bx < dx ||
        ax > cx && ax > dx && bx > cx && bx > dx ||
        ay < cy && ay < dy && by < cy && by < dy ||
        ay > cy && ay > dy && by > cy && by > dy) return null;
    return geom.segmentIntersection(ax, ay, bx, by, cx, cy, dx, dy);
  }

  var PathBuffer = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getPolylineBufferMaker: getPolylineBufferMaker,
    addBufferVertex: addBufferVertex,
    bufferIntersection: bufferIntersection
  });

  function getPolylineBufferMaker2(arcs, geod, getBearing, opts) {
    var makeLeftBuffer = getPathBufferMaker2(arcs, geod, getBearing, opts);
    var geomType = opts.geometry_type;

    function polygonCoords(ring) {
      return [ring];
    }

    function needLeftBuffer(path, arcs) {
      if (geomType == 'polyline') {
        return opts.type != 'right';
      }
      // assume polygon type
      if (opts.type == 'outer') {
        return geom.getPathWinding(path, arcs) == 1;
      }
      if (opts.type == 'inner') {
        return geom.getPathWinding(path, arcs) == -1;
      }
      return true;
    }

    function needRightBuffer() {
      return geomType == 'polyline' && opts.type != 'left';
    }

    function makeBufferParts(pathArcs, dist) {
      var leftPartials, rightPartials, parts, revPathArcs;

      if (needLeftBuffer(pathArcs, arcs)) {
        leftPartials = makeLeftBuffer(pathArcs, dist);
      }
      if (needRightBuffer()) {
        revPathArcs = reversePath(pathArcs.concat());
        rightPartials = makeLeftBuffer(revPathArcs, dist);
      }
      parts = (leftPartials || []).concat(rightPartials || []);
      return parts.map(polygonCoords);
    }

    // Returns a GeoJSON Geometry (MultiLineString or MultiPolygon) or null
    return function(shape, dist) {
      var geom = {
        type: 'MultiPolygon',
        coordinates: []
      };
      for (var i=0; i<shape.length; i++) {
        geom.coordinates = geom.coordinates.concat(makeBufferParts(shape[i], dist));
      }
      return geom.coordinates.length == 0 ? null : geom;
    };
  }

  function getPathBufferMaker2(arcs, geod, getBearing, opts) {
    var backtrackSteps = opts.backtrack >= 0 ? opts.backtrack : 50;
    var pathIter = new ShapeIter(arcs);
    // var capStyle = opts.cap_style || 'round'; // expect 'round' or 'flat'
    var partials, left, center;
    var bounds;
    // TODO: implement other join styles than round

    // function updateTolerance(dist) {

    // }

    function addRoundJoin(x, y, startDir, angle, dist) {
      var increment = 10;
      var endDir = startDir + angle;
      var dir = startDir + increment;
      while (dir < endDir) {
        addBufferVertex(geod(x, y, dir, dist));
        dir += increment;
      }
    }

    // function addRoundJoin2(arr, x, y, startDir, angle, dist) {
    //   var increment = 10;
    //   var endDir = startDir + angle;
    //   var dir = startDir + increment;
    //   while (dir < endDir) {
    //     addBufferVertex(arr, geod(x, y, dir, dist));
    //     dir += increment;
    //   }
    // }

    // Test if two points are within a snapping tolerance
    // TODO: calculate the tolerance more sensibly
    function veryClose(x1, y1, x2, y2, tol) {
      var dist = geom.distance2D(x1, y1, x2, y2);
      return dist < tol;
    }

    function veryCloseToPrevPoint(arr, x, y) {
      var prev = arr[arr.length - 1];
      return veryClose(prev[0], prev[1], x, y, 0.000001);
    }

    function appendPoint(arr, p) {
      var prev = arr[arr.length - 1];
      if (!veryClose(prev[0], prev[1], p[0], p[1], 1e-10)) {
        arr.push(p);
      }
    }

    // function makeCap(x, y, direction, dist) {
    //   if (capStyle == 'flat') {
    //     return [[x, y]];
    //   }
    //   return makeRoundCap(x, y, direction, dist);
    // }

    // function makeRoundCap(x, y, segmentDir, dist) {
    //   var points = [];
    //   var increment = 10;
    //   var startDir = segmentDir - 90;
    //   var angle = increment;
    //   while (angle < 180) {
    //     points.push(geod(x, y, startDir + angle, dist));
    //     angle += increment;
    //   }
    //   return points;
    // }

    // get angle between two extruded segments in degrees
    // positive angle means join in convex (range: 0-180 degrees)
    // negative angle means join is concave (range: -180-0 degrees)
    function getJoinAngle(direction1, direction2) {
      var delta = direction2 - direction1;
      if (delta > 180) {
        delta -= 360;
      }
      if (delta < -180) {
        delta += 360;
      }
      return delta;
    }


    // TODO: handle polygon holes
    function addBufferVertex(d) {
      var arr = left;
      var a, b, c, c0, hit;
      // c is the start point of the segment formed by appending point d to the polyline.
      c0 = c = arr[arr.length - 1];
      for (var i=0, idx = arr.length - 3; idx >= 0; i++, idx--) {
        a = arr[idx];
        b = arr[idx + 1];
        // TODO: consider using a geodetic intersection function for lat-long datasets
        hit = bufferIntersection(a[0], a[1], b[0], b[1], c[0], c[1], d[0], d[1]);
        if (hit) {
          if (segmentTurn(a, b, c, d) == 1) {
            // interpretation: segment cd crosses segment ab from outside to inside
            // the buffer -- we need to start a new partial; otherwise,
            // the following code would likely remove a loop representing
            // an oxbow-type hole in the buffer.
            //
            finishPartial();
            break;
          }
          // TODO: handle collinear segments (consider creating new partial)
          // if (hit.length != 2) console.log('COLLINEAR', hit)

          // segments intersect, indicating a spurious loop: remove the loop and
          // replace the endpoints of the intersecting segments with the intersection point.
          while (arr.length > idx + 1) arr.pop();
          appendPoint(arr, hit);
          c = hit; // update starting point of the newly added segment
        }

        // Maintain a bounding box around vertices before the backtrack limit.
        // If the latest segment intersects this bounding box, there could be a self-
        // intersection -- start a new partial to prevent self-intersection.
        //
        if (i >= backtrackSteps) {
          if (!bounds) {
            bounds = new Bounds();
            bounds.mergePoint(a[0], a[1]);
          }
          bounds.mergePoint(b[0], b[1]);
          if (testSegmentBoundsIntersection(c0, d, bounds)) {
            finishPartial();
          }
          break;
        }
      }

      appendPoint(arr, d);
    }

    function finishPartial() {
      // Get endpoints of the two polylines, for starting the next partial
      var leftEP = left[left.length - 1];
      var centerEP = center[center.length - 1];

      // Make a polygon ring
      var ring = [];
      extendArray(ring, left);
      center.reverse();
      extendArray(ring, center);
      ring.push(ring[0]); // close ring
      partials.push(ring);

      // Start next partial
      left.push(leftEP);
      center.push(centerEP);

      // clear bbox
      // bbox = null;
    }

    function extendArray(arr, arr2) {
      arr2.reverse();
      while(arr2.length > 0) arr.push(arr2.pop());
    }

    return function(path, dist) {
      // var x0, y0;
      var x1, y1, x2, y2;
      var p1, p2;
      // var firstBearing;
      var bearing, prevBearing, joinAngle;
      partials = [];
      left = [];
      center = [];
      pathIter.init(path);

      // if (pathIter.hasNext()) {
      //   x0 = x2 = pathIter.x;
      //   y0 = y2 = pathIter.y;
      // }
      while (pathIter.hasNext()) {
        // TODO: use a tolerance
        if (pathIter.x === x2 && pathIter.y === y2) continue; // skip duplicate points
        x1 = x2;
        y1 = y2;
        x2 = pathIter.x;
        y2 = pathIter.y;

        prevBearing = bearing;
        bearing = getBearing(x1, y1, x2, y2);
        // shift original polyline segment to the left by buffer distance
        p1 = geod(x1, y1, bearing - 90, dist);
        p2 = geod(x2, y2, bearing - 90, dist);

        if (center.length === 0) {
          // first loop, second point in this partial
          // if (partials.length === 0) {
          //   firstBearing = bearing;
          // }
          left.push(p1, p2);
          center.push([x1, y1], [x2, y2]);
        } else {
          //
          joinAngle = getJoinAngle(prevBearing, bearing);
          if (veryCloseToPrevPoint(left, p1[0], p1[1])) {
            // skip first point
            addBufferVertex(p2);
          } else if (joinAngle > 0) {
            addRoundJoin(x1, y1, prevBearing - 90, joinAngle, dist);
            addBufferVertex(p1);
            addBufferVertex(p2);
          } else {
            addBufferVertex(p1);
            addBufferVertex(p2);
          }
          center.push([x2, y2]);
        }
      }

      if (center.length > 1) {
        finishPartial();
      }
      // TODO: handle defective polylines

      // if (x2 == x0 && y2 == y0) {
      //   // add join to finish closed path
      //   joinAngle = getJoinAngle(bearing, firstBearing);
      //   if (joinAngle > 0) {
      //     addRoundJoin(leftpart, x2, y2, bearing - 90, joinAngle, dist);
      //   }
      // } else {
      //   // add a cap to finish open path
      //   leftpart.push.apply(leftpart, makeCap(x2, y2, bearing, dist));
      // }

      return partials;
    };
  }

  // GeographicLib docs: https://geographiclib.sourceforge.io/html/js/
  //   https://geographiclib.sourceforge.io/html/js/module-GeographicLib_Geodesic.Geodesic.html
  //   https://geographiclib.sourceforge.io/html/js/tutorial-2-interface.html
  function getGeodesic(P) {
    if (!isLatLngCRS(P)) error('Expected an unprojected CRS');
    var f = P.es / (1 + Math.sqrt(P.one_es));
    var GeographicLib = require$1('mproj').internal.GeographicLib;
    return new GeographicLib.Geodesic.Geodesic(P.a, f);
  }

  function interpolatePoint2D(ax, ay, bx, by, k) {
    var j = 1 - k;
    return [ax * j + bx * k, ay * j + by * k];
  }

  function getInterpolationFunction(P) {
    var spherical = P && isLatLngCRS(P);
    if (!spherical) return interpolatePoint2D;
    var geod = getGeodesic(P);
    return function(lng, lat, lng2, lat2, k) {
      var r = geod.Inverse(lat, lng, lat2, lng2);
      var dist = r.s12 * k;
      var r2 = geod.Direct(lat, lng, r.azi1, dist);
      return [r2.lon2, r2.lat2];
    };
  }

  function getPlanarSegmentEndpoint(x, y, bearing, meterDist) {
    var rad = bearing / 180 * Math.PI;
    var dx = Math.sin(rad) * meterDist;
    var dy = Math.cos(rad) * meterDist;
    return [x + dx, y + dy];
  }

  // source: https://github.com/mapbox/cheap-ruler/blob/master/index.js
  function fastGeodeticSegmentFunction(lng, lat, bearing, meterDist) {
    var D2R = Math.PI / 180;
    var cos = Math.cos(lat * D2R);
    var cos2 = 2 * cos * cos - 1;
    var cos3 = 2 * cos * cos2 - cos;
    var cos4 = 2 * cos * cos3 - cos2;
    var cos5 = 2 * cos * cos4 - cos3;
    var kx = (111.41513 * cos - 0.09455 * cos3 + 0.00012 * cos5) * 1000;
    var ky = (111.13209 - 0.56605 * cos2 + 0.0012 * cos4) * 1000;
    var bearingRad = bearing * D2R;
    var lat2 = lat + Math.cos(bearingRad) * meterDist / ky;
    var lng2 = lng + Math.sin(bearingRad) * meterDist / kx;
    return [lng2, lat2];
  }

  function getGeodeticSegmentFunction(P) {
    if (!isLatLngCRS(P)) {
      return getPlanarSegmentEndpoint;
    }
    var g = getGeodesic(P);
    return function(lng, lat, bearing, meterDist) {
      var o = g.Direct(lat, lng, bearing, meterDist);
      var p = [o.lon2, o.lat2];
      return p;
    };
  }

  function getFastGeodeticSegmentFunction(P) {
    // CAREFUL: this function has higher error at very large distances and at the poles
    // also, it wouldn't work for other planets than Earth
    return isLatLngCRS(P) ? fastGeodeticSegmentFunction : getPlanarSegmentEndpoint;
  }


  function bearingDegrees(a, b, c, d) {
    return geom.bearing(a, b, c, d) * 180 / Math.PI;
  }

  function bearingDegrees2D(a, b, c, d) {
    return geom.bearing2D(a, b, c, d) * 180 / Math.PI;
  }

  // return function to calculate bearing of a segment in degrees
  function getBearingFunction(dataset) {
    var P = getDatasetCRS(dataset);
    return isLatLngCRS(P) ? bearingDegrees : bearingDegrees2D;
  }

  var Geodesic = /*#__PURE__*/Object.freeze({
    __proto__: null,
    interpolatePoint2D: interpolatePoint2D,
    getInterpolationFunction: getInterpolationFunction,
    getPlanarSegmentEndpoint: getPlanarSegmentEndpoint,
    getGeodeticSegmentFunction: getGeodeticSegmentFunction,
    getFastGeodeticSegmentFunction: getFastGeodeticSegmentFunction,
    bearingDegrees: bearingDegrees,
    bearingDegrees2D: bearingDegrees2D,
    getBearingFunction: getBearingFunction
  });

  function makePolylineBuffer(lyr, dataset, opts) {
    var geojson = makeShapeBufferGeoJSON(lyr, dataset, opts);
    var dataset2 = importGeoJSON(geojson, {});
    dissolveBufferDataset(dataset2, opts);
    return dataset2;
  }

  function makeShapeBufferGeoJSON(lyr, dataset, opts) {
    var distanceFn = getBufferDistanceFunction(lyr, dataset, opts);
    getBufferToleranceFunction(dataset, opts);
    var geod = getFastGeodeticSegmentFunction(getDatasetCRS(dataset));
    var getBearing = getBearingFunction(dataset);
    var makerOpts = Object.assign({geometry_type: lyr.geometry_type}, opts);
    var factory = opts.v2 ? getPolylineBufferMaker2 : getPolylineBufferMaker;
    var makeShapeBuffer = factory(dataset.arcs, geod, getBearing, makerOpts);
    lyr.data ? lyr.data.getRecords() : null;
    var geometries = lyr.shapes.map(function(shape, i) {
      var dist = distanceFn(i);
      if (!dist || !shape) return null;
      return makeShapeBuffer(shape, dist, lyr.geometry_type);
    });
    // TODO: make sure that importer supports null geometries (not standard GeoJSON);
    return {
      type: 'GeometryCollection',
      geometries: geometries
    };
  }

  function makePolygonBuffer(lyr, dataset, opts) {
    var geojson = makeShapeBufferGeoJSON(lyr, dataset, opts);
    var dataset2 = importGeoJSON(geojson, {});
    dissolveBufferDataset(dataset2);
    return dataset2;
  }

  // Utility functions for GeoJSON-style lat-long [x,y] coordinates and arrays of coords

  var e = 1e-10;
  var T = 90 - e;
  var L = -180 + e;
  var B$1 = -90 + e;
  var R = 180 - e;

  function lastEl(arr) {
    return arr[arr.length - 1];
  }

  function samePoint(a, b) {
    return a && b && a[0] === b[0] && a[1] === b[1];
  }

  function isClosedPath(arr) {
    return samePoint(arr[0], lastEl(arr));
  }

  // remove likely rounding errors
  function snapToEdge(p) {
    if (p[0] <= L) p[0] = -180;
    if (p[0] >= R) p[0] = 180;
    if (p[1] <= B$1) p[1] = -90;
    if (p[1] >= T) p[1] = 90;
  }

  function onPole(p) {
    return p[1] >= T || p[1] <= B$1;
  }

  function isWholeWorld(coords) {
    // TODO: check that l,r,t,b are all reached
    for (var i=0, n=coords.length; i<n; i++) {
      if (!isEdgePoint(coords[i])) return false;
    }
    return true;
  }

  function touchesEdge(coords) {
    for (var i=0, n=coords.length; i<n; i++) {
      if (isEdgePoint(coords[i])) return true;
    }
    return false;
  }

  function isEdgeSegment(a, b) {
    // TODO: handle segments between pole and non-edge point
    // (these shoudn't exist in a properly clipped path)
    return (onPole(a) || onPole(b)) ||
      a[0] <= L && b[0] <= L || a[0] >= R && b[0] >= R;
  }

  function isEdgePoint(p) {
    return p[1] <= B$1 || p[1] >= T || p[0] <= L || p[0] >= R;
  }

  // Remove segments that belong solely to cut points
  // TODO: verify that antimeridian crosses have matching y coords
  // TODO: stitch together split-apart polygons ?
  //
  function removeCutSegments(coords) {
    if (!touchesEdge(coords)) return coords;
    var coords2 = [];
    var a, b, c;
    var skipped = false;
    coords.pop(); // remove duplicate point
    a = coords[coords.length-1];
    b = coords[0];
    for (var ci=1, n=coords.length; ci <= n; ci++) {
      c = ci == n ? coords2[0] : coords[ci];
      if (!c) continue; // undefined c could occur in a defective path
      if ((skipped || isEdgeSegment(a, b)) && isEdgeSegment(b, c)) {
        // skip b
        // console.log("skipping b:", ci, a, b, c)
        skipped = true;
      } else {
        if (skipped === true) {
          skipped = false;
        }
        coords2.push(b);
        a = b;
      }
      b = c;
    }
    if (coords2.length > 0) {
      coords2.push(coords2[0].concat()); // close the path
    }
    // TODO: handle runs that are split at the array boundary
    return coords2;
  }


  function removePolylineCrosses(path) {
    return splitPathAtAntimeridian(path);
  }

  function isAntimeridianPoint(p) {
    // return p[0] <= L || p[0] >= R;
    return p[0] == -180 || p[0] == 180;
  }

  // Removes antimeridian crossings from an array of polygon rings
  // TODO: handle edge case: segment is collinear with antimeridian
  // TODO: handle edge case: path coordinates exceed the standard lat-long range
  //
  // rings: array of rings of [x,y] points.
  // Returns array of split-apart rings
  function removePolygonCrosses(rings) {
    var rings2 = [];
    var splitRings = [];
    var ring;
    for (var i=0; i<rings.length; i++) {
      ring = rings[i];
      if (!isClosedPath(ring)) {
        error('Received an open path');
      }
      if (countCrosses(ring) === 0) {
        rings2.push(ring);
      } else {
        splitRings = splitRings.concat(splitPathAtAntimeridian(ring));
      }
    }
    if (splitRings.length > 0) {
      rings2 = rings2.concat(reconnectSplitParts(splitRings));
    }
    return rings2;
  }

  // Stitch an array of split-apart paths into coordinate rings
  // Assumes that the first and last point of each split-apart path is 180 or -180
  // parts: array of paths that have been split at the antimeridian
  function reconnectSplitParts(parts) {
    var yy = getSortedIntersections(parts);
    var rings = [];
    var usedParts = [];
    parts.forEach(function(part, i) {
      if (usedParts[i]) return;
      if (!isValidSplitPart(part)) {
        error('Geometry error');
      }
      var ring = addPartToRing(part, []);
      if (ring) {
        if (!isClosedPath(ring)) {
          error('Generated an open ring');
        }
        rings.push(ring);
      }
    });

    return rings;

    function addPartToRing(part, ring) {
      var lastPoint = lastEl(part);
      var i = parts.indexOf(part);
      if (usedParts[i]) {
        debug('Tried to use a previously used path');
        return null;
      }
      usedParts[i] = true;
      ring = ring.concat(part);
      var nextPoint = findNextPoint(parts, lastPoint, yy);
      if (!nextPoint) {
        return null;
      }
      if (lastPoint[0] != nextPoint[0]) {
        // add polar line to switch from east to west or west to east
        // coming from east -> turn south
        // coming from west -> turn north
        var poleY = lastPoint[0] == 180 ? -90 : 90;
        // need a center point (lines longer than 90 degrees cause confusion when rotating)
        ring.push([lastPoint[0], poleY], [0, poleY], [nextPoint[0], poleY]);
      }
      var nextPart = findPartStartingAt(parts, nextPoint);
      if (!nextPart) {
        return null;
      }
      if (samePoint(ring[0], nextPart[0])) {
        // done!
        ring.push(ring[0]); // close the ring
        return ring;
      }
      return addPartToRing(nextPart, ring);
    }
  }

  function addSubPath(paths, path) {
    if (path.length > 1) paths.push(path);
  }

  function isValidSplitPart(part) {
    var lastX = lastEl(part)[0];
    var firstX = part[0][0];
    return (lastX == 180 || lastX == -180) && (firstX == 180 || firstX == -180);
  }

  // p: last point of previous part
  function findNextPoint(parts, p, yy) {
    var x = p[0];
    var y = p[1];
    var i = yy.indexOf(y);
    var xOpp = x == -180 ? 180 : -180;
    var turnSouth = x == 180; // intersecting from the east -> turn south
    var iNext = turnSouth ? i - 1 : i + 1;
    var nextPoint;
    if (x != 180 && x != -180) {
      debug('Unexpected error');
      return null;
    }
    if (i == -1) {
      debug('Point missing from intersection table:', p);
      return null;
    }
    if (iNext < 0 || iNext >= yy.length) {
      // no path to traverse to along the antimeridian --
      // assume the path surrounds one of the poles
      // enclose south pole
      nextPoint = [xOpp, y];
    } else {
      nextPoint = [x, yy[iNext]];
    }
    return nextPoint;
  }

  function findPartStartingAt(parts, firstPoint) {
    for (var i=0; i<parts.length; i++) {
      if (samePoint(parts[i][0], firstPoint)) {
        return parts[i];
      }
    }
    return null;
  }

  function countCrosses(path) {
    var c = 0, pp, p;
    for (var i=0, n=path.length; i<n; i++) {
      p = path[i];
      if (i>0 && Math.abs(pp[0] - p[0]) > 180) {
        c++;
      }
      pp = p;
    }
    return c;
  }

  function splitPathAtAntimeridian(path) {
    var parts = [];
    var part = [];
    var firstPoint = path[0];
    var lastPoint = lastEl(path);
    var closed = samePoint(firstPoint, lastPoint);
    var p, pp, y;
    for (var i=0, n=path.length; i<n; i++) {
      p = path[i];
      if (i>0 && segmentCrossesAntimeridian(pp, p)) {
        // y = sphericalIntercept(pp, p);
        y = planarIntercept(pp, p);
        addIntersectionPoint(part, pp, y);
        addSubPath(parts, part);
        part = [];
        addIntersectionPoint(part, p, y);
        // console.log(y, y2)
      }
      part.push(p);
      pp = p;
    }
    addSubPath(parts, part);

    // join first and last parts of a split-apart ring, so that the first part
    // originates at the antimeridian
    if (closed && parts.length > 1 && !isAntimeridianPoint(firstPoint)) {
      part = parts.pop();
      part.pop(); // remove duplicate point
      parts[0] = part.concat(parts[0]);
    }
    return parts;
  }

  function segmentCrossesAntimeridian(a, b) {
    return Math.abs(a[0] - b[0]) > 180;
  }

  function getSortedIntersections(parts) {
    var values = parts.map(function(p) {
      return p[0][1];
    });
    return utils.genericSort(values, true);
  }


  function addIntersectionPoint(part, p, yint) {
    var xint = p[0] < 0 ? -180 : 180;
    if (!isAntimeridianPoint(p)) { // don't a point if p is already on the antimeridian
      part.push([xint, yint]);
    }
  }


  // p1, p2: two vertices on different sides of the antimeridian
  // Returns y-intercept of the segment connecting p1, p2
  // TODO: consider using the great-circle intersection, instead of
  // the planar intersection.
  // (Planar should be fine if p1 and p2 are close to lon. 180)
  function planarIntercept(p1, p2) {
    var dx = p2[0] - p1[0]; // pos: crosses antimeridian w->e, neg: e->w
    var dx1, dx2;
    if (dx > 0) {
      dx1 = p1[0] + 180;
      dx2 = 180 - p2[0];
    } else {
      dx1 = 180 - p1[0];
      dx2 = p2[0] + 180;
    }
    // avoid fp rounding error if a point is on antimeridian
    if (dx1 === 0) return p1[1];
    if (dx2 === 0) return p2[1];
    return (dx2 * p1[1] + dx1 * p2[1]) / (dx1 + dx2);
  }

  function ringArea(ring) {
    var iter = new PointIter(ring);
    return getSphericalPathArea2(iter);
  }

  function makePointBuffer(lyr, dataset, opts) {
    var geojson = makePointBufferGeoJSON(lyr, dataset, opts);
    return importGeoJSON(geojson, {});
  }

  // Make a single geodetic circle
  function getCircleGeoJSON(center, radius, vertices, opts) {
    var n = vertices || 360;
    var geod = getGeodeticSegmentFunction(parseCrsString('wgs84')); // ?
    if (opts.inset) {
      radius -= opts.inset;
    }
    return opts.geometry_type == 'polyline' ?
      getPointBufferLineString([center], radius, n, geod) :
      getPointBufferPolygon([center], radius, n, geod, true);
  }

  // Convert a point layer to circles
  function makePointBufferGeoJSON(lyr, dataset, opts) {
    var vertices = opts.vertices || 72;
    var distanceFn = getBufferDistanceFunction(lyr, dataset, opts);
    var crs = getDatasetCRS(dataset);
    var spherical = isLatLngCRS(crs);
    var geod = getGeodeticSegmentFunction(crs);
    var geometries = lyr.shapes.map(function(shape, i) {
      var dist = distanceFn(i);
      if (!dist || !shape) return null;
      return getPointBufferPolygon(shape, dist, vertices, geod, spherical);
    });
    // TODO: make sure that importer supports null geometries (nonstandard GeoJSON);
    return {
      type: 'GeometryCollection',
      geometries: geometries
    };
  }

  function getPointBufferPolygon(points, distance, vertices, geod, spherical) {
    var rings = [], coords, coords2;
    if (!points || !points.length) return null;
    for (var i=0; i<points.length; i++) {
      coords = getPointBufferCoordinates(points[i], distance, vertices, geod);
      if (!spherical) {
        rings.push([coords]);
      } else if (countCrosses(coords) > 0) {
        coords2 = removePolygonCrosses([coords]);
        while (coords2.length > 0) rings.push([coords2.pop()]); // geojson polygon coords, no hole
      } else if (ringArea(coords) < 0) {
        // negative spherical area: CCW ring, indicating a circle of >180 degrees
        // that fully encloses both poles and the antimeridian.
        // need to add an enclosure around the entire sphere
        // TODO: compare to distance param as a sanity check
        rings.push([
          [[180, 90], [180, -90], [0, -90], [-180, -90], [-180, 90], [0, 90], [180, 90]],
          coords
        ]);
      } else {
        rings.push([coords]);
      }
    }
    return {
      type: 'MultiPolygon',
      coordinates: rings
    };
  }

  function getPointBufferLineString(points, distance, vertices, geod) {
    var rings = [], coords;
    if (!points || !points.length) return null;
    for (var i=0; i<points.length; i++) {
      coords = getPointBufferCoordinates(points[i], distance, vertices, geod);
      coords = removePolylineCrosses(coords);
      while (coords.length > 0) rings.push(coords.pop());
    }
    return rings.length == 1 ? {
      type: 'LineString',
      coordinates: rings[0]
    } : {
      type: 'MultiLineString',
      coordinates: rings
    };
  }

  // Returns array of [x, y] coordinates in a closed ring
  function getPointBufferCoordinates(center, meterDist, vertices, geod) {
    var coords = [],
        angle = 360 / vertices,
        theta;
    for (var i=0; i<vertices; i++) {
      // offsetting by half a step so 4 sides are flat, not pointy
      // (looks better on low-vertex circles)
      theta = (i + 0.5) * angle % 360;
      coords.push(geod(center[0], center[1], theta, meterDist));
    }
    coords.push(coords[0].concat());
    return coords;
  }

  // TODO: consider if layers should be buffered together
  // cmd.buffer = function(layers, dataset, opts) {
  //   return makeBufferLayer(layers[0], dataset, opts);
  // };

  cmd.buffer = makeBufferLayer;

  function makeBufferLayer(lyr, dataset, opts) {
    var dataset2;
    if (lyr.geometry_type == 'point') {
      dataset2 = makePointBuffer(lyr, dataset, opts);
    } else if (lyr.geometry_type == 'polyline') {
      dataset2 = makePolylineBuffer(lyr, dataset, opts);
    } else if (lyr.geometry_type == 'polygon') {
      dataset2 = makePolygonBuffer(lyr, dataset, opts);
    } else {
      stop("Unsupported geometry type");
    }

    var lyr2 = mergeOutputLayerIntoDataset(lyr, dataset, dataset2, opts);
    return [lyr2];
  }

  var scaledIntervals =
    [10,12,15,18,20,22,25,30,35,40,45,50,60,70,80,90,100];
  var precisions =
    [10, 2, 5, 2,10, 2, 5,10, 5,10, 5,50,10,10,10,10,10];


  function getNormalPrecision(scaledInterval) {
    var i = scaledIntervals.indexOf(scaledInterval);
    return precisions[i] || error('Unknown error');
  }

  // return a weighting (0-1) to add strength to classifications that use
  // rounder numbers
  function getRoundnessScore(interval, precision) {
    return precision >= 50 && 1 || precision >= 10 && 0.9 || precision >= 5 && 0.8 || 0.7;
  }

  function getNiceBreaks(values, numBreaks) {
    var quantileBreaks = getQuantileBreaks(values, numBreaks);
    var lowerBreak = quantileBreaks[0];
    var upperBreak = quantileBreaks[quantileBreaks.length-1];
    var data = getCandidateBreaks(lowerBreak, upperBreak, numBreaks);
    // add distribution data and quality metric to each candidate
    data.forEach(function(o) {
      getDistributionData(o.breaks, values);
      o.distribution = getDistributionData(o.breaks, values);
      o.quality = o.roundness * evaluateDistribution(o.distribution);
    });
    utils.sortOn(data, 'quality', false);
    return data[0].breaks;
  }


  function evaluateDistribution(distribution) {
    var ideal = utils.sum(distribution) / distribution.length;
    var first = distribution[0];
    var last = distribution[distribution.length - 1];
    var q = (bucketScore(ideal, first) + bucketScore(ideal, last)) / 2;
    return q;
  }

  // downweight buckets the more they deviate from an ideal size
  function bucketScore(ideal, actual) {
    if (actual > ideal) {
      return ideal / actual;
    } else {
      return ideal / (2 * ideal - actual);
    }
  }

  // kludge to avoid rounding errors in break values
  function applyScale(normalVal, scale) {
    if (scale < 1) {
      return normalVal * Math.round(1 / scale);
    }
    return normalVal / scale;
  }

  function getCandidateBreaks(lowerBreak, upperBreak, numBreaks) {
    var cands = [];
    // calculate rounding using equal interval, when possible
    var maxBreak = Math.max(Math.abs(lowerBreak), Math.abs(upperBreak));
    var subRange = numBreaks >= 2 ?
        (upperBreak - lowerBreak) / (numBreaks - 1) : maxBreak;
    var scale = getRangeScale(subRange);
    var scaledRange = scale * subRange;
    var scaledIntervals = getNiceIntervals(scaledRange);
    scaledIntervals.forEach(function(scaledInterval) {
      var scaledPrecision = getNormalPrecision(scaledInterval);
      var interval = applyScale(scaledInterval, scale);
      var precision = applyScale(scaledPrecision, scale);
      var fenceposts = getBreakFenceposts(lowerBreak, precision);
      fenceposts.forEach(function(lowBound) {
        cands.push({
          interval: interval,
          precision: precision,
          roundness: getRoundnessScore(scaledInterval, scaledPrecision),
          breaks: getRoundBreaks(lowBound, interval, numBreaks)
        });
      });
    });
    return cands;
  }


  function getRoundBreaks(lowerBreak, interval, numBreaks) {
    var breaks = [lowerBreak];
    for (var i=1; i<numBreaks; i++) {
      breaks.push(lowerBreak + interval * i);
    }
    return breaks;
  }

  function getBreakFenceposts(val, precision) {
    var boundVal = getRoundingFunction(precision)(val);
    var boundVal2 = boundVal + (val > boundVal ? precision : -precision);
    var fenceposts = boundVal < boundVal2 ? [boundVal, boundVal2] : [boundVal2, boundVal];
    return fenceposts;
  }

  function getNiceIntervals(scaledRange) {
    var intervals = scaledIntervals;
    var lower, upper;
    for (var i=1; i<intervals.length; i++) {
      lower = intervals[i-1];
      upper = intervals[i];
      if (scaledRange >= lower && scaledRange <= upper) {
        return [lower, upper];
      }
    }
    error('Range error');
  }

  function getRangeScale(range) {
    var s = 1;
    if (range > 0.0001 === false || range < 1e9 === false) {
      stop('Data range error');
    }
    while (range > 100) {
      range /= 10;
      s /= 10;
    }
    while (range < 10) {
      range *= 10;
      s *= 10;
    }
    return s;
  }

  function define(constructor, factory, prototype) {
    constructor.prototype = factory.prototype = prototype;
    prototype.constructor = constructor;
  }

  function extend(parent, definition) {
    var prototype = Object.create(parent.prototype);
    for (var key in definition) prototype[key] = definition[key];
    return prototype;
  }

  function Color() {}

  var darker = 0.7;
  var brighter = 1 / darker;

  var reI = "\\s*([+-]?\\d+)\\s*",
      reN = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",
      reP = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",
      reHex = /^#([0-9a-f]{3,8})$/,
      reRgbInteger = new RegExp(`^rgb\\(${reI},${reI},${reI}\\)$`),
      reRgbPercent = new RegExp(`^rgb\\(${reP},${reP},${reP}\\)$`),
      reRgbaInteger = new RegExp(`^rgba\\(${reI},${reI},${reI},${reN}\\)$`),
      reRgbaPercent = new RegExp(`^rgba\\(${reP},${reP},${reP},${reN}\\)$`),
      reHslPercent = new RegExp(`^hsl\\(${reN},${reP},${reP}\\)$`),
      reHslaPercent = new RegExp(`^hsla\\(${reN},${reP},${reP},${reN}\\)$`);

  var named = {
    aliceblue: 0xf0f8ff,
    antiquewhite: 0xfaebd7,
    aqua: 0x00ffff,
    aquamarine: 0x7fffd4,
    azure: 0xf0ffff,
    beige: 0xf5f5dc,
    bisque: 0xffe4c4,
    black: 0x000000,
    blanchedalmond: 0xffebcd,
    blue: 0x0000ff,
    blueviolet: 0x8a2be2,
    brown: 0xa52a2a,
    burlywood: 0xdeb887,
    cadetblue: 0x5f9ea0,
    chartreuse: 0x7fff00,
    chocolate: 0xd2691e,
    coral: 0xff7f50,
    cornflowerblue: 0x6495ed,
    cornsilk: 0xfff8dc,
    crimson: 0xdc143c,
    cyan: 0x00ffff,
    darkblue: 0x00008b,
    darkcyan: 0x008b8b,
    darkgoldenrod: 0xb8860b,
    darkgray: 0xa9a9a9,
    darkgreen: 0x006400,
    darkgrey: 0xa9a9a9,
    darkkhaki: 0xbdb76b,
    darkmagenta: 0x8b008b,
    darkolivegreen: 0x556b2f,
    darkorange: 0xff8c00,
    darkorchid: 0x9932cc,
    darkred: 0x8b0000,
    darksalmon: 0xe9967a,
    darkseagreen: 0x8fbc8f,
    darkslateblue: 0x483d8b,
    darkslategray: 0x2f4f4f,
    darkslategrey: 0x2f4f4f,
    darkturquoise: 0x00ced1,
    darkviolet: 0x9400d3,
    deeppink: 0xff1493,
    deepskyblue: 0x00bfff,
    dimgray: 0x696969,
    dimgrey: 0x696969,
    dodgerblue: 0x1e90ff,
    firebrick: 0xb22222,
    floralwhite: 0xfffaf0,
    forestgreen: 0x228b22,
    fuchsia: 0xff00ff,
    gainsboro: 0xdcdcdc,
    ghostwhite: 0xf8f8ff,
    gold: 0xffd700,
    goldenrod: 0xdaa520,
    gray: 0x808080,
    green: 0x008000,
    greenyellow: 0xadff2f,
    grey: 0x808080,
    honeydew: 0xf0fff0,
    hotpink: 0xff69b4,
    indianred: 0xcd5c5c,
    indigo: 0x4b0082,
    ivory: 0xfffff0,
    khaki: 0xf0e68c,
    lavender: 0xe6e6fa,
    lavenderblush: 0xfff0f5,
    lawngreen: 0x7cfc00,
    lemonchiffon: 0xfffacd,
    lightblue: 0xadd8e6,
    lightcoral: 0xf08080,
    lightcyan: 0xe0ffff,
    lightgoldenrodyellow: 0xfafad2,
    lightgray: 0xd3d3d3,
    lightgreen: 0x90ee90,
    lightgrey: 0xd3d3d3,
    lightpink: 0xffb6c1,
    lightsalmon: 0xffa07a,
    lightseagreen: 0x20b2aa,
    lightskyblue: 0x87cefa,
    lightslategray: 0x778899,
    lightslategrey: 0x778899,
    lightsteelblue: 0xb0c4de,
    lightyellow: 0xffffe0,
    lime: 0x00ff00,
    limegreen: 0x32cd32,
    linen: 0xfaf0e6,
    magenta: 0xff00ff,
    maroon: 0x800000,
    mediumaquamarine: 0x66cdaa,
    mediumblue: 0x0000cd,
    mediumorchid: 0xba55d3,
    mediumpurple: 0x9370db,
    mediumseagreen: 0x3cb371,
    mediumslateblue: 0x7b68ee,
    mediumspringgreen: 0x00fa9a,
    mediumturquoise: 0x48d1cc,
    mediumvioletred: 0xc71585,
    midnightblue: 0x191970,
    mintcream: 0xf5fffa,
    mistyrose: 0xffe4e1,
    moccasin: 0xffe4b5,
    navajowhite: 0xffdead,
    navy: 0x000080,
    oldlace: 0xfdf5e6,
    olive: 0x808000,
    olivedrab: 0x6b8e23,
    orange: 0xffa500,
    orangered: 0xff4500,
    orchid: 0xda70d6,
    palegoldenrod: 0xeee8aa,
    palegreen: 0x98fb98,
    paleturquoise: 0xafeeee,
    palevioletred: 0xdb7093,
    papayawhip: 0xffefd5,
    peachpuff: 0xffdab9,
    peru: 0xcd853f,
    pink: 0xffc0cb,
    plum: 0xdda0dd,
    powderblue: 0xb0e0e6,
    purple: 0x800080,
    rebeccapurple: 0x663399,
    red: 0xff0000,
    rosybrown: 0xbc8f8f,
    royalblue: 0x4169e1,
    saddlebrown: 0x8b4513,
    salmon: 0xfa8072,
    sandybrown: 0xf4a460,
    seagreen: 0x2e8b57,
    seashell: 0xfff5ee,
    sienna: 0xa0522d,
    silver: 0xc0c0c0,
    skyblue: 0x87ceeb,
    slateblue: 0x6a5acd,
    slategray: 0x708090,
    slategrey: 0x708090,
    snow: 0xfffafa,
    springgreen: 0x00ff7f,
    steelblue: 0x4682b4,
    tan: 0xd2b48c,
    teal: 0x008080,
    thistle: 0xd8bfd8,
    tomato: 0xff6347,
    turquoise: 0x40e0d0,
    violet: 0xee82ee,
    wheat: 0xf5deb3,
    white: 0xffffff,
    whitesmoke: 0xf5f5f5,
    yellow: 0xffff00,
    yellowgreen: 0x9acd32
  };

  define(Color, color, {
    copy(channels) {
      return Object.assign(new this.constructor, this, channels);
    },
    displayable() {
      return this.rgb().displayable();
    },
    hex: color_formatHex, // Deprecated! Use color.formatHex.
    formatHex: color_formatHex,
    formatHex8: color_formatHex8,
    formatHsl: color_formatHsl,
    formatRgb: color_formatRgb,
    toString: color_formatRgb
  });

  function color_formatHex() {
    return this.rgb().formatHex();
  }

  function color_formatHex8() {
    return this.rgb().formatHex8();
  }

  function color_formatHsl() {
    return hslConvert(this).formatHsl();
  }

  function color_formatRgb() {
    return this.rgb().formatRgb();
  }

  function color(format) {
    var m, l;
    format = (format + "").trim().toLowerCase();
    return (m = reHex.exec(format)) ? (l = m[1].length, m = parseInt(m[1], 16), l === 6 ? rgbn(m) // #ff0000
        : l === 3 ? new Rgb((m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), ((m & 0xf) << 4) | (m & 0xf), 1) // #f00
        : l === 8 ? rgba(m >> 24 & 0xff, m >> 16 & 0xff, m >> 8 & 0xff, (m & 0xff) / 0xff) // #ff000000
        : l === 4 ? rgba((m >> 12 & 0xf) | (m >> 8 & 0xf0), (m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), (((m & 0xf) << 4) | (m & 0xf)) / 0xff) // #f000
        : null) // invalid hex
        : (m = reRgbInteger.exec(format)) ? new Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0)
        : (m = reRgbPercent.exec(format)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) // rgb(100%, 0%, 0%)
        : (m = reRgbaInteger.exec(format)) ? rgba(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1)
        : (m = reRgbaPercent.exec(format)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) // rgb(100%, 0%, 0%, 1)
        : (m = reHslPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%)
        : (m = reHslaPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) // hsla(120, 50%, 50%, 1)
        : named.hasOwnProperty(format) ? rgbn(named[format]) // eslint-disable-line no-prototype-builtins
        : format === "transparent" ? new Rgb(NaN, NaN, NaN, 0)
        : null;
  }

  function rgbn(n) {
    return new Rgb(n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff, 1);
  }

  function rgba(r, g, b, a) {
    if (a <= 0) r = g = b = NaN;
    return new Rgb(r, g, b, a);
  }

  function rgbConvert(o) {
    if (!(o instanceof Color)) o = color(o);
    if (!o) return new Rgb;
    o = o.rgb();
    return new Rgb(o.r, o.g, o.b, o.opacity);
  }

  function rgb$1(r, g, b, opacity) {
    return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity);
  }

  function Rgb(r, g, b, opacity) {
    this.r = +r;
    this.g = +g;
    this.b = +b;
    this.opacity = +opacity;
  }

  define(Rgb, rgb$1, extend(Color, {
    brighter(k) {
      k = k == null ? brighter : Math.pow(brighter, k);
      return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
    },
    darker(k) {
      k = k == null ? darker : Math.pow(darker, k);
      return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
    },
    rgb() {
      return this;
    },
    clamp() {
      return new Rgb(clampi(this.r), clampi(this.g), clampi(this.b), clampa(this.opacity));
    },
    displayable() {
      return (-0.5 <= this.r && this.r < 255.5)
          && (-0.5 <= this.g && this.g < 255.5)
          && (-0.5 <= this.b && this.b < 255.5)
          && (0 <= this.opacity && this.opacity <= 1);
    },
    hex: rgb_formatHex, // Deprecated! Use color.formatHex.
    formatHex: rgb_formatHex,
    formatHex8: rgb_formatHex8,
    formatRgb: rgb_formatRgb,
    toString: rgb_formatRgb
  }));

  function rgb_formatHex() {
    return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}`;
  }

  function rgb_formatHex8() {
    return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}${hex((isNaN(this.opacity) ? 1 : this.opacity) * 255)}`;
  }

  function rgb_formatRgb() {
    const a = clampa(this.opacity);
    return `${a === 1 ? "rgb(" : "rgba("}${clampi(this.r)}, ${clampi(this.g)}, ${clampi(this.b)}${a === 1 ? ")" : `, ${a})`}`;
  }

  function clampa(opacity) {
    return isNaN(opacity) ? 1 : Math.max(0, Math.min(1, opacity));
  }

  function clampi(value) {
    return Math.max(0, Math.min(255, Math.round(value) || 0));
  }

  function hex(value) {
    value = clampi(value);
    return (value < 16 ? "0" : "") + value.toString(16);
  }

  function hsla(h, s, l, a) {
    if (a <= 0) h = s = l = NaN;
    else if (l <= 0 || l >= 1) h = s = NaN;
    else if (s <= 0) h = NaN;
    return new Hsl(h, s, l, a);
  }

  function hslConvert(o) {
    if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity);
    if (!(o instanceof Color)) o = color(o);
    if (!o) return new Hsl;
    if (o instanceof Hsl) return o;
    o = o.rgb();
    var r = o.r / 255,
        g = o.g / 255,
        b = o.b / 255,
        min = Math.min(r, g, b),
        max = Math.max(r, g, b),
        h = NaN,
        s = max - min,
        l = (max + min) / 2;
    if (s) {
      if (r === max) h = (g - b) / s + (g < b) * 6;
      else if (g === max) h = (b - r) / s + 2;
      else h = (r - g) / s + 4;
      s /= l < 0.5 ? max + min : 2 - max - min;
      h *= 60;
    } else {
      s = l > 0 && l < 1 ? 0 : h;
    }
    return new Hsl(h, s, l, o.opacity);
  }

  function hsl(h, s, l, opacity) {
    return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity);
  }

  function Hsl(h, s, l, opacity) {
    this.h = +h;
    this.s = +s;
    this.l = +l;
    this.opacity = +opacity;
  }

  define(Hsl, hsl, extend(Color, {
    brighter(k) {
      k = k == null ? brighter : Math.pow(brighter, k);
      return new Hsl(this.h, this.s, this.l * k, this.opacity);
    },
    darker(k) {
      k = k == null ? darker : Math.pow(darker, k);
      return new Hsl(this.h, this.s, this.l * k, this.opacity);
    },
    rgb() {
      var h = this.h % 360 + (this.h < 0) * 360,
          s = isNaN(h) || isNaN(this.s) ? 0 : this.s,
          l = this.l,
          m2 = l + (l < 0.5 ? l : 1 - l) * s,
          m1 = 2 * l - m2;
      return new Rgb(
        hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2),
        hsl2rgb(h, m1, m2),
        hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2),
        this.opacity
      );
    },
    clamp() {
      return new Hsl(clamph(this.h), clampt(this.s), clampt(this.l), clampa(this.opacity));
    },
    displayable() {
      return (0 <= this.s && this.s <= 1 || isNaN(this.s))
          && (0 <= this.l && this.l <= 1)
          && (0 <= this.opacity && this.opacity <= 1);
    },
    formatHsl() {
      const a = clampa(this.opacity);
      return `${a === 1 ? "hsl(" : "hsla("}${clamph(this.h)}, ${clampt(this.s) * 100}%, ${clampt(this.l) * 100}%${a === 1 ? ")" : `, ${a})`}`;
    }
  }));

  function clamph(value) {
    value = (value || 0) % 360;
    return value < 0 ? value + 360 : value;
  }

  function clampt(value) {
    return Math.max(0, Math.min(1, value || 0));
  }

  /* From FvD 13.37, CSS Color Module Level 3 */
  function hsl2rgb(h, m1, m2) {
    return (h < 60 ? m1 + (m2 - m1) * h / 60
        : h < 180 ? m2
        : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60
        : m1) * 255;
  }

  const radians = Math.PI / 180;
  const degrees = 180 / Math.PI;

  var A = -0.14861,
      B = +1.78277,
      C = -0.29227,
      D = -0.90649,
      E = +1.97294,
      ED = E * D,
      EB = E * B,
      BC_DA = B * C - D * A;

  function cubehelixConvert(o) {
    if (o instanceof Cubehelix) return new Cubehelix(o.h, o.s, o.l, o.opacity);
    if (!(o instanceof Rgb)) o = rgbConvert(o);
    var r = o.r / 255,
        g = o.g / 255,
        b = o.b / 255,
        l = (BC_DA * b + ED * r - EB * g) / (BC_DA + ED - EB),
        bl = b - l,
        k = (E * (g - l) - C * bl) / D,
        s = Math.sqrt(k * k + bl * bl) / (E * l * (1 - l)), // NaN if l=0 or l=1
        h = s ? Math.atan2(k, bl) * degrees - 120 : NaN;
    return new Cubehelix(h < 0 ? h + 360 : h, s, l, o.opacity);
  }

  function cubehelix$2(h, s, l, opacity) {
    return arguments.length === 1 ? cubehelixConvert(h) : new Cubehelix(h, s, l, opacity == null ? 1 : opacity);
  }

  function Cubehelix(h, s, l, opacity) {
    this.h = +h;
    this.s = +s;
    this.l = +l;
    this.opacity = +opacity;
  }

  define(Cubehelix, cubehelix$2, extend(Color, {
    brighter(k) {
      k = k == null ? brighter : Math.pow(brighter, k);
      return new Cubehelix(this.h, this.s, this.l * k, this.opacity);
    },
    darker(k) {
      k = k == null ? darker : Math.pow(darker, k);
      return new Cubehelix(this.h, this.s, this.l * k, this.opacity);
    },
    rgb() {
      var h = isNaN(this.h) ? 0 : (this.h + 120) * radians,
          l = +this.l,
          a = isNaN(this.s) ? 0 : this.s * l * (1 - l),
          cosh = Math.cos(h),
          sinh = Math.sin(h);
      return new Rgb(
        255 * (l + a * (A * cosh + B * sinh)),
        255 * (l + a * (C * cosh + D * sinh)),
        255 * (l + a * (E * cosh)),
        this.opacity
      );
    }
  }));

  function basis(t1, v0, v1, v2, v3) {
    var t2 = t1 * t1, t3 = t2 * t1;
    return ((1 - 3 * t1 + 3 * t2 - t3) * v0
        + (4 - 6 * t2 + 3 * t3) * v1
        + (1 + 3 * t1 + 3 * t2 - 3 * t3) * v2
        + t3 * v3) / 6;
  }

  function basis$1(values) {
    var n = values.length - 1;
    return function(t) {
      var i = t <= 0 ? (t = 0) : t >= 1 ? (t = 1, n - 1) : Math.floor(t * n),
          v1 = values[i],
          v2 = values[i + 1],
          v0 = i > 0 ? values[i - 1] : 2 * v1 - v2,
          v3 = i < n - 1 ? values[i + 2] : 2 * v2 - v1;
      return basis((t - i / n) * n, v0, v1, v2, v3);
    };
  }

  var constant = x => () => x;

  function linear(a, d) {
    return function(t) {
      return a + t * d;
    };
  }

  function exponential(a, b, y) {
    return a = Math.pow(a, y), b = Math.pow(b, y) - a, y = 1 / y, function(t) {
      return Math.pow(a + t * b, y);
    };
  }

  function hue(a, b) {
    var d = b - a;
    return d ? linear(a, d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d) : constant(isNaN(a) ? b : a);
  }

  function gamma(y) {
    return (y = +y) === 1 ? nogamma : function(a, b) {
      return b - a ? exponential(a, b, y) : constant(isNaN(a) ? b : a);
    };
  }

  function nogamma(a, b) {
    var d = b - a;
    return d ? linear(a, d) : constant(isNaN(a) ? b : a);
  }

  var rgb = (function rgbGamma(y) {
    var color = gamma(y);

    function rgb(start, end) {
      var r = color((start = rgb$1(start)).r, (end = rgb$1(end)).r),
          g = color(start.g, end.g),
          b = color(start.b, end.b),
          opacity = nogamma(start.opacity, end.opacity);
      return function(t) {
        start.r = r(t);
        start.g = g(t);
        start.b = b(t);
        start.opacity = opacity(t);
        return start + "";
      };
    }

    rgb.gamma = rgbGamma;

    return rgb;
  })(1);

  function rgbSpline(spline) {
    return function(colors) {
      var n = colors.length,
          r = new Array(n),
          g = new Array(n),
          b = new Array(n),
          i, color;
      for (i = 0; i < n; ++i) {
        color = rgb$1(colors[i]);
        r[i] = color.r || 0;
        g[i] = color.g || 0;
        b[i] = color.b || 0;
      }
      r = spline(r);
      g = spline(g);
      b = spline(b);
      color.opacity = 1;
      return function(t) {
        color.r = r(t);
        color.g = g(t);
        color.b = b(t);
        return color + "";
      };
    };
  }

  var rgbBasis = rgbSpline(basis$1);

  function numberArray(a, b) {
    if (!b) b = [];
    var n = a ? Math.min(b.length, a.length) : 0,
        c = b.slice(),
        i;
    return function(t) {
      for (i = 0; i < n; ++i) c[i] = a[i] * (1 - t) + b[i] * t;
      return c;
    };
  }

  function isNumberArray(x) {
    return ArrayBuffer.isView(x) && !(x instanceof DataView);
  }

  function genericArray(a, b) {
    var nb = b ? b.length : 0,
        na = a ? Math.min(nb, a.length) : 0,
        x = new Array(na),
        c = new Array(nb),
        i;

    for (i = 0; i < na; ++i) x[i] = d3_interpolate(a[i], b[i]);
    for (; i < nb; ++i) c[i] = b[i];

    return function(t) {
      for (i = 0; i < na; ++i) c[i] = x[i](t);
      return c;
    };
  }

  function date(a, b) {
    var d = new Date;
    return a = +a, b = +b, function(t) {
      return d.setTime(a * (1 - t) + b * t), d;
    };
  }

  function number(a, b) {
    return a = +a, b = +b, function(t) {
      return a * (1 - t) + b * t;
    };
  }

  function object(a, b) {
    var i = {},
        c = {},
        k;

    if (a === null || typeof a !== "object") a = {};
    if (b === null || typeof b !== "object") b = {};

    for (k in b) {
      if (k in a) {
        i[k] = d3_interpolate(a[k], b[k]);
      } else {
        c[k] = b[k];
      }
    }

    return function(t) {
      for (k in i) c[k] = i[k](t);
      return c;
    };
  }

  var reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,
      reB = new RegExp(reA.source, "g");

  function zero(b) {
    return function() {
      return b;
    };
  }

  function one(b) {
    return function(t) {
      return b(t) + "";
    };
  }

  function string(a, b) {
    var bi = reA.lastIndex = reB.lastIndex = 0, // scan index for next number in b
        am, // current match in a
        bm, // current match in b
        bs, // string preceding current number in b, if any
        i = -1, // index in s
        s = [], // string constants and placeholders
        q = []; // number interpolators

    // Coerce inputs to strings.
    a = a + "", b = b + "";

    // Interpolate pairs of numbers in a & b.
    while ((am = reA.exec(a))
        && (bm = reB.exec(b))) {
      if ((bs = bm.index) > bi) { // a string precedes the next number in b
        bs = b.slice(bi, bs);
        if (s[i]) s[i] += bs; // coalesce with previous string
        else s[++i] = bs;
      }
      if ((am = am[0]) === (bm = bm[0])) { // numbers in a & b match
        if (s[i]) s[i] += bm; // coalesce with previous string
        else s[++i] = bm;
      } else { // interpolate non-matching numbers
        s[++i] = null;
        q.push({i: i, x: number(am, bm)});
      }
      bi = reB.lastIndex;
    }

    // Add remains of b.
    if (bi < b.length) {
      bs = b.slice(bi);
      if (s[i]) s[i] += bs; // coalesce with previous string
      else s[++i] = bs;
    }

    // Special optimization for only a single match.
    // Otherwise, interpolate each of the numbers and rejoin the string.
    return s.length < 2 ? (q[0]
        ? one(q[0].x)
        : zero(b))
        : (b = q.length, function(t) {
            for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t);
            return s.join("");
          });
  }

  function d3_interpolate(a, b) {
    var t = typeof b, c;
    return b == null || t === "boolean" ? constant(b)
        : (t === "number" ? number
        : t === "string" ? ((c = color(b)) ? (b = c, rgb) : string)
        : b instanceof color ? rgb
        : b instanceof Date ? date
        : isNumberArray(b) ? numberArray
        : Array.isArray(b) ? genericArray
        : typeof b.valueOf !== "function" && typeof b.toString !== "function" || isNaN(b) ? object
        : number)(a, b);
  }

  function cubehelix$1(hue) {
    return (function cubehelixGamma(y) {
      y = +y;

      function cubehelix(start, end) {
        var h = hue((start = cubehelix$2(start)).h, (end = cubehelix$2(end)).h),
            s = nogamma(start.s, end.s),
            l = nogamma(start.l, end.l),
            opacity = nogamma(start.opacity, end.opacity);
        return function(t) {
          start.h = h(t);
          start.s = s(t);
          start.l = l(Math.pow(t, y));
          start.opacity = opacity(t);
          return start + "";
        };
      }

      cubehelix.gamma = cubehelixGamma;

      return cubehelix;
    })(1);
  }

  cubehelix$1(hue);
  var cubehelixLong = cubehelix$1(nogamma);

  // TODO: support three or more stops
  function getGradientFunction(stops) {
    var min = stops[0] / 100,
        max = stops[1] / 100;
    if (stops.length != 2) {
      stop('Only two stops are currently supported');
    }
    if (!(min >= 0 && max <= 1 && min < max)) {
      stop('Invalid gradient stops:', stops);
    }
    return function(t) {
      return t * (max - min) + min;
    };
  }

  function getStoppedValues(values, stops) {
    var interpolate = getInterpolatedValueGetter(values, null);
    var n = values.length;
    var fstop = getGradientFunction(stops);
    var values2 = [];
    var t, val;
    for (var i=0; i<n; i++) {
      t = fstop(i / (n - 1));
      val = interpolate(t * (n - 1));
      values2.push(val);
    }
    return values2;
  }

  // convert a continuous index ([0, n-1], -1) to a corresponding interpolated value
  function getInterpolatedValueGetter(values, nullValue) {
    var interpolators = [];
    var tmax = values.length - 1;
    for (var i=1; i<values.length; i++) {
      interpolators.push(d3_interpolate(values[i-1], values[i]));
    }
    return function(t) {
      if (t == -1) return nullValue;
      if ((t >= 0 && t <= tmax) === false) {
        error('Range error');
      }
      var i = t == tmax ? tmax - 1 : Math.floor(t);
      var j = t == tmax ? 1 : t % 1;
      return interpolators[i](j);
    };
  }

  // return an array of n values
  // assumes that values can be interpolated by d3-interpolate
  // (colors and numbers should work)
  function interpolateValuesToClasses(values, n, stops) {
    if (values.length == n && !stops) return values;
    var numPairs = values.length - 1;
    var output = [values[0]];
    var k, j, t, intVal;
    for (var i=1; i<n-1; i++) {
      k = i / (n-1) * numPairs;
      j = Math.floor(k);
      t = k - j;
      // if (convert) t = convert(t);
      intVal = d3_interpolate(values[j], values[j+1])(t);
      output.push(intVal);
    }
    output.push(values[values.length - 1]);
    if (stops) {
      output = getStoppedValues(output, stops);
    }
    return output;
  }

  // convert an index (0 ... n-1, -1, -2) to a corresponding discreet value
  function getDiscreteValueGetter(values, nullValue, otherValue) {
    var n = values.length;
    return function(i) {
      if (i >= 0 && i < n) {
        return values[i];
      }
      if (i == -2) {
        return otherValue === undefined ? nullValue : otherValue;
      }
      return nullValue;
    };
  }

  function getOutputFunction(classValues, nullValue, opts) {
    // get a function to convert class indexes to output values
    //
    if (opts.continuous) {
      return getInterpolatedValueGetter(classValues, nullValue);
    } else {
      return  getDiscreteValueGetter(classValues, nullValue, opts.other);
    }
  }

  function getKeyStyle(type, opts) {
    return {
      width: opts.key_width || type == 'dataviz' && 500 || 300,
      tileHeight: opts.key_tile_height || 10,
      labelSuffix: opts.key_label_suffix || '',
      lastSuffix: opts.key_last_suffix || '',
      chartHeight: 90,
      chartColor: '#ddd',
      ticColor: 'rgba(0,0,0,0.3)',
      ticLen: opts.key_tic_length >= 0 ? +opts.key_tic_length : 6,
      fontFamily: 'sans-serif',
      fontSize: opts.key_font_size || 13,
      textColor: '#555'
    };
  }

  function makeSimpleKey(colors, breaks, minVal, maxVal, opts) {
    var style = getKeyStyle('simple', opts);
    var tileWidth = style.width / colors.length;
    var tileData = makeEqualTiles(tileWidth, style.tileHeight, colors);
    var layers = [tileData];
    var labels, tics, ticBreaks;
    if (colors.length == breaks.length + 1) {
      ticBreaks = getEvenlySpacedTicOffsets(breaks.length, style.width);
      labels = getTicLabels(breaks, ticBreaks, 0, style.width, style);
      tics = getTics(ticBreaks, 0, style.width, style);
      layers.push(tics, labels);
    } else if (colors.length == breaks.length + 2) {
      style.ticLen = 2; // kludge for label spacing
      labels = getInlineLabels(getFullBreaks(breaks, minVal, maxVal), style);
      layers.push(labels);
    }
    exportKey(opts.key_name || 'simple-key', layers, style.width);
  }

  function makeDatavizKey(colors, breaks, ascending, opts) {
    var style = getKeyStyle('dataviz', opts);
    var minVal = ascending[0];
    var maxVal = ascending[ascending.length - 1];
    var partitions = getFullBreaks(breaks, minVal, maxVal);
    var chart = getReferenceChart(ascending, style);
    var tiles = getProportionalTiles(colors, breaks, minVal, maxVal, style);
    var labels = getTicLabels(partitions, partitions, minVal, maxVal, style);
    var tics = getTics(partitions, minVal, maxVal, style);
    exportKey(opts.key_name || 'dataviz-key', [chart, tiles, tics, labels], style.width);
  }

  function makeGradientKey(classify, breaks, minVal, maxVal, opts) {
    var style = getKeyStyle('gradient', opts);
    var partitions = getFullBreaks(breaks, minVal, maxVal);
    var gradient = makeGradient(classify, partitions, style);
    var ticBreaks = getEvenlySpacedTicOffsets(breaks.length, style.width);
    var labels = getTicLabels(breaks, ticBreaks, 0, style.width, style);
    var tics = getTics(ticBreaks, 0, style.width, style);
    var layers = [gradient, tics, labels];
    exportKey(opts.key_name || 'gradient-key', layers, style.width);
  }

  // export function makeGradientDatavizKey(classify, breaks, ascending, opts) {
  //   var style = getKeyStyle('dataviz', opts);
  //   var minVal = ascending[0];
  //   var maxVal = ascending[ascending.length - 1];
  //   var partitions = getFullBreaks(breaks, minVal, maxVal);
  //   var chart = getReferenceChart(ascending, style);
  //   var gradient = makeGradient(classify, partitions, style);
  //   // var tiles = getProportionalTiles(colors, breaks, minVal, maxVal, style);
  //   var labels = getTicLabels(partitions, partitions, minVal, maxVal, style);
  //   var tics = getTics(partitions, minVal, maxVal, style);
  //   exportKey(opts.key_name || 'dataviz-key', [chart, gradient, tics, labels], style.width);
  // }

  function getXScale(keyWidth, minVal, maxVal) {
    return function(val) {
      return (val - minVal) / (maxVal - minVal) * keyWidth;
    };
  }

  function getLabelTexts(values, style) {
    var digits = getLabelDigits(values);
    return values.map(function(val, i) {
      var isLast = i == values.length - 1;
      var suffix = isLast && style.lastSuffix || style.labelSuffix || '';
      return roundToDigits(val, digits) + suffix;
    });
  }

  function getLabelDigits(values) {
    var min = values[0];
    var max = values[values.length - 1];
    var avg = (max - min) / values.length;
    var d = 0;
    if (avg < 1) d = 2;
    else if (avg < 10) d = 1;
    return d;
  }

  function getEvenlySpacedTicOffsets(n, width) {
    var arr = [];
    for (var i=0; i<n; i++) {
      arr.push((i + 1) / (n + 1) * width);
    }
    return arr;
  }

  function getTics(breaks, minVal, maxVal, style) {
    var getX = getXScale(style.width, minVal, maxVal);
    var tics = [];
    for (var i=0; i<breaks.length; i++) {
      tics.push(makeTic(getX(breaks[i]), style));
    }
    return featuresToDataset(tics);
  }

  function getInlineLabels(values, style) {
    var labels = [];
    var texts = getLabelTexts(values, style);
    getLabelShift(style);
    var x;
    for (var i=0; i<texts.length; i++) {
      x = (i + 0.5) * style.width / texts.length;
      labels.push(makeLabel(texts[i], x, style));
    }
    return featuresToDataset(labels);
  }

  function getLabelShift(style) {
    // kludge to nudge numbers towards the tic
    return style.labelSuffix ? 3 : 0;
  }

  function getFullBreaks(innerBreaks, minVal, maxVal) {
    return [minVal].concat(innerBreaks, maxVal);
  }

  function getTicLabels(values, breaks, minVal, maxVal, style) {
    var texts = getLabelTexts(values, style);
    var getX = getXScale(style.width, minVal, maxVal);
    var labels = [];
    for (var i=0; i<breaks.length; i++) {
      labels.push(makeLabel(texts[i], getX(breaks[i]), style));
    }
    return featuresToDataset(labels);
  }

  function getProportionalTiles(colors, breaks, minVal, maxVal, style) {
    var arr = getFullBreaks(breaks, minVal, maxVal);
    var getX = getXScale(style.width, minVal, maxVal);
    var tiles = [];
    var x, w;
    for (var i=0; i<arr.length; i++) {
      x = getX(arr[i]);
      w = getX(arr[i+1]) - x;
      tiles.push(makeTile(x, 0, w, style.tileHeight, colors[i]));
    }
    return featuresToDataset(tiles);
  }

  function getReferenceChart(ascending, style) {
    var barWidth = 5;
    var numBars = Math.floor(style.width / barWidth);
    var breaks = getEqualIntervalBreaks(ascending, numBars - 1);
    var counts = getDistributionData(breaks, ascending);
    var maxCount = Math.max.apply(counts, counts);
    var bars = [];
    var y0 = style.tileHeight; // shift chart above the tiles
    var c, h;
    for (var i=0; i<numBars; i++) {
      c = counts[i];
      if (!c) continue;
      h = c / maxCount * style.chartHeight;
      bars.push(makeTile(i*barWidth, y0, barWidth, h , style.chartColor));
    }
    return featuresToDataset(bars);
  }

  function exportKey(name, datasets, width) {
    var svgOpts = {
      width: width,
      crisp_paths: true,
      default_linecap: 'butt'
    };
    var filename = name + (name.endsWith('.svg') ? '' : '.svg');
    var dataset = datasets.length == 1 ? datasets[0] : mergeDatasets(datasets);
    var output = exportSVG(dataset, svgOpts);
    output[0].filename = filename;
    writeFiles(output, {});
  }

  function featuresToDataset(features) {
    var json = {
      type: 'FeatureCollection',
      features: features
    };
    return importGeoJSON(json);
  }

  function makeGradient(classify, partitions, style) {
    var tiles = [];
    var getVal = pixToValue(partitions, style.width);
    var w = 2;
    for (var x=0; x<style.width; x += w) {
      tiles.push(makeTile(x, 0, w, style.tileHeight, classify(getVal(x))));
    }
    return featuresToDataset(tiles);
  }

  function pixToValue(partitions, keyWidth) {
    var classes = partitions.length - 1;
    var sectionWidth = keyWidth / classes;
    return function(x) {
      var i = Math.min(Math.floor(x / sectionWidth), classes - 1); // clamp
      var k = (x - i * sectionWidth) / sectionWidth;
      return partitions[i] * (1 - k) + partitions[i+1] * k;
    };
  }


  function makeEqualTiles(w, h, colors) {
    var tiles = [];
    for (var i=0; i<colors.length; i++) {
      tiles.push(makeTile(i * w, 0, w, h, colors[i]));
    }
    return featuresToDataset(tiles);
  }

  function getRectangle(x, y, w, h) {
    return [[x, y], [x, y+h], [x+w, y+h], [x+w, y], [x, y]];
  }

  function makeLabel(str, x, style) {
    var y = -(style.ticLen + style.fontSize * 0.7 + 4);
    var align;
    if (x <= 0) {
      align = 'start';
    } else if (x >= style.width) {
      align = 'end';
    } else {
      align = 'middle';
      x += getLabelShift(style);
    }
    return {
      type: 'Feature',
      properties: {
        'label-text': str,
        'font-family': style.fontFamily,
        'font-size': style.fontSize,
        'text-anchor': align,
        fill: style.textColor
      },
      geometry: {
        type: 'Point',
        coordinates: [x, y]
      }
    };
  }

  function makeTic(x, style) {
    var y = style.tileHeight;
    var h = style.tileHeight + style.ticLen;
    return {
      type: 'Feature',
      properties: { stroke: style.ticColor },
      geometry: {
        type: 'LineString',
        coordinates: [[x, y], [x, y - h]]
      }
    };
  }

  function makeTile(x, y, w, h, fill) {
    var coords = getRectangle(x, y, w, h);
    return {
      type: 'Feature',
      properties: {fill: fill},
      geometry: {
        type: 'Polygon',
        coordinates: [coords]
      }
    };
  }

  function getSequentialClassifier$1(classValues, nullValue, dataValues, method, opts) {
    var numValues = classValues.length;
    var numBuckets = opts.continuous ? numValues - 1 : numValues;

    // continuously interpolated colors/values use one fewer breakpoint than
    // discreetly classed values
    var numBreaks = numBuckets - 1;
    var round = opts.precision ? getRoundingFunction(opts.precision) : null;
    var breaks, classifier, dataToClass, classToValue;

    if (round) {
      dataValues = dataValues.map(round);
    }

    var ascending = getAscendingNumbers(dataValues);
    if (opts.range) {
      ascending = applyDataRange(ascending, opts.range);
    }
    var nullCount = dataValues.length - ascending.length;
    var minVal = ascending[0];
    var maxVal = ascending[ascending.length - 1];

    // kludge
    var clamp = opts.range ? function(val) {
      if (val < opts.range[0]) val = opts.range[0];
      if (val > opts.range[1]) val = opts.range[1];
      return val;
    } : null;

    if (opts.range) {
      minVal = opts.range[0];
      maxVal = opts.range[1];
    }

    if (numBreaks === 0) {
      breaks = [];
    } else if (opts.breaks) {
      // user-defined breaks
      breaks = opts.breaks;
    } else if (method == 'equal-interval') {
      breaks = getEqualIntervalBreaks(ascending, numBreaks);
    } else if (method == 'quantile') {
      breaks = getQuantileBreaks(ascending, numBreaks);
    } else if (method == 'hybrid') {
      breaks = getHybridBreaks(ascending, numBreaks);
    } else if (method == 'nice') {
      breaks = getNiceBreaks(ascending, numBreaks);
      message('Nice breaks:', breaks);
    } else {
      stop('Unknown classification method:', method);
    }

    printDistributionInfo(ascending, breaks, nullCount);

    if (opts.continuous) {
      dataToClass = getContinuousClassifier(breaks, minVal, maxVal);
    } else {
      dataToClass = getDiscreteClassifier(breaks, round);
    }
    classToValue = getOutputFunction(classValues, nullValue, opts);
    classifier = function(val) {
      if (clamp) val = clamp(val);
      return classToValue(dataToClass(val));
    };

    // generate a key if we've got colors and a key style
    if (opts.colors && (opts.key || opts.key_style)) {
      if (opts.key_style == 'gradient' && opts.continuous) {
        makeGradientKey(classifier, breaks, minVal, maxVal, opts);
      // } else if (opts.key_style == 'dataviz' && opts.continuous) {
      //   makeGradientDatavizKey(classifier, breaks, ascending, opts);
      } else if (opts.key_style == 'dataviz') {
        makeDatavizKey(classValues, breaks, ascending, opts);
      } else if (opts.key || opts.key_style == 'simple') {
        makeSimpleKey(classValues, breaks, minVal, maxVal, opts);
      }
    }

    return classifier;
  }

  function getClassRanges(breaks, ascending) {
    var ranges = [];
    var ids, geBound, ltBound, range;
    for (var breakId=0, i=0; breakId <= breaks.length; breakId++) {
      geBound = breakId === 0 ? -Infinity : breaks[breakId-1];
      ltBound = breakId < breaks.length ? breaks[breakId] : Infinity;
      ids = getClassRange(ascending, geBound, ltBound, i);
      if (ids) {
        // the usual case: a bucket containing >0 values
        range = [ascending[ids[0]], ascending[ids[1]]];
        i = ids[1];
      } else if (breakId === 0) {
        // left-most bucket, empty
        range = [ltBound, ltBound];
      } else if (breakId < breaks.length) {
        // internal bucket, empty
        range = [geBound, ltBound];
      } else {
        // right-most bucket, empty
        range = [geBound, geBound];
      }
      ranges.push(range);
    }
    return ranges;
  }

  // Gets the first and last value in a sequential class (bucket)
  // Returns null if bucket is empty
  // i: an index into the array of sorted numbers,
  //    at or before the first number in the bucket
  function getClassRange(ascending, geBound, ltBound, i) {
    var n = ascending.length;
    var rangeStart = -1, rangeEnd = -1;
    var val;
    while (i < n) {
      val = ascending[i];
      if (val >= ltBound) break;
      if (rangeStart == -1 && val >= geBound) {
        rangeStart = i;
      }
      rangeEnd = i;
      i++;
    }
    return rangeStart > -1 && rangeEnd > -1 ? [rangeStart, rangeEnd] : null;
  }

  function printDistributionInfo(ascending, breaks, nulls) {
    var dist = getDistributionData(breaks, ascending);
    var tableRows = getClassRanges(breaks, ascending).map(function(range, i) {
      return [`${range[0]} - ${range[1]}`, `(${dist[i]})`];
    });
    tableRows.push(['null or non-numeric values', `(${nulls})`]);
    // message('Computed breaks:', breaks);
    // message('Distribution:', dist.join(','));
    message('Data ranges and (feature counts):\n' + formatColumns(tableRows, ['left', 'right']));
  }

  function getDiscreteClassifier(breaks, round) {
    var inverted = false; // breaks are in descending sequence
    // if (values.length != breaks.length + 1) {
    //   stop("Number of values should be one more than number of class breaks");
    // }
    // validate breaks
    // Accepts repeated values -- should this be allowed?
    if (testAscendingNumbers(breaks)) ; else if (testDescendingNumbers(breaks)) {
      breaks = breaks.concat().reverse();
      inverted = true;
    } else {
      stop('Invalid class breaks:', breaks.join(','));
    }
    return function(val) {
      var i = -1;
      if (Number(val) === val) { // exclude null, NaN, strings, etc.
        if (round) val = val(round);
        i = getClassId(val, breaks);
      }
      if (inverted && i > -1) {
        i = breaks.length - i;
      }
      return i;
    };
  }

  // uses linear interpolation between breakpoints
  // (perhaps not ideal for long-tail distributions)
  // breaks: array of (0 or more) inner breakpoints
  function getContinuousClassifier(breaks, minVal, maxVal) {
    return function(val) {
      var n = breaks.length;
      var min, max, j;
      if (!utils.isValidNumber(val) || val < minVal || val > maxVal){
        return -1;
      }
      for (var i=0; i<=n; i++) {
        max = i === n ? maxVal : breaks[i];
        if (i === n || val < max) {
          min = i === 0 ? minVal : breaks[i-1];
          j = (val - min) / (max - min);
          return i + j;
        }
      }
      error('Range error');
    };
  }

  function getEqualIntervalBreaks(ascending, numBreaks) {
    var numRanges = numBreaks + 1,
        minVal = ascending[0],
        maxVal = ascending[ascending.length - 1],
        interval = (maxVal - minVal) / numRanges,
        breaks = [],
        i;
    for (i = 1; i<numRanges; i++) {
      breaks.push(minVal + i * interval);
    }
    return breaks;
  }

  function getQuantileBreaks(ascending, numBreaks) {
    var numRanges = numBreaks + 1;
    var n = ascending.length / numRanges;
    var breaks = [];
    var i, j;
    for (i = 1; i<numRanges; i++) {
      j = Math.floor(i * n);
      breaks.push(ascending[j]);
    }
    return breaks;
  }

  // inner breaks have equal-interval spacing
  // first and last bucket are sized like quantiles (they are sized to contain
  // a proportional share of the data)
  function getHybridBreaks(ascending, numBreaks) {
    var quantileBreaks = getQuantileBreaks(ascending, numBreaks);
    if (numBreaks < 3) return quantileBreaks;
    var lowerBreak = quantileBreaks[0];
    var upperBreak = quantileBreaks[quantileBreaks.length-1];
    var innerValues = ascending.filter(function(val) {
      return val >= lowerBreak && val < upperBreak;
    });
    var innerBreaks = getEqualIntervalBreaks(innerValues, numBreaks - 2);
    var breaks = [lowerBreak].concat(innerBreaks).concat(upperBreak);
    return breaks;
  }

  function getDistributionData(breaks, ascending) {
    var arr = utils.initializeArray(new Array(breaks.length + 1), 0);
    ascending.forEach(function(val) {
      var i = getClassId(val, breaks);
      if (i == -1) {
        error('Indexing error');
      } else {
        arr[i]++;
      }
    });
    return arr;
  }

  function applyDataRange(values, range) {
    var minval = range[0];
    var maxval = range[1];
    if (maxval > minval === false) {
      stop('Invalid data range:', range);
    }
    var values2 = values.map(function(val) {
      if (val < minval) val = minval;
      if (val > maxval) val = maxval;
      return val;
    });
    if (values2[0] < minval) {
      values2.unshift(minval);
    }
    if (values2[values2.length - 1] < maxval) {
      values2.push(maxval);
    }
    return values2;
  }

  function getAscendingNumbers(values) {
    var numbers = values.filter(utils.isFiniteNumber);
    utils.genericSort(numbers, true);
    return numbers;
  }

  function arraysAreIdentical(a, b) {
    for (var i=0; i<a.length; i++) {
      if (a[i] !== b[i]) return false;
    }
    return a.length == b.length;
  }

  function testAscendingNumbers(arr) {
    return arraysAreIdentical(arr, utils.genericSort(arr.map(parseFloat)));
  }

  function testDescendingNumbers(arr) {
    return arraysAreIdentical(arr, utils.genericSort(arr.map(parseFloat), false));
  }

  // breaks: threshold values between ranges (ascending order)
  // Returns array index of a sequential range, or -1 if @val not numeric
  function getClassId(val, breaks) {
    var i = 0;
    if (!utils.isValidNumber(val)) {
      return -1;
    }
    while (i < breaks.length && val >= breaks[i]) i++;
    return i;
  }

  function getCategoricalClassifier(classValues, nullVal, opts) {
    // categories: strings to match in the data
    var categories = opts.categories;
    var classToValue = getDiscreteValueGetter(classValues, nullVal, opts.other);
    return function(val) {
      var i = categories.indexOf(val);
      var idx = -1;
      if (i >= 0) {
        idx = i;
      } else if (val) {
        idx = -2; // field contains an 'other' value
      } else {
        idx = -1; // field is empty (null value)
      }
      return classToValue(idx);
    };
  }

  // Returns a function for constructing a query function that accepts an arc id and
  // returns information about the polygon or polygons that use the given arc.
  // TODO: explain this better.
  //
  // options:
  //   filter: optional filter function; signature: function(idA, idB or -1) : boolean
  //   reusable: flag that lets an arc be queried multiple times.
  function getArcClassifier(shapes, arcs) {
    var opts = arguments[2] || {},
        useOnce = !opts.reusable,
        n = arcs.size(),
        a = new Int32Array(n),
        b = new Int32Array(n);

    utils.initializeArray(a, -1);
    utils.initializeArray(b, -1);

    traversePaths(shapes, function(o) {
      var i = absArcId(o.arcId);
      var shpId = o.shapeId;
      var aval = a[i];
      if (aval == -1) {
        a[i] = shpId;
      } else if (shpId < aval) {
        b[i] = aval;
        a[i] = shpId;
      } else {
        b[i] = shpId;
      }
    });

    function classify(arcId, getKey) {
      var i = absArcId(arcId);
      var shpA = a[i];
      var shpB = b[i];
      var key;
      if (shpA == -1) return null;
      key = getKey(shpA, shpB);
      if (key === null || key === false) return null;
      if (useOnce) {
        // arc can only be queried once
        a[i] = -1;
        b[i] = -1;
      }
      // use optional filter to exclude some arcs
      if (opts.filter && !opts.filter(shpA, shpB)) return null;
      return key;
    }

    return function(getKey) {
      return function(arcId) {
        return classify(arcId, getKey);
      };
    };
  }

  var ArcClassifier = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getArcClassifier: getArcClassifier
  });

  // Returns a function for querying the neighbors of a given shape. The function
  // can be called in either of two ways:
  //
  // 1. function(shapeId, callback)
  //    Callback signature: function(adjacentShapeId, arcId)
  //    The callback function is called once for each arc that the given feature
  //    shares with another feature.
  //
  // 2. function(shapeId)
  //    The function returns an array of unique ids of neighboring shapes, or
  //    an empty array if a shape has no neighbors.
  //
  function getNeighborLookupFunction(lyr, arcs) {
    var classifier = getArcClassifier(lyr.shapes, arcs, {reusable: true});
    var classify = classifier(onShapes);
    var currShapeId;
    var neighbors;
    var callback;

    function onShapes(a, b) {
      if (b == -1) return -1; // outer edges are b == -1
      return a == currShapeId ? b : a;
    }

    function onArc(arcId) {
      var nabeId = classify(arcId);
      if (nabeId == -1) return;
      if (callback) {
        callback(nabeId, arcId);
      } else if (neighbors.indexOf(nabeId) == -1) {
        neighbors.push(nabeId);
      }
    }

    return function(shpId, cb) {
      currShapeId = shpId;
      if (cb) {
        callback = cb;
        forEachArcId(lyr.shapes[shpId], onArc);
        callback = null;
      } else {
        neighbors = [];
        forEachArcId(lyr.shapes[shpId], onArc);
        return neighbors;
      }
    };
  }


  // Returns an array containing all pairs of adjacent shapes
  // in a collection of polygon shapes. A pair of shapes is represented as
  // an array of two shape indexes [a, b].
  function findPairsOfNeighbors(shapes, arcs) {
    var getKey = function(a, b) {
      return b > -1 && a > -1 ? [a, b] : null;
    };
    var classify = getArcClassifier(shapes, arcs)(getKey);
    var arr = [];
    var index = {};
    var onArc = function(arcId) {
      var obj = classify(arcId);
      var key;
      if (obj) {
        key = obj.join('~');
        if (key in index === false) {
          arr.push(obj);
          index[key] = true;
        }
      }
    };
    forEachArcId(shapes, onArc);
    return arr;
  }

  var PolygonNeighbors = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getNeighborLookupFunction: getNeighborLookupFunction,
    findPairsOfNeighbors: findPairsOfNeighbors
  });

  function getNonAdjacentClassifier(lyr, dataset, colors) {
    requirePolygonLayer(lyr);
    var getNeighbors = getNeighborLookupFunction(lyr, dataset.arcs);
    var errorCount = 0;
    var data = utils.range(getFeatureCount(lyr)).map(function(shpId) {
      var nabes = getNeighbors(shpId) || [];
      var d = {
        nabes: nabes,
        colorId: -1,
        nabeColors: [],
        uncolored: nabes.length, // number of uncolored neighbors
        saturation: 0, // number of unique colors of neighbors
        common: 0 // number of repeated colors in neighbors
      };
      return d;
    });
    var getSortedColorIds = getUpdateFunction(colors.length);
    var colorIds = getSortedColorIds();
    // Sort adjacency data by number of neighbors in descending order
    var iter = getNodeIterator(data);
    // Assign colors, starting with polygons with the largest number of neighbors
    iter.forEach(function(d) {
      var colorId = pickColor(d, data, colorIds);
      if (colorId == -1) {
        errorCount++;
        colorId = colorIds[0];
      }
      d.colorId = colorId;
      {
        colorIds = getSortedColorIds(colorId);
      }
    });

    if (errorCount > 0) {
      message(`Unable to find non-adjacent colors for ${errorCount} ${errorCount == 1 ? 'polygon' : 'polygons'}`);
    }
    return function(shpId) {
      return colors[data[shpId].colorId];
    };
  }

  function getNodeIterator(data) {
    var sorted = data.concat();
    utils.sortOn(sorted, 'uncolored', true);
    function forEach(cb) {
      var item;
      while(sorted.length > 0) {
        item = sorted.pop();
        cb(item);
        updateNeighbors(item, sorted, data);
      }
    }

    return {
      forEach: forEach
    };
  }

  function updateNeighbors(item, sorted, data) {
    var nabe;
    var ids = item.nabes;
    for (var i=0; i<ids.length; i++) {
      nabe = data[ids[i]];
      if (nabe.colorId > -1) continue;
      updateNeighbor(nabe, item.colorId, sorted);
    }
  }

  function updateNeighbor(a, colorId, sorted) {
    var i = findItem(a, sorted);
    var n = sorted.length;
    var b;
    if (i == -1) {
      error('Indexing error');
    }
    a.uncolored--;
    if (!a.nabeColors.includes(colorId)) {
      a.saturation++;
      a.nabeColors.push(colorId);
    } else {
      a.common++;
    }
    // bubble sort!!!
    while (++i < n) {
      b = sorted[i];
      if (!betterThan(a, b)) break;
      sorted[i-1] = b;
      sorted[i] = a;
    }
  }

  function findItem(a, sorted) {
    // return sorted.indexOf(a); // bottleneck
    // binary search in sorted array
    var start = 0, end = sorted.length, i;
    while (end - start > 50) {
      i = Math.floor((start + end) / 2);
      if (sorted[i].saturation >= a.saturation) {
        end = i;
      } else {
        start = i;
      }
    }
    return sorted.indexOf(a, start);
  }

  function betterThan(a, b) {
    if (a.saturation > b.saturation) return true;
    if (a.saturation < b.saturation) return false;
    if (a.common > b.common) return true;
    if (a.common < b.common) return false;
    // based on 4-color tests with counties and zipcodes, this condition adds a bit of strength
    if (a.uncolored < b.uncolored) return true;
    return false;
  }

  // Pick the id of a color that is not shared with a neighboring polygon
  function pickColor(d, data, colorIds) {
    var candidateId;
    for (var i=0; i<colorIds.length; i++) {
      candidateId = colorIds[i];
      if (isAvailableColor(d, data, candidateId)) {
        return candidateId;
      }
    }
    return -1; // no colors are available
  }

  function isAvailableColor(d, data, colorId) {
    var nabes = d.nabes;
    for (var i=0; i<nabes.length; i++) {
      if (data[nabes[i]].colorId === colorId) return false;
    }
    return true;
  }

  // Update function returns an array of ids, sorted in descending order of preference
  // (less-used ids are preferred).
  // Function recieves an (optional) id that was just used.
  function getUpdateFunction(n) {
    var ids = utils.range(n);
    var counts = new Uint32Array(n);
    return function(i) {
      if (i >= 0 && i < n) {
        counts[i]++;
        utils.sortArrayIndex(ids, counts, true);
      } else if (i !== undefined) {
        error('Unexpected color index:', i);
      }
      return ids;
    };
  }

  function getIndexedClassifier(values, nullVal, opts) {
    // TODO: handle continuous classification
    var numBuckets = values.length;
    var classToValue = getOutputFunction(values, nullVal, opts);

    return function(val) {
      var idx = utils.isInteger(val) && val >= 0 && val < numBuckets ? val : -1;
      return classToValue(idx);
    };
  }

  // returns the number of classes, based on the largest class index found
  function getIndexedClassCount(records, name) {
    var invalid = [];
    var maxId = -1;
    records.forEach(function(d) {
      var val = (d || {})[name];
      if (!utils.isInteger(val) || val < -2) {
        invalid.push(val);
      } else {
        maxId = Math.max(maxId, val);
      }
    });
    if (invalid.length > 0) {
      stop(`Class index field contains invalid value(s): ${invalid.slice(0, 5)}`);
    }
    return maxId + 1;
  }

  function colors(specifier) {
    var n = specifier.length / 6 | 0, colors = new Array(n), i = 0;
    while (i < n) colors[i] = "#" + specifier.slice(i * 6, ++i * 6);
    return colors;
  }

  var category10 = colors("1f77b4ff7f0e2ca02cd627289467bd8c564be377c27f7f7fbcbd2217becf");

  var Accent = colors("7fc97fbeaed4fdc086ffff99386cb0f0027fbf5b17666666");

  var Dark2 = colors("1b9e77d95f027570b3e7298a66a61ee6ab02a6761d666666");

  var Paired = colors("a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928");

  var Pastel1 = colors("fbb4aeb3cde3ccebc5decbe4fed9a6ffffcce5d8bdfddaecf2f2f2");

  var Pastel2 = colors("b3e2cdfdcdaccbd5e8f4cae4e6f5c9fff2aef1e2cccccccc");

  var Set1 = colors("e41a1c377eb84daf4a984ea3ff7f00ffff33a65628f781bf999999");

  var Set2 = colors("66c2a5fc8d628da0cbe78ac3a6d854ffd92fe5c494b3b3b3");

  var Set3 = colors("8dd3c7ffffb3bebadafb807280b1d3fdb462b3de69fccde5d9d9d9bc80bdccebc5ffed6f");

  var Tableau10 = colors("4e79a7f28e2ce1575976b7b259a14fedc949af7aa1ff9da79c755fbab0ab");

  var ramp$1 = scheme => rgbBasis(scheme[scheme.length - 1]);

  var scheme$q = new Array(3).concat(
    "d8b365f5f5f55ab4ac",
    "a6611adfc27d80cdc1018571",
    "a6611adfc27df5f5f580cdc1018571",
    "8c510ad8b365f6e8c3c7eae55ab4ac01665e",
    "8c510ad8b365f6e8c3f5f5f5c7eae55ab4ac01665e",
    "8c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e",
    "8c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e",
    "5430058c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e003c30",
    "5430058c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e003c30"
  ).map(colors);

  var BrBG = ramp$1(scheme$q);

  var scheme$p = new Array(3).concat(
    "af8dc3f7f7f77fbf7b",
    "7b3294c2a5cfa6dba0008837",
    "7b3294c2a5cff7f7f7a6dba0008837",
    "762a83af8dc3e7d4e8d9f0d37fbf7b1b7837",
    "762a83af8dc3e7d4e8f7f7f7d9f0d37fbf7b1b7837",
    "762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b7837",
    "762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b7837",
    "40004b762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b783700441b",
    "40004b762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b783700441b"
  ).map(colors);

  var PRGn = ramp$1(scheme$p);

  var scheme$o = new Array(3).concat(
    "e9a3c9f7f7f7a1d76a",
    "d01c8bf1b6dab8e1864dac26",
    "d01c8bf1b6daf7f7f7b8e1864dac26",
    "c51b7de9a3c9fde0efe6f5d0a1d76a4d9221",
    "c51b7de9a3c9fde0eff7f7f7e6f5d0a1d76a4d9221",
    "c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221",
    "c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221",
    "8e0152c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221276419",
    "8e0152c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221276419"
  ).map(colors);

  var PiYG = ramp$1(scheme$o);

  var scheme$n = new Array(3).concat(
    "998ec3f7f7f7f1a340",
    "5e3c99b2abd2fdb863e66101",
    "5e3c99b2abd2f7f7f7fdb863e66101",
    "542788998ec3d8daebfee0b6f1a340b35806",
    "542788998ec3d8daebf7f7f7fee0b6f1a340b35806",
    "5427888073acb2abd2d8daebfee0b6fdb863e08214b35806",
    "5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b35806",
    "2d004b5427888073acb2abd2d8daebfee0b6fdb863e08214b358067f3b08",
    "2d004b5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b358067f3b08"
  ).map(colors);

  var PuOr = ramp$1(scheme$n);

  var scheme$m = new Array(3).concat(
    "ef8a62f7f7f767a9cf",
    "ca0020f4a58292c5de0571b0",
    "ca0020f4a582f7f7f792c5de0571b0",
    "b2182bef8a62fddbc7d1e5f067a9cf2166ac",
    "b2182bef8a62fddbc7f7f7f7d1e5f067a9cf2166ac",
    "b2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac",
    "b2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac",
    "67001fb2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac053061",
    "67001fb2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac053061"
  ).map(colors);

  var RdBu = ramp$1(scheme$m);

  var scheme$l = new Array(3).concat(
    "ef8a62ffffff999999",
    "ca0020f4a582bababa404040",
    "ca0020f4a582ffffffbababa404040",
    "b2182bef8a62fddbc7e0e0e09999994d4d4d",
    "b2182bef8a62fddbc7ffffffe0e0e09999994d4d4d",
    "b2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d",
    "b2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d",
    "67001fb2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d1a1a1a",
    "67001fb2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d1a1a1a"
  ).map(colors);

  var RdGy = ramp$1(scheme$l);

  var scheme$k = new Array(3).concat(
    "fc8d59ffffbf91bfdb",
    "d7191cfdae61abd9e92c7bb6",
    "d7191cfdae61ffffbfabd9e92c7bb6",
    "d73027fc8d59fee090e0f3f891bfdb4575b4",
    "d73027fc8d59fee090ffffbfe0f3f891bfdb4575b4",
    "d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4",
    "d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4",
    "a50026d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4313695",
    "a50026d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4313695"
  ).map(colors);

  var RdYlBu = ramp$1(scheme$k);

  var scheme$j = new Array(3).concat(
    "fc8d59ffffbf91cf60",
    "d7191cfdae61a6d96a1a9641",
    "d7191cfdae61ffffbfa6d96a1a9641",
    "d73027fc8d59fee08bd9ef8b91cf601a9850",
    "d73027fc8d59fee08bffffbfd9ef8b91cf601a9850",
    "d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850",
    "d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850",
    "a50026d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850006837",
    "a50026d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850006837"
  ).map(colors);

  var RdYlGn = ramp$1(scheme$j);

  var scheme$i = new Array(3).concat(
    "fc8d59ffffbf99d594",
    "d7191cfdae61abdda42b83ba",
    "d7191cfdae61ffffbfabdda42b83ba",
    "d53e4ffc8d59fee08be6f59899d5943288bd",
    "d53e4ffc8d59fee08bffffbfe6f59899d5943288bd",
    "d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd",
    "d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd",
    "9e0142d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd5e4fa2",
    "9e0142d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd5e4fa2"
  ).map(colors);

  var Spectral = ramp$1(scheme$i);

  var scheme$h = new Array(3).concat(
    "e5f5f999d8c92ca25f",
    "edf8fbb2e2e266c2a4238b45",
    "edf8fbb2e2e266c2a42ca25f006d2c",
    "edf8fbccece699d8c966c2a42ca25f006d2c",
    "edf8fbccece699d8c966c2a441ae76238b45005824",
    "f7fcfde5f5f9ccece699d8c966c2a441ae76238b45005824",
    "f7fcfde5f5f9ccece699d8c966c2a441ae76238b45006d2c00441b"
  ).map(colors);

  var BuGn = ramp$1(scheme$h);

  var scheme$g = new Array(3).concat(
    "e0ecf49ebcda8856a7",
    "edf8fbb3cde38c96c688419d",
    "edf8fbb3cde38c96c68856a7810f7c",
    "edf8fbbfd3e69ebcda8c96c68856a7810f7c",
    "edf8fbbfd3e69ebcda8c96c68c6bb188419d6e016b",
    "f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d6e016b",
    "f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d810f7c4d004b"
  ).map(colors);

  var BuPu = ramp$1(scheme$g);

  var scheme$f = new Array(3).concat(
    "e0f3dba8ddb543a2ca",
    "f0f9e8bae4bc7bccc42b8cbe",
    "f0f9e8bae4bc7bccc443a2ca0868ac",
    "f0f9e8ccebc5a8ddb57bccc443a2ca0868ac",
    "f0f9e8ccebc5a8ddb57bccc44eb3d32b8cbe08589e",
    "f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe08589e",
    "f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe0868ac084081"
  ).map(colors);

  var GnBu = ramp$1(scheme$f);

  var scheme$e = new Array(3).concat(
    "fee8c8fdbb84e34a33",
    "fef0d9fdcc8afc8d59d7301f",
    "fef0d9fdcc8afc8d59e34a33b30000",
    "fef0d9fdd49efdbb84fc8d59e34a33b30000",
    "fef0d9fdd49efdbb84fc8d59ef6548d7301f990000",
    "fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301f990000",
    "fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301fb300007f0000"
  ).map(colors);

  var OrRd = ramp$1(scheme$e);

  var scheme$d = new Array(3).concat(
    "ece2f0a6bddb1c9099",
    "f6eff7bdc9e167a9cf02818a",
    "f6eff7bdc9e167a9cf1c9099016c59",
    "f6eff7d0d1e6a6bddb67a9cf1c9099016c59",
    "f6eff7d0d1e6a6bddb67a9cf3690c002818a016450",
    "fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016450",
    "fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016c59014636"
  ).map(colors);

  var PuBuGn = ramp$1(scheme$d);

  var scheme$c = new Array(3).concat(
    "ece7f2a6bddb2b8cbe",
    "f1eef6bdc9e174a9cf0570b0",
    "f1eef6bdc9e174a9cf2b8cbe045a8d",
    "f1eef6d0d1e6a6bddb74a9cf2b8cbe045a8d",
    "f1eef6d0d1e6a6bddb74a9cf3690c00570b0034e7b",
    "fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0034e7b",
    "fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0045a8d023858"
  ).map(colors);

  var PuBu = ramp$1(scheme$c);

  var scheme$b = new Array(3).concat(
    "e7e1efc994c7dd1c77",
    "f1eef6d7b5d8df65b0ce1256",
    "f1eef6d7b5d8df65b0dd1c77980043",
    "f1eef6d4b9dac994c7df65b0dd1c77980043",
    "f1eef6d4b9dac994c7df65b0e7298ace125691003f",
    "f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125691003f",
    "f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125698004367001f"
  ).map(colors);

  var PuRd = ramp$1(scheme$b);

  var scheme$a = new Array(3).concat(
    "fde0ddfa9fb5c51b8a",
    "feebe2fbb4b9f768a1ae017e",
    "feebe2fbb4b9f768a1c51b8a7a0177",
    "feebe2fcc5c0fa9fb5f768a1c51b8a7a0177",
    "feebe2fcc5c0fa9fb5f768a1dd3497ae017e7a0177",
    "fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a0177",
    "fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a017749006a"
  ).map(colors);

  var RdPu = ramp$1(scheme$a);

  var scheme$9 = new Array(3).concat(
    "edf8b17fcdbb2c7fb8",
    "ffffcca1dab441b6c4225ea8",
    "ffffcca1dab441b6c42c7fb8253494",
    "ffffccc7e9b47fcdbb41b6c42c7fb8253494",
    "ffffccc7e9b47fcdbb41b6c41d91c0225ea80c2c84",
    "ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea80c2c84",
    "ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea8253494081d58"
  ).map(colors);

  var YlGnBu = ramp$1(scheme$9);

  var scheme$8 = new Array(3).concat(
    "f7fcb9addd8e31a354",
    "ffffccc2e69978c679238443",
    "ffffccc2e69978c67931a354006837",
    "ffffccd9f0a3addd8e78c67931a354006837",
    "ffffccd9f0a3addd8e78c67941ab5d238443005a32",
    "ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443005a32",
    "ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443006837004529"
  ).map(colors);

  var YlGn = ramp$1(scheme$8);

  var scheme$7 = new Array(3).concat(
    "fff7bcfec44fd95f0e",
    "ffffd4fed98efe9929cc4c02",
    "ffffd4fed98efe9929d95f0e993404",
    "ffffd4fee391fec44ffe9929d95f0e993404",
    "ffffd4fee391fec44ffe9929ec7014cc4c028c2d04",
    "ffffe5fff7bcfee391fec44ffe9929ec7014cc4c028c2d04",
    "ffffe5fff7bcfee391fec44ffe9929ec7014cc4c02993404662506"
  ).map(colors);

  var YlOrBr = ramp$1(scheme$7);

  var scheme$6 = new Array(3).concat(
    "ffeda0feb24cf03b20",
    "ffffb2fecc5cfd8d3ce31a1c",
    "ffffb2fecc5cfd8d3cf03b20bd0026",
    "ffffb2fed976feb24cfd8d3cf03b20bd0026",
    "ffffb2fed976feb24cfd8d3cfc4e2ae31a1cb10026",
    "ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cb10026",
    "ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cbd0026800026"
  ).map(colors);

  var YlOrRd = ramp$1(scheme$6);

  var scheme$5 = new Array(3).concat(
    "deebf79ecae13182bd",
    "eff3ffbdd7e76baed62171b5",
    "eff3ffbdd7e76baed63182bd08519c",
    "eff3ffc6dbef9ecae16baed63182bd08519c",
    "eff3ffc6dbef9ecae16baed64292c62171b5084594",
    "f7fbffdeebf7c6dbef9ecae16baed64292c62171b5084594",
    "f7fbffdeebf7c6dbef9ecae16baed64292c62171b508519c08306b"
  ).map(colors);

  var Blues = ramp$1(scheme$5);

  var scheme$4 = new Array(3).concat(
    "e5f5e0a1d99b31a354",
    "edf8e9bae4b374c476238b45",
    "edf8e9bae4b374c47631a354006d2c",
    "edf8e9c7e9c0a1d99b74c47631a354006d2c",
    "edf8e9c7e9c0a1d99b74c47641ab5d238b45005a32",
    "f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45005a32",
    "f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45006d2c00441b"
  ).map(colors);

  var Greens = ramp$1(scheme$4);

  var scheme$3 = new Array(3).concat(
    "f0f0f0bdbdbd636363",
    "f7f7f7cccccc969696525252",
    "f7f7f7cccccc969696636363252525",
    "f7f7f7d9d9d9bdbdbd969696636363252525",
    "f7f7f7d9d9d9bdbdbd969696737373525252252525",
    "fffffff0f0f0d9d9d9bdbdbd969696737373525252252525",
    "fffffff0f0f0d9d9d9bdbdbd969696737373525252252525000000"
  ).map(colors);

  var Greys = ramp$1(scheme$3);

  var scheme$2 = new Array(3).concat(
    "efedf5bcbddc756bb1",
    "f2f0f7cbc9e29e9ac86a51a3",
    "f2f0f7cbc9e29e9ac8756bb154278f",
    "f2f0f7dadaebbcbddc9e9ac8756bb154278f",
    "f2f0f7dadaebbcbddc9e9ac8807dba6a51a34a1486",
    "fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a34a1486",
    "fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a354278f3f007d"
  ).map(colors);

  var Purples = ramp$1(scheme$2);

  var scheme$1 = new Array(3).concat(
    "fee0d2fc9272de2d26",
    "fee5d9fcae91fb6a4acb181d",
    "fee5d9fcae91fb6a4ade2d26a50f15",
    "fee5d9fcbba1fc9272fb6a4ade2d26a50f15",
    "fee5d9fcbba1fc9272fb6a4aef3b2ccb181d99000d",
    "fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181d99000d",
    "fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181da50f1567000d"
  ).map(colors);

  var Reds = ramp$1(scheme$1);

  var scheme = new Array(3).concat(
    "fee6cefdae6be6550d",
    "feeddefdbe85fd8d3cd94701",
    "feeddefdbe85fd8d3ce6550da63603",
    "feeddefdd0a2fdae6bfd8d3ce6550da63603",
    "feeddefdd0a2fdae6bfd8d3cf16913d948018c2d04",
    "fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d948018c2d04",
    "fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d94801a636037f2704"
  ).map(colors);

  var Oranges = ramp$1(scheme);

  function cividis(t) {
    t = Math.max(0, Math.min(1, t));
    return "rgb("
        + Math.max(0, Math.min(255, Math.round(-4.54 - t * (35.34 - t * (2381.73 - t * (6402.7 - t * (7024.72 - t * 2710.57))))))) + ", "
        + Math.max(0, Math.min(255, Math.round(32.49 + t * (170.73 + t * (52.82 - t * (131.46 - t * (176.58 - t * 67.37))))))) + ", "
        + Math.max(0, Math.min(255, Math.round(81.24 + t * (442.36 - t * (2482.43 - t * (6167.24 - t * (6614.94 - t * 2475.67)))))))
        + ")";
  }

  var cubehelix = cubehelixLong(cubehelix$2(300, 0.5, 0.0), cubehelix$2(-240, 0.5, 1.0));

  var warm = cubehelixLong(cubehelix$2(-100, 0.75, 0.35), cubehelix$2(80, 1.50, 0.8));

  var cool = cubehelixLong(cubehelix$2(260, 0.75, 0.35), cubehelix$2(80, 1.50, 0.8));

  var c$1 = cubehelix$2();

  function rainbow(t) {
    if (t < 0 || t > 1) t -= Math.floor(t);
    var ts = Math.abs(t - 0.5);
    c$1.h = 360 * t - 100;
    c$1.s = 1.5 - 1.5 * ts;
    c$1.l = 0.8 - 0.9 * ts;
    return c$1 + "";
  }

  var c = rgb$1(),
      pi_1_3 = Math.PI / 3,
      pi_2_3 = Math.PI * 2 / 3;

  function sinebow(t) {
    var x;
    t = (0.5 - t) * Math.PI;
    c.r = 255 * (x = Math.sin(t)) * x;
    c.g = 255 * (x = Math.sin(t + pi_1_3)) * x;
    c.b = 255 * (x = Math.sin(t + pi_2_3)) * x;
    return c + "";
  }

  function turbo(t) {
    t = Math.max(0, Math.min(1, t));
    return "rgb("
        + Math.max(0, Math.min(255, Math.round(34.61 + t * (1172.33 - t * (10793.56 - t * (33300.12 - t * (38394.49 - t * 14825.05))))))) + ", "
        + Math.max(0, Math.min(255, Math.round(23.31 + t * (557.33 + t * (1225.33 - t * (3574.96 - t * (1073.77 + t * 707.56))))))) + ", "
        + Math.max(0, Math.min(255, Math.round(27.2 + t * (3211.1 - t * (15327.97 - t * (27814 - t * (22569.18 - t * 6838.66)))))))
        + ")";
  }

  function ramp(range) {
    var n = range.length;
    return function(t) {
      return range[Math.max(0, Math.min(n - 1, Math.floor(t * n)))];
    };
  }

  var viridis = ramp(colors("44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725"));

  var magma = ramp(colors("00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf"));

  var inferno = ramp(colors("00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4"));

  var plasma = ramp(colors("0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921"));

  var d3Scales = /*#__PURE__*/Object.freeze({
    __proto__: null,
    schemeCategory10: category10,
    schemeAccent: Accent,
    schemeDark2: Dark2,
    schemePaired: Paired,
    schemePastel1: Pastel1,
    schemePastel2: Pastel2,
    schemeSet1: Set1,
    schemeSet2: Set2,
    schemeSet3: Set3,
    schemeTableau10: Tableau10,
    interpolateBrBG: BrBG,
    schemeBrBG: scheme$q,
    interpolatePRGn: PRGn,
    schemePRGn: scheme$p,
    interpolatePiYG: PiYG,
    schemePiYG: scheme$o,
    interpolatePuOr: PuOr,
    schemePuOr: scheme$n,
    interpolateRdBu: RdBu,
    schemeRdBu: scheme$m,
    interpolateRdGy: RdGy,
    schemeRdGy: scheme$l,
    interpolateRdYlBu: RdYlBu,
    schemeRdYlBu: scheme$k,
    interpolateRdYlGn: RdYlGn,
    schemeRdYlGn: scheme$j,
    interpolateSpectral: Spectral,
    schemeSpectral: scheme$i,
    interpolateBuGn: BuGn,
    schemeBuGn: scheme$h,
    interpolateBuPu: BuPu,
    schemeBuPu: scheme$g,
    interpolateGnBu: GnBu,
    schemeGnBu: scheme$f,
    interpolateOrRd: OrRd,
    schemeOrRd: scheme$e,
    interpolatePuBuGn: PuBuGn,
    schemePuBuGn: scheme$d,
    interpolatePuBu: PuBu,
    schemePuBu: scheme$c,
    interpolatePuRd: PuRd,
    schemePuRd: scheme$b,
    interpolateRdPu: RdPu,
    schemeRdPu: scheme$a,
    interpolateYlGnBu: YlGnBu,
    schemeYlGnBu: scheme$9,
    interpolateYlGn: YlGn,
    schemeYlGn: scheme$8,
    interpolateYlOrBr: YlOrBr,
    schemeYlOrBr: scheme$7,
    interpolateYlOrRd: YlOrRd,
    schemeYlOrRd: scheme$6,
    interpolateBlues: Blues,
    schemeBlues: scheme$5,
    interpolateGreens: Greens,
    schemeGreens: scheme$4,
    interpolateGreys: Greys,
    schemeGreys: scheme$3,
    interpolatePurples: Purples,
    schemePurples: scheme$2,
    interpolateReds: Reds,
    schemeReds: scheme$1,
    interpolateOranges: Oranges,
    schemeOranges: scheme,
    interpolateCividis: cividis,
    interpolateCubehelixDefault: cubehelix,
    interpolateRainbow: rainbow,
    interpolateWarm: warm,
    interpolateCool: cool,
    interpolateSinebow: sinebow,
    interpolateTurbo: turbo,
    interpolateViridis: viridis,
    interpolateMagma: magma,
    interpolateInferno: inferno,
    interpolatePlasma: plasma
  });

  var index = {
    categorical: [],
    sequential: [],
    rainbow: [],
    diverging: [],
    all: []
  };
  var ramps;

  function initSchemes() {
    if (ramps) return;
    ramps = {};
    addSchemesFromD3('categorical', 'Category10,Accent,Dark2,Paired,Pastel1,Pastel2,Set1,Set2,Set3,Tableau10');
    addSchemesFromD3('sequential', 'Blues,Greens,Greys,Purples,Reds,Oranges,BuGn,BuPu,GnBu,OrRd,PuBuGn,PuBu,PuRd,RdPu,YlGnBu,YlGn,YlOrBr,YlOrRd');
    addSchemesFromD3('rainbow', 'Cividis,CubehelixDefault,Rainbow,Warm,Cool,Sinebow,Turbo,Viridis,Magma,Inferno,Plasma');
    addSchemesFromD3('diverging', 'BrBG,PRGn,PRGn,PiYG,PuOr,RdBu,RdGy,RdYlBu,RdYlGn,Spectral');
    testLib(); // make sure these schemes are all available
    addCategoricalScheme('Category20',
      '1f77b4aec7e8ff7f0effbb782ca02c98df8ad62728ff98969467bdc5b0d58c564bc49c94e377c2f7b6d27f7f7fc7c7c7bcbd22dbdb8d17becf9edae5');
    addCategoricalScheme('Category20b',
      '393b795254a36b6ecf9c9ede6379398ca252b5cf6bcedb9c8c6d31bd9e39e7ba52e7cb94843c39ad494ad6616be7969c7b4173a55194ce6dbdde9ed6');
    addCategoricalScheme('Category20c',
      '3182bd6baed69ecae1c6dbefe6550dfd8d3cfdae6bfdd0a231a35474c476a1d99bc7e9c0756bb19e9ac8bcbddcdadaeb636363969696bdbdbdd9d9d9');
    addCategoricalScheme('Tableau20',
      '4c78a89ecae9f58518ffbf7954a24b88d27ab79a20f2cf5b43989483bcb6e45756ff9d9879706ebab0acd67195fcbfd2b279a2d6a5c99e765fd8b5a5');
    index.all = [].concat(index.sequential, index.rainbow, index.diverging, index.categorical);

  }

  function standardName(name) {
    if (!name) return null;
    var lcname = name.toLowerCase();
    for (var i=0; i<index.all.length; i++) {
      if (index.all[i].toLowerCase() == lcname) {
        return index.all[i];
      }
    }
    return null;
  }

  function addSchemesFromD3(type, names) {
    index[type] = index[type].concat(names.split(','));
  }

  function addCategoricalScheme(name, str) {
    index.categorical.push(name);
    ramps[name] = unpackRamp(str);
  }

  function unpackRamp(str) {
    var colors = [];
    for (var i=0, n=str.length; i<n; i+=6) {
      colors.push('#' + str.substr(i, 6));
    }
    return colors;
  }

  function testLib() {
    schemes(index.categorical);
    schemes(index.sequential);
    schemes(index.diverging);
    interpolators(index.sequential);
    interpolators(index.rainbow);
    interpolators(index.diverging);

    function schemes(arr) {
      arr.forEach(function(name) {
        if (!d3Scales['scheme' + name]) {
          message('Warning: missing data for', name);
        }
      });
    }

    function interpolators(arr) {
      arr.forEach(function(name) {
        if (!d3Scales['interpolate' + name]) {
          message('Missing interpolator for', name);
        }
      });
    }
  }

  function printColorSchemeNames() {
    initSchemes();
    print('Built-in color schemes (from d3):');
    print ('Categorical\n' + formatStringsAsGrid(index.categorical));
    print ('\nSequential\n' + formatStringsAsGrid(index.sequential));
    print ('\nDiverging\n' + formatStringsAsGrid(index.diverging));
    print ('\nMulti-hue/rainbow\n' + formatStringsAsGrid(index.rainbow));
  }

  function pickRandomColorScheme(type) {
    initSchemes();
    var names = index[type];
    if (!names) error('Unknown color scheme type:', type);
    var i = Math.floor(Math.random() * names.length);
    return names[i];
  }

  function getRandomColors(n) {
    initSchemes();
    var colors = getCategoricalColorScheme('Tableau20', 20);
    utils.shuffle(colors);
    colors = wrapColors(colors, n);
    return colors.slice(0, n);
  }

  function getCategoricalColorScheme(name, n) {
    var colors;
    initSchemes();
    name = standardName(name);
    if (!isColorSchemeName(name)) {
      stop('Unknown color scheme name:', name);
    } else if (isCategoricalColorScheme(name)) {
      colors = ramps[name] || d3Scales['scheme' + name];
    } else {
      colors = getColorRamp(name, n);
    }
    if (n > colors.length) {
      // stop(name, 'does not contain', n, 'colors');
      message('Color scheme has', colors.length, 'colors. Using duplication to match', n, 'categories.');
      colors = wrapColors(colors, n);
    } else {
      colors = colors.slice(0, n);
    }
    return colors;
  }

  function wrapColors(colors, n) {
    while (colors.length > 0 && colors.length < n) {
      colors = colors.concat(colors.slice(0, n - colors.length));
    }
    return colors;
  }

  function isColorSchemeName(name) {
    initSchemes();
    return index.all.includes(standardName(name));
  }

  function isCategoricalColorScheme(name) {
    initSchemes();
    return index.categorical.includes(standardName(name));
  }

  function getColorRamp(name, n, stops) {
    initSchemes();
    name = standardName(name);
    var ramps = d3Scales['scheme' + name];
    var interpolate = d3Scales['interpolate' + name];
    var ramp;
    if (!ramps && !interpolate) {
      stop('Unknown color scheme name:', name);
    }
    if (index.categorical.includes(name)) {
      stop(name, ' is a categorical color scheme (expected a sequential color scheme)');
    }
    if (ramps && ramps[n]) {
      ramp = ramps[n];
    } else {
      ramp = getInterpolatedRamp(interpolate, n);
    }
    if (stops) {
      ramp = getStoppedValues(ramp, stops);
    }
    return ramp;
  }

  function getInterpolatedRamp(interpolate, n) {
    if (n > 0 === false || !utils.isInteger(n)) {
      error('Expected a positive integer');
    }
    var ramp = [];
    for (var i=0; i<n; i++) {
      ramp.push(interpolate(i / (n - 1)));
    }
    return ramp;
  }

  function getNullValue(opts) {
    var nullValue;
    if ('null_value' in opts) {
      nullValue = parseNullValue(opts.null_value);
    } else if (opts.colors) {
      nullValue = '#eee';
    } else if (opts.values) {
      nullValue = null;
    } else {
      nullValue = -1; // kludge, to match behavior of getClassValues()
    }
    return nullValue;
  }

  // Parse command line string arguments to the correct data type
  function parseNullValue(val) {
    if (utils.isString(val) && !isNaN(+val)) {
      val = +val;
    }
    if (val === 'null') {
      val = null;
    }
    return val;
  }

  function getClassValues(method, n, opts) {
    var categorical = method == 'categorical' || method == 'non-adjacent';
    var colorArg = opts.colors && opts.colors.length == 1 ? opts.colors[0] : null;
    var colorScheme;

    if (colorArg == 'random') {
      if (categorical) {
        return getRandomColors(n);
      }
      colorScheme = pickRandomColorScheme('sequential');
      message('Randomly selected color ramp:', colorScheme);
    } else if (isColorSchemeName(colorArg)) {
      colorScheme = colorArg;
    } else if (colorArg && !parseColor(colorArg)) {
      stop('Unrecognized color scheme name:', colorArg);
    } else if (opts.colors) {
      opts.colors.forEach(validateColor);
    }

    if (colorScheme) {
      if (categorical && isCategoricalColorScheme(colorScheme)) {
        return getCategoricalColorScheme(colorScheme, n);
      } else {
        return getColorRamp(colorScheme, n, opts.stops);
      }
    } else if (opts.colors || opts.values) {
      if (categorical) {
        return getCategoricalValues(opts.colors || opts.values, n);
      } else {
        return getInterpolableValues(opts.colors || opts.values, n, opts);
      }
    } else {
      // use numerical class indexes (0, 1, ...) if no values are given
      return getIndexes(n);
    }
  }

  function getCategoricalValues(values, n) {
    if (n != values.length) {
      stop('Mismatch in number of categories and number of values');
    }
    return values;
  }

  function getIndexes(n) {
    var vals = [];
    for (var i=0; i<n; i++) {
      vals.push(i);
    }
    return vals;
  }

  // TODO: check for non-interpolatable value types (e.g. boolean, text)
  function getInterpolableValues(arr, n, opts) {
    var values = parseValues(arr);
    if (n != values.length || opts.stops) {
      return interpolateValuesToClasses(values, n, opts.stops);
    }
    return values;
  }

  // convert strings to numbers if they all parse as numbers
  // arr: an array of strings
  function parseValues(strings) {
    var values = strings;
    if (strings.every(utils.parseNumber)) {
      values = strings.map(function(str) {
        return +str;
      });
    }
    return values;
  }

  var sequential = ['quantile', 'nice', 'equal-interval', 'hybrid', 'breaks'];
  var all = ['non-adjacent', 'indexed', 'categorical'].concat(sequential);

  function getClassifyMethod(opts, dataType) {
    var method;
    if (opts.method) {
      method = opts.method;
    } else if (opts.breaks) {
      method = 'breaks';
    } else if (opts.index_field) {
      method = 'indexed';
    } else if (opts.categories || dataType == 'string') {
      method = 'categorical';
    } else  if (dataType == 'number') {
      method = 'quantile'; // TODO: validate data field
    } else if (dataType == 'date' || dataType == 'object') {
      stop('Data type does not support classification:', dataType);
    } else if (dataType === null) {
      // data field is empty
      return null; // kludge
    } else if (dataType === undefined) {
      // no data field was given
      stop('Expected a data field to classify or the non-adjacent option');
    } else {
      stop('Unable to determine which classification method to use.');
    }
    if (!all.includes(method)) {
      stop('Not a recognized classification method:', method);
    }
    if (sequential.includes(method) && dataType != 'number' && dataType !== null) {
      stop('The', method, 'method requires a numerical data field');
    }
    return method;
  }

  cmd.classify = function(lyr, dataset, optsArg) {
    if (!lyr.data) {
      initDataTable(lyr);
    }
    var opts = optsArg || {};
    var records = lyr.data && lyr.data.getRecords();
    var valuesAreColors = !!opts.colors;
    var dataField, fieldType, outputField;
    var values, nullValue;
    var classifyByValue, classifyByRecordId;
    var numClasses, numValues;
    var method;

    if (opts.color_scheme) {
      stop('color-scheme is not a valid option, use colors instead');
    }

    // get data field to use for classification
    //
    if (opts.index_field) {
      dataField = opts.index_field;
      fieldType = getColumnType(opts.field, records);
   } else if (opts.field) {
      dataField = opts.field;
      fieldType = getColumnType(opts.field, records);
    }
    if (dataField) {
      requireDataField(lyr.data, dataField);
    }

    // get classification method
    //
    method = getClassifyMethod(opts, fieldType);

    // validate classification method
    if (method == 'non-adjacent') {
      if (lyr.geometry_type != 'polygon') {
        stop('The non-adjacent option requires a polygon layer');
      }
      if (dataField) {
        stop('The non-adjacent option does not accept a data field argument');
      }
    } else if (!dataField) {
      stop('Missing a data field to classify');
    }


    // get the number of classes and the number of values
    //
    // expand categories if value is '*'
    // use all unique values if categories option is missing
    if (method == 'categorical') {
      if ((!opts.categories || opts.categories.includes('*')) && dataField) {
        opts.categories = getUniqFieldValues(records, dataField);
      }
    }

    if (opts.classes) {
      if (!utils.isInteger(opts.classes) || opts.classes > 1 === false) {
        stop('Invalid number of classes:', opts.classes, '(expected a value greater than 1)');
      }
      numClasses = opts.classes;
    } else if (method == 'indexed' && dataField) {
      numClasses = getIndexedClassCount(records, dataField);
    } else if (opts.breaks) {
      numClasses = opts.breaks.length + 1;
    } else if (method == 'categorical' && opts.categories) {
      numClasses = opts.categories.length;
    } else if (opts.colors && opts.colors.length > 1) {
      numClasses = opts.colors.length;
    } else if (opts.values && opts.values.length > 1) {
      numClasses = opts.values.length;
    } else if (method == 'non-adjacent') {
      numClasses = 5;
    } else {
      numClasses = 4;
    }
    numValues = opts.continuous ? numClasses + 1 : numClasses;
    if (numValues > 1 === false) {
      stop('Missing a valid number of values');
    }

    // get colors or other values
    //
    values = getClassValues(method, numValues, opts);
    if (opts.invert) {
      values = values.concat().reverse();
    }
    if (valuesAreColors) {
      message('Colors:', formatValuesForLogging(values));
    }

    nullValue = getNullValue(opts);

    // get a function to convert input data to class indexes
    //
    if (fieldType === null) {
      // no valid data -- always return null value
      classifyByRecordId = function() {return nullValue;};
    } else if (method == 'non-adjacent') {
      classifyByRecordId = getNonAdjacentClassifier(lyr, dataset, values);
    } else if (method == 'indexed') {
      // data is pre-classified... just read the index from a field
      classifyByValue = getIndexedClassifier(values, nullValue, opts);
    } else if (method == 'categorical') {
      classifyByValue = getCategoricalClassifier(values, nullValue, opts);
    } else {
      classifyByValue = getSequentialClassifier$1(values, nullValue, getFieldValues(records, dataField), method, opts);
    }

    if (classifyByValue) {
      classifyByRecordId = function(id) {
        var d = records[id] || {};
        return classifyByValue(d[dataField]);
      };
    }

    // get the name of the output field
    //
    if (valuesAreColors) {
      outputField = lyr.geometry_type == 'polyline' ? 'stroke' : 'fill';
    } else {
      outputField = 'class';
    }
    if (opts.save_as) {
      outputField = opts.save_as; // override the default field name
    } else {
      message(`Output was saved to "${outputField}" field (use save-as= to change)`);
      // message('Use save-as=<field> to save to a different field');
    }

    records.forEach(function(d, i) {
      d[outputField] = classifyByRecordId(i);
    });
  };

  function formatValuesForLogging(arr) {
    if (arr.some(val => utils.isString(val) && val.indexOf('rgb(') === 0)) {
      return formatColorsAsHex(arr);
    }
    return arr;
  }

  function formatColorsAsHex(colors) {
    return colors.map(function(col) {
      var o = color(col);
      if (!o) stop('Unable to parse color:', col);
      return o.formatHex();
    });
  }

  // Remove small-area polygon rings (very simple implementation of sliver removal)
  // TODO: more sophisticated sliver detection (e.g. could consider ratio of area to perimeter)
  // TODO: consider merging slivers into adjacent polygons to prevent gaps from forming
  // TODO: consider separate gap removal function as an alternative to merging slivers
  //
  cmd.filterSlivers = function(lyr, dataset, opts) {
    if (lyr.geometry_type != 'polygon') {
      return 0;
    }
    return filterSlivers(lyr, dataset, opts);
  };

  function filterSlivers(lyr, dataset, optsArg) {
    var opts = utils.extend({sliver_control: 1}, optsArg);
    var filterData = getSliverFilter(lyr, dataset, opts);
    var ringTest = filterData.filter;
    var removed = 0;
    var pathFilter = function(path, i, paths) {
      if (ringTest(path)) {
        removed++;
        return null;
      }
    };

    editShapes(lyr.shapes, pathFilter);
    message(utils.format("Removed %'d sliver%s using %s", removed, utils.pluralSuffix(removed), filterData.label));
    return removed;
  }

  function filterClipSlivers(lyr, clipLyr, arcs) {
    var threshold = getDefaultSliverThreshold(lyr, arcs);
    // message('Using variable sliver threshold (based on ' + (threshold / 1e6) + ' sqkm)');
    var ringTest = getSliverTest(arcs, threshold, 1);
    var flags = new Uint8Array(arcs.size());
    var removed = 0;
    var pathFilter = function(path) {
      var prevArcs = 0,
          newArcs = 0;
      for (var i=0, n=path && path.length || 0; i<n; i++) {
        if (flags[absArcId(path[i])] > 0) {
          newArcs++;
        } else {
          prevArcs++;
        }
      }
      // filter paths that contain arcs from both original and clip/erase layers
      //   and are small
      if (newArcs > 0 && prevArcs > 0 && ringTest(path)) {
        removed++;
        return null;
      }
    };

    countArcsInShapes(clipLyr.shapes, flags);
    editShapes(lyr.shapes, pathFilter);
    return removed;
  }

  // Assumes: Arcs have been divided
  //
  function clipPolylines(targetShapes, clipShapes, nodes, type) {
    var index = new PathIndex(clipShapes, nodes.arcs);

    return targetShapes.map(function(shp) {
      return clipPolyline(shp);
    });

    function clipPolyline(shp) {
      var clipped = null;
      if (shp) clipped = shp.reduce(clipPath, []);
      return clipped && clipped.length > 0 ? clipped : null;
    }

    function clipPath(memo, path) {
      var clippedPath = null,
          arcId, enclosed;
      for (var i=0; i<path.length; i++) {
        arcId = path[i];
        enclosed = index.arcIsEnclosed(arcId);
        if (enclosed && type == 'clip' || !enclosed && type == 'erase') {
          if (!clippedPath) {
            memo.push(clippedPath = []);
          }
          clippedPath.push(arcId);
        } else {
          clippedPath = null;
        }
      }
      return memo;
    }
  }

  var PolylineClipping = /*#__PURE__*/Object.freeze({
    __proto__: null,
    clipPolylines: clipPolylines
  });

  // TODO: to prevent invalid holes,
  // could erase the holes from the space-enclosing rings.
  function appendHolesToRings(cw, ccw) {
    for (var i=0, n=ccw.length; i<n; i++) {
      cw.push(ccw[i]);
    }
    return cw;
  }

  function getPolygonDissolver(nodes, spherical) {
    spherical = spherical && !nodes.arcs.isPlanar();
    var flags = new Uint8Array(nodes.arcs.size());
    var divide = getHoleDivider(nodes, spherical);
    var pathfind = getRingIntersector(nodes, flags);

    return function(shp) {
      if (!shp) return null;
      var cw = [],
          ccw = [];

      divide(shp, cw, ccw);
      cw = pathfind(cw, 'flatten');
      ccw.forEach(reversePath);
      ccw = pathfind(ccw, 'flatten');
      ccw.forEach(reversePath);
      var shp2 = appendHolesToRings(cw, ccw);
      var dissolved = pathfind(shp2, 'dissolve');

      if (dissolved.length > 1) {
        dissolved = fixNestingErrors(dissolved, nodes.arcs);
      }

      return dissolved.length > 0 ? dissolved : null;
    };
  }

  // TODO: remove dependency on old polygon dissolve function

  // assumes layers and arcs have been prepared for clipping
  function clipPolygons(targetShapes, clipShapes, nodes, type, optsArg) {
    var arcs = nodes.arcs;
    var opts = optsArg || {};
    var clipFlags = new Uint8Array(arcs.size());
    var routeFlags = new Uint8Array(arcs.size());
    var clipArcTouches = 0;
    var clipArcUses = 0;
    var usedClipArcs = [];
    var dividePath = getPathFinder(nodes, useRoute, routeIsActive);
    var dissolvePolygon = getPolygonDissolver(nodes);

    // The following cleanup step is a performance bottleneck (it often takes longer than
    // other clipping operations) and is usually not needed. Furthermore, it only
    // eliminates a few kinds of problems, like target polygons with abnormal winding
    // or overlapping rings. TODO: try to optimize or remove it for all cases

    // skipping shape cleanup when using the experimental fast bbox clipping option
    if (!opts.bbox2) {
      // clean each target polygon by dissolving its rings
      targetShapes = targetShapes.map(dissolvePolygon);
    }

    // Originally, clip shapes were dissolved here as an optimization, using
    // an unreliable dissolve function.
    // Now, clip shapes are dissolved using a more reliable (but slower)
    // function in mapshaper-clip-erase.js
    // clipShapes = [dissolvePolygon(internal.concatShapes(clipShapes))];

    // Open pathways in the clip/erase layer
    // Need to expose clip/erase routes in both directions by setting route
    // in both directions to visible -- this is how cut-out shapes are detected
    // Or-ing with 0x11 makes both directions visible (so reverse paths will block)
    openArcRoutes(clipShapes, arcs, clipFlags, type == 'clip', type == 'erase', !!"dissolve", 0x11);
    var index = new PathIndex(clipShapes, arcs);
    var clippedShapes = targetShapes.map(function(shape, i) {
      if (shape) {
        return clipPolygon(shape, type, index);
      }
      return null;
    });

    // add clip/erase polygons that are fully contained in a target polygon
    // need to index only non-intersecting clip shapes
    // (Intersecting shapes have one or more arcs that have been scanned)

    // first, find shapes that do not intersect the target layer
    // (these could be inside or outside the target polygons)
    var undividedClipShapes = findUndividedClipShapes(clipShapes);

    closeArcRoutes(clipShapes, arcs, routeFlags, true, true); // not needed?
    index = new PathIndex(undividedClipShapes, arcs);
    targetShapes.forEach(function(shape, shapeId) {
      // find clipping paths that are internal to this target polygon
      var paths = shape ? findInteriorPaths(shape, type, index) : null;
      if (paths) {
        clippedShapes[shapeId] = (clippedShapes[shapeId] || []).concat(paths);
      }
    });

    return clippedShapes;

    function clipPolygon(shape, type, index) {
      var dividedShape = [],
          clipping = type == 'clip',
          erasing = type == 'erase';

      // open pathways for entire polygon rather than one ring at a time --
      // need to create polygons that connect positive-space rings and holes
      openArcRoutes(shape, arcs, routeFlags, true, false, false);

      forEachShapePart(shape, function(ids) {
        var path;
        for (var i=0, n=ids.length; i<n; i++) {
          clipArcTouches = 0;
          clipArcUses = 0;
          path = dividePath(ids[i]);
          if (path) {
            // if ring doesn't touch/intersect a clip/erase polygon, check if it is contained
            // if (clipArcTouches === 0) {
            // if ring doesn't incorporate an arc from the clip/erase polygon,
            // check if it is contained (assumes clip shapes are dissolved)
            if (clipArcTouches === 0 || clipArcUses === 0) { //
              var contained = index.pathIsEnclosed(path);
              if (clipping && contained || erasing && !contained) {
                dividedShape.push(path);
              }
              // TODO: Consider breaking if polygon is unchanged
            } else {
              dividedShape.push(path);
            }
          }
        }
      });

      // Clear pathways of current target shape to hidden/closed
      closeArcRoutes(shape, arcs, routeFlags, true, true, true);
      // Also clear pathways of any clip arcs that were used
      if (usedClipArcs.length > 0) {
        closeArcRoutes(usedClipArcs, arcs, routeFlags, true, true, true);
        usedClipArcs = [];
      }

      return dividedShape.length === 0 ? null : dividedShape;
    }

    function routeIsActive(id) {
      var fw = id >= 0,
          abs = fw ? id : ~id,
          visibleBit = fw ? 1 : 0x10,
          targetBits = routeFlags[abs],
          clipBits = clipFlags[abs];

      if (clipBits > 0) clipArcTouches++;
      return (targetBits & visibleBit) > 0 || (clipBits & visibleBit) > 0;
    }

    function useRoute(id) {
      var fw = id >= 0,
          abs = fw ? id : ~id,
          targetBits = routeFlags[abs],
          clipBits = clipFlags[abs],
          targetRoute, clipRoute;

      if (fw) {
        targetRoute = targetBits;
        clipRoute = clipBits;
      } else {
        targetRoute = targetBits >> 4;
        clipRoute = clipBits >> 4;
      }
      targetRoute &= 3;
      clipRoute &= 3;

      var usable = false;
      // var usable = targetRoute === 3 || targetRoute === 0 && clipRoute == 3;
      if (targetRoute == 3) {
        // special cases where clip route and target route both follow this arc
        if (clipRoute == 1) ; else if (clipRoute == 2 && type == 'erase') ; else {
          usable = true;
        }

      } else if (targetRoute === 0 && clipRoute == 3) {
        usedClipArcs.push(id);
        usable = true;
      }

      if (usable) {
        if (clipRoute == 3) {
          clipArcUses++;
        }
        // Need to close all arcs after visiting them -- or could cause a cycle
        //   on layers with strange topology
        if (fw) {
          targetBits = setBits(targetBits, 1, 3);
        } else {
          targetBits = setBits(targetBits, 0x10, 0x30);
        }
      }

      targetBits |= fw ? 4 : 0x40; // record as visited
      routeFlags[abs] = targetBits;
      return usable;
    }

    // Filter a collection of shapes to exclude paths that contain clip/erase arcs
    // and paths that are hidden (e.g. internal boundaries)
    function findUndividedClipShapes(clipShapes) {
      return clipShapes.map(function(shape) {
        var usableParts = [];
        forEachShapePart(shape, function(ids) {
          var pathIsClean = true,
              pathIsVisible = false;
          for (var i=0; i<ids.length; i++) {
            // check if arc was used in fw or rev direction
            if (!arcIsUnused(ids[i], routeFlags)) {
              pathIsClean = false;
              break;
            }
            // check if clip arc is visible
            if (!pathIsVisible && arcIsVisible(ids[i], clipFlags)) {
              pathIsVisible = true;
            }
          }
          if (pathIsClean && pathIsVisible) usableParts.push(ids);
        });
        return usableParts.length > 0 ? usableParts : null;
      });
    }

    // Test if arc is unused in both directions
    // (not testing open/closed or visible/hidden)
    function arcIsUnused(id, flags) {
      var abs = absArcId(id),
          flag = flags[abs];
          return (flag & 0x44) === 0;
    }

    function arcIsVisible(id, flags) {
      var flag = flags[absArcId(id)];
      return (flag & 0x11) > 0;
    }

    // search for indexed clipping paths contained in a shape
    // dissolve them if needed
    function findInteriorPaths(shape, type, index) {
      var enclosedPaths = index.findPathsInsideShape(shape),
          dissolvedPaths = [];
      if (!enclosedPaths) return null;
      // ...
      if (type == 'erase') enclosedPaths.forEach(reversePath);
      if (enclosedPaths.length <= 1) {
        dissolvedPaths = enclosedPaths; // no need to dissolve single-part paths
      } else {
        openArcRoutes(enclosedPaths, arcs, routeFlags, true, false, true);
        enclosedPaths.forEach(function(ids) {
          var path;
          for (var j=0; j<ids.length; j++) {
            path = dividePath(ids[j]);
            if (path) {
              dissolvedPaths.push(path);
            }
          }
        });
      }

      return dissolvedPaths.length > 0 ? dissolvedPaths : null;
    }
  } // end clipPolygons()

  //
  function clipPoints(points, clipShapes, arcs, type) {
    var index = new PathIndex(clipShapes, arcs);

    var points2 = points.reduce(function(memo, feat) {
      var n = feat ? feat.length : 0,
          feat2 = [],
          enclosed;

      for (var i=0; i<n; i++) {
        enclosed = index.findEnclosingShape(feat[i]) > -1;
        if (type == 'clip' && enclosed || type == 'erase' && !enclosed) {
          feat2.push(feat[i].concat());
        }
      }

      memo.push(feat2.length > 0 ? feat2 : null);
      return memo;
    }, []);

    return points2;
  }

  var ClipPoints = /*#__PURE__*/Object.freeze({
    __proto__: null,
    clipPoints: clipPoints
  });

  // Create a merged dataset by appending the overlay layer to the target dataset
  // so it is last in the layers array.
  // DOES NOT insert clipping points
  function mergeLayersForOverlay(targetLayers, targetDataset, clipSrc, opts) {
    utils.some(targetLayers, layerHasPaths);
    var bbox = opts.bbox || opts.bbox2;
    var mergedDataset, clipDataset, clipLyr;
    if (clipSrc && clipSrc.geometry_type) {
      // TODO: update tests to remove this case (clipSrc is a layer)
      clipSrc = {dataset: targetDataset, layer: clipSrc, disposable: true};
    }
    if (bbox) {
      clipDataset = convertClipBounds(bbox);
      clipLyr = clipDataset.layers[0];
    } else if (!clipSrc) {
      stop("Command requires a source file, layer id or bbox");
    } else if (clipSrc.layer && clipSrc.dataset) {
      clipLyr = clipSrc.layer;
      clipDataset = utils.defaults({layers: [clipLyr]}, clipSrc.dataset);
    } else if (clipSrc.layers && clipSrc.layers.length == 1) {
      clipLyr = clipSrc.layers[0];
      clipDataset = clipSrc;
    }
    if (targetDataset.arcs != clipDataset.arcs) {
      // using external dataset -- need to merge arcs
      if (clipSrc && !clipSrc.disposable) {
        // copy overlay layer shapes because arc ids will be reindexed during merging
        clipDataset.layers[0] = copyLayerShapes(clipDataset.layers[0]);
      }
      // merge external dataset with target dataset,
      // so arcs are shared between target layers and clipping lyr
      // Assumes that layers in clipDataset can be modified (if necessary, a copy should be passed in)
      mergedDataset = mergeDatasets([targetDataset, clipDataset]);
      buildTopology(mergedDataset); // identify any shared arcs between clipping layer and target dataset
    } else {
      // overlay layer belongs to the same dataset as target layers... move it to the end
      mergedDataset = utils.extend({}, targetDataset);
      mergedDataset.layers = targetDataset.layers.filter(function(lyr) {return lyr != clipLyr;});
      mergedDataset.layers.push(clipLyr);
    }
    return mergedDataset;
  }

  function convertClipBounds(bb) {
    var x0 = bb[0], y0 = bb[1], x1 = bb[2], y1 = bb[3],
        arc = [[x0, y0], [x0, y1], [x1, y1], [x1, y0], [x0, y0]];

    if (!(y1 > y0 && x1 > x0)) {
      stop("Invalid bbox (should be [xmin, ymin, xmax, ymax]):", bb);
    }
    return {
      arcs: new ArcCollection([arc]),
      layers: [{
        shapes: [[[0]]],
        geometry_type: 'polygon'
      }]
    };
  }

  var OverlayUtils = /*#__PURE__*/Object.freeze({
    __proto__: null,
    mergeLayersForOverlay: mergeLayersForOverlay
  });

  // Insert cutting points in arcs, where bbox intersects other shapes
  // Return a polygon layer containing the bounding box vectors, divided at cutting points.
  function divideDatasetByBBox(dataset, bbox) {
    var arcs = dataset.arcs;
    var data = findBBoxCutPoints(arcs, bbox);
    var map = insertCutPoints(data.cutPoints, arcs);
    arcs.dedupCoords();
    remapDividedArcs(dataset, map);
    // merge bbox dataset with target dataset,
    // so arcs are shared between target layers and bbox layer
    var clipDataset = bboxPointsToClipDataset(data.bboxPoints);
    var mergedDataset = mergeDatasets([dataset, clipDataset]);
    // TODO: detect if we need to rebuild topology (unlikely), like with the full clip command
    // buildTopology(mergedDataset);
    var clipLyr = mergedDataset.layers.pop();
    dataset.arcs = mergedDataset.arcs;
    dataset.layers = mergedDataset.layers;
    return clipLyr;
  }

  function bboxPointsToClipDataset(arr) {
    var arcs = [];
    var shape = [];
    var layer = {geometry_type: 'polygon', shapes: [[shape]]};
    var p1, p2;
    for (var i=0, n=arr.length - 1; i<n; i++) {
      p1 = arr[i];
      p2 = arr[i+1];
      arcs.push([[p1.x, p1.y], [p2.x, p2.y]]);
      shape.push(i);
    }
    return {
      arcs: new ArcCollection(arcs),
      layers: [layer]
    };
  }

  function findBBoxCutPoints(arcs, bbox) {
    var left = bbox[0],
        bottom = bbox[1],
        right = bbox[2],
        top = bbox[3];

    // arrays of intersection points along each bbox edge
    var tt = [],
        rr = [],
        bb = [],
        ll = [];

    arcs.forEachSegment(function(i, j, xx, yy) {
      var ax = xx[i],
          ay = yy[i],
          bx = xx[j],
          by = yy[j];
      var hit;
      if (segmentOutsideBBox(ax, ay, bx, by, left, bottom, right, top)) return;
      if (segmentInsideBBox(ax, ay, bx, by, left, bottom, right, top)) return;

      hit = geom.segmentIntersection(left, top, right, top, ax, ay, bx, by);
      if (hit) addHit(tt, hit, i, j, xx, yy);

      hit = geom.segmentIntersection(left, bottom, right, bottom, ax, ay, bx, by);
      if (hit) addHit(bb, hit, i, j, xx, yy);

      hit = geom.segmentIntersection(left, bottom, left, top, ax, ay, bx, by);
      if (hit) addHit(ll, hit, i, j, xx, yy);

      hit = geom.segmentIntersection(right, bottom, right, top, ax, ay, bx, by);
      if (hit) addHit(rr, hit, i, j, xx, yy);
    });

    return {
      cutPoints: ll.concat(bb, rr, tt),
      bboxPoints: getDividedBBoxPoints(bbox, ll, tt, rr, bb)
    };

    function addHit(arr, hit, i, j, xx, yy) {
      if (!hit) return;
      arr.push(formatHit(hit[0], hit[1], i, j, xx, yy));
      if (hit.length == 4) {
        arr.push(formatHit(hit[2], hit[3], i, j, xx, yy));
      }
    }

    function formatHit(x, y, i, j, xx, yy) {
      var ids = formatIntersectingSegment(x, y, i, j, xx, yy);
      return getCutPoint(x, y, ids[0], ids[1]);
    }
  }

  function segmentOutsideBBox(ax, ay, bx, by, xmin, ymin, xmax, ymax) {
    return ax < xmin && bx < xmin || ax > xmax && bx > xmax ||
        ay < ymin && by < ymin || ay > ymax && by > ymax;
  }

  function segmentInsideBBox(ax, ay, bx, by, xmin, ymin, xmax, ymax) {
    return ax > xmin && bx > xmin && ax < xmax && bx < xmax &&
        ay > ymin && by > ymin && ay < ymax && by < ymax;
  }

  // Returns an array of points representing the vertices in
  // the bbox with cutting points inserted.
  function getDividedBBoxPoints(bbox, ll, tt, rr, bb) {
    var bl = {x: bbox[0], y: bbox[1]},
        tl = {x: bbox[0], y: bbox[3]},
        tr = {x: bbox[2], y: bbox[3]},
        br = {x: bbox[2], y: bbox[1]};
    ll = utils.sortOn(ll.concat([bl, tl]), 'y', true);
    tt = utils.sortOn(tt.concat([tl, tr]), 'x', true);
    rr = utils.sortOn(rr.concat([tr, br]), 'y', false);
    bb = utils.sortOn(bb.concat([br, bl]), 'x', false);
    return ll.concat(tt, rr, bb).reduce(function(memo, p2) {
      var p1 = memo.length > 0 ? memo[memo.length-1] : null;
      if (p1 === null || p1.x != p2.x || p1.y != p2.y) memo.push(p2);
      return memo;
    }, []);
  }

  var Bbox2Clipping = /*#__PURE__*/Object.freeze({
    __proto__: null,
    divideDatasetByBBox: divideDatasetByBBox,
    segmentOutsideBBox: segmentOutsideBBox,
    segmentInsideBBox: segmentInsideBBox
  });

  cmd.clipLayers = function(target, src, dataset, opts) {
    return clipLayers(target, src, dataset, "clip", opts);
  };

  cmd.eraseLayers = function(target, src, dataset, opts) {
    return clipLayers(target, src, dataset, "erase", opts);
  };

  cmd.clipLayer = function(targetLyr, src, dataset, opts) {
    return cmd.clipLayers([targetLyr], src, dataset, opts)[0];
  };

  cmd.eraseLayer = function(targetLyr, src, dataset, opts) {
    return cmd.eraseLayers([targetLyr], src, dataset, opts)[0];
  };

  cmd.sliceLayers = function(target, src, dataset, opts) {
    return clipLayers(target, src, dataset, "slice", opts);
  };

  cmd.sliceLayer = function(targetLyr, src, dataset, opts) {
    return cmd.sliceLayers([targetLyr], src, dataset, opts);
  };

  function clipLayersInPlace(layers, clipSrc, dataset, type, opts) {
    var outputLayers = clipLayers(layers, clipSrc, dataset, type, opts);
    // remove arcs from the clipping dataset, if they are not used by any layer
    layers.forEach(function(lyr, i) {
      var lyr2 = outputLayers[i];
      lyr.shapes = lyr2.shapes;
      lyr.data = lyr2.data;
    });
    dissolveArcs(dataset);
  }

  // @clipSrc: layer in @dataset or filename
  // @type: 'clip' or 'erase'
  function clipLayers(targetLayers, clipSrc, targetDataset, type, opts) {
    var usingPathClip = utils.some(targetLayers, layerHasPaths);
    var mergedDataset, clipLyr, nodes;
    opts = opts || {no_cleanup: true}; // TODO: update testing functions
    if (opts.bbox2 && usingPathClip) { // assumes target dataset has arcs
      return clipLayersByBBox(targetLayers, targetDataset, opts);
    }
    mergedDataset = mergeLayersForOverlay(targetLayers, targetDataset, clipSrc, opts);
    clipLyr = mergedDataset.layers[mergedDataset.layers.length-1];
    if (usingPathClip) {
      // add vertices at all line intersections
      // (generally slower than actual clipping)
      nodes = addIntersectionCuts(mergedDataset, opts);
      targetDataset.arcs = mergedDataset.arcs;
      // dissolve clip layer shapes (to remove overlaps and other topological issues
      // that might confuse the clipping function)
      // use a data-free copy of the clip lyr, so data records are not dissolved
      // (this avoids triggering an unnecessary and expensive DBF read operation in some cases).
      clipLyr = utils.defaults({data: null}, clipLyr);
      clipLyr = dissolvePolygonLayer2(clipLyr, mergedDataset, {quiet: true, silent: true});

    } else {
      nodes = new NodeCollection(mergedDataset.arcs);
    }
    // clipLyr = mergedDataset.layers.pop();
    return clipLayersByLayer(targetLayers, clipLyr, nodes, type, opts);
  }

  function clipLayersByBBox(layers, dataset, opts) {
    var bbox = opts.bbox2;
    var clipLyr = divideDatasetByBBox(dataset, bbox);
    var nodes = new NodeCollection(dataset.arcs);
    var retn = clipLayersByLayer(layers, clipLyr, nodes, 'clip', opts);
    return retn;
  }

  function clipLayersByLayer(targetLayers, clipLyr, nodes, type, opts) {
    requirePolygonLayer(clipLyr, "Requires a polygon clipping layer");
    return targetLayers.reduce(function(memo, targetLyr) {
      if (type == 'slice') {
        memo = memo.concat(sliceLayerByLayer(targetLyr, clipLyr, nodes, opts));
      } else {
        memo.push(clipLayerByLayer(targetLyr, clipLyr, nodes, type, opts));
      }
      return memo;
    }, []);
  }

  function getSliceLayerName(clipLyr, field, i) {
    var id = field ? clipLyr.data.getRecords()[0][field] : i + 1;
    return 'slice-' + id;
  }

  function sliceLayerByLayer(targetLyr, clipLyr, nodes, opts) {
    // may not need no_replace
    var clipLayers = cmd.splitLayer(clipLyr, opts.id_field, {no_replace: true});
    return clipLayers.map(function(clipLyr, i) {
      var outputLyr = clipLayerByLayer(targetLyr, clipLyr, nodes, 'clip', opts);
      outputLyr.name = getSliceLayerName(clipLyr, opts.id_field, i);
      return outputLyr;
    });
  }

  function clipLayerByLayer(targetLyr, clipLyr, nodes, type, opts) {
    var arcs = nodes.arcs;
    var shapeCount = targetLyr.shapes ? targetLyr.shapes.length : 0;
    var nullCount = 0, sliverCount = 0;
    var clippedShapes, outputLyr;
    if (shapeCount === 0) {
      return targetLyr; // ignore empty layer
    }
    if (targetLyr === clipLyr) {
      stop('Can\'t clip a layer with itself');
    }

    // TODO: optimize some of these functions for bbox clipping
    if (targetLyr.geometry_type == 'point') {
      clippedShapes = clipPoints(targetLyr.shapes, clipLyr.shapes, arcs, type);
    } else if (targetLyr.geometry_type == 'polygon') {
      clippedShapes = clipPolygons(targetLyr.shapes, clipLyr.shapes, nodes, type, opts);
    } else if (targetLyr.geometry_type == 'polyline') {
      clippedShapes = clipPolylines(targetLyr.shapes, clipLyr.shapes, nodes, type);
    } else {
      stop('Invalid target layer:', targetLyr.name);
    }

    outputLyr = {
      name: targetLyr.name,
      geometry_type: targetLyr.geometry_type,
      shapes: clippedShapes,
      data: targetLyr.data // replaced post-filter
    };

    // Remove sliver polygons
    if (opts.remove_slivers && outputLyr.geometry_type == 'polygon') {
      sliverCount = filterClipSlivers(outputLyr, clipLyr, arcs);
    }

    // Remove null shapes (likely removed by clipping/erasing, although possibly already present)
    cmd.filterFeatures(outputLyr, arcs, {remove_empty: true, verbose: false});

    // clone data records (to avoid sharing records between layers)
    // TODO: this is not needed when replacing target with a single layer
    if (outputLyr.data) {
      outputLyr.data = outputLyr.data.clone();
    }

    // TODO: redo messages, now that many layers may be clipped
    nullCount = shapeCount - outputLyr.shapes.length;
    if (nullCount && sliverCount) {
      message(getClipMessage(nullCount, sliverCount));
    }
    return outputLyr;
  }

  function getClipMessage(nullCount, sliverCount) {
    var nullMsg = nullCount ? utils.format('%,d null feature%s', nullCount, utils.pluralSuffix(nullCount)) : '';
    var sliverMsg = sliverCount ? utils.format('%,d sliver%s', sliverCount, utils.pluralSuffix(sliverCount)) : '';
    if (nullMsg || sliverMsg) {
      return utils.format('Removed %s%s%s', nullMsg, (nullMsg && sliverMsg ? ' and ' : ''), sliverMsg);
    }
    return '';
  }

  var ClipErase = /*#__PURE__*/Object.freeze({
    __proto__: null,
    clipLayersInPlace: clipLayersInPlace,
    clipLayers: clipLayers,
    clipLayersByBBox: clipLayersByBBox,
    clipLayersByLayer: clipLayersByLayer,
    getClipMessage: getClipMessage
  });

  // Assign a cluster id to each polygon in a dataset, which can be used with
  //   one of the dissolve commands to dissolve the clusters
  // Works by iteratively grouping pairs of polygons with the smallest distance
  //   between centroids.
  // Results are not optimal -- may be useful for creating levels of detail on
  //   interactive maps, not useful for analysis.
  //
  cmd.cluster = function(lyr, arcs, opts) {
    requirePolygonLayer(lyr);
    var groups = calcPolygonClusters(lyr, arcs, opts);
    var idField = opts.id_field || "cluster";
    insertFieldValues(lyr, idField, groups);
    return lyr;
  };

  function calcPolygonClusters(lyr, arcs, opts) {
    var calcScore = getPolygonClusterCalculator(opts);
    var size = lyr.shapes.length;
    var pct = opts.pct ? utils.parsePercent(opts.pct) : 1;
    var count = Math.round(size * pct);
    var groupField = opts.group_by || null;

    // working set of polygon records
    var shapeItems = lyr.shapes.map(function(shp, i) {
      var groupId = groupField && lyr.data.getRecordAt(i)[groupField] || null;
      return {
        ids: [i],
        area: geom.getShapeArea(shp, arcs),
        bounds: arcs.getMultiShapeBounds(shp),
        centroid: geom.getShapeCentroid(shp, arcs), // centroid of largest ring
        group: groupId,
        friends: []
      };
    });

    var mergeItems = []; // list of pairs of shapes that can be merged
    var mergeIndex = {}; // keep track of merges, to prevent duplicates
    var next;

    if (groupField && !lyr.data) stop("Missing attribute data table");

    // Populate mergeItems array
    findPairsOfNeighbors(lyr.shapes, arcs).forEach(function(ab, i) {
      // ab: [a, b] indexes of two polygons
      var a = shapeItems[ab[0]],
          b = shapeItems[ab[1]],
          item, id;
      if (a.group !== b.group) return;
      item = {ids: ab};
      item.score = getScore(item);
      if (item.score < 0) return;
      id = mergeItems.length;
      a.friends.push(id);
      b.friends.push(id);
      mergeItems.push(item);
    });

    // main loop
    while (count-- > 0 && (next = nextItem())) {
      merge(next);
    }

    // Assign a sequential id to each of the remaining original shapes and the
    // new aggregated shapes
    return shapeItems.filter(Boolean).reduce(function(memo, shape, clusterId) {
      var ids = shape.ids;
      for (var i=0; i<ids.length; i++) {
        memo[ids[i]] = clusterId;
      }
      return memo;
    }, []);

    function merge(item) {
      var merged = mergeShapes(item.ids);
      var mergedId = shapeItems.length;
      shapeItems[mergedId] = merged;
      updateList(merged.friends, item.ids, mergedId);
    }

    // Find lowest-ranked merge candidate and remove it from the list
    // Scans entire list - n^2 performance - tested ~20sec for 50,000 polygons
    function nextItem() {
      var minId = -1,
          min = Infinity,
          item, i, n;
      for (i=0, n=mergeItems.length; i<n; i++) {
        item = mergeItems[i];
        if (item !== null && item.score < min) {
          min = item.score;
          minId = i;
        }
      }
      if (minId == -1) return null;
      item = mergeItems[minId];
      mergeItems[minId] = null;
      return item;
    }

    function getScore(item) {
      return calcScore(shapeItems[item.ids[0]], shapeItems[item.ids[1]]);
    }

    function mergeCentroids(dest, src) {
      var k = dest.area / (dest.area + src.area),
          a = dest.centroid,
          b = src.centroid;
      // TODO: consider using geodetic distance when appropriate
      a.x = a.x * k + b.x * (1 - k);
      a.y = a.y * k + b.y * (1 - k);
    }

    function mergeShapes(ids) {
      var dest = shapeItems[ids[0]];
      var src = shapeItems[ids[1]];
      dest.bounds.mergeBounds(src.bounds);
      dest.area += src.area;
      dest.ids = dest.ids.concat(src.ids);
      mergeCentroids(dest, src);
      shapeItems[ids[0]] = null;
      shapeItems[ids[1]] = null;
      dest.friends = filterFriends(dest.friends.concat(src.friends));
      return dest;
    }

    // remove ids of duplicate and invalid merge candidates
    function filterFriends(friends) {
      var index = {};
      var merged = [];
      var id;
      for (var i=0; i<friends.length; i++) {
        id = friends[i];
        if ((id in index === false) && mergeItems[id] !== null) {
          merged.push(id);
          index[id] = true;
        }
      }
      return merged;
    }

    // re-index merge candidates after merging two shapes into a new shape
    function updateList(friends, oldIds, newId) {
      var item, id;
      for (var i=0, n=friends.length; i<n; i++) {
        id = friends[i];
        item = mergeItems[id];
        if (contains(item.ids, oldIds)) {
          mergeItems[id] = updateItem(item, oldIds, newId);
        }
      }
    }

    // re-index a merge candidate; return null if it duplicates a previously merged
    //   pair of shapes
    function updateItem(item, oldIds, newId) {
      var a = item.ids[0];
      var b = item.ids[1];
      var key;
      if (oldIds[0] == a || oldIds[1] == a) a = newId;
      if (oldIds[0] == b || oldIds[1] == b) b = newId;
      if (a == b) return null;
      item.ids = [a, b];
      key = clusterKey(item);
      if (key in mergeIndex) return null;
      mergeIndex[key] = true;
      item.score = getScore(item);
      if (item.score < 0) return null;
      return item;
    }

    function contains(a, b) {
      return a[0] === b[0] || a[0] === b[1] || a[1] === b[0] || a[1] === b[1];
    }

    function clusterKey(friend) {
      var a = friend.ids[0],
          b = friend.ids[1];
      if (b < a) {
        a = b;
        b = friend.ids[0];
      }
      return a + ',' + b;
    }
  }

  function getPolygonClusterCalculator(opts) {
    var maxWidth = opts.max_width || Infinity;
    var maxHeight = opts.max_height || Infinity;
    var maxArea = opts.max_area || Infinity;
    return function(a, b) {
      var area = a.area + b.area,
          // TODO: use geodetic distance when appropriate
          score = geom.distance2D(a.centroid.x, a.centroid.y, b.centroid.x, b.centroid.y),
          bounds = a.bounds.clone().mergeBounds(b.bounds);
      if (area > maxArea || bounds.width() > maxWidth ||
          bounds.height() > maxHeight) {
        score = -1;
      }
      return score;
    };
  }

  cmd.colorizer = function(opts) {
    if (!opts.name) {
      stop("Missing required name= parameter");
    }
    if (isReservedName(opts.name)) {
      stop('"' + opts.name + '" is a reserved name');
    }
    getStashedVar('defs')[opts.name] = getColorizerFunction(opts);
  };

  function isReservedName(name) {
    return /^(stroke|stroke-width|stroke-dasharray|stroke-opacity|fill|fill-opacity|opacity|r|class)$/.test(name);
  }

  function getColorizerFunction(opts) {
    var nodataColor = opts.nodata || 'white';
    var round = opts.precision ? getRoundingFunction(opts.precision) : null;
    var colorFunction;

    if (!opts.random && (!opts.colors || !opts.colors.length)) {
      stop("Missing colors= parameter");
    }

    if (opts.random) {
      colorFunction = getRandomColorFunction(opts.colors);
    } else if (opts.breaks) {
      if (opts.colors.length != opts.breaks.length + 1) {
        stop("Number of colors should be one more than number of class breaks");
      }
      colorFunction = getSequentialClassifier(opts.breaks, opts.colors, nodataColor, round);
    } else if (opts.categories) {
      if (opts.colors.length != opts.categories.length) {
        stop("Number of colors should be equal to the number of categories");
      }
      colorFunction = getCategoricalClassifier(opts.colors, nodataColor, opts);
    } else {
      stop("Missing categories= or breaks= parameter");
    }

    return colorFunction;
  }

  function getSequentialClassifier(breaks, colors, nullVal, round) {
    var classify = getDiscreteClassifier(breaks, round);
    var toColor = getDiscreteValueGetter(colors, nullVal);
    return function(val) {
      return toColor(classify(val));
    };
  }

  function fastStringHash(val) {
    // based on https://github.com/darkskyapp/string-hash (public domain)
    var str = String(val),
        hash = 5381,
        i = str.length;
    while (i > 0) {
      hash = (hash * 33) ^ str.charCodeAt(--i);
    }
    return Math.abs(hash);
  }

  function getRandomColorFunction(colors) {
    if (!colors || !colors.length) {
      colors = '#ccc,#888,#444'.split(',');
    }
    return function(val) {
      var n = colors.length;
      var i = val === undefined ?
          Math.floor(Math.random() * n) : fastStringHash(val) % n;
      return colors[i];
    };
  }

  var Colorizer = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getColorizerFunction: getColorizerFunction
  });

  cmd.comment = function() {}; // no-op, so -comment doesn't trigger a parsing error

  function expressionUsesGeoJSON(exp) {
    return exp.includes('this.geojson');
  }

  function getFeatureEditor(lyr, dataset) {
    var changed = false;
    var api = {};
    // need to copy attribute to avoid circular references if geojson is assigned
    // to a data property.
    var copy = copyLayer(lyr);
    var features = exportLayerAsGeoJSON(copy, dataset, {}, true);

    api.get = function(i) {
      return features[i];
    };

    api.set = function(feat, i) {
      changed = true;
      if (utils.isString(feat)) {
        feat = JSON.parse(feat);
      }
      features[i] = GeoJSON.toFeature(feat); // TODO: validate
    };

    api.done = function() {
      if (!changed) return; // read-only expression
      // TODO: validate number of features, etc.
      var geojson = {
        type: 'FeatureCollection',
        features: features
      };

      // console.log(JSON.stringify(geojson, null, 2))
      return importGeoJSON(geojson);
    };
    return api;
  }

  cmd.dashlines = function(lyr, dataset, opts) {
    var crs = getDatasetCRS(dataset);
    var defs = getStashedVar('defs');
    var exp = `this.geojson = splitFeature(this.geojson)`;
    requirePolylineLayer(lyr);
    defs.splitFeature = getSplitFeatureFunction(crs, opts);
    cmd.evaluateEachFeature(lyr, dataset, exp, opts);
    delete defs.splitFeature;
  };

  function getSplitFeatureFunction(crs, opts) {
    var dashLen = opts.dash_length ? convertDistanceParam(opts.dash_length, crs) : 0;
    var gapLen = opts.gap_length ? convertDistanceParam(opts.gap_length, crs) : 0;
    if (dashLen > 0 === false) {
      stop('Missing required dash-length parameter');
    }
    if (gapLen >= 0 == false) {
      stop('Invalid gap-length option');
    }
    var splitLine = getSplitLineFunction(crs, dashLen, gapLen, opts);
    return function(feat) {
      var geom = feat.geometry;
      if (!geom) return feat;
      if (geom.type == 'LineString') {
        geom.type = 'MultiLineString';
        geom.coordinates = [geom.coordinates];
      }
      if (geom.type != 'MultiLineString') {
        error('Unexpected geometry:', geom.type);
      }
      geom.coordinates = geom.coordinates.reduce(function(memo, coords) {
        try {
          var parts = splitLine(coords);
          memo = memo.concat(parts);
        } catch(e) {
          console.error(e);
          throw e;
        }
        return memo;
      }, []);

      return feat;
    };
  }

  function getSplitLineFunction(crs, dashLen, gapLen, opts) {
    var planar = !!opts.planar;
    var interpolate = getInterpolationFunction(planar ? null : crs);
    var distance =  isLatLngCRS(crs) ? greatCircleDistance : distance2D;
    var inDash, parts2, interval, scale;
    function addPart(coords) {
      if (inDash) parts2.push(coords);
      if (gapLen > 0) {
        inDash = !inDash;
        interval = scale * (inDash ? dashLen : gapLen);
      }
    }

    return function splitLineString(coords) {
      var elapsedDist = 0;
      var p = coords[0];
      var coords2 = [p];
      var segLen, pct, prev;
      if (opts.scaled) {
        scale = scaleDashes(dashLen, gapLen, getLineLength(coords, distance));
      } else {
        scale = 1;
      }
      // init this LineString
      inDash = gapLen > 0 ? false : true;
      interval = scale * (inDash ? dashLen : gapLen);
      if (!inDash) {
        // start gapped lines with a half-gap
        // (a half-gap or a half-dash is probably better for rings and intersecting lines)
        interval *= 0.5;
      }
      parts2 = [];
      for (var i=1, n=coords.length; i<n; i++) {
        prev = p;
        p = coords[i];
        segLen = distance(prev[0], prev[1], p[0], p[1]);
        if (segLen <= 0) continue;
        while (elapsedDist + segLen >= interval) {
          // this segment contains a break either within it or at the far endpoint
          pct = (interval - elapsedDist) / segLen;
          if (pct > 0.999 && i == n - 1) {
            // snap to endpoint (so fp rounding errors don't result in a tiny
            // last segment)
            pct = 1;
          }
          if (pct < 1) {
            prev = interpolate(prev[0], prev[1], p[0], p[1], pct);
          } else {
            prev = p;
          }
          coords2.push(prev);
          addPart(coords2);
          // start a new part
          coords2 = pct < 1 ? [prev] : [];
          elapsedDist = 0;
          segLen = (1 - pct) * segLen;
        }
        coords2.push(p);
        elapsedDist += segLen;
      }
      if (elapsedDist > 0 && coords2.length > 1) {
        addPart(coords2);
      }
      return parts2;
    };
  }

  function getLineLength(coords, distance) {
    var len = 0;
    for (var i=1, n=coords.length; i<n; i++) {
      len += distance(coords[i-1][0], coords[i-1][1], coords[i][0], coords[i][1]);
    }
    return len;
  }

  function scaleDashes(dash, gap, len) {
    var n = len / (dash + gap); // number of dashes
    var n1 = Math.floor(n);
    var n2 = Math.ceil(n);
    var k1 = len / (n1 * (dash + gap)); // scaled-up dashes, >1
    var k2 = len / (n2 * (dash + gap)); // scaled-down dashes <1
    var k = k2;
    if (k1 < 1/k2 && n1 > 0) {
      k = k1; // pick the smaller of the two scales
    }
    return k;
  }

  // This function creates a continuous mosaic of data values in a
  // given field by assigning data from adjacent polygon features to polygons
  // that contain null values.
  // The 'contiguous' option removes data islands to create contiguous groups
  // that are likely to be the result of unreliable data (e.g. faulty geocodes).

  cmd.dataFill = function(lyr, arcs, opts) {
    var field = opts.field;
    if (!field) stop("Missing required field= parameter");
    requireDataField(lyr, field);
    if (lyr.geometry_type != 'polygon') stop("Target layer must be polygon type");
    var getNeighbors = getNeighborLookupFunction(lyr, arcs);
    var fillCount, islandCount;

    // get function to check if a shape was empty before data-fill
    var initiallyEmpty = (function() {
      var flags = lyr.data.getRecords().map(function(rec) {
        return isEmptyValue(rec[field]);
      });
      return function(i) {return flags[i];};
    }());

    // step one: fill empty units
    fillCount = dataFillEmpty(field, lyr, arcs, getNeighbors);

    // step two: smooth perimeters
    dataFillSmooth(field, lyr, arcs, getNeighbors, initiallyEmpty);

    // step three: remove non-contiguous data islands
    if (opts.contiguous) {
      islandCount = dataFillIslandGroups(field, lyr, arcs, getNeighbors, opts);
    }

    message('Filled', fillCount, 'empty polygons' + utils.pluralSuffix(fillCount));
    if (islandCount > 0) {
      message('Removed', islandCount, 'non-contiguous polygon group' + utils.pluralSuffix(islandCount));
    }
  };

  // Assign values to units without data, using the values of neighboring units.
  function dataFillEmpty(field, lyr, arcs, getNeighbors) {
    var records = lyr.data.getRecords();
    var onShape = getDataFillCalculator(field, lyr, arcs, getNeighbors);
    var isEmpty = getEmptyValueFilter(field, lyr);
    var groups = {}; // groups, indexed by key
    var assignCount = 0;

    // step one: place features in groups based on data values of non-empty neighbors.
    // (grouping is an attempt to avoid ragged edges between groups of same-value units,
    // which occured when data was assigned to units independently of adjacent units).
    lyr.shapes.forEach(function(shp, i) {
      if (!isEmpty(i)) return; // only assign shapes with missing values
      var data = onShape(i);
      if (!data.group) return; // e.g. if no neighbors have data
      addDataToGroup(data, groups);
    });

    // step two: assign the same value to all members of a group
    Object.keys(groups).forEach(function(groupId) {
      var group = groups[groupId];
      var value = getMaxWeightValue(group);
      assignValueToShapes(group.shapes, value);
    });

    function assignValueToShapes(ids, val) {
      ids.forEach(function(id) {
        assignCount++;
        records[id][field] = val;
      });
    }

    function addDataToGroup(d, groups) {
      var group = groups[d.group];
      var j;
      if (!group) {
        groups[d.group] = {
          shapes: [d.shape],
          weights: d.weights,
          values: d.values
        };
        return;
      }
      group.shapes.push(d.shape);
      for (var i=0, n=d.values.length; i<n; i++) {
        // add new weights to the group's total weights
        j = group.values.indexOf(d.values[i]);
        group.weights[j] += d.weights[i];
      }
    }

    if (assignCount > 0) {
      // recursively fill empty neighbors of the newly filled shapes
      assignCount += dataFillEmpty(field, lyr, arcs, getNeighbors);
    }
    return assignCount;
  }


  // Try to smooth out jaggedness resulting from filling empty units
  // This function assigns a different adjacent data value to formerly empty units,
  // if this would produce a shorter boundary.
  function dataFillSmooth(field, lyr, arcs, getNeighbors, wasEmpty) {
    var onShape = getDataFillCalculator(field, lyr, arcs, getNeighbors);
    var records = lyr.data.getRecords();
    var updates = 0;
    lyr.shapes.forEach(function(shp, i) {
      if (!wasEmpty(i)) return; // only edit shapes that were originally empty
      var data = onShape(i);
      if (data.values.length < 2) return; // no other values are available
      var currVal = records[i][field];
      var topVal = getMaxWeightValue(data);
      if (currVal != topVal) {
        records[i][field] = topVal;
        updates++;
      }
    });
    return updates;
  }

  // Remove less-important data islands to ensure that data groups are contiguous
  //
  function dataFillIslandGroups(field, lyr, arcs, getNeighbors, opts) {
    var records = lyr.data.getRecords();
    var groupsByValue = {}; // array of group objects, indexed by data values
    var unitIndex = new Uint8Array(lyr.shapes.length);
    var currGroup = null;
    var islandCount = 0;
    var weightField = opts.weight_field || null;

    if (weightField) {
      requireDataField(lyr, weightField);
    }

    // 1. form groups of contiguous units with the same attribute value
    lyr.shapes.forEach(function(shp, shpId) {
      onShape(shpId);
    });

    // 2. retain the most important group for each value; discard satellite groups
    Object.keys(groupsByValue).forEach(function(val) {
      var groups = groupsByValue[val];
      var maxIdx;
      if (groups.length < 2) return;
      maxIdx = indexOfMaxValue(groups);
      if (maxIdx == -1) return; // error condition...
      groups
        .filter(function(group, i) {return i != maxIdx;})
        .forEach(clearIslandGroup);
    });

    // 3. fill gaps left by removing groups
    if (islandCount > 0) {
      dataFillEmpty(field, lyr, arcs, getNeighbors);
    }
    return islandCount;

    function clearIslandGroup(group) {
      islandCount++;
      group.shapes.forEach(function(shpId) {
        records[shpId][field] = null;
      });
    }

    function onShape(shpId) {
      if (unitIndex[shpId] == 1) return; // already added to a group
      var val = records[shpId][field];
      var firstShape = false;
      if (isEmptyValue(val)) return;
      if (!currGroup) {
        // start a new group
        firstShape = true;
        currGroup = {
          value: val,
          shapes: [],
          weight: 0
        };
        if (val in groupsByValue === false) {
          groupsByValue[val] = [];
        }
        groupsByValue[val].push(currGroup);
      } else if (val != currGroup.value) {
        return;
      }
      if (weightField) {
        currGroup.weight += records[shpId][weightField];
      } else {
        currGroup.weight += geom.getShapeArea(lyr.shapes[shpId], arcs);
      }
      currGroup.shapes.push(shpId);
      unitIndex[shpId] = 1;
      // TODO: consider switching from depth-first traversal to breadth-first
      getNeighbors(shpId).forEach(onShape);
      if (firstShape) {
        currGroup = null;
      }
    }
  }


  // Return value with the greatest weight from a datafill object
  function getMaxWeightValue(d) {
    var maxWeight = Math.max.apply(null, d.weights);
    var i = d.weights.indexOf(maxWeight);
    return d.values[i]; // return highest weighted value
  }

  // TODO: move to a more sensible file... mapshaper-calc-utils?
  function indexOfMaxValue(arr, key) {
    var maxWeight = -Infinity;
    var idx = -1;
    arr.forEach(function(o, i) {
      if (o.weight > maxWeight) {
        idx = i;
        maxWeight = o.weight;
      }
    });
    return idx;
  }

  function isEmptyValue(val) {
     return !val && val !== 0;
  }

  function getEmptyValueFilter(field, lyr) {
    var records = lyr.data.getRecords();
    return function(i) {
      var rec = records[i];
      return rec ? isEmptyValue(rec[field]) : false;
    };
  }

  // Returns a function to fetch the values of a data field from the neighbors of
  // a polygon feature. Each value is assigned a weight in proportion to the
  // length of the borders between the polygon and its neighbors.
  function getDataFillCalculator(field, lyr, arcs, getNeighbors) {
    var isPlanar = arcs.isPlanar();
    var records = lyr.data.getRecords();
    var tmp;

    function onSharedArc(nabeId, arcId) {
      var weight, i;
      var val = records[nabeId][field];
      if (isEmptyValue(val)) return;
      // weight is the length of the shared border
      // TODO: consider support for alternate weighting schemes
      weight = geom.calcPathLen([arcId], arcs, !isPlanar);
      i = tmp.values.indexOf(val);
      if (i == -1) {
        tmp.values.push(val);
        tmp.weights.push(weight);
      } else {
        tmp.weights[i] += weight;
      }
    }

    return function(shpId) {
      tmp = {
        shape: shpId,
        weights: [],
        values: [],
        group: ''
      };
      getNeighbors(shpId, onSharedArc);
      tmp.group = tmp.values.concat().sort().join('~');
      return tmp;
    };
  }

  cmd.define = function(opts) {
    if (!opts.expression) {
      stop('Missing an assignment expression');
    }
    var defs = getStashedVar('defs');
    var compiled = compileFeatureExpression(opts.expression, {}, null, {no_warn: true});
    compiled(null, defs);
  };

  // Removes small gaps and all overlaps
  cmd.dissolve2 = function(layers, dataset, opts) {
    layers.forEach(requirePolygonLayer);
    addIntersectionCuts(dataset, opts);
    return layers.map(function(lyr) {
      if (!layerHasPaths(lyr)) return lyr;
      return dissolvePolygonLayer2(lyr, dataset, opts);
    });
  };

  // Returns a function for filtering multiple source-table records
  // (used by -join command)
  function getJoinFilter(data, exp) {
    var test = getJoinFilterTestFunction(exp, data);
    var calc = null;
    if (expressionHasCalcFunction(exp)) {
      calc = getJoinFilterCalcFunction(exp, data);
    }

    return function(srcIds, destRec) {
      var d = calc ? calc(srcIds) : null;
      var filtered = [],
          retn, i;
      for (i=0; i<srcIds.length; i++) {
        retn = test(srcIds[i], destRec, d);
        if (retn === true) {
          filtered.push(srcIds[i]);
        } else if (retn !== false) {
          stop('"where" expression must return true or false');
        }
      }
      return filtered;
    };
  }

  function expressionHasCalcFunction(exp) {
    return utils.some(['isMax', 'isMin', 'isMode'], function(name) {
      return exp.indexOf(name) > -1;
    });
  }


  function getJoinFilterCalcFunction(exp, data) {
    var values, max, min, context, calc;

    context = {
      isMax: function(val) {
        if (val > max) max = val;
      },
      isMin: function(val) {
        if (val < min) min = val;
      },
      isMode: function(val) {
        if (!values) {
          values = [];
        }
        values.push(val);
      }
    };

    calc = compileFeatureExpression(exp, {data: data}, null, {context: context});

    function reset() {
      max = -Infinity;
      min = Infinity;
      values = null;
    }

    return function(ids) {
      var mode;
      reset();
      for (var i=0; i<ids.length; i++) {
        calc(ids[i]);
      }
      mode = values ? getModeData(values) : null;
      return {
        max: max,
        min: min,
        modes: mode ? mode.modes : null,
        margin: mode ? mode.margin : null
      };
    };
  }


  function getJoinFilterTestFunction(exp, data) {
    var test, calcRec, destRec;
    var context = {
      isMax: function(val) {
        return val === calcRec.max;
      },
      isMin: function(val) {
        return val === calcRec.min;
      },
      isMode: function(val) {
        return calcRec.modes.indexOf(val) > -1;
      }
    };
    // 'target' property is an accessor function,
    // so the object it references can be updated.
    Object.defineProperty(context, 'target', {
      get: function() {
        return destRec;
      },
      enumerable: true // so it can be mixed-in to the actual expression context
    });

    test = compileFeatureExpression(exp, {data: data}, null, {context: context, returns: true});

    // calcR: results from calculation phase, or null
    return function(srcId, destR, calcR) {
      calcRec = calcR;
      destRec = destR;
      return test(srcId);
    };
  }

  var JoinFilter = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getJoinFilter: getJoinFilter
  });

  // Join data from @src table to records in @dest table
  function joinTables(dest, src, join, opts) {
    return joinTableToLayer({data: dest}, src, join, opts);
  }

  // Join data from @src table to records in @destLyr layer.
  // @join function
  //    Receives index of record in the dest table
  //    Returns array of matching records in src table, or null if no matches
  //
  function joinTableToLayer(destLyr, src, join, opts) {
    var dest = destLyr.data,
        useDuplication = !!opts.duplication,
        srcRecords = src.getRecords(),
        destRecords = dest.getRecords(),
        prefix = opts.prefix || '',
        unmatchedRecords = [],
        joinFields = getFieldsToJoin(dest.getFields(), src.getFields(), opts),
        sumFields = opts.sum_fields || [],
        copyFields = utils.difference(joinFields, sumFields),
        joinCounts = new Uint32Array(srcRecords.length),
        matchCount = 0,
        collisionCount = 0,
        collisionFields = [],
        skipCount = 0,
        retn = {},
        srcRec, srcId, destRec, joins, count, filter, calc, i, j, n, m;

    // support for duplication of destination records
    var duplicateRecords, destShapes;
    if (useDuplication) {
      if (opts.calc) stop('duplication and calc options cannot be used together');
      duplicateRecords = dest.clone().getRecords();
      destShapes = destLyr.shapes || [];
    }

    if (opts.where) {
      filter = getJoinFilter(src, opts.where);
    }

    if (opts.calc) {
      calc = getJoinCalc(src, opts.calc);
    }

    // join source records to target records
    n = destRecords.length;
    for (i=0; i<n; i++) {
      destRec = destRecords[i];
      joins = join(i);
      if (joins && filter) {
        skipCount += joins.length;
        joins = filter(joins, destRec);
        skipCount -= joins.length;
      }
      for (j=0, count=0, m=joins ? joins.length : 0; j<m; j++) {
        srcId = joins[j];
        srcRec = srcRecords[srcId];
        // duplication mode: many-to-one joins add new features to the target layer.
        if (count > 0 && useDuplication) {
          destRec = copyRecord(duplicateRecords[i]);
          destRecords.push(destRec);
          destShapes.push(cloneShape(destShapes[i]));
        }
        if (count === 0 || useDuplication) {
          if (copyFields.length > 0) {
            // only copying the first match
            joinByCopy(destRec, srcRec, copyFields, prefix);
          }
        } else if (count == 1) {
          if (copyFields.length > 0 && !prefix) {
            findCollisionFields(destRec, srcRec, copyFields, collisionFields);
          }
          collisionCount++; // count target records with multiple joins
        }
        if (sumFields.length > 0) {
          joinBySum(destRec, srcRec, sumFields, prefix);
        }
        joinCounts[srcId]++;
        count++;
      }
      if (calc) {
        calc(joins, destRec);
      }
      if (count > 0) {
        matchCount++;
      } else if (destRec) {
        if (opts.unmatched) {
          // Save a copy of unmatched record, before null values from join fields
          // are added.
          unmatchedRecords.push(utils.extend({}, destRec));
        }
        updateUnmatchedRecord(destRec, copyFields, sumFields, prefix);
      }
    }

    printJoinMessage(matchCount, n,
        countJoins(joinCounts), srcRecords.length, skipCount, collisionCount, collisionFields);

    if (opts.unjoined) {
      retn.unjoined = {
        name: 'unjoined',
        data: new DataTable(srcRecords.filter(function(o, i) {
          return joinCounts[i] === 0;
        }))
      };
    }
    if (opts.unmatched) {
      retn.unmatched = {
        name: 'unmatched',
        data: new DataTable(unmatchedRecords)
      };
    }
    return retn;
  }

  function validateFieldNames(arr) {
    arr.forEach(function(name) {
      if (/:(str|num)/.test(name)) {
        stop("Unsupported use of type hints. Use string-fields= or field-types= options instead");
      }
    });
  }


  function countJoins(counts) {
    var joinCount = 0;
    for (var i=0, n=counts.length; i<n; i++) {
      if (counts[i] > 0) {
        joinCount++;
      }
    }
    return joinCount;
  }

  // Unset fields of unmatched records get null/empty values
  function updateUnmatchedRecord(rec, copyFields, sumFields, prefix) {
    joinByCopy(rec, {}, copyFields, prefix);
    joinBySum(rec, {}, sumFields, prefix);
  }

  /*
  internal.getCountFieldName = function(fields) {
    var uniq = internal.getUniqFieldNames(fields.concat("joins"));
    return uniq.pop();
  };
  */

  function joinByCopy(dest, src, fields, prefix) {
    var f, f2;
    prefix = prefix || '';
    for (var i=0, n=fields.length; i<n; i++) {
      // dest[fields[i]] = src[fields[i]];
      // Use null when the source record is missing an expected value
      // TODO: think some more about whether this is desirable
      f = fields[i];
      f2 = prefix + f;
      if (Object.prototype.hasOwnProperty.call(src, f)) {
        dest[f2] = src[f];
      } else if (!Object.prototype.hasOwnProperty.call(dest, f2)) {
        dest[f2] = null;
      }
    }
  }

  function joinBySum(dest, src, fields, prefix) {
    var f, f2;
    prefix = prefix || '';
    for (var j=0; j<fields.length; j++) {
      f = fields[j];
      f2 = prefix + f;
      dest[f2] = (dest[f2] || 0) + (src[f] || 0);
    }
  }

  function findCollisionFields(dest, src, fields, collisionFields) {
    var f;
    for (var i=0, n=fields.length; i<n; i++) {
      f = fields[i];
      if (dest[f] !== src[f] && collisionFields.indexOf(f) === -1) {
        collisionFields.push(f);
      }
    }
  }

  function printJoinMessage(matches, n, joins, m, skipped, collisions, collisionFields) {
    // TODO: add tip for troubleshooting join problems, if join is less than perfect.
    var unmatched = n - matches;
    if (matches > 0 === false) {
      message("No records could be joined");
      return;
    }
    message(utils.format("Joined data from %'d source record%s to %'d target record%s",
        joins, utils.pluralSuffix(joins), matches, utils.pluralSuffix(matches)));
    if (unmatched > 0) {
      message(utils.format('%d target record%s received no data', unmatched, utils.pluralSuffix(unmatched)));
      // message(utils.format('%d target records received no data', n-matches));
    }
    if (joins < m) {
      message(utils.format("%d/%d source records could not be joined", m-joins, m));
    }
    if (skipped > 0) {
      message(utils.format("%d/%d source records were skipped", skipped, m));
    }
    if (collisions > 0) {
      message(utils.format('%d/%d target records were matched by multiple source records (many-to-one relationship)', collisions, n));
      if (collisionFields.length > 0) {
        message(utils.format('Inconsistent values were found in field%s [%s] during many-to-one join. Values in the first joining record were used.', utils.pluralSuffix(collisionFields.length), collisionFields.join(',')));
      }
    }
  }

  function getFieldsToJoin(destFields, srcFields, opts) {
    var joinFields;
    if (opts.fields) {
      if (opts.fields.indexOf('*') > -1) {
        joinFields = srcFields;
      } else {
        joinFields = opts.fields;
        validateFieldNames(joinFields);
      }
    } else if (opts.calc) {
      // presence of calc= option suggests a many-to-one or many-to-many join;
      // it usually doesn't make sense to join all fields by default
      joinFields = [];
    } else {
      // If a list of fields to join is not given, try to join all of the
      // source fields
      joinFields = srcFields;
      // exclude source key field from key-based join (if fields are not given explicitly)
      if (opts.keys) {
        joinFields = utils.difference(joinFields, [opts.keys[1]]);
      }
    }
    if (!opts.force && !opts.prefix) {
      // overwrite existing fields if the "force" option is set.
      // prefix also overwrites... TODO: consider changing this
      var duplicateFields = utils.intersection(joinFields, destFields);
      if (duplicateFields.length > 0) {
        message('Same-named fields not joined without the "force" flag:', duplicateFields);
        joinFields = utils.difference(joinFields, duplicateFields);
      }
    }
    return joinFields;
  }

  var JoinTables = /*#__PURE__*/Object.freeze({
    __proto__: null,
    joinTables: joinTables,
    joinTableToLayer: joinTableToLayer,
    validateFieldNames: validateFieldNames,
    updateUnmatchedRecord: updateUnmatchedRecord,
    findCollisionFields: findCollisionFields,
    getFieldsToJoin: getFieldsToJoin
  });

  cmd.divide = function(targetLayers, targetDataset, source, opts) {
    targetLayers.forEach(requirePolylineLayer);
    var mergedDataset = mergeLayersForOverlay(targetLayers, targetDataset, source, opts);
    var nodes = addIntersectionCuts(mergedDataset, opts);
    var polygonLyr = mergedDataset.layers.pop();
    requirePolygonLayer(polygonLyr);
    // Assume that topology is now built
    targetDataset.arcs = mergedDataset.arcs;
    targetLayers.forEach(function(polylineLyr) {
      dividePolylineLayer(polylineLyr, polygonLyr, nodes, opts);
    });
  };

  function dividePolylineLayer(polylineLyr, polygonLyr, nodes, opts) {
    var index = new PathIndex(polygonLyr.shapes, nodes.arcs);
    var records = polylineLyr.data ? polylineLyr.data.getRecords() : [];
    var shapes2 = [];
    var records2 = [];
    var index2 = [];
    var outputLines;
    var outputKeys;
    var outputMatches;
    polylineLyr.shapes.forEach(function(shp, i) {
      var rec = records[i] || {};
      if (!shp) {
        // case: record with no geometry -- retain in the output layer
        shapes2.push(null);
        records2.push(rec);
        return;
      }
      outputLines = [];
      outputKeys = [];
      outputMatches = [];
      forEachShapePart(shp, onPart);
      outputLines.forEach(function(shape2, i) {
        shapes2.push(shape2);
        records2.push(i > 0 ? utils.extend({}, rec) : rec); // assume input data is being replaced
        index2.push(outputMatches[i]);
      });
    });
    polylineLyr.shapes = shapes2;
    polylineLyr.data = new DataTable(records2);
    joinTables(polylineLyr.data, polygonLyr.data, function(i) {
      return index2[i] || [];
    }, opts);

    function addDividedParts(parts, keys, matches) {
      var keyId, key;
      for (var i=0; i<parts.length; i++) {
        key = keys[i];
        keyId = outputKeys.indexOf(key);
        if (keyId == -1) {
          outputKeys.push(key);
          outputLines.push([parts[i]]);
          outputMatches.push(matches[i]);
        } else {
          outputLines[keyId].push(parts[i]);
        }
      }
    }

    function getKey(shapeIds) {
      return shapeIds.sort().join(',');
      // multiple matches: treat like no match
      // return shapeIds.length == 1 ? String(shapeIds[0]) : '-1';
    }

    // Partition each part
    function onPart(ids) {
      var parts2 = [];
      var keys2 = [];
      var matches2 = [];
      var prevKey = null;
      var containingIds, key, part2, arcId;
      // assign each arc to a divided shape
      for (var i=0, n=ids.length; i<n; i++) {
        arcId = ids[i];
        containingIds = index.findShapesEnclosingArc(absArcId(arcId));
        key = getKey(containingIds);
        if (key === prevKey) {
          // case: continuation of a part
          part2.push(arcId);
        } else {
          // case: start of a new part
          part2 = [arcId];
          parts2.push(part2);
          keys2.push(key);
          matches2.push(containingIds);
        }
        prevKey = key;
      }
      addDividedParts(parts2, keys2, matches2);
    }
  }

  function MaxHeap() {
    return new Heap('max');
  }

  // A heap data structure used for computing Visvalingam simplification data.
  // type: 'max' or 'min' (min is default)
  //
  function Heap(type) {
    var heapBuf = utils.expandoBuffer(Int32Array),
        indexBuf = utils.expandoBuffer(Int32Array),
        heavierThan = type == 'max' ? lessThan : greaterThan,
        itemsInHeap = 0,
        dataArr,
        heapArr,
        indexArr;

    this.init = function(values) {
      var i;
      dataArr = values;
      itemsInHeap = values.length;
      heapArr = heapBuf(itemsInHeap);
      indexArr = indexBuf(itemsInHeap);
      for (i=0; i<itemsInHeap; i++) {
        insertValue(i, i);
      }
      // place non-leaf items
      for (i=(itemsInHeap-2) >> 1; i >= 0; i--) {
        downHeap(i);
      }
    };

    this.size = function() {
      return itemsInHeap;
    };

    // Update a single value and re-heap
    this.updateValue = function(valIdx, val) {
      var heapIdx = indexArr[valIdx];
      dataArr[valIdx] = val;
      if (!(heapIdx >= 0 && heapIdx < itemsInHeap)) {
        error("Out-of-range heap index.");
      }
      downHeap(upHeap(heapIdx));
    };

    this.popValue = function() {
      return dataArr[this.pop()];
    };

    this.getValue = function(idx) {
      return dataArr[idx];
    };

    this.peek = function() {
      return heapArr[0];
    };

    this.peekValue = function() {
      return dataArr[heapArr[0]];
    };

    // Return the idx of the lowest-value item in the heap
    this.pop = function() {
      var popIdx;
      if (itemsInHeap <= 0) {
        error("Tried to pop from an empty heap.");
      }
      popIdx = heapArr[0];
      insertValue(0, heapArr[--itemsInHeap]); // move last item in heap into root position
      downHeap(0);
      return popIdx;
    };

    function upHeap(idx) {
      var parentIdx;
      // Move item up in the heap until it's at the top or is not lighter than its parent
      while (idx > 0) {
        parentIdx = (idx - 1) >> 1;
        if (heavierThan(idx, parentIdx)) {
          break;
        }
        swapItems(idx, parentIdx);
        idx = parentIdx;
      }
      return idx;
    }

    // Swap item at @idx with any lighter children
    function downHeap(idx) {
      var minIdx = compareDown(idx);

      while (minIdx > idx) {
        swapItems(idx, minIdx);
        idx = minIdx; // descend in the heap
        minIdx = compareDown(idx);
      }
    }

    function swapItems(a, b) {
      var i = heapArr[a];
      insertValue(a, heapArr[b]);
      insertValue(b, i);
    }

    // Associate a heap idx with the index of a value in data arr
    function insertValue(heapIdx, valId) {
      indexArr[valId] = heapIdx;
      heapArr[heapIdx] = valId;
    }

    // comparator for Visvalingam min heap
    // @a, @b: Indexes in @heapArr
    function greaterThan(a, b) {
      var idx1 = heapArr[a],
          idx2 = heapArr[b],
          val1 = dataArr[idx1],
          val2 = dataArr[idx2];
      // If values are equal, compare array indexes.
      // This is not a requirement of the Visvalingam algorithm,
      // but it generates output that matches Mahes Visvalingam's
      // reference implementation.
      // See https://hydra.hull.ac.uk/assets/hull:10874/content
      return (val1 > val2 || val1 === val2 && idx1 > idx2);
    }

    // comparator for max heap
    function lessThan(a, b) {
      var idx1 = heapArr[a],
          idx2 = heapArr[b];
      return dataArr[idx1] < dataArr[idx2];
    }

    function compareDown(idx) {
      var a = 2 * idx + 1,
          b = a + 1,
          n = itemsInHeap;
      if (a < n && heavierThan(idx, a)) {
        idx = a;
      }
      if (b < n && heavierThan(idx, b)) {
        idx = b;
      }
      return idx;
    }
  }

  // TODO: optimize point-in-polygon tests for complex polygons and many points
  // import { PathIndex } from '../paths/mapshaper-path-index';

  function placeDotsInPolygon(shp, arcs, n, opts) {
    // TODO: skip tiny sliver polygons?
    if (n === 0) return [];
    if (opts.evenness === 0) return placeDotsRandomly(shp, arcs, n);
    // TODO: if n == 1, consider using the 'inner' point of a polygon
    return placeDotsEvenly(shp, arcs, n, opts);
  }

  function placeDotsRandomly(shp, arcs, n) {
    var bounds = arcs.getMultiShapeBounds(shp);
    var coords = [];
    for (var i=0; i<n; i++) {
      coords.push(placeRandomDot(shp, arcs, bounds));
    }
    return coords;
  }

  function placeRandomDot(shp, arcs, bounds) {
    var limit = 100;
    var i = 0;
    var x, y;
    while (++i < limit) {
      x = bounds.xmin + Math.random() * bounds.width();
      y = bounds.ymin + Math.random() * bounds.height();
      if (testPointInPolygon(x, y, shp, arcs)) {
        return [x, y];
      }
    }
    return null;
  }

  function placeDotsEvenly(shp, arcs, n, opts) {
    var evenness = opts.evenness >= 0 ? Math.min(opts.evenness, 1) : 1;
    var shpArea = geom.getPlanarShapeArea(shp, arcs);
    if (shpArea > 0 === false) return [];
    var bounds = arcs.getMultiShapeBounds(shp);
    var approxQueries = Math.round(n * bounds.area() / shpArea);
    if (opts.progressive) {
      // TODO: implement this properly
      approxQueries = Math.ceil(approxQueries / 6);
    }
    var grid = new DotGrid(bounds, approxQueries, evenness);
    var coords = [];
    for (var i=0; i<n; i++) {
      coords.push(placeDot(shp, arcs, grid));
    }
    grid.done();
    return coords;
  }

  function placeDot(shp, arcs, grid) {
    var i = 0;
    var limit = 100;
    var p;
    while (++i < limit) {
      p = grid.getPoint();
      if (!p) continue;
      if (testPointInPolygon(p[0], p[1], shp, arcs)) {
        return p;
      }
    }
    return null;
  }

  // A method for placing dots in a 2D rectangular space
  // evenness: varies from 0-1
  //   0 is purely random
  //   1 uses a hybrid approach, first creating a sparse structure of random
  //      dots, then progressively filling in the spaces between dots
  //   (0-1) first creates an evenish structure of dots, then places additional
  //      dots using "dart-throwing" -- picking random points until a point
  //      is found that exceeds a (variable) distance from any other point
  //
  function DotGrid(bounds, approxQueries, evenness) {
    var x0 = bounds.xmin;
    var y0 = bounds.ymin;
    var w = bounds.width();
    var h = bounds.height();
    var k =  0.5 * (evenness - 1) + 1; // k varies from 0.5 to 1
    var approxCells = approxQueries * 0.9 * k;
    var cols = Math.round(Math.sqrt(approxCells * w / h)) || 1;
    var rows = Math.ceil(cols * h / w); // overshoots bbox height
    var gridWidth = w;
    var cells = cols * rows;
    var cellId = -1;
    var shuffledIds;
    var grid = initGrid(cells);
    // data used by optimal method
    var bestPoints;
    var bestHeap;

    // Set the initial distance threshold between dots (based on a square grid)
    // When evenness < 1 (dart-throwing mode) the distance threshold is reduced in
    //   proportion to the value of evenness.
    // From trial and error, a 0.7 constant seems to give good results.
    var initialDotSpacing = gridWidth / cols * 0.7 * evenness;
    var dotSpacing = initialDotSpacing;

    this.done = done;
    this.getPoint = getPoint;

    function done() {
    }

    function getPoint() {
      if (evenness === 1) return getOptimalPoint();
      if (evenness === 0) return getRandomPoint();
      return getSpacedPoint();
    }

    function initGrid(n) {
      var arr = [];
      for (var i=0; i<n; i++) arr.push([]);
      return arr;
    }

    function getOptimalPoint() {
      var p = getFirstFillPoint();
      if (p) return usePoint(p);

      // fill in the gaps of the initial placement, starting with the largest gap
      if (!bestPoints) {
        initBestPoints();
      }
      return useBestPoint();
    }

    // try to place a random but spaced point in each grid cell
    // (to create an initial sparse structure that gets filled in later)
    function getFirstFillPoint() {
      var p;
      if (!shuffledIds) {
        shuffledIds = utils.range(cells);
        utils.shuffle(shuffledIds);
      }
      while (++cellId < cells) {
        p = getRandomPointInCell(shuffledIds[cellId]);
        if (pointIsUsable(p)) {
          return p;
        }
      }
    }

    function getSpacedPoint() {
      // use dart-throwing, reject points that are within the minimum distance
      var probesBeforeRelaxation = Math.ceil(Math.pow(cells, 0.8));
      var maxProbes = cells * 10;
      var probes = 0;
      var p = getFirstFillPoint();
      if (p) return usePoint(p);

      while (probes++ < maxProbes) {
        p = getRandomPoint();
        if (pointIsUsable(p)) {
          return usePoint(p);
        }
        if (probes % probesBeforeRelaxation === 0) {
          // relax min dist after a number of failed probes
          dotSpacing *= 0.9;
        }
      }
      return null;
    }

    // Add point to grid of used points
    function usePoint(p) {
      var i = pointToIdx(p);
      grid[i].push(p);
      return p;
    }

    function useBestPoint() {
      var bestId = bestHeap.peek();
      var p = bestPoints[bestId];
      usePoint(p); // add to grid of used points
      updateNeighbors(p, bestId); // update best point of this cell and neighbors
      dotSpacing = bestHeap.peekValue();
      return p;
    }

    function initBestPoints() {
      var values = [];
      bestPoints = [];
      for (var i=0; i<cells; i++) {
        values.push(findBestPointInCell(i));
      }
      bestHeap = new MaxHeap();
      bestHeap.init(values);
    }

    function updateNeighbors(p, i) {
      var r = idxToRow(i);
      var c = idxToCol(i);
      updateBestPointInCell(i);
      updateNeighbor(p, c+1, r);
      updateNeighbor(p, c, r+1);
      updateNeighbor(p, c-1, r);
      updateNeighbor(p, c, r-1);
      updateNeighbor(p, c+1, r+1);
      updateNeighbor(p, c-1, r+1);
      updateNeighbor(p, c-1, r-1);
      updateNeighbor(p, c+1, r-1);
    }

    function updateNeighbor(addedPt, c, r) {
      var i = colRowToIdx(c, r);
      if (i == -1) return;
      var bestPt = bestPoints[i];
      var dist = bestHeap.getValue(i);
      // don't need to update best point if the newly added point is too far away
      // to have an effect.
      // (about 80% of updates are skipped, typically)
      if (distSq(addedPt, bestPt) < dist * dist) {
        updateBestPointInCell(i);
      }
    }

    function updateBestPointInCell(i) {
      var dist = findBestPointInCell(i);
      bestHeap.updateValue(i, dist);
    }

    function findBestPointInCell(idx) {
      // Find a point by finding the best-placed center point in a grid of sub-cells,
      // then recursively dividing the winning sub-cell
      var r = idxToRow(idx);
      var c = idxToCol(idx);
      var p = findBestPointInSubCell(c, r, 0, 0, 1);
      bestPoints[idx] = p;
      return p.pop();
    }

    // c, r: location of parent cell in the grid
    // c1, r1: index of sub-cell at the given z-value
    // z: depth of recursive subdivision
    function findBestPointInSubCell(c, r, c1, r1, z) {
      // using a 3x3 grid instead of 2x2 ... testing showed that 2x2 was more
      // likely to misidentify the sub-cell with the optimal point
      var q = 3;
      var perSide = Math.pow(q, z); // number of cell divisions per axis at this z
      var maxDist = 0;
      var c2, r2, p, best, dist;
      for (var i=0; i<q; i++) {
        for (var j=0; j<q; j++) {
          p = getGridPointInCell(c, r, c1 + i, r1 + j, perSide);
          dist = findDistanceFromNearbyFeatures(maxDist, p, c, r);
          if (dist > maxDist) {
            maxDist = dist;
            best = p;
            c2 = i;
            r2 = j;
          }
        }
      }
      if (z == 2) { // stop subdividing the cell at this level
        best.push(maxDist); // return distance as third element
        return best;
      } else {
        return findBestPointInSubCell(c, r, (c1 + c2)*q, (r1 + r2)*q, z + 1);
      }
    }

    function getGridPointInCell(c, r, c2, r2, n) {
      var dx = (c2 + 0.5) / n;
      var dy = (r2 + 0.5) / n;
      var x = (dx + c) / cols * w + x0;
      var y = (dy + r) / rows * h + y0;
      return [x, y];
    }

    // col, row offsets of a cell and its 8 neighbors
    // (ordered to reject unsuitable points faster)
    var nabes = [
      [0, 0], [0, -1], [-1, 0], [1, 0], [0, 1],
      [-1, 1], [1, -1], [-1, -1], [1, 1]
    ];

    function findDistanceFromNearbyFeatures(memo, xy, c, r) {
      var minDistSq = Infinity;
      var offs, c2, r2, distSq, dist;
      for (var i=0; i<9; i++) {
        offs = nabes[i];
        c2 = offs[0];
        r2 = offs[1];
        distSq = distSqFromPointsInCell(xy, c + c2, r + r2);
        if (distSq < memo * memo) {
          // short-circuit rejection of this point (optimization)
          // -- it is closer than a previously tested point
          return 0;
        }
        if (distSq < minDistSq) {
          minDistSq = distSq;
        }
      }
      dist = Math.sqrt(minDistSq);
      // maintain distance from grid edge
      // (this prevents two sets of dots from appearing right along the edges of
      // rectangular polygons).
      dist = Math.min(dist, spaceFromEdge(xy, c, r));
      return dist;
    }

    function spaceFromEdge(xy, c, r) {
      // ignore edges if cell is internal to the grid
      if (c > 0 && r > 0 && c < cols-1 && r < rows-1) return Infinity;
      var x = xy[0], y = xy[1];
      // exaggerating the true distance to prevent a visible gutter from appearing
      // along the borders of shapes with rectangular edges.
      return Math.min(x - x0, x0 + w - x, y - y0, y0 + h - y) * 3;
    }

    function distSqFromPointsInCell(xy, c, r) {
      var minDist = Infinity, dist;
      var idx = colRowToIdx(c, r);
      var points = idx > -1 ? grid[idx] : []; // off the edge
      for (var i=0; i<points.length; i++) {
        dist = distSq(xy, points[i]);
        if (dist < minDist) minDist = dist;
      }
      return minDist;
    }

    function distSq(a, b) {
      var dx = a[0] - b[0];
      var dy = a[1] - b[1];
      return dx * dx + dy * dy;
    }

    function getRandomPointInCell(i) {
      var r = idxToRow(i);
      var c = idxToCol(i);
      var x = (Math.random() + c) / cols * w + x0;
      var y = (Math.random() + r) / rows * h + y0;
      var p = [x, y];
      return p;
    }

    function getRandomPoint() {
      return getRandomPointInCell(getRandomCell());
    }

    function getRandomCell() {
      return Math.floor(Math.random() * cells);
    }

    function pointIsUsable(xy) {
      var c = pointToCol(xy),
          r = pointToRow(xy);
      var collision = testCollision(xy, c, r) ||
        testEdgeCollision(xy, c, r) ||
        testCollision(xy, c+1, r) ||
        testCollision(xy, c, r+1) ||
        testCollision(xy, c-1, r) ||
        testCollision(xy, c, r-1) ||
        testCollision(xy, c+1, r+1) ||
        testCollision(xy, c-1, r+1) ||
        testCollision(xy, c-1, r-1) ||
        testCollision(xy, c+1, r-1);
      return !collision;
    }

    function testEdgeCollision(xy, c, r) {
      return spaceFromEdge(xy, c, r) < dotSpacing;
    }

    function testCollision(xy, c, r) {
      var i = colRowToIdx(c, r);
      if (i == -1) return false;
      var points = grid[i];
      return testPointCollision(xy, points, dotSpacing);
    }

    function testPointCollision(xy, points, dist) {
      var d2 = dist * dist;
      for (var i=0; i<points.length; i++) {
        if (distSq(xy, points[i]) < d2) {
          return true;
        }
      }
      return false;
    }

    function pointToCol(xy) {
      var dx = xy[0] - x0;
      var c = Math.floor(dx / w * cols);
      if (c < 0) c = 0;
      if (c >= cols) c = cols-1;
      return c;
    }

    function pointToRow(xy) {
      var dy = xy[1] - y0;
      var r = Math.floor(dy / h * rows);
      if (r < 0) r = 0;
      if (r >= rows) r = rows-1;
      return r;
    }

    function colRowToIdx(c, r) {
      if (c < 0 || r < 0 || c >= cols || r >= rows) return -1;
      return r * cols + c;
    }

    function pointToIdx(xy) {
      var c = pointToCol(xy);
      var r = pointToRow(xy);
      var idx = r * cols + c;
      return idx;
    }

    function idxToCol(i) {
      return i % cols;
    }

    function idxToRow(i) {
      return Math.floor(i / cols);
    }
  }

  cmd.dots = function(lyr, arcs, opts) {
    requirePolygonLayer(lyr);
    if (!Array.isArray(opts.fields)) {
      stop("Missing required fields parameter");
    }
    if (layerHasNonNullData(lyr)) {
      opts.fields.forEach(function(f, i) {
        requireDataField(lyr, f);
      });
      (opts.copy_fields || []).forEach(function(f) {
        requireDataField(lyr, f);
      });
    }
    // if (!Array.isArray(opts.colors)) {
    //   stop("Missing required colors parameter");
    // }
    if (Array.isArray(opts.colors)) {
      opts.colors.forEach(validateColor);
    }

    var records = lyr.data ? lyr.data.getRecords() : [];
    var shapes2 = [];
    var records2 = [];
    lyr.shapes.forEach(function(shp, i) {
      var d = records[i];
      if (!d) return;
      var data =  makeDotsForShape(shp, arcs, d, opts);
      for (var j=0, n=data.shapes.length; j<n; j++) {
        shapes2.push(data.shapes[j]);
        records2.push(data.attributes[j]);
      }
    });

    var lyr2 = {
      geometry_type: 'point',
      shapes: shapes2,
      data: new DataTable(records2)
    };
    setOutputLayerName(lyr2, lyr, null, opts);
    return [lyr2];
  };

  function makeDotsForShape(shp, arcs, rec, opts) {
    var retn = {
      shapes: [],
      attributes:[]
    };
    if (!shp) return retn;
    var counts = opts.fields.map(function(f) {
      var val = rec[f] || 0;
      if (opts.per_dot > 0) {
        val = Math.round(val / opts.per_dot);
      }
      return val;
    });
    var indexes = expandCounts(counts);
    var dots = placeDots(shp, arcs, indexes.length, opts);

    // randomize dot sequence so dots of the same color do not always overlap dots of
    // other colors in dense areas.
    // TODO: instead of random shuffling, interleave dot classes more regularly?
    utils.shuffle(indexes);
    var idx, prevIdx = -1;
    var multipart = !!opts.multipart;
    var coords, p, d;
    for (var i=0; i<dots.length; i++) {
      p = dots[i];
      if (!p) continue;
      idx = indexes[i];
      if (p.length === 3 && opts.debug) {
        idx = p.pop(); // way to debug dot placement visually
      }
      if (!multipart || idx != prevIdx) {
        prevIdx = idx;
        retn.shapes.push(coords = []);
        d = getDataRecord(idx, rec, opts);
        retn.attributes.push(d);
      }
      coords.push(p);
    }
    return retn;
  }

  function placeDots(shp, arcs, n, opts) {
    // split apart multipart polygons for more efficient dot placement
    var polys = shp.length > 1 ? explodePolygon(shp, arcs) : [shp];
    var counts = apportionDotsByArea(polys, arcs, n);
    var dots = [];
    for (var i=0; i<polys.length; i++) {
      dots = dots.concat(placeDotsInPolygon(polys[i], arcs, counts[i], opts));
    }
    return dots;
  }

  function apportionDotsByArea(polys, arcs, n) {
    if (polys.length === 1) return [n];
    var areas = polys.map(function(shp) {
      return geom.getPlanarShapeArea(shp, arcs);
    });
    var remainingArea = utils.sum(areas);
    var remainingDots = n;
    return areas.map(function(area, i) {
      var pct = area / remainingArea;
      var count = Math.round(remainingDots * pct);
      remainingDots -= count;
      remainingArea -= area;
      return count;
    });
  }

  function expandCounts(counts) {
    var arr = [];
    counts.forEach(function(n, i) {
      while (n-- > 0) arr.push(i);
    });
    return arr;
  }

  // i: dot class index
  // d: properties of original polygon
  // opts: dots command options
  function getDataRecord(i, d, opts) {
    var o = {};
    var key = opts.save_as || 'fill';
    var values = opts.colors || opts.values;
    if (values) {
      o[key] = values[i];
      o.r = opts.r || 1.3;
    } else if (opts.r) {
      o.r = opts.r;
    }
    if (opts.copy_fields) {
      for (var j=0; j<opts.copy_fields.length; j++) {
        o[opts.copy_fields[j]] = d[opts.copy_fields[j]];
      }
    }
    return o;
  }

  cmd.drop2 = function(catalog, targets, opts) {
    targets.forEach(function(target) {
      cmd.drop(catalog, target.layers, target.dataset, opts);
    });
  };

  cmd.drop = function(catalog, layers, dataset, opts) {
    var updateArcs = false;

    layers.forEach(function(lyr) {
      var fields = lyr.data && opts.fields;
      var allFields = fields && fieldListContainsAll(fields, lyr.data.getFields());
      var deletion = !fields && !opts.geometry && !opts.holes || allFields && opts.geometry;
      if (opts.geometry) {
        updateArcs |= layerHasPaths(lyr);
        delete lyr.shapes;
        delete lyr.geometry_type;
      }
      if (opts.holes && lyr.geometry_type == 'polygon') {
        deleteHoles(lyr, dataset.arcs);
      }
      if (deletion) {
        catalog.deleteLayer(lyr, dataset);
      } else if (allFields) {
        delete lyr.data;
      } else if (fields) {
        opts.fields.forEach(lyr.data.deleteField, lyr.data);
      }
    });

    if (updateArcs) {
      pruneArcs(dataset);
    }
  };

  cmd.evaluateEachFeature = function(lyr, dataset, exp, opts) {
    var n = getFeatureCount(lyr),
        arcs = dataset.arcs,
        compiled, filter;

    var exprOpts = {
      geojson_editor: expressionUsesGeoJSON(exp) ? getFeatureEditor(lyr, dataset) : null
    };

    // TODO: consider not creating a data table -- not needed if expression only references geometry
    if (n > 0 && !lyr.data) {
      lyr.data = new DataTable(n);
    }
    if (opts && opts.where) {
      filter = compileValueExpression(opts.where, lyr, arcs);
    }
    compiled = compileFeatureExpression(exp, lyr, arcs, exprOpts);
    // call compiled expression with id of each record
    for (var i=0; i<n; i++) {
      if (!filter || filter(i)) {
        compiled(i);
      }
    }

    var replacement = exprOpts.geojson_editor ? exprOpts.geojson_editor.done() : null;
    if (replacement) {
      replaceLayerContents(lyr, dataset, replacement);
    }
  };

  var externalCommands = {};

  cmd.external = function(opts) {
    // TODO: remove duplication with -require command
    var _module, moduleFile, moduleName;
    if (!opts.module) {
      stop('Missing required "module" parameter');
    }
    if (cli.isFile(opts.module)) {
      moduleFile = opts.module;
    } else if (cli.isFile(opts.module + '.js')) {
      moduleFile = opts.module + '.js';
    } else {
      moduleName = opts.module;
    }
    if (moduleFile) {
      moduleFile = require$1('path').join(process.cwd(), moduleFile);
    }
    try {
      _module = require$1(moduleFile || moduleName);
      _module(coreAPI);
    } catch(e) {
      // stop(e);
      stop('Unable to load external module:', e.message);
    }
  };

  cmd.registerCommand = function(name, params) {
    var defn = {name: name, options: params.options || []};
    // Add definitions of options common to all commands (TODO: remove duplication)
    defn.options.push({name: 'target'});
    utils.defaults(defn, params);
    validateExternalCommand(defn);
    externalCommands[name] = defn;
  };

  function validateExternalCommand(defn) {
    if (typeof defn.command != 'function') {
      stop('Expected "command" parameter function');
    }
    if (!defn.target) {
      stop('Missing required "target" parameter');
    }
  }

  cmd.runExternalCommand = function(cmdOpts, catalog) {
    var name = cmdOpts.name;
    var cmdDefn = externalCommands[name];
    if (!cmdDefn) {
      stop('Unsupported command:', name);
    }
    var targetType = cmdDefn.target;
    var opts = parseExternalCommand(name, cmdDefn, cmdOpts._);
    var targets = catalog.findCommandTargets(opts.target || '*');
    var target = targets[0];
    if (!target) {
      stop('Missing a target');
    }
    if (targetType == 'layer' && (target.layers.length != 1 || targets.length > 1)) {
      stop('This command only supports targeting a single layer');
    }
    if (targets.length > 1) {
      stop("Targetting layers from multiple datasets is not supported");
    }
    if (targetType == 'layer') {
      cmdDefn.command(target.layers[0], target.dataset, opts.options);
    } else if (targetType == 'layers') {
      cmdDefn.command(target.layers, target.dataset, opts.options);
    }
  };

  function parseExternalCommand(name, cmdDefn, tokens) {
    var parser = new CommandParser();
    var cmd = parser.command(name);
    (cmdDefn.options || []).forEach(function(o) {
      cmd.option(o.name, o);
    });
    var parsed = parser.parseArgv(['-' + name].concat(tokens));
    return parsed[0];
  }

  /* require mapshaper-rectangle, mapshaper-furniture */

  cmd.frame = function(catalog, source, opts) {
    var size, bounds, tmp, dataset;
    if (+opts.width > 0 === false && +opts.pixels > 0 === false) {
      stop("Missing a width or area");
    }
    if (opts.width && opts.height) {
      opts = utils.extend({}, opts);
      // Height is a string containing either a number or a
      //   comma-sep. pair of numbers (range); here we convert height to
      //   an aspect-ratio parameter for the rectangle() function
      opts.aspect_ratio = getAspectRatioArg(opts.width, opts.height);
      // TODO: currently returns max,min aspect ratio, should return in min,max order
      // (rectangle() function should handle max,min argument correctly now anyway)
    }
    tmp = cmd.rectangle(source, opts);
    bounds = getDatasetBounds(tmp);
    if (probablyDecimalDegreeBounds(bounds)) {
      stop('Frames require projected, not geographical coordinates');
    } else if (!getDatasetCRS(tmp)) {
      message('Warning: missing projection data. Assuming coordinates are meters and k (scale factor) is 1');
    }
    size = getFrameSize(bounds, opts);
    if (size[0] > 0 === false) {
      stop('Missing a valid frame width');
    }
    if (size[1] > 0 === false) {
      stop('Missing a valid frame height');
    }
    dataset = {info: {}, layers:[{
      name: opts.name || 'frame',
      data: new DataTable([{
        width: size[0],
        height: size[1],
        bbox: bounds.toArray(),
        type: 'frame'
      }])
    }]};
    catalog.addDataset(dataset);
  };

  // Convert width and height args to aspect ratio arg for the rectangle() function
  function getAspectRatioArg(widthArg, heightArg) {
    // heightArg is a string containing either a number or a
    // comma-sep. pair of numbers (range);
    return heightArg.split(',').map(function(opt) {
      var height = Number(opt),
          width = Number(widthArg);
      if (!opt) return '';
      return width / height;
    }).reverse().join(',');
  }

  furnitureRenderers.frame = function(d) {
    var lineWidth = 1,
        // inset stroke by half of line width
        off = lineWidth / 2,
        obj = importPolygon([[[off, off], [off, d.height - off],
          [d.width - off, d.height - off],
          [d.width - off, off], [off, off]]]);
    utils.extend(obj.properties, {
        fill: 'none',
        stroke: d.stroke || 'black',
        'stroke-width': d['stroke-width'] || lineWidth
    });
    return [obj];
  };

  var Frame = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getAspectRatioArg: getAspectRatioArg
  });

  cmd.filterGeom = function(lyr, arcs, opts) {
    if (!layerHasGeometry(lyr)) {
      stop("Layer is missing geometry");
    }
    if (opts.bbox) {
      filterByBoundsIntersection(lyr, arcs, opts);
    }
    cmd.filterFeatures(lyr, arcs, {remove_empty: true, verbose: false});
  };

  function filterByBoundsIntersection(lyr, arcs, opts) {
    var filter = getBoundsIntersectionFilter(opts.bbox, lyr, arcs);
    editShapes(lyr.shapes, filter);
  }

  function getBoundsIntersectionFilter(bbox, lyr, arcs) {
    var bounds = new Bounds(bbox);
    var filter = lyr.geometry_type == 'point' ?
          getPointInBoundsTest(bounds) :
          getPathBoundsIntersectionTest(bounds, arcs);
    return filter;
  }

  function getPointInBoundsTest(bounds) {
    return function(xy) {
      var contains =  bounds.containsPoint(xy[0], xy[1]);
      return contains ? xy : null;
    };
  }

  // V1 too-simple test: bounding-box intersection
  // internal.getPathBoundsIntersectionTest = function(bounds, arcs) {
  //   return function(path) {
  //     return bounds.intersects(arcs.getSimpleShapeBounds(path)) ? path : null;
  //   };
  // };

  function getPathBoundsIntersectionTest(bounds, arcs) {
    var bbox = bounds.toArray(),
      left = bbox[0],
      bottom = bbox[1],
      right = bbox[2],
      top = bbox[3];

    return function(path) {
      // case: bounding boxes don't intersect -> the path doesn't intersect the box
      if (!bounds.intersects(arcs.getSimpleShapeBounds(path))) {
        return null;
      }
      var intersects = false;
      var ax, ay, bx, by;
      var iter = arcs.getShapeIter(path);

      if (iter.hasNext()) {
        ax = iter.x;
        ay = iter.y;
      }
      while (iter.hasNext()) {
        bx = ax;
        by = ay;
        ax = iter.x;
        ay = iter.y;
        if (segmentOutsideBBox(ax, ay, bx, by, left, bottom, right, top)) continue;
        if (segmentInsideBBox(ax, ay, bx, by, left, bottom, right, top)) {
          intersects = true;
          break;
        }
        if (geom.segmentIntersection(left, top, right, top, ax, ay, bx, by) ||
            geom.segmentIntersection(left, bottom, right, bottom, ax, ay, bx, by) ||
            geom.segmentIntersection(left, bottom, left, top, ax, ay, bx, by) ||
            geom.segmentIntersection(right, bottom, right, top, ax, ay, bx, by)) {
          intersects = true;
          break;
        }
      }

      // case: bbox is entirely inside this ring
      if (!intersects && geom.testPointInRing(left, bottom, path, arcs)) {
        intersects = true;
      }
      return intersects ? path : null;
    };
  }

  // Return a function for testing if a shape (path or point) intersects a bounding box
  // TODO: move this function to a different file
  function getBBoxIntersectionTest(bbox, lyr, arcs) {
    var filter = getBoundsIntersectionFilter(bbox, lyr, arcs);
    return function(shapeId) {
      var shp = lyr.shapes[shapeId];
      if (!shp) return false;
      for (var i=0; i<shp.length; i++) {
        if (filter(shp[i])) return true;
      }
      return false;
    };
  }

  // return array of shape ids
  function findShapesIntersectingBBox(bbox, lyr, arcs) {
    var test = getBBoxIntersectionTest(bbox, lyr, arcs);
    var ids = [];
    for (var i=0; i<lyr.shapes.length; i++) {
      if (test(i)) ids.push(i);
    }
    return ids;
  }

  var FilterGeom = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getBBoxIntersectionTest: getBBoxIntersectionTest,
    findShapesIntersectingBBox: findShapesIntersectingBBox
  });

  cmd.filterFeatures = function(lyr, arcs, opts) {
    var records = lyr.data ? lyr.data.getRecords() : null,
        shapes = lyr.shapes || null,
        n = getFeatureCount(lyr),
        filteredShapes = shapes ? [] : null,
        filteredRecords = records ? [] : null,
        filteredLyr = getOutputLayer(lyr, opts),
        invert = !!opts.invert,
        filter;

    if (opts.expression) {
      filter = compileValueExpression(opts.expression, lyr, arcs);
    }

    if (opts.ids) {
      filter = combineFilters(filter, getIdFilter(opts.ids));
    }

    if (opts.remove_empty) {
      filter = combineFilters(filter, getNullGeometryFilter(lyr, arcs));
    }

    if (opts.bbox) {
      filter = combineFilters(filter, getBBoxIntersectionTest(opts.bbox, lyr, arcs));
    }

    if (!filter) {
      stop("Missing a filter criterion");
    }

    utils.repeat(n, function(shapeId) {
      var result = filter(shapeId);
      if (invert) result = !result;
      if (result === true) {
        if (shapes) filteredShapes.push(shapes[shapeId] || null);
        if (records) filteredRecords.push(records[shapeId] || null);
      } else if (result !== false) {
        stop("Expression must return true or false");
      }
    });

    filteredLyr.shapes = filteredShapes;
    filteredLyr.data = filteredRecords ? new DataTable(filteredRecords) : null;
    if (opts.no_replace) {
      // if adding a layer, don't share objects between source and filtered layer
      filteredLyr = copyLayer(filteredLyr);
    }

    if (opts.verbose !== false) {
      message(utils.format('Retained %,d of %,d features', getFeatureCount(filteredLyr), n));
    }

    return filteredLyr;
  };

  // TODO: update filter command to use this function
  function filterLayerInPlace(lyr, filter, invert) {
    var records = lyr.data ? lyr.data.getRecords() : null,
        shapes = lyr.shapes || null,
        n = getFeatureCount(lyr),
        filteredShapes = shapes ? [] : null,
        filteredRecords = records ? [] : null;
    utils.repeat(n, function(shapeId) {
      var result = filter(shapeId);
      if (invert) result = !result;
      if (result === true) {
        if (shapes) filteredShapes.push(shapes[shapeId] || null);
        if (records) filteredRecords.push(records[shapeId] || null);
      } else if (result !== false) {
        stop("Expression must return true or false");
      }
    });
    lyr.shapes = filteredShapes;
    lyr.data = filteredRecords ? new DataTable(filteredRecords) : null;
  }

  function getIdFilter(ids) {
    var set = new Set(ids);
    return function(i) {
      return set.has(i);
    };
  }

  function getNullGeometryFilter(lyr, arcs) {
    var shapes = lyr.shapes;
    if (lyr.geometry_type == 'polygon') {
      return getEmptyPolygonFilter(shapes, arcs);
    }
    return function(i) {return !!shapes[i];};
  }

  function getEmptyPolygonFilter(shapes, arcs) {
    return function(i) {
      var shp = shapes[i];
      return !!shp && geom.getPlanarShapeArea(shapes[i], arcs) > 0;
    };
  }

  function combineFilters(a, b) {
    return (a && b && function(id) {
        return a(id) && b(id);
      }) || a || b;
  }

  cmd.filterIslands = function(lyr, dataset, optsArg) {
    var opts = utils.extend({sliver_control: 0}, optsArg); // no sliver control
    var arcs = dataset.arcs;
    var removed = 0;
    var filter;
    if (lyr.geometry_type != 'polygon') {
      return;
    }
    if (!opts.min_area && !opts.min_vertices) {
      message("Missing a criterion for filtering islands; use min-area or min-vertices");
      return;
    }

    if (opts.min_area) {
      filter = getSliverFilter(lyr, dataset, opts).filter;
    } else {
      filter = getVertexCountTest(opts.min_vertices, arcs);
    }
    removed += filterIslands(lyr, arcs, filter);
    if (opts.remove_empty) {
      cmd.filterFeatures(lyr, arcs, {remove_empty: true, verbose: false});
    }
    message(utils.format("Removed %'d island%s", removed, utils.pluralSuffix(removed)));
  };

  function getVertexCountTest(minVertices, arcs) {
    return function(path) {
      // first and last vertex in ring count as one
      return geom.countVerticesInPath(path, arcs) <= minVertices;
    };
  }

  function filterIslands(lyr, arcs, ringTest) {
    var removed = 0;
    var counts = new Uint8Array(arcs.size());
    countArcsInShapes(lyr.shapes, counts);

    var pathFilter = function(path, i, paths) {
      if (path.length == 1) { // got an island ring
        if (counts[absArcId(path[0])] === 1) { // and not part of a donut hole
          if (!ringTest || ringTest(path)) { // and it meets any filtering criteria
            // and it does not contain any holes itself
            // O(n^2), so testing this last
            if (!ringHasHoles(path, paths, arcs)) {
              removed++;
              return null;
            }
          }
        }
      }
    };
    editShapes(lyr.shapes, pathFilter);
    return removed;
  }

  function ringIntersectsBBox(ring, bbox, arcs) {
    for (var i=0, n=ring.length; i<n; i++) {
      if (arcs.arcIntersectsBBox(absArcId(ring[i]), bbox)) {
        return true;
      }
    }
    return false;
  }

  // Assumes that ring boundaries to not cross
  function ringHasHoles(ring, rings, arcs) {
    var bbox = arcs.getSimpleShapeBounds2(ring);
    var sibling, p;
    for (var i=0, n=rings.length; i<n; i++) {
      sibling = rings[i];
      // try to avoid expensive point-in-ring test
      if (sibling && sibling != ring && ringIntersectsBBox(sibling, bbox, arcs)) {
        p = arcs.getVertex(sibling[0], 0);
        if (geom.testPointInRing(p.x, p.y, ring, arcs)) {
          return true;
        }
      }
    }
    return false;
  }

  cmd.filterIslands2 = function(lyr, dataset, optsArg) {
    var opts = utils.extend({sliver_control: 0}, optsArg); // no sliver control
    var arcs = dataset.arcs;
    var removed = 0;
    var filter;
    if (lyr.geometry_type != 'polygon') {
      return;
    }
    if (!opts.min_area && !opts.min_vertices) {
      message("Missing a criterion for filtering islands; use min-area or min-vertices");
      return;
    }

    if (opts.min_area) {
      filter = getSliverFilter(lyr, dataset, opts).filter;
    } else {
      filter = getVertexCountTest(opts.min_vertices, arcs);
    }
    removed += filterIslands2(lyr, arcs, filter);
    if (opts.remove_empty) {
      cmd.filterFeatures(lyr, arcs, {remove_empty: true, verbose: false});
    }
    message(utils.format("Removed %'d island%s", removed, utils.pluralSuffix(removed)));
  };


  function filterIslands2(lyr, arcs, ringTest) {
    var removed = 0;
    var counts = new Uint8Array(arcs.size());
    countArcsInShapes(lyr.shapes, counts);

    var pathFilter = function(path, i, paths) {
      if (path.length == 1) { // got an island ring
        if (counts[absArcId(path[0])] === 1) { // and not part of a donut hole
          if (!ringTest || ringTest(path)) { // and it meets any filtering criteria
            // and it does not contain any holes itself
            // O(n^2), so testing this last
            if (!ringHasHoles(path, paths, arcs)) {
              removed++;
              return null;
            }
          }
        }
      }
    };
    editShapes(lyr.shapes, pathFilter);
    return removed;
  }

  cmd.filterFields = function(lyr, names) {
    var table = lyr.data;
    names = names || [];
    requireDataFields(table, names);
    if (!table) return;
    // old method: does not set field order e.g. in CSV output files
    // utils.difference(table.getFields(), names).forEach(table.deleteField, table);
    // the below method sets field order of CSV output, and is generally faster
    var map = mapFieldNames(names);
    lyr.data.update(getRecordMapper(map));
  };

  cmd.renameFields = function(lyr, names) {
    var map = mapFieldNames(names);
    requireDataFields(lyr.data, Object.keys(map));
    utils.defaults(map, mapFieldNames(lyr.data.getFields()));
    lyr.data.update(getRecordMapper(map));
  };

  function mapFieldNames(names) {
    return (names || []).reduce(function(memo, str) {
      var parts = str.split('='),
          dest = utils.trimQuotes(parts[0]),
          src = parts.length > 1 ? utils.trimQuotes(parts[1]) : dest;
      if (!src || !dest) stop("Invalid name assignment:", str);
      memo[src] = dest;
      return memo;
    }, {});
  }

  function getRecordMapper(map) {
    var fields = Object.keys(map);
    return function(src) {
      var dest = {}, key;
      for (var i=0, n=fields.length; i<n; i++) {
        key = fields[i];
        dest[map[key]] = src[key];
      }
      return dest;
    };
  }

  // internal.getRecordMapper = function(map) {
  //   var fields = Object.keys(map);
  //   return new Function("rec", "return {" + fields.map(function(name, i) {
  //     var key = JSON.stringify(name);
  //     return key + ": rec[" + key + "]";
  //   }).join(",") + "}");
  // };

  // Removes points that are far from other points
  cmd.filterPoints = function(lyr, dataset, opts) {
    requireSinglePointLayer(lyr);
    if (opts.group_interval > 0 === false) {
      stop('Expected a positive group_interval parameter');
    }

    // TODO: remove duplication with mapshaper-alpha-shapes.js
    var alphaFilter = getAlphaDistanceFilter(dataset, opts.group_interval);
    var points = getPointsInLayer(lyr);
    var del = Delaunator.from(points);
    var triangles = del.triangles;
    var index = new Uint8Array(points.length);
    var a, b, c, ai, bi, ci;
    for (var i=0, n=triangles.length; i<n; i+=3) {
      // a, b, c: triangle vertices in CCW order
      ai = triangles[i];
      bi = triangles[i+1];
      ci = triangles[i+2];
      a = points[ai];
      b = points[bi];
      c = points[ci];
      if (alphaFilter(a, b) && alphaFilter(b, c) && alphaFilter(a, c)) {
        index[ai] = 1;
        index[bi] = 1;
        index[ci] = 1;
      }
    }
    filterLayerInPlace(lyr, function(shpId) {
      return index[shpId] == 1;
    });
  };

  function joinPointsToPolygons(targetLyr, arcs, pointLyr, opts) {
    // TODO: option to copy points that can't be joined to a new layer
    var joinFunction = getPolygonToPointsFunction(targetLyr, arcs, pointLyr, opts);
    prepJoinLayers(targetLyr, pointLyr);
    return joinTableToLayer(targetLyr, pointLyr.data, joinFunction, opts);
  }

  function joinPolygonsToPoints(targetLyr, polygonLyr, arcs, opts) {
    var joinFunction = getPointToPolygonsFunction(targetLyr, polygonLyr, arcs);
    prepJoinLayers(targetLyr, polygonLyr);
    return joinTableToLayer(targetLyr, polygonLyr.data, joinFunction, opts);
  }

  function prepJoinLayers(targetLyr, srcLyr) {
    if (!targetLyr.data) {
      // create an empty data table if target layer is missing attributes
      targetLyr.data = new DataTable(targetLyr.shapes.length);
    }
    if (!srcLyr.data) {
      stop("Can't join a layer that is missing attribute data");
    }
  }

  function getPolygonToPointsFunction(polygonLyr, arcs, pointLyr, opts) {
    // Build a reverse lookup table for mapping polygon ids to point ids.
    var joinFunction = getPointToPolygonsFunction(pointLyr, polygonLyr, arcs);
    var index = [];
    var firstMatch = !!opts.first_match; // a point is assigned to the first matching polygon
    pointLyr.shapes.forEach(function(shp, pointId) {
      var polygonIds = joinFunction(pointId);
      var n = polygonIds ? polygonIds.length : 0;
      var polygonId;
      for (var i=0; i<n; i++) {
        polygonId = polygonIds[i];
        if (polygonId in index) {
          index[polygonId].push(pointId);
        } else {
          index[polygonId] = [pointId];
        }
        if (firstMatch) break;
      }
    });

    return function(polygonId) {
      return index[polygonId] || null;
    };
  }


  // Returned function gets ids of all polygons that intersect a point (or the first
  //   point of multipoint features). TODO: handle multipoint features properly.
  function getPointToPolygonsFunction(pointLyr, polygonLyr, arcs, opts) {
    var index = new PathIndex(polygonLyr.shapes, arcs),
        points = pointLyr.shapes;

    return function(pointId) {
      var shp = points[pointId],
          polygonIds = shp ? index.findEnclosingShapes(shp[0]) : [];
      return polygonIds.length > 0 ? polygonIds : null;
    };
  }

  var PointPolygonJoin = /*#__PURE__*/Object.freeze({
    __proto__: null,
    joinPointsToPolygons: joinPointsToPolygons,
    joinPolygonsToPoints: joinPolygonsToPoints,
    prepJoinLayers: prepJoinLayers,
    getPolygonToPointsFunction: getPolygonToPointsFunction
  });

  // This is a special-purpose function designed to copy a data field from a points
  // layer to a target polygon layer using a spatial join. It tries to create a continuous
  // mosaic of data values, even if some of the polygons are not intersected by points.
  // It is "fuzzy" because it treats locations in the points file as potentially unreliable.
  //
  // A typical use case is joining geocoded address data containing a neighborhood
  // or precinct field to a Census Block file, in preparation to dissolving the
  // blocks into larger polygons.
  //
  cmd.fuzzyJoin = function(polygonLyr, arcs, src, opts) {
    var pointLyr = src ? src.layer : null;
    if (!pointLyr || !layerHasPoints(pointLyr)) {
      stop('Missing a point layer to join from');
    }
    requireDataField(pointLyr, opts.field);
    requirePolygonLayer(polygonLyr);
    if (opts.dedup_points) {
      cmd.uniq(pointLyr, null, {expression: 'this.x + "~" + this.y + "~" + this.properties[' + JSON.stringify(opts.field) + ']', verbose: false});
    }
    fuzzyJoin(polygonLyr, arcs, pointLyr, opts);
  };

  function fuzzyJoin(polygonLyr, arcs, pointLyr, opts) {
    var field = opts.field;
    // using first_match param: don't let a point be assigned to multiple polygons
    var getPointIds = getPolygonToPointsFunction(polygonLyr, arcs, pointLyr, {first_match: true});
    var getFieldValues = getFieldValuesFunction(pointLyr, field);
    var assignedValues = [];
    var countData = [];
    var modeCounts = [];

    // Step one: assign join values to mode value; resolve ties
    polygonLyr.shapes.forEach(function(shp, i) {
      var pointIds = getPointIds(i) || [];
      var values = getFieldValues(pointIds);
      var modeData = getModeData(values, true);
      var modeValue = modeData.margin > 0 ? modeData.modes[0] : null;
      var isTie = modeValue === null && modeData.modes.length > 1;
      if (isTie) {
        // resolve ties by picking between the candidate data values
        // todo: consider using this method to evaluate near-ties as well
        modeValue = resolveFuzzyJoinTie(modeData.modes, pointLyr, pointIds, field, shp, arcs);
      }
      modeCounts[i] = modeData.count || 0;
      // retain count/mode data, to use later for restoring dropouts
      if (opts.no_dropouts) {
        countData.push(modeData);
      }
      assignedValues.push(modeValue);
    });

    insertFieldValues(polygonLyr, 'join-count', modeCounts);
    insertFieldValues(polygonLyr, field, assignedValues);

    // fill in missing values, etc. using the data-fill function
    cmd.dataFill(polygonLyr, arcs,
      {field: field, weight_field: 'join-count', contiguous: opts.contiguous});

    // restore dropouts
    if (opts.no_dropouts) {
      var missingValues = findDropoutValues(polygonLyr, pointLyr, field);
      if (missingValues.length > 0) {
        restoreDropoutValues(polygonLyr, field, missingValues, countData);
      }
    }

  }

  // Returns a function for converting an array of feature ids to an array of values from a given data field.
  function getFieldValuesFunction(lyr, field) {
    var records = lyr.data.getRecords();
    return function getFieldValues(ids) {
      var values = [], rec;
      for (var i=0; i<ids.length; i++) {
        rec = records[ids[i]];
        values.push(rec[field]);
      }
      return values;
    };
  }

  function findDropoutValues(targetLyr, sourceLyr, field) {
    var sourceValues = getUniqFieldValues(sourceLyr.data.getRecords(), field);
    var targetValues = getUniqFieldValues(targetLyr.data.getRecords(), field);
    var missing = utils.difference(sourceValues, targetValues);
    return missing;
  }

  function restoreDropoutValues(lyr, field, missingValues, countData) {
    var records = lyr.data.getRecords();
    var failures = [];
    var restoredIds = [];

    missingValues.map(function(missingValue) {
      var shpId = findDropoutInsertionShape(missingValue, countData);
      if (shpId > -1 && restoredIds.indexOf(shpId) === -1) {
        records[shpId][field] = missingValue;
        restoredIds.push(shpId);
      } else {
        failures.push(missingValue);
      }
    });

    message('Restored', restoredIds.length, 'dropout value' + utils.pluralSuffix(restoredIds.length));

    // TODO: handle different kinds of failure differently:
    // a. values that point-to-polygon failed to match to a polygon
    // b. multiple dropout values are assigned to the same target polygon
    // c. restoring a dropout results in replacing the only instance of another value
    if (failures.length > 0) {
      message('Failed to restore dropout value(s):', failures.join(', '));
    }
  }

  function findDropoutInsertionShape(value, countData) {
    var id = -1;
    var count = 0;
    countData.forEach(function(d, shpId) {
      var i = d.values.indexOf(value);
      var n = i > -1 ? d.counts[i] : 0;
      if (n > count) {
        id = shpId;
        count = n;
      }
    });
    return id;
  }

  // TODO: move to more appropriate file
  function getPointsToPolygonDistance(points, poly, arcs) {
    // todo: handle multipoint geometry (this function will return an invalid distance
    // if the first point in a multipoint feature falls outside the target polygon
    var p = points[0];
    // unsigned distance to nearest polygon boundary
    return geom.getPointToShapeDistance(p[0], p[1], poly, arcs);
  }

  function resolveFuzzyJoinTie(modeValues, pointLyr, pointIds, field, shp, arcs) {
    var weights = modeValues.map(function() {return 0;}); // initialize to 0
    pointIds.forEach(function(pointId) {
      var coords = pointLyr.shapes[pointId];
      var val = pointLyr.data.getRecordAt(pointId)[field];
      var i = modeValues.indexOf(val);
      if (i === -1) return;
      var dist = getPointsToPolygonDistance(coords, shp, arcs);
      weights[i] += dist;
    });
    // use value with the highest weight
    var maxWeight = Math.max.apply(null, weights);
    var maxValue = modeValues[weights.indexOf(maxWeight)];
    return maxValue;
  }

  // Returns number of arcs that were removed
  function editArcs(arcs, onPoint) {
    var nn2 = [],
        xx2 = [],
        yy2 = [],
        errors = 0,
        n;

    arcs.forEach(function(arc, i) {
      editArc(arc, onPoint);
    });
    arcs.updateVertexData(nn2, xx2, yy2);
    return errors;

    function append(p) {
      if (p) {
        xx2.push(p[0]);
        yy2.push(p[1]);
        n++;
      }
    }

    function editArc(arc, cb) {
      var x, y, xp, yp, retn;
      var valid = true;
      var i = 0;
      n = 0;
      while (arc.hasNext()) {
        x = arc.x;
        y = arc.y;
        retn = cb(append, x, y, xp, yp, i++);
        if (retn === false) {
          valid = false;
          // assumes that it's ok for the arc iterator to be interrupted.
          break;
        }
        xp = x;
        yp = y;
      }
      if (valid && n == 1) {
        // only one valid point was added to this arc (invalid)
        // e.g. this could happen during reprojection.
        // making this arc empty
        // error("An invalid arc was created");
        message("An invalid arc was created");
        valid = false;
      }
      if (valid) {
        nn2.push(n);
      } else {
        // remove any points that were added for an invalid arc
        while (n-- > 0) {
          xx2.pop();
          yy2.pop();
        }
        nn2.push(0); // add empty arc (to preserve mapping from paths to arcs)
        errors++;
      }
    }
  }

  function DatasetEditor(dataset) {
    var layers = [];
    var arcs = [];

    this.done = function() {
      dataset.layers = layers;
      if (arcs.length) {
        dataset.arcs = new ArcCollection(arcs);
        buildTopology(dataset);
      }
    };

    this.editLayer = function(lyr, cb) {
      var type = lyr.geometry_type;
      if (dataset.layers.indexOf(lyr) != layers.length) {
        error('Layer was edited out-of-order');
      }
      if (!type) {
        layers.push(lyr);
        return;
      }
      var shapes = lyr.shapes.map(function(shape, shpId) {
        var shape2 = [], retn, input;
        for (var i=0, n=shape ? shape.length : 0; i<n; i++) {
          input = type == 'point' ? shape[i] : idsToCoords(shape[i]);
          retn = cb(input, i, shape);
          if (!Array.isArray(retn)) continue;
          if (type == 'point') {
            shape2.push(retn);
          } else if (type == 'polygon' || type == 'polyline') {
            extendPathShape(shape2, retn || []);
          }
        }
        return shape2.length > 0 ? shape2 : null;
      });
      layers.push(Object.assign(lyr, {shapes: shapes}));
    };

    function extendPathShape(shape, parts) {
      for (var i=0; i<parts.length; i++) {
        shape.push([arcs.length]);
        arcs.push(parts[i]);
      }
    }

    function idsToCoords(ids) {
      var coords = [];
      var iter = dataset.arcs.getShapeIter(ids);
      while (iter.hasNext()) {
        coords.push([iter.x, iter.y]);
      }
      return coords;
    }
  }

  // Planar densification by an interval
  function densifyPathByInterval(coords, interval, interpolate) {
    if (findMaxPathInterval(coords) < interval) return coords;
    if (!interpolate) {
      interpolate = getIntervalInterpolator(interval);
    }
    var coords2 = [coords[0]], a, b;
    for (var i=1, n=coords.length; i<n; i++) {
      a = coords[i-1];
      b = coords[i];
      if (geom.distance2D(a[0], a[1], b[0], b[1]) > interval + 1e-4) {
        appendArr(coords2, interpolate(a, b));
      }
      coords2.push(b);
    }
    return coords2;
  }

  function getIntervalInterpolator(interval) {
    return function(a, b) {
      var points = [];
      // var rev = a[0] == b[0] ? a[1] > b[1] : a[0] > b[0];
      var dist = geom.distance2D(a[0], a[1], b[0], b[1]);
      var n = Math.round(dist / interval) - 1;
      var dx = (b[0] - a[0]) / (n + 1),
          dy = (b[1] - a[1]) / (n + 1);
      for (var i=1; i<=n; i++) {
        points.push([a[0] + dx * i, a[1] + dy * i]);
      }
      return points;
    };
  }


  // Interpolate the same points regardless of segment direction
  function densifyAntimeridianSegment(a, b, interval) {
    var y1, y2;
    var coords = [];
    var ascending = a[1] < b[1];
    if (a[0] != b[0]) error('Expected an edge segment');
    if (interval > 0 === false) error('Expected a positive interval');
    if (ascending) {
      y1 = a[1];
      y2 = b[1];
    } else {
      y1 = b[1];
      y2 = a[1];
    }
    var y = Math.floor(y1 / interval) * interval + interval;
    while (y < y2) {
      coords.push([a[0], y]);
      y += interval;
    }
    if (!ascending) coords.reverse();
    return coords;
  }

  function appendArr(dest, src) {
    for (var i=0; i<src.length; i++) dest.push(src[i]);
  }

  function findMaxPathInterval(coords) {
    var maxSq = 0, intSq, a, b;
    for (var i=1, n=coords.length; i<n; i++) {
      a = coords[i-1];
      b = coords[i];
      intSq = geom.distanceSq(a[0], a[1], b[0], b[1]);
      if (intSq > maxSq) maxSq = intSq;
    }
    return Math.sqrt(maxSq);
  }

  function projectAndDensifyArcs(arcs, proj) {
    var interval = getDefaultDensifyInterval(arcs, proj);
    var minIntervalSq = interval * interval * 25;
    var p;
    return editArcs(arcs, onPoint);

    function onPoint(append, lng, lat, prevLng, prevLat, i) {
      var pp = p;
      p = proj(lng, lat);
      if (!p) return false; // signal that current arc contains an error

      // Don't try to densify shorter segments (optimization)
      if (i > 0 && geom.distanceSq(p[0], p[1], pp[0], pp[1]) > minIntervalSq) {
        densifySegment(prevLng, prevLat,  pp[0],  pp[1], lng, lat, p[0], p[1], proj, interval)
          .forEach(append);
      }
      append(p);
    }
  }

  // Use the median of intervals computed by projecting segments.
  // We're probing a number of points, because @proj might only be valid in
  // a sub-region of the dataset bbox (e.g. +proj=tpers)
  function findDensifyInterval(bounds, xy, proj) {
    var steps = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9];
    var points = [];
    for (var i=0; i<steps.length; i++) {
      for (var j=0; j<steps.length; j++) {
        points.push([steps[i], steps[j]]);
      }
    }
    var intervals = points.map(function(pos) {
      var x = bounds.xmin + bounds.width() * pos[0];
      var y = bounds.ymin + bounds.height() * pos[1];
      var a = proj(x, y);
      var b = proj(x + xy[0], y + xy[1]);
      return a && b ? geom.distance2D(a[0], a[1], b[0], b[1]) : Infinity;
    }).filter(function(int) {return int < Infinity;});
    return intervals.length > 0 ? utils.findMedian(intervals) : Infinity;
  }

  // Kludgy way to get a useful interval for densifying a bounding box.
  // Uses a fraction of average bbox side length)
  // TODO: improve
  function findDensifyInterval2(bb, proj) {
    var a = proj(bb.centerX(), bb.centerY()),
        c = proj(bb.centerX(), bb.ymin), // right center
        d = proj(bb.xmax, bb.centerY()); // bottom center
    var interval = a && c && d ? (geom.distance2D(a[0], a[1], c[0], c[1]) +
          geom.distance2D(a[0], a[1], d[0], d[1])) / 5000 : Infinity;
    return interval;
  }

  // Returns an interval in projected units
  function getDefaultDensifyInterval(arcs, proj) {
    var xy = getAvgSegment2(arcs),
        bb = arcs.getBounds(),
        intervalA = findDensifyInterval(bb, xy, proj),
        intervalB = findDensifyInterval2(bb, proj),
        interval = Math.min(intervalA, intervalB);
    if (interval == Infinity) {
      error('Densification error');
    }
    return interval;
  }

  // Interpolate points into a projected line segment if needed to prevent large
  //   deviations from path of original unprojected segment.
  // @points (optional) array of accumulated points
  function densifySegment(lng0, lat0, x0, y0, lng2, lat2, x2, y2, proj, interval, points) {
    // Find midpoint between two endpoints and project it (assumes longitude does
    // not wrap). TODO Consider bisecting along great circle path -- although this
    // would not be good for boundaries that follow line of constant latitude.
    var lng1 = (lng0 + lng2) / 2,
        lat1 = (lat0 + lat2) / 2,
        p = proj(lng1, lat1),
        distSq;
    if (!p) return; // TODO: consider if this is adequate for handling proj. errors
    distSq = geom.pointSegDistSq2(p[0], p[1], x0, y0, x2, y2); // sq displacement
    points = points || [];
    // Bisect current segment if the projected midpoint deviates from original
    //   segment by more than the @interval parameter.
    //   ... but don't bisect very small segments to prevent infinite recursion
    //   (e.g. if projection function is discontinuous)
    if (distSq > interval * interval * 0.25 && geom.distance2D(lng0, lat0, lng2, lat2) > 0.01) {
      densifySegment(lng0, lat0, x0, y0, lng1, lat1, p[0], p[1], proj, interval, points);
      points.push(p);
      densifySegment(lng1, lat1, p[0], p[1], lng2, lat2, x2, y2, proj, interval, points);
    }
    return points;
  }

  // Create rectangles around each feature in a layer
  cmd.rectangles = function(targetLyr, targetDataset, opts) {
    if (!layerHasGeometry(targetLyr)) {
      stop("Layer is missing geometric shapes");
    }
    var crsInfo = getDatasetCrsInfo(targetDataset);
    var records = targetLyr.data ? targetLyr.data.getRecords() : null;
    var geometries = targetLyr.shapes.map(function(shp) {
      var bounds = targetLyr.geometry_type == 'point' ?
        getPointFeatureBounds(shp) : targetDataset.arcs.getMultiShapeBounds(shp);
      bounds = applyRectangleOptions(bounds, crsInfo.crs, opts);
      if (!bounds) return null;
      return convertBboxToGeoJSON(bounds.toArray(), opts);
    });
    var geojson = {
      type: 'FeatureCollection',
      features: geometries.map(function(geom, i) {
        var rec = records && records[i] || null;
        if (rec && opts.no_replace) {
          rec = utils.extend({}, rec); // make a copy
        }
        return {
          type: 'Feature',
          properties: rec,
          geometry: geom
        };
      })
    };
    var dataset = importGeoJSON(geojson, {});
    setDatasetCrsInfo(dataset, crsInfo);
    var outputLayers = mergeDatasetsIntoDataset(targetDataset, [dataset]);
    setOutputLayerName(outputLayers[0], targetLyr, null, opts);
    return outputLayers;
  };

  // Create rectangles around one or more target layers
  //
  cmd.rectangle2 = function(target, opts) {
    var datasets = target.layers.map(function(lyr) {
      var dataset = cmd.rectangle({layer: lyr, dataset: target.dataset}, opts);
      setOutputLayerName(dataset.layers[0], lyr, null, opts);
      if (!opts.no_replace) {
        dataset.layers[0].name = lyr.name || dataset.layers[0].name;
      }
      return dataset;
    });
    return mergeDatasetsIntoDataset(target.dataset, datasets);
  };

  cmd.rectangle = function(source, opts) {
    var bounds, crsInfo;
    if (source) {
      bounds = getLayerBounds(source.layer, source.dataset.arcs);
      crsInfo = getDatasetCrsInfo(source.dataset);
    } else if (opts.bbox) {
      bounds = new Bounds(opts.bbox);
      crsInfo = getCrsInfo('wgs84');
    }
    bounds = bounds && applyRectangleOptions(bounds, crsInfo.crs, opts);
    if (!bounds || !bounds.hasBounds()) {
      stop('Missing rectangle extent');
    }
    var geojson = convertBboxToGeoJSON(bounds.toArray(), opts);
    var dataset = importGeoJSON(geojson, {});
    dataset.layers[0].name = opts.name || 'rectangle';
    setDatasetCrsInfo(dataset, crsInfo);
    return dataset;
  };

  function applyRectangleOptions(bounds, crs, opts) {
    var isGeoBox = probablyDecimalDegreeBounds(bounds);
    if (opts.offset) {
      bounds = applyBoundsOffset(opts.offset, bounds, crs);
    }
    if (bounds.area() > 0 === false) return null;
    if (opts.aspect_ratio) {
      bounds = applyAspectRatio(opts.aspect_ratio, bounds);
    }
    if (isGeoBox) {
      bounds = clampToWorldBounds(bounds);
    }
    return bounds;
  }

  // opt: aspect ratio as a single number or a range (e.g. "1,2");
  function applyAspectRatio(opt, bounds) {
    var range = String(opt).split(',').map(parseFloat),
      aspectRatio = bounds.width() / bounds.height(),
      min, max; // min is height limit, max is width limit
    if (range.length == 1) {
      range.push(range[0]);
    } else if (range[0] > range[1]) {
      range.reverse();
    }
    min = range[0];
    max = range[1];
    if (!min && !max) return bounds;
    if (!min) min = -Infinity;
    if (!max) max = Infinity;
    if (aspectRatio < min) {
      bounds.fillOut(min);
    } else if (aspectRatio > max) {
      bounds.fillOut(max);
    }
    return bounds;
  }

  function applyBoundsOffset(offsetOpt, bounds, crs) {
    var offsets = convertFourSides(offsetOpt, crs, bounds);
    bounds.padBounds(offsets[0], offsets[1], offsets[2], offsets[3]);
    return bounds;
  }

  function convertBboxToGeoJSON(bbox, optsArg) {
    var opts = optsArg || {};
    var coords = [[bbox[0], bbox[1]], [bbox[0], bbox[3]], [bbox[2], bbox[3]],
        [bbox[2], bbox[1]], [bbox[0], bbox[1]]];
    if (opts.interval > 0) {
      coords = densifyPathByInterval(coords, opts.interval);
    }
    return opts.geometry_type == 'polyline' ? {
      type: 'LineString',
      coordinates: coords
    } : {
      type: 'Polygon',
      coordinates: [coords]
    };
  }

  var Rectangle = /*#__PURE__*/Object.freeze({
    __proto__: null,
    applyAspectRatio: applyAspectRatio,
    convertBboxToGeoJSON: convertBboxToGeoJSON
  });

  function getSemiMinorAxis(P) {
    return P.a * Math.sqrt(1 - (P.es || 0));
  }

  function getCircleRadiusFromAngle(P, angle) {
    // Using semi-minor axis radius, to prevent overflowing projection bounds
    // when clipping up to the edge of the projectable area
    // TODO: improve (this just gives a safe minimum distance, not the best distance)
    // TODO: modify point buffer function to use angle + ellipsoidal geometry
    return angle * Math.PI / 180 * getSemiMinorAxis(P);
  }

  function getCrsSlug(P) {
    return P.params.proj.param; // kludge
  }

  // 'normal' = the projection is aligned to the Earth's axis
  // (i.e. it has a normal aspect)
  function isRotatedNormalProjection(P) {
    return isAxisAligned(P) && P.lam0 !== 0;
  }

  // Projection is vertically aligned to earth's axis
  function isAxisAligned(P) {
    // TODO: consider projections that may or may not be aligned,
    // depending on parameters
    if (inList(P, 'cassini,gnom,bertin1953,chamb,ob_tran,tpeqd,healpix,rhealpix,' +
      'ocea,omerc,tmerc,etmerc')) {
      return false;
    }
    if (isAzimuthal(P)) {
      return false;
    }
    return true;
  }

  function getBoundingMeridian(P) {
    if (P.lam0 === 0) return 180;
    return getAntimeridian(P.lam0 * 180 / Math.PI);
  }

  // Are the projection's bounds meridians?
  function isMeridianBounded(P) {
    // TODO: add azimuthal projection with lat0 == 0
    // if (inList(P, 'ortho') && P.lam0 === 0) return true;
    return isAxisAligned(P); // TODO: look for exceptions to this
  }

  function isAzimuthal(P) {
    return inList(P,
      'aeqd,gnom,laea,mil_os,lee_os,gs48,alsk,gs50,nsper,tpers,ortho,qsc,stere,ups,sterea');
  }

  function inList(P, str) {
    return str.split(',').includes(getCrsSlug(P));
  }

  // based on d3 implementation of Euler-angle rotation
  // https://github.com/d3/d3-geo/blob/master/src/rotation.js
  // license: https://github.com/d3/d3-geo/blob/master/LICENSE

  function rotateDatasetCoords(dataset, rotation, inv) {
    var proj = getRotationFunction(rotation, inv);
    dataset.layers.filter(layerHasPoints).forEach(function(lyr) {
      projectPointLayer(lyr, proj);
    });
    if (dataset.arcs) {
      projectArcs(dataset.arcs, proj);
    }
  }

  function getRotationFunction(rotation, inv) {
    var f = getRotationFunction2(rotation, inv);
    return function(lng, lat) {
      return f([lng, lat]);
    };
  }

  function getRotationFunction2(rotation, inv) {
    var a = (rotation[0] || 0) * D2R,
        b = (rotation[1] || 0) * D2R,
        c = (rotation[2] || 0) * D2R;
    return function(p) {
      p[0] *= D2R;
      p[1] *= D2R;
      var rotate = inv ? rotatePointInv : rotatePoint;
      rotate(p, a, b, c);
      p[0] *= R2D;
      p[1] *= R2D;
      return p;
    };
  }

  function rotatePoint(p, deltaLam, deltaPhi, deltaGam) {
    if (deltaLam != 0) rotateLambda(p, deltaLam);
    if (deltaPhi !== 0 || deltaGam !== 0) {
      rotatePhiGamma(p, deltaPhi, deltaGam, false);
    }
    return p;
  }

  function rotatePointInv(p, deltaLam, deltaPhi, deltaGam) {
    if (deltaPhi !== 0 || deltaGam !== 0) {
      rotatePhiGamma(p, deltaPhi, deltaGam, true);
    }
    if (deltaLam != 0) rotateLambda(p, -deltaLam);
    return p;
  }

  function rotateLambda(p, deltaLam) {
    var lam = p[0] + deltaLam;
    if (lam > Math.PI) lam -= 2 * Math.PI;
    else if (lam < -Math.PI) lam += 2 * Math.PI;
    p[0] = lam;
  }

  function rotatePhiGamma(p, deltaPhi, deltaGam, inv) {
    var cosDeltaPhi = Math.cos(deltaPhi),
        sinDeltaPhi = Math.sin(deltaPhi),
        cosDeltaGam = Math.cos(deltaGam),
        sinDeltaGam = Math.sin(deltaGam),
        cosPhi = Math.cos(p[1]),
        x = Math.cos(p[0]) * cosPhi,
        y = Math.sin(p[0]) * cosPhi,
        z = Math.sin(p[1]),
        k;
    if (inv) {
      k = z * cosDeltaGam - y * sinDeltaGam;
      p[0] = Math.atan2(y * cosDeltaGam + z * sinDeltaGam, x * cosDeltaPhi + k * sinDeltaPhi);
      p[1] = Math.asin(k * cosDeltaPhi - x * sinDeltaPhi);
    } else {
      k = z * cosDeltaPhi + x * sinDeltaPhi;
      p[0] = Math.atan2(y * cosDeltaGam - k * sinDeltaGam, x * cosDeltaPhi - z * sinDeltaPhi);
      p[1] = Math.asin(k * cosDeltaGam + y * sinDeltaGam);
    }
  }

  cmd.rotate = rotateDataset;

  function rotateDataset(dataset, opts) {
    if (!isLatLngCRS(getDatasetCRS(dataset))) {
      stop('Command requires a lat-long dataset.');
    }
    if (!Array.isArray(opts.rotation) || !opts.rotation.length) {
      stop('Invalid rotation parameter');
    }
    var rotatePoint = getRotationFunction2(opts.rotation, opts.invert);
    var editor = new DatasetEditor(dataset);
    if (dataset.arcs) {
      dataset.arcs.flatten();
    }

    dataset.layers.forEach(function(lyr) {
      var type = lyr.geometry_type;
      editor.editLayer(lyr, getGeometryRotator(type, rotatePoint, opts));
    });
    editor.done();
    if (!opts.debug) {
      buildTopology(dataset);
      cleanProjectedPathLayers(dataset);
    }
  }

  function getGeometryRotator(layerType, rotatePoint, opts) {
    var rings;
    if (layerType == 'point') {
      return function(coords) {
        coords.forEach(rotatePoint);
        return coords;
      };
    }
    if (layerType == 'polyline') {
      return function(coords) {
        coords = densifyPathByInterval(coords, 0.5);
        coords.forEach(rotatePoint);
        return removePolylineCrosses(coords);
      };
    }
    if (layerType == 'polygon') {
      return function(coords, i, shape) {
        if (isWholeWorld(coords)) {
          coords = densifyPathByInterval(coords, 0.5);
        } else {
          coords.forEach(snapToEdge);
          coords = removeCutSegments(coords);
          coords = densifyPathByInterval(coords, 0.5, getInterpolator(0.5));
          coords.forEach(rotatePoint);
          // coords.forEach(snapToEdge);
        }
        if (i === 0) { // first part
          rings = [];
        }
        if (coords.length < 4) {
          debug('Short ring', coords);
          return;
        }
        if (!samePoint(coords[0], lastEl(coords))) {
          error('Open polygon ring');
        }
        rings.push(coords); // accumulate rings
        if (i == shape.length - 1) { // last part
          return opts.debug ? rings : removePolygonCrosses(rings);
        }
      };
    }
    return null; // assume layer has no geometry -- callback should not be called
  }

  function getInterpolator(interval) {
    var interpolate = getIntervalInterpolator(interval);
    return function(a, b) {
      var points;
      if (onPole(a) || onPole(b)) {
        points = [];
      } else if (isEdgeSegment(a, b)) {
        points = densifyAntimeridianSegment(a, b, interval);
      } else if (segmentCrossesAntimeridian(a, b)) {
        // TODO: interpolate up to antimeridian?
        points = [];
      } else {
        points = interpolate(a, b);
      }
      return points;
    };
  }

  cmd.lines = function(lyr, dataset, opts) {
    opts = opts || {};
    if (opts.callouts) {
      requirePointLayer(lyr);
      return pointsToCallouts(lyr, dataset, opts);
    } else if (lyr.geometry_type == 'point') {
      return pointsToLines(lyr, dataset, opts);
    } else if (opts.segments) {
      return [convertShapesToSegments(lyr, dataset)];
    } else if (opts.arcs) {
      return [convertShapesToArcs(lyr, dataset)];
    } else if (lyr.geometry_type == 'polygon') {
      return polygonsToLines(lyr, dataset.arcs, opts);
    } else {
      requirePolygonLayer(lyr, "Command requires a polygon or point layer");
    }
  };

  function convertShapesToArcs(lyr, dataset) {
    var arcs = dataset.arcs;
    var test = getArcPresenceTest(lyr.shapes, arcs);
    var records = [];
    var shapes = [];
    for (var i=0, n=arcs.size(); i<n; i++) {
      if (!test(i)) continue;
      records.push({arcid: i});
      shapes.push([[i]]);
    }
    return {
      geometry_type: 'polyline',
      data: new DataTable(records),
      shapes: shapes
    };
  }

  function convertShapesToSegments(lyr, dataset) {
    var arcs = dataset.arcs;
    var geojson = {type: 'FeatureCollection', features: []};
    var test = getArcPresenceTest(lyr.shapes, arcs);
    var arcId;
    for (var i=0, n=arcs.size(); i<n; i++) {
      arcId = i;
      if (!test(arcId)) continue;
      arcs.forEachArcSegment(arcId, onSeg);
    }
    function onSeg(i1, i2, xx, yy) {
      var a = xx[i1],
          b = yy[i1],
          c = xx[i2],
          d = yy[i2];
      geojson.features.push({
        type: 'Feature',
        properties: {arc: arcId, i1: i1, i2: i2, x1: a, y1: b, x2: c, y2: d},
        geometry: {type: 'LineString', coordinates: [[a, b], [c, d]]}
      });
    }
    var merged = mergeDatasets([dataset, importGeoJSON(geojson, {})]);
    dataset.arcs = merged.arcs;
    // buildTopology(dataset);
    return merged.layers.pop();
  }

  function pointsToLines(lyr, dataset, opts) {
    var geojson = opts.groupby ?
      groupedPointsToLineGeoJSON(lyr, opts.groupby, opts) :
      pointShapesToLineGeometry(lyr.shapes); // no grouping: return single line with no attributes
    var dataset2 = importGeoJSON(geojson);
    var outputLayers = mergeDatasetsIntoDataset(dataset, [dataset2]);
    // if (!opts.no_replace) {
    //   outputLayers[0].name = lyr.name || outputLayers[0].name;
    // }
    setOutputLayerName(outputLayers[0], lyr, null, opts);
    return outputLayers;
  }

  function pointsToCallouts(lyr, dataset, opts) {
    var records = lyr.data ? lyr.data.getRecords() : null;
    var calloutLen = getLayerBounds(lyr).width() / 50;
    var pointToSegment = function(p) {
      return [p, [p[0] + calloutLen, p[1]]];
    };
    var geojson = {
      type: 'FeatureCollection',
      features: lyr.shapes.map(function(shp, i) {
        return {
          type: 'Feature',
          properties: records ? records[i] : null,
          geometry: {
            type: 'MultiLineString',
            coordinates: shp.map(pointToSegment)
          }
        };
      })
    };
    var dataset2 = importGeoJSON(geojson);
    var outputLayers = mergeDatasetsIntoDataset(dataset, [dataset2]);
    setOutputLayerName(outputLayers[0], lyr.name, null, opts);
    return outputLayers;
  }

  function groupedPointsToLineGeoJSON(lyr, field, opts) {
    var groups = [];
    var getGroupId = getCategoryClassifier([field], lyr.data);
    var dataOpts = utils.defaults({fields: [field]}, opts);
    var records = aggregateDataRecords(lyr.data.getRecords(), getGroupId, dataOpts);
    var features;
    lyr.shapes.forEach(function(shape, i) {
      var groupId = getGroupId(i);
      if (groupId in groups === false) {
        groups[groupId] = [];
      }
      groups[groupId].push(shape);
    });
    features = groups.map(function(shapes, i) {
      return {
        type: 'Feature',
        properties: records[i],
        geometry: shapes.length > 1 ? pointShapesToLineGeometry(shapes) : null
      };
    });
    return {
      type: 'FeatureCollection',
      features: features
    };
  }

  // TOOD: automatically convert rings into separate shape parts
  function pointShapesToLineGeometry(shapes) {
    var coords = [];
    forEachPoint(shapes, function(p) {
      coords.push(p.concat());
    });
    return {type: 'LineString', coordinates: coords};
  }

  function polygonsToLines(lyr, arcs, opts) {
    opts = opts || {};
    var filter = opts.where ? compileFeaturePairFilterExpression(opts.where, lyr, arcs) : null,
        decorateRecord = opts.each ? getLineRecordDecorator(opts.each, lyr, arcs) : null,
        classifier = getArcClassifier(lyr.shapes, arcs, {filter: filter}),
        fields = utils.isArray(opts.fields) ? opts.fields : [],
        rankId = 0,
        shapes = [],
        records = [],
        outputLyr;

    if (fields.length > 0 && !lyr.data) {
      stop("Missing a data table");
    }

    addLines(extractOuterLines(lyr.shapes, classifier), 'outer');

    fields.forEach(function(field) {
      var data = lyr.data.getRecords();
      var key = function(a, b) {
        var arec = data[a];
        var brec = data[b];
        if (!arec || !brec || arec[field] === brec[field]) {
          return null;
        }
        return a + '-' + b;
      };
      requireDataField(lyr, field);
      addLines(extractLines(lyr.shapes, classifier(key)), field);
    });

    addLines(extractInnerLines(lyr.shapes, classifier), 'inner');
    outputLyr = createLineLayer(shapes, records);
    setOutputLayerName(outputLyr, lyr, null, opts);
    return outputLyr;

    function addLines(lines, typeName) {
      var attr = lines.map(function(shp, i) {
        var rec = {RANK: rankId, TYPE: typeName};
        if (decorateRecord) decorateRecord(rec, shp);
        return rec;
      });
      shapes = utils.merge(lines, shapes);
      records = utils.merge(attr, records);
      rankId++;
    }
  }


  // kludgy way to implement each= option of -lines command
  function getLineRecordDecorator(exp, lyr, arcs) {
    // repurpose arc classifier function to convert arc ids to shape ids of original polygons
    var procArcId = getArcClassifier(lyr.shapes, arcs)(procShapeIds);
    var compiled = compileFeaturePairExpression(exp, lyr, arcs);
    var tmp;

    function procShapeIds(shpA, shpB) {
      compiled(shpA, shpB, tmp);
    }

    return function(rec, shp) {
      tmp = rec;
      procArcId(shp[0][0]);
      return rec;
    };
  }


  function createLineLayer(lines, records) {
    return {
      geometry_type: 'polyline',
      shapes: lines,
      data: records ? new DataTable(records) : null
    };
  }

  function extractOuterLines(shapes, classifier) {
    var key = function(a, b) {return b == -1 ? String(a) : null;};
    return extractLines(shapes, classifier(key));
  }

  function extractInnerLines(shapes, classifier) {
    var key = function(a, b) {return b > -1 ? a + '-' + b : null;};
    return extractLines(shapes, classifier(key));
  }

  function extractLines(shapes, classify) {
    var lines = [],
        index = {},
        prev = null,
        prevKey = null,
        part;

    traversePaths(shapes, onArc, onPart);

    function onArc(o) {
      var arcId = o.arcId,
          key = classify(arcId),
          isContinuation, line;
      if (key) {
        line = key in index ? index[key] : null;
        isContinuation = key == prevKey && o.shapeId == prev.shapeId && o.partId == prev.partId;
        if (!line) {
          line = [[arcId]]; // new shape
          index[key] = line;
          lines.push(line);
        } else if (isContinuation) {
          line[line.length-1].push(arcId); // extending prev part
        } else {
          line.push([arcId]); // new part
        }

        // if extracted line is split across endpoint of original polygon ring, then merge
        if (o.i == part.arcs.length - 1 &&  // this is last arc in ring
            line.length > 1 &&              // extracted line has more than one part
            line[0][0] == part.arcs[0]) {   // first arc of first extracted part is first arc in ring
          line[0] = line.pop().concat(line[0]);
        }
      }
      prev = o;
      prevKey = key;
    }

    function onPart(o) {
      part = o;
    }

    return lines;
  }

  var Lines = /*#__PURE__*/Object.freeze({
    __proto__: null,
    polygonsToLines: polygonsToLines,
    createLineLayer: createLineLayer,
    extractInnerLines: extractInnerLines
  });

  function getClippingDataset(src, dest, opts) {
    return getUnprojectedBoundingPolygon(src, dest, opts);
  }

  function getUnprojectedBoundingPolygon(src, dest, opts) {
    var dataset;
    if (isCircleClippedProjection(dest) || opts.clip_angle || dest.clip_angle) {
      dataset = getBoundingCircle(src, dest, opts);
    } else if (isRectangleClippedProjection(dest) || opts.clip_bbox) {
      dataset = getBoundingRectangle(dest, opts);
    }
    return dataset || null;
  }

  // If possible, return a lat-long bbox that can be used to
  // test whether data exceeds the projection bounds ands needs to be clipped
  // export function getInnerBoundingBBox(P, opts) {
  //   var bbox = null;
  //   if (opts.clip_bbox) {
  //     bbox = opts.clip_bbox;
  //   } else if (isRectangleClippedProjection(dest)) {
  //     bbox
  //   }
  //   return bbox;
  // }

  // Return projected polygon extent of both clipped and unclipped projections
  function getPolygonDataset$1(src, dest, opts) {
    // use clipping area if projection is clipped
    var dataset = getUnprojectedBoundingPolygon(src, dest, opts);
    if (!dataset) {
      // use entire world if projection is not clipped
      dataset = getBoundingRectangle(dest, {clip_bbox: [-180,-90,180,90]});
    }
    projectDataset(dataset, src, dest, {no_clip: false, quiet: true});
    return dataset;
  }

  // Return projected outline of clipped projections
  function getOutlineDataset(src, dest, opts) {
    var dataset = getUnprojectedBoundingPolygon(src, dest, opts);
    if (dataset) {
      // project, with cutting & cleanup
      projectDataset(dataset, src, dest, {no_clip: false, quiet: true});
      dataset.layers[0].geometry_type = 'polyline';
    }
    return dataset || null;
  }

  function getBoundingRectangle(dest, opts) {
    var bbox = opts.clip_bbox || getDefaultClipBBox(dest);
    var rotation = getRotationParams(dest);
    if (!bbox) error('Missing expected clip bbox.');
    opts = Object.assign({interval: 0.5}, opts); // make sure edges can curve
    var geojson = convertBboxToGeoJSON(bbox, opts);
    var dataset = importGeoJSON(geojson);
    if (rotation) {
      rotateDataset(dataset, {rotation: rotation, invert: true});
    }
    return dataset;
  }

  function getBoundingCircle(src, dest, opts) {
    var angle = opts.clip_angle || dest.clip_angle || getDefaultClipAngle(dest);
    if (!angle) return null;
    verbose(`Using clip angle of ${ +angle.toFixed(2) } degrees`);
    var dist = getClippingRadius(src, angle);
    var cp = getProjCenter(dest);
    // kludge: attach the clipping angle to the CRS, so subsequent commands
    // (e.g. -graticule) can create an outline
    dest.clip_angle = angle;
    var geojson = getCircleGeoJSON(cp, dist, null, opts);
    return importGeoJSON(geojson);
  }

  function isRectangleClippedProjection(P) {
    // TODO: add tmerc, etmerc, ...
    // return inList(P, 'tmerc,utm,etmerc,merc,bertin1953');
    return inList(P, 'merc,bertin1953');
  }

  function getDefaultClipBBox(P) {
    var e = 1e-3;
    var slug = getCrsSlug(P);
    var tmerc = [-179,-90,179,90];
    var bbox = {
      // longlat: [-180, -90, 180, 90],
      tmerc: tmerc,
      utm: tmerc,
      etmerc: tmerc,
      merc: [-180, -89, 180, 89],
      lcc: [-180, -89, 180, 89],
      bertin1953: [-180 + e, -90 + e, 180 - e, 90 - e]
    }[slug];
    return bbox;
  }

  function getClampBBox(P) {
    var bbox;
    if (inList(P, 'merc,lcc')) {
      bbox = getDefaultClipBBox(P);
    }
    return bbox;
  }

  function isCircleClippedProjection(P) {
    return inList(P, 'stere,sterea,ups,ortho,gnom,laea,nsper,tpers');
  }

  function getPerspectiveClipAngle(P) {
    var h = parseFloat(P.params.h.param);
    if (!h || h < 0) {
      return 0;
    }
    var theta = Math.acos(P.a / (P.a + h)) * 180 / Math.PI;
    theta *= 0.995; // reducing a bit to avoid out-of-range errors
    return theta;
  }

  function getDefaultClipAngle(P) {
    var slug = getCrsSlug(P);
    if (slug == 'nsper') return getPerspectiveClipAngle(P);
    if (slug == 'tpers') {
      message('Automatic clipping is not supported for the Tilted Perspective projection');
      return 0;
    }
    return {
      gnom: 60,
      laea: 179,
      ortho: 89.9, // TODO: investigate projection errors closer to 90
      stere: 142,
      sterea: 142,
      ups: 10.5 // TODO: should be 6.5 deg at north pole
    }[slug] || 0;
  }

  function getRotationParams(P) {
    var slug = getCrsSlug(P);
    if (slug == 'bertin1953') return [-16.5,-42];
    if (slug == 'tmerc' || slug == 'utm' || slug == 'etmerc') {
      if (P.lam0 !== 0) return [P.lam0 * 180 / Math.PI];
    }
    return null;
  }


  function getProjCenter(P) {
    var rtod = 180 / Math.PI;
    return [P.lam0 * rtod, P.phi0 * rtod];
  }

  // Convert a clip angle to a distance in meters
  function getClippingRadius(P, angle) {
    return getCircleRadiusFromAngle(P, angle);
  }

  function preProjectionClip(dataset, src, dest, opts) {
    if (!isLatLngCRS(src) || opts.no_clip) return false;
    // rotated normal-aspect projections can generally have a thin slice removed
    // from the rotated antimeridian, instead of clipping them
    var cut = insertPreProjectionCuts(dataset, src, dest);
    var clipped = false;
    var clipData;
    // experimental -- we can probably get away with just clamping some CRSs that
    // have a slightly restricted coord range (e.g. Mercator), instead of doing
    // a clip (more expensive)
    var clampBox = getClampBBox(dest);
    if (clampBox) {
      clampDataset(dataset, clampBox);
    } else {
      clipData = getClippingDataset(src, dest, opts);
    }
    // clip data to projection limits (some projections), if content exceeds the limit
    //
    if (clipData) {
      clipped = clipLayersIfNeeded(dataset, clipData);
    }
    return cut || clipped;
  }

  function clipLayersIfNeeded(dataset, clipData) {
    // Avoid clipping layers that are fully enclosed within the projectable
    // coordinate space (represented by a dataset containing a single
    // polygon layer, @clipData). This avoids performing unnecessary intersection
    // tests on each line segment.
    var layers = dataset.layers.filter(function(lyr) {
      return !layerIsFullyEnclosed(lyr, dataset, clipData);
    });
    if (layers.length > 0) {
      clipLayersInPlace(layers, clipData, dataset, 'clip');
      return true;
    }
    return false;
  }

  // @clipData: a dataset containing a polygon layer
  function layerIsFullyEnclosed(lyr, dataset, clipData) {
    // This test uses the layer's bounding box to represent the extent of the
    // layer, and can produce false negatives.
    var dataBounds = getLayerBounds(lyr, dataset.arcs);
    var enclosed = false;
    clipData.layers[0].shapes.forEach(function(shp, i) {
      enclosed = enclosed || testBoundsInPolygon(dataBounds, shp, clipData.arcs);
    });
    return enclosed;
  }


  function insertPreProjectionCuts(dataset, src, dest) {
    var antimeridian = getAntimeridian(dest.lam0 * 180 / Math.PI);
    // currently only supports adding a single vertical cut to earth axis-aligned
    // map projections centered on a non-zero longitude.
    // TODO: need a more sophisticated kind of cutting to handle other cases
    if (dataset.arcs && isRotatedNormalProjection(dest) && datasetCrossesLon(dataset, antimeridian)) {
      insertVerticalCut(dataset, antimeridian);
      dissolveArcs(dataset);
      return true;
    }
    return false;
  }

  function clampDataset(dataset, bbox) {
    transformPoints(dataset, function(x, y) {
      return [utils.clamp(x, bbox[0], bbox[2]), utils.clamp(y, bbox[1], bbox[3])];
    });
  }

  function datasetCrossesLon(dataset, lon) {
    var crosses = 0;
    dataset.arcs.forEachSegment(function(i, j, xx, yy) {
      var ax = xx[i],
          bx = xx[j];
      if (ax <= lon && bx >= lon || ax >= lon && bx <= lon) crosses++;
    });
    return crosses > 0;
  }

  function insertVerticalCut(dataset, lon) {
    var pathLayers = dataset.layers.filter(layerHasPaths);
    if (pathLayers.length === 0) return;
    var e = 1e-8;
    var bbox = [lon-e, -91, lon+e, 91];
    // densify (so cut line can curve, e.g. Cupola projection)
    var geojson = convertBboxToGeoJSON(bbox, {interval: 0.5});
    var clip = importGeoJSON(geojson);
    clipLayersInPlace(pathLayers, clip, dataset, 'erase');
  }

  // Converts a Proj.4 projection name (e.g. lcc, tmerc) to a Proj.4 string
  // by picking parameters that are appropriate to the extent of the dataset
  // being projected (e.g. standard parallels, longitude of origin)
  // Works for lcc, aea, tmerc, etc.
  // TODO: add more projections
  //
  function expandProjDefn(str, dataset) {
    var mproj = require$1('mproj');
    var proj4, params, bbox, isConic2SP, isCentered, decimals;
    if (str in mproj.internal.pj_list === false) {
      // not a bare projection code -- assume valid projection string in other format
      return str;
    }
    isConic2SP = ['lcc', 'aea'].includes(str);
    isCentered = ['tmerc', 'etmerc'].includes(str);
    proj4 = '+proj=' + str;
    if (isConic2SP || isCentered) {
      bbox = getBBox(dataset); // TODO: support projected datasets
      decimals = getBoundsPrecisionForDisplay(bbox);
      params = isCentered ? getCenterParams(bbox, decimals) : getConicParams(bbox, decimals);
      proj4 += ' ' + params;
      message(`Converted "${str}" to "${proj4}"`);
    }
    return proj4;
  }

  function getBBox(dataset) {
    if (!isLatLngCRS(getDatasetCRS(dataset))) {
      stop('Expected unprojected data');
    }
    return getDatasetBounds(dataset).toArray();
  }

  // See: Savric & Jenny, "Automating the selection of standard parallels for conic map projections"
  // Using one-sixth rule, not the more complicated formula proposed by the authors
  function getConicParams(bbox, decimals) {
    var cx = (bbox[0] + bbox[2]) / 2;
    var h = bbox[3] - bbox[1];
    var sp1 = bbox[1] + 1/6 * h;
    var sp2 = bbox[1] + 5/6 * h;
    return `+lon_0=${ cx.toFixed(decimals) } +lat_1=${ sp1.toFixed(decimals) } +lat_2=${ sp2.toFixed(decimals) }`;
  }

  function getCenterParams(bbox, decimals) {
    var cx = (bbox[0] + bbox[2]) / 2;
    var cy = (bbox[1] + bbox[3]) / 2;
    return `+lon_0=${ cx.toFixed(decimals) } +lat_0=${ cy.toFixed(decimals) }`;
  }

  var ProjectionParams = /*#__PURE__*/Object.freeze({
    __proto__: null,
    expandProjDefn: expandProjDefn,
    getConicParams: getConicParams,
    getCenterParams: getCenterParams
  });

  cmd.proj = function(dataset, catalog, opts) {
    var srcInfo, destInfo, destStr;
    if (opts.init) {
      srcInfo = fetchCrsInfo(opts.init, catalog);
      if (!srcInfo.crs) stop("Unknown projection source:", opts.init);
      setDatasetCrsInfo(dataset, srcInfo);
    }
    if (opts.match) {
      destInfo = fetchCrsInfo(opts.match, catalog);
    } else if (opts.crs) {
      destStr = expandProjDefn(opts.crs, dataset);
      destInfo = getCrsInfo(destStr);
    }
    if (destInfo) {
      projCmd(dataset, destInfo, opts);
    }
  };

  function projCmd(dataset, destInfo, opts) {
    // modify copy of coordinate data when running in web UI, so original shapes
    // are preserved if an error occurs
    var modifyCopy = runningInBrowser(),
        originals = [],
        target = {info: dataset.info || {}};

    if (!destInfo.crs) {
      stop("Missing projection data");
    }

    if (!datasetHasGeometry(dataset)) {
      // still set the crs of datasets that are missing geometry
      setDatasetCrsInfo(dataset, destInfo);
      return;
    }

    var srcInfo = getDatasetCrsInfo(dataset);
    if (!srcInfo.crs) {
      stop("Unable to project -- source coordinate system is unknown");
    }

    if (crsAreEqual(srcInfo.crs, destInfo.crs)) {
      message("Source and destination CRS are the same");
      return;
    }

    if (dataset.arcs) {
      dataset.arcs.flatten(); // bake in any pending simplification
      target.arcs = modifyCopy ? dataset.arcs.getCopy() : dataset.arcs;
    }

    target.layers = dataset.layers.map(function(lyr) {
      if (modifyCopy) {
        originals.push(lyr);
        lyr = copyLayerShapes(lyr);
      }
      return lyr;
    });

    projectDataset(target, srcInfo.crs, destInfo.crs, opts || {});

    // dataset.info.prj = destInfo.prj; // may be undefined
    setDatasetCrsInfo(target, destInfo);

    dataset.arcs = target.arcs;
    originals.forEach(function(lyr, i) {
      // replace original layers with modified layers
      utils.extend(lyr, target.layers[i]);
    });
  }


  // name: a layer identifier, .prj file or projection defn
  // Converts layer ids and .prj files to CRS defn
  // Returns projection defn
  function fetchCrsInfo(name, catalog) {
    var dataset, source, info = {};
    if (/\.prj$/i.test(name)) {
      dataset = importFile(name, {});
      if (dataset) {
        info.prj = dataset.info.prj;
        info.crs = parsePrj(info.prj);
      }
      return info;
    }
    if (catalog && (source = catalog.findSingleLayer(name))) {
      dataset = source.dataset;
      return getDatasetCrsInfo(dataset);
    }
    // assume name is a projection defn
    return getCrsInfo(name);
  }

  function projectDataset(dataset, src, dest, opts) {
    var proj = getProjTransform2(src, dest); // v2 returns null points instead of throwing an error
    var badArcs = 0;
    var badPoints = 0;
    var clipped = preProjectionClip(dataset, src, dest, opts);
    dataset.layers.forEach(function(lyr) {
      if (layerHasPoints(lyr)) {
        badPoints += projectPointLayer(lyr, proj); // v2 compatible (invalid points are removed)
      }
    });
    if (dataset.arcs) {
      if (opts.densify) {
        badArcs = projectAndDensifyArcs(dataset.arcs, proj);
      } else {
        badArcs = projectArcs2(dataset.arcs, proj);
      }
    }

    if (clipped) {
      // TODO: could more selective in cleaning clipped layers
      // (probably only needed when clipped area crosses the antimeridian or includes a pole)
      cleanProjectedPathLayers(dataset);
    }

    if (badArcs > 0 && !opts.quiet) {
      message(`Removed ${badArcs} ${badArcs == 1 ? 'path' : 'paths'} containing unprojectable vertices.`);
    }
    if (badPoints > 0 && !opts.quiet) {
      message(`Removed ${badPoints} unprojectable ${badPoints == 1 ? 'point' : 'points'}.`);
    }
    dataset.info.crs = dest;
  }

  // * Heals cuts in previously split-apart polygons
  // * Removes line intersections
  // * TODO: what if a layer contains polygons with desired overlaps? should
  //   we ignore overlaps between different features?
  function cleanProjectedPathLayers(dataset) {
    // TODO: only clean affected polygons (cleaning all polygons can be slow)
    var polygonLayers = dataset.layers.filter(lyr => lyr.geometry_type == 'polygon');
    // clean options: force a topology update (by default, this only happens when
    // vertices change during cleaning, but reprojection can require a topology update
    // even if clean does not change vertices)
    var cleanOpts = {
      allow_overlaps: true,
      rebuild_topology: true,
      no_arc_dissolve: true,
      quiet: true,
      verbose: false};
    cleanLayers(polygonLayers, dataset, cleanOpts);
   // remove unused arcs from polygon and polyline layers
    // TODO: fix bug that leaves uncut arcs in the arc table
    //   (e.g. when projecting a graticule)
    dissolveArcs(dataset);
  }

  // proj: function to project [x, y] point; should return null if projection fails
  // TODO: fatal error if no points project?
  function projectPointLayer(lyr, proj) {
    var errors = 0;
    editShapes(lyr.shapes, function(p) {
      var p2 = proj(p[0], p[1]);
      if (!p2) errors++;
      return p2; // removes points that fail to project
    });
    return errors;
  }

  function projectArcs(arcs, proj) {
    var data = arcs.getVertexData(),
        xx = data.xx,
        yy = data.yy,
        // old simplification data  will not be optimal after reprojection;
        // re-using for now to avoid error in web ui
        zz = data.zz,
        z = arcs.getRetainedInterval(),
        p;

    for (var i=0, n=xx.length; i<n; i++) {
      p = proj(xx[i], yy[i]);
      if (!p) error('Unprojectable point:', xx[i], yy[i]);
      xx[i] = p[0];
      yy[i] = p[1];
    }
    arcs.updateVertexData(data.nn, xx, yy, zz);
    arcs.setRetainedInterval(z);
  }

  function projectArcs2(arcs, proj) {
    return editArcs(arcs, onPoint);
    function onPoint(append, x, y, prevX, prevY, i) {
      var p = proj(x, y);
      // TODO: prevent arcs with just one point
      if (p) {
        append(p);
      } else {
        return false; // signal that the arc is invalid (no more points will be projected in this arc)
      }
    }
  }

  var Proj = /*#__PURE__*/Object.freeze({
    __proto__: null,
    fetchCrsInfo: fetchCrsInfo,
    projectDataset: projectDataset,
    cleanProjectedPathLayers: cleanProjectedPathLayers,
    projectPointLayer: projectPointLayer,
    projectArcs: projectArcs,
    projectArcs2: projectArcs2
  });

  cmd.graticule = function(dataset, opts) {
    var name = opts.polygon ? 'polygon' : 'graticule';
    var graticule, destInfo;
    if (dataset && !isLatLngDataset(dataset)) {
      // project graticule to match dataset
      destInfo = getDatasetCrsInfo(dataset);
      if (!destInfo.crs) stop("Coordinate system is unknown, unable to create a graticule");
      graticule = opts.polygon ?
        createProjectedPolygon(destInfo.crs, opts) :
        createProjectedGraticule(destInfo.crs, opts);
      setDatasetCrsInfo(graticule, destInfo);
    } else {
      graticule = opts.polygon ?
        createUnprojectedPolygon(opts) :
        createUnprojectedGraticule(opts);
      setDatasetCrsInfo(graticule, getCrsInfo('wgs84'));
    }
    graticule.layers[0].name = name;
    return graticule;
  };

  function createUnprojectedPolygon(opts) {
    var crs = parseCrsString('wgs84');
    return getPolygonDataset$1(crs, crs, opts);
  }

  function createProjectedPolygon(dest, opts) {
    var src = parseCrsString('wgs84');
    return getPolygonDataset$1(src, dest, opts);
  }

  function createUnprojectedGraticule(opts) {
    var src = parseCrsString('wgs84');
    var graticule = importGeoJSON(createGraticule(src, false, opts));
    return graticule;
  }

  function createProjectedGraticule(dest, opts) {
    var src = parseCrsString('wgs84');
    // var outline = getOutlineDataset(src, dest, {inset: 0, geometry_type: 'polyline'});
    var outline = getOutlineDataset(src, dest, {});
    var graticule = importGeoJSON(createGraticule(dest, !!outline, opts));
    projectDataset(graticule, src, dest, {no_clip: false}); // TODO: densify?
    if (outline) {
      graticule = addOutlineToGraticule(graticule, outline);
    }
    buildTopology(graticule); // needed for cleaning to work
    cleanLayers(graticule.layers, graticule, {verbose: false});
    return graticule;
  }

  function addOutlineToGraticule(graticule, outline) {
    var merged = mergeDatasets([graticule, outline]);
    var src = merged.layers.pop();
    var dest = merged.layers[0];
    var records = dest.data.getRecords();
    src.shapes.forEach(function(shp) {
      dest.shapes.push(shp);
      records.push({type: 'outline', value: null});
    });
    return merged;
  }

  // Create graticule as a polyline dataset
  //
  function createGraticule(P, outlined, opts) {
    var interval = opts.interval || 10;
    if (![5,10,15,30,45].includes(interval)) stop('Invalid interval:', interval);
    P.lam0 * 180 / Math.PI;
    var precision = interval > 10 ? 1 : 0.5; // degrees between each vertex
    var xstep = interval;
    var ystep = interval;
    var xstepMajor = 90;
    var xn = Math.round(360 / xstep);
    var yn = Math.round(180 / ystep) + 1;
    var xx = utils.range(xn, -180 + xstep, xstep);
    var yy = utils.range(yn, -90, ystep);
    var meridians = [];
    var parallels = [];
    var edgeMeridians = isMeridianBounded(P) ? getEdgeMeridians(P) : null;
    xx.forEach(function(x) {
      if (edgeMeridians && (tooClose(x, edgeMeridians[0]) || tooClose(x, edgeMeridians[1]))) {
        return;
      }
      createMeridian(x, x % xstepMajor === 0);
    });

    if (edgeMeridians && !outlined) {
      // add meridian lines that will appear on the left and right sides of the
      // projected graticule
      createMeridian(edgeMeridians[0], true);
      createMeridian(edgeMeridians[1], true);
    }

    yy.forEach(function(y) {
      createParallel(y);
    });

    var geojson = {
      type: 'FeatureCollection',
      features: meridians.concat(parallels)
    };
    return geojson;

    function tooClose(a, b) {
      return Math.abs(a - b) < interval / 5;
    }

    function createMeridian(x, extended) {
      var y0 = ystep <= 15 ? ystep : 0;
      createMeridianPart(x, -90 + y0, 90 - y0);
      if (extended && y0 > 0) {
        // adding extensions as separate parts, so if the polar coordinates
        // fail to project, at least the rest of the meridian line will remain
        createMeridianPart(x, -90, -90 + y0);
        createMeridianPart(x, 90 - y0, 90);
      }
    }

    function createMeridianPart(x, ymin, ymax) {
      var coords = densifyPathByInterval([[x, ymin], [x, ymax]], precision);
      meridians.push(graticuleFeature(coords, {type: 'meridian', value: roundCoord$1(x)}));
    }

    function createParallel(y) {
      var coords = densifyPathByInterval([[-180, y], [180, y]], precision);
      parallels.push(graticuleFeature(coords, {type: 'parallel', value: y}));
    }
  }

  // remove tiny offsets
  function roundCoord$1(x) {
    return +x.toFixed(3) || 0;
  }

  function getEdgeMeridians(P) {
    var lon = getBoundingMeridian(P);
    // offs must be larger than gutter width in mapshaper-spherical-cutting.js
    var offs = 2e-8;
    return lon == 180 ? [-180, 180] : [lon - offs, lon + offs];
  }

  function graticuleFeature(coords, o) {
    return {
      type: 'Feature',
      properties: o,
      geometry: {
        type: 'LineString',
        coordinates: coords
      }
    };
  }

  function resetControlFlow(job) {
    job.control = null;
  }

  function stopJob(job) {
    getState(job).stopped = true;
  }

  function jobIsStopped(job) {
    return getState(job).stopped === true;
  }

  function inControlBlock(job) {
    return !!getState(job).inControlBlock;
  }

  function enterActiveBranch(job) {
    var state = getState(job);
    state.inControlBlock = true;
    state.active = true;
    state.complete = true;
  }

  function enterInactiveBranch(job) {
    var state = getState(job);
    state.inControlBlock = true;
    state.active = false;
  }

  function blockWasActive(job) {
    return !!getState(job).complete;
  }

  function inActiveBranch(job) {
    return !!getState(job).active;
  }

  function getState(job) {
    return job.control || (job.control = {});
  }

  function compileIfCommandExpression(expr, catalog, opts) {
    var targetId = opts.layer || opts.target || null;
    var targets = catalog.findCommandTargets(targetId);
    var isSingle = targets.length == 1 && targets[0].layers.length == 1;
    if (targets.length === 0 && targetId) {
      stop('Layer not found:', targetId);
    }
    var ctx;
    if (isSingle) {
      ctx = getLayerProxy(targets[0].layers[0], targets[0].dataset.arcs);
    } else {
      ctx = getNullLayerProxy(targets);
    }
    ctx.global = getStashedVar('defs') || {}; // TODO: remove duplication with mapshaper.expressions.mjs
    var exprOpts = Object.assign({returns: true}, opts);
    var func = compileExpressionToFunction(expr, exprOpts);

    // @geoType: optional geometry type (polygon, polyline, point, null);
    ctx.layer_exists = function(name, geoType) {
      var targets = catalog.findCommandTargets(name, geoType);
      if (targets.length === 0) return false;
      return true;
    };

    ctx.file_exists = function(file) {
      return cli.isFile(file);
    };

    return function() {
      try {
        return func.call(ctx, {}, ctx);
      } catch(e) {
        // if (opts.quiet) throw e;
        stop(e.name, "in expression [" + expr + "]:", e.message);
      }
    };
  }

  function skipCommand(cmdName, job) {
    // allow all control commands to run
    if (jobIsStopped(job)) return true;
    if (isControlFlowCommand(cmdName)) return false;
    return inControlBlock(job) && !inActiveBranch(job);
  }

  cmd.if = function(job, opts) {
    if (inControlBlock(job)) {
      stop('Nested -if commands are not supported.');
    }
    evaluateIf(job, opts);
  };

  cmd.elif = function(job, opts) {
    if (!inControlBlock(job)) {
      stop('-elif command must be preceded by an -if command.');
    }
    evaluateIf(job, opts);
  };

  cmd.else = function(job) {
    if (!inControlBlock(job)) {
      stop('-else command must be preceded by an -if command.');
    }
    if (blockWasActive(job)) {
      enterInactiveBranch(job);
    } else {
      enterActiveBranch(job);
    }
  };

  cmd.endif = function(job) {
    if (!inControlBlock(job)) {
      stop('-endif command must be preceded by an -if command.');
    }
    resetControlFlow(job);
  };

  function isControlFlowCommand(cmd) {
    return ['if','elif','else','endif'].includes(cmd);
  }

  function test(catalog, opts) {
    // var targ = getTargetLayer(catalog, opts);
    if (opts.expression) {
      return compileIfCommandExpression(opts.expression, catalog, opts)();
    }
    // if (opts.empty) {
    //   return layerIsEmpty(targ.layer);
    // }
    // if (opts.not_empty) {
    //   return !layerIsEmpty(targ.layer);
    // }
    return true;
  }

  function evaluateIf(job, opts) {
    if (!blockWasActive(job) && test(job.catalog, opts)) {
      enterActiveBranch(job);
    } else {
      enterInactiveBranch(job);
    }
  }

  cmd.ignore = function(targetLayer, dataset, opts) {
    if (opts.empty && layerIsEmpty(targetLayer)) {
      interrupt('Layer is empty, stopping processing');
    }
  };

  cmd.include = function(opts) {
    var content, obj, context;
    // TODO: handle web context
    if (!opts.file) {
      stop("Missing name of a JS file to load");
    }
    // opts.input is an optional file cache (used by applyCommands())
    cli.checkFileExists(opts.file, opts.input);
    content = cli.readFile(opts.file, 'utf8', opts.input);
    if (typeof content == 'string') {
      if (!/^\s*\{[\s\S]*\}\s*$/.test(content)) {
        stop("Expected a JavaScript object containing key:value pairs");
      }
      try {
        // Try to isolate the imported JS code from the program scope and global environment
        // TODO: consider whether this is desirable... it may be pointless anyway
        //   as long as we're passing through the 'require()' function
        context = getBaseContext();
        context.require = require;
        obj = Function('ctx', 'with(ctx) {return (' + content + ');}').call({}, context);
        // obj = eval('(' + content + ')');
      } catch(e) {
        stop(e.name, 'in JS source:', e.message);
      }
    } else if (typeof content == 'object') {
      // content could be an object if an object is passed to applyCommands()
      obj = content;
    }

    utils.extend(getStashedVar('defs'), obj);
  };

  var MAX_RULE_LEN = 50;

  cmd.info = function(targets, opts) {
    var layers = expandCommandTargets(targets);
    var arr = layers.map(function(o) {
      return getLayerInfo(o.layer, o.dataset);
    });
    message(formatInfo(arr));
    if (opts.save_to) {
      var output = [{
        filename: opts.save_to + (opts.save_to.endsWith('.json') ? '' : '.json'),
        content: JSON.stringify(arr, null, 2)
      }];
      writeFiles(output, opts);
    }
  };

  cmd.printInfo = cmd.info; // old name

  function getLayerInfo(lyr, dataset) {
    var n = getFeatureCount(lyr);
    var o = {
      layer_name: lyr.name,
      geometry_type: lyr.geometry_type,
      feature_count: n,
      null_shape_count: 0,
      null_data_count: lyr.data ? countNullRecords(lyr.data.getRecords()) : n
    };
    if (lyr.shapes && lyr.shapes.length > 0) {
      o.null_shape_count = countNullShapes(lyr.shapes);
      o.bbox = getLayerBounds(lyr, dataset.arcs).toArray();
      o.proj4 = getProjInfo(dataset);
    }
    o.source_file = getLayerSourceFile(lyr, dataset) || null;
    o.attribute_data = getAttributeTableInfo(lyr);
    return o;
  }

  // i: (optional) record index
  function getAttributeTableInfo(lyr, i) {
    if (!lyr.data || lyr.data.size() === 0 || lyr.data.getFields().length === 0) {
      return null;
    }
    var fields = applyFieldOrder(lyr.data.getFields(), 'ascending');
    var valueName = i === undefined ? 'first_value' : 'value';
    return fields.map(function(fname) {
      return {
        field: fname,
        [valueName]: lyr.data.getReadOnlyRecordAt(i || 0)[fname]
      };
    });
  }

  function formatInfo(arr) {
    var str = '';
    arr.forEach(function(info, i) {
      var title =  'Layer:    ' + (info.layer_name || '[unnamed layer]');
      var tableStr = formatAttributeTableInfo(info.attribute_data);
      var tableWidth = measureLongestLine(tableStr);
      var ruleLen = Math.min(Math.max(title.length, tableWidth), MAX_RULE_LEN);
      str += '\n';
      str += utils.lpad('', ruleLen, '=') + '\n';
      str += title + '\n';
      str += utils.lpad('', ruleLen, '-') + '\n';
      str += formatLayerInfo(info);
      str += tableStr;
    });
    return str;
  }

  function formatLayerInfo(data) {
    var str = '';
    str += "Type:     " + (data.geometry_type || "tabular data") + "\n";
    str += utils.format("Records:  %,d\n",data.feature_count);
    if (data.null_shape_count > 0) {
      str += utils.format("Nulls:     %'d", data.null_shape_count) + "\n";
    }
    if (data.geometry_type && data.feature_count > data.null_shape_count) {
      str += "Bounds:   " + data.bbox.join(',') + "\n";
      str += "CRS:      " + data.proj4 + "\n";
    }
    str += "Source:   " + (data.source_file || 'n/a') + "\n";
    return str;
  }

  function formatAttributeTableInfo(arr) {
    if (!arr) return "Attribute data: [none]\n";
    var header = "\nAttribute data\n";
    var valKey = 'first_value' in arr[0] ? 'first_value' : 'value';
    var vals = [];
    var fields = [];
    arr.forEach(function(o) {
      fields.push(o.field);
      vals.push(o[valKey]);
    });
    var maxIntegralChars = vals.reduce(function(max, val) {
      if (utils.isNumber(val)) {
        max = Math.max(max, countIntegralChars(val));
      }
      return max;
    }, 0);
    var col1Arr = ['Field'].concat(fields);
    var col2Arr = vals.reduce(function(memo, val) {
      memo.push(formatTableValue(val, maxIntegralChars));
      return memo;
    }, [valKey == 'first_value' ? 'First value' : 'Value']);
    var col1Chars = maxChars(col1Arr);
    var col2Chars = maxChars(col2Arr);
    var sepStr = (utils.rpad('', col1Chars + 2, '-') + '+' +
        utils.rpad('', col2Chars + 2, '-')).substr(0, MAX_RULE_LEN);
    var sepLine = sepStr + '\n';
    var table = '';
    col1Arr.forEach(function(col1, i) {
      var w = stringDisplayWidth(col1);
      table += ' ' + col1 + utils.rpad('', col1Chars - w, ' ') + ' | ' +
        col2Arr[i] + '\n';
      if (i === 0) table += sepLine; // separator after first line
    });
    return header + sepLine + table + sepLine;
  }

  function measureLongestLine(str) {
    return Math.max.apply(null, str.split('\n').map(function(line) {return stringDisplayWidth(line);}));
  }

  function stringDisplayWidth(str) {
    var w = 0;
    for (var i = 0, n=str.length; i < n; i++) {
      w += charDisplayWidth(str.charCodeAt(i));
    }
    return w;
  }

  // see https://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c
  // this is a simplified version, focusing on double-width CJK chars and ignoring nonprinting etc chars
  function charDisplayWidth(c) {
    if (c >= 0x1100 &&
      (c <= 0x115f || c == 0x2329 || c == 0x232a ||
      (c >= 0x2e80 && c <= 0xa4cf && c != 0x303f) || /* CJK ... Yi */
      (c >= 0xac00 && c <= 0xd7a3) || /* Hangul Syllables */
      (c >= 0xf900 && c <= 0xfaff) || /* CJK Compatibility Ideographs */
      (c >= 0xfe10 && c <= 0xfe19) || /* Vertical forms */
      (c >= 0xfe30 && c <= 0xfe6f) || /* CJK Compatibility Forms */
      (c >= 0xff00 && c <= 0xff60) || /* Fullwidth Forms */
      (c >= 0xffe0 && c <= 0xffe6) ||
      (c >= 0x20000 && c <= 0x2fffd) ||
      (c >= 0x30000 && c <= 0x3fffd))) return 2;
    return 1;
  }

  // TODO: consider polygons with zero area or other invalid geometries
  function countNullShapes(shapes) {
    var count = 0;
    for (var i=0; i<shapes.length; i++) {
      if (!shapes[i] || shapes[i].length === 0) count++;
    }
    return count;
  }

  function countNullRecords(records) {
    var count = 0;
    for (var i=0; i<records.length; i++) {
      if (!records[i]) count++;
    }
    return count;
  }

  function maxChars(arr) {
    return arr.reduce(function(memo, str) {
      var w = stringDisplayWidth(str);
      return w > memo ? w : memo;
    }, 0);
  }

  function formatString(str) {
    var replacements = {
      '\n': '\\n',
      '\r': '\\r',
      '\t': '\\t'
    };
    var cleanChar = function(c) {
      // convert newlines and carriage returns
      // TODO: better handling of non-printing chars
      return c in replacements ? replacements[c] : '';
    };
    str = str.replace(/[\r\t\n]/g, cleanChar);
    return "'" + str + "'";
  }

  function countIntegralChars(val) {
    return utils.isNumber(val) ? (utils.formatNumber(val) + '.').indexOf('.') : 0;
  }

  function formatTableValue(val, integralChars) {
    var str;
    if (utils.isNumber(val)) {
      str = utils.lpad("", integralChars - countIntegralChars(val), ' ') +
        utils.formatNumber(val);
    } else if (utils.isString(val)) {
      str = formatString(val);
    } else if (utils.isDate(val)) {
      str = utils.formatDateISO(val) + ' (Date)';
    } else if (utils.isObject(val)) { // if {} or [], display JSON
      str = JSON.stringify(val);
    } else {
      str = String(val);
    }

    if (typeof str != 'string') {
      // e.g. JSON.stringify converts functions to undefined
      str = '[' + (typeof val) + ']';
    }

    return str;
  }

  var Info = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getLayerInfo: getLayerInfo,
    getAttributeTableInfo: getAttributeTableInfo,
    formatAttributeTableInfo: formatAttributeTableInfo,
    formatTableValue: formatTableValue
  });

  // TODO: make sure that the inlay shapes and data are not shared
  cmd.inlay = function(targetLayers, src, targetDataset, opts) {
    var mergedDataset = mergeLayersForOverlay(targetLayers, targetDataset, src, opts);
    var inlayLyr = mergedDataset.layers[mergedDataset.layers.length - 1];
    requirePolygonLayer(inlayLyr);
    targetLayers.forEach(requirePolygonLayer);
    var eraseSrc = {layer: copyLayer(inlayLyr), dataset: mergedDataset};
    var erasedLayers = cmd.eraseLayers(targetLayers, eraseSrc, mergedDataset, opts);
    var outputLayers = erasedLayers.map(function(lyr0) {
      // similar to applyCommandToLayerSelection() (mapshaper-command-utils.js)
      var lyr1 = copyLayer(inlayLyr);
      var lyr2 = cmd.mergeLayers([lyr0, lyr1], {force: true})[0];
      lyr2.name = lyr0.name;
      return lyr2;
    });
    targetDataset.arcs = mergedDataset.arcs;
    return outputLayers;
  };

  cmd.innerlines = function(lyr, arcs, opts) {
    opts = opts || {};
    requirePolygonLayer(lyr);
    var filter = opts.where ? compileFeaturePairFilterExpression(opts.where, lyr, arcs) : null;
    var classifier = getArcClassifier(lyr.shapes, arcs, {filter: filter});
    var lines = extractInnerLines(lyr.shapes, classifier);
    var outputLyr = createLineLayer(lines, null);

    if (lines.length === 0) {
      message("No shared boundaries were found");
    }
    setOutputLayerName(outputLyr, lyr, null, opts);
    return outputLyr;
  };

  cmd.inspect = function(lyr, arcs, opts) {
    var ids = selectFeatures(lyr, arcs, opts);
    var msg;
    if (ids.length == 1) {
      msg = getFeatureInfo(ids[0], lyr, arcs);
    } else {
      msg = utils.format("Expression matched %d feature%s. Select one feature for details", ids.length, utils.pluralSuffix(ids.length));
    }
    message(msg);
  };

  function getFeatureInfo(id, lyr, arcs) {
      var msg = "Feature " + id + '\n';
      msg += getShapeInfo(id, lyr, arcs);
      msg += formatAttributeTableInfo(getAttributeTableInfo(lyr, id));
      return msg;
  }

  function getShapeInfo(id, lyr, arcs) {
    var shp = lyr.shapes ? lyr.shapes[id] : null;
    var type = lyr.geometry_type;
    var info, msg;
    if (!shp || !type) {
      return 'Geometry: [null]\n';
    }
    msg = 'Geometry\n  Type: ' + type + '\n';
    if (type == 'point') {
      msg += '  Points: ' + shp.length + '\n';
    } else if (type == 'polyline') {
      msg += '  Parts: ' + shp.length + '\n';
    } else if (type == 'polygon') {
      info = getPolygonInfo(shp, arcs);
      msg += utils.format('  Rings: %d cw, %d ccw\n', info.cw, info.ccw);
      msg += '  Planar area: ' + info.area + '\n';
      if (info.sph_area) {
        msg += '  Spherical area: ' + info.sph_area + ' sq. meters\n';
      }
    }
    return msg;
  }

  function getPolygonInfo(shp, arcs) {
    var o = {rings: shp.length, cw: 0, ccw: 0, area: 0};
    var area;
    for (var i=0; i<shp.length; i++) {
      area = geom.getPlanarPathArea(shp[i], arcs);
      if (area > 0) {
        o.cw++;
      } else if (area < 0) {
        o.ccw++;
      }
      o.area += area;
    }
    if (!arcs.isPlanar()) {
      o.sph_area = geom.getSphericalShapeArea(shp, arcs);
    }
    return o;
  }

  function selectFeatures(lyr, arcs, opts) {
    var n = getFeatureCount(lyr),
        ids = [],
        filter;
    if (!opts.expression) {
      stop("Missing a JS expression for selecting a feature");
    }
    filter = compileValueExpression(opts.expression, lyr, arcs);
    utils.repeat(n, function(id) {
      var result = filter(id);
      if (result === true) {
        ids.push(id);
      } else if (result !== false) {
        stop("Expression must return true or false");
      }
    });
    return ids;
  }

  function joinPolygonsViaMosaic(targetLyr, targetDataset, source, opts) {
    var mergedDataset = mergeLayersForOverlay([targetLyr], targetDataset, source, opts);
    var nodes = addIntersectionCuts(mergedDataset, opts);
    var sourceLyr = mergedDataset.layers.pop();
    targetDataset.arcs = mergedDataset.arcs;
    prepJoinLayers(targetLyr, sourceLyr);
    var mergedLyr = {
      geometry_type: 'polygon',
      shapes: targetLyr.shapes.concat(sourceLyr.shapes)
    };
    var mosaicIndex = new MosaicIndex(mergedLyr, nodes, {flat: false});

    var joinOpts = utils.extend({}, opts);
    var joinFunction = getPolygonToPolygonFunction(targetLyr, sourceLyr, mosaicIndex, opts);
    var retn = joinTableToLayer(targetLyr, sourceLyr.data, joinFunction, joinOpts);

    if (opts.interpolate) {
      if (opts.duplication) stop('duplication and interpolate options cannot be used together');
      interpolateFieldsByArea(targetLyr, sourceLyr, mosaicIndex, opts);
    }
    return retn;
  }


  function interpolateFieldsByArea(destLyr, sourceLyr, mosaicIndex, opts) {
    var mosaicRecords = getOverlapDataByTile(destLyr, sourceLyr, mosaicIndex, opts);
    var sourceFields = opts.interpolate;
    var sourceRecords = sourceLyr.data.getRecords();

    // for each destination polygon, calculate interpolated values,
    // using the data calculated in previous steps
    destLyr.data.getRecords().forEach(function(destRec, destId) {
      var tileIds = mosaicIndex.getTileIdsByShapeId(destId);
      var tileRecords = [], i, field;
      for (i=0; i<tileIds.length; i++) {
        tileRecords.push(mosaicRecords[tileIds[i]]);
      }
      for (i=0; i<sourceFields.length; i++) {
        field = sourceFields[i];
        destRec[field] = getInterpolatedValue(field, tileRecords, sourceRecords);
      }
    });
  }

  function getOverlapDataByTile(destLyr, sourceLyr, mosaicIndex, opts) {
    var getShapeArea = opts.planar ? geom.getPlanarShapeArea : geom.getShapeArea;
    var destLen = destLyr.shapes.length;
    var mosaicShapes = mosaicIndex.mosaic;
    var arcs = mosaicIndex.nodes.arcs;
    // initialize data objects for each mosaic tile
    var mosaicRecords = mosaicShapes.map(function(tile, i) {
      var rec = {
        area: getShapeArea(tile, arcs),
        weight: 0,
        sourceId: -1
      };
      return rec;
    });

    // identify the source polygon that overlaps each tile,
    // and calculate the percentage of the source shape represented by each tile
    sourceLyr.shapes.forEach(function(sourceShp, sourceId) {
      var tileIds = mosaicIndex.getTileIdsByShapeId(sourceId + destLen);
      var shapeArea = getShapeArea(sourceShp, arcs);
      var tileRec;
      for (var i=0; i<tileIds.length; i++) {
        tileRec = mosaicRecords[tileIds[i]];
        if (tileRec.sourceId > -1) {
          // overlap in source layer
          continue;
        }
        tileRec.weight = tileRec.area / shapeArea;
        tileRec.sourceId = sourceId;
      }
    });
    return mosaicRecords;
  }


  function getInterpolatedValue(field, tileRecords, sourceRecords) {
    var value = 0, tileRec, sourceRec;
    for (var i=0; i<tileRecords.length; i++) {
      tileRec = tileRecords[i];
      if (tileRec.sourceId == -1) continue;
      sourceRec = sourceRecords[tileRec.sourceId];
      value += tileRec.weight * sourceRec[field];
    }
    return value;
  }

  function getIdConversionFunction(offset, length) {
    return function (mergedIds) {
      var ids = [], id;
      for (var i=0; i<mergedIds.length; i++) {
        id = mergedIds[i] - offset;
        if (id >= 0 && id < length) ids.push(id);
      }
      return ids;
    };
  }

  function getMaxOverlapFunction(destLyr, srcLyr, mosaicIndex) {
    var arcs = mosaicIndex.nodes.arcs;
    var destLen = destLyr.shapes.length;

    function getTotalArea(tileIds) {
      var area = 0;
      for (var i=0; i<tileIds.length; i++) {
        area += geom.getShapeArea(mosaicIndex.mosaic[tileIds[i]], arcs);
      }
      return area;
    }

    return function(destId, srcIds) {
      var destTileIds = mosaicIndex.getTileIdsByShapeId(destId);
      var maxArea = 0;
      var maxId = -1;
      srcIds.forEach(function(srcId, i) {
        var srcTileIds = mosaicIndex.getTileIdsByShapeId(srcId + destLen);
        var sharedIds = utils.intersection(destTileIds, srcTileIds);
        var area = getTotalArea(sharedIds);
        if (area >= maxArea) {
          maxId = srcId;
          maxArea = area;
        }
      });
      if (maxId == -1) error('Geometry error');
      return [maxId];
    };
  }


  // Returned function converts a target layer feature id to multiple source feature ids
  // TODO: option to join the source polygon with the greatest overlapping area
  // TODO: option to ignore source polygon with small overlaps
  //       (as a percentage of the area of one or the other polygon?)
  function getPolygonToPolygonFunction(targetLyr, srcLyr, mosaicIndex, opts) {
    var mergedToSourceIds = getIdConversionFunction(targetLyr.shapes.length, srcLyr.shapes.length);
    var selectMaxOverlap;
    if (opts.largest_overlap) {
      selectMaxOverlap = getMaxOverlapFunction(targetLyr, srcLyr, mosaicIndex);
    }

    return function(targId) {
      var tileIds = mosaicIndex.getTileIdsByShapeId(targId);
      var sourceIds = [], tmp;
      for (var i=0; i<tileIds.length; i++) {
        tmp = mosaicIndex.getSourceIdsByTileId(tileIds[i]);
        tmp = mergedToSourceIds(tmp);
        sourceIds = sourceIds.length > 0 ? sourceIds.concat(tmp) : tmp;
      }
      sourceIds = utils.uniq(sourceIds);
      if (sourceIds.length > 1 && opts.largest_overlap) {
        sourceIds = selectMaxOverlap(targId, sourceIds);
      }
      return sourceIds;
    };
  }

  // Parse a formatted value in DMS DM or D to a numeric value. Returns NaN if unparsable.
  // Delimiters: degrees: D|d|°; minutes: '; seconds: "
  function parseDMS(str) {
    var rxp = /^([nsew+-]?)([0-9.]+)[d°]? ?([0-9.]*)['′]? ?([0-9.]*)["″]? ?([nsew]?)$/i;
    var match = rxp.exec(str.trim());
    var d = NaN;
    var deg, min, sec;
    if (match) {
      deg = match[2] || '0';
      min = match[3] || '0';
      sec = match[4] || '0';
      d = (+deg) + (+min) / 60 + (+sec) / 3600;
      if (/[sw-]/i.test(match[1]) || /[sw]/i.test(match[5])) {
        d = -d;
      }
    }
    return d;
  }

  function findNearestVertices(p, shp, arcs) {
    var p2 = findNearestVertex(p[0], p[1], shp, arcs);
    return findVertexIds(p2.x, p2.y, arcs);
  }


  function snapVerticesToPoint(ids, p, arcs, final) {
    ids.forEach(function(idx) {
      setVertexCoords(p[0], p[1], idx, arcs);
    });
    if (final) {
      // kludge to get dataset to recalculate internal bounding boxes
      arcs.transformPoints(function() {});
    }
  }


  // p: point to snap
  // ids: ids of nearby vertices, possibly including an arc endpoint
  function snapPointToArcEndpoint(p, ids, arcs) {
    var p2, dx, dy;
    ids.forEach(function(idx) {
      if (vertexIsArcStart(idx, arcs)) {
        p2 = getVertexCoords(idx + 1, arcs);
      } else if (vertexIsArcEnd(idx, arcs)) {
        p2 = getVertexCoords(idx - 1, arcs);
      }
    });
    if (!p2) return;
    dx = p2[0] - p[0];
    dy = p2[1] - p[1];
    if (Math.abs(dx) > Math.abs(dy)) {
      p[1] = p2[1]; // snap y coord
    } else {
      p[0] = p2[0];
    }
  }

  // Find ids of vertices with identical coordinates to x,y in an ArcCollection
  // Caveat: does not exclude vertices that are not visible at the
  //   current level of simplification.
  function findVertexIds(x, y, arcs) {
    var data = arcs.getVertexData(),
        xx = data.xx,
        yy = data.yy,
        ids = [];
    for (var i=0, n=xx.length; i<n; i++) {
      if (xx[i] == x && yy[i] == y) ids.push(i);
    }
    return ids;
  }

  function getVertexCoords(i, arcs) {
    var data = arcs.getVertexData();
    return [data.xx[i], data.yy[i]];
  }

  function vertexIsArcEnd(idx, arcs) {
    // Test whether the vertex at index @idx is the endpoint of an arc
    var data = arcs.getVertexData(),
        ii = data.ii,
        nn = data.nn;
    for (var j=0, n=ii.length; j<n; j++) {
      if (idx === ii[j] + nn[j] - 1) return true;
    }
    return false;
  }

  function vertexIsArcStart(idx, arcs) {
    var ii = arcs.getVertexData().ii;
    for (var j=0, n=ii.length; j<n; j++) {
      if (idx === ii[j]) return true;
    }
    return false;
  }

  function setVertexCoords(x, y, i, arcs) {
    var data = arcs.getVertexData();
    data.xx[i] = x;
    data.yy[i] = y;
  }

  function findNearestVertex(x, y, shp, arcs, spherical) {
    var calcLen = spherical ? geom.greatCircleDistance : geom.distance2D,
        minLen = Infinity,
        minX, minY, dist, iter;
    for (var i=0; i<shp.length; i++) {
      iter = arcs.getShapeIter(shp[i]);
      while (iter.hasNext()) {
        dist = calcLen(x, y, iter.x, iter.y);
        if (dist < minLen) {
          minLen = dist;
          minX = iter.x;
          minY = iter.y;
        }
      }
    }
    return minLen < Infinity ? {x: minX, y: minY} : null;
  }

  var VertexUtils = /*#__PURE__*/Object.freeze({
    __proto__: null,
    findNearestVertices: findNearestVertices,
    snapVerticesToPoint: snapVerticesToPoint,
    snapPointToArcEndpoint: snapPointToArcEndpoint,
    findVertexIds: findVertexIds,
    getVertexCoords: getVertexCoords,
    vertexIsArcEnd: vertexIsArcEnd,
    vertexIsArcStart: vertexIsArcStart,
    setVertexCoords: setVertexCoords,
    findNearestVertex: findNearestVertex
  });

  // Returns x,y coordinates of the point that is at the midpoint of each polyline feature
  // Uses 2d cartesian geometry
  // TODO: optionally use spherical geometry
  function polylineToMidpoints(shp, arcs, opts) {
    if (!shp) return null;
    var points = shp.map(function(path) {
      return findPathMidpoint(path, arcs, false);
    });
    return points;
  }

  function findPathMidpoint(path, arcs, useNearestVertex) {
    var halfLen = calcPathLen(path, arcs, false) / 2;
    var partialLen = 0;
    var p;
    forEachSegmentInPath(path, arcs, function(i, j, xx, yy) {
      var a = xx[i],
          b = yy[i],
          c = xx[j],
          d = yy[j];
      if (p) return;
      if (halfLen > 0 === false) {
        return [a, b];
      }
      var segLen = distance2D(a, b, c, d);
      var k;
      if (partialLen + segLen >= halfLen) {
        k = (halfLen - partialLen) / segLen;
        if (useNearestVertex) {
          k = k < 0.5 ? 0 : 1;
        }
        // p = [a + k * (c - a), b + k * (d - b)];
        p = [(1 - k) * a + k * c, (1 - k) * b + k * d];
      }
      partialLen += segLen;
    });
    if (!p) {
      error('Geometry error');
    }
    return p;
  }

  // Returns x,y coordinates of the vertex that is closest to the bbox center point
  //   (uses part with the largest-area bbox in )
  // TODO: explore other methods for replacing a polyline with a point.
  function polylineToPoint(shp, arcs, opts) {
    var spherical = !arcs.isPlanar();
    var part = !shp ? null : (shp.length == 1 ? shp[0] : findLongestPolylinePart(shp, arcs, spherical));
    if (!part) return null;
    var bbox = arcs.getSimpleShapeBounds(part);
    var p = findNearestVertex(bbox.centerX(), bbox.centerY(), [part], arcs, spherical);
    return p;
  }

  function findLongestPolylinePart(shp, arcs, spherical) {
    var maxLen = 0;
    var maxPart = null;
    shp.forEach(function(path) {
      var len = geom.calcPathLen(path, arcs, spherical);
      if (len > maxLen) {
        maxLen = len;
        maxPart = path;
      }
    });
    return maxPart;
  }

  cmd.createPointLayer = function(srcLyr, dataset, opts) {
    var destLyr = getOutputLayer(srcLyr, opts);
    var arcs = dataset.arcs;
    if (opts.intersections) {
      testIntersections(arcs);
      destLyr = srcLyr;
    } else if (opts.interpolated) {
      // TODO: consider making attributed points, including distance from origin
      destLyr.shapes = interpolatedPointsFromVertices(srcLyr, dataset, opts);
    } else if (opts.vertices) {
      destLyr.shapes = pointsFromVertices(srcLyr, arcs);
    } else if (opts.vertices2) {
      destLyr.shapes = pointsFromVertices2(srcLyr, arcs);
    } else if (opts.endpoints) {
      destLyr.shapes = pointsFromEndpoints(srcLyr, arcs);
    } else if (opts.x || opts.y) {
      destLyr.shapes = pointsFromDataTable(srcLyr.data, opts);
    } else if (srcLyr.geometry_type == 'polygon') {
      destLyr.shapes = pointsFromPolygons(srcLyr, arcs, opts);
    } else if (opts.midpoints) {
      requirePolylineLayer(srcLyr);
      destLyr.shapes = midpointsFromPolylines(srcLyr, arcs);
    } else if (srcLyr.geometry_type == 'polyline') {
      destLyr.shapes = pointsFromPolylines(srcLyr, arcs);
    } else if (!srcLyr.geometry_type) {
      destLyr.shapes = pointsFromDataTableAuto(srcLyr.data);
    } else {
      stop("Expected a polygon or polyline layer");
    }
    destLyr.geometry_type = 'point';

    var nulls = destLyr.shapes.reduce(function(sum, shp) {
      if (!shp) sum++;
      return sum;
    }, 0);

    if (nulls > 0) {
      message(utils.format('%,d of %,d points are null', nulls, destLyr.shapes.length));
    }
    if (srcLyr.data) {
      destLyr.data = opts.no_replace ? srcLyr.data.clone() : srcLyr.data;
    }
    return destLyr;
  };

  // TODO: finish testing stripe count functions and remove
  function testIntersections(arcs) {
    var pointCount =  arcs.getFilteredPointCount(),
        arcCount = arcs.size(),
        segCount = pointCount - arcCount,
        stripes = calcSegmentIntersectionStripeCount2(arcs),
        stripes2 = Math.ceil(stripes / 10),
        stripes3 = stripes * 10,
        stripes4 = calcSegmentIntersectionStripeCount(arcs);

    console.log("points:", pointCount, "arcs:", arcCount, "segs:", segCount);
    [stripes2, stripes, stripes3, stripes4].forEach(function(n) {
      console.time(n + ' stripes');
      findSegmentIntersections(arcs, {stripes: n});
      console.timeEnd(n + ' stripes');
    });
  }

  function interpolatePointsAlongArc(ids, arcs, interval) {
    var iter = arcs.getShapeIter(ids);
    var distance = arcs.isPlanar() ? geom.distance2D : geom.greatCircleDistance;
    var coords = [];
    var elapsedDist = 0;
    var prevX, prevY;
    var segLen, k, p;
    if (iter.hasNext()) {
      coords.push([iter.x, iter.y]);
      prevX = iter.x;
      prevY = iter.y;
    }
    while (iter.hasNext()) {
      segLen = distance(prevX, prevY, iter.x, iter.y);
      while (elapsedDist + segLen >= interval) {
        k = (interval - elapsedDist) / segLen;
        // TODO: consider using great-arc distance for lat-long points
        p = interpolatePoint2D(prevX, prevY, iter.x, iter.y, k);
        elapsedDist = 0;
        coords.push(p);
        prevX = p[0];
        prevY = p[1];
        segLen = distance(prevX, prevY, iter.x, iter.y);
      }
      elapsedDist += segLen;
      prevX = iter.x;
      prevY = iter.y;
    }
    if (elapsedDist > 0) {
      coords.push([prevX, prevY]);
    }
    return coords;
  }

  function interpolatedPointsFromVertices(lyr, dataset, opts) {
    var interval = convertIntervalParam(opts.interval, getDatasetCRS(dataset));
    var coords;
    if (interval > 0 === false) stop("Invalid interpolation interval:", opts.interval);
    if (lyr.geometry_type != 'polyline') stop("Expected a polyline layer");
    return lyr.shapes.map(function(shp, shpId) {
      coords = [];
      if (shp) shp.forEach(nextPart);
      return coords.length > 0 ? coords : null;
    });
    function nextPart(ids) {
      var points = interpolatePointsAlongArc(ids, dataset.arcs, interval);
      coords = coords.concat(points);
    }
  }

  // Unique vertices within each feature
  function pointsFromVertices(lyr, arcs, opts) {
    var coords, index;
    if (lyr.geometry_type != "polygon" && lyr.geometry_type != 'polyline') {
      stop("Expected a polygon or polyline layer");
    }
    return lyr.shapes.map(function(shp, shpId) {
      coords = [];
      index = {}; // TODO: use more efficient index
      (shp || []).forEach(nextPart);
      return coords.length > 0 ? coords : null;
    });

    function addPoint(p) {
      var key = p.x + '~' + p.y;
      if (key in index === false) {
        index[key] = true;
        coords.push([p.x, p.y]);
      }
    }

    function nextPart(ids) {
      var iter = arcs.getShapeIter(ids);
      while (iter.hasNext()) {
        addPoint(iter);
      }
    }
  }

  // Simple conversion of path vertices to points (duplicate locations not removed)
  // TODO: Provide some way to rebuild paths from points (e.g. multipart features)
  function pointsFromVertices2(lyr, arcs, opts) {
    var coords;
    if (lyr.geometry_type != "polygon" && lyr.geometry_type != 'polyline') {
      stop("Expected a polygon or polyline layer");
    }
    return lyr.shapes.map(function(shp, shpId) {
      coords = [];
      (shp || []).forEach(nextPart);
      return coords.length > 0 ? coords : null;
    });

    function nextPart(ids) {
      var iter = arcs.getShapeIter(ids);
      while (iter.hasNext()) {
        coords.push([iter.x, iter.y]);
      }
    }
  }

  function pointsFromEndpoints(lyr, arcs) {
    var coords, index;
    if (lyr.geometry_type != "polygon" && lyr.geometry_type != 'polyline') {
      stop("Expected a polygon or polyline layer");
    }
    return lyr.shapes.map(function(shp, shpId) {
      coords = [];
      index = {}; // TODO: use more efficient index
      (shp || []).forEach(nextPart);
      return coords.length > 0 ? coords : null;
    });

    function addPoint(p) {
      var key = p.x + '~' + p.y;
      if (key in index === false) {
        index[key] = true;
        coords.push([p.x, p.y]);
      }
    }

    function nextPart(ids) {
      for (var i=0; i<ids.length; i++) {
        addPoint(arcs.getVertex(ids[i], 0));
        addPoint(arcs.getVertex(ids[i], -1));
      }
    }
  }

  function midpointsFromPolylines(lyr, arcs, opts) {
    return lyr.shapes.map(function(shp) {
      return polylineToMidpoints(shp, arcs);
    });
  }

  function pointsFromPolylines(lyr, arcs, opts) {
    return lyr.shapes.map(function(shp) {
      var p = polylineToPoint(shp, arcs);
      return p ? [[p.x, p.y]] : null;
    });
  }

  function pointsFromPolygons(lyr, arcs, opts) {
    var func = opts.inner ? findAnchorPoint : geom.getShapeCentroid;
    return lyr.shapes.map(function(shp) {
      var p = func(shp, arcs);
      return p ? [[p.x, p.y]] : null;
    });
  }

  function coordinateFromValue(val) {
    var tmp;
    if (utils.isFiniteNumber(val)) {
      return val;
    }
    // exclude empty string (not a valid coordinate, but would get coerced to 0)
    if (utils.isString(val) && val !== '') {
      tmp = +val;
      if (utils.isFiniteNumber(tmp)) {
        return tmp;
      }
      tmp = parseDMS(val); // try to parse as DMS
      if (utils.isFiniteNumber(tmp)) {
        return tmp;
      }
    }
    return NaN;
  }

  function findXField(fields) {
    var rxp = /^(lng|long?|longitude|x)$/i;
    return utils.find(fields, function(name) {
      return rxp.test(name);
    });
  }

  function findYField(fields) {
    var rxp = /^(lat|latitude|y)$/i;
    return utils.find(fields, function(name) {
      return rxp.test(name);
    });
  }

  function pointsFromDataTableAuto(data) {
    var fields = data ? data.getFields() : [];
    var opts = {
      x: findXField(fields),
      y: findYField(fields)
    };
    return pointsFromDataTable(data, opts);
  }

  function pointsFromDataTable(data, opts) {
    if (!data) stop("Layer is missing a data table");
    if (!opts.x || !opts.y || !data.fieldExists(opts.x) || !data.fieldExists(opts.y)) {
      stop("Missing x,y data fields");
    }

    return data.getRecords().map(function(rec) {
      var x = coordinateFromValue(rec[opts.x]),
          y = coordinateFromValue(rec[opts.y]);
      if (isNaN(x) || isNaN(y)) {
        return null;
      }
      return [[x, y]];
    });
  }

  var Points = /*#__PURE__*/Object.freeze({
    __proto__: null,
    pointsFromPolygons: pointsFromPolygons,
    coordinateFromValue: coordinateFromValue,
    findXField: findXField,
    findYField: findYField
  });

  function joinPolygonsViaPoints(targetLyr, targetDataset, source, opts) {

    var sourceLyr = source.layer,
        sourceDataset = source.dataset,
        pointLyr, retn;

    if (targetLyr.shapes.length > sourceLyr.shapes.length) {
      // convert target polygons to points, then join source data to points
      pointLyr = pointsFromPolygonsForJoin(targetLyr, targetDataset);
      retn = joinPolygonsToPoints(pointLyr, sourceLyr, sourceDataset.arcs, opts);
      targetLyr.data = pointLyr.data;
    } else {
      // convert source polygons to points, then join points to target polygons
      pointLyr = pointsFromPolygonsForJoin(sourceLyr, sourceDataset);
      retn = joinPointsToPolygons(targetLyr, targetDataset.arcs, pointLyr, opts);
    }
    return retn;
  }

  function pointsFromPolygonsForJoin(lyr, dataset) {
    // TODO use faster method to get inner points
    return {
      geometry_type: 'point',
      shapes: pointsFromPolygons(lyr, dataset.arcs, {inner: true}),
      data: lyr.data // TODO copy if needed
    };
  }

  function joinPolygonsToPolygons(targetLyr, targetDataset, source, opts) {
    if (opts.point_method) {
      return joinPolygonsViaPoints(targetLyr, targetDataset, source, opts);
    } else {
      return joinPolygonsViaMosaic(targetLyr, targetDataset, source, opts);
    }
  }

  function pointsFromPolylinesForJoin(lyr, dataset) {
    var shapes = lyr.shapes.map(function(shp) {
      return polylineToMidpoints(shp, dataset.arcs);
    });
    return {
      geometry_type: 'point',
      shapes: shapes,
      data: lyr.data // TODO copy if needed
    };
  }

  function validateOpts(opts) {
    if (!opts.point_method) {
      stop('The "point-method" flag is required for polyline-polygon joins');
    }
  }

  function joinPolylinesToPolygons(targetLyr, targetDataset, source, opts) {
    validateOpts(opts);
    var pointLyr = pointsFromPolylinesForJoin(source.layer, source.dataset);
    var retn = joinPointsToPolygons(targetLyr, targetDataset.arcs, pointLyr, opts);
    return retn;
  }

  function joinPolygonsToPolylines(targetLyr, targetDataset, source, opts) {
    validateOpts(opts);
    var pointLyr = pointsFromPolylinesForJoin(targetLyr, targetDataset);
    var retn = joinPolygonsToPoints(pointLyr, source.layer, source.dataset.arcs, opts);
    targetLyr.data = pointLyr.data;
    return retn;
  }

  class TinyQueue {
      constructor(data = [], compare = defaultCompare) {
          this.data = data;
          this.length = this.data.length;
          this.compare = compare;

          if (this.length > 0) {
              for (let i = (this.length >> 1) - 1; i >= 0; i--) this._down(i);
          }
      }

      push(item) {
          this.data.push(item);
          this.length++;
          this._up(this.length - 1);
      }

      pop() {
          if (this.length === 0) return undefined;

          const top = this.data[0];
          const bottom = this.data.pop();
          this.length--;

          if (this.length > 0) {
              this.data[0] = bottom;
              this._down(0);
          }

          return top;
      }

      peek() {
          return this.data[0];
      }

      _up(pos) {
          const {data, compare} = this;
          const item = data[pos];

          while (pos > 0) {
              const parent = (pos - 1) >> 1;
              const current = data[parent];
              if (compare(item, current) >= 0) break;
              data[pos] = current;
              pos = parent;
          }

          data[pos] = item;
      }

      _down(pos) {
          const {data, compare} = this;
          const halfLength = this.length >> 1;
          const item = data[pos];

          while (pos < halfLength) {
              let left = (pos << 1) + 1;
              let best = data[left];
              const right = left + 1;

              if (right < this.length && compare(data[right], best) < 0) {
                  left = right;
                  best = data[right];
              }
              if (compare(best, item) >= 0) break;

              data[pos] = best;
              pos = left;
          }

          data[pos] = item;
      }
  }

  function defaultCompare(a, b) {
      return a < b ? -1 : a > b ? 1 : 0;
  }

  /*
  ISC License

  Copyright (c) 2017, Vladimir Agafonkin

  Permission to use, copy, modify, and/or distribute this software for any purpose
  with or without fee is hereby granted, provided that the above copyright notice
  and this permission notice appear in all copies.

  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  THIS SOFTWARE.
  */

  var earthRadius = 6371;
  var rad = Math.PI / 180;

  function around(index, lng, lat, maxResults, maxDistance, predicate) {
      var maxHaverSinDist = 1, result = [];

      if (maxResults === undefined) maxResults = Infinity;
      if (maxDistance !== undefined) maxHaverSinDist = haverSin(maxDistance / earthRadius);

      // a distance-sorted priority queue that will contain both points and kd-tree nodes
      var q = new TinyQueue([], compareDist);

      // an object that represents the top kd-tree node (the whole Earth)
      var node = {
          left: 0, // left index in the kd-tree array
          right: index.ids.length - 1, // right index
          axis: 0, // 0 for longitude axis and 1 for latitude axis
          dist: 0, // will hold the lower bound of children's distances to the query point
          minLng: -180, // bounding box of the node
          minLat: -90,
          maxLng: 180,
          maxLat: 90
      };

      var cosLat = Math.cos(lat * rad);
      var right, left, item;

      while (node) {
          right = node.right;
          left = node.left;

          if (right - left <= index.nodeSize) { // leaf node

              // add all points of the leaf node to the queue
              for (var i = left; i <= right; i++) {
                  item = index.points[index.ids[i]];
                  if (!predicate || predicate(item)) {
                      q.push({
                          i: index.ids[i],
                          item: item,
                          dist: haverSinDist(lng, lat, index.coords[2 * i], index.coords[2 * i + 1], cosLat)
                      });
                  }
              }

          } else { // not a leaf node (has child nodes)

              var m = (left + right) >> 1; // middle index
              var midLng = index.coords[2 * m];
              var midLat = index.coords[2 * m + 1];

              // add middle point to the queue
              item = index.points[index.ids[m]];
              if (!predicate || predicate(item)) {
                  q.push({
                      i: index.ids[m],
                      item: item,
                      dist: haverSinDist(lng, lat, midLng, midLat, cosLat)
                  });
              }

              var nextAxis = (node.axis + 1) % 2;

              // first half of the node
              var leftNode = {
                  left: left,
                  right: m - 1,
                  axis: nextAxis,
                  minLng: node.minLng,
                  minLat: node.minLat,
                  maxLng: node.axis === 0 ? midLng : node.maxLng,
                  maxLat: node.axis === 1 ? midLat : node.maxLat,
                  dist: 0
              };
              // second half of the node
              var rightNode = {
                  left: m + 1,
                  right: right,
                  axis: nextAxis,
                  minLng: node.axis === 0 ? midLng : node.minLng,
                  minLat: node.axis === 1 ? midLat : node.minLat,
                  maxLng: node.maxLng,
                  maxLat: node.maxLat,
                  dist: 0
              };

              leftNode.dist = boxDist(lng, lat, cosLat, leftNode);
              rightNode.dist = boxDist(lng, lat, cosLat, rightNode);

              // add child nodes to the queue
              q.push(leftNode);
              q.push(rightNode);
          }

          // fetch closest points from the queue; they're guaranteed to be closer
          // than all remaining points (both individual and those in kd-tree nodes),
          // since each node's distance is a lower bound of distances to its children
          while (q.length && q.peek().item) {
              var candidate = q.pop();
              if (candidate.dist > maxHaverSinDist) return result;
              // result.push(candidate.item);
              result.push(candidate.i);
              if (result.length === maxResults) return result;
          }

          // the next closest kd-tree node
          node = q.pop();
      }

      return result;
  }

  // lower bound for distance from a location to points inside a bounding box
  function boxDist(lng, lat, cosLat, node) {
      var minLng = node.minLng;
      var maxLng = node.maxLng;
      var minLat = node.minLat;
      var maxLat = node.maxLat;

      // query point is between minimum and maximum longitudes
      if (lng >= minLng && lng <= maxLng) {
          if (lat < minLat) return haverSin((lat - minLat) * rad);
          if (lat > maxLat) return haverSin((lat - maxLat) * rad);
          return 0;
      }

      // query point is west or east of the bounding box;
      // calculate the extremum for great circle distance from query point to the closest longitude;
      var haverSinDLng = Math.min(haverSin((lng - minLng) * rad), haverSin((lng - maxLng) * rad));
      var extremumLat = vertexLat(lat, haverSinDLng);

      // if extremum is inside the box, return the distance to it
      if (extremumLat > minLat && extremumLat < maxLat) {
          return haverSinDistPartial(haverSinDLng, cosLat, lat, extremumLat);
      }
      // otherwise return the distan e to one of the bbox corners (whichever is closest)
      return Math.min(
          haverSinDistPartial(haverSinDLng, cosLat, lat, minLat),
          haverSinDistPartial(haverSinDLng, cosLat, lat, maxLat)
      );
  }

  function compareDist(a, b) {
      return a.dist - b.dist;
  }

  function haverSin(theta) {
      var s = Math.sin(theta / 2);
      return s * s;
  }

  function haverSinDistPartial(haverSinDLng, cosLat1, lat1, lat2) {
      return cosLat1 * Math.cos(lat2 * rad) * haverSinDLng + haverSin((lat1 - lat2) * rad);
  }

  function haverSinDist(lng1, lat1, lng2, lat2, cosLat1) {
      var haverSinDLng = haverSin((lng1 - lng2) * rad);
      return haverSinDistPartial(haverSinDLng, cosLat1, lat1, lat2);
  }

  function vertexLat(lat, haverSinDLng) {
      var cosDLng = 1 - 2 * haverSinDLng;
      if (cosDLng <= 0) return lat > 0 ? 90 : -90;
      return Math.atan(Math.tan(lat * rad) / cosDLng) / rad;
  }

  function PointIndex(srcLyr, crs, opts) {
    requireSinglePointLayer(srcLyr);
    var points = getPointsInLayer(srcLyr);
    var maxDist = opts.max_distance ? convertDistanceParam(opts.max_distance, crs) : 1e-3;
    var kdbush = require$1('kdbush');
    var index = new kdbush(points);
    var lookup = getLookupFunction(index, crs, maxDist);
    var uniqIndex = new IdTestIndex(points.length);

    this.lookupByMultiPoint = function(shape) {
      var hits = [], p, i, j, n;
      for (i=0, n=shape ? shape.length : 0; i<n; i++) {
        p = shape[i];
        hits = lookup(p);
        for (j=0; j<hits.length; j++) {
          uniqIndex.setId(hits[j]);
        }
      }
      hits = uniqIndex.getIds();
      uniqIndex.clear();
      return hits;
    };
  }

  function getLookupFunction(index, crs, meterDist) {
    var geodetic = crs ? isLatLngCRS(crs) : false;
    var toMeter = crs && crs.to_meter || 1;
    if (geodetic) {
      return function(p) {
        // kdbush uses km
        return around(index, p[0], p[1], Infinity, meterDist / 1000);
      };
    }
    return function(p) {
      return index.within(p[0], p[1], meterDist / toMeter);
    };
  }

  function joinPointsToPoints(targetLyr, srcLyr, crs, opts) {
    var joinFunction = getPointToPointFunction(targetLyr, srcLyr, crs, opts);
    prepJoinLayers(targetLyr, srcLyr);
    return joinTableToLayer(targetLyr, srcLyr.data, joinFunction, opts);
  }

  function getPointToPointFunction(targetLyr, srcLyr, crs, opts) {
    var shapes = targetLyr.shapes;
    var index = new PointIndex(srcLyr, crs, opts);
    return function(targId) {
      var matches = index.lookupByMultiPoint(shapes[targId]);
      return matches.length > 0 ? matches : null;
    };
  }

  cmd.join = function(targetLyr, targetDataset, src, opts) {
    var srcType, targetType, retn;
    if (!src || !src.dataset) {
      stop("Missing a joinable data source");
    }
    if (opts.keys) {
      // join using data in attribute fields
      if (opts.keys.length != 2) {
        stop("Expected two key fields: a target field and a source field");
      }
      if (!src.layer.data) {
        stop("Source layer is missing attribute data");
      }
      retn = joinAttributesToFeatures(targetLyr, src.layer.data, opts);
    } else {
      // spatial join
      if (!src.layer.data) {
        // KLUDGE -- users might want to join a layer without attributes
        // to test for intersection... the simplest way to support this is
        // to add an empty data table to the source layer
        initDataTable(src.layer);
      }
      requireDatasetsHaveCompatibleCRS([targetDataset, src.dataset]);
      srcType = src.layer.geometry_type;
      targetType = targetLyr.geometry_type;
      if (srcType == 'point' && targetType == 'polygon') {
        retn = joinPointsToPolygons(targetLyr, targetDataset.arcs, src.layer, opts);
      } else if (srcType == 'polygon' && targetType == 'point') {
        retn = joinPolygonsToPoints(targetLyr, src.layer, src.dataset.arcs, opts);
      } else if (srcType == 'point' && targetType == 'point') {
        retn = joinPointsToPoints(targetLyr, src.layer, getDatasetCRS(targetDataset), opts);
      } else if (srcType == 'polygon' && targetType == 'polygon') {
        retn = joinPolygonsToPolygons(targetLyr, targetDataset, src, opts);
      } else if (srcType == 'polyline' && targetType == 'polygon') {
        retn = joinPolylinesToPolygons(targetLyr, targetDataset, src, opts);
      } else if (srcType == 'polygon' && targetType == 'polyline') {
        retn = joinPolygonsToPolylines(targetLyr, targetDataset, src, opts);
      } else {
        stop(utils.format("Unable to join %s geometry to %s geometry",
            srcType || 'null', targetType || 'null'));
      }
    }

    if (retn.unmatched) {
      targetDataset.layers.push(retn.unmatched);
    }
    if (retn.unjoined) {
      targetDataset.layers.push(retn.unjoined);
    }
  };

  function joinAttributesToFeatures(destLyr, srcTable, opts) {
    var keys = opts.keys,
        destKey = keys[0],
        srcKey = keys[1],
        destTable = destLyr.data,
        joinFunction = getJoinByKey(destTable, destKey, srcTable, srcKey);
    validateFieldNames(keys);
    return joinTableToLayer(destLyr, srcTable, joinFunction, opts);
  }

  // Return a function for translating a target id to an array of source ids based on values
  // of two key fields.
  function getJoinByKey(dest, destKey, src, srcKey) {
    if (!dest) {
      stop('Target layer is missing an attribute table');
    }
    if (!src) {
      stop('Source layer is missing an attribute table');
    }
    var destRecords = dest.getRecords();
    var srcRecords = src.getRecords();
    var index = createTableIndex(srcRecords, srcKey);
    var srcType, destType;
    if (srcRecords.length == 0) {
      // allow empty external tables
      return function(i) {return [];};
    }
    requireDataField(src, srcKey, 'External table is missing a field named:');
    requireDataField(dest, destKey, 'Target layer is missing key field:');
    srcType = getColumnType(srcKey, src.getRecords());
    destType = getColumnType(destKey, destRecords);
    validateJoinFieldType(srcKey, srcType);
    validateJoinFieldType(destKey, destType);
    if (srcType != destType) {
      stop("Join keys have mismatched data types:", destType, "and", srcType);
    }
    return function(i) {
      var destRec = destRecords[i],
          val = destRec ? destRec[destKey] : null,
          retn = null;
      if (destRec && val in index) {
        retn = index[val];
        if (!Array.isArray(retn)) retn = [retn];
      }
      return retn;
    };
  }

  function validateJoinFieldType(field, type) {
    if (!type || type == 'object') {
      stop('[' + field + '] field has an unsupported data type. Expected string or number.');
    }
  }

  function createTableIndex(records, f) {
    var index = {}, rec, key;
    for (var i=0, n=records.length; i<n; i++) {
      rec = records[i];
      key = rec[f];
      if (key in index === false) {
        index[key] = i;
      } else if (Array.isArray(index[key])) {
        index[key].push(i);
      } else {
        index[key] = [index[key], i];
      }
    }
    return index;
  }

  var Join = /*#__PURE__*/Object.freeze({
    __proto__: null,
    joinAttributesToFeatures: joinAttributesToFeatures
  });

  cmd.mosaic = function(layers, dataset, opts) {
    var lyr = layers[0];
    if (!lyr || layers.length > 1) {
      stop('Command takes a single target layer');
    }
    requirePolygonLayer(lyr);
    var nodes = addIntersectionCuts(dataset, opts);
    var mosaicIndex = new MosaicIndex(lyr, nodes, {flat: false});
    var mosaicShapes = mosaicIndex.mosaic;
    var records2;

    var lyr2 = {
      name: 'name' in lyr ? lyr.name : undefined,
      shapes: mosaicShapes,
      geometry_type: 'polygon',
    };

    if (opts.calc) {
      records2 = recombineDataRecords(lyr.data.getRecords(), mosaicIndex.getSourceIdsByTileId, mosaicShapes.length, opts);
      lyr2.data = new DataTable(records2);
    }

    return [lyr2];
  };

  cmd.polygonGrid = function(targetLayers, targetDataset, opts) {
    requireProjectedDataset(targetDataset);
    var params = getGridParams(targetLayers, targetDataset, opts);
    var gridDataset = makeGridDataset(params);

    gridDataset.info = targetDataset.info; // copy CRS to grid dataset // TODO: improve
    setOutputLayerName(gridDataset.layers[0], null, 'grid', opts);
    if (opts.debug) gridDataset.layers.push(cmd.pointGrid2(targetLayers, targetDataset, opts));
    return gridDataset;
  };

  // TODO: Update -point-grid command to use this function
  cmd.pointGrid2 = function(targetLayers, targetDataset, opts) {
    var params = getGridParams(targetLayers, targetDataset, opts);
    var geojson;
    if (params.type == 'square') {
      geojson = getPointGridGeoJSON(getSquareGridCoordinates(params));
    } else if (params.type == 'hex') {
      geojson = getPointGridGeoJSON(getHexGridCoordinates(params));
    } else {
      stop('Unsupported grid type');
    }
    alignGridToBounds(geojson, params.bbox);
    var gridDataset = importGeoJSON(geojson, {});
    if (opts.name) gridDataset.layers[0].name = opts.name;
    return gridDataset.layers[0];
  };

  function makeGridDataset(params, opts) {
    var geojson, dataset;
    if (params.type == 'square') {
      geojson = getSquareGridGeoJSON(getSquareGridCoordinates(params));
    } else if (params.type == 'hex') {
      geojson = getHexGridGeoJSON(getHexGridCoordinates(params));
    } else if (params.type == 'hex2') {
      // use rotated grid
      geojson = getHexGridGeoJSON(getHexGridCoordinates(swapGridParams(params)));
      swapPolygonCoords(geojson);
    } else {
      stop('Unsupported grid type');
    }
    alignGridToBounds(geojson, params.bbox);
    dataset = importGeoJSON(geojson, {});
    buildTopology(dataset);
    return dataset;
  }

  function swapGridParams(params) {
    var bbox = params.bbox;
    return utils.defaults({
      width: params.height,
      height: params.width,
      bbox: [bbox[1], bbox[0], bbox[3], bbox[2]]
    }, params);
  }

  function swapPolygonCoords(json) {
    json.geometries.forEach(function(geom) {
      geom.coordinates[0] = geom.coordinates[0].map(function(p) {
        return [p[1], p[0]];
      });
    });
  }

  function getGridParams(layers, dataset, opts) {
    var params = {};
    var crs = dataset ? getDatasetCRS(dataset) : null;
    if (opts.interval) {
      params.interval = convertIntervalParam(opts.interval, crs);
    } else {
      stop('Missing required interval option');
    }
    if (opts.bbox) {
      params.bbox = opts.bbox;
    } else if (dataset) {
      dataset = utils.defaults({layers: layers}, dataset);
      params.bbox = getDatasetBounds(dataset).toArray();
    } else {
      stop('Missing grid bbox');
    }
    params.width = params.bbox[2] - params.bbox[0];
    params.height = params.bbox[3] - params.bbox[1];
    params.type = opts.type || 'square';
    return params;
  }

  function getPointGridGeoJSON(arr) {
    var geometries = [];
    arr.forEach(function(row) {
      row.forEach(function(xy) {
        geometries.push({
          type: 'Point',
          coordinates: xy
        });
      });
    });
    return {type: 'GeometryCollection', geometries: geometries};
  }

  function getHexGridGeoJSON(arr) {
    var geometries = [], a, b, c, d, e, f;
    var rows = arr.length - 2;
    var row, col, midOffset, evenRow;
    for (row = 0; row < rows; row++) {
      evenRow = row % 2 === 0;
      col = evenRow ? 0 : 2;
      midOffset = evenRow ? 0 : -1;
      for (; true; col += 3) {
        a = arr[row][col];
        b = arr[row + 1][col + midOffset]; // middle-left
        c = arr[row + 2][col];
        d = arr[row + 2][col + 1];
        e = arr[row + 1][col + 2 + midOffset]; // middle-right
        f = arr[row][col + 1];
        if (!d || !e) break; // end of row
        geometries.push({
          type: 'Polygon',
          coordinates: [[a, b, c, d, e, f, a]]
        });
      }
    }
    return {type: 'GeometryCollection', geometries: geometries};
  }

  function getSquareGridGeoJSON(arr) {
    var geometries = [], a, b, c, d;
    for (var row = 0, rows = arr.length - 1; row < rows; row++) {
      for (var col = 0, cols = arr[row].length - 1; col < cols; col++) {
        a = arr[row][col];
        b = arr[row + 1][col];
        c = arr[row + 1][col + 1];
        d = arr[row][col + 1];
        geometries.push({
          type: 'Polygon',
          coordinates: [[a, b, c, d, a]]
        });
      }
    }
    return {type: 'GeometryCollection', geometries: geometries};
  }

  function getHexGridCoordinates(params) {
    var xInterval = params.interval;
    var yInterval = Math.sqrt(3) * xInterval / 2;
    var xOddRowShift = xInterval / 2;
    var xmax = params.width + xInterval * 2; // width of hexagon is 2 * xInterval
    var ymax = params.height + yInterval * 2; // height of hexagon is 2 * yInterval
    var y = -yInterval;
    var rows = [];
    var x, row;
    while (y < ymax) {
      x = rows.length % 2 === 0 ? 0 : -xOddRowShift;
      row = [];
      rows.push(row);
      while (x < xmax) {
        row.push([x, y]);
        x += xInterval;
      }
      y += yInterval;
    }
    return rows;
  }

  function getSquareGridCoordinates(params) {
    var y = 0, rows = [],
        interval = params.interval,
        xmax = params.width + interval,
        ymax = params.height + interval,
        x, row;
    while (y < ymax) {
      x = 0;
      row = [];
      rows.push(row);
      while (x < xmax) {
        row.push([x, y]);
        x += interval;
      }
      y += interval;
    }
    return rows;
  }

  function alignGridToBounds(geojson, bbox) {
    var geojsonBbox = findPolygonGridBounds(geojson);
    var dx = (bbox[2] + bbox[0]) / 2 - (geojsonBbox[2] + geojsonBbox[0]) / 2;
    var dy = (bbox[3] + bbox[1]) / 2 - (geojsonBbox[3] + geojsonBbox[1]) / 2;
    shiftPolygonGrid(geojson, dx, dy);
  }

  function shiftPolygonGrid(geojson, dx, dy) {
    geojson.geometries.forEach(function(geom) {
      if (geom.type == 'Point') {
        geom.coordinates = [geom.coordinates[0] + dx, geom.coordinates[1] + dy];
      }
      if (geom.type == 'Polygon') {
        geom.coordinates[0] = geom.coordinates[0].map(function(xy) {
          return [xy[0] + dx, xy[1] + dy];
        });
      }
    });
  }

  function findPolygonGridBounds(geojson) {
    var boundsFunctions = {
      Point: pointBounds,
      Polygon: polygonBounds
    };
    return geojson.geometries.reduce(function(memo, geom) {
      var getBounds = boundsFunctions[geom.type];
      var bbox = getBounds(geom);
      if (!memo) return bbox;
      updateBounds(memo, bbox[0], bbox[1]);
      updateBounds(memo, bbox[2], bbox[3]);
      return memo;
    }, null);

    function polygonBounds(geom) {
      return geom.coordinates[0].reduce(function(bbox, p) {
        if (!bbox) return [p[0], p[1], p[0], p[1]];
        updateBounds(bbox, p[0], p[1]);
        return bbox;
      }, null);
    }

    function pointBounds(geom) {
      var p = geom.coordinates;
      return [p[0], p[1], p[0], p[1]];
    }

    function updateBounds(bbox, x, y) {
      if (x < bbox[0]) bbox[0] = x;
      if (y < bbox[1]) bbox[1] = y;
      if (x > bbox[2]) bbox[2] = x;
      if (y > bbox[3]) bbox[3] = y;
    }
  }

  cmd.pointGrid = function(dataset, opts) {
    var gridOpts = getPointGridParams(dataset, opts);
    var lyr = createPointGridLayer(createPointGrid(gridOpts));
    setOutputLayerName(lyr, null, 'grid', opts);
    return lyr;
  };

  function getPointGridParams(dataset, opts) {
    var params = {};
    var crs = dataset ? getDatasetCRS(dataset) : null;
    if (opts.interval) {
      params.interval = convertIntervalParam(opts.interval, crs);
    } else if (opts.rows > 0 && opts.cols > 0) {
      params.rows = opts.rows;
      params.cols = opts.cols;
    } else ;
    if (opts.bbox) {
      params.bbox = opts.bbox;
    } else if (dataset) {
      params.bbox = getDatasetBounds(dataset).toArray();
    } else {
      params.bbox = [-180, -90, 180, 90];
    }
    return params;
  }

  function createPointGridLayer(rows, opts) {
    var points = [];
    rows.forEach(function(row, rowId) {
      for (var i=0; i<row.length; i++) {
        points.push([row[i]]);
      }
    });
    return {
      geometry_type: 'point',
      shapes: points
    };
  }


  // Returns a grid of [x,y] points so that point(c,r) == arr[r][c]
  function createPointGrid(opts) {
    var bbox = opts.bbox,
        w = bbox[2] - bbox[0],
        h = bbox[3] - bbox[1],
        rowsArr = [], rowArr,
        cols, rows, dx, dy, x0, y0, x, y;

    if (opts.interval > 0) {
      dx = opts.interval;
      dy = opts.interval;
      cols = Math.round(w / dx) - 1;
      rows = Math.round(h / dy) - 1;
      x0 = bbox[0] + (w - cols * dx) / 2;
      y0 = bbox[1] + (h - rows * dy) / 2;
    } else if (opts.rows > 0 && opts.cols > 0) {
      cols = opts.cols;
      rows = opts.rows;
      dx = (w / cols);
      dy = (h / rows);
      x0 = bbox[0] + dx / 2;
      y0 = bbox[1] + dy / 2;
    }

    if (dx > 0 === false || dy > 0 === false) {
      stop('Invalid grid parameters');
    }

    y = y0;
    while (y <= bbox[3]) {
      x = x0;
      rowsArr.push(rowArr = []);
      while (x <= bbox[2]) {
        rowArr.push([x, y]);
        x += dx;
      }
      y += dy;
    }
    return rowsArr;
  }

  cmd.pointToGrid = function(targetLayers, targetDataset, opts) {
    targetLayers.forEach(requirePointLayer);
    if (opts.interval > 0 === false) {
      stop('Expected a non-negative interval parameter');
    }
    if (opts.radius > 0 === false) ;
    // var bbox = getLayerBounds(pointLyr).toArray();
    // Use target dataset, so grids are aligned between layers
    // TODO: align grids between datasets
    var bbox = getDatasetBounds(targetDataset).toArray();

    var datasets = [targetDataset];
    var outputLayers = targetLayers.map(function(pointLyr) {
      if (countMultiPartFeatures(pointLyr) > 0) {
        stop('This command requires single points');
      }
      var dataset = getPolygonDataset(pointLyr, bbox, opts);
      var gridLyr = dataset.layers[0];
      datasets.push(dataset);
      setOutputLayerName(gridLyr, pointLyr, 'grid', opts);
      return gridLyr;
    });

    var merged = mergeDatasets(datasets);
    // build topology for the entire dataset, in case the command is used on
    // multiple target layers.
    buildTopology(merged);
    targetDataset.arcs = merged.arcs;
    return outputLayers;
  };

  function getPolygonDataset(pointLyr, gridBBox, opts) {
    var points = getPointsInLayer(pointLyr);
    var cellSize = opts.interval;
    var grid = getGridData(gridBBox, cellSize, opts);
    var pointCircleRadius = getPointCircleRadius(opts);
    var findPointIdsByCellId = getPointIndex(points, grid, pointCircleRadius);
    var geojson = {
      type: 'FeatureCollection',
      features: []
    };
    var calc = opts.calc ? getJoinCalc(pointLyr.data, opts.calc) : null;
    var candidateIds, weights, center, d;

    for (var i=0, n=grid.cells(); i<n; i++) {
      candidateIds = findPointIdsByCellId(i);
      if (!candidateIds.length) continue;
      center = grid.idxToPoint(i);
      weights = calcWeights(center, cellSize, points, candidateIds, pointCircleRadius);
      d = calcCellProperties(candidateIds, weights, calc);
      if (d.weight > 0.05 === false) continue;
      d.id = i;
      geojson.features.push({
        type: 'Feature',
        properties: d,
        geometry: makeCellPolygon(i, grid, opts)
      });
    }
    return importGeoJSON(geojson, {});
  }

  function getPointCircleRadius(opts) {
    var cellRadius = opts.interval * Math.sqrt(1 / Math.PI);
    return opts.radius > 0 ? opts.radius : cellRadius;
  }

  function calcCellProperties(pointIds, weights, calc) {
    var hitIds = [];
    var weight = 0;
    var partial;
    var d;
    for (var i=0; i<pointIds.length; i++) {
      partial = weights[i];
      if (partial > 0 === false) continue;
      weight += partial;
      hitIds.push(pointIds[i]);
    }
    d = {weight: weight};
    if (calc) {
      calc(hitIds, d);
    }
    return d;
  }

  function calcWeights(cellCenter, cellSize, points, pointIds, pointRadius) {
    var weights = [];
    var cellRadius = cellSize * Math.sqrt(1 / Math.PI); // radius of circle with same area as cell
    var cellArea = cellSize * cellSize;
    var w;
    for (var i=0; i<pointIds.length; i++) {
      w = twoCircleIntersection(cellCenter, cellRadius, points[pointIds[i]], pointRadius) / cellArea;
      weights.push(w);
    }
    return weights;
  }

  // Source: https://diego.assencio.com/?index=8d6ca3d82151bad815f78addf9b5c1c6
  function twoCircleIntersection(c1, r1, c2, r2) {
    var d = distance2D(c1[0], c1[1], c2[0], c2[1]);
    if (d >= r1 + r2) return 0;
    var r1sq = r1 * r1,
        r2sq = r2 * r2,
        d1 = (r1sq - r2sq + d * d) / (2 * d),
        d2 = d - d1;
    if (d <= Math.abs(r1 - r2)) {
      return Math.PI * Math.min(r1sq, r2sq);
    }
    return r1sq * Math.acos(d1/r1) - d1 * Math.sqrt(r1sq - d1 * d1) +
      r2sq * Math.acos(d2/r2) - d2 * Math.sqrt(r2sq - d2 * d2);
  }

  function makeCellPolygon(idx, grid, opts) {
    var coords = opts.circles ?
      makeCircleCoords(grid.idxToPoint(idx), opts) :
      makeCellCoords(grid.idxToBBox(idx), opts);
    return {
      type: 'Polygon',
      coordinates: [coords]
    };
  }

  function makeCellCoords(bbox, opts) {
    var margin = opts.interval * (opts.cell_margin || 0);
    var a = bbox[0] + margin,
        b = bbox[1] + margin,
        c = bbox[2] - margin,
        d = bbox[3] - margin;
    return [[a, b],[a, d],[c, d],[c, b],[a, b]];
  }

  function makeCircleCoords(center, opts) {
    var margin = opts.cell_margin > 0 ? opts.cell_margin : 1e-6;
    var radius = opts.interval / 2 * (1 - margin);
    return getPointBufferCoordinates(center, radius, 20, getPlanarSegmentEndpoint);
  }

  function getPointIndex(points, grid, radius) {
    var Flatbush = require$1('flatbush');
    var gridIndex = new IdTestIndex(grid.cells());
    var bboxIndex = new Flatbush(points.length);
    var empty = [];
    points.forEach(function(p) {
      addPointToGridIndex(p, gridIndex, grid);
      bboxIndex.add.apply(bboxIndex, getPointBounds(p, radius));
    });
    bboxIndex.finish();
    return function(i) {
      if (!gridIndex.hasId(i)) return empty;
      var bbox = grid.idxToBBox(i);
      var indices = bboxIndex.search.apply(bboxIndex, bbox);
      return indices;
    };
  }

  function addPointToGridIndex(p, index, grid) {
    var i = grid.pointToIdx(p);
    var c = grid.idxToCol(i);
    var r = grid.idxToRow(i);
    addCellToGridIndex(c+1, r+1, grid, index);
    addCellToGridIndex(c+1, r, grid, index);
    addCellToGridIndex(c+1, r-1, grid, index);
    addCellToGridIndex(c, r+1, grid, index);
    addCellToGridIndex(c, r, grid, index);
    addCellToGridIndex(c, r-1, grid, index);
    addCellToGridIndex(c-1, r+1, grid, index);
    addCellToGridIndex(c-1, r, grid, index);
    addCellToGridIndex(c-1, r-1, grid, index);
  }

  function addCellToGridIndex(c, r, grid, index) {
    var i = grid.colRowToIdx(c, r);
    if (i > -1) index.setId(i);
  }

  // TODO: support spherical coords
  function getPointBounds(p, radius) {
    return [p[0] - radius, p[1] - radius, p[0] + radius, p[1] + radius];
  }

  // grid boundaries includes the origin
  // (this way, grids calculated from different sets of points will all align)
  function getAlignedRange(minCoord, maxCoord, interval) {
    var idx = Math.floor(minCoord / interval) - 1;
    var idx2 = Math.ceil(maxCoord / interval) + 1;
    return [idx * interval, idx2 * interval];
  }

  function getCenteredRange(minCoord, maxCoord, interval) {
    var w = maxCoord - minCoord;
    var w2 = Math.ceil(w / interval) * interval;
    var pad = (w2 - w) / 2 + interval;
    return [minCoord - pad, maxCoord + pad];
  }

  function getAlignedGridBounds(bbox, interval) {
    var xx = getAlignedRange(bbox[0], bbox[2], interval);
    var yy = getAlignedRange(bbox[1], bbox[3], interval);
    return [xx[0], yy[0], xx[1], yy[1]];
  }

  function getCenteredGridBounds(bbox, interval) {
    var xx = getCenteredRange(bbox[0], bbox[2], interval);
    var yy = getCenteredRange(bbox[1], bbox[3], interval);
    return [xx[0], yy[0], xx[1], yy[1]];
  }

  // TODO: Use this function for other grid-based commands
  function getGridData(bbox, interval, opts) {
    var extent = opts && opts.aligned ?
      getAlignedGridBounds(bbox, interval) :
      getCenteredGridBounds(bbox, interval);
    var xmin = extent[0];
    var ymin = extent[1];
    var w = extent[2] - xmin;
    var h = extent[3] - ymin;
    var cols = Math.round(w / interval);
    var rows = Math.round(h / interval);
    // var xmin = bbox[0] - interval;
    // var ymin = bbox[1] - interval;
    // var xmax = bbox[2] + interval;
    // var ymax = bbox[3] + interval;
    // var w = xmax - xmin;
    // var h = ymax - ymin;
    // var cols = Math.ceil(w / interval);
    // var rows = Math.ceil(h / interval);
    function size() {
      return [cols, rows];
    }
    function cells() {
      return cols * rows;
    }
    function pointToCol(xy) {
      var dx = xy[0] - xmin;
      return Math.floor(dx / w * cols);
    }
    function pointToRow(xy) {
      var dy = xy[1] - ymin;
      return Math.floor(dy / h * rows);
    }
    function colRowToIdx(c, r) {
      if (c < 0 || r < 0 || c >= cols || r >= rows) return -1;
      return r * cols + c;
    }
    function pointToIdx(xy) {
      var c = pointToCol(xy);
      var r = pointToRow(xy);
      return colRowToIdx(c, r);
    }
    function idxToCol(i) {
      return i % cols;
    }
    function idxToRow(i) {
      return Math.floor(i / cols);
    }
    function idxToPoint(idx) {
      var x = xmin + (idxToCol(idx) + 0.5) * interval;
      var y = ymin + (idxToRow(idx) + 0.5) * interval;
      return [x, y];
    }
    function idxToBBox(idx) {
      var c = idxToCol(idx);
      var r = idxToRow(idx);
      return [
        xmin + c * interval, ymin + r * interval,
        xmin + (c + 1) * interval, ymin + (r + 1) * interval
      ];
    }
    return {
      size, cells, pointToCol, pointToRow, colRowToIdx, pointToIdx,
      idxToCol, idxToRow, idxToBBox, idxToPoint
    };
  }

  function closeUndershoots(lyr, dataset, opts) {
    var maxGapLen = opts.gap_tolerance ? convertIntervalParam(opts.gap_tolerance, getDatasetCRS(dataset)) : 0;
    var arcs = dataset.arcs;
    var arcFilter = getArcPresenceTest(lyr.shapes, arcs);
    var nodes = new NodeCollection(dataset.arcs, arcFilter);
    var dangles = findPotentialUndershoots(nodes, maxGapLen);
    if (dangles.length === 0) return nodes;
    var arcShapes = arcsToShapes(arcs, arcFilter);
    var index = new PathIndex(arcShapes, arcs);
    var extensions = dangles.reduce(function(memo, dangle) {
      var candidates = index.findPointEnclosureCandidates(dangle.point, maxGapLen);
      var nearestHit = findUndershootTarget(dangle, candidates, arcs, maxGapLen);
      if (nearestHit) {
        memo.push(getArcExtension(nearestHit, dangle.arc, arcs));
      }
      return memo;
    }, []);

    // TODO: consider alternative: append small patch arcs to paths instead of shifting endpoints
    dataset.arcs = insertArcExtensions(arcs, extensions);
    return addIntersectionCuts(dataset, {});
  }

  // Return information about an arc that @endpoint can connect with to close a gap
  // @candidates: array of ids of possible target arcs
  function findUndershootTarget(endpoint, candidates, arcs, maxGapLen) {
    var absId = absArcId(endpoint.arc);
    var target = null;
    candidates.forEach(function(candId) {
      var hit;
      if (candId == absId) return; // ignore self-intersections
      hit = geom.getPointToPathInfo(endpoint.point[0], endpoint.point[1], [candId], arcs);
      if (hit && hit.distance <= maxGapLen && (!target || hit.distance < target.distance)) {
        target = hit;
      }
    });
    return target;
  }


  // Create a polyline shape for each arc in an ArcCollection
  function arcsToShapes(arcs, filter) {
    var shapes = [];
    for (var i=0, n=arcs.size(); i<n; i++) {
      shapes.push(filter(i) ? [[i]] : null);
    }
    return shapes;
  }

  // Find unconnected (dangling) arcs that don't look like overshoots
  function findPotentialUndershoots(nodes, maxLen) {
    return nodes.findDanglingEndpoints().filter(function(o) {
      return geom.calcPathLen([o.arc], nodes.arcs) > maxLen;
    });
  }

  function insertArcExtensions(arcs, extensions) {
    var data = arcs.getVertexData();
    extensions.forEach(function(obj) {
      var i = arcs.indexOfVertex(obj.arc, -1);
      data.xx[i] = obj.point[0];
      data.yy[i] = obj.point[1];
    });

    // re-index arc bounds
    arcs.updateVertexData(data.nn, data.xx, data.yy, data.zz);
    return arcs;
  }

  function chooseCloserPoint(p, a, b) {
    return geom.distance2D(p[0], p[1], a[0], a[1]) < geom.distance2D(p[0], p[1], b[0], b[1]) ? a : b;
  }

  function pointIsEndpoint(p, a, b) {
    return p[0] == a[0] && p[1] == a[1] || p[0] == b[0] && p[1] == b[1];
  }

  // move point <b> a bit farther away from <a>
  function addTinyOvershoot(a, b) {
    var dist = geom.distance2D(a[0], a[1], b[0], b[1]);
    var k = (dist + 1e-6) / dist;
    return [a[0] + k * (b[0] - a[0]), a[1] + k * (b[1] - a[1])];
  }

  function getArcExtension(hit, arcId, arcs) {
    var v0 = arcs.getVertex(arcId, -1),
        endPtOld = [v0.x, v0.y],
        v1 = arcs.getVertex(arcId, -2),
        p1 = [v1.x, v1.y],
        s1 = hit.segment[0],
        s2 = hit.segment[1],
        endPtNew = geom.findClosestPointOnSeg(endPtOld[0], endPtOld[1], s1[0], s1[1], s2[0], s2[1]);
    if (!pointIsEndpoint(endPtNew, s1, s2)) {
      // add small overshoot if new endpoint is not a vertex, to make sure intersection
      // is correctly detected later
      endPtNew = addTinyOvershoot(p1, endPtNew);
      // handle floating point rounding errors by snapping to a segment endpoint
      if (!geom.segmentIntersection(p1[0], p1[1], endPtNew[0], endPtNew[1], s1[0], s1[1], s2[0], s2[1])) {
        endPtNew = chooseCloserPoint(p1, s1, s2);
      }
      // TODO: test edge cases; moving the endpoint of a dangling arc could create
      //   invalid geometry, e.g. duplicate points
    }
    return {
      arc: arcId,
      point: endPtNew
    };
  }

  cmd.polygons = function(layers, dataset, opts) {
    layers.forEach(requirePolylineLayer);
    // use larger-than-default snapping in addIntersectionCuts()
    // (kludge, snaps together some almost-identical pairs of lines in ne_10m_land_ocean_seams.shp)
    // if (opts.gap_tolerance) {
      //opts = utils.defaults({snap_interval: opts.gap_tolerance * 0.1}, opts);
    // }
    addIntersectionCuts(dataset, opts);
    return layers.map(function(lyr) {
      if (lyr.geometry_type != 'polyline') stop("Expected a polyline layer");
      if (opts.from_rings) {
        return createPolygonLayerFromRings(lyr, dataset);
      }
      return createPolygonLayer(lyr, dataset, opts);
    });
  };

  // Convert a polyline layer of rings to a polygon layer
  function createPolygonLayerFromRings(lyr, dataset) {
    var arcs = dataset.arcs;
    var openCount = 0;
    editShapes(lyr.shapes, function(part) {
      if (geom.pathIsClosed(part, arcs)) {
        return part;
      }
      openCount++;
      return null;
    });
    if (openCount > 0) {
      message('Removed', openCount, 'open ' + (openCount == 1 ? 'ring' : 'rings'));
    }
    lyr.geometry_type = 'polygon';
    rewindPolygons(lyr, arcs);
    return lyr;
  }

  function createPolygonLayer(lyr, dataset, opts) {
    var nodes = closeUndershoots(lyr, dataset, opts);
    var data = buildPolygonMosaic(nodes);
    return {
      geometry_type: 'polygon',
      name: lyr.name,
      shapes: data.mosaic
    };
  }

  cmd.print = function(msgArg) {
    print(msgArg || '');
  };

  cmd.renameLayers = function(layers, names, catalog) {
    if (names && names.join('').indexOf('=') > -1) {
      renameByAssignment(names, catalog);
    } else {
      renameTargetLayers(names, layers);
    }
  };

  function renameByAssignment(names, catalog) {
    var index = mapLayerNames(names);
    catalog.forEachLayer(function(lyr) {
      if (index[lyr.name]) {
        lyr.name = index[lyr.name];
      }
    });
  }

  function renameTargetLayers(names, layers) {
    var nameCount = names && names.length || 0;
    var name = '';
    var suffix = '';
    layers.forEach(function(lyr, i) {
      if (i < nameCount) {
        name = names[i];
      }
      if (name && nameCount < layers.length && (i >= nameCount - 1)) {
        suffix = (suffix || 0) + 1;
      }
      lyr.name = name + suffix;
    });
  }

  // TODO: remove duplication with mapFieldNames()
  function mapLayerNames(names) {
    return (names || []).reduce(function(memo, str) {
      var parts = str.split('='),
          dest = utils.trimQuotes(parts[0]),
          src = utils.trimQuotes(parts[1] || '');
      if (!src) stop("Invalid name assignment:", str);
      memo[src] = dest;
      return memo;
    }, {});
  }

  // Parse an array or a string of command line tokens into an array of
  // command objects.
  function parseCommands(tokens) {
    if (Array.isArray(tokens) && utils.isObject(tokens[0])) {
      // argv seems to contain parsed commands already... make a copy
      return tokens.map(function(cmd) {
        return {name: cmd.name, options: Object.assign({}, cmd.options)};
      });
    }
    if (utils.isString(tokens)) {
      tokens = splitShellTokens(tokens);
    }
    return getOptionParser().parseArgv(tokens);
  }

  function standardizeConsoleCommands(raw) {
    var str = raw.replace(/^mapshaper\b/, '').trim();
    getOptionParser();
    // support multiline string of commands pasted into console
    str = str.split(/\n+/g).map(function(str) {
      var match = /^[a-z][\w-]*/i.exec(str = str.trim());
      //if (match && parser.isCommandName(match[0])) {
      if (match) {
        // add hyphen prefix to bare command
        // also add hyphen to non-command strings, for a better error message
        // ("unsupported command" instead of "The -i command cannot be run in the browser")
        str = '-' + str;
      }
      return str;
    }).join(' ');
    return str;
  }

  // Parse a command line string for the browser console
  function parseConsoleCommands(raw) {
    var str = standardizeConsoleCommands(raw);
    var parsed = parseCommands(str);
    parsed.forEach(function(cmd) {
      cli.checkCommandEnv(cmd.name);
    });
    return parsed;
  }

  var ParseCommands = /*#__PURE__*/Object.freeze({
    __proto__: null,
    parseCommands: parseCommands,
    standardizeConsoleCommands: standardizeConsoleCommands,
    parseConsoleCommands: parseConsoleCommands
  });

  cmd.run = function(job, targets, opts, cb) {
    var commandStr, commands;
    if (opts.include) {
      cmd.include({file: opts.include});
    }
    if (!opts.commands) {
      stop("Missing commands parameter");
    }
    commandStr = runGlobalExpression(opts.commands, targets);
    if (commandStr) {
      commands = parseCommands(commandStr);
      runParsedCommands(commands, job, cb);
    } else {
      cb(null);
    }
  };

  function runGlobalExpression(expression, targets) {
    var ctx = getBaseContext();
    var output, targetData;
    // TODO: throw an informative error if target is used when there are multiple targets
    if (targets && targets.length == 1) {
      targetData = getRunCommandData(targets[0]);
      Object.defineProperty(ctx, 'target', {value: targetData});
    }
    utils.extend(ctx, getStashedVar('defs'));
    try {
      output = Function('ctx', 'with(ctx) {return (' + expression + ');}').call({}, ctx);
    } catch(e) {
      stop(e.name, 'in JS source:', e.message);
    }
    return output;
  }


  function getRunCommandData(target) {
    var lyr = target.layers[0];
    var data = getLayerInfo(lyr, target.dataset);
    data.layer = lyr;
    data.dataset = target.dataset;
    return data;
  }

  cmd.require = function(targets, opts) {
    var defs = getStashedVar('defs');
    var moduleFile, moduleName, mod;
    if (!opts.module) {
      stop("Missing module name or path to module");
    }
    if (cli.isFile(opts.module)) {
      moduleFile = opts.module;
    } else if (cli.isFile(opts.module + '.js')) {
      moduleFile = opts.module + '.js';
    } else {
      moduleName = opts.module;
    }
    if (moduleFile) {
      moduleFile = require$1('path').join(process.cwd(), moduleFile);
    }
    try {
      mod = require$1(moduleFile || moduleName);
    } catch(e) {
      stop(e);
    }
    if (moduleName || opts.alias) {
      defs[opts.alias || moduleName] = mod;
    } else {
      Object.assign(defs, mod);
    }
    if (opts.init) {
      runGlobalExpression(opts.init, targets);
    }
  };

  cmd.shape = function(targetDataset, opts) {
    var geojson, dataset;
    if (opts.coordinates) {
      geojson = makeShapeFromCoords(opts);
    } else if (opts.type == 'circle') {
      geojson = makeCircle(opts);
    } else if (opts.type == 'rectangle' && opts.bbox) {
      geojson = getRectangleGeoJSON(opts);
    } else {
      stop('Missing coordinates parameter');
    }
    // TODO: project shape if targetDataset is projected
    dataset = importGeoJSON(geojson, {});
    if (opts.rotation) {
      rotateDatasetCoords(dataset, opts.rotation);
    }
    dataset.layers[0].name = opts.name || opts.type || 'shape';
    return dataset;
  };

  function getRectangleGeoJSON(opts) {
    var bbox = opts.bbox,
        xmin = bbox[0],
        ymin = bbox[1],
        xmax = bbox[2],
        ymax = bbox[3],
        interval = 0.5,
        coords = [],
        type = opts.geometry == 'polyline' ? 'LineString' : 'Polygon';
    addSide(xmin, ymin, xmin, ymax);
    addSide(xmin, ymax, xmax, ymax);
    addSide(xmax, ymax, xmax, ymin);
    addSide(xmax, ymin, xmin, ymin);
    coords.push([xmin, ymin]);
    return {
      type: type,
      coordinates: type == 'Polygon' ? [coords] : coords
    };

    function addSide(x1, y1, x2, y2) {
      var dx = x2 - x1,
          dy = y2 - y1,
          n = Math.ceil(Math.max(Math.abs(dx) / interval, Math.abs(dy) / interval)),
          xint = dx / n,
          yint = dy / n;
      for (var i=0; i<n; i++) {
        coords.push([x1 + i * xint, y1 + i * yint]);
      }
    }
  }

  function makeCircle(opts) {
    if (opts.radius > 0 === false && opts.radius_angle > 0 === false) {
      stop('Missing required radius parameter.');
    }
    var cp = opts.center || [0, 0];
    var radius = opts.radius || getCircleRadiusFromAngle(parseCrsString('wgs84'), opts.radius_angle);
    return getCircleGeoJSON(cp, radius, null, {geometry_type : opts.geometry || 'polygon'});
  }

  function makeShapeFromCoords(opts) {
    var coordinates = [];
    var offsets = opts.offsets || [];
    var coords = opts.coordinates;
    var type, i, x, y;
    if (coords.length >= 2 === false) {
      stop('Invalid coordinates parameter.');
    }
    for (i=0; i<coords.length; i+= 2) {
      x = coords[i];
      y = coords[i + 1];
      coordinates.push([x, y]);
    }
    for (i=0; i<offsets.length; i+=2) {
      x += offsets[i];
      y += offsets[i + 1];
      coordinates.push([x, y]);
    }
    if (GeoJSON.pathIsRing(coordinates)) {
      type = 'Polygon';
    } else if (opts.closed && coordinates.length >= 3) {
      type = 'Polygon';
      coordinates.push(coordinates[0]);
    } else {
      type = 'LineString';
    }
    return {
      type: type,
      coordinates: type == 'Polygon' ? [coordinates] : coordinates
    };

  }

  function calcSimplifyStats(arcs, use3D) {
    var distSq = use3D ? pointSegGeoDistSq : geom.pointSegDistSq,
        calcAngle = use3D ? geom.signedAngleSph : geom.signedAngle,
        removed = 0,
        retained = 0,
        collapsedRings = 0,
        max = 0,
        sum = 0,
        iprev = -1,
        jprev = -1,
        measures = [],
        angles = [],
        zz = arcs.getVertexData().zz,
        stats;

    arcs.forEachSegment(function(i, j, xx, yy) {
      var ax, ay, bx, by, d2, d, skipped, angle, tmp;
      ax = xx[i];
      ay = yy[i];
      bx = xx[j];
      by = yy[j];

      if (i == jprev) {
        angle = calcAngle(xx[iprev], yy[iprev], ax, ay, bx, by);
        if (angle > Math.PI) angle = 2 * Math.PI - angle;
        if (!isNaN(angle)) {
          angles.push(angle * 180 / Math.PI);
        }
      }
      iprev = i;
      jprev = j;

      if (zz[i] < Infinity) {
        retained++;
      }
      skipped = j - i - 1;
      if (skipped < 1) return;
      removed += skipped;

      if (ax == bx && ay == by) {
        collapsedRings++;
      } else {
        d2 = 0;
        while (++i < j) {
          tmp = distSq(xx[i], yy[i], ax, ay, bx, by);
          d2 = Math.max(d2, tmp);
        }
        d = Math.sqrt(d2);
        sum += d;
        measures.push(d);
        max = Math.max(max, d);
      }
    });

    function pointSegGeoDistSq(alng, alat, blng, blat, clng, clat) {
      var xx = [], yy = [], zz = [];
      geom.convLngLatToSph([alng, blng, clng], [alat, blat, clat], xx, yy, zz);
      return geom.pointSegDistSq3D(xx[0], yy[0], zz[0], xx[1], yy[1], zz[1],
            xx[2], yy[2], zz[2]);
    }

    stats = {
      angleMean: 0,
      displacementMean: 0,
      displacementMax: max,
      collapsedRings: collapsedRings,
      removed: removed,
      retained: retained,
      uniqueCount: countUniqueVertices(arcs),
      removableCount: removed + retained
    };

    if (angles.length > 0) {
      // stats.medianAngle = utils.findMedian(angles);
      stats.angleMean = utils.sum(angles) / angles.length;
      // stats.lt30 = utils.findRankByValue(angles, 30) / angles.length * 100;
      // stats.lt45 = utils.findRankByValue(angles, 45) / angles.length * 100;
      // stats.lt60 = utils.findRankByValue(angles, 60) / angles.length * 100;
      // stats.lt90 = utils.findRankByValue(angles, 90) / angles.length * 100;
      // stats.lt120 = utils.findRankByValue(angles, 120) / angles.length * 100;
      // stats.lt135 = utils.findRankByValue(angles, 135) / angles.length * 100;
      stats.angleQuartiles = [
        utils.findValueByPct(angles, 0.75),
        utils.findValueByPct(angles, 0.5),
        utils.findValueByPct(angles, 0.25)
      ];
    }

    if (measures.length > 0) {
      stats.displacementMean = sum / measures.length;
      // stats.median = utils.findMedian(measures);
      // stats.stdDev = Math.sqrt(sumSq / measures.length);
      stats.displacementQuartiles = [
        utils.findValueByPct(measures, 0.75),
        utils.findValueByPct(measures, 0.5),
        utils.findValueByPct(measures, 0.25)
      ];
    }
    return stats;
  }

  function countUniqueVertices(arcs) {
    // TODO: exclude any zero-length arcs
    var endpoints = arcs.size() * 2;
    var nodes = new NodeCollection(arcs).size();
    return arcs.getPointCount() - endpoints + nodes;
  }

  var Visvalingam = {};

  Visvalingam.getArcCalculator = function(metric, is3D) {
    var heap = new Heap(),
        prevBuf = utils.expandoBuffer(Int32Array),
        nextBuf = utils.expandoBuffer(Int32Array),
        calc = is3D ?
          function(b, c, d, xx, yy, zz) {
            return metric(xx[b], yy[b], zz[b], xx[c], yy[c], zz[c], xx[d], yy[d], zz[d]);
          } :
          function(b, c, d, xx, yy) {
            return metric(xx[b], yy[b], xx[c], yy[c], xx[d], yy[d]);
          };

    // Calculate Visvalingam simplification data for an arc
    // @kk (Float64Array|Array) Receives calculated simplification thresholds
    // @xx, @yy, (@zz) Buffers containing vertex coordinates
    return function calcVisvalingam(kk, xx, yy, zz) {
      var arcLen = kk.length,
          prevArr = prevBuf(arcLen),
          nextArr = nextBuf(arcLen),
          val, maxVal = -Infinity,
          b, c, d; // indexes of points along arc

      if (zz && !is3D) {
        error("[visvalingam] Received z-axis data for 2D simplification");
      } else if (!zz && is3D) {
        error("[visvalingam] Missing z-axis data for 3D simplification");
      } else if (kk.length > xx.length) {
        error("[visvalingam] Incompatible data arrays:", kk.length, xx.length);
      }

      // Initialize Visvalingam "effective area" values and references to
      //   prev/next points for each point in arc.
      for (c=0; c<arcLen; c++) {
        b = c-1;
        d = c+1;
        if (b < 0 || d >= arcLen) {
          val = Infinity; // endpoint maxVals
        } else {
          val = calc(b, c, d, xx, yy, zz);
        }
        kk[c] = val;
        nextArr[c] = d;
        prevArr[c] = b;
      }
      heap.init(kk);

      // Calculate removal thresholds for each internal point in the arc
      //
      while (heap.size() > 0) {
        c = heap.pop(); // Remove the point with the least effective area.
        val = kk[c];
        if (val === Infinity) {
          break;
        }
        if (val < maxVal) {
          // don't assign current point a lesser value than the last removed vertex
          kk[c] = maxVal;
        } else {
          maxVal = val;
        }

        // Recompute effective area of neighbors of the removed point.
        b = prevArr[c];
        d = nextArr[c];
        if (b > 0) {
          val = calc(prevArr[b], b, d, xx, yy, zz);
          heap.updateValue(b, val);
        }
        if (d < arcLen-1) {
          val = calc(b, d, nextArr[d], xx, yy, zz);
          heap.updateValue(d, val);
        }
        nextArr[b] = d;
        prevArr[d] = b;
      }
    };
  };

  Visvalingam.standardMetric = geom.triangleArea;
  Visvalingam.standardMetric3D = geom.triangleArea3D;

  Visvalingam.getWeightedMetric = function(opts) {
    var weight = Visvalingam.getWeightFunction(opts);
    return function(ax, ay, bx, by, cx, cy) {
      var area = geom.triangleArea(ax, ay, bx, by, cx, cy),
          cos = geom.cosine(ax, ay, bx, by, cx, cy);
      return weight(cos) * area;
    };
  };

  Visvalingam.getWeightedMetric3D = function(opts) {
    var weight = Visvalingam.getWeightFunction(opts);
    return function(ax, ay, az, bx, by, bz, cx, cy, cz) {
      var area = geom.triangleArea3D(ax, ay, az, bx, by, bz, cx, cy, cz),
          cos = geom.cosine3D(ax, ay, az, bx, by, bz, cx, cy, cz);
      return weight(cos) * area;
    };
  };

  Visvalingam.getWeightCoefficient = function(opts) {
    return opts && utils.isNumber(opts && opts.weighting) ? opts.weighting : 0.7;
  };

  // Get a parameterized version of Visvalingam.weight()
  Visvalingam.getWeightFunction = function(opts) {
    var k = Visvalingam.getWeightCoefficient(opts);
    return function(cos) {
      return -cos * k + 1;
    };
  };

  // Weight triangle area by inverse cosine
  // Standard weighting favors 90-deg angles; this curve peaks at 120 deg.
  Visvalingam.weight = function(cos) {
    var k = 0.7;
    return -cos * k + 1;
  };

  Visvalingam.getEffectiveAreaSimplifier = function(use3D) {
    var metric = use3D ? Visvalingam.standardMetric3D : Visvalingam.standardMetric;
    return Visvalingam.getPathSimplifier(metric, use3D);
  };

  Visvalingam.getWeightedSimplifier = function(opts, use3D) {
    var metric = use3D ? Visvalingam.getWeightedMetric3D(opts) : Visvalingam.getWeightedMetric(opts);
    return Visvalingam.getPathSimplifier(metric, use3D);
  };

  Visvalingam.getPathSimplifier = function(metric, use3D) {
    return Visvalingam.scaledSimplify(Visvalingam.getArcCalculator(metric, use3D));
  };


  Visvalingam.scaledSimplify = function(f) {
    return function(kk, xx, yy, zz) {
      f(kk, xx, yy, zz);
      for (var i=1, n=kk.length - 1; i<n; i++) {
        // convert area metric to a linear equivalent
        kk[i] = Math.sqrt(kk[i]) * 0.65;
      }
    };
  };

  function getSimplifyMethodLabel(slug) {
    return {
      dp: "Ramer-Douglas-Peucker",
      visvalingam: "Visvalingam",
      weighted_visvalingam: "Weighted Visvalingam"
    }[slug] || "Unknown";
  }

  function printSimplifyInfo(arcs, opts) {
    var method = getSimplifyMethod(opts);
    var name = getSimplifyMethodLabel(method);
    var spherical = useSphericalSimplify(arcs, opts);
    var stats = calcSimplifyStats(arcs, spherical);
    var pct1 = (stats.removed + stats.collapsedRings) / stats.uniqueCount || 0;
    var pct2 = stats.removed / stats.removableCount || 0;
    var aq = stats.angleQuartiles;
    var dq = stats.displacementQuartiles;
    var lines = ["Simplification statistics"];
    lines.push(utils.format("Method: %s (%s) %s", name, spherical ? 'spherical' : 'planar',
        method == 'weighted_visvalingam' ? '(weighting=' + Visvalingam.getWeightCoefficient(opts) + ')' : ''));
    lines.push(utils.format("Removed vertices: %,d", stats.removed + stats.collapsedRings));
    lines.push(utils.format("   %.1f% of %,d unique coordinate locations", pct1 * 100, stats.uniqueCount));
    lines.push(utils.format("   %.1f% of %,d filterable coordinate locations", pct2 * 100, stats.removableCount));
    lines.push(utils.format("Simplification threshold: %.4f %s", arcs.getRetainedInterval(),
        spherical ? 'meters' : ''));
    lines.push(utils.format("Collapsed rings: %,d", stats.collapsedRings));
    lines.push("Displacement statistics");
    lines.push(utils.format("   Mean displacement: %.4f", stats.displacementMean));
    lines.push(utils.format("   Max displacement: %.4f", stats.displacementMax));
    if (dq) {
      lines.push(utils.format("   Quartiles: %.2f, %.2f, %.2f", dq[0], dq[1], dq[2]));
    }
    lines.push("Vertex angle statistics");
    lines.push(utils.format("   Mean angle: %.2f degrees", stats.angleMean));
    // lines.push(utils.format("   Angles < 45: %.2f%", stats.lt45));
    if (aq) {
      lines.push(utils.format("   Quartiles: %.2f, %.2f, %.2f", aq[0], aq[1], aq[2]));
    }

    message(lines.join('\n   '));
  }

  // Remove line-segment intersections introduced by simplification by rolling
  // back simplification along intersecting segments.
  //
  // Limitation of this method: it can't remove intersections that are present
  // in the original dataset.
  // TODO: don't roll back simplification for unrepairable intersections.
  //
  function postSimplifyRepair(arcs) {
    var intersections = findSegmentIntersections(arcs),
        unfixable = repairIntersections(arcs, intersections),
        countPre = intersections.length,
        countPost = unfixable.length,
        countFixed = countPre > countPost ? countPre - countPost : 0,
        msg;
    if (countPre > 0) {
      msg = utils.format("Repaired %'i intersection%s", countFixed,
          utils.pluralSuffix(countFixed));
      if (countPost > 0) {
        msg += utils.format("; %'i intersection%s could not be repaired", countPost,
            utils.pluralSuffix(countPost));
      }
      message(msg);
    }
  }

  // @intersections (Array) Output from findSegmentIntersections()
  // Returns array of unresolved intersections, or empty array if none.
  // (export for GUI)
  function repairIntersections(arcs, intersections) {
    while (unwindIntersections(arcs, intersections) > 0) {
      intersections = findSegmentIntersections(arcs);
    }
    return intersections;
  }

  function unwindIntersections(arcs, intersections) {
    var data = arcs.getVertexData(),
        zlim = arcs.getRetainedInterval(),
        changes = 0,
        loops = 0,
        replacements, queue, target, i;

    // create a queue of unwind targets
    queue = getUnwindTargets(intersections, zlim, data.zz);
    utils.sortOn(queue, 'z', !!"ascending");

    while (queue.length > 0) {
      target = queue.pop();
      // redetect unwind target, in case a previous unwind operation has changed things
      // TODO: don't redetect if target couldn't have been affected
      replacements = redetectIntersectionTarget(target, zlim, data.xx, data.yy, data.zz);
      if (replacements.length == 1) {
        replacements = unwindIntersection(replacements[0], zlim, data.zz);
        changes++;
      }

      for (i=0; i<replacements.length; i++) {
        insertUnwindTarget(queue, replacements[i]);
      }
    }
    if (++loops > 500000) {
      verbose("Caught an infinite loop at intersection:", target);
      return 0;
    }
    return changes;
  }

  function getUnwindTargets(intersections, zlim, zz) {
    return intersections.reduce(function(memo, o) {
      var target = getUnwindTarget(o, zlim, zz);
      if (target !== null) {
        memo.push(target);
      }
      return memo;
    }, []);
  }

  // @o an intersection object
  // returns null if no vertices can be added along both segments
  // else returns an object with properties:
  //   a: intersecting segment to be partitioned
  //   b: intersecting segment to be retained
  //   z: threshold value of one or more points along [a] to be re-added
  function getUnwindTarget(o, zlim, zz) {
    var ai = findNextRemovableVertex(zz, zlim, o.a[0], o.a[1]),
        bi = findNextRemovableVertex(zz, zlim, o.b[0], o.b[1]),
        targ;
    if (ai == -1 && bi == -1) {
      targ = null;
    } else if (bi == -1 || ai != -1 && zz[ai] > zz[bi]) {
      targ = {
        a: o.a,
        b: o.b,
        z: zz[ai]
      };
    } else {
      targ = {
        a: o.b,
        b: o.a,
        z: zz[bi]
      };
    }
    return targ;
  }

  // Insert an intersection into sorted position
  function insertUnwindTarget(arr, obj) {
    var ins = arr.length;
    while (ins > 0) {
      if (arr[ins-1].z <= obj.z) {
        break;
      }
      arr[ins] = arr[ins-1];
      ins--;
    }
    arr[ins] = obj;
  }

  // Partition one of two intersecting segments by setting the removal threshold
  // of vertices indicated by @target equal to @zlim (the current simplification
  // level of the ArcCollection)
  function unwindIntersection(target, zlim, zz) {
    var replacements = [];
    var start = target.a[0],
        end = target.a[1],
        z = target.z;
    for (var i = start + 1; i <= end; i++) {
      if (zz[i] == z || i == end) {
        replacements.push({
          a: [start, i],
          b: target.b,
          z: z
        });
        if (i != end) zz[i] = zlim;
        start = i;
      }
    }
    if (replacements.length < 2) error("Error in unwindIntersection()");
    return replacements;
  }

  function redetectIntersectionTarget(targ, zlim, xx, yy, zz) {
    var segIds = getIntersectionCandidates(targ, zlim, xx, yy, zz);
    var intersections = intersectSegments(segIds, xx, yy);
    return getUnwindTargets(intersections, zlim, zz);
  }

  function getIntersectionCandidates(o, zlim, xx, yy, zz) {
    var segIds = getSegmentVertices(o.a, zlim, xx, yy, zz);
    segIds = segIds.concat(getSegmentVertices(o.b, zlim, xx, yy, zz));
    return segIds;
  }

  // Get all segments defined by two endpoints and the vertices between
  // them that are at or above the current simplification threshold.
  // TODO: test intersections with identical start + end ids
  function getSegmentVertices(seg, zlim, xx, yy, zz) {
    var start, end, prev, ids = [];
    if (seg[0] <= seg[1]) {
      start = seg[0];
      end = seg[1];
    } else {
      start = seg[1];
      end = seg[0];
    }
    prev = start;
    for (var i=start+1; i<=end; i++) {
      if (zz[i] >= zlim) {
        if (xx[prev] < xx[i]) {
          ids.push(prev, i);
        } else {
          ids.push(i, prev);
        }
        prev = i;
      }
    }
    return ids;
  }

  var PostSimplifyRepair = /*#__PURE__*/Object.freeze({
    __proto__: null,
    postSimplifyRepair: postSimplifyRepair,
    repairIntersections: repairIntersections
  });

  var DouglasPeucker = {};

  DouglasPeucker.metricSq3D = geom.pointSegDistSq3D;
  DouglasPeucker.metricSq = geom.pointSegDistSq;

  // @dest array to contain point removal thresholds
  // @xx, @yy arrays of x, y coords of a path
  // @zz (optional) array of z coords for spherical simplification
  //
  DouglasPeucker.calcArcData = function(dest, xx, yy, zz) {
    var len = dest.length,
        useZ = !!zz;

    dest[0] = dest[len-1] = Infinity;
    if (len > 2) {
      procSegment(0, len-1, 1, Number.MAX_VALUE);
    }

    function procSegment(startIdx, endIdx, depth, distSqPrev) {
      // get endpoint coords
      var ax = xx[startIdx],
          ay = yy[startIdx],
          cx = xx[endIdx],
          cy = yy[endIdx],
          az, cz;
      if (useZ) {
        az = zz[startIdx];
        cz = zz[endIdx];
      }

      var maxDistSq = 0,
          maxIdx = 0,
          distSqLeft = 0,
          distSqRight = 0,
          distSq;

      for (var i=startIdx+1; i<endIdx; i++) {
        if (useZ) {
          distSq = DouglasPeucker.metricSq3D(xx[i], yy[i], zz[i], ax, ay, az, cx, cy, cz);
        } else {
          distSq = DouglasPeucker.metricSq(xx[i], yy[i], ax, ay, cx, cy);
        }

        if (distSq >= maxDistSq) {
          maxDistSq = distSq;
          maxIdx = i;
        }
      }

      // Case -- threshold of parent segment is less than threshold of curr segment
      // Curr max point is assigned parent's threshold, so parent is not removed
      // before child as simplification is increased.
      //
      if (distSqPrev < maxDistSq) {
        maxDistSq = distSqPrev;
      }

      if (maxIdx - startIdx > 1) {
        distSqLeft = procSegment(startIdx, maxIdx, depth+1, maxDistSq);
      }
      if (endIdx - maxIdx > 1) {
        distSqRight = procSegment(maxIdx, endIdx, depth+1, maxDistSq);
      }

      // Case -- max point of curr segment is highest-threshold point of an island polygon
      // Give point the same threshold as the next-highest point, to prevent
      // a 3-vertex degenerate ring.
      if (depth == 1 && ax == cx && ay == cy) {
        maxDistSq = Math.max(distSqLeft, distSqRight);
      }

      dest[maxIdx] =  Math.sqrt(maxDistSq);
      return maxDistSq;
    }
  };

  function keepEveryPolygon(arcData, layers) {
    layers.forEach(function(lyr) {
      if (lyr.geometry_type == 'polygon') {
        protectLayerShapes(arcData, lyr.shapes);
      }
    });
  }

  function protectLayerShapes(arcData, shapes) {
    shapes.forEach(function(shape) {
      protectShape(arcData, shape);
    });
  }

  // Protect a single shape from complete removal by simplification
  // @arcData an ArcCollection
  // @shape an array containing one or more arrays of arc ids, or null if null shape
  //
  function protectShape(arcData, shape) {
    var maxArea = 0,
        arcCount = shape ? shape.length : 0,
        maxRing, area;
    // Find ring with largest bounding box
    for (var i=0; i<arcCount; i++) {
      area = arcData.getSimpleShapeBounds(shape[i]).area();
      if (area > maxArea) {
        maxRing = shape[i];
        maxArea = area;
      }
    }

    if (!maxRing || maxRing.length === 0) {
      // invald shape
      verbose("[protectShape()] Invalid shape:", shape);
    } else {
      protectPolygonRing(arcData, maxRing);
    }
  }

  // Re-inflate a polygon ring that has collapsed due to simplification by
  //   adding points in reverse order of removal until polygon is inflated.
  function protectPolygonRing(arcData, ring) {
    var zlim = arcData.getRetainedInterval(),
        // use epsilon as min area instead of 0, in case f.p. rounding produces
        // a positive area for a collapsed polygon.
        minArea = 1e-10,
        area, added;
    arcData.setRetainedInterval(Infinity);
    area = geom.getPlanarPathArea(ring, arcData);
    while (area <= minArea) {
      added = lockMaxThreshold(arcData, ring);
      if (added === 0) {
        verbose("[protectMultiRing()] Failed on ring:", ring);
        break;
      }
      area = geom.getPlanarPathArea(ring, arcData);
    }
    arcData.setRetainedInterval(zlim);
  }

  // Protect the vertex or vertices with the largest non-infinite
  // removal threshold in a ring.
  //
  function lockMaxThreshold(arcData, ring) {
    var targZ = 0,
        targArcId,
        raw = arcData.getVertexData(),
        arcId, id, z,
        start, end;

    for (var i=0; i<ring.length; i++) {
      arcId = ring[i];
      if (arcId < 0) arcId = ~arcId;
      start = raw.ii[arcId];
      end = start + raw.nn[arcId] - 1;
      id = findNextRemovableVertex(raw.zz, Infinity, start, end);
      if (id == -1) continue;
      z = raw.zz[id];
      if (z > targZ) {
        targZ = z;
        targArcId = arcId;
      }
    }
    if (targZ > 0) {
      // There may be more than one vertex with the target Z value; lock them all.
      start = raw.ii[targArcId];
      end = start + raw.nn[targArcId] - 1;
      return replaceInArray(raw.zz, targZ, Infinity, start, end);
    }
    return 0;
  }

  function replaceInArray(zz, value, replacement, start, end) {
    var count = 0;
    for (var i=start; i<=end; i++) {
      if (zz[i] === value) {
        zz[i] = replacement;
        count++;
      }
    }
    return count;
  }

  var KeepShapes = /*#__PURE__*/Object.freeze({
    __proto__: null,
    keepEveryPolygon: keepEveryPolygon,
    protectShape: protectShape,
    replaceInArray: replaceInArray
  });

  cmd.simplify = function(dataset, opts) {
    var arcs = dataset.arcs;
    if (!arcs || arcs.size() === 0) return; // removed in v0.4.125: stop("Missing path data");
    opts = getStandardSimplifyOpts(dataset, opts); // standardize options
    simplifyPaths(arcs, opts);

    // calculate and apply simplification interval
    if (opts.percentage || opts.percentage === 0) {
      arcs.setRetainedPct(utils.parsePercent(opts.percentage));
    } else if (opts.interval || opts.interval === 0) {
      arcs.setRetainedInterval(convertSimplifyInterval(opts.interval, dataset, opts));
    } else if (opts.resolution) {
      arcs.setRetainedInterval(convertSimplifyResolution(opts.resolution, arcs, opts));
    } else if (opts.presimplify) {
      return;
    } else {
      stop("Missing a simplification amount");
    }

    finalizeSimplification(dataset, opts);
  };

  function finalizeSimplification(dataset, opts) {
    var arcs = dataset.arcs;
    if (opts.keep_shapes) {
      keepEveryPolygon(arcs, dataset.layers);
    }

    if (!opts.no_repair && arcs.getRetainedInterval() > 0) {
      postSimplifyRepair(arcs);
    }

    if (opts.stats) {
      printSimplifyInfo(arcs, opts);
    }

    // stash simplification options (used by gui settings dialog)
    dataset.info = utils.defaults({simplify: opts}, dataset.info);
  }

  function getStandardSimplifyOpts(dataset, opts) {
    opts = opts || {};
    return utils.defaults({
      method: getSimplifyMethod(opts),
      spherical: useSphericalSimplify(dataset.arcs, opts)
    }, opts);
  }

  function useSphericalSimplify(arcs, opts) {
    return !opts.planar && !arcs.isPlanar();
  }

  // Calculate simplification thresholds for each vertex of an arc collection
  // (modifies @arcs ArcCollection in-place)
  function simplifyPaths(arcs, opts) {
    var simplifyPath = getSimplifyFunction(opts);
    arcs.setThresholds(new Float64Array(arcs.getPointCount())); // Create array to hold simplification data
    if (opts.spherical) {
      simplifyPaths3D(arcs, simplifyPath);
      protectWorldEdges(arcs);
    } else {
      simplifyPaths2D(arcs, simplifyPath);
    }
    if (opts.lock_box) {
      protectContentEdges(arcs);
    }
  }

  function simplifyPaths2D(arcs, simplify) {
    arcs.forEach3(function(xx, yy, kk, i) {
      simplify(kk, xx, yy);
    });
  }

  function simplifyPaths3D(arcs, simplify) {
    var xbuf = utils.expandoBuffer(Float64Array),
        ybuf = utils.expandoBuffer(Float64Array),
        zbuf = utils.expandoBuffer(Float64Array);
    arcs.forEach3(function(xx, yy, kk, i) {
      var n = xx.length,
          xx2 = xbuf(n),
          yy2 = ybuf(n),
          zz2 = zbuf(n);
      geom.convLngLatToSph(xx, yy, xx2, yy2, zz2);
      simplify(kk, xx2, yy2, zz2);
    });
  }

  function getSimplifyMethod(opts) {
    var m = opts.method;
    if (!m || m == 'weighted' || m == 'visvalingam' && opts.weighting) {
      m =  'weighted_visvalingam';
    }
    return m;
  }

  function getSimplifyFunction(opts) {
    var f;
    if (opts.method == 'dp') {
      f = DouglasPeucker.calcArcData;
    } else if (opts.method == 'visvalingam') {
      f = Visvalingam.getEffectiveAreaSimplifier(opts.spherical);
    } else if (opts.method == 'weighted_visvalingam') {
      f = Visvalingam.getWeightedSimplifier(opts, opts.spherical);
    } else {
      stop('Unsupported simplify method:', opts.method);
    }
    return f;
  }

  function protectContentEdges(arcs) {
    var e = 1e-14;
    var bb = arcs.getBounds();
    bb.padBounds(-e, -e, -e, -e);
    limitSimplificationExtent(arcs, bb.toArray(), true);
  }

  // @hardLimit
  //    true: never remove edge vertices
  //    false: never remove before other vertices
  function limitSimplificationExtent(arcs, bb, hardLimit) {
    var arcBounds = arcs.getBounds().toArray();
    // return if content doesn't reach edges
    if (geom.containsBounds(bb, arcBounds) === true) return;
    arcs.forEach3(function(xx, yy, zz) {
      var lockZ = hardLimit ? Infinity : 0,
      x, y;
      for (var i=0, n=zz.length; i<n; i++) {
        x = xx[i];
        y = yy[i];
        if (x >= bb[2] || x <= bb[0] || y <= bb[1] || y >= bb[3]) {
          if (lockZ === 0) {
            lockZ = findMaxThreshold(zz);
          }
          if (zz[i] !== Infinity) { // don't override lock value
            zz[i] = lockZ;
          }
        }
      }
    });
  }

  // Protect polar coordinates and coordinates at the prime meridian from
  // being removed before other points in a path.
  // Assume: coordinates are in decimal degrees
  //
  function protectWorldEdges(arcs) {
    // Need to handle coords with rounding errors:
    // -179.99999999999994 in test/data/ne/ne_110m_admin_0_scale_rank.shp
    // 180.00000000000003 in ne/ne_50m_admin_0_countries.shp
    limitSimplificationExtent(arcs, getWorldBounds(1e-12), false);
  }

  // Return largest value in an array, ignoring Infinity (lock value)
  //
  function findMaxThreshold(zz) {
    var z, maxZ = 0;
    for (var i=0, n=zz.length; i<n; i++) {
      z = zz[i];
      if (z > maxZ && z < Infinity) {
        maxZ = z;
      }
    }
    return maxZ;
  }

  function parseSimplifyResolution(raw) {
    var parts, w, h;
    if (utils.isNumber(raw)) {
      w = raw;
      h = raw;
    }
    else if (utils.isString(raw)) {
      parts = raw.split(/[x ,]/);
      w = Number(parts[0]) || 0;
      h = parts.length == 2 ? Number(parts[1]) || 0 : w;
    }
    if (!(w >= 0 && h >= 0 && w + h > 0)) {
      stop("Invalid simplify resolution:", raw);
    }
    return [w, h]; // TODO: validate;
  }

  function calcPlanarInterval(xres, yres, width, height) {
    var fitWidth = xres !== 0 && width / height > xres / yres || yres === 0;
    return fitWidth ? width / xres : height / yres;
  }

  // Calculate a simplification interval for unprojected data, given an output resolution
  // (This is approximate, since we don't know how the data will be projected for display)
  function calcSphericalInterval(xres, yres, bounds) {
    // Using length of arc along parallel through center of bbox as content width
    // TODO: consider using great circle instead of parallel arc to calculate width
    //    (doesn't work if width of bbox is greater than 180deg)
    var width = geom.degreesToMeters(bounds.width()) * Math.cos(bounds.centerY() * geom.D2R);
    var height = geom.degreesToMeters(bounds.height());
    return calcPlanarInterval(xres, yres, width, height);
  }

  function convertSimplifyInterval(param, dataset, opts) {
    var crs = getDatasetCRS(dataset);
    var interval;
    if (useSphericalSimplify(dataset.arcs, opts)) {
      interval = convertDistanceParam(param, crs);
    } else {
      interval = convertIntervalParam(param, crs);
    }
    return interval;
  }

  // convert resolution to an interval
  function convertSimplifyResolution(param, arcs, opts) {
    var res = parseSimplifyResolution(param);
    var bounds = arcs.getBounds();
    var interval;
    if (useSphericalSimplify(arcs, opts)) {
      interval = calcSphericalInterval(res[0], res[1], bounds);
    } else {
      interval = calcPlanarInterval(res[0], res[1], bounds.width(), bounds.height());
    }
    // scale interval to double the resolution (single-pixel resolution creates
    //  visible artifacts)
    interval *= 0.5;
    return interval;
  }

  var Simplify = /*#__PURE__*/Object.freeze({
    __proto__: null,
    finalizeSimplification: finalizeSimplification,
    getStandardSimplifyOpts: getStandardSimplifyOpts,
    useSphericalSimplify: useSphericalSimplify,
    simplifyPaths: simplifyPaths,
    getSimplifyMethod: getSimplifyMethod,
    protectWorldEdges: protectWorldEdges,
    parseSimplifyResolution: parseSimplifyResolution,
    calcPlanarInterval: calcPlanarInterval,
    calcSphericalInterval: calcSphericalInterval,
    convertSimplifyInterval: convertSimplifyInterval,
    convertSimplifyResolution: convertSimplifyResolution
  });

  cmd.sortFeatures = function(lyr, arcs, opts) {
    var n = getFeatureCount(lyr),
        ascending = !opts.descending,
        compiled = compileValueExpression(opts.expression, lyr, arcs),
        values = [];

    utils.repeat(n, function(i) {
      values.push(compiled(i));
    });

    var ids = utils.getSortedIds(values, ascending);
    if (lyr.shapes) {
      utils.reorderArray(lyr.shapes, ids);
    }
    if (lyr.data) {
      utils.reorderArray(lyr.data.getRecords(), ids);
    }
  };

  cmd.snap = function(dataset, opts) {
    var interval = 0;
    var snapCount = 0;
    var arcs = dataset.arcs;
    var arcBounds = arcs && arcs.getBounds();
    if (!arcBounds || !arcBounds.hasBounds()) {
      stop('Dataset is missing path data');
    }
    if (opts.precision) {
      setCoordinatePrecision(dataset, opts.precision);
    } else if (opts.interval) {
      interval = convertIntervalParam(opts.interval, getDatasetCRS(dataset));
    } else {
      interval = getHighPrecisionSnapInterval(arcBounds.toArray());
    }
    arcs.flatten(); // bake in any simplification
    if (interval > 0 && opts.endpoints) {
      // snaps line endpoints together
      // TODO: also snap endpoints to line segments to remove undershoots and overshoots
      snapCount = snapEndpointsByInterval(arcs, interval);
      message(utils.format("Snapped %s endpoint%s", snapCount, utils.pluralSuffix(snapCount)));
    } else if (interval > 0) {
      snapCount = snapCoordsByInterval(arcs, interval);
      message(utils.format("Snapped %s point%s", snapCount, utils.pluralSuffix(snapCount)));
    }
    if (snapCount > 0 || opts.precision) {
      arcs.dedupCoords();
      buildTopology(dataset);
    }
  };

  // @expression: optional field name or expression
  //
  cmd.splitLayer = function(src, expression, optsArg) {
    var opts = optsArg || {},
        lyr0 = opts.no_replace ? copyLayer(src) : src,
        properties = lyr0.data ? lyr0.data.getRecords() : null,
        shapes = lyr0.shapes,
        index = {},
        splitLayers = [],
        namer;

    if (opts.ids) {
      namer = getIdSplitFunction(opts.ids);
    } else {
      namer = getSplitNameFunction(lyr0, expression);
    }

    // if (splitField) {
    //   internal.requireDataField(lyr0, splitField);
    // }

    utils.repeat(getFeatureCount(lyr0), function(i) {
      var name = namer(i),
          lyr;

      if (name in index === false) {
        index[name] = splitLayers.length;
        lyr = {
          geometry_type: lyr0.geometry_type,
          name: name,
          data: properties ? new DataTable() : null,
          shapes: shapes ? [] : null
        };
        splitLayers.push(lyr);
      } else {
        lyr = splitLayers[index[name]];
      }
      if (shapes) {
        lyr.shapes.push(shapes[i]);
      }
      if (properties) {
        lyr.data.getRecords().push(properties[i]);
      }
    });
    return splitLayers;
  };

  function getIdSplitFunction(ids) {
    var set = new Set(ids);
    return function(i) {
      return set.has(i) ? '1' : '2';
    };
  }

  function getDefaultSplitFunction(lyr) {
    // if not splitting on an expression and layer is unnamed, name split-apart layers
    // like: split-1, split-2, ...
    return function(i) {
      return (lyr && lyr.name || 'split') + '-' + (i + 1);
    };
  }

  function getSplitNameFunction(lyr, exp) {
    var compiled;
    if (!exp) return getDefaultSplitFunction(lyr);
    lyr = {name: lyr.name, data: lyr.data}; // remove shape info
    compiled = compileValueExpression(exp, lyr, null);
    return function(i) {
      var val = compiled(i);
      return String(val);
      // return val || val === 0 ? String(val) : '';
    };
  }


  // internal.getSplitKey = function(i, field, properties) {
  //   var rec = field && properties ? properties[i] : null;
  //   return String(rec ? rec[field] : i + 1);
  // };

  // internal.getSplitLayerName = function(base, key) {
  //   return (base ? base + '-' : '') + key;
  // };

  // internal.getStringInterpolator = function(str) {
  //   var body = 'with($$ctx) { return `' + str + '`; }';
  //   var f = new Function("$$ctx", body);
  //   return function(o) {
  //     var s = '';
  //     try {
  //       s = f(ctx);
  //     } catch(e) {
  //       stop("Unable to interpolate [" + str + "]");
  //     }
  //     return s;
  //   }
  // };

  var Split = /*#__PURE__*/Object.freeze({
    __proto__: null,
    getSplitNameFunction: getSplitNameFunction
  });

  cmd.stop = function(job) {
    stopJob(job);
  };

  cmd.svgStyle = function(lyr, dataset, opts) {
    var filter;
    if (!lyr.data) {
      initDataTable(lyr);
    }
    if (opts.where) {
      filter = compileValueExpression(opts.where, lyr, dataset.arcs);
    }
    Object.keys(opts).forEach(function(optName) {
      var svgName = optName.replace('_', '-'); // undo cli parser name conversion
      if (!isSupportedSvgStyleProperty(svgName)) {
        return;
      }
      var strVal = opts[optName].trim();
      var accessor = getSymbolPropertyAccessor(strVal, svgName, lyr);
      getLayerDataTable(lyr).getRecords().forEach(function(rec, i) {
        if (filter && !filter(i)) {
          // make sure field exists if record is excluded by filter
          if (svgName in rec === false) {
            rec[svgName] = undefined;
          }
        } else {
          rec[svgName] = accessor(i);
        }
      });
    });
  };

  var roundCoord = getRoundingFunction(0.01);

  function getSymbolFillColor(d) {
    return d.fill || 'magenta';
  }

  function getSymbolStrokeColor(d) {
    return d.stroke || d.fill || 'magenta';
  }

  function getSymbolRadius(d) {
    if (d.radius === 0 || d.length === 0 || d.r === 0) return 0;
    return d.radius || d.length || d.r || 5; // use a default value
  }

  function forEachSymbolCoord(coords, cb) {
    var isPoint = coords && utils.isNumber(coords[0]);
    var isNested = !isPoint && coords && Array.isArray(coords[0]);
    if (isPoint) return cb(coords);
    for (var i=0; i<coords.length; i++) {
      if (isNested) forEachSymbolCoord(coords[i], cb);
    }
  }

  function flipY(coords) {
    forEachSymbolCoord(coords, function(p) {
      p[1] = -p[1];
    });
  }

  function scaleAndShiftCoords(coords, scale, shift) {
    forEachSymbolCoord(coords, function(xy) {
      xy[0] = xy[0] * scale + shift[0];
      xy[1] = xy[1] * scale + shift[1];
    });
  }

  function roundCoordsForSVG(coords) {
    forEachSymbolCoord(coords, function(p) {
      p[0] = roundCoord(p[0]);
      p[1] = roundCoord(p[1]);
    });
  }

  function rotateCoords(coords, rotation) {
    if (!rotation) return;
    var f = getAffineTransform(rotation, 1, [0, 0], [0, 0]);
    forEachSymbolCoord(coords, function(p) {
      var p2 = f(p[0], p[1]);
      p[0] = p2[0];
      p[1] = p2[1];
    });
  }

  function getStickArrowCoords(d) {
    return getArrowCoords(d, 'stick');
  }

  function getFilledArrowCoords(d) {
    return getArrowCoords(d, 'standard');
  }

  function getArrowCoords(d, style) {
    var stickArrow = style == 'stick',
        // direction = d.rotation || d.direction || 0,
        direction = d.direction || 0, // rotation is an independent parameter
        stemTaper = d['stem-taper'] || 0,
        curvature = d['stem-curve'] || 0,
        size = calcArrowSize(d, stickArrow);
    if (!size) return null;
    var stemLen = size.stemLen,
        headLen = size.headLen,
        headDx = size.headWidth / 2,
        stemDx = size.stemWidth / 2,
        baseDx = stemDx * (1 - stemTaper),
        head, stem, coords, dx, dy;

    if (curvature) {
      // make curved stem
      if (direction > 0) curvature = -curvature;
      var theta = Math.abs(curvature) / 180 * Math.PI;
      var sign = curvature > 0 ? 1 : -1;
      var ax = baseDx * Math.cos(theta); // rotate arrow base
      var ay = baseDx * Math.sin(theta) * -sign;
      dx = stemLen * Math.sin(theta / 2) * sign;
      dy = stemLen * Math.cos(theta / 2);

      if (stickArrow) {
        stem = getCurvedStemCoords(-ax, -ay, dx, dy);
      } else {
        var leftStem = getCurvedStemCoords(-ax, -ay, -stemDx + dx, dy);
        var rightStem = getCurvedStemCoords(ax, ay, stemDx + dx, dy);
        stem = leftStem.concat(rightStem.reverse());
      }

    } else {
      // make straight stem
      dx = 0;
      dy = stemLen;
      if (stickArrow) {
        stem = [[0, 0], [0, stemLen]];
      } else {
        stem = [[-baseDx, 0], [baseDx, 0]];
      }
    }

    if (stickArrow) {
      // make stick arrow
      head = [[-headDx + dx, stemLen - headLen], [dx, stemLen], [headDx + dx, stemLen - headLen]];
      coords = [stem, head]; // MultiLineString coords
    } else {
      // make filled arrow
      // coordinates go counter clockwise, starting from the leftmost head coordinate
      head = [[stemDx + dx, dy], [headDx + dx, dy],
          [dx, headLen + dy], [-headDx + dx, dy], [-stemDx + dx, dy]];
      coords = stem.concat(head);
      coords.push(stem[0].concat()); // closed path
      coords = [coords]; // Polygon coords
    }

    if (d.anchor == 'end') {
      scaleAndShiftCoords(coords, 1, [-dx, -dy - headLen]);
    } else if (d.anchor == 'middle') {
      // shift midpoint away from the head a bit for a more balanced placement
      // scaleAndShiftCoords(coords, 1, [-dx/2, (-dy - headLen)/2]);
      scaleAndShiftCoords(coords, 1, [-dx * 0.5, -dy * 0.5 - headLen * 0.25]);
    }

    rotateCoords(coords, direction);
    if (d.flipped) {
      flipY(coords);
    }
    return coords;
  }

  // function calcStraightArrowCoords(stemLen, headLen, stemDx, headDx, baseDx) {
  //   return [[baseDx, 0], [stemDx, stemLen], [headDx, stemLen], [0, stemLen + headLen],
  //         [-headDx, stemLen], [-stemDx, stemLen], [-baseDx, 0], [baseDx, 0]];
  // }

  function calcArrowSize(d, stickArrow) {
    // don't display arrows with negative length
    var totalLen = Math.max(d.radius || d.length || d.r || 0, 0),
        scale = 1,
        o = initArrowSize(d); // calc several parameters

    if (totalLen >= 0) {
      scale = calcScale(totalLen, o.headLen, d);
      o.stemWidth *= scale;
      o.headWidth *= scale;
      o.headLen *= scale;
      o.stemLen = stickArrow ? totalLen : totalLen - o.headLen;
    }

    if (o.headWidth < o.stemWidth) {
      stop('Arrow head must be at least as wide as the stem.');
    }
    return o;
  }

  function calcScale(totalLen, headLen, d) {
    var minStemRatio = d['min-stem-ratio'] >= 0 ? d['min-stem-ratio'] : 0;
    var stemLen = d['stem-length'] || 0;
    var maxHeadPct = 1 - minStemRatio;
    var headPct = headLen / totalLen;
    var scale = 1;

    if (headPct > maxHeadPct) {
      scale = maxHeadPct / headPct;
    } else if (stemLen + headLen > totalLen) {
      scale = totalLen / (stemLen + headLen);
    }
    return scale || 0;
  }

  function initArrowSize(d) {
    var sizeRatio = getHeadSizeRatio(d['head-angle'] || 40); // length to width
    var o = {
      stemWidth: d['stem-width'] || 2,
      stemLen: d['stem-length'] || 0,
      headWidth: d['head-width'],
      headLen: d['head-length']
    };
    if (!o.headWidth) {
      if (o.headLen) {
        o.headWidth = o.headLen / sizeRatio;
      } else {
        o.headWidth = o.stemWidth * 3; // assumes stemWidth has been set
      }
    }
    if (!o.headLen) {
      o.headLen = o.headWidth * sizeRatio;
    }
    return o;
  }


  // Returns ratio of head length to head width
  function getHeadSizeRatio(headAngle) {
    return 1 / Math.tan(Math.PI * headAngle / 180 / 2) / 2;
  }


  // ax, ay: point on the base
  // bx, by: point on the stem
  function getCurvedStemCoords(ax, ay, bx, by) {
    // case: curved side intrudes into head (because stem is too short)
    if (ay > by) {
      return [[ax * by / ay, by]];
    }
    var dx = bx - ax,
        dy = by - ay,
        dy1 = (dy * dy - dx * dx) / (2 * dy),
        dy2 = dy - dy1,
        dx2 = Math.sqrt(dx * dx + dy * dy) / 2,
        theta = Math.PI - Math.asin(dx2 / dy2) * 2,
        degrees = theta * 180 / Math.PI,
        radius = dy2 / Math.tan(theta / 2),
        leftBend = bx > ax,
        sign = leftBend ? 1 : -1,
        points = Math.round(degrees / 5) + 2,
        increment = theta / (points + 1),
        coords = [[bx, by]];

    for (var i=1; i<= points; i++) {
      var phi = i * increment / 2;
      var sinPhi = Math.sin(phi);
      var cosPhi = Math.cos(phi);
      var c = sinPhi * radius * 2;
      var a = sinPhi * c;
      var b = cosPhi * c;
      coords.push([bx - a * sign, by - b]);
    }
    coords.push([ax, ay]);
    return coords;
  }

  function makeCircleSymbol(d, opts) {
    var radius = getSymbolRadius(d);
    // TODO: remove duplication with svg-symbols.js
    if (+opts.scale) radius *= +opts.scale;
    return {
      type: 'circle',
      fill: getSymbolFillColor(d),
      r: radius
    };
  }

  function getPolygonCoords(d) {
    var radius = getSymbolRadius(d),
        sides = +d.sides || getSidesByType(d.type),
        rotated = sides % 2 == 1,
        coords = [],
        angle, b;

    if (radius > 0 === false) return null;
    if (sides >= 3 === false) {
      stop(`Invalid number of sides (${sides})`);
    }
    if (d.orientation == 'b' || d.flipped || d.rotated) {
      rotated = !rotated;
    }
    b = rotated ? 0 : 0.5;
    for (var i=0; i<sides; i++) {
      angle = (i + b) / sides * 360;
      coords.push(getPlanarSegmentEndpoint(0, 0, angle, radius));
    }
    coords.push(coords[0].concat());
    return [coords];
  }

  function getSidesByType(type) {
    return {
      circle: 72,
      triangle: 3,
      square: 4,
      pentagon: 5,
      hexagon: 6,
      heptagon: 7,
      octagon: 8,
      nonagon: 9,
      decagon: 10
    }[type] || 4;
  }

  function getStarCoords(d) {
    var radius = getSymbolRadius(d),
        points = d.points || d.sides && d.sides / 2 || 5,
        sides = points * 2,
        minorRadius = getMinorRadius(points) * radius,
        b = d.orientation == 'b' || d.flipped || d.rotated ? 0 : 1,
        coords = [],
        angle, len;

    if (radius > 0 === false) return null;
    if (points < 5) {
      stop(`Invalid number of points for a star (${points})`);
    }
    for (var i=0; i<sides; i++) {
      len = i % 2 == 0 ? minorRadius : radius;
      angle = (i + b) / sides * 360;
      coords.push(getPlanarSegmentEndpoint(0, 0, angle, len));
    }
    coords.push(coords[0].concat());
    return [coords];
  }

  function getMinorRadius(points) {
    var innerAngle = 360 / points;
    var pointAngle = getDefaultPointAngle(points);
    var thetaA = Math.PI / 180 * innerAngle / 2;
    var thetaB = Math.PI / 180 * pointAngle / 2;
    var a = Math.tan(thetaB) / (Math.tan(thetaB) + Math.tan(thetaA));
    var c = a / Math.cos(thetaA);
    return c;
  }

  function getDefaultPointAngle(points) {
    var minSkip = 1;
    var maxSkip = Math.ceil(points / 2) - 2;
    var skip = Math.floor((maxSkip + minSkip) / 2);
    return getPointAngle(points, skip);
  }

  // skip: number of adjacent points to skip when drawing a segment
  function getPointAngle(points, skip) {
    var unitAngle = 360 / points;
    var centerAngle = unitAngle * (skip + 1);
    return 180 - centerAngle;
  }

  // Returns a svg-symbol object
  function makeRingSymbol(d, opts) {
    var scale = +opts.scale || 1;
    var radii = parseRings(d.radii || '2').map(function(r) { return r * scale; });
    var solidCenter = utils.isOdd(radii.length);
    var color = getSymbolFillColor(d);
    var parts = [];
    if (solidCenter) {
      parts.push({
        type: 'circle',
        fill: color,
        r: radii.shift()
      });
    }
    for (var i=0; i<radii.length; i+= 2) {
      parts.push({
        type: 'circle',
        fill: 'none', // TODO remove default black fill so this is not needed
        stroke: color,
        'stroke-width':  roundToTenths(radii[i+1] - radii[i]),
        r: roundToTenths(radii[i+1] * 0.5 + radii[i] * 0.5)
      });
    }
    return {
      type: 'group',
      parts: parts
    };
  }

  // Returns GeoJSON MultiPolygon coords
  function getRingCoords(d) {
    var radii = parseRings(d.radii || '2');
    var coords = [];
    var solidCenter = utils.isOdd(radii.length);
    var ring, hole;
    for (var i=0; i<radii.length; i++) {
      ring = getPolygonCoords({
        type: 'circle',
        radius: radii[i]
      });
      if (!solidCenter || i > 0) {
        i++;
        hole = ring;
        ring = getPolygonCoords({
          type: 'circle',
          radius: radii[i]
        });
        ring.push(hole[0]);
      }
      coords.push(ring);
    }
    return coords;
  }

  function parseRings(arg) {
    var arr = Array.isArray(arg) ? arg : parseNumberList(arg);
    utils.genericSort(arr, true);
    return utils.uniq(arr);
  }

  // Returns an svg-symbol data object for one symbol
  function makePathSymbol(coords, properties, geojsonType) {
    var sym;
    if (geojsonType == 'MultiPolygon' || geojsonType == 'Polygon') {
      sym = {
        type: 'polygon',
        fill: getSymbolFillColor(properties),
        coordinates: geojsonType == 'Polygon' ? coords : flattenMultiPolygonCoords(coords)
      };
    } else if (geojsonType == 'LineString' || geojsonType == 'MultiLineString') {
      sym = {
        type: 'polyline',
        stroke: getSymbolStrokeColor(properties),
        'stroke-width': properties['stroke-width'] || 2,
        coordinates: geojsonType == 'LineString' ? [coords] : coords
      };
    } else {
      error('Unsupported type:', geojsonType);
    }
    roundCoordsForSVG(sym.coordinates);
    return sym;
  }

  // TODO: refactor to remove duplication in mapshaper-svg-style.js
  cmd.symbols = function(inputLyr, dataset, opts) {
    requireSinglePointLayer(inputLyr);
    var lyr = opts.no_replace ? copyLayer(inputLyr) : inputLyr;
    var shapeMode = !!opts.geographic;
    var metersPerPx;
    if (shapeMode) {
      requireProjectedDataset(dataset);
      metersPerPx = opts.pixel_scale || getMetersPerPixel(lyr);
    }
    var records = getLayerDataTable(lyr).getRecords();
    var getSymbolData = getSymbolDataAccessor(lyr, opts);
    var geometries = lyr.shapes.map(function(shp, i) {
      if (!shp) return null;
      var d = getSymbolData(i);
      var rec = records[i] || {};

      // non-polygon symbols
      if (!shapeMode && d.type == 'circle') {
        rec['svg-symbol'] = makeCircleSymbol(d, opts);
        return;
      }
      if (!shapeMode && d.type == 'ring') {
        rec['svg-symbol'] = makeRingSymbol(d, opts);
        return;
      }

      var geojsonType = 'Polygon';
      var coords;
      // these symbols get converted to polygon shapes
      if (d.type == 'arrow' && opts.arrow_style == 'stick') {
        coords = getStickArrowCoords(d);
        geojsonType = 'MultiLineString';
      } else if (d.type == 'arrow') {
        coords = getFilledArrowCoords(d);
      } else if (d.type == 'ring') {
        coords = getRingCoords(d);
        geojsonType = 'MultiPolygon';
      } else if (d.type == 'star') {
        coords = getStarCoords(d);
      } else {
        coords = getPolygonCoords(d);
      }
      if (!coords) return null;
      rotateCoords(coords, +d.rotation || 0);
      if (!shapeMode) {
        flipY(coords);
      }
      if (+opts.scale) {
        scaleAndShiftCoords(coords, +opts.scale, [0, 0]);
      }
      if (shapeMode) {
        scaleAndShiftCoords(coords, metersPerPx, shp[0]);
        if (d.fill) rec.fill = d.fill;
        if (d.stroke) rec.stroke = d.stroke;
        return createGeometry(coords, geojsonType);
      } else {
        rec['svg-symbol'] = makePathSymbol(coords, d, geojsonType);
      }
    });

    var outputLyr, dataset2;
    if (shapeMode) {
      dataset2 = importGeometries(geometries, records);
      outputLyr = mergeOutputLayerIntoDataset(inputLyr, dataset, dataset2, opts);
      outputLyr.data = lyr.data;
    } else {
      outputLyr = lyr;
    }
    return [outputLyr];
  };

  function importGeometries(geometries, records) {
    var features = geometries.map(function(geom, i) {
      records[i];
      return {
        type: 'Feature',
        properties: records[i] || null,
        geometry: geom
      };
    });
    var geojson = {
      type: 'FeatureCollection',
      features: features
    };
    return importGeoJSON(geojson);
  }

  function createGeometry(coords, type) {
    return {
      type: type,
      coordinates: coords
    };
  }

  function getMetersPerPixel(lyr, dataset) {
    var bounds = getLayerBounds(lyr);
    // TODO: need a better way to handle a single point with no extent
    var extent = bounds.width() || bounds.height() || 1000;
    return extent / 800;
  }

  var Symbols = /*#__PURE__*/Object.freeze({
    __proto__: null
  });

  cmd.target = function(catalog, opts) {
    var type = (opts.type || '').toLowerCase().replace('linestring', 'polyline');
    var pattern = opts.target || '*';
    var targets = catalog.findCommandTargets(pattern, type);
    if (type && 'polygon,polyline,point'.split(',').indexOf(type) == -1) {
      stop("Invalid layer type:", opts.type);
    }
    if (targets.length === 0) {
      stop("No layers were matched (pattern: " + pattern + (type ? ' type: ' + type : '') + ")");
    }
    if (opts.name || opts.name === '') {
      // TODO: improve this
      targets[0].layers[0].name = opts.name;
    }
    catalog.setDefaultTargets(targets);
  };

  cmd.union = function(targetLayers, targetDataset, opts) {
    if (targetLayers.length < 2) {
      stop('Command requires at least two target layers');
    }
    targetLayers.forEach(requirePolygonLayer);

    // Need to add cuts before creating merged layer (arc ids may change)
    var nodes = addIntersectionCuts(targetDataset, opts);
    var allFields = [];
    var allShapes = [];
    var layerData = [];
    targetLayers.forEach(function(lyr, i) {
      var fields = lyr.data ? lyr.data.getFields() : [];
      if (opts.fields) {
        fields = opts.fields.indexOf('*') > 1 ? fields :
          fields.filter(function(name) {return opts.fields.indexOf(name) > -1;});
      }
      layerData.push({
        layer: lyr,
        fields: fields,
        records: lyr.data ? lyr.data.getRecords() : null,
        offset: allShapes.length,
        size: lyr.shapes.length
      });
      allFields = allFields.concat(fields);
      allShapes = allShapes.concat(lyr.shapes);
    });
    var unionFields = utils.uniqifyNames(allFields, function(name, n) {
      return name + '_' + n;
    });
    var mergedLyr = {
      geometry_type: 'polygon',
      shapes: allShapes
    };
    var mosaicIndex = new MosaicIndex(mergedLyr, nodes, {flat: false});
    var mosaicShapes = mosaicIndex.mosaic;
    var mosaicRecords = mosaicShapes.map(function(shp, i) {
      var mergedIds = mosaicIndex.getSourceIdsByTileId(i);
      var values = [];
      var lyrInfo, srcId, rec;
      for (var lyrId=0, n=layerData.length; lyrId < n; lyrId++) {
        lyrInfo = layerData[lyrId];
        srcId = unionFindOriginId(mergedIds, lyrInfo.offset, lyrInfo.size);
        rec = srcId == -1 || lyrInfo.records === null ? null : lyrInfo.records[srcId];
        unionAddDataValues(values, lyrInfo.fields, rec);
      }
      return unionMakeDataRecord(unionFields, values);
    });

    var unionLyr = {
      name: 'union',
      geometry_type: 'polygon',
      shapes: mosaicShapes,
      data: new DataTable(mosaicRecords)
    };
    return [unionLyr];
  };

  function unionFindOriginId(mergedIds, offset, length) {
    var mergedId;
    for (var i=0; i<mergedIds.length; i++) {
      mergedId = mergedIds[i];
      if (mergedId >= offset && mergedId < offset + length) {
        return mergedId - offset;
      }
    }
    return -1;
  }

  function unionAddDataValues(arr, fields, rec) {
    for (var i=0; i<fields.length; i++) {
      arr.push(rec ? rec[fields[i]] : null);
    }
  }

  function unionMakeDataRecord(fields, values) {
    var rec = {};
    for (var i=0; i<fields.length; i++) {
      rec[fields[i]] = values[i];
    }
    return rec;
  }

  cmd.uniq = function(lyr, arcs, opts) {
    var n = getFeatureCount(lyr),
        compiled = compileValueExpression(opts.expression, lyr, arcs),
        maxCount = opts.max_count || 1,
        counts = {},
        keepFlags = [],
        verbose = !!opts.verbose,
        invert = !!opts.invert,
        index = !!opts.index,
        records = lyr.data ? lyr.data.getRecords() : null,
        filter = function(d, i) {return keepFlags[i];};


    utils.repeat(n, function(i) {
      var val = compiled(i);
      var count = val in counts ? counts[val] + 1 : 1;
      var keep = count <= maxCount;
      var rec;
      if (index) {
        keep = true;
        rec = records && records[i];
        if (rec) rec.index = count;
      } else if (invert) {
        keep = !keep;
      }
      keepFlags[i] = keep;
      counts[val] = count;
      if (verbose && !keep) {
        message(utils.format('Removing feature %i key: [%s]', i, val));
      }
    });

    if (lyr.shapes) {
      lyr.shapes = lyr.shapes.filter(filter);
    }
    if (records) {
      lyr.data = new DataTable(records.filter(filter));
    }
    if (opts.verbose !== false) {
      message(utils.format('Retained %,d of %,d features', getFeatureCount(lyr), n));
    }
  };

  cmd.variableSimplify = function(layers, dataset, opts) {
    var lyr = layers[0];
    var arcs = dataset.arcs;
    var getShapeThreshold;
    var arcThresholds;
    if (layers.length != 1) {
      stop('Variable simplification requires a single target layer');
    }
    if (!layerHasPaths(lyr)) {
      stop('Target layer is missing path data');
    }

    opts = getStandardSimplifyOpts(dataset, opts);
    simplifyPaths(arcs, opts);

    if (opts.interval) {
      getShapeThreshold = getVariableIntervalFunction(opts.interval, lyr, dataset, opts);
    } else if (opts.percentage) {
      getShapeThreshold = getVariablePercentageFunction(opts.percentage, lyr, dataset);
    } else if (opts.resolution) {
      getShapeThreshold = getVariableResolutionFunction(opts.resolution, lyr, dataset, opts);
    } else {
      stop("Missing a simplification expression");
    }

    arcThresholds = calculateVariableThresholds(lyr, arcs, getShapeThreshold);
    applyArcThresholds(arcs, arcThresholds);
    arcs.setRetainedInterval(1e20); // set to a huge value
    finalizeSimplification(dataset, opts);
    arcs.flatten(); // bake in simplification (different from standard -simplify)
  };

  function getVariableIntervalFunction(exp, lyr, dataset, opts) {
    var compiled = compileSimplifyExpression(exp, lyr, dataset.arcs);
    return function(shpId) {
      var val = compiled(shpId);
      return convertSimplifyInterval(val, dataset, opts);
    };
  }

  function getVariableResolutionFunction(exp, lyr, dataset, opts) {
    var compiled = compileSimplifyExpression(exp, lyr, dataset.arcs);
    return function(shpId) {
      var val = compiled(shpId);
      return convertSimplifyResolution(val, dataset.arcs, opts);
    };
  }

  function getVariablePercentageFunction(exp, lyr, dataset, opts) {
    var compiled = compileSimplifyExpression(exp, lyr, dataset.arcs);
    var pctToInterval = getThresholdFunction(dataset.arcs);
    return function(shpId) {
      var val = compiled(shpId);
      var pct = utils.parsePercent(val);
      return pctToInterval(pct);
    };
  }

  // TODO: memoize?
  function compileSimplifyExpression(exp, lyr, arcs) {
    return compileValueExpression(exp, lyr, arcs);
  }

  // Filter arcs based on an array of thresholds
  function applyArcThresholds(arcs, thresholds) {
    arcs.getVertexData().zz;
    arcs.forEach2(function(start, n, xx, yy, zz, arcId) {
      var arcZ = thresholds[arcId];
      var z;
      for (var i=1; i<n-1; i++) {
        z = zz[start + i];
        // if (z >= arcZ || arcZ === Infinity) { // Infinity test is a bug
        if (z >= arcZ) {
          // protect vertices with thresholds that are >= than the computed threshold
          // for this arc
          zz[start + i] = Infinity;
        }
      }
    });
  }

  function calculateVariableThresholds(lyr, arcs, getShapeThreshold) {
    var thresholds = new Float64Array(arcs.size()); // init to 0s
    var UNUSED = -1;
    var currThresh;
    utils.initializeArray(thresholds, UNUSED);
    lyr.shapes.forEach(function(shp, shpId) {
      currThresh = getShapeThreshold(shpId);
      forEachArcId(shp || [], procArc);
    });
    // set unset arcs to 0 so they are not simplified
    for (var i=0, n=thresholds.length; i<n; i++) {
      if (thresholds[i] == UNUSED) {
        thresholds[i] = 0;
      }
    }
    return thresholds;

    function procArc(arcId) {
      var i = arcId < 0 ? ~arcId : arcId;
      var savedThresh = thresholds[i];
      if (savedThresh > currThresh || savedThresh == UNUSED) {
        thresholds[i] = currThresh;
      }
    }
  }

  // Split the shapes in a layer according to a grid
  // Return array of layers. Use -o bbox-index option to create index
  //
  cmd.splitLayerOnGrid = function(lyr, arcs, opts) {
    var shapes = lyr.shapes,
        type = lyr.geometry_type,
        setId = !!opts.id_field, // assign id but, don't split to layers
        fieldName = opts.id_field || "__split__",
        classify = getShapeClassifier(getLayerBounds(lyr, arcs), opts.cols, opts.rows),
        properties;

    if (!type) {
      stop("Layer has no geometry");
    }

    if (!lyr.data) {
      lyr.data = new DataTable(shapes.length);
    }
    properties = lyr.data.getRecords();

    lyr.shapes.forEach(function(shp, i) {
      var bounds = type == 'point' ? getPointBounds$1([shp]) : arcs.getMultiShapeBounds(shp);
      var name = bounds.hasBounds() ? classify(bounds) : '';
      var rec = properties[i] = properties[i] || {};
      rec[fieldName] = name;
    });

    if (setId) return lyr; // don't split layer (instead assign cell ids)

    return cmd.splitLayer(lyr, fieldName).filter(function(lyr) {
      var name = lyr.data.getRecordAt(0)[fieldName];
      lyr.name = name;
      lyr.data.deleteField(fieldName);
      return !!name;
    });

    function getShapeClassifier(bounds, cols, rows) {
      var xmin = bounds.xmin,
          ymin = bounds.ymin,
          w = bounds.width(),
          h = bounds.height();

      if (rows > 0 === false || cols > 0 === false) {
        stop('Invalid grid parameters');
      }

      if (w > 0 === false || h > 0 === false) {
        cols = 1;
        rows = 1;
      }

      return function(bounds) {
        var c = Math.floor((bounds.centerX() - xmin) / w * cols),
            r = Math.floor((bounds.centerY() - ymin) / h * rows);
        c = utils.clamp(c, 0, cols-1) || 0;
        r = utils.clamp(r, 0, rows-1) || 0;
        return "r" + r + "c" + c;
      };
    }
  };

  // Recursively divide a layer into two layers until a (compiled) expression
  // no longer returns true. The original layer is split along the long side of
  // its bounding box, so that each split-off layer contains half of the original
  // shapes (+/- 1).
  //
  cmd.subdivideLayer = function(lyr, arcs, exp) {
    return subdivide(lyr, arcs, exp);
  };

  function subdivide(lyr, arcs, exp) {
    var divide = evalCalcExpression(lyr, arcs, exp),
        subdividedLayers = [],
        tmp, bounds, lyr1, lyr2, layerName;

    if (!utils.isBoolean(divide)) {
      stop("Expression must evaluate to true or false");
    }
    if (divide) {
      bounds = getLayerBounds(lyr, arcs);
      tmp = divideLayer(lyr, arcs, bounds);
      lyr1 = tmp[0];
      if (lyr1.shapes.length > 1 && lyr1.shapes.length < lyr.shapes.length) {
        utils.merge(subdividedLayers, subdivide(lyr1, arcs, exp));
      } else {
        subdividedLayers.push(lyr1);
      }

      lyr2 = tmp[1];
      if (lyr2.shapes.length > 1 && lyr2.shapes.length < lyr.shapes.length) {
        utils.merge(subdividedLayers, subdivide(lyr2, arcs, exp));
      } else {
        subdividedLayers.push(lyr2);
      }
    } else {
      subdividedLayers.push(lyr);
    }
    layerName = getSplitNameFunction(lyr);
    subdividedLayers.forEach(function(lyr2, i) {
      lyr2.name = layerName(i);
      utils.defaults(lyr2, lyr);
    });
    return subdividedLayers;
  }

  // split one layer into two layers containing the same number of shapes (+-1),
  // either horizontally or vertically
  //
  function divideLayer(lyr, arcs, bounds) {
    var properties = lyr.data ? lyr.data.getRecords() : null,
        shapes = lyr.shapes,
        lyr1, lyr2;
    lyr1 = {
      geometry_type: lyr.geometry_type,
      shapes: [],
      data: properties ? [] : null
    };
    lyr2 = {
      geometry_type: lyr.geometry_type,
      shapes: [],
      data: properties ? [] : null
    };

    var useX = bounds && bounds.width() > bounds.height();
    // TODO: think about case where there are null shapes with NaN centers
    var centers = shapes.map(function(shp) {
      var bounds = arcs.getMultiShapeBounds(shp);
      return useX ? bounds.centerX() : bounds.centerY();
    });
    var ids = utils.range(centers.length);
    ids.sort(function(a, b) {
      return centers[a] - centers[b];
    });
    ids.forEach(function(shapeId, i) {
      var dest = i < shapes.length / 2 ? lyr1 : lyr2;
      dest.shapes.push(shapes[shapeId]);
      if (properties) {
        dest.data.push(properties[shapeId]);
      }
    });

    if (properties) {
      lyr1.data = new DataTable(lyr1.data);
      lyr2.data = new DataTable(lyr2.data);
    }
    return [lyr1, lyr2];
  }

  function commandAcceptsMultipleTargetDatasets(name) {
    return name == 'rotate' || name == 'info' || name == 'proj' ||
      name == 'drop' || name == 'target' || name == 'if' || name == 'elif' ||
      name == 'else' || name == 'endif';
  }

  function commandAcceptsEmptyTarget(name) {
    return name == 'graticule' || name == 'i' || name == 'help' ||
      name == 'point-grid' || name == 'shape' || name == 'rectangle' ||
      name == 'require' || name == 'run' || name == 'define' ||
      name == 'include' || name == 'print' || name == 'comment' || name == 'if' || name == 'elif' ||
      name == 'else' || name == 'endif' || name == 'stop' || name == 'add-shape';
  }

  async function runCommand(command, job) {
    var name = command.name,
        opts = command.options,
        source,
        outputDataset,
        outputLayers,
        outputFiles,
        targets,
        targetDataset,
        targetLayers,
        arcs;

    if (skipCommand(name, job)) {
      return done(null);
    }

    if (!job) job = new Job();
    job.startCommand(command);

    try { // catch errors from synchronous functions
      T$1.start();

      if (name == 'rename-layers') {
        // default target is all layers
        targets = job.catalog.findCommandTargets(opts.target || '*');
        targetLayers = targets.reduce(function(memo, obj) {
          return memo.concat(obj.layers);
        }, []);

      } else if (name == 'o') {
        // when combining GeoJSON layers, default is all layers
        // TODO: check that combine_layers is only used w/ GeoJSON output
        targets = job.catalog.findCommandTargets(opts.target || opts.combine_layers && '*');

      } else if (commandAcceptsMultipleTargetDatasets(name)) {
        targets = job.catalog.findCommandTargets(opts.target);

      } else {
        targets = job.catalog.findCommandTargets(opts.target);
        // special case to allow -merge-layers and -union to combine layers from multiple datasets
        // TODO: support multi-dataset targets for other commands
        if (targets.length > 1 && (name == 'merge-layers' || name == 'union')) {
          targets = mergeCommandTargets(targets, job.catalog);
        }

        if (targets.length == 1) {
          targetDataset = targets[0].dataset;
          arcs = targetDataset.arcs;
          targetLayers = targets[0].layers;
          // target= option sets default target
          job.catalog.setDefaultTarget(targetLayers, targetDataset);

        } else if (targets.length > 1) {
          stop("This command does not support targetting layers from different datasets");
        }
      }

      if (targets.length === 0) {
        if (opts.target) {
          stop(utils.format('Missing target: %s\nAvailable layers: %s',
              opts.target, getFormattedLayerList(job.catalog)));
        }
        if (!commandAcceptsEmptyTarget(name)) {
          throw new UserError("No data is available");
        }
      }

      if (opts.source) {
        source = findCommandSource(convertSourceName(opts.source, targets), job.catalog, opts);
      }

      if (name == 'add-shape') {
        if (!targetDataset) {
          targetDataset = {info: {}, layers: []};
          targetLayers = targetDataset.layers;
          job.catalog.addDataset(targetDataset);
        }
        outputLayers = cmd.addShape(targetLayers, targetDataset, opts);
      } else if (name == 'affine') {
        cmd.affine(targetLayers, targetDataset, opts);

      } else if (name == 'alpha-shapes') {
        outputLayers = applyCommandToEachLayer(cmd.alphaShapes, targetLayers, targetDataset, opts);
        // outputLayers = null;

      } else if (name == 'buffer') {
         outputLayers = applyCommandToEachLayer(cmd.buffer, targetLayers, targetDataset, opts);
        // outputLayers = cmd.buffer(targetLayers, targetDataset, opts);

      } else if (name == 'data-fill') {
        applyCommandToEachLayer(cmd.dataFill, targetLayers, arcs, opts);

      } else if (name == 'cluster') {
        applyCommandToEachLayer(cmd.cluster, targetLayers, arcs, opts);

      } else if (name == 'calc') {
        applyCommandToEachLayer(cmd.calc, targetLayers, arcs, opts);

      } else if (name == 'classify') {
        applyCommandToEachLayer(cmd.classify, targetLayers, targetDataset, opts);

      } else if (name == 'clean') {
        cmd.cleanLayers(targetLayers, targetDataset, opts);

      } else if (name == 'clip') {
        outputLayers = cmd.clipLayers(targetLayers, source, targetDataset, opts);

      } else if (name == 'colorizer') {
        outputLayers = cmd.colorizer(opts);

      } else if (name == 'comment') {
        // no-op

      } else if (name == 'dashlines') {
        applyCommandToEachLayer(cmd.dashlines, targetLayers, targetDataset, opts);

      } else if (name == 'define') {
        cmd.define(opts);

      } else if (name == 'dissolve') {
        outputLayers = applyCommandToEachLayer(cmd.dissolve, targetLayers, arcs, opts);

      } else if (name == 'dissolve2') {
        outputLayers = cmd.dissolve2(targetLayers, targetDataset, opts);

      } else if (name == 'divide') {
        cmd.divide(targetLayers, targetDataset, source, opts);

      } else if (name == 'dots') {
        outputLayers = applyCommandToEachLayer(cmd.dots, targetLayers, arcs, opts);

      } else if (name == 'drop') {
        cmd.drop2(job.catalog, targets, opts);
        // cmd.drop(catalog, targetLayers, targetDataset, opts);

      } else if (name == 'each') {
        applyCommandToEachLayer(cmd.evaluateEachFeature, targetLayers, targetDataset, opts.expression, opts);

      } else if (name == 'erase') {
        outputLayers = cmd.eraseLayers(targetLayers, source, targetDataset, opts);

      } else if (name == 'explode') {
        outputLayers = applyCommandToEachLayer(cmd.explodeFeatures, targetLayers, arcs, opts);

      } else if (name == 'external') {
        cmd.external(opts);

      } else if (name == 'filter') {
        outputLayers = applyCommandToEachLayer(cmd.filterFeatures, targetLayers, arcs, opts);

      } else if (name == 'filter-fields') {
        applyCommandToEachLayer(cmd.filterFields, targetLayers, opts.fields);

      } else if (name == 'filter-geom') {
        applyCommandToEachLayer(cmd.filterGeom, targetLayers, arcs, opts);

      } else if (name == 'filter-islands') {
        applyCommandToEachLayer(cmd.filterIslands, targetLayers, targetDataset, opts);

      } else if (name == 'filter-islands2') {
        applyCommandToEachLayer(cmd.filterIslands2, targetLayers, targetDataset, opts);

      } else if (name == 'filter-points') {
        applyCommandToEachLayer(cmd.filterPoints, targetLayers, targetDataset, opts);

      } else if (name == 'filter-slivers') {
        applyCommandToEachLayer(cmd.filterSlivers, targetLayers, targetDataset, opts);

      } else if (name == 'frame') {
        cmd.frame(job.catalog, source, opts);

      } else if (name == 'fuzzy-join') {
        applyCommandToEachLayer(cmd.fuzzyJoin, targetLayers, arcs, source, opts);

      } else if (name == 'graticule') {
        job.catalog.addDataset(cmd.graticule(targetDataset, opts));

      } else if (name == 'help') {
        // placing this here to handle errors from invalid command names
        getOptionParser().printHelp(command.options.command);

      } else if (name == 'i') {
        if (opts.replace) job.catalog = new Catalog(); // is this what we want?
        targetDataset = await cmd.importFiles(job.catalog, command.options);
        if (targetDataset) {
          outputLayers = targetDataset.layers; // kludge to allow layer naming below
        }

      } else if (name == 'if' || name == 'elif') {
        // target = findSingleTargetLayer(opts.layer, targets[0], catalog);
        // cmd[name](target.layer, target.dataset, opts);
        cmd[name](job, opts);

      } else if (name == 'else' || name == 'endif') {
        cmd[name](job);

      } else if (name == 'ignore') {
        applyCommandToEachLayer(cmd.ignore, targetLayers, targetDataset, opts);

      } else if (name == 'include') {
        cmd.include(opts);

      } else if (name == 'info') {
        cmd.info(targets, opts);

      } else if (name == 'inlay') {
        outputLayers = cmd.inlay(targetLayers, source, targetDataset, opts);

      } else if (name == 'inspect') {
        applyCommandToEachLayer(cmd.inspect, targetLayers, arcs, opts);

      } else if (name == 'innerlines') {
        outputLayers = applyCommandToEachLayer(cmd.innerlines, targetLayers, arcs, opts);

      } else if (name == 'join') {
        applyCommandToEachLayer(cmd.join, targetLayers, targetDataset, source, opts);

      } else if (name == 'lines') {
        outputLayers = applyCommandToEachLayer(cmd.lines, targetLayers, targetDataset, opts);

      } else if (name == 'merge-layers') {
        // returned layers are modified input layers
        // (assumes that targetLayers are replaced by outputLayers below)
        outputLayers = cmd.mergeAndFlattenLayers(targetLayers, targetDataset, opts);
        // outputLayers = cmd.mergeLayers(targetLayers, opts);

      } else if (name == 'mosaic') {
        // opts.no_replace = true; // add mosaic as a new layer
        outputLayers = cmd.mosaic(targetLayers, targetDataset, opts);

      } else if (name == 'o') {
        outputFiles = await exportTargetLayers(targets, opts);
        if (opts.final) {
          // don't propagate data if output is final
          //// catalog = null;
          job.catalog = new Catalog();
        }
        await utils.promisify(writeFiles)(outputFiles, opts);

      } else if (name == 'point-grid') {
        outputLayers = [cmd.pointGrid(targetDataset, opts)];
        if (!targetDataset) {
          job.catalog.addDataset({layers: outputLayers});
        }

      } else if (name == 'point-to-grid') {
        outputLayers = cmd.pointToGrid(targetLayers, targetDataset, opts);

      } else if (name == 'grid') {
        outputDataset = cmd.polygonGrid(targetLayers, targetDataset, opts);

      } else if (name == 'points') {
        outputLayers = applyCommandToEachLayer(cmd.createPointLayer, targetLayers, targetDataset, opts);

      } else if (name == 'polygons') {
        outputLayers = cmd.polygons(targetLayers, targetDataset, opts);

      } else if (name == 'print') {
        cmd.print(command._.join(' '));

      } else if (name == 'proj') {
        await utils.promisify(initProjLibrary)(opts);
        job.resumeCommand();
        targets.forEach(function(targ) {
          cmd.proj(targ.dataset, job.catalog, opts);
        });

      } else if (name == 'rectangle') {
        if (source || opts.bbox || targets.length === 0) {
          job.catalog.addDataset(cmd.rectangle(source, opts));
        } else {
          outputLayers = cmd.rectangle2(targets[0], opts);
        }

      } else if (name == 'rectangles') {
        outputLayers = applyCommandToEachLayer(cmd.rectangles, targetLayers, targetDataset, opts);

      } else if (name == 'rename-fields') {
        applyCommandToEachLayer(cmd.renameFields, targetLayers, opts.fields);

      } else if (name == 'rename-layers') {
        cmd.renameLayers(targetLayers, opts.names, job.catalog);

      } else if (name == 'require') {
        cmd.require(targets, opts);

      } else if (name == 'rotate') {
        targets.forEach(function(targ) {
          cmd.rotate(targ.dataset, opts);
        });

      } else if (name == 'run') {
        await utils.promisify(cmd.run)(job, targets, opts);

      } else if (name == 'scalebar') {
        cmd.scalebar(job.catalog, opts);

      } else if (name == 'shape') {
        job.catalog.addDataset(cmd.shape(targetDataset, opts));

      } else if (name == 'shapes') {
        outputLayers = applyCommandToEachLayer(cmd.shapes, targetLayers, targetDataset, opts);

      } else if (name == 'simplify') {
        if (opts.variable) {
          cmd.variableSimplify(targetLayers, targetDataset, opts);
        } else {
          cmd.simplify(targetDataset, opts);
        }

      } else if (name == 'slice') {
        outputLayers = cmd.sliceLayers(targetLayers, source, targetDataset, opts);

      } else if (name == 'snap') {
        cmd.snap(targetDataset, opts);

      } else if (name == 'sort') {
        applyCommandToEachLayer(cmd.sortFeatures, targetLayers, arcs, opts);

      } else if (name == 'split') {
        outputLayers = applyCommandToEachLayer(cmd.splitLayer, targetLayers, opts.expression, opts);

      } else if (name == 'stop') {
        cmd.stop(job);

      } else if (name == 'split-on-grid') {
        outputLayers = applyCommandToEachLayer(cmd.splitLayerOnGrid, targetLayers, arcs, opts);

      } else if (name == 'stitch') {
        cmd.stitch(targetDataset);

      } else if (name == 'style') {
        applyCommandToEachLayer(cmd.svgStyle, targetLayers, targetDataset, opts);

      } else if (name == 'symbols') {
        outputLayers = applyCommandToEachLayer(cmd.symbols, targetLayers, targetDataset, opts);

      } else if (name == 'subdivide') {
        outputLayers = applyCommandToEachLayer(cmd.subdivideLayer, targetLayers, arcs, opts.expression);

      } else if (name == 'target') {
        cmd.target(job.catalog, opts);

      } else if (name == 'union') {
        outputLayers = cmd.union(targetLayers, targetDataset, opts);

      } else if (name == 'uniq') {
        applyCommandToEachLayer(cmd.uniq, targetLayers, arcs, opts);

      } else {
        // throws error if command is not registered
        cmd.runExternalCommand(command, job.catalog);
      }

      // apply name parameter
      if (('name' in opts) && outputLayers) {
        // TODO: consider uniqifying multiple layers here
        outputLayers.forEach(function(lyr) {
          lyr.name = opts.name;
        });
      }

      if (outputDataset) {
        job.catalog.addDataset(outputDataset); // also sets default target
        outputLayers = outputDataset.layers;
        if (targetLayers && !opts.no_replace) {
          // remove target layers from target dataset
          targetLayers.forEach(function(lyr) {
            job.catalog.deleteLayer(lyr, targetDataset);
          });
        }
      } else if (outputLayers && targetDataset && outputLayers != targetDataset.layers) {
        // integrate output layers into the target dataset
        if (opts.no_replace) {
          // make sure commands do not return input layers with 'no_replace' option
          if (!outputLayersAreDifferent(outputLayers, targetLayers || [])) {
            error('Command returned invalid output');
          }

          targetDataset.layers = targetDataset.layers.concat(outputLayers);
        } else {
          // TODO: consider replacing old layers as they are generated, for gc
          replaceLayers(targetDataset, targetLayers, outputLayers);
          // some operations leave unreferenced arcs that should be cleaned up
          if ((name == 'clip' || name == 'erase' || name == 'rectangle' ||
              name == 'rectangles' || name == 'filter' && opts.cleanup) && !opts.no_cleanup) {
            dissolveArcs(targetDataset);
          }
        }

        if (opts.apart) {
          job.catalog.setDefaultTargets(splitApartLayers( targetDataset, outputLayers).map(function(dataset) {
            return {
              dataset: dataset,
              layers: dataset.layers.concat()
            };
          }));
        } else {
          // use command output as new default target
          job.catalog.setDefaultTarget(outputLayers, targetDataset);
        }
      }

      // delete arcs if no longer needed (e.g. after -points command)
      // (after output layers have been integrated)
      if (targetDataset) {
        cleanupArcs(targetDataset);
      }
    } catch(e) {
      return done(e);
    }

    // non-erroring synchronous commands are done
    return done(null);

    function done(err) {
      job.endCommand();
      verbose('-', T$1.stop());
      if (err) throw err;
      return job;
    }
  }

  function outputLayersAreDifferent(output, input) {
    return !utils.some(input, function(lyr) {
      return output.indexOf(lyr) > -1;
    });
  }

  // Apply a command to an array of target layers
  function applyCommandToEachLayer(func, targetLayers) {
    var args = utils.toArray(arguments).slice(2);
    return targetLayers.reduce(function(memo, lyr) {
      var result = func.apply(null, [lyr].concat(args));
      if (utils.isArray(result)) { // some commands return an array of layers
        memo = memo.concat(result);
      } else if (result) { // assuming result is a layer
        memo.push(result);
      }
      return memo;
    }, []);
  }

  // Parse command line args into commands and run them
  // Function takes an optional Node-style callback. A Promise is returned if no callback is given.
  //   function(argv[, input], callback)
  //   function(argv[, input]) (returns Promise)
  // argv: String or array containing command line args.
  // input: (optional) Object containing file contents indexed by filename
  //
  function runCommands(argv) {
    var opts = importRunArgs.apply(null, arguments);
    _runCommands(argv, opts, function(err) {
      opts.callback(err);
    });
    if (opts.promise) return opts.promise;
  }

  // Similar to runCommands(), but returns output files to the callback or Promise
  //   instead of using file I/O.
  // Callback signature: function(<error>, <data>) -- data is an object
  //   containing output from any -o commands, indexed by filename.
  //
  function applyCommands(argv) {
    var opts = importRunArgs.apply(null, arguments);
    var callback = opts.callback;
    var outputArr = opts.output = []; // output gets added to this array
    _runCommands(argv, opts, function(err) {
      if (err) {
        return callback(err);
      }
      if (opts.legacy) return callback(null, toLegacyOutputFormat(outputArr));
      return callback(null, toOutputFormat(outputArr));
    });
    if (opts.promise) return opts.promise;
  }

  // Run commands with extra heap memory
  //   function(argv[, options], callback)
  //   function(argv[, options]) (returns Promise)
  // options: (optional) object with "xl" property, e.g. {xl: "16gb"}
  //
  function runCommandsXL(argv) {
    var opts = importRunArgs.apply(null, arguments);
    var mapshaperScript = require$1('path').join(__dirname, 'bin/mapshaper');
    var gb = parseFloat(opts.options.xl) || 8;
    var err;
    if (gb < 1 || gb > 64) {
      err = new Error('Unsupported heap size:' + gb + 'GB');
      printError(err);
      opts.callback(err);
      return opts.promise; // may be undefined
    }
    if (!loggingEnabled()) argv += ' -quiet'; // kludge to pass logging setting to subprocess
    var mb = Math.round(gb * 1000);
    var command = [process.execPath, '--max-old-space-size=' + mb, mapshaperScript, argv].join(' ');
    var child = require$1('child_process').exec(command, {}, function(err, stdout, stderr) {
      opts.callback(err);
    });
    child.stdout.pipe(process.stdout);
    child.stderr.pipe(process.stderr);
    if (opts.promise) return opts.promise;
  }

  // Parse the arguments from runCommands() or applyCommands()
  function importRunArgs(arg0, arg1, arg2) {
    var opts = {options: {}};
    if (utils.isFunction(arg1)) {
      opts.callback = arg1;
    } else if (utils.isFunction(arg2)) {
      opts.callback = arg2;
      // identify legacy input format (used by some tests)
      opts.legacy = arg1 && guessInputContentType(arg1) != null;
      opts.input = arg1;
    } else {
      // if no callback, create a promise and a callback for resolving the promise
      opts.promise = new Promise(function(resolve, reject) {
        opts.callback = function(err, data) {
          if (err) reject(err);
          else resolve(data);
        };
      });
    }
    if (!opts.legacy && utils.isObject(arg1)) {
      if (arg1.xl) {
        // options for runCommandsXL()
        opts.options = arg1;
      } else {
        // input data for runCommands() and applyCommands()
        opts.input = arg1;
      }
    }
    return opts;
  }

  // Return an object containing content of zero or more output files, indexed by filename.
  function toOutputFormat(arr) {
    return arr.reduce(function(memo, o) {
      memo[o.filename] = o.content;
      return memo;
    }, {});
  }

  // Unified function for processing calls to runCommands() and applyCommands()
  function _runCommands(argv, opts, callback) {

    var outputArr = opts.output || null,
        inputObj = opts.input,
        commands;
    try {
      commands = parseCommands(argv);
    } catch(e) {
      printError(e);
      return callback(e);
    }

    if (opts.legacy) {
      message("Warning: deprecated input format");
      commands = convertLegacyCommands(commands, inputObj);
      inputObj = null;
    }

    if (commands.length === 0) {
      return callback(new UserError("No commands to run"));
    }

    commands = runAndRemoveInfoCommands(commands);
    if (commands.length === 0) return done(null);

    // add options to -i -o -join -clip -erase etc. commands to bypass file i/o
    // TODO: find a less kludgy solution
    commands.forEach(function(cmd) {
      if (commandTakesFileInput(cmd.name) && inputObj) {
        cmd.options.input = inputObj;
      }
      if (outputArr && (cmd.name == 'o' || cmd.name == 'info' && cmd.options.save_to)) {
        cmd.options.output = outputArr;
      }
    });

    var batches = divideImportCommand(commands);
    utils.reduceAsync(batches, null, nextGroup, done);

    function nextGroup(prevJob, commands, next) {
      runParsedCommands(commands, new Job(), function(err, job) {
        err = filterError(err);
        next(err, job);
      });
    }

    function done(err, job) {
      err = filterError(err);
      if (err) printError(err);
      callback(err, job);
    }
  }

  function commandTakesFileInput(name) {
    return (name == 'i' || name == 'join' || name == 'erase' || name == 'clip' || name == 'include');
  }

  function toLegacyOutputFormat(arr) {
    if (arr.length > 1) {
      // Return an array if multiple files are output
      return utils.pluck(arr, 'content');
    }
    if (arr.length == 1) {
      // Return content if a single file is output
      return arr[0].content;
    }
    return null;
  }

  function convertLegacyCommands(arr, inputObj) {
    var i = utils.find(arr, function(cmd) {return cmd.name == 'i';});
    var o = utils.find(arr, function(cmd) {return cmd.name == 'o';});
    if (!i) {
      i = {name: 'i', options: {}};
      arr.unshift(i);
    }
    i.options.files = ['__input__'];
    i.options.input = {__input__: inputObj};
    if (!o) {
      arr.push({name: 'o', options: {}});
    }
    return arr;
  }

  // TODO: rewrite tests and remove this function
  function testCommands(argv, done) {
    _runCommands(argv, {}, function(err, job) {
      var targets = job ? job.catalog.getDefaultTargets() : [];
      var output;
      if (!err && targets.length > 0) {
        // returns dataset for compatibility with some older tests
        output = targets[0].dataset;
      }
      done(err, output);
    });
  }


  // Execute a sequence of parsed commands
  // @commands Array of parsed commands
  // @job: Job object containing previously imported data
  // @done: function([error], [job])
  //
  function runParsedCommands(commands, job, done) {
    if (!runningInBrowser() && commands[commands.length-1].name == 'o') {
      // in CLI, set 'final' flag on final -o command, so the export function knows
      // that it can modify the output dataset in-place instead of making a copy.
      commands[commands.length-1].options.final = true;
    }
    if (!job) job = new Job();
    commands = readAndRemoveSettings(job, commands);
    // if (!runningInBrowser()) {
    //   printStartupMessages();
    // }
    commands = runAndRemoveInfoCommands(commands);
    if (commands.length === 0) {
      return done(null);
    }
    // we're no longer using the same Job for all batches -- no reset needed
    // // resetting closes any unterminated -if blocks from a previous command sequence
    // resetControlFlow(job);
    utils.reduceAsync(commands, job, nextCommand, done);

    function nextCommand(job, cmd, next) {
      runCommand(cmd, job).then(function(result) {
        next(null, result);
      }).catch(function(e) {
        next(e);
      });
    }
  }

  function filterError(err) {
    if (err && err.name == 'NonFatalError') {
      printError(err);
      return null;
    }
    return err;
  }

  // If an initial import command indicates that several input files should be
  //   processed separately, then duplicate the sequence of commands to run
  //   once for each input file
  // @commands Array of parsed commands
  // Returns: Array of one or more sequences of parsed commands
  //
  function divideImportCommand(commands) {
    var firstCmd = commands[0],
        opts = firstCmd.options;

    if (firstCmd.name != 'i' || opts.stdin || opts.merge_files ||
      opts.combine_files || !opts.files || opts.files.length < 2) {
      return [commands];
    }

    return opts.files.map(function(file) {
      var group = [{
        name: 'i',
        options: utils.defaults({
          files:[file],
          replace: true  // kludge to replace data catalog
        }, opts)
      }];
      group.push.apply(group, commands.slice(1));
      return group;
    });
  }


  function printStartupMessages() {
    // print heap memory message if running with a custom amount
    var rxp = /^--max-old-space-size=([0-9]+)$/;
    var arg = process.execArgv.find(function(s) {
      return rxp.test(s);
    });
    if (arg) {
      message('Allocating', rxp.exec(arg)[1] / 1000, 'GB of heap memory');
    }
  }

  // Some settings use command syntax and are parsed as commands.
  function readAndRemoveSettings(job, commands) {
    var settings = {VERBOSE: false, QUIET: false, DEBUG: false};
    var filtered = commands.filter(function(cmd) {
      if (cmd.name == 'verbose') {
        settings.VERBOSE = true;
      } else if (cmd.name == 'quiet') {
        settings.QUIET = true;
      } else if (cmd.name == 'debug') {
        settings.DEBUG = true;
      } else {
        return true;
      }
      return false;
    });
    job.initSettings(settings);
    return filtered;
  }

  // Run informational commands and remove them from the array of parsed commands
  function runAndRemoveInfoCommands(commands) {
    return commands.filter(function(cmd) {
      if (cmd.name == 'version') {
        print(typeof VERSION == 'undefined' ? '' : VERSION);
      } else if (cmd.name == 'encodings') {
        printEncodings();
      } else if (cmd.name == 'colors') {
        printColorSchemeNames();
      } else if (cmd.name == 'projections') {
        printProjections();
      } else {
        return true;
      }
      return false;
    });
  }

  var RunCommands = /*#__PURE__*/Object.freeze({
    __proto__: null,
    runCommands: runCommands,
    applyCommands: applyCommands,
    runCommandsXL: runCommandsXL,
    testCommands: testCommands,
    runParsedCommands: runParsedCommands,
    runAndRemoveInfoCommands: runAndRemoveInfoCommands
  });

  // the mapshaper public api only has 4 functions
  var coreAPI = {
    runCommands,
    applyCommands,
    runCommandsXL,
    enableLogging
  };

  // Return an array containing points from a path iterator, clipped to a bounding box
  // Currently using this function for clipping styled polygons in the GUI to speed up layer rendering.
  // Artifacts along the edges make this unsuitable for clipping datasets
  // TODO: support clipping a single-part shape to multiple parts
  // TODO: prevent artifacts along edges
  function clipIterByBounds(iter, bounds) {
    var points = [];
    var bbox = getClippingBBox(bounds);
    var xy, xyp, first, isRing;
    while (iter.hasNext()) {
      xy = [iter.x, iter.y];
      addClippedPoint(points, xyp, xy, bbox);
      xyp = xy;
      if (!first) first = xy;
    }
    // detect closed rings
    isRing = pointsAreEqual(first, xy);
    if (isRing && points.length > 0 && !pointsAreEqual(points[0], points[points.length - 1])) {
      // some rings need to be closed
      points.push(points[0].concat());
    }
    if (isRing && points.length < 4 || points.length < 2) {
      // catch defective rings and polylines
      points = [];
    }
    return points;
  }

  function pointsAreEqual(a, b) {
    return a && b && a[0] === b[0] && a[1] === b[1];
  }

  //  2 3 4
  //  1 8 5
  //  0 7 6
  function getPointSector(x, y, bbox) {
    var bl = bbox[0];
    var tr = bbox[2];
    var i;
    if (x > tr[0]) {
      i = y > tr[1] && 4 || y >= bl[1] && 5 || 6; // right col
    } else if (x >= bl[0]) {
      i = y > tr[1] && 3 || y >= bl[1] && 8 || 7; // middle col
    } else {
      i = y > tr[1] && 2 || y >= bl[1] && 1 || 0; // left col
    }
    return i;
  }

  function isCornerSector(q) {
    return q == 0 || q == 2 || q == 4 || q == 6;
  }

  // Number of CCW turns to normalize
  function getSectorRotation(q) {
    return q > 1 && q < 8 ? Math.floor(q / 2) : 0;
  }

  // i: rotation number
  // b: bbox object
  function rotateClippingBox(i, bbox) {
    var a = bbox[0],
        b = bbox[1],
        c = bbox[2],
        d = bbox[3];
    if (i === 0) {
      bbox = [a, b, c, d];
    } else if (i == 1) {
      bbox = [b, c, d, a];
    } else if (i == 2) {
      bbox = [c, d, a, b];
    } else if (i == 3) {
      bbox = [d, a, b, c];
    } else error('Invalid rotation number');
    return bbox;
  }

  // Convert a Bounds object to an array of 4 points designed to be rotated
  function getClippingBBox(bounds) {
    return [[bounds.xmin, bounds.ymin],
            [bounds.xmin, bounds.ymax],
            [bounds.xmax, bounds.ymax],
            [bounds.xmax, bounds.ymin]];
  }

  // i: ccw turns (0-3)
  function rotateSector(i, q) {
    return q < 8 && q >= 0 ? (q + 8 - i * 2) % 8 : q;
  }

  function getCornerBySector(q, bbox) {
    if (isCornerSector(q)) {
      return bbox[q / 2].concat();
    }
    error('Invalid corner sector:', q);
  }

  function addCornerPoint(points, q, bbox) {
    points.push(getCornerBySector(q, bbox));
  }

  function addClippedPoint(points, p1, p2, bbox) {
    var q1 = p1 ? getPointSector(p1[0], p1[1], bbox) : -1;
    var q2 = getPointSector(p2[0], p2[1], bbox);
    var rot;
    // even polylines need to be connected along bbox edges to prevent artifact
    //   segments cutting through the bbox
    // TODO: convert disconnected parts to individual polylines or rings
    var closed = true;

    if (q1 == 8 && q2 == 8) {
      // segment is fully within box
      points.push(p2);

    } else if (q1 == q2) ; else if (q1 == -1) {
      // p2 is first point in the path
      if (q2 == 8) {
        points.push(p2);
      } else if (isCornerSector(q2)) {
        addCornerPoint(points, q2, bbox);
      }

    } else if (q1 == 8) {
      // segment leaves box
      addSegmentBoundsIntersection(points, p1, p2, bbox);
      if (isCornerSector(q2)) {
        addCornerPoint(points, q2, bbox);
      }

    } else if (q2 == 8) {
      // segment enters box
      addSegmentBoundsIntersection(points, p1, p2, bbox);
      points.push(p2);

    } else {
      // segment travels from one outer sector to another outer sector
      // normalise segment by rotating bbox so that p1 is
      // in the 0 or 1 sector relative to the bbox coordinates, if p1 is in an
      // outer segment
      rot = getSectorRotation(q1);
      bbox = rotateClippingBox(rot, bbox);
      q1 = rotateSector(rot, q1);
      q2 = rotateSector(rot, q2);
      if (q1 == 0) {
        // first point is in a corner sector
        if (q2 === 0 || q2 === 1 || q2 === 7) ; else if (q2 == 2 || q2 == 6) {
          // move to adjacent corner
          addCornerPoint(points, q2, bbox);

        } else if (q2 == 3) {
          // far left edge (intersection or left corner)
          if (!addSegmentBoundsIntersection(points, p1, p2, bbox) && closed) addCornerPoint(points, 2, bbox);

        } else if (q2 == 4) {
          // opposite corner
          if (!addSegmentBoundsIntersection(points, p1, p2, bbox)) {
            // determine if bbox is to the left or right of segment
            if (geom.orient2D(p1[0], p1[1], p2[0], p2[1], bbox[0][0], bbox[0][1]) > 1) {
              // bbox is on the left (seg -> nearest corner is CCW)
              addCornerPoint(points, 6, bbox);
            } else {
              // bbox is on the right
              addCornerPoint(points, 2, bbox);
            }
          }
          addCornerPoint(points, q2, bbox);

        } else if (q2 == 5) {
          // far right edge (intersection or right corner)
          if (!addSegmentBoundsIntersection(points, p1, p2, bbox) && closed) addCornerPoint(points, 6, bbox);
        }

      } else if (q1 == 1) {
        // first point is in a side sector
        if (q2 == 2 || q2 === 0) {
          // near left corner, near right corner
          addCornerPoint(points, q2, bbox);

        } else if (q2 == 3) {
          // to left side
          if (!addSegmentBoundsIntersection(points, p1, p2, bbox) && closed) addCornerPoint(points, 2, bbox);

        } else if (q2 == 4) {
          // to far left corner
          if (!addSegmentBoundsIntersection(points, p1, p2, bbox) && closed) addCornerPoint(points, 2, bbox);
          addCornerPoint(points, 4, bbox);

        } else if (q2 == 5) {
          // to opposite side
          addSegmentBoundsIntersection(points, p1, p2, bbox);

        } else if (q2 == 6) {
          // to far right corner
          if (!addSegmentBoundsIntersection(points, p1, p2, bbox) && closed) addCornerPoint(points, 0, bbox);
          addCornerPoint(points, 6, bbox);

        } else if (q2 == 7) {
          // to right side
          if (!addSegmentBoundsIntersection(points, p1, p2, bbox) && closed) addCornerPoint(points, 0, bbox);
        }

      } else {
        error("Sector error");
      }
    }
  }

  function addSegmentSegmentIntersection(points, a, b, c, d) {
    var p = geom.segmentIntersection(a[0], a[1], b[0], b[1], c[0], c[1],
          d[0], d[1]);
    if (p) points.push(p);
  }

  function addSegmentBoundsIntersection(points, a, b, bounds) {
    var hits = [];
    addSegmentSegmentIntersection(hits, a, b, bounds[0], bounds[1]); // first edge
    addSegmentSegmentIntersection(hits, a, b, bounds[0], bounds[3]); // last edge
    addSegmentSegmentIntersection(hits, a, b, bounds[1], bounds[2]);
    addSegmentSegmentIntersection(hits, a, b, bounds[2], bounds[3]);
    if (hits.length > 0 ) {
      points.push.apply(points, hits);
      return true;
    }
    return false;
  }

  // TODO: Need to rethink polygon repair: these function can cause problems
  // when part of a self-intersecting polygon is removed
  //
  function repairPolygonGeometry(layers, dataset, opts) {
    var nodes = addIntersectionCuts(dataset);
    layers.forEach(function(lyr) {
      repairSelfIntersections(lyr, nodes);
    });
    return layers;
  }

  // Remove any small shapes formed by twists in each ring
  // // OOPS, NO // Retain only the part with largest area
  // // this causes problems when a cut-off hole has a matching ring in another polygon
  // TODO: consider cases where cut-off parts should be retained
  //
  function repairSelfIntersections(lyr, nodes) {
    var splitter = getSelfIntersectionSplitter(nodes);

    lyr.shapes = lyr.shapes.map(function(shp, i) {
      return cleanPolygon(shp);
    });

    function cleanPolygon(shp) {
      var cleanedPolygon = [];
      forEachShapePart(shp, function(ids) {
        // TODO: consider returning null if path can't be split
        var splitIds = splitter(ids);
        if (splitIds.length === 0) {
          error("[cleanPolygon()] Defective path:", ids);
        } else if (splitIds.length == 1) {
          cleanedPolygon.push(splitIds[0]);
        } else {
          var shapeArea = geom.getPlanarPathArea(ids, nodes.arcs),
              sign = shapeArea > 0 ? 1 : -1,
              mainRing;

          splitIds.reduce(function(max, ringIds, i) {
            var pathArea = geom.getPlanarPathArea(ringIds, nodes.arcs) * sign;
            if (pathArea > max) {
              mainRing = ringIds;
              max = pathArea;
            }
            return max;
          }, 0);

          if (mainRing) {
            cleanedPolygon.push(mainRing);
          }
        }
      });
      return cleanedPolygon.length > 0 ? cleanedPolygon : null;
    }
  }

  var PolygonRepair = /*#__PURE__*/Object.freeze({
    __proto__: null,
    repairPolygonGeometry: repairPolygonGeometry,
    repairSelfIntersections: repairSelfIntersections
  });

  // Attach functions exported by modules to the "internal" object,
  // so they can be run by tests and by the GUI.
  // TODO: rewrite tests to import functions directly from modules,
  //       export only functions called by the GUI.
  var internal = {};

  internal.svg = Object.assign({}, SvgStringify, SvgPathUtils, GeojsonToSvg, SvgLabels, SvgSymbols);

  // Assign functions and objects exported from modules to the 'internal' namespace
  // to maintain compatibility with tests and to expose (some of) them to the GUI.

  Object.assign(internal, {
    Job,
    Dbf,
    DbfReader,
    DouglasPeucker,
    geojson: GeoJSON,
    json: { parse: parse },
    ShpType,
    topojson: TopoJSON,
    Visvalingam,
    ArcCollection,
    Bounds,
    clipIterByBounds,
    CommandParser,
    DataTable,
    editArcs,
    GeoJSONReader,
    Heap,
    NodeCollection,
    parseDMS,
    PathIndex,
    PolygonIndex,
    ShpReader,
    Transform
  });

  Object.assign(internal,
    AnchorPoints,
    ArcClassifier,
    ArcDissolve,
    ArcUtils,
    Bbox2Clipping,
    BinArray$1,
    BufferCommon,
    Calc,
    CalcUtils,
    Catalog$1,
    ClipErase,
    ClipPoints,
    Colorizer,
    CustomProjections,
    DataAggregation,
    DatasetUtils,
    DataUtils,
    DbfImport,
    DelimExport,
    DelimImport,
    DelimReader,
    Encodings,
    Explode,
    Export,
    Expressions,
    FileExport,
    FileImport,
    FilenameUtils,
    FileReader$1,
    FileTypes,
    FilterGeom,
    Frame,
    FrameData,
    Furniture,
    Geodesic,
    GeojsonExport,
    GeojsonImport,
    Gzip,
    Import,
    Info,
    IntersectionCuts,
    Join,
    JoinCalc,
    JoinFilter,
    JoinTables,
    JsonImport,
    JsonTable,
    KeepShapes,
    LatLon,
    LayerUtils,
    Lines,
    Logging,
    Merging,
    MosaicIndex$1,
    OptionParsingUtils,
    OutputFormat,
    OverlayUtils,
    Pack, Unpack,
    ParseCommands,
    PathBuffer,
    PathEndpoints,
    PathExport,
    Pathfinder,
    PathfinderUtils,
    PathImport,
    PathRepair,
    PathUtils,
    PixelTransform,
    PointPolygonJoin,
    Points,
    PointUtils,
    PolygonDissolve,
    PolygonDissolve2,
    PolygonHoles,
    PolygonMosaic,
    PolygonNeighbors,
    PolygonRepair,
    PolygonTiler$1,
    PolylineClipping,
    PostSimplifyRepair,
    Proj,
    Projections,
    ProjectionParams,
    Rectangle,
    Rounding,
    RunCommands,
    Scalebar,
    SegmentIntersection,
    ShapeIter$1,
    ShapeUtils,
    ShpCommon,
    ShpExport,
    ShpImport,
    Simplify,
    SimplifyFast,
    SimplifyPct,
    Slivers,
    Snapping,
    SourceUtils,
    Split,
    Env,
    Stash,
    Stringify,
    Svg,
    SvgProperties,
    Symbols,
    TargetUtils,
    TopojsonExport,
    TopojsonImport,
    Topology,
    Units,
    SvgHatch,
    VertexUtils,
    Zip
  );

  // The entry point for the core mapshaper module

  var moduleAPI = Object.assign({
    cli, cmd, geom, utils, internal,
  }, coreAPI);

  if (typeof module === "object" && module.exports) {
    module.exports = moduleAPI;
  } else if (typeof window === "object" && window) {
    window.mapshaper = moduleAPI;
  }

})();

}).call(this)}).call(this,require('_process'),require("buffer").Buffer,require("timers").setImmediate,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/mapshaper")
},{"@placemarkio/tokml":"@placemarkio/tokml","_process":87,"buffer":"buffer","timers":105,"zlib":56}],32:[function(require,module,exports){
var hasMap = typeof Map === 'function' && Map.prototype;
var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null;
var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null;
var mapForEach = hasMap && Map.prototype.forEach;
var hasSet = typeof Set === 'function' && Set.prototype;
var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null;
var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null;
var setForEach = hasSet && Set.prototype.forEach;
var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype;
var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null;
var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype;
var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null;
var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype;
var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null;
var booleanValueOf = Boolean.prototype.valueOf;
var objectToString = Object.prototype.toString;
var functionToString = Function.prototype.toString;
var $match = String.prototype.match;
var $slice = String.prototype.slice;
var $replace = String.prototype.replace;
var $toUpperCase = String.prototype.toUpperCase;
var $toLowerCase = String.prototype.toLowerCase;
var $test = RegExp.prototype.test;
var $concat = Array.prototype.concat;
var $join = Array.prototype.join;
var $arrSlice = Array.prototype.slice;
var $floor = Math.floor;
var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null;
var gOPS = Object.getOwnPropertySymbols;
var symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null;
var hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object';
// ie, `has-tostringtag/shams
var toStringTag = typeof Symbol === 'function' && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? 'object' : 'symbol')
    ? Symbol.toStringTag
    : null;
var isEnumerable = Object.prototype.propertyIsEnumerable;

var gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || (
    [].__proto__ === Array.prototype // eslint-disable-line no-proto
        ? function (O) {
            return O.__proto__; // eslint-disable-line no-proto
        }
        : null
);

function addNumericSeparator(num, str) {
    if (
        num === Infinity
        || num === -Infinity
        || num !== num
        || (num && num > -1000 && num < 1000)
        || $test.call(/e/, str)
    ) {
        return str;
    }
    var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;
    if (typeof num === 'number') {
        var int = num < 0 ? -$floor(-num) : $floor(num); // trunc(num)
        if (int !== num) {
            var intStr = String(int);
            var dec = $slice.call(str, intStr.length + 1);
            return $replace.call(intStr, sepRegex, '$&_') + '.' + $replace.call($replace.call(dec, /([0-9]{3})/g, '$&_'), /_$/, '');
        }
    }
    return $replace.call(str, sepRegex, '$&_');
}

var utilInspect = require('./util.inspect');
var inspectCustom = utilInspect.custom;
var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null;

module.exports = function inspect_(obj, options, depth, seen) {
    var opts = options || {};

    if (has(opts, 'quoteStyle') && (opts.quoteStyle !== 'single' && opts.quoteStyle !== 'double')) {
        throw new TypeError('option "quoteStyle" must be "single" or "double"');
    }
    if (
        has(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number'
            ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity
            : opts.maxStringLength !== null
        )
    ) {
        throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');
    }
    var customInspect = has(opts, 'customInspect') ? opts.customInspect : true;
    if (typeof customInspect !== 'boolean' && customInspect !== 'symbol') {
        throw new TypeError('option "customInspect", if provided, must be `true`, `false`, or `\'symbol\'`');
    }

    if (
        has(opts, 'indent')
        && opts.indent !== null
        && opts.indent !== '\t'
        && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0)
    ) {
        throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');
    }
    if (has(opts, 'numericSeparator') && typeof opts.numericSeparator !== 'boolean') {
        throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');
    }
    var numericSeparator = opts.numericSeparator;

    if (typeof obj === 'undefined') {
        return 'undefined';
    }
    if (obj === null) {
        return 'null';
    }
    if (typeof obj === 'boolean') {
        return obj ? 'true' : 'false';
    }

    if (typeof obj === 'string') {
        return inspectString(obj, opts);
    }
    if (typeof obj === 'number') {
        if (obj === 0) {
            return Infinity / obj > 0 ? '0' : '-0';
        }
        var str = String(obj);
        return numericSeparator ? addNumericSeparator(obj, str) : str;
    }
    if (typeof obj === 'bigint') {
        var bigIntStr = String(obj) + 'n';
        return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr;
    }

    var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth;
    if (typeof depth === 'undefined') { depth = 0; }
    if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') {
        return isArray(obj) ? '[Array]' : '[Object]';
    }

    var indent = getIndent(opts, depth);

    if (typeof seen === 'undefined') {
        seen = [];
    } else if (indexOf(seen, obj) >= 0) {
        return '[Circular]';
    }

    function inspect(value, from, noIndent) {
        if (from) {
            seen = $arrSlice.call(seen);
            seen.push(from);
        }
        if (noIndent) {
            var newOpts = {
                depth: opts.depth
            };
            if (has(opts, 'quoteStyle')) {
                newOpts.quoteStyle = opts.quoteStyle;
            }
            return inspect_(value, newOpts, depth + 1, seen);
        }
        return inspect_(value, opts, depth + 1, seen);
    }

    if (typeof obj === 'function' && !isRegExp(obj)) { // in older engines, regexes are callable
        var name = nameOf(obj);
        var keys = arrObjKeys(obj, inspect);
        return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : '');
    }
    if (isSymbol(obj)) {
        var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, '$1') : symToString.call(obj);
        return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString;
    }
    if (isElement(obj)) {
        var s = '<' + $toLowerCase.call(String(obj.nodeName));
        var attrs = obj.attributes || [];
        for (var i = 0; i < attrs.length; i++) {
            s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts);
        }
        s += '>';
        if (obj.childNodes && obj.childNodes.length) { s += '...'; }
        s += '</' + $toLowerCase.call(String(obj.nodeName)) + '>';
        return s;
    }
    if (isArray(obj)) {
        if (obj.length === 0) { return '[]'; }
        var xs = arrObjKeys(obj, inspect);
        if (indent && !singleLineValues(xs)) {
            return '[' + indentedJoin(xs, indent) + ']';
        }
        return '[ ' + $join.call(xs, ', ') + ' ]';
    }
    if (isError(obj)) {
        var parts = arrObjKeys(obj, inspect);
        if (!('cause' in Error.prototype) && 'cause' in obj && !isEnumerable.call(obj, 'cause')) {
            return '{ [' + String(obj) + '] ' + $join.call($concat.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }';
        }
        if (parts.length === 0) { return '[' + String(obj) + ']'; }
        return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }';
    }
    if (typeof obj === 'object' && customInspect) {
        if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && utilInspect) {
            return utilInspect(obj, { depth: maxDepth - depth });
        } else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') {
            return obj.inspect();
        }
    }
    if (isMap(obj)) {
        var mapParts = [];
        if (mapForEach) {
            mapForEach.call(obj, function (value, key) {
                mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj));
            });
        }
        return collectionOf('Map', mapSize.call(obj), mapParts, indent);
    }
    if (isSet(obj)) {
        var setParts = [];
        if (setForEach) {
            setForEach.call(obj, function (value) {
                setParts.push(inspect(value, obj));
            });
        }
        return collectionOf('Set', setSize.call(obj), setParts, indent);
    }
    if (isWeakMap(obj)) {
        return weakCollectionOf('WeakMap');
    }
    if (isWeakSet(obj)) {
        return weakCollectionOf('WeakSet');
    }
    if (isWeakRef(obj)) {
        return weakCollectionOf('WeakRef');
    }
    if (isNumber(obj)) {
        return markBoxed(inspect(Number(obj)));
    }
    if (isBigInt(obj)) {
        return markBoxed(inspect(bigIntValueOf.call(obj)));
    }
    if (isBoolean(obj)) {
        return markBoxed(booleanValueOf.call(obj));
    }
    if (isString(obj)) {
        return markBoxed(inspect(String(obj)));
    }
    if (!isDate(obj) && !isRegExp(obj)) {
        var ys = arrObjKeys(obj, inspect);
        var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object;
        var protoTag = obj instanceof Object ? '' : 'null prototype';
        var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? 'Object' : '';
        var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : '';
        var tag = constructorTag + (stringTag || protoTag ? '[' + $join.call($concat.call([], stringTag || [], protoTag || []), ': ') + '] ' : '');
        if (ys.length === 0) { return tag + '{}'; }
        if (indent) {
            return tag + '{' + indentedJoin(ys, indent) + '}';
        }
        return tag + '{ ' + $join.call(ys, ', ') + ' }';
    }
    return String(obj);
};

function wrapQuotes(s, defaultStyle, opts) {
    var quoteChar = (opts.quoteStyle || defaultStyle) === 'double' ? '"' : "'";
    return quoteChar + s + quoteChar;
}

function quote(s) {
    return $replace.call(String(s), /"/g, '&quot;');
}

function isArray(obj) { return toStr(obj) === '[object Array]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isDate(obj) { return toStr(obj) === '[object Date]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isRegExp(obj) { return toStr(obj) === '[object RegExp]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isError(obj) { return toStr(obj) === '[object Error]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isString(obj) { return toStr(obj) === '[object String]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isNumber(obj) { return toStr(obj) === '[object Number]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isBoolean(obj) { return toStr(obj) === '[object Boolean]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }

// Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives
function isSymbol(obj) {
    if (hasShammedSymbols) {
        return obj && typeof obj === 'object' && obj instanceof Symbol;
    }
    if (typeof obj === 'symbol') {
        return true;
    }
    if (!obj || typeof obj !== 'object' || !symToString) {
        return false;
    }
    try {
        symToString.call(obj);
        return true;
    } catch (e) {}
    return false;
}

function isBigInt(obj) {
    if (!obj || typeof obj !== 'object' || !bigIntValueOf) {
        return false;
    }
    try {
        bigIntValueOf.call(obj);
        return true;
    } catch (e) {}
    return false;
}

var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; };
function has(obj, key) {
    return hasOwn.call(obj, key);
}

function toStr(obj) {
    return objectToString.call(obj);
}

function nameOf(f) {
    if (f.name) { return f.name; }
    var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/);
    if (m) { return m[1]; }
    return null;
}

function indexOf(xs, x) {
    if (xs.indexOf) { return xs.indexOf(x); }
    for (var i = 0, l = xs.length; i < l; i++) {
        if (xs[i] === x) { return i; }
    }
    return -1;
}

function isMap(x) {
    if (!mapSize || !x || typeof x !== 'object') {
        return false;
    }
    try {
        mapSize.call(x);
        try {
            setSize.call(x);
        } catch (s) {
            return true;
        }
        return x instanceof Map; // core-js workaround, pre-v2.5.0
    } catch (e) {}
    return false;
}

function isWeakMap(x) {
    if (!weakMapHas || !x || typeof x !== 'object') {
        return false;
    }
    try {
        weakMapHas.call(x, weakMapHas);
        try {
            weakSetHas.call(x, weakSetHas);
        } catch (s) {
            return true;
        }
        return x instanceof WeakMap; // core-js workaround, pre-v2.5.0
    } catch (e) {}
    return false;
}

function isWeakRef(x) {
    if (!weakRefDeref || !x || typeof x !== 'object') {
        return false;
    }
    try {
        weakRefDeref.call(x);
        return true;
    } catch (e) {}
    return false;
}

function isSet(x) {
    if (!setSize || !x || typeof x !== 'object') {
        return false;
    }
    try {
        setSize.call(x);
        try {
            mapSize.call(x);
        } catch (m) {
            return true;
        }
        return x instanceof Set; // core-js workaround, pre-v2.5.0
    } catch (e) {}
    return false;
}

function isWeakSet(x) {
    if (!weakSetHas || !x || typeof x !== 'object') {
        return false;
    }
    try {
        weakSetHas.call(x, weakSetHas);
        try {
            weakMapHas.call(x, weakMapHas);
        } catch (s) {
            return true;
        }
        return x instanceof WeakSet; // core-js workaround, pre-v2.5.0
    } catch (e) {}
    return false;
}

function isElement(x) {
    if (!x || typeof x !== 'object') { return false; }
    if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) {
        return true;
    }
    return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function';
}

function inspectString(str, opts) {
    if (str.length > opts.maxStringLength) {
        var remaining = str.length - opts.maxStringLength;
        var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : '');
        return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer;
    }
    // eslint-disable-next-line no-control-regex
    var s = $replace.call($replace.call(str, /(['\\])/g, '\\$1'), /[\x00-\x1f]/g, lowbyte);
    return wrapQuotes(s, 'single', opts);
}

function lowbyte(c) {
    var n = c.charCodeAt(0);
    var x = {
        8: 'b',
        9: 't',
        10: 'n',
        12: 'f',
        13: 'r'
    }[n];
    if (x) { return '\\' + x; }
    return '\\x' + (n < 0x10 ? '0' : '') + $toUpperCase.call(n.toString(16));
}

function markBoxed(str) {
    return 'Object(' + str + ')';
}

function weakCollectionOf(type) {
    return type + ' { ? }';
}

function collectionOf(type, size, entries, indent) {
    var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ', ');
    return type + ' (' + size + ') {' + joinedEntries + '}';
}

function singleLineValues(xs) {
    for (var i = 0; i < xs.length; i++) {
        if (indexOf(xs[i], '\n') >= 0) {
            return false;
        }
    }
    return true;
}

function getIndent(opts, depth) {
    var baseIndent;
    if (opts.indent === '\t') {
        baseIndent = '\t';
    } else if (typeof opts.indent === 'number' && opts.indent > 0) {
        baseIndent = $join.call(Array(opts.indent + 1), ' ');
    } else {
        return null;
    }
    return {
        base: baseIndent,
        prev: $join.call(Array(depth + 1), baseIndent)
    };
}

function indentedJoin(xs, indent) {
    if (xs.length === 0) { return ''; }
    var lineJoiner = '\n' + indent.prev + indent.base;
    return lineJoiner + $join.call(xs, ',' + lineJoiner) + '\n' + indent.prev;
}

function arrObjKeys(obj, inspect) {
    var isArr = isArray(obj);
    var xs = [];
    if (isArr) {
        xs.length = obj.length;
        for (var i = 0; i < obj.length; i++) {
            xs[i] = has(obj, i) ? inspect(obj[i], obj) : '';
        }
    }
    var syms = typeof gOPS === 'function' ? gOPS(obj) : [];
    var symMap;
    if (hasShammedSymbols) {
        symMap = {};
        for (var k = 0; k < syms.length; k++) {
            symMap['$' + syms[k]] = syms[k];
        }
    }

    for (var key in obj) { // eslint-disable-line no-restricted-syntax
        if (!has(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue
        if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue
        if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) {
            // this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section
            continue; // eslint-disable-line no-restricted-syntax, no-continue
        } else if ($test.call(/[^\w$]/, key)) {
            xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj));
        } else {
            xs.push(key + ': ' + inspect(obj[key], obj));
        }
    }
    if (typeof gOPS === 'function') {
        for (var j = 0; j < syms.length; j++) {
            if (isEnumerable.call(obj, syms[j])) {
                xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj));
            }
        }
    }
    return xs;
}

},{"./util.inspect":54}],33:[function(require,module,exports){
'use strict';

var replace = String.prototype.replace;
var percentTwenties = /%20/g;

var Format = {
    RFC1738: 'RFC1738',
    RFC3986: 'RFC3986'
};

module.exports = {
    'default': Format.RFC3986,
    formatters: {
        RFC1738: function (value) {
            return replace.call(value, percentTwenties, '+');
        },
        RFC3986: function (value) {
            return String(value);
        }
    },
    RFC1738: Format.RFC1738,
    RFC3986: Format.RFC3986
};

},{}],34:[function(require,module,exports){
'use strict';

var stringify = require('./stringify');
var parse = require('./parse');
var formats = require('./formats');

module.exports = {
    formats: formats,
    parse: parse,
    stringify: stringify
};

},{"./formats":33,"./parse":35,"./stringify":36}],35:[function(require,module,exports){
'use strict';

var utils = require('./utils');

var has = Object.prototype.hasOwnProperty;
var isArray = Array.isArray;

var defaults = {
    allowDots: false,
    allowPrototypes: false,
    allowSparse: false,
    arrayLimit: 20,
    charset: 'utf-8',
    charsetSentinel: false,
    comma: false,
    decoder: utils.decode,
    delimiter: '&',
    depth: 5,
    ignoreQueryPrefix: false,
    interpretNumericEntities: false,
    parameterLimit: 1000,
    parseArrays: true,
    plainObjects: false,
    strictNullHandling: false
};

var interpretNumericEntities = function (str) {
    return str.replace(/&#(\d+);/g, function ($0, numberStr) {
        return String.fromCharCode(parseInt(numberStr, 10));
    });
};

var parseArrayValue = function (val, options) {
    if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) {
        return val.split(',');
    }

    return val;
};

// This is what browsers will submit when the ✓ character occurs in an
// application/x-www-form-urlencoded body and the encoding of the page containing
// the form is iso-8859-1, or when the submitted form has an accept-charset
// attribute of iso-8859-1. Presumably also with other charsets that do not contain
// the ✓ character, such as us-ascii.
var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('&#10003;')

// These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded.
var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓')

var parseValues = function parseQueryStringValues(str, options) {
    var obj = {};
    var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str;
    var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit;
    var parts = cleanStr.split(options.delimiter, limit);
    var skipIndex = -1; // Keep track of where the utf8 sentinel was found
    var i;

    var charset = options.charset;
    if (options.charsetSentinel) {
        for (i = 0; i < parts.length; ++i) {
            if (parts[i].indexOf('utf8=') === 0) {
                if (parts[i] === charsetSentinel) {
                    charset = 'utf-8';
                } else if (parts[i] === isoSentinel) {
                    charset = 'iso-8859-1';
                }
                skipIndex = i;
                i = parts.length; // The eslint settings do not allow break;
            }
        }
    }

    for (i = 0; i < parts.length; ++i) {
        if (i === skipIndex) {
            continue;
        }
        var part = parts[i];

        var bracketEqualsPos = part.indexOf(']=');
        var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1;

        var key, val;
        if (pos === -1) {
            key = options.decoder(part, defaults.decoder, charset, 'key');
            val = options.strictNullHandling ? null : '';
        } else {
            key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key');
            val = utils.maybeMap(
                parseArrayValue(part.slice(pos + 1), options),
                function (encodedVal) {
                    return options.decoder(encodedVal, defaults.decoder, charset, 'value');
                }
            );
        }

        if (val && options.interpretNumericEntities && charset === 'iso-8859-1') {
            val = interpretNumericEntities(val);
        }

        if (part.indexOf('[]=') > -1) {
            val = isArray(val) ? [val] : val;
        }

        if (has.call(obj, key)) {
            obj[key] = utils.combine(obj[key], val);
        } else {
            obj[key] = val;
        }
    }

    return obj;
};

var parseObject = function (chain, val, options, valuesParsed) {
    var leaf = valuesParsed ? val : parseArrayValue(val, options);

    for (var i = chain.length - 1; i >= 0; --i) {
        var obj;
        var root = chain[i];

        if (root === '[]' && options.parseArrays) {
            obj = [].concat(leaf);
        } else {
            obj = options.plainObjects ? Object.create(null) : {};
            var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;
            var index = parseInt(cleanRoot, 10);
            if (!options.parseArrays && cleanRoot === '') {
                obj = { 0: leaf };
            } else if (
                !isNaN(index)
                && root !== cleanRoot
                && String(index) === cleanRoot
                && index >= 0
                && (options.parseArrays && index <= options.arrayLimit)
            ) {
                obj = [];
                obj[index] = leaf;
            } else if (cleanRoot !== '__proto__') {
                obj[cleanRoot] = leaf;
            }
        }

        leaf = obj;
    }

    return leaf;
};

var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) {
    if (!givenKey) {
        return;
    }

    // Transform dot notation to bracket notation
    var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey;

    // The regex chunks

    var brackets = /(\[[^[\]]*])/;
    var child = /(\[[^[\]]*])/g;

    // Get the parent

    var segment = options.depth > 0 && brackets.exec(key);
    var parent = segment ? key.slice(0, segment.index) : key;

    // Stash the parent if it exists

    var keys = [];
    if (parent) {
        // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties
        if (!options.plainObjects && has.call(Object.prototype, parent)) {
            if (!options.allowPrototypes) {
                return;
            }
        }

        keys.push(parent);
    }

    // Loop through children appending to the array until we hit depth

    var i = 0;
    while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) {
        i += 1;
        if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) {
            if (!options.allowPrototypes) {
                return;
            }
        }
        keys.push(segment[1]);
    }

    // If there's a remainder, just add whatever is left

    if (segment) {
        keys.push('[' + key.slice(segment.index) + ']');
    }

    return parseObject(keys, val, options, valuesParsed);
};

var normalizeParseOptions = function normalizeParseOptions(opts) {
    if (!opts) {
        return defaults;
    }

    if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') {
        throw new TypeError('Decoder has to be a function.');
    }

    if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {
        throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');
    }
    var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset;

    return {
        allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots,
        allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes,
        allowSparse: typeof opts.allowSparse === 'boolean' ? opts.allowSparse : defaults.allowSparse,
        arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit,
        charset: charset,
        charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,
        comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma,
        decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder,
        delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter,
        // eslint-disable-next-line no-implicit-coercion, no-extra-parens
        depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth,
        ignoreQueryPrefix: opts.ignoreQueryPrefix === true,
        interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities,
        parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit,
        parseArrays: opts.parseArrays !== false,
        plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects,
        strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling
    };
};

module.exports = function (str, opts) {
    var options = normalizeParseOptions(opts);

    if (str === '' || str === null || typeof str === 'undefined') {
        return options.plainObjects ? Object.create(null) : {};
    }

    var tempObj = typeof str === 'string' ? parseValues(str, options) : str;
    var obj = options.plainObjects ? Object.create(null) : {};

    // Iterate over the keys and setup the new object

    var keys = Object.keys(tempObj);
    for (var i = 0; i < keys.length; ++i) {
        var key = keys[i];
        var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string');
        obj = utils.merge(obj, newObj, options);
    }

    if (options.allowSparse === true) {
        return obj;
    }

    return utils.compact(obj);
};

},{"./utils":37}],36:[function(require,module,exports){
'use strict';

var getSideChannel = require('side-channel');
var utils = require('./utils');
var formats = require('./formats');
var has = Object.prototype.hasOwnProperty;

var arrayPrefixGenerators = {
    brackets: function brackets(prefix) {
        return prefix + '[]';
    },
    comma: 'comma',
    indices: function indices(prefix, key) {
        return prefix + '[' + key + ']';
    },
    repeat: function repeat(prefix) {
        return prefix;
    }
};

var isArray = Array.isArray;
var push = Array.prototype.push;
var pushToArray = function (arr, valueOrArray) {
    push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]);
};

var toISO = Date.prototype.toISOString;

var defaultFormat = formats['default'];
var defaults = {
    addQueryPrefix: false,
    allowDots: false,
    charset: 'utf-8',
    charsetSentinel: false,
    delimiter: '&',
    encode: true,
    encoder: utils.encode,
    encodeValuesOnly: false,
    format: defaultFormat,
    formatter: formats.formatters[defaultFormat],
    // deprecated
    indices: false,
    serializeDate: function serializeDate(date) {
        return toISO.call(date);
    },
    skipNulls: false,
    strictNullHandling: false
};

var isNonNullishPrimitive = function isNonNullishPrimitive(v) {
    return typeof v === 'string'
        || typeof v === 'number'
        || typeof v === 'boolean'
        || typeof v === 'symbol'
        || typeof v === 'bigint';
};

var sentinel = {};

var stringify = function stringify(
    object,
    prefix,
    generateArrayPrefix,
    commaRoundTrip,
    strictNullHandling,
    skipNulls,
    encoder,
    filter,
    sort,
    allowDots,
    serializeDate,
    format,
    formatter,
    encodeValuesOnly,
    charset,
    sideChannel
) {
    var obj = object;

    var tmpSc = sideChannel;
    var step = 0;
    var findFlag = false;
    while ((tmpSc = tmpSc.get(sentinel)) !== void undefined && !findFlag) {
        // Where object last appeared in the ref tree
        var pos = tmpSc.get(object);
        step += 1;
        if (typeof pos !== 'undefined') {
            if (pos === step) {
                throw new RangeError('Cyclic object value');
            } else {
                findFlag = true; // Break while
            }
        }
        if (typeof tmpSc.get(sentinel) === 'undefined') {
            step = 0;
        }
    }

    if (typeof filter === 'function') {
        obj = filter(prefix, obj);
    } else if (obj instanceof Date) {
        obj = serializeDate(obj);
    } else if (generateArrayPrefix === 'comma' && isArray(obj)) {
        obj = utils.maybeMap(obj, function (value) {
            if (value instanceof Date) {
                return serializeDate(value);
            }
            return value;
        });
    }

    if (obj === null) {
        if (strictNullHandling) {
            return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key', format) : prefix;
        }

        obj = '';
    }

    if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) {
        if (encoder) {
            var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key', format);
            return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value', format))];
        }
        return [formatter(prefix) + '=' + formatter(String(obj))];
    }

    var values = [];

    if (typeof obj === 'undefined') {
        return values;
    }

    var objKeys;
    if (generateArrayPrefix === 'comma' && isArray(obj)) {
        // we need to join elements in
        if (encodeValuesOnly && encoder) {
            obj = utils.maybeMap(obj, encoder);
        }
        objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }];
    } else if (isArray(filter)) {
        objKeys = filter;
    } else {
        var keys = Object.keys(obj);
        objKeys = sort ? keys.sort(sort) : keys;
    }

    var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? prefix + '[]' : prefix;

    for (var j = 0; j < objKeys.length; ++j) {
        var key = objKeys[j];
        var value = typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key];

        if (skipNulls && value === null) {
            continue;
        }

        var keyPrefix = isArray(obj)
            ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(adjustedPrefix, key) : adjustedPrefix
            : adjustedPrefix + (allowDots ? '.' + key : '[' + key + ']');

        sideChannel.set(object, step);
        var valueSideChannel = getSideChannel();
        valueSideChannel.set(sentinel, sideChannel);
        pushToArray(values, stringify(
            value,
            keyPrefix,
            generateArrayPrefix,
            commaRoundTrip,
            strictNullHandling,
            skipNulls,
            generateArrayPrefix === 'comma' && encodeValuesOnly && isArray(obj) ? null : encoder,
            filter,
            sort,
            allowDots,
            serializeDate,
            format,
            formatter,
            encodeValuesOnly,
            charset,
            valueSideChannel
        ));
    }

    return values;
};

var normalizeStringifyOptions = function normalizeStringifyOptions(opts) {
    if (!opts) {
        return defaults;
    }

    if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') {
        throw new TypeError('Encoder has to be a function.');
    }

    var charset = opts.charset || defaults.charset;
    if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {
        throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');
    }

    var format = formats['default'];
    if (typeof opts.format !== 'undefined') {
        if (!has.call(formats.formatters, opts.format)) {
            throw new TypeError('Unknown format option provided.');
        }
        format = opts.format;
    }
    var formatter = formats.formatters[format];

    var filter = defaults.filter;
    if (typeof opts.filter === 'function' || isArray(opts.filter)) {
        filter = opts.filter;
    }

    return {
        addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix,
        allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots,
        charset: charset,
        charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,
        delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter,
        encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode,
        encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder,
        encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly,
        filter: filter,
        format: format,
        formatter: formatter,
        serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate,
        skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls,
        sort: typeof opts.sort === 'function' ? opts.sort : null,
        strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling
    };
};

module.exports = function (object, opts) {
    var obj = object;
    var options = normalizeStringifyOptions(opts);

    var objKeys;
    var filter;

    if (typeof options.filter === 'function') {
        filter = options.filter;
        obj = filter('', obj);
    } else if (isArray(options.filter)) {
        filter = options.filter;
        objKeys = filter;
    }

    var keys = [];

    if (typeof obj !== 'object' || obj === null) {
        return '';
    }

    var arrayFormat;
    if (opts && opts.arrayFormat in arrayPrefixGenerators) {
        arrayFormat = opts.arrayFormat;
    } else if (opts && 'indices' in opts) {
        arrayFormat = opts.indices ? 'indices' : 'repeat';
    } else {
        arrayFormat = 'indices';
    }

    var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];
    if (opts && 'commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') {
        throw new TypeError('`commaRoundTrip` must be a boolean, or absent');
    }
    var commaRoundTrip = generateArrayPrefix === 'comma' && opts && opts.commaRoundTrip;

    if (!objKeys) {
        objKeys = Object.keys(obj);
    }

    if (options.sort) {
        objKeys.sort(options.sort);
    }

    var sideChannel = getSideChannel();
    for (var i = 0; i < objKeys.length; ++i) {
        var key = objKeys[i];

        if (options.skipNulls && obj[key] === null) {
            continue;
        }
        pushToArray(keys, stringify(
            obj[key],
            key,
            generateArrayPrefix,
            commaRoundTrip,
            options.strictNullHandling,
            options.skipNulls,
            options.encode ? options.encoder : null,
            options.filter,
            options.sort,
            options.allowDots,
            options.serializeDate,
            options.format,
            options.formatter,
            options.encodeValuesOnly,
            options.charset,
            sideChannel
        ));
    }

    var joined = keys.join(options.delimiter);
    var prefix = options.addQueryPrefix === true ? '?' : '';

    if (options.charsetSentinel) {
        if (options.charset === 'iso-8859-1') {
            // encodeURIComponent('&#10003;'), the "numeric entity" representation of a checkmark
            prefix += 'utf8=%26%2310003%3B&';
        } else {
            // encodeURIComponent('✓')
            prefix += 'utf8=%E2%9C%93&';
        }
    }

    return joined.length > 0 ? prefix + joined : '';
};

},{"./formats":33,"./utils":37,"side-channel":46}],37:[function(require,module,exports){
'use strict';

var formats = require('./formats');

var has = Object.prototype.hasOwnProperty;
var isArray = Array.isArray;

var hexTable = (function () {
    var array = [];
    for (var i = 0; i < 256; ++i) {
        array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());
    }

    return array;
}());

var compactQueue = function compactQueue(queue) {
    while (queue.length > 1) {
        var item = queue.pop();
        var obj = item.obj[item.prop];

        if (isArray(obj)) {
            var compacted = [];

            for (var j = 0; j < obj.length; ++j) {
                if (typeof obj[j] !== 'undefined') {
                    compacted.push(obj[j]);
                }
            }

            item.obj[item.prop] = compacted;
        }
    }
};

var arrayToObject = function arrayToObject(source, options) {
    var obj = options && options.plainObjects ? Object.create(null) : {};
    for (var i = 0; i < source.length; ++i) {
        if (typeof source[i] !== 'undefined') {
            obj[i] = source[i];
        }
    }

    return obj;
};

var merge = function merge(target, source, options) {
    /* eslint no-param-reassign: 0 */
    if (!source) {
        return target;
    }

    if (typeof source !== 'object') {
        if (isArray(target)) {
            target.push(source);
        } else if (target && typeof target === 'object') {
            if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) {
                target[source] = true;
            }
        } else {
            return [target, source];
        }

        return target;
    }

    if (!target || typeof target !== 'object') {
        return [target].concat(source);
    }

    var mergeTarget = target;
    if (isArray(target) && !isArray(source)) {
        mergeTarget = arrayToObject(target, options);
    }

    if (isArray(target) && isArray(source)) {
        source.forEach(function (item, i) {
            if (has.call(target, i)) {
                var targetItem = target[i];
                if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') {
                    target[i] = merge(targetItem, item, options);
                } else {
                    target.push(item);
                }
            } else {
                target[i] = item;
            }
        });
        return target;
    }

    return Object.keys(source).reduce(function (acc, key) {
        var value = source[key];

        if (has.call(acc, key)) {
            acc[key] = merge(acc[key], value, options);
        } else {
            acc[key] = value;
        }
        return acc;
    }, mergeTarget);
};

var assign = function assignSingleSource(target, source) {
    return Object.keys(source).reduce(function (acc, key) {
        acc[key] = source[key];
        return acc;
    }, target);
};

var decode = function (str, decoder, charset) {
    var strWithoutPlus = str.replace(/\+/g, ' ');
    if (charset === 'iso-8859-1') {
        // unescape never throws, no try...catch needed:
        return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);
    }
    // utf-8
    try {
        return decodeURIComponent(strWithoutPlus);
    } catch (e) {
        return strWithoutPlus;
    }
};

var encode = function encode(str, defaultEncoder, charset, kind, format) {
    // This code was originally written by Brian White (mscdex) for the io.js core querystring library.
    // It has been adapted here for stricter adherence to RFC 3986
    if (str.length === 0) {
        return str;
    }

    var string = str;
    if (typeof str === 'symbol') {
        string = Symbol.prototype.toString.call(str);
    } else if (typeof str !== 'string') {
        string = String(str);
    }

    if (charset === 'iso-8859-1') {
        return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) {
            return '%26%23' + parseInt($0.slice(2), 16) + '%3B';
        });
    }

    var out = '';
    for (var i = 0; i < string.length; ++i) {
        var c = string.charCodeAt(i);

        if (
            c === 0x2D // -
            || c === 0x2E // .
            || c === 0x5F // _
            || c === 0x7E // ~
            || (c >= 0x30 && c <= 0x39) // 0-9
            || (c >= 0x41 && c <= 0x5A) // a-z
            || (c >= 0x61 && c <= 0x7A) // A-Z
            || (format === formats.RFC1738 && (c === 0x28 || c === 0x29)) // ( )
        ) {
            out += string.charAt(i);
            continue;
        }

        if (c < 0x80) {
            out = out + hexTable[c];
            continue;
        }

        if (c < 0x800) {
            out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);
            continue;
        }

        if (c < 0xD800 || c >= 0xE000) {
            out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);
            continue;
        }

        i += 1;
        c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));
        /* eslint operator-linebreak: [2, "before"] */
        out += hexTable[0xF0 | (c >> 18)]
            + hexTable[0x80 | ((c >> 12) & 0x3F)]
            + hexTable[0x80 | ((c >> 6) & 0x3F)]
            + hexTable[0x80 | (c & 0x3F)];
    }

    return out;
};

var compact = function compact(value) {
    var queue = [{ obj: { o: value }, prop: 'o' }];
    var refs = [];

    for (var i = 0; i < queue.length; ++i) {
        var item = queue[i];
        var obj = item.obj[item.prop];

        var keys = Object.keys(obj);
        for (var j = 0; j < keys.length; ++j) {
            var key = keys[j];
            var val = obj[key];
            if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) {
                queue.push({ obj: obj, prop: key });
                refs.push(val);
            }
        }
    }

    compactQueue(queue);

    return value;
};

var isRegExp = function isRegExp(obj) {
    return Object.prototype.toString.call(obj) === '[object RegExp]';
};

var isBuffer = function isBuffer(obj) {
    if (!obj || typeof obj !== 'object') {
        return false;
    }

    return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
};

var combine = function combine(a, b) {
    return [].concat(a, b);
};

var maybeMap = function maybeMap(val, fn) {
    if (isArray(val)) {
        var mapped = [];
        for (var i = 0; i < val.length; i += 1) {
            mapped.push(fn(val[i]));
        }
        return mapped;
    }
    return fn(val);
};

module.exports = {
    arrayToObject: arrayToObject,
    assign: assign,
    combine: combine,
    compact: compact,
    decode: decode,
    encode: encode,
    isBuffer: isBuffer,
    isRegExp: isRegExp,
    maybeMap: maybeMap,
    merge: merge
};

},{"./formats":33}],38:[function(require,module,exports){
var slice = Array.prototype.slice;

function dashify(method, file) {
  return function(path) {
    var argv = arguments;
    if (path == "-") (argv = slice.call(argv)).splice(0, 1, file);
    return method.apply(null, argv);
  };
}

exports.readFile = dashify(require("./read-file"), "/dev/stdin");
exports.readFileSync = dashify(require("./read-file-sync"), "/dev/stdin");
exports.writeFile = dashify(require("./write-file"), "/dev/stdout");
exports.writeFileSync = dashify(require("./write-file-sync"), "/dev/stdout");

},{"./read-file":42,"./read-file-sync":41,"./write-file":44,"./write-file-sync":43}],39:[function(require,module,exports){
(function (Buffer){(function (){
module.exports = function(options) {
  if (options) {
    if (typeof options === "string") return encoding(options);
    if (options.encoding !== null) return encoding(options.encoding);
  }
  return identity();
};

function identity() {
  var chunks = [];
  return {
    push: function(chunk) { chunks.push(chunk); },
    value: function() { return Buffer.concat(chunks); }
  };
}

function encoding(encoding) {
  var chunks = [];
  return {
    push: function(chunk) { chunks.push(chunk); },
    value: function() { return Buffer.concat(chunks).toString(encoding); }
  };
}

}).call(this)}).call(this,require("buffer").Buffer)
},{"buffer":"buffer"}],40:[function(require,module,exports){
(function (Buffer){(function (){
module.exports = function(data, options) {
  return typeof data === "string"
      ? new Buffer(data, typeof options === "string" ? options
          : options && options.encoding !== null ? options.encoding
          : "utf8")
      : data;
};

}).call(this)}).call(this,require("buffer").Buffer)
},{"buffer":"buffer"}],41:[function(require,module,exports){
(function (Buffer){(function (){
var fs = require("fs"),
    decode = require("./decode");

module.exports = function(filename, options) {
  if (fs.statSync(filename).isFile()) {
    return fs.readFileSync(filename, options);
  } else {
    var fd = fs.openSync(filename, options && options.flag || "r"),
        decoder = decode(options);

    while (true) { // eslint-disable-line no-constant-condition
      try {
        var buffer = new Buffer(bufferSize),
            bytesRead = fs.readSync(fd, buffer, 0, bufferSize);
      } catch (e) {
        if (e.code === "EOF") break;
        fs.closeSync(fd);
        throw e;
      }
      if (bytesRead === 0) break;
      decoder.push(buffer.slice(0, bytesRead));
    }

    fs.closeSync(fd);
    return decoder.value();
  }
};

var bufferSize = 1 << 16;

}).call(this)}).call(this,require("buffer").Buffer)
},{"./decode":39,"buffer":"buffer","fs":"fs"}],42:[function(require,module,exports){
(function (process){(function (){
var fs = require("fs"),
    decode = require("./decode");

module.exports = function(path, options, callback) {
  if (arguments.length < 3) callback = options, options = null;

  switch (path) {
    case "/dev/stdin": return readStream(process.stdin, options, callback);
  }

  fs.stat(path, function(error, stat) {
    if (error) return callback(error);
    if (stat.isFile()) return fs.readFile(path, options, callback);
    readStream(fs.createReadStream(path, options ? {flags: options.flag || "r"} : {}), options, callback); // N.B. flag / flags
  });
};

function readStream(stream, options, callback) {
  var decoder = decode(options);
  stream.on("error", callback);
  stream.on("data", function(d) { decoder.push(d); });
  stream.on("end", function() { callback(null, decoder.value()); });
}

}).call(this)}).call(this,require('_process'))
},{"./decode":39,"_process":87,"fs":"fs"}],43:[function(require,module,exports){
var fs = require("fs"),
    encode = require("./encode");

module.exports = function(filename, data, options) {
  var stat;

  try {
    stat = fs.statSync(filename);
  } catch (error) {
    if (error.code !== "ENOENT") throw error;
  }

  if (!stat || stat.isFile()) {
    fs.writeFileSync(filename, data, options);
  } else {
    var fd = fs.openSync(filename, options && options.flag || "w"),
        bytesWritten = 0,
        bytesTotal = (data = encode(data, options)).length;

    while (bytesWritten < bytesTotal) {
      try {
        bytesWritten += fs.writeSync(fd, data, bytesWritten, bytesTotal - bytesWritten, null);
      } catch (error) {
        if (error.code === "EPIPE") break; // ignore broken pipe, e.g., | head
        fs.closeSync(fd);
        throw error;
      }
    }

    fs.closeSync(fd);
  }
};

},{"./encode":40,"fs":"fs"}],44:[function(require,module,exports){
(function (process){(function (){
var fs = require("fs"),
    encode = require("./encode");

module.exports = function(path, data, options, callback) {
  if (arguments.length < 4) callback = options, options = null;

  switch (path) {
    case "/dev/stdout": return writeStream(process.stdout, "write", data, options, callback);
    case "/dev/stderr": return writeStream(process.stderr, "write", data, options, callback);
  }

  fs.stat(path, function(error, stat) {
    if (error && error.code !== "ENOENT") return callback(error);
    if (stat && stat.isFile()) return fs.writeFile(path, data, options, callback);
    writeStream(fs.createWriteStream(path, options ? {flags: options.flag || "w"} : {}), "end", data, options, callback); // N.B. flag / flags
  });
};

function writeStream(stream, send, data, options, callback) {
  stream.on("error", function(error) { callback(error.code === "EPIPE" ? null : error); }); // ignore broken pipe, e.g., | head
  stream[send](encode(data, options), function(error) { callback(error && error.code === "EPIPE" ? null : error); });
}

}).call(this)}).call(this,require('_process'))
},{"./encode":40,"_process":87,"fs":"fs"}],45:[function(require,module,exports){
(function (process){(function (){
/* eslint-disable node/no-deprecated-api */

'use strict'

var buffer = require('buffer')
var Buffer = buffer.Buffer

var safer = {}

var key

for (key in buffer) {
  if (!buffer.hasOwnProperty(key)) continue
  if (key === 'SlowBuffer' || key === 'Buffer') continue
  safer[key] = buffer[key]
}

var Safer = safer.Buffer = {}
for (key in Buffer) {
  if (!Buffer.hasOwnProperty(key)) continue
  if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue
  Safer[key] = Buffer[key]
}

safer.Buffer.prototype = Buffer.prototype

if (!Safer.from || Safer.from === Uint8Array.from) {
  Safer.from = function (value, encodingOrOffset, length) {
    if (typeof value === 'number') {
      throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value)
    }
    if (value && typeof value.length === 'undefined') {
      throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value)
    }
    return Buffer(value, encodingOrOffset, length)
  }
}

if (!Safer.alloc) {
  Safer.alloc = function (size, fill, encoding) {
    if (typeof size !== 'number') {
      throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size)
    }
    if (size < 0 || size >= 2 * (1 << 30)) {
      throw new RangeError('The value "' + size + '" is invalid for option "size"')
    }
    var buf = Buffer(size)
    if (!fill || fill.length === 0) {
      buf.fill(0)
    } else if (typeof encoding === 'string') {
      buf.fill(fill, encoding)
    } else {
      buf.fill(fill)
    }
    return buf
  }
}

if (!safer.kStringMaxLength) {
  try {
    safer.kStringMaxLength = process.binding('buffer').kStringMaxLength
  } catch (e) {
    // we can't determine kStringMaxLength in environments where process.binding
    // is unsupported, so let's not set it
  }
}

if (!safer.constants) {
  safer.constants = {
    MAX_LENGTH: safer.kMaxLength
  }
  if (safer.kStringMaxLength) {
    safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength
  }
}

module.exports = safer

}).call(this)}).call(this,require('_process'))
},{"_process":87,"buffer":"buffer"}],46:[function(require,module,exports){
'use strict';

var GetIntrinsic = require('get-intrinsic');
var callBound = require('call-bind/callBound');
var inspect = require('object-inspect');

var $TypeError = GetIntrinsic('%TypeError%');
var $WeakMap = GetIntrinsic('%WeakMap%', true);
var $Map = GetIntrinsic('%Map%', true);

var $weakMapGet = callBound('WeakMap.prototype.get', true);
var $weakMapSet = callBound('WeakMap.prototype.set', true);
var $weakMapHas = callBound('WeakMap.prototype.has', true);
var $mapGet = callBound('Map.prototype.get', true);
var $mapSet = callBound('Map.prototype.set', true);
var $mapHas = callBound('Map.prototype.has', true);

/*
 * This function traverses the list returning the node corresponding to the
 * given key.
 *
 * That node is also moved to the head of the list, so that if it's accessed
 * again we don't need to traverse the whole list. By doing so, all the recently
 * used nodes can be accessed relatively quickly.
 */
var listGetNode = function (list, key) { // eslint-disable-line consistent-return
	for (var prev = list, curr; (curr = prev.next) !== null; prev = curr) {
		if (curr.key === key) {
			prev.next = curr.next;
			curr.next = list.next;
			list.next = curr; // eslint-disable-line no-param-reassign
			return curr;
		}
	}
};

var listGet = function (objects, key) {
	var node = listGetNode(objects, key);
	return node && node.value;
};
var listSet = function (objects, key, value) {
	var node = listGetNode(objects, key);
	if (node) {
		node.value = value;
	} else {
		// Prepend the new node to the beginning of the list
		objects.next = { // eslint-disable-line no-param-reassign
			key: key,
			next: objects.next,
			value: value
		};
	}
};
var listHas = function (objects, key) {
	return !!listGetNode(objects, key);
};

module.exports = function getSideChannel() {
	var $wm;
	var $m;
	var $o;
	var channel = {
		assert: function (key) {
			if (!channel.has(key)) {
				throw new $TypeError('Side channel does not contain ' + inspect(key));
			}
		},
		get: function (key) { // eslint-disable-line consistent-return
			if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {
				if ($wm) {
					return $weakMapGet($wm, key);
				}
			} else if ($Map) {
				if ($m) {
					return $mapGet($m, key);
				}
			} else {
				if ($o) { // eslint-disable-line no-lonely-if
					return listGet($o, key);
				}
			}
		},
		has: function (key) {
			if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {
				if ($wm) {
					return $weakMapHas($wm, key);
				}
			} else if ($Map) {
				if ($m) {
					return $mapHas($m, key);
				}
			} else {
				if ($o) { // eslint-disable-line no-lonely-if
					return listHas($o, key);
				}
			}
			return false;
		},
		set: function (key, value) {
			if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {
				if (!$wm) {
					$wm = new $WeakMap();
				}
				$weakMapSet($wm, key, value);
			} else if ($Map) {
				if (!$m) {
					$m = new $Map();
				}
				$mapSet($m, key, value);
			} else {
				if (!$o) {
					/*
					 * Initialize the linked list as an empty node, so that we don't have
					 * to special-case handling of the first node: we can always refer to
					 * it as (previous node).next, instead of something like (list).head
					 */
					$o = { key: {}, next: null };
				}
				listSet($o, key, value);
			}
		}
	};
	return channel;
};

},{"call-bind/callBound":2,"get-intrinsic":6,"object-inspect":32}],47:[function(require,module,exports){
"use strict";
exports.__esModule = true;
var qs_1 = require("qs");
function handleQs(url, query) {
    var _a = url.split('?'), start = _a[0], part2 = _a[1];
    var qs = (part2 || '').split('#')[0];
    var end = part2 && part2.split('#').length > 1 ? '#' + part2.split('#')[1] : '';
    var baseQs = qs_1.parse(qs);
    for (var i in query) {
        baseQs[i] = query[i];
    }
    qs = qs_1.stringify(baseQs);
    if (qs !== '') {
        qs = '?' + qs;
    }
    return start + qs + end;
}
exports["default"] = handleQs;

},{"qs":34}],48:[function(require,module,exports){
(function (global){(function (){
'use strict';

var objectAssign = require('object-assign');

// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
// original notice:

/*!
 * The buffer module from node.js, for the browser.
 *
 * @author   Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
 * @license  MIT
 */
function compare(a, b) {
  if (a === b) {
    return 0;
  }

  var x = a.length;
  var y = b.length;

  for (var i = 0, len = Math.min(x, y); i < len; ++i) {
    if (a[i] !== b[i]) {
      x = a[i];
      y = b[i];
      break;
    }
  }

  if (x < y) {
    return -1;
  }
  if (y < x) {
    return 1;
  }
  return 0;
}
function isBuffer(b) {
  if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
    return global.Buffer.isBuffer(b);
  }
  return !!(b != null && b._isBuffer);
}

// based on node assert, original notice:
// NB: The URL to the CommonJS spec is kept just for tradition.
//     node-assert has evolved a lot since then, both in API and behavior.

// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
//
// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
//
// Originally from narwhal.js (http://narwhaljs.org)
// Copyright (c) 2009 Thomas Robinson <280north.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the 'Software'), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

var util = require('util/');
var hasOwn = Object.prototype.hasOwnProperty;
var pSlice = Array.prototype.slice;
var functionsHaveNames = (function () {
  return function foo() {}.name === 'foo';
}());
function pToString (obj) {
  return Object.prototype.toString.call(obj);
}
function isView(arrbuf) {
  if (isBuffer(arrbuf)) {
    return false;
  }
  if (typeof global.ArrayBuffer !== 'function') {
    return false;
  }
  if (typeof ArrayBuffer.isView === 'function') {
    return ArrayBuffer.isView(arrbuf);
  }
  if (!arrbuf) {
    return false;
  }
  if (arrbuf instanceof DataView) {
    return true;
  }
  if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
    return true;
  }
  return false;
}
// 1. The assert module provides functions that throw
// AssertionError's when particular conditions are not met. The
// assert module must conform to the following interface.

var assert = module.exports = ok;

// 2. The AssertionError is defined in assert.
// new assert.AssertionError({ message: message,
//                             actual: actual,
//                             expected: expected })

var regex = /\s*function\s+([^\(\s]*)\s*/;
// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
function getName(func) {
  if (!util.isFunction(func)) {
    return;
  }
  if (functionsHaveNames) {
    return func.name;
  }
  var str = func.toString();
  var match = str.match(regex);
  return match && match[1];
}
assert.AssertionError = function AssertionError(options) {
  this.name = 'AssertionError';
  this.actual = options.actual;
  this.expected = options.expected;
  this.operator = options.operator;
  if (options.message) {
    this.message = options.message;
    this.generatedMessage = false;
  } else {
    this.message = getMessage(this);
    this.generatedMessage = true;
  }
  var stackStartFunction = options.stackStartFunction || fail;
  if (Error.captureStackTrace) {
    Error.captureStackTrace(this, stackStartFunction);
  } else {
    // non v8 browsers so we can have a stacktrace
    var err = new Error();
    if (err.stack) {
      var out = err.stack;

      // try to strip useless frames
      var fn_name = getName(stackStartFunction);
      var idx = out.indexOf('\n' + fn_name);
      if (idx >= 0) {
        // once we have located the function frame
        // we need to strip out everything before it (and its line)
        var next_line = out.indexOf('\n', idx + 1);
        out = out.substring(next_line + 1);
      }

      this.stack = out;
    }
  }
};

// assert.AssertionError instanceof Error
util.inherits(assert.AssertionError, Error);

function truncate(s, n) {
  if (typeof s === 'string') {
    return s.length < n ? s : s.slice(0, n);
  } else {
    return s;
  }
}
function inspect(something) {
  if (functionsHaveNames || !util.isFunction(something)) {
    return util.inspect(something);
  }
  var rawname = getName(something);
  var name = rawname ? ': ' + rawname : '';
  return '[Function' +  name + ']';
}
function getMessage(self) {
  return truncate(inspect(self.actual), 128) + ' ' +
         self.operator + ' ' +
         truncate(inspect(self.expected), 128);
}

// At present only the three keys mentioned above are used and
// understood by the spec. Implementations or sub modules can pass
// other keys to the AssertionError's constructor - they will be
// ignored.

// 3. All of the following functions must throw an AssertionError
// when a corresponding condition is not met, with a message that
// may be undefined if not provided.  All assertion methods provide
// both the actual and expected values to the assertion error for
// display purposes.

function fail(actual, expected, message, operator, stackStartFunction) {
  throw new assert.AssertionError({
    message: message,
    actual: actual,
    expected: expected,
    operator: operator,
    stackStartFunction: stackStartFunction
  });
}

// EXTENSION! allows for well behaved errors defined elsewhere.
assert.fail = fail;

// 4. Pure assertion tests whether a value is truthy, as determined
// by !!guard.
// assert.ok(guard, message_opt);
// This statement is equivalent to assert.equal(true, !!guard,
// message_opt);. To test strictly for the value true, use
// assert.strictEqual(true, guard, message_opt);.

function ok(value, message) {
  if (!value) fail(value, true, message, '==', assert.ok);
}
assert.ok = ok;

// 5. The equality assertion tests shallow, coercive equality with
// ==.
// assert.equal(actual, expected, message_opt);

assert.equal = function equal(actual, expected, message) {
  if (actual != expected) fail(actual, expected, message, '==', assert.equal);
};

// 6. The non-equality assertion tests for whether two objects are not equal
// with != assert.notEqual(actual, expected, message_opt);

assert.notEqual = function notEqual(actual, expected, message) {
  if (actual == expected) {
    fail(actual, expected, message, '!=', assert.notEqual);
  }
};

// 7. The equivalence assertion tests a deep equality relation.
// assert.deepEqual(actual, expected, message_opt);

assert.deepEqual = function deepEqual(actual, expected, message) {
  if (!_deepEqual(actual, expected, false)) {
    fail(actual, expected, message, 'deepEqual', assert.deepEqual);
  }
};

assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
  if (!_deepEqual(actual, expected, true)) {
    fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
  }
};

function _deepEqual(actual, expected, strict, memos) {
  // 7.1. All identical values are equivalent, as determined by ===.
  if (actual === expected) {
    return true;
  } else if (isBuffer(actual) && isBuffer(expected)) {
    return compare(actual, expected) === 0;

  // 7.2. If the expected value is a Date object, the actual value is
  // equivalent if it is also a Date object that refers to the same time.
  } else if (util.isDate(actual) && util.isDate(expected)) {
    return actual.getTime() === expected.getTime();

  // 7.3 If the expected value is a RegExp object, the actual value is
  // equivalent if it is also a RegExp object with the same source and
  // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
  } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
    return actual.source === expected.source &&
           actual.global === expected.global &&
           actual.multiline === expected.multiline &&
           actual.lastIndex === expected.lastIndex &&
           actual.ignoreCase === expected.ignoreCase;

  // 7.4. Other pairs that do not both pass typeof value == 'object',
  // equivalence is determined by ==.
  } else if ((actual === null || typeof actual !== 'object') &&
             (expected === null || typeof expected !== 'object')) {
    return strict ? actual === expected : actual == expected;

  // If both values are instances of typed arrays, wrap their underlying
  // ArrayBuffers in a Buffer each to increase performance
  // This optimization requires the arrays to have the same type as checked by
  // Object.prototype.toString (aka pToString). Never perform binary
  // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
  // bit patterns are not identical.
  } else if (isView(actual) && isView(expected) &&
             pToString(actual) === pToString(expected) &&
             !(actual instanceof Float32Array ||
               actual instanceof Float64Array)) {
    return compare(new Uint8Array(actual.buffer),
                   new Uint8Array(expected.buffer)) === 0;

  // 7.5 For all other Object pairs, including Array objects, equivalence is
  // determined by having the same number of owned properties (as verified
  // with Object.prototype.hasOwnProperty.call), the same set of keys
  // (although not necessarily the same order), equivalent values for every
  // corresponding key, and an identical 'prototype' property. Note: this
  // accounts for both named and indexed properties on Arrays.
  } else if (isBuffer(actual) !== isBuffer(expected)) {
    return false;
  } else {
    memos = memos || {actual: [], expected: []};

    var actualIndex = memos.actual.indexOf(actual);
    if (actualIndex !== -1) {
      if (actualIndex === memos.expected.indexOf(expected)) {
        return true;
      }
    }

    memos.actual.push(actual);
    memos.expected.push(expected);

    return objEquiv(actual, expected, strict, memos);
  }
}

function isArguments(object) {
  return Object.prototype.toString.call(object) == '[object Arguments]';
}

function objEquiv(a, b, strict, actualVisitedObjects) {
  if (a === null || a === undefined || b === null || b === undefined)
    return false;
  // if one is a primitive, the other must be same
  if (util.isPrimitive(a) || util.isPrimitive(b))
    return a === b;
  if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
    return false;
  var aIsArgs = isArguments(a);
  var bIsArgs = isArguments(b);
  if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
    return false;
  if (aIsArgs) {
    a = pSlice.call(a);
    b = pSlice.call(b);
    return _deepEqual(a, b, strict);
  }
  var ka = objectKeys(a);
  var kb = objectKeys(b);
  var key, i;
  // having the same number of owned properties (keys incorporates
  // hasOwnProperty)
  if (ka.length !== kb.length)
    return false;
  //the same set of keys (although not necessarily the same order),
  ka.sort();
  kb.sort();
  //~~~cheap key test
  for (i = ka.length - 1; i >= 0; i--) {
    if (ka[i] !== kb[i])
      return false;
  }
  //equivalent values for every corresponding key, and
  //~~~possibly expensive deep test
  for (i = ka.length - 1; i >= 0; i--) {
    key = ka[i];
    if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
      return false;
  }
  return true;
}

// 8. The non-equivalence assertion tests for any deep inequality.
// assert.notDeepEqual(actual, expected, message_opt);

assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
  if (_deepEqual(actual, expected, false)) {
    fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
  }
};

assert.notDeepStrictEqual = notDeepStrictEqual;
function notDeepStrictEqual(actual, expected, message) {
  if (_deepEqual(actual, expected, true)) {
    fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
  }
}


// 9. The strict equality assertion tests strict equality, as determined by ===.
// assert.strictEqual(actual, expected, message_opt);

assert.strictEqual = function strictEqual(actual, expected, message) {
  if (actual !== expected) {
    fail(actual, expected, message, '===', assert.strictEqual);
  }
};

// 10. The strict non-equality assertion tests for strict inequality, as
// determined by !==.  assert.notStrictEqual(actual, expected, message_opt);

assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (actual === expected) {
    fail(actual, expected, message, '!==', assert.notStrictEqual);
  }
};

function expectedException(actual, expected) {
  if (!actual || !expected) {
    return false;
  }

  if (Object.prototype.toString.call(expected) == '[object RegExp]') {
    return expected.test(actual);
  }

  try {
    if (actual instanceof expected) {
      return true;
    }
  } catch (e) {
    // Ignore.  The instanceof check doesn't work for arrow functions.
  }

  if (Error.isPrototypeOf(expected)) {
    return false;
  }

  return expected.call({}, actual) === true;
}

function _tryBlock(block) {
  var error;
  try {
    block();
  } catch (e) {
    error = e;
  }
  return error;
}

function _throws(shouldThrow, block, expected, message) {
  var actual;

  if (typeof block !== 'function') {
    throw new TypeError('"block" argument must be a function');
  }

  if (typeof expected === 'string') {
    message = expected;
    expected = null;
  }

  actual = _tryBlock(block);

  message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
            (message ? ' ' + message : '.');

  if (shouldThrow && !actual) {
    fail(actual, expected, 'Missing expected exception' + message);
  }

  var userProvidedMessage = typeof message === 'string';
  var isUnwantedException = !shouldThrow && util.isError(actual);
  var isUnexpectedException = !shouldThrow && actual && !expected;

  if ((isUnwantedException &&
      userProvidedMessage &&
      expectedException(actual, expected)) ||
      isUnexpectedException) {
    fail(actual, expected, 'Got unwanted exception' + message);
  }

  if ((shouldThrow && actual && expected &&
      !expectedException(actual, expected)) || (!shouldThrow && actual)) {
    throw actual;
  }
}

// 11. Expected to throw an error:
// assert.throws(block, Error_opt, message_opt);

assert.throws = function(block, /*optional*/error, /*optional*/message) {
  _throws(true, block, error, message);
};

// EXTENSION! This is annoying to write outside this module.
assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
  _throws(false, block, error, message);
};

assert.ifError = function(err) { if (err) throw err; };

// Expose a strict only variant of assert
function strict(value, message) {
  if (!value) fail(value, true, message, '==', strict);
}
assert.strict = objectAssign(strict, assert, {
  equal: assert.strictEqual,
  deepEqual: assert.deepStrictEqual,
  notEqual: assert.notStrictEqual,
  notDeepEqual: assert.notDeepStrictEqual
});
assert.strict.strict = assert.strict;

var objectKeys = Object.keys || function (obj) {
  var keys = [];
  for (var key in obj) {
    if (hasOwn.call(obj, key)) keys.push(key);
  }
  return keys;
};

}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"object-assign":75,"util/":51}],49:[function(require,module,exports){
if (typeof Object.create === 'function') {
  // implementation from standard node.js 'util' module
  module.exports = function inherits(ctor, superCtor) {
    ctor.super_ = superCtor
    ctor.prototype = Object.create(superCtor.prototype, {
      constructor: {
        value: ctor,
        enumerable: false,
        writable: true,
        configurable: true
      }
    });
  };
} else {
  // old school shim for old browsers
  module.exports = function inherits(ctor, superCtor) {
    ctor.super_ = superCtor
    var TempCtor = function () {}
    TempCtor.prototype = superCtor.prototype
    ctor.prototype = new TempCtor()
    ctor.prototype.constructor = ctor
  }
}

},{}],50:[function(require,module,exports){
module.exports = function isBuffer(arg) {
  return arg && typeof arg === 'object'
    && typeof arg.copy === 'function'
    && typeof arg.fill === 'function'
    && typeof arg.readUInt8 === 'function';
}
},{}],51:[function(require,module,exports){
(function (process,global){(function (){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
  if (!isString(f)) {
    var objects = [];
    for (var i = 0; i < arguments.length; i++) {
      objects.push(inspect(arguments[i]));
    }
    return objects.join(' ');
  }

  var i = 1;
  var args = arguments;
  var len = args.length;
  var str = String(f).replace(formatRegExp, function(x) {
    if (x === '%%') return '%';
    if (i >= len) return x;
    switch (x) {
      case '%s': return String(args[i++]);
      case '%d': return Number(args[i++]);
      case '%j':
        try {
          return JSON.stringify(args[i++]);
        } catch (_) {
          return '[Circular]';
        }
      default:
        return x;
    }
  });
  for (var x = args[i]; i < len; x = args[++i]) {
    if (isNull(x) || !isObject(x)) {
      str += ' ' + x;
    } else {
      str += ' ' + inspect(x);
    }
  }
  return str;
};


// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
  // Allow for deprecating things in the process of starting up.
  if (isUndefined(global.process)) {
    return function() {
      return exports.deprecate(fn, msg).apply(this, arguments);
    };
  }

  if (process.noDeprecation === true) {
    return fn;
  }

  var warned = false;
  function deprecated() {
    if (!warned) {
      if (process.throwDeprecation) {
        throw new Error(msg);
      } else if (process.traceDeprecation) {
        console.trace(msg);
      } else {
        console.error(msg);
      }
      warned = true;
    }
    return fn.apply(this, arguments);
  }

  return deprecated;
};


var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
  if (isUndefined(debugEnviron))
    debugEnviron = process.env.NODE_DEBUG || '';
  set = set.toUpperCase();
  if (!debugs[set]) {
    if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
      var pid = process.pid;
      debugs[set] = function() {
        var msg = exports.format.apply(exports, arguments);
        console.error('%s %d: %s', set, pid, msg);
      };
    } else {
      debugs[set] = function() {};
    }
  }
  return debugs[set];
};


/**
 * Echos the value of a value. Trys to print the value out
 * in the best way possible given the different types.
 *
 * @param {Object} obj The object to print out.
 * @param {Object} opts Optional options object that alters the output.
 */
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
  // default options
  var ctx = {
    seen: [],
    stylize: stylizeNoColor
  };
  // legacy...
  if (arguments.length >= 3) ctx.depth = arguments[2];
  if (arguments.length >= 4) ctx.colors = arguments[3];
  if (isBoolean(opts)) {
    // legacy...
    ctx.showHidden = opts;
  } else if (opts) {
    // got an "options" object
    exports._extend(ctx, opts);
  }
  // set default options
  if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  if (isUndefined(ctx.depth)) ctx.depth = 2;
  if (isUndefined(ctx.colors)) ctx.colors = false;
  if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  if (ctx.colors) ctx.stylize = stylizeWithColor;
  return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;


// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
  'bold' : [1, 22],
  'italic' : [3, 23],
  'underline' : [4, 24],
  'inverse' : [7, 27],
  'white' : [37, 39],
  'grey' : [90, 39],
  'black' : [30, 39],
  'blue' : [34, 39],
  'cyan' : [36, 39],
  'green' : [32, 39],
  'magenta' : [35, 39],
  'red' : [31, 39],
  'yellow' : [33, 39]
};

// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
  'special': 'cyan',
  'number': 'yellow',
  'boolean': 'yellow',
  'undefined': 'grey',
  'null': 'bold',
  'string': 'green',
  'date': 'magenta',
  // "name": intentionally not styling
  'regexp': 'red'
};


function stylizeWithColor(str, styleType) {
  var style = inspect.styles[styleType];

  if (style) {
    return '\u001b[' + inspect.colors[style][0] + 'm' + str +
           '\u001b[' + inspect.colors[style][1] + 'm';
  } else {
    return str;
  }
}


function stylizeNoColor(str, styleType) {
  return str;
}


function arrayToHash(array) {
  var hash = {};

  array.forEach(function(val, idx) {
    hash[val] = true;
  });

  return hash;
}


function formatValue(ctx, value, recurseTimes) {
  // Provide a hook for user-specified inspect functions.
  // Check that value is an object with an inspect function on it
  if (ctx.customInspect &&
      value &&
      isFunction(value.inspect) &&
      // Filter out the util module, it's inspect function is special
      value.inspect !== exports.inspect &&
      // Also filter out any prototype objects using the circular check.
      !(value.constructor && value.constructor.prototype === value)) {
    var ret = value.inspect(recurseTimes, ctx);
    if (!isString(ret)) {
      ret = formatValue(ctx, ret, recurseTimes);
    }
    return ret;
  }

  // Primitive types cannot have properties
  var primitive = formatPrimitive(ctx, value);
  if (primitive) {
    return primitive;
  }

  // Look up the keys of the object.
  var keys = Object.keys(value);
  var visibleKeys = arrayToHash(keys);

  if (ctx.showHidden) {
    keys = Object.getOwnPropertyNames(value);
  }

  // IE doesn't make error fields non-enumerable
  // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  if (isError(value)
      && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
    return formatError(value);
  }

  // Some type of object without properties can be shortcutted.
  if (keys.length === 0) {
    if (isFunction(value)) {
      var name = value.name ? ': ' + value.name : '';
      return ctx.stylize('[Function' + name + ']', 'special');
    }
    if (isRegExp(value)) {
      return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
    }
    if (isDate(value)) {
      return ctx.stylize(Date.prototype.toString.call(value), 'date');
    }
    if (isError(value)) {
      return formatError(value);
    }
  }

  var base = '', array = false, braces = ['{', '}'];

  // Make Array say that they are Array
  if (isArray(value)) {
    array = true;
    braces = ['[', ']'];
  }

  // Make functions say that they are functions
  if (isFunction(value)) {
    var n = value.name ? ': ' + value.name : '';
    base = ' [Function' + n + ']';
  }

  // Make RegExps say that they are RegExps
  if (isRegExp(value)) {
    base = ' ' + RegExp.prototype.toString.call(value);
  }

  // Make dates with properties first say the date
  if (isDate(value)) {
    base = ' ' + Date.prototype.toUTCString.call(value);
  }

  // Make error with message first say the error
  if (isError(value)) {
    base = ' ' + formatError(value);
  }

  if (keys.length === 0 && (!array || value.length == 0)) {
    return braces[0] + base + braces[1];
  }

  if (recurseTimes < 0) {
    if (isRegExp(value)) {
      return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
    } else {
      return ctx.stylize('[Object]', 'special');
    }
  }

  ctx.seen.push(value);

  var output;
  if (array) {
    output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  } else {
    output = keys.map(function(key) {
      return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
    });
  }

  ctx.seen.pop();

  return reduceToSingleString(output, base, braces);
}


function formatPrimitive(ctx, value) {
  if (isUndefined(value))
    return ctx.stylize('undefined', 'undefined');
  if (isString(value)) {
    var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
                                             .replace(/'/g, "\\'")
                                             .replace(/\\"/g, '"') + '\'';
    return ctx.stylize(simple, 'string');
  }
  if (isNumber(value))
    return ctx.stylize('' + value, 'number');
  if (isBoolean(value))
    return ctx.stylize('' + value, 'boolean');
  // For some reason typeof null is "object", so special case here.
  if (isNull(value))
    return ctx.stylize('null', 'null');
}


function formatError(value) {
  return '[' + Error.prototype.toString.call(value) + ']';
}


function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  var output = [];
  for (var i = 0, l = value.length; i < l; ++i) {
    if (hasOwnProperty(value, String(i))) {
      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
          String(i), true));
    } else {
      output.push('');
    }
  }
  keys.forEach(function(key) {
    if (!key.match(/^\d+$/)) {
      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
          key, true));
    }
  });
  return output;
}


function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  var name, str, desc;
  desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  if (desc.get) {
    if (desc.set) {
      str = ctx.stylize('[Getter/Setter]', 'special');
    } else {
      str = ctx.stylize('[Getter]', 'special');
    }
  } else {
    if (desc.set) {
      str = ctx.stylize('[Setter]', 'special');
    }
  }
  if (!hasOwnProperty(visibleKeys, key)) {
    name = '[' + key + ']';
  }
  if (!str) {
    if (ctx.seen.indexOf(desc.value) < 0) {
      if (isNull(recurseTimes)) {
        str = formatValue(ctx, desc.value, null);
      } else {
        str = formatValue(ctx, desc.value, recurseTimes - 1);
      }
      if (str.indexOf('\n') > -1) {
        if (array) {
          str = str.split('\n').map(function(line) {
            return '  ' + line;
          }).join('\n').substr(2);
        } else {
          str = '\n' + str.split('\n').map(function(line) {
            return '   ' + line;
          }).join('\n');
        }
      }
    } else {
      str = ctx.stylize('[Circular]', 'special');
    }
  }
  if (isUndefined(name)) {
    if (array && key.match(/^\d+$/)) {
      return str;
    }
    name = JSON.stringify('' + key);
    if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
      name = name.substr(1, name.length - 2);
      name = ctx.stylize(name, 'name');
    } else {
      name = name.replace(/'/g, "\\'")
                 .replace(/\\"/g, '"')
                 .replace(/(^"|"$)/g, "'");
      name = ctx.stylize(name, 'string');
    }
  }

  return name + ': ' + str;
}


function reduceToSingleString(output, base, braces) {
  var numLinesEst = 0;
  var length = output.reduce(function(prev, cur) {
    numLinesEst++;
    if (cur.indexOf('\n') >= 0) numLinesEst++;
    return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  }, 0);

  if (length > 60) {
    return braces[0] +
           (base === '' ? '' : base + '\n ') +
           ' ' +
           output.join(',\n  ') +
           ' ' +
           braces[1];
  }

  return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}


// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
  return Array.isArray(ar);
}
exports.isArray = isArray;

function isBoolean(arg) {
  return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;

function isNull(arg) {
  return arg === null;
}
exports.isNull = isNull;

function isNullOrUndefined(arg) {
  return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;

function isNumber(arg) {
  return typeof arg === 'number';
}
exports.isNumber = isNumber;

function isString(arg) {
  return typeof arg === 'string';
}
exports.isString = isString;

function isSymbol(arg) {
  return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;

function isUndefined(arg) {
  return arg === void 0;
}
exports.isUndefined = isUndefined;

function isRegExp(re) {
  return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;

function isObject(arg) {
  return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;

function isDate(d) {
  return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;

function isError(e) {
  return isObject(e) &&
      (objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;

function isFunction(arg) {
  return typeof arg === 'function';
}
exports.isFunction = isFunction;

function isPrimitive(arg) {
  return arg === null ||
         typeof arg === 'boolean' ||
         typeof arg === 'number' ||
         typeof arg === 'string' ||
         typeof arg === 'symbol' ||  // ES6 symbol
         typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;

exports.isBuffer = require('./support/isBuffer');

function objectToString(o) {
  return Object.prototype.toString.call(o);
}


function pad(n) {
  return n < 10 ? '0' + n.toString(10) : n.toString(10);
}


var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
              'Oct', 'Nov', 'Dec'];

// 26 Feb 16:19:34
function timestamp() {
  var d = new Date();
  var time = [pad(d.getHours()),
              pad(d.getMinutes()),
              pad(d.getSeconds())].join(':');
  return [d.getDate(), months[d.getMonth()], time].join(' ');
}


// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
  console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};


/**
 * Inherit the prototype methods from one constructor into another.
 *
 * The Function.prototype.inherits from lang.js rewritten as a standalone
 * function (not on Function.prototype). NOTE: If this file is to be loaded
 * during bootstrapping this function needs to be rewritten using some native
 * functions as prototype setup using normal JavaScript does not work as
 * expected during bootstrapping (see mirror.js in r114903).
 *
 * @param {function} ctor Constructor function which needs to inherit the
 *     prototype.
 * @param {function} superCtor Constructor function to inherit prototype from.
 */
exports.inherits = require('inherits');

exports._extend = function(origin, add) {
  // Don't do anything if add isn't an object
  if (!add || !isObject(add)) return origin;

  var keys = Object.keys(add);
  var i = keys.length;
  while (i--) {
    origin[keys[i]] = add[keys[i]];
  }
  return origin;
};

function hasOwnProperty(obj, prop) {
  return Object.prototype.hasOwnProperty.call(obj, prop);
}

}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./support/isBuffer":50,"_process":87,"inherits":49}],52:[function(require,module,exports){
(function (global){(function (){
'use strict';

var possibleNames = [
	'BigInt64Array',
	'BigUint64Array',
	'Float32Array',
	'Float64Array',
	'Int16Array',
	'Int32Array',
	'Int8Array',
	'Uint16Array',
	'Uint32Array',
	'Uint8Array',
	'Uint8ClampedArray'
];

var g = typeof globalThis === 'undefined' ? global : globalThis;

module.exports = function availableTypedArrays() {
	var out = [];
	for (var i = 0; i < possibleNames.length; i++) {
		if (typeof g[possibleNames[i]] === 'function') {
			out[out.length] = possibleNames[i];
		}
	}
	return out;
};

}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],53:[function(require,module,exports){
'use strict'

exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray

var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array

var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
  lookup[i] = code[i]
  revLookup[code.charCodeAt(i)] = i
}

// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63

function getLens (b64) {
  var len = b64.length

  if (len % 4 > 0) {
    throw new Error('Invalid string. Length must be a multiple of 4')
  }

  // Trim off extra bytes after placeholder bytes are found
  // See: https://github.com/beatgammit/base64-js/issues/42
  var validLen = b64.indexOf('=')
  if (validLen === -1) validLen = len

  var placeHoldersLen = validLen === len
    ? 0
    : 4 - (validLen % 4)

  return [validLen, placeHoldersLen]
}

// base64 is 4/3 + up to two characters of the original data
function byteLength (b64) {
  var lens = getLens(b64)
  var validLen = lens[0]
  var placeHoldersLen = lens[1]
  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}

function _byteLength (b64, validLen, placeHoldersLen) {
  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}

function toByteArray (b64) {
  var tmp
  var lens = getLens(b64)
  var validLen = lens[0]
  var placeHoldersLen = lens[1]

  var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))

  var curByte = 0

  // if there are placeholders, only get up to the last complete 4 chars
  var len = placeHoldersLen > 0
    ? validLen - 4
    : validLen

  var i
  for (i = 0; i < len; i += 4) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 18) |
      (revLookup[b64.charCodeAt(i + 1)] << 12) |
      (revLookup[b64.charCodeAt(i + 2)] << 6) |
      revLookup[b64.charCodeAt(i + 3)]
    arr[curByte++] = (tmp >> 16) & 0xFF
    arr[curByte++] = (tmp >> 8) & 0xFF
    arr[curByte++] = tmp & 0xFF
  }

  if (placeHoldersLen === 2) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 2) |
      (revLookup[b64.charCodeAt(i + 1)] >> 4)
    arr[curByte++] = tmp & 0xFF
  }

  if (placeHoldersLen === 1) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 10) |
      (revLookup[b64.charCodeAt(i + 1)] << 4) |
      (revLookup[b64.charCodeAt(i + 2)] >> 2)
    arr[curByte++] = (tmp >> 8) & 0xFF
    arr[curByte++] = tmp & 0xFF
  }

  return arr
}

function tripletToBase64 (num) {
  return lookup[num >> 18 & 0x3F] +
    lookup[num >> 12 & 0x3F] +
    lookup[num >> 6 & 0x3F] +
    lookup[num & 0x3F]
}

function encodeChunk (uint8, start, end) {
  var tmp
  var output = []
  for (var i = start; i < end; i += 3) {
    tmp =
      ((uint8[i] << 16) & 0xFF0000) +
      ((uint8[i + 1] << 8) & 0xFF00) +
      (uint8[i + 2] & 0xFF)
    output.push(tripletToBase64(tmp))
  }
  return output.join('')
}

function fromByteArray (uint8) {
  var tmp
  var len = uint8.length
  var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  var parts = []
  var maxChunkLength = 16383 // must be multiple of 3

  // go through the array every three bytes, we'll deal with trailing stuff later
  for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
    parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  }

  // pad the end with zeros, but make sure to not forget the extra bytes
  if (extraBytes === 1) {
    tmp = uint8[len - 1]
    parts.push(
      lookup[tmp >> 2] +
      lookup[(tmp << 4) & 0x3F] +
      '=='
    )
  } else if (extraBytes === 2) {
    tmp = (uint8[len - 2] << 8) + uint8[len - 1]
    parts.push(
      lookup[tmp >> 10] +
      lookup[(tmp >> 4) & 0x3F] +
      lookup[(tmp << 2) & 0x3F] +
      '='
    )
  }

  return parts.join('')
}

},{}],54:[function(require,module,exports){

},{}],55:[function(require,module,exports){
(function (process,Buffer){(function (){
'use strict';
/* eslint camelcase: "off" */

var assert = require('assert');

var Zstream = require('pako/lib/zlib/zstream');
var zlib_deflate = require('pako/lib/zlib/deflate.js');
var zlib_inflate = require('pako/lib/zlib/inflate.js');
var constants = require('pako/lib/zlib/constants');

for (var key in constants) {
  exports[key] = constants[key];
}

// zlib modes
exports.NONE = 0;
exports.DEFLATE = 1;
exports.INFLATE = 2;
exports.GZIP = 3;
exports.GUNZIP = 4;
exports.DEFLATERAW = 5;
exports.INFLATERAW = 6;
exports.UNZIP = 7;

var GZIP_HEADER_ID1 = 0x1f;
var GZIP_HEADER_ID2 = 0x8b;

/**
 * Emulate Node's zlib C++ layer for use by the JS layer in index.js
 */
function Zlib(mode) {
  if (typeof mode !== 'number' || mode < exports.DEFLATE || mode > exports.UNZIP) {
    throw new TypeError('Bad argument');
  }

  this.dictionary = null;
  this.err = 0;
  this.flush = 0;
  this.init_done = false;
  this.level = 0;
  this.memLevel = 0;
  this.mode = mode;
  this.strategy = 0;
  this.windowBits = 0;
  this.write_in_progress = false;
  this.pending_close = false;
  this.gzip_id_bytes_read = 0;
}

Zlib.prototype.close = function () {
  if (this.write_in_progress) {
    this.pending_close = true;
    return;
  }

  this.pending_close = false;

  assert(this.init_done, 'close before init');
  assert(this.mode <= exports.UNZIP);

  if (this.mode === exports.DEFLATE || this.mode === exports.GZIP || this.mode === exports.DEFLATERAW) {
    zlib_deflate.deflateEnd(this.strm);
  } else if (this.mode === exports.INFLATE || this.mode === exports.GUNZIP || this.mode === exports.INFLATERAW || this.mode === exports.UNZIP) {
    zlib_inflate.inflateEnd(this.strm);
  }

  this.mode = exports.NONE;

  this.dictionary = null;
};

Zlib.prototype.write = function (flush, input, in_off, in_len, out, out_off, out_len) {
  return this._write(true, flush, input, in_off, in_len, out, out_off, out_len);
};

Zlib.prototype.writeSync = function (flush, input, in_off, in_len, out, out_off, out_len) {
  return this._write(false, flush, input, in_off, in_len, out, out_off, out_len);
};

Zlib.prototype._write = function (async, flush, input, in_off, in_len, out, out_off, out_len) {
  assert.equal(arguments.length, 8);

  assert(this.init_done, 'write before init');
  assert(this.mode !== exports.NONE, 'already finalized');
  assert.equal(false, this.write_in_progress, 'write already in progress');
  assert.equal(false, this.pending_close, 'close is pending');

  this.write_in_progress = true;

  assert.equal(false, flush === undefined, 'must provide flush value');

  this.write_in_progress = true;

  if (flush !== exports.Z_NO_FLUSH && flush !== exports.Z_PARTIAL_FLUSH && flush !== exports.Z_SYNC_FLUSH && flush !== exports.Z_FULL_FLUSH && flush !== exports.Z_FINISH && flush !== exports.Z_BLOCK) {
    throw new Error('Invalid flush value');
  }

  if (input == null) {
    input = Buffer.alloc(0);
    in_len = 0;
    in_off = 0;
  }

  this.strm.avail_in = in_len;
  this.strm.input = input;
  this.strm.next_in = in_off;
  this.strm.avail_out = out_len;
  this.strm.output = out;
  this.strm.next_out = out_off;
  this.flush = flush;

  if (!async) {
    // sync version
    this._process();

    if (this._checkError()) {
      return this._afterSync();
    }
    return;
  }

  // async version
  var self = this;
  process.nextTick(function () {
    self._process();
    self._after();
  });

  return this;
};

Zlib.prototype._afterSync = function () {
  var avail_out = this.strm.avail_out;
  var avail_in = this.strm.avail_in;

  this.write_in_progress = false;

  return [avail_in, avail_out];
};

Zlib.prototype._process = function () {
  var next_expected_header_byte = null;

  // If the avail_out is left at 0, then it means that it ran out
  // of room.  If there was avail_out left over, then it means
  // that all of the input was consumed.
  switch (this.mode) {
    case exports.DEFLATE:
    case exports.GZIP:
    case exports.DEFLATERAW:
      this.err = zlib_deflate.deflate(this.strm, this.flush);
      break;
    case exports.UNZIP:
      if (this.strm.avail_in > 0) {
        next_expected_header_byte = this.strm.next_in;
      }

      switch (this.gzip_id_bytes_read) {
        case 0:
          if (next_expected_header_byte === null) {
            break;
          }

          if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID1) {
            this.gzip_id_bytes_read = 1;
            next_expected_header_byte++;

            if (this.strm.avail_in === 1) {
              // The only available byte was already read.
              break;
            }
          } else {
            this.mode = exports.INFLATE;
            break;
          }

        // fallthrough
        case 1:
          if (next_expected_header_byte === null) {
            break;
          }

          if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID2) {
            this.gzip_id_bytes_read = 2;
            this.mode = exports.GUNZIP;
          } else {
            // There is no actual difference between INFLATE and INFLATERAW
            // (after initialization).
            this.mode = exports.INFLATE;
          }

          break;
        default:
          throw new Error('invalid number of gzip magic number bytes read');
      }

    // fallthrough
    case exports.INFLATE:
    case exports.GUNZIP:
    case exports.INFLATERAW:
      this.err = zlib_inflate.inflate(this.strm, this.flush

      // If data was encoded with dictionary
      );if (this.err === exports.Z_NEED_DICT && this.dictionary) {
        // Load it
        this.err = zlib_inflate.inflateSetDictionary(this.strm, this.dictionary);
        if (this.err === exports.Z_OK) {
          // And try to decode again
          this.err = zlib_inflate.inflate(this.strm, this.flush);
        } else if (this.err === exports.Z_DATA_ERROR) {
          // Both inflateSetDictionary() and inflate() return Z_DATA_ERROR.
          // Make it possible for After() to tell a bad dictionary from bad
          // input.
          this.err = exports.Z_NEED_DICT;
        }
      }
      while (this.strm.avail_in > 0 && this.mode === exports.GUNZIP && this.err === exports.Z_STREAM_END && this.strm.next_in[0] !== 0x00) {
        // Bytes remain in input buffer. Perhaps this is another compressed
        // member in the same archive, or just trailing garbage.
        // Trailing zero bytes are okay, though, since they are frequently
        // used for padding.

        this.reset();
        this.err = zlib_inflate.inflate(this.strm, this.flush);
      }
      break;
    default:
      throw new Error('Unknown mode ' + this.mode);
  }
};

Zlib.prototype._checkError = function () {
  // Acceptable error states depend on the type of zlib stream.
  switch (this.err) {
    case exports.Z_OK:
    case exports.Z_BUF_ERROR:
      if (this.strm.avail_out !== 0 && this.flush === exports.Z_FINISH) {
        this._error('unexpected end of file');
        return false;
      }
      break;
    case exports.Z_STREAM_END:
      // normal statuses, not fatal
      break;
    case exports.Z_NEED_DICT:
      if (this.dictionary == null) {
        this._error('Missing dictionary');
      } else {
        this._error('Bad dictionary');
      }
      return false;
    default:
      // something else.
      this._error('Zlib error');
      return false;
  }

  return true;
};

Zlib.prototype._after = function () {
  if (!this._checkError()) {
    return;
  }

  var avail_out = this.strm.avail_out;
  var avail_in = this.strm.avail_in;

  this.write_in_progress = false;

  // call the write() cb
  this.callback(avail_in, avail_out);

  if (this.pending_close) {
    this.close();
  }
};

Zlib.prototype._error = function (message) {
  if (this.strm.msg) {
    message = this.strm.msg;
  }
  this.onerror(message, this.err

  // no hope of rescue.
  );this.write_in_progress = false;
  if (this.pending_close) {
    this.close();
  }
};

Zlib.prototype.init = function (windowBits, level, memLevel, strategy, dictionary) {
  assert(arguments.length === 4 || arguments.length === 5, 'init(windowBits, level, memLevel, strategy, [dictionary])');

  assert(windowBits >= 8 && windowBits <= 15, 'invalid windowBits');
  assert(level >= -1 && level <= 9, 'invalid compression level');

  assert(memLevel >= 1 && memLevel <= 9, 'invalid memlevel');

  assert(strategy === exports.Z_FILTERED || strategy === exports.Z_HUFFMAN_ONLY || strategy === exports.Z_RLE || strategy === exports.Z_FIXED || strategy === exports.Z_DEFAULT_STRATEGY, 'invalid strategy');

  this._init(level, windowBits, memLevel, strategy, dictionary);
  this._setDictionary();
};

Zlib.prototype.params = function () {
  throw new Error('deflateParams Not supported');
};

Zlib.prototype.reset = function () {
  this._reset();
  this._setDictionary();
};

Zlib.prototype._init = function (level, windowBits, memLevel, strategy, dictionary) {
  this.level = level;
  this.windowBits = windowBits;
  this.memLevel = memLevel;
  this.strategy = strategy;

  this.flush = exports.Z_NO_FLUSH;

  this.err = exports.Z_OK;

  if (this.mode === exports.GZIP || this.mode === exports.GUNZIP) {
    this.windowBits += 16;
  }

  if (this.mode === exports.UNZIP) {
    this.windowBits += 32;
  }

  if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW) {
    this.windowBits = -1 * this.windowBits;
  }

  this.strm = new Zstream();

  switch (this.mode) {
    case exports.DEFLATE:
    case exports.GZIP:
    case exports.DEFLATERAW:
      this.err = zlib_deflate.deflateInit2(this.strm, this.level, exports.Z_DEFLATED, this.windowBits, this.memLevel, this.strategy);
      break;
    case exports.INFLATE:
    case exports.GUNZIP:
    case exports.INFLATERAW:
    case exports.UNZIP:
      this.err = zlib_inflate.inflateInit2(this.strm, this.windowBits);
      break;
    default:
      throw new Error('Unknown mode ' + this.mode);
  }

  if (this.err !== exports.Z_OK) {
    this._error('Init error');
  }

  this.dictionary = dictionary;

  this.write_in_progress = false;
  this.init_done = true;
};

Zlib.prototype._setDictionary = function () {
  if (this.dictionary == null) {
    return;
  }

  this.err = exports.Z_OK;

  switch (this.mode) {
    case exports.DEFLATE:
    case exports.DEFLATERAW:
      this.err = zlib_deflate.deflateSetDictionary(this.strm, this.dictionary);
      break;
    default:
      break;
  }

  if (this.err !== exports.Z_OK) {
    this._error('Failed to set dictionary');
  }
};

Zlib.prototype._reset = function () {
  this.err = exports.Z_OK;

  switch (this.mode) {
    case exports.DEFLATE:
    case exports.DEFLATERAW:
    case exports.GZIP:
      this.err = zlib_deflate.deflateReset(this.strm);
      break;
    case exports.INFLATE:
    case exports.INFLATERAW:
    case exports.GUNZIP:
      this.err = zlib_inflate.inflateReset(this.strm);
      break;
    default:
      break;
  }

  if (this.err !== exports.Z_OK) {
    this._error('Failed to reset stream');
  }
};

exports.Zlib = Zlib;
}).call(this)}).call(this,require('_process'),require("buffer").Buffer)
},{"_process":87,"assert":48,"buffer":"buffer","pako/lib/zlib/constants":78,"pako/lib/zlib/deflate.js":80,"pako/lib/zlib/inflate.js":82,"pako/lib/zlib/zstream":86}],56:[function(require,module,exports){
(function (process){(function (){
'use strict';

var Buffer = require('buffer').Buffer;
var Transform = require('stream').Transform;
var binding = require('./binding');
var util = require('util');
var assert = require('assert').ok;
var kMaxLength = require('buffer').kMaxLength;
var kRangeErrorMessage = 'Cannot create final Buffer. It would be larger ' + 'than 0x' + kMaxLength.toString(16) + ' bytes';

// zlib doesn't provide these, so kludge them in following the same
// const naming scheme zlib uses.
binding.Z_MIN_WINDOWBITS = 8;
binding.Z_MAX_WINDOWBITS = 15;
binding.Z_DEFAULT_WINDOWBITS = 15;

// fewer than 64 bytes per chunk is stupid.
// technically it could work with as few as 8, but even 64 bytes
// is absurdly low.  Usually a MB or more is best.
binding.Z_MIN_CHUNK = 64;
binding.Z_MAX_CHUNK = Infinity;
binding.Z_DEFAULT_CHUNK = 16 * 1024;

binding.Z_MIN_MEMLEVEL = 1;
binding.Z_MAX_MEMLEVEL = 9;
binding.Z_DEFAULT_MEMLEVEL = 8;

binding.Z_MIN_LEVEL = -1;
binding.Z_MAX_LEVEL = 9;
binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION;

// expose all the zlib constants
var bkeys = Object.keys(binding);
for (var bk = 0; bk < bkeys.length; bk++) {
  var bkey = bkeys[bk];
  if (bkey.match(/^Z/)) {
    Object.defineProperty(exports, bkey, {
      enumerable: true, value: binding[bkey], writable: false
    });
  }
}

// translation table for return codes.
var codes = {
  Z_OK: binding.Z_OK,
  Z_STREAM_END: binding.Z_STREAM_END,
  Z_NEED_DICT: binding.Z_NEED_DICT,
  Z_ERRNO: binding.Z_ERRNO,
  Z_STREAM_ERROR: binding.Z_STREAM_ERROR,
  Z_DATA_ERROR: binding.Z_DATA_ERROR,
  Z_MEM_ERROR: binding.Z_MEM_ERROR,
  Z_BUF_ERROR: binding.Z_BUF_ERROR,
  Z_VERSION_ERROR: binding.Z_VERSION_ERROR
};

var ckeys = Object.keys(codes);
for (var ck = 0; ck < ckeys.length; ck++) {
  var ckey = ckeys[ck];
  codes[codes[ckey]] = ckey;
}

Object.defineProperty(exports, 'codes', {
  enumerable: true, value: Object.freeze(codes), writable: false
});

exports.Deflate = Deflate;
exports.Inflate = Inflate;
exports.Gzip = Gzip;
exports.Gunzip = Gunzip;
exports.DeflateRaw = DeflateRaw;
exports.InflateRaw = InflateRaw;
exports.Unzip = Unzip;

exports.createDeflate = function (o) {
  return new Deflate(o);
};

exports.createInflate = function (o) {
  return new Inflate(o);
};

exports.createDeflateRaw = function (o) {
  return new DeflateRaw(o);
};

exports.createInflateRaw = function (o) {
  return new InflateRaw(o);
};

exports.createGzip = function (o) {
  return new Gzip(o);
};

exports.createGunzip = function (o) {
  return new Gunzip(o);
};

exports.createUnzip = function (o) {
  return new Unzip(o);
};

// Convenience methods.
// compress/decompress a string or buffer in one step.
exports.deflate = function (buffer, opts, callback) {
  if (typeof opts === 'function') {
    callback = opts;
    opts = {};
  }
  return zlibBuffer(new Deflate(opts), buffer, callback);
};

exports.deflateSync = function (buffer, opts) {
  return zlibBufferSync(new Deflate(opts), buffer);
};

exports.gzip = function (buffer, opts, callback) {
  if (typeof opts === 'function') {
    callback = opts;
    opts = {};
  }
  return zlibBuffer(new Gzip(opts), buffer, callback);
};

exports.gzipSync = function (buffer, opts) {
  return zlibBufferSync(new Gzip(opts), buffer);
};

exports.deflateRaw = function (buffer, opts, callback) {
  if (typeof opts === 'function') {
    callback = opts;
    opts = {};
  }
  return zlibBuffer(new DeflateRaw(opts), buffer, callback);
};

exports.deflateRawSync = function (buffer, opts) {
  return zlibBufferSync(new DeflateRaw(opts), buffer);
};

exports.unzip = function (buffer, opts, callback) {
  if (typeof opts === 'function') {
    callback = opts;
    opts = {};
  }
  return zlibBuffer(new Unzip(opts), buffer, callback);
};

exports.unzipSync = function (buffer, opts) {
  return zlibBufferSync(new Unzip(opts), buffer);
};

exports.inflate = function (buffer, opts, callback) {
  if (typeof opts === 'function') {
    callback = opts;
    opts = {};
  }
  return zlibBuffer(new Inflate(opts), buffer, callback);
};

exports.inflateSync = function (buffer, opts) {
  return zlibBufferSync(new Inflate(opts), buffer);
};

exports.gunzip = function (buffer, opts, callback) {
  if (typeof opts === 'function') {
    callback = opts;
    opts = {};
  }
  return zlibBuffer(new Gunzip(opts), buffer, callback);
};

exports.gunzipSync = function (buffer, opts) {
  return zlibBufferSync(new Gunzip(opts), buffer);
};

exports.inflateRaw = function (buffer, opts, callback) {
  if (typeof opts === 'function') {
    callback = opts;
    opts = {};
  }
  return zlibBuffer(new InflateRaw(opts), buffer, callback);
};

exports.inflateRawSync = function (buffer, opts) {
  return zlibBufferSync(new InflateRaw(opts), buffer);
};

function zlibBuffer(engine, buffer, callback) {
  var buffers = [];
  var nread = 0;

  engine.on('error', onError);
  engine.on('end', onEnd);

  engine.end(buffer);
  flow();

  function flow() {
    var chunk;
    while (null !== (chunk = engine.read())) {
      buffers.push(chunk);
      nread += chunk.length;
    }
    engine.once('readable', flow);
  }

  function onError(err) {
    engine.removeListener('end', onEnd);
    engine.removeListener('readable', flow);
    callback(err);
  }

  function onEnd() {
    var buf;
    var err = null;

    if (nread >= kMaxLength) {
      err = new RangeError(kRangeErrorMessage);
    } else {
      buf = Buffer.concat(buffers, nread);
    }

    buffers = [];
    engine.close();
    callback(err, buf);
  }
}

function zlibBufferSync(engine, buffer) {
  if (typeof buffer === 'string') buffer = Buffer.from(buffer);

  if (!Buffer.isBuffer(buffer)) throw new TypeError('Not a string or buffer');

  var flushFlag = engine._finishFlushFlag;

  return engine._processChunk(buffer, flushFlag);
}

// generic zlib
// minimal 2-byte header
function Deflate(opts) {
  if (!(this instanceof Deflate)) return new Deflate(opts);
  Zlib.call(this, opts, binding.DEFLATE);
}

function Inflate(opts) {
  if (!(this instanceof Inflate)) return new Inflate(opts);
  Zlib.call(this, opts, binding.INFLATE);
}

// gzip - bigger header, same deflate compression
function Gzip(opts) {
  if (!(this instanceof Gzip)) return new Gzip(opts);
  Zlib.call(this, opts, binding.GZIP);
}

function Gunzip(opts) {
  if (!(this instanceof Gunzip)) return new Gunzip(opts);
  Zlib.call(this, opts, binding.GUNZIP);
}

// raw - no header
function DeflateRaw(opts) {
  if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);
  Zlib.call(this, opts, binding.DEFLATERAW);
}

function InflateRaw(opts) {
  if (!(this instanceof InflateRaw)) return new InflateRaw(opts);
  Zlib.call(this, opts, binding.INFLATERAW);
}

// auto-detect header.
function Unzip(opts) {
  if (!(this instanceof Unzip)) return new Unzip(opts);
  Zlib.call(this, opts, binding.UNZIP);
}

function isValidFlushFlag(flag) {
  return flag === binding.Z_NO_FLUSH || flag === binding.Z_PARTIAL_FLUSH || flag === binding.Z_SYNC_FLUSH || flag === binding.Z_FULL_FLUSH || flag === binding.Z_FINISH || flag === binding.Z_BLOCK;
}

// the Zlib class they all inherit from
// This thing manages the queue of requests, and returns
// true or false if there is anything in the queue when
// you call the .write() method.

function Zlib(opts, mode) {
  var _this = this;

  this._opts = opts = opts || {};
  this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK;

  Transform.call(this, opts);

  if (opts.flush && !isValidFlushFlag(opts.flush)) {
    throw new Error('Invalid flush flag: ' + opts.flush);
  }
  if (opts.finishFlush && !isValidFlushFlag(opts.finishFlush)) {
    throw new Error('Invalid flush flag: ' + opts.finishFlush);
  }

  this._flushFlag = opts.flush || binding.Z_NO_FLUSH;
  this._finishFlushFlag = typeof opts.finishFlush !== 'undefined' ? opts.finishFlush : binding.Z_FINISH;

  if (opts.chunkSize) {
    if (opts.chunkSize < exports.Z_MIN_CHUNK || opts.chunkSize > exports.Z_MAX_CHUNK) {
      throw new Error('Invalid chunk size: ' + opts.chunkSize);
    }
  }

  if (opts.windowBits) {
    if (opts.windowBits < exports.Z_MIN_WINDOWBITS || opts.windowBits > exports.Z_MAX_WINDOWBITS) {
      throw new Error('Invalid windowBits: ' + opts.windowBits);
    }
  }

  if (opts.level) {
    if (opts.level < exports.Z_MIN_LEVEL || opts.level > exports.Z_MAX_LEVEL) {
      throw new Error('Invalid compression level: ' + opts.level);
    }
  }

  if (opts.memLevel) {
    if (opts.memLevel < exports.Z_MIN_MEMLEVEL || opts.memLevel > exports.Z_MAX_MEMLEVEL) {
      throw new Error('Invalid memLevel: ' + opts.memLevel);
    }
  }

  if (opts.strategy) {
    if (opts.strategy != exports.Z_FILTERED && opts.strategy != exports.Z_HUFFMAN_ONLY && opts.strategy != exports.Z_RLE && opts.strategy != exports.Z_FIXED && opts.strategy != exports.Z_DEFAULT_STRATEGY) {
      throw new Error('Invalid strategy: ' + opts.strategy);
    }
  }

  if (opts.dictionary) {
    if (!Buffer.isBuffer(opts.dictionary)) {
      throw new Error('Invalid dictionary: it should be a Buffer instance');
    }
  }

  this._handle = new binding.Zlib(mode);

  var self = this;
  this._hadError = false;
  this._handle.onerror = function (message, errno) {
    // there is no way to cleanly recover.
    // continuing only obscures problems.
    _close(self);
    self._hadError = true;

    var error = new Error(message);
    error.errno = errno;
    error.code = exports.codes[errno];
    self.emit('error', error);
  };

  var level = exports.Z_DEFAULT_COMPRESSION;
  if (typeof opts.level === 'number') level = opts.level;

  var strategy = exports.Z_DEFAULT_STRATEGY;
  if (typeof opts.strategy === 'number') strategy = opts.strategy;

  this._handle.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS, level, opts.memLevel || exports.Z_DEFAULT_MEMLEVEL, strategy, opts.dictionary);

  this._buffer = Buffer.allocUnsafe(this._chunkSize);
  this._offset = 0;
  this._level = level;
  this._strategy = strategy;

  this.once('end', this.close);

  Object.defineProperty(this, '_closed', {
    get: function () {
      return !_this._handle;
    },
    configurable: true,
    enumerable: true
  });
}

util.inherits(Zlib, Transform);

Zlib.prototype.params = function (level, strategy, callback) {
  if (level < exports.Z_MIN_LEVEL || level > exports.Z_MAX_LEVEL) {
    throw new RangeError('Invalid compression level: ' + level);
  }
  if (strategy != exports.Z_FILTERED && strategy != exports.Z_HUFFMAN_ONLY && strategy != exports.Z_RLE && strategy != exports.Z_FIXED && strategy != exports.Z_DEFAULT_STRATEGY) {
    throw new TypeError('Invalid strategy: ' + strategy);
  }

  if (this._level !== level || this._strategy !== strategy) {
    var self = this;
    this.flush(binding.Z_SYNC_FLUSH, function () {
      assert(self._handle, 'zlib binding closed');
      self._handle.params(level, strategy);
      if (!self._hadError) {
        self._level = level;
        self._strategy = strategy;
        if (callback) callback();
      }
    });
  } else {
    process.nextTick(callback);
  }
};

Zlib.prototype.reset = function () {
  assert(this._handle, 'zlib binding closed');
  return this._handle.reset();
};

// This is the _flush function called by the transform class,
// internally, when the last chunk has been written.
Zlib.prototype._flush = function (callback) {
  this._transform(Buffer.alloc(0), '', callback);
};

Zlib.prototype.flush = function (kind, callback) {
  var _this2 = this;

  var ws = this._writableState;

  if (typeof kind === 'function' || kind === undefined && !callback) {
    callback = kind;
    kind = binding.Z_FULL_FLUSH;
  }

  if (ws.ended) {
    if (callback) process.nextTick(callback);
  } else if (ws.ending) {
    if (callback) this.once('end', callback);
  } else if (ws.needDrain) {
    if (callback) {
      this.once('drain', function () {
        return _this2.flush(kind, callback);
      });
    }
  } else {
    this._flushFlag = kind;
    this.write(Buffer.alloc(0), '', callback);
  }
};

Zlib.prototype.close = function (callback) {
  _close(this, callback);
  process.nextTick(emitCloseNT, this);
};

function _close(engine, callback) {
  if (callback) process.nextTick(callback);

  // Caller may invoke .close after a zlib error (which will null _handle).
  if (!engine._handle) return;

  engine._handle.close();
  engine._handle = null;
}

function emitCloseNT(self) {
  self.emit('close');
}

Zlib.prototype._transform = function (chunk, encoding, cb) {
  var flushFlag;
  var ws = this._writableState;
  var ending = ws.ending || ws.ended;
  var last = ending && (!chunk || ws.length === chunk.length);

  if (chunk !== null && !Buffer.isBuffer(chunk)) return cb(new Error('invalid input'));

  if (!this._handle) return cb(new Error('zlib binding closed'));

  // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag
  // (or whatever flag was provided using opts.finishFlush).
  // If it's explicitly flushing at some other time, then we use
  // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression
  // goodness.
  if (last) flushFlag = this._finishFlushFlag;else {
    flushFlag = this._flushFlag;
    // once we've flushed the last of the queue, stop flushing and
    // go back to the normal behavior.
    if (chunk.length >= ws.length) {
      this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH;
    }
  }

  this._processChunk(chunk, flushFlag, cb);
};

Zlib.prototype._processChunk = function (chunk, flushFlag, cb) {
  var availInBefore = chunk && chunk.length;
  var availOutBefore = this._chunkSize - this._offset;
  var inOff = 0;

  var self = this;

  var async = typeof cb === 'function';

  if (!async) {
    var buffers = [];
    var nread = 0;

    var error;
    this.on('error', function (er) {
      error = er;
    });

    assert(this._handle, 'zlib binding closed');
    do {
      var res = this._handle.writeSync(flushFlag, chunk, // in
      inOff, // in_off
      availInBefore, // in_len
      this._buffer, // out
      this._offset, //out_off
      availOutBefore); // out_len
    } while (!this._hadError && callback(res[0], res[1]));

    if (this._hadError) {
      throw error;
    }

    if (nread >= kMaxLength) {
      _close(this);
      throw new RangeError(kRangeErrorMessage);
    }

    var buf = Buffer.concat(buffers, nread);
    _close(this);

    return buf;
  }

  assert(this._handle, 'zlib binding closed');
  var req = this._handle.write(flushFlag, chunk, // in
  inOff, // in_off
  availInBefore, // in_len
  this._buffer, // out
  this._offset, //out_off
  availOutBefore); // out_len

  req.buffer = chunk;
  req.callback = callback;

  function callback(availInAfter, availOutAfter) {
    // When the callback is used in an async write, the callback's
    // context is the `req` object that was created. The req object
    // is === this._handle, and that's why it's important to null
    // out the values after they are done being used. `this._handle`
    // can stay in memory longer than the callback and buffer are needed.
    if (this) {
      this.buffer = null;
      this.callback = null;
    }

    if (self._hadError) return;

    var have = availOutBefore - availOutAfter;
    assert(have >= 0, 'have should not go down');

    if (have > 0) {
      var out = self._buffer.slice(self._offset, self._offset + have);
      self._offset += have;
      // serve some output to the consumer.
      if (async) {
        self.push(out);
      } else {
        buffers.push(out);
        nread += out.length;
      }
    }

    // exhausted the output buffer, or used all the input create a new one.
    if (availOutAfter === 0 || self._offset >= self._chunkSize) {
      availOutBefore = self._chunkSize;
      self._offset = 0;
      self._buffer = Buffer.allocUnsafe(self._chunkSize);
    }

    if (availOutAfter === 0) {
      // Not actually done.  Need to reprocess.
      // Also, update the availInBefore to the availInAfter value,
      // so that if we have to hit it a third (fourth, etc.) time,
      // it'll have the correct byte counts.
      inOff += availInBefore - availInAfter;
      availInBefore = availInAfter;

      if (!async) return true;

      var newReq = self._handle.write(flushFlag, chunk, inOff, availInBefore, self._buffer, self._offset, self._chunkSize);
      newReq.callback = callback; // this same function
      newReq.buffer = chunk;
      return;
    }

    if (!async) return false;

    // finished with the chunk.
    cb();
  }
};

util.inherits(Deflate, Zlib);
util.inherits(Inflate, Zlib);
util.inherits(Gzip, Zlib);
util.inherits(Gunzip, Zlib);
util.inherits(DeflateRaw, Zlib);
util.inherits(InflateRaw, Zlib);
util.inherits(Unzip, Zlib);
}).call(this)}).call(this,require('_process'))
},{"./binding":55,"_process":87,"assert":48,"buffer":"buffer","stream":89,"util":109}],57:[function(require,module,exports){
arguments[4][2][0].apply(exports,arguments)
},{"./":58,"dup":2,"get-intrinsic":63}],58:[function(require,module,exports){
arguments[4][3][0].apply(exports,arguments)
},{"dup":3,"function-bind":62,"get-intrinsic":63}],59:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

'use strict';

var R = typeof Reflect === 'object' ? Reflect : null
var ReflectApply = R && typeof R.apply === 'function'
  ? R.apply
  : function ReflectApply(target, receiver, args) {
    return Function.prototype.apply.call(target, receiver, args);
  }

var ReflectOwnKeys
if (R && typeof R.ownKeys === 'function') {
  ReflectOwnKeys = R.ownKeys
} else if (Object.getOwnPropertySymbols) {
  ReflectOwnKeys = function ReflectOwnKeys(target) {
    return Object.getOwnPropertyNames(target)
      .concat(Object.getOwnPropertySymbols(target));
  };
} else {
  ReflectOwnKeys = function ReflectOwnKeys(target) {
    return Object.getOwnPropertyNames(target);
  };
}

function ProcessEmitWarning(warning) {
  if (console && console.warn) console.warn(warning);
}

var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
  return value !== value;
}

function EventEmitter() {
  EventEmitter.init.call(this);
}
module.exports = EventEmitter;
module.exports.once = once;

// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;

EventEmitter.prototype._events = undefined;
EventEmitter.prototype._eventsCount = 0;
EventEmitter.prototype._maxListeners = undefined;

// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
var defaultMaxListeners = 10;

function checkListener(listener) {
  if (typeof listener !== 'function') {
    throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
  }
}

Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
  enumerable: true,
  get: function() {
    return defaultMaxListeners;
  },
  set: function(arg) {
    if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
      throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
    }
    defaultMaxListeners = arg;
  }
});

EventEmitter.init = function() {

  if (this._events === undefined ||
      this._events === Object.getPrototypeOf(this)._events) {
    this._events = Object.create(null);
    this._eventsCount = 0;
  }

  this._maxListeners = this._maxListeners || undefined;
};

// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
    throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
  }
  this._maxListeners = n;
  return this;
};

function _getMaxListeners(that) {
  if (that._maxListeners === undefined)
    return EventEmitter.defaultMaxListeners;
  return that._maxListeners;
}

EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  return _getMaxListeners(this);
};

EventEmitter.prototype.emit = function emit(type) {
  var args = [];
  for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
  var doError = (type === 'error');

  var events = this._events;
  if (events !== undefined)
    doError = (doError && events.error === undefined);
  else if (!doError)
    return false;

  // If there is no 'error' event listener then throw.
  if (doError) {
    var er;
    if (args.length > 0)
      er = args[0];
    if (er instanceof Error) {
      // Note: The comments on the `throw` lines are intentional, they show
      // up in Node's output if this results in an unhandled exception.
      throw er; // Unhandled 'error' event
    }
    // At least give some kind of context to the user
    var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
    err.context = er;
    throw err; // Unhandled 'error' event
  }

  var handler = events[type];

  if (handler === undefined)
    return false;

  if (typeof handler === 'function') {
    ReflectApply(handler, this, args);
  } else {
    var len = handler.length;
    var listeners = arrayClone(handler, len);
    for (var i = 0; i < len; ++i)
      ReflectApply(listeners[i], this, args);
  }

  return true;
};

function _addListener(target, type, listener, prepend) {
  var m;
  var events;
  var existing;

  checkListener(listener);

  events = target._events;
  if (events === undefined) {
    events = target._events = Object.create(null);
    target._eventsCount = 0;
  } else {
    // To avoid recursion in the case that type === "newListener"! Before
    // adding it to the listeners, first emit "newListener".
    if (events.newListener !== undefined) {
      target.emit('newListener', type,
                  listener.listener ? listener.listener : listener);

      // Re-assign `events` because a newListener handler could have caused the
      // this._events to be assigned to a new object
      events = target._events;
    }
    existing = events[type];
  }

  if (existing === undefined) {
    // Optimize the case of one listener. Don't need the extra array object.
    existing = events[type] = listener;
    ++target._eventsCount;
  } else {
    if (typeof existing === 'function') {
      // Adding the second element, need to change to array.
      existing = events[type] =
        prepend ? [listener, existing] : [existing, listener];
      // If we've already got an array, just append.
    } else if (prepend) {
      existing.unshift(listener);
    } else {
      existing.push(listener);
    }

    // Check for listener leak
    m = _getMaxListeners(target);
    if (m > 0 && existing.length > m && !existing.warned) {
      existing.warned = true;
      // No error code for this since it is a Warning
      // eslint-disable-next-line no-restricted-syntax
      var w = new Error('Possible EventEmitter memory leak detected. ' +
                          existing.length + ' ' + String(type) + ' listeners ' +
                          'added. Use emitter.setMaxListeners() to ' +
                          'increase limit');
      w.name = 'MaxListenersExceededWarning';
      w.emitter = target;
      w.type = type;
      w.count = existing.length;
      ProcessEmitWarning(w);
    }
  }

  return target;
}

EventEmitter.prototype.addListener = function addListener(type, listener) {
  return _addListener(this, type, listener, false);
};

EventEmitter.prototype.on = EventEmitter.prototype.addListener;

EventEmitter.prototype.prependListener =
    function prependListener(type, listener) {
      return _addListener(this, type, listener, true);
    };

function onceWrapper() {
  if (!this.fired) {
    this.target.removeListener(this.type, this.wrapFn);
    this.fired = true;
    if (arguments.length === 0)
      return this.listener.call(this.target);
    return this.listener.apply(this.target, arguments);
  }
}

function _onceWrap(target, type, listener) {
  var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
  var wrapped = onceWrapper.bind(state);
  wrapped.listener = listener;
  state.wrapFn = wrapped;
  return wrapped;
}

EventEmitter.prototype.once = function once(type, listener) {
  checkListener(listener);
  this.on(type, _onceWrap(this, type, listener));
  return this;
};

EventEmitter.prototype.prependOnceListener =
    function prependOnceListener(type, listener) {
      checkListener(listener);
      this.prependListener(type, _onceWrap(this, type, listener));
      return this;
    };

// Emits a 'removeListener' event if and only if the listener was removed.
EventEmitter.prototype.removeListener =
    function removeListener(type, listener) {
      var list, events, position, i, originalListener;

      checkListener(listener);

      events = this._events;
      if (events === undefined)
        return this;

      list = events[type];
      if (list === undefined)
        return this;

      if (list === listener || list.listener === listener) {
        if (--this._eventsCount === 0)
          this._events = Object.create(null);
        else {
          delete events[type];
          if (events.removeListener)
            this.emit('removeListener', type, list.listener || listener);
        }
      } else if (typeof list !== 'function') {
        position = -1;

        for (i = list.length - 1; i >= 0; i--) {
          if (list[i] === listener || list[i].listener === listener) {
            originalListener = list[i].listener;
            position = i;
            break;
          }
        }

        if (position < 0)
          return this;

        if (position === 0)
          list.shift();
        else {
          spliceOne(list, position);
        }

        if (list.length === 1)
          events[type] = list[0];

        if (events.removeListener !== undefined)
          this.emit('removeListener', type, originalListener || listener);
      }

      return this;
    };

EventEmitter.prototype.off = EventEmitter.prototype.removeListener;

EventEmitter.prototype.removeAllListeners =
    function removeAllListeners(type) {
      var listeners, events, i;

      events = this._events;
      if (events === undefined)
        return this;

      // not listening for removeListener, no need to emit
      if (events.removeListener === undefined) {
        if (arguments.length === 0) {
          this._events = Object.create(null);
          this._eventsCount = 0;
        } else if (events[type] !== undefined) {
          if (--this._eventsCount === 0)
            this._events = Object.create(null);
          else
            delete events[type];
        }
        return this;
      }

      // emit removeListener for all listeners on all events
      if (arguments.length === 0) {
        var keys = Object.keys(events);
        var key;
        for (i = 0; i < keys.length; ++i) {
          key = keys[i];
          if (key === 'removeListener') continue;
          this.removeAllListeners(key);
        }
        this.removeAllListeners('removeListener');
        this._events = Object.create(null);
        this._eventsCount = 0;
        return this;
      }

      listeners = events[type];

      if (typeof listeners === 'function') {
        this.removeListener(type, listeners);
      } else if (listeners !== undefined) {
        // LIFO order
        for (i = listeners.length - 1; i >= 0; i--) {
          this.removeListener(type, listeners[i]);
        }
      }

      return this;
    };

function _listeners(target, type, unwrap) {
  var events = target._events;

  if (events === undefined)
    return [];

  var evlistener = events[type];
  if (evlistener === undefined)
    return [];

  if (typeof evlistener === 'function')
    return unwrap ? [evlistener.listener || evlistener] : [evlistener];

  return unwrap ?
    unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
}

EventEmitter.prototype.listeners = function listeners(type) {
  return _listeners(this, type, true);
};

EventEmitter.prototype.rawListeners = function rawListeners(type) {
  return _listeners(this, type, false);
};

EventEmitter.listenerCount = function(emitter, type) {
  if (typeof emitter.listenerCount === 'function') {
    return emitter.listenerCount(type);
  } else {
    return listenerCount.call(emitter, type);
  }
};

EventEmitter.prototype.listenerCount = listenerCount;
function listenerCount(type) {
  var events = this._events;

  if (events !== undefined) {
    var evlistener = events[type];

    if (typeof evlistener === 'function') {
      return 1;
    } else if (evlistener !== undefined) {
      return evlistener.length;
    }
  }

  return 0;
}

EventEmitter.prototype.eventNames = function eventNames() {
  return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
};

function arrayClone(arr, n) {
  var copy = new Array(n);
  for (var i = 0; i < n; ++i)
    copy[i] = arr[i];
  return copy;
}

function spliceOne(list, index) {
  for (; index + 1 < list.length; index++)
    list[index] = list[index + 1];
  list.pop();
}

function unwrapListeners(arr) {
  var ret = new Array(arr.length);
  for (var i = 0; i < ret.length; ++i) {
    ret[i] = arr[i].listener || arr[i];
  }
  return ret;
}

function once(emitter, name) {
  return new Promise(function (resolve, reject) {
    function errorListener(err) {
      emitter.removeListener(name, resolver);
      reject(err);
    }

    function resolver() {
      if (typeof emitter.removeListener === 'function') {
        emitter.removeListener('error', errorListener);
      }
      resolve([].slice.call(arguments));
    };

    eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
    if (name !== 'error') {
      addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
    }
  });
}

function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
  if (typeof emitter.on === 'function') {
    eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
  }
}

function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
  if (typeof emitter.on === 'function') {
    if (flags.once) {
      emitter.once(name, listener);
    } else {
      emitter.on(name, listener);
    }
  } else if (typeof emitter.addEventListener === 'function') {
    // EventTarget does not have `error` event semantics like Node
    // EventEmitters, we do not listen for `error` events here.
    emitter.addEventListener(name, function wrapListener(arg) {
      // IE does not have builtin `{ once: true }` support so we
      // have to do it manually.
      if (flags.once) {
        emitter.removeEventListener(name, wrapListener);
      }
      listener(arg);
    });
  } else {
    throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
  }
}

},{}],60:[function(require,module,exports){
'use strict';

var isCallable = require('is-callable');

var toStr = Object.prototype.toString;
var hasOwnProperty = Object.prototype.hasOwnProperty;

var forEachArray = function forEachArray(array, iterator, receiver) {
    for (var i = 0, len = array.length; i < len; i++) {
        if (hasOwnProperty.call(array, i)) {
            if (receiver == null) {
                iterator(array[i], i, array);
            } else {
                iterator.call(receiver, array[i], i, array);
            }
        }
    }
};

var forEachString = function forEachString(string, iterator, receiver) {
    for (var i = 0, len = string.length; i < len; i++) {
        // no such thing as a sparse string.
        if (receiver == null) {
            iterator(string.charAt(i), i, string);
        } else {
            iterator.call(receiver, string.charAt(i), i, string);
        }
    }
};

var forEachObject = function forEachObject(object, iterator, receiver) {
    for (var k in object) {
        if (hasOwnProperty.call(object, k)) {
            if (receiver == null) {
                iterator(object[k], k, object);
            } else {
                iterator.call(receiver, object[k], k, object);
            }
        }
    }
};

var forEach = function forEach(list, iterator, thisArg) {
    if (!isCallable(iterator)) {
        throw new TypeError('iterator must be a function');
    }

    var receiver;
    if (arguments.length >= 3) {
        receiver = thisArg;
    }

    if (toStr.call(list) === '[object Array]') {
        forEachArray(list, iterator, receiver);
    } else if (typeof list === 'string') {
        forEachString(list, iterator, receiver);
    } else {
        forEachObject(list, iterator, receiver);
    }
};

module.exports = forEach;

},{"is-callable":72}],61:[function(require,module,exports){
arguments[4][4][0].apply(exports,arguments)
},{"dup":4}],62:[function(require,module,exports){
arguments[4][5][0].apply(exports,arguments)
},{"./implementation":61,"dup":5}],63:[function(require,module,exports){
arguments[4][6][0].apply(exports,arguments)
},{"dup":6,"function-bind":62,"has":68,"has-symbols":65}],64:[function(require,module,exports){
'use strict';

var GetIntrinsic = require('get-intrinsic');

var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true);

if ($gOPD) {
	try {
		$gOPD([], 'length');
	} catch (e) {
		// IE 8 has a broken gOPD
		$gOPD = null;
	}
}

module.exports = $gOPD;

},{"get-intrinsic":63}],65:[function(require,module,exports){
arguments[4][7][0].apply(exports,arguments)
},{"./shams":66,"dup":7}],66:[function(require,module,exports){
arguments[4][8][0].apply(exports,arguments)
},{"dup":8}],67:[function(require,module,exports){
'use strict';

var hasSymbols = require('has-symbols/shams');

module.exports = function hasToStringTagShams() {
	return hasSymbols() && !!Symbol.toStringTag;
};

},{"has-symbols/shams":66}],68:[function(require,module,exports){
arguments[4][9][0].apply(exports,arguments)
},{"dup":9,"function-bind":62}],69:[function(require,module,exports){
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  var e, m
  var eLen = (nBytes * 8) - mLen - 1
  var eMax = (1 << eLen) - 1
  var eBias = eMax >> 1
  var nBits = -7
  var i = isLE ? (nBytes - 1) : 0
  var d = isLE ? -1 : 1
  var s = buffer[offset + i]

  i += d

  e = s & ((1 << (-nBits)) - 1)
  s >>= (-nBits)
  nBits += eLen
  for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}

  m = e & ((1 << (-nBits)) - 1)
  e >>= (-nBits)
  nBits += mLen
  for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}

  if (e === 0) {
    e = 1 - eBias
  } else if (e === eMax) {
    return m ? NaN : ((s ? -1 : 1) * Infinity)
  } else {
    m = m + Math.pow(2, mLen)
    e = e - eBias
  }
  return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}

exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  var e, m, c
  var eLen = (nBytes * 8) - mLen - 1
  var eMax = (1 << eLen) - 1
  var eBias = eMax >> 1
  var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  var i = isLE ? 0 : (nBytes - 1)
  var d = isLE ? 1 : -1
  var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0

  value = Math.abs(value)

  if (isNaN(value) || value === Infinity) {
    m = isNaN(value) ? 1 : 0
    e = eMax
  } else {
    e = Math.floor(Math.log(value) / Math.LN2)
    if (value * (c = Math.pow(2, -e)) < 1) {
      e--
      c *= 2
    }
    if (e + eBias >= 1) {
      value += rt / c
    } else {
      value += rt * Math.pow(2, 1 - eBias)
    }
    if (value * c >= 2) {
      e++
      c /= 2
    }

    if (e + eBias >= eMax) {
      m = 0
      e = eMax
    } else if (e + eBias >= 1) {
      m = ((value * c) - 1) * Math.pow(2, mLen)
      e = e + eBias
    } else {
      m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
      e = 0
    }
  }

  for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}

  e = (e << mLen) | m
  eLen += mLen
  for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}

  buffer[offset + i - d] |= s * 128
}

},{}],70:[function(require,module,exports){
if (typeof Object.create === 'function') {
  // implementation from standard node.js 'util' module
  module.exports = function inherits(ctor, superCtor) {
    if (superCtor) {
      ctor.super_ = superCtor
      ctor.prototype = Object.create(superCtor.prototype, {
        constructor: {
          value: ctor,
          enumerable: false,
          writable: true,
          configurable: true
        }
      })
    }
  };
} else {
  // old school shim for old browsers
  module.exports = function inherits(ctor, superCtor) {
    if (superCtor) {
      ctor.super_ = superCtor
      var TempCtor = function () {}
      TempCtor.prototype = superCtor.prototype
      ctor.prototype = new TempCtor()
      ctor.prototype.constructor = ctor
    }
  }
}

},{}],71:[function(require,module,exports){
'use strict';

var hasToStringTag = require('has-tostringtag/shams')();
var callBound = require('call-bind/callBound');

var $toString = callBound('Object.prototype.toString');

var isStandardArguments = function isArguments(value) {
	if (hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value) {
		return false;
	}
	return $toString(value) === '[object Arguments]';
};

var isLegacyArguments = function isArguments(value) {
	if (isStandardArguments(value)) {
		return true;
	}
	return value !== null &&
		typeof value === 'object' &&
		typeof value.length === 'number' &&
		value.length >= 0 &&
		$toString(value) !== '[object Array]' &&
		$toString(value.callee) === '[object Function]';
};

var supportsStandardArguments = (function () {
	return isStandardArguments(arguments);
}());

isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests

module.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments;

},{"call-bind/callBound":57,"has-tostringtag/shams":67}],72:[function(require,module,exports){
'use strict';

var fnToStr = Function.prototype.toString;
var reflectApply = typeof Reflect === 'object' && Reflect !== null && Reflect.apply;
var badArrayLike;
var isCallableMarker;
if (typeof reflectApply === 'function' && typeof Object.defineProperty === 'function') {
	try {
		badArrayLike = Object.defineProperty({}, 'length', {
			get: function () {
				throw isCallableMarker;
			}
		});
		isCallableMarker = {};
		// eslint-disable-next-line no-throw-literal
		reflectApply(function () { throw 42; }, null, badArrayLike);
	} catch (_) {
		if (_ !== isCallableMarker) {
			reflectApply = null;
		}
	}
} else {
	reflectApply = null;
}

var constructorRegex = /^\s*class\b/;
var isES6ClassFn = function isES6ClassFunction(value) {
	try {
		var fnStr = fnToStr.call(value);
		return constructorRegex.test(fnStr);
	} catch (e) {
		return false; // not a function
	}
};

var tryFunctionObject = function tryFunctionToStr(value) {
	try {
		if (isES6ClassFn(value)) { return false; }
		fnToStr.call(value);
		return true;
	} catch (e) {
		return false;
	}
};
var toStr = Object.prototype.toString;
var objectClass = '[object Object]';
var fnClass = '[object Function]';
var genClass = '[object GeneratorFunction]';
var ddaClass = '[object HTMLAllCollection]'; // IE 11
var ddaClass2 = '[object HTML document.all class]';
var ddaClass3 = '[object HTMLCollection]'; // IE 9-10
var hasToStringTag = typeof Symbol === 'function' && !!Symbol.toStringTag; // better: use `has-tostringtag`

var isIE68 = !(0 in [,]); // eslint-disable-line no-sparse-arrays, comma-spacing

var isDDA = function isDocumentDotAll() { return false; };
if (typeof document === 'object') {
	// Firefox 3 canonicalizes DDA to undefined when it's not accessed directly
	var all = document.all;
	if (toStr.call(all) === toStr.call(document.all)) {
		isDDA = function isDocumentDotAll(value) {
			/* globals document: false */
			// in IE 6-8, typeof document.all is "object" and it's truthy
			if ((isIE68 || !value) && (typeof value === 'undefined' || typeof value === 'object')) {
				try {
					var str = toStr.call(value);
					return (
						str === ddaClass
						|| str === ddaClass2
						|| str === ddaClass3 // opera 12.16
						|| str === objectClass // IE 6-8
					) && value('') == null; // eslint-disable-line eqeqeq
				} catch (e) { /**/ }
			}
			return false;
		};
	}
}

module.exports = reflectApply
	? function isCallable(value) {
		if (isDDA(value)) { return true; }
		if (!value) { return false; }
		if (typeof value !== 'function' && typeof value !== 'object') { return false; }
		try {
			reflectApply(value, null, badArrayLike);
		} catch (e) {
			if (e !== isCallableMarker) { return false; }
		}
		return !isES6ClassFn(value) && tryFunctionObject(value);
	}
	: function isCallable(value) {
		if (isDDA(value)) { return true; }
		if (!value) { return false; }
		if (typeof value !== 'function' && typeof value !== 'object') { return false; }
		if (hasToStringTag) { return tryFunctionObject(value); }
		if (isES6ClassFn(value)) { return false; }
		var strClass = toStr.call(value);
		if (strClass !== fnClass && strClass !== genClass && !(/^\[object HTML/).test(strClass)) { return false; }
		return tryFunctionObject(value);
	};

},{}],73:[function(require,module,exports){
'use strict';

var toStr = Object.prototype.toString;
var fnToStr = Function.prototype.toString;
var isFnRegex = /^\s*(?:function)?\*/;
var hasToStringTag = require('has-tostringtag/shams')();
var getProto = Object.getPrototypeOf;
var getGeneratorFunc = function () { // eslint-disable-line consistent-return
	if (!hasToStringTag) {
		return false;
	}
	try {
		return Function('return function*() {}')();
	} catch (e) {
	}
};
var GeneratorFunction;

module.exports = function isGeneratorFunction(fn) {
	if (typeof fn !== 'function') {
		return false;
	}
	if (isFnRegex.test(fnToStr.call(fn))) {
		return true;
	}
	if (!hasToStringTag) {
		var str = toStr.call(fn);
		return str === '[object GeneratorFunction]';
	}
	if (!getProto) {
		return false;
	}
	if (typeof GeneratorFunction === 'undefined') {
		var generatorFunc = getGeneratorFunc();
		GeneratorFunction = generatorFunc ? getProto(generatorFunc) : false;
	}
	return getProto(fn) === GeneratorFunction;
};

},{"has-tostringtag/shams":67}],74:[function(require,module,exports){
(function (global){(function (){
'use strict';

var forEach = require('for-each');
var availableTypedArrays = require('available-typed-arrays');
var callBound = require('call-bind/callBound');

var $toString = callBound('Object.prototype.toString');
var hasToStringTag = require('has-tostringtag/shams')();
var gOPD = require('gopd');

var g = typeof globalThis === 'undefined' ? global : globalThis;
var typedArrays = availableTypedArrays();

var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) {
	for (var i = 0; i < array.length; i += 1) {
		if (array[i] === value) {
			return i;
		}
	}
	return -1;
};
var $slice = callBound('String.prototype.slice');
var toStrTags = {};
var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof');
if (hasToStringTag && gOPD && getPrototypeOf) {
	forEach(typedArrays, function (typedArray) {
		var arr = new g[typedArray]();
		if (Symbol.toStringTag in arr) {
			var proto = getPrototypeOf(arr);
			var descriptor = gOPD(proto, Symbol.toStringTag);
			if (!descriptor) {
				var superProto = getPrototypeOf(proto);
				descriptor = gOPD(superProto, Symbol.toStringTag);
			}
			toStrTags[typedArray] = descriptor.get;
		}
	});
}

var tryTypedArrays = function tryAllTypedArrays(value) {
	var anyTrue = false;
	forEach(toStrTags, function (getter, typedArray) {
		if (!anyTrue) {
			try {
				anyTrue = getter.call(value) === typedArray;
			} catch (e) { /**/ }
		}
	});
	return anyTrue;
};

module.exports = function isTypedArray(value) {
	if (!value || typeof value !== 'object') { return false; }
	if (!hasToStringTag || !(Symbol.toStringTag in value)) {
		var tag = $slice($toString(value), 8, -1);
		return $indexOf(typedArrays, tag) > -1;
	}
	if (!gOPD) { return false; }
	return tryTypedArrays(value);
};

}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"available-typed-arrays":52,"call-bind/callBound":57,"for-each":60,"gopd":64,"has-tostringtag/shams":67}],75:[function(require,module,exports){
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/

'use strict';
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;

function toObject(val) {
	if (val === null || val === undefined) {
		throw new TypeError('Object.assign cannot be called with null or undefined');
	}

	return Object(val);
}

function shouldUseNative() {
	try {
		if (!Object.assign) {
			return false;
		}

		// Detect buggy property enumeration order in older V8 versions.

		// https://bugs.chromium.org/p/v8/issues/detail?id=4118
		var test1 = new String('abc');  // eslint-disable-line no-new-wrappers
		test1[5] = 'de';
		if (Object.getOwnPropertyNames(test1)[0] === '5') {
			return false;
		}

		// https://bugs.chromium.org/p/v8/issues/detail?id=3056
		var test2 = {};
		for (var i = 0; i < 10; i++) {
			test2['_' + String.fromCharCode(i)] = i;
		}
		var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
			return test2[n];
		});
		if (order2.join('') !== '0123456789') {
			return false;
		}

		// https://bugs.chromium.org/p/v8/issues/detail?id=3056
		var test3 = {};
		'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
			test3[letter] = letter;
		});
		if (Object.keys(Object.assign({}, test3)).join('') !==
				'abcdefghijklmnopqrst') {
			return false;
		}

		return true;
	} catch (err) {
		// We don't expect any of the above to throw, but better to be safe.
		return false;
	}
}

module.exports = shouldUseNative() ? Object.assign : function (target, source) {
	var from;
	var to = toObject(target);
	var symbols;

	for (var s = 1; s < arguments.length; s++) {
		from = Object(arguments[s]);

		for (var key in from) {
			if (hasOwnProperty.call(from, key)) {
				to[key] = from[key];
			}
		}

		if (getOwnPropertySymbols) {
			symbols = getOwnPropertySymbols(from);
			for (var i = 0; i < symbols.length; i++) {
				if (propIsEnumerable.call(from, symbols[i])) {
					to[symbols[i]] = from[symbols[i]];
				}
			}
		}
	}

	return to;
};

},{}],76:[function(require,module,exports){
'use strict';


var TYPED_OK =  (typeof Uint8Array !== 'undefined') &&
                (typeof Uint16Array !== 'undefined') &&
                (typeof Int32Array !== 'undefined');

function _has(obj, key) {
  return Object.prototype.hasOwnProperty.call(obj, key);
}

exports.assign = function (obj /*from1, from2, from3, ...*/) {
  var sources = Array.prototype.slice.call(arguments, 1);
  while (sources.length) {
    var source = sources.shift();
    if (!source) { continue; }

    if (typeof source !== 'object') {
      throw new TypeError(source + 'must be non-object');
    }

    for (var p in source) {
      if (_has(source, p)) {
        obj[p] = source[p];
      }
    }
  }

  return obj;
};


// reduce buffer size, avoiding mem copy
exports.shrinkBuf = function (buf, size) {
  if (buf.length === size) { return buf; }
  if (buf.subarray) { return buf.subarray(0, size); }
  buf.length = size;
  return buf;
};


var fnTyped = {
  arraySet: function (dest, src, src_offs, len, dest_offs) {
    if (src.subarray && dest.subarray) {
      dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
      return;
    }
    // Fallback to ordinary array
    for (var i = 0; i < len; i++) {
      dest[dest_offs + i] = src[src_offs + i];
    }
  },
  // Join array of chunks to single array.
  flattenChunks: function (chunks) {
    var i, l, len, pos, chunk, result;

    // calculate data length
    len = 0;
    for (i = 0, l = chunks.length; i < l; i++) {
      len += chunks[i].length;
    }

    // join chunks
    result = new Uint8Array(len);
    pos = 0;
    for (i = 0, l = chunks.length; i < l; i++) {
      chunk = chunks[i];
      result.set(chunk, pos);
      pos += chunk.length;
    }

    return result;
  }
};

var fnUntyped = {
  arraySet: function (dest, src, src_offs, len, dest_offs) {
    for (var i = 0; i < len; i++) {
      dest[dest_offs + i] = src[src_offs + i];
    }
  },
  // Join array of chunks to single array.
  flattenChunks: function (chunks) {
    return [].concat.apply([], chunks);
  }
};


// Enable/Disable typed arrays use, for testing
//
exports.setTyped = function (on) {
  if (on) {
    exports.Buf8  = Uint8Array;
    exports.Buf16 = Uint16Array;
    exports.Buf32 = Int32Array;
    exports.assign(exports, fnTyped);
  } else {
    exports.Buf8  = Array;
    exports.Buf16 = Array;
    exports.Buf32 = Array;
    exports.assign(exports, fnUntyped);
  }
};

exports.setTyped(TYPED_OK);

},{}],77:[function(require,module,exports){
'use strict';

// Note: adler32 takes 12% for level 0 and 2% for level 6.
// It isn't worth it to make additional optimizations as in original.
// Small size is preferable.

// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
//   claim that you wrote the original software. If you use this software
//   in a product, an acknowledgment in the product documentation would be
//   appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
//   misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.

function adler32(adler, buf, len, pos) {
  var s1 = (adler & 0xffff) |0,
      s2 = ((adler >>> 16) & 0xffff) |0,
      n = 0;

  while (len !== 0) {
    // Set limit ~ twice less than 5552, to keep
    // s2 in 31-bits, because we force signed ints.
    // in other case %= will fail.
    n = len > 2000 ? 2000 : len;
    len -= n;

    do {
      s1 = (s1 + buf[pos++]) |0;
      s2 = (s2 + s1) |0;
    } while (--n);

    s1 %= 65521;
    s2 %= 65521;
  }

  return (s1 | (s2 << 16)) |0;
}


module.exports = adler32;

},{}],78:[function(require,module,exports){
'use strict';

// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
//   claim that you wrote the original software. If you use this software
//   in a product, an acknowledgment in the product documentation would be
//   appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
//   misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.

module.exports = {

  /* Allowed flush values; see deflate() and inflate() below for details */
  Z_NO_FLUSH:         0,
  Z_PARTIAL_FLUSH:    1,
  Z_SYNC_FLUSH:       2,
  Z_FULL_FLUSH:       3,
  Z_FINISH:           4,
  Z_BLOCK:            5,
  Z_TREES:            6,

  /* Return codes for the compression/decompression functions. Negative values
  * are errors, positive values are used for special but normal events.
  */
  Z_OK:               0,
  Z_STREAM_END:       1,
  Z_NEED_DICT:        2,
  Z_ERRNO:           -1,
  Z_STREAM_ERROR:    -2,
  Z_DATA_ERROR:      -3,
  //Z_MEM_ERROR:     -4,
  Z_BUF_ERROR:       -5,
  //Z_VERSION_ERROR: -6,

  /* compression levels */
  Z_NO_COMPRESSION:         0,
  Z_BEST_SPEED:             1,
  Z_BEST_COMPRESSION:       9,
  Z_DEFAULT_COMPRESSION:   -1,


  Z_FILTERED:               1,
  Z_HUFFMAN_ONLY:           2,
  Z_RLE:                    3,
  Z_FIXED:                  4,
  Z_DEFAULT_STRATEGY:       0,

  /* Possible values of the data_type field (though see inflate()) */
  Z_BINARY:                 0,
  Z_TEXT:                   1,
  //Z_ASCII:                1, // = Z_TEXT (deprecated)
  Z_UNKNOWN:                2,

  /* The deflate compression method */
  Z_DEFLATED:               8
  //Z_NULL:                 null // Use -1 or null inline, depending on var type
};

},{}],79:[function(require,module,exports){
'use strict';

// Note: we can't get significant speed boost here.
// So write code to minimize size - no pregenerated tables
// and array tools dependencies.

// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
//   claim that you wrote the original software. If you use this software
//   in a product, an acknowledgment in the product documentation would be
//   appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
//   misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.

// Use ordinary array, since untyped makes no boost here
function makeTable() {
  var c, table = [];

  for (var n = 0; n < 256; n++) {
    c = n;
    for (var k = 0; k < 8; k++) {
      c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
    }
    table[n] = c;
  }

  return table;
}

// Create table on load. Just 255 signed longs. Not a problem.
var crcTable = makeTable();


function crc32(crc, buf, len, pos) {
  var t = crcTable,
      end = pos + len;

  crc ^= -1;

  for (var i = pos; i < end; i++) {
    crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  }

  return (crc ^ (-1)); // >>> 0;
}


module.exports = crc32;

},{}],80:[function(require,module,exports){
'use strict';

// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
//   claim that you wrote the original software. If you use this software
//   in a product, an acknowledgment in the product documentation would be
//   appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
//   misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.

var utils   = require('../utils/common');
var trees   = require('./trees');
var adler32 = require('./adler32');
var crc32   = require('./crc32');
var msg     = require('./messages');

/* Public constants ==========================================================*/
/* ===========================================================================*/


/* Allowed flush values; see deflate() and inflate() below for details */
var Z_NO_FLUSH      = 0;
var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH    = 2;
var Z_FULL_FLUSH    = 3;
var Z_FINISH        = 4;
var Z_BLOCK         = 5;
//var Z_TREES         = 6;


/* Return codes for the compression/decompression functions. Negative values
 * are errors, positive values are used for special but normal events.
 */
var Z_OK            = 0;
var Z_STREAM_END    = 1;
//var Z_NEED_DICT     = 2;
//var Z_ERRNO         = -1;
var Z_STREAM_ERROR  = -2;
var Z_DATA_ERROR    = -3;
//var Z_MEM_ERROR     = -4;
var Z_BUF_ERROR     = -5;
//var Z_VERSION_ERROR = -6;


/* compression levels */
//var Z_NO_COMPRESSION      = 0;
//var Z_BEST_SPEED          = 1;
//var Z_BEST_COMPRESSION    = 9;
var Z_DEFAULT_COMPRESSION = -1;


var Z_FILTERED            = 1;
var Z_HUFFMAN_ONLY        = 2;
var Z_RLE                 = 3;
var Z_FIXED               = 4;
var Z_DEFAULT_STRATEGY    = 0;

/* Possible values of the data_type field (though see inflate()) */
//var Z_BINARY              = 0;
//var Z_TEXT                = 1;
//var Z_ASCII               = 1; // = Z_TEXT
var Z_UNKNOWN             = 2;


/* The deflate compression method */
var Z_DEFLATED  = 8;

/*============================================================================*/


var MAX_MEM_LEVEL = 9;
/* Maximum value for memLevel in deflateInit2 */
var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_MEM_LEVEL = 8;


var LENGTH_CODES  = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS      = 256;
/* number of literal bytes 0..255 */
var L_CODES       = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES       = 30;
/* number of distance codes */
var BL_CODES      = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE     = 2 * L_CODES + 1;
/* maximum heap size */
var MAX_BITS  = 15;
/* All codes must not exceed MAX_BITS bits */

var MIN_MATCH = 3;
var MAX_MATCH = 258;
var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);

var PRESET_DICT = 0x20;

var INIT_STATE = 42;
var EXTRA_STATE = 69;
var NAME_STATE = 73;
var COMMENT_STATE = 91;
var HCRC_STATE = 103;
var BUSY_STATE = 113;
var FINISH_STATE = 666;

var BS_NEED_MORE      = 1; /* block not completed, need more input or more output */
var BS_BLOCK_DONE     = 2; /* block flush performed */
var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
var BS_FINISH_DONE    = 4; /* finish done, accept no more input or output */

var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.

function err(strm, errorCode) {
  strm.msg = msg[errorCode];
  return errorCode;
}

function rank(f) {
  return ((f) << 1) - ((f) > 4 ? 9 : 0);
}

function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }


/* =========================================================================
 * Flush as much pending output as possible. All deflate() output goes
 * through this function so some applications may wish to modify it
 * to avoid allocating a large strm->output buffer and copying into it.
 * (See also read_buf()).
 */
function flush_pending(strm) {
  var s = strm.state;

  //_tr_flush_bits(s);
  var len = s.pending;
  if (len > strm.avail_out) {
    len = strm.avail_out;
  }
  if (len === 0) { return; }

  utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  strm.next_out += len;
  s.pending_out += len;
  strm.total_out += len;
  strm.avail_out -= len;
  s.pending -= len;
  if (s.pending === 0) {
    s.pending_out = 0;
  }
}


function flush_block_only(s, last) {
  trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  s.block_start = s.strstart;
  flush_pending(s.strm);
}


function put_byte(s, b) {
  s.pending_buf[s.pending++] = b;
}


/* =========================================================================
 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
 * IN assertion: the stream state is correct and there is enough room in
 * pending_buf.
 */
function putShortMSB(s, b) {
//  put_byte(s, (Byte)(b >> 8));
//  put_byte(s, (Byte)(b & 0xff));
  s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  s.pending_buf[s.pending++] = b & 0xff;
}


/* ===========================================================================
 * Read a new buffer from the current input stream, update the adler32
 * and total number of bytes read.  All deflate() input goes through
 * this function so some applications may wish to modify it to avoid
 * allocating a large strm->input buffer and copying from it.
 * (See also flush_pending()).
 */
function read_buf(strm, buf, start, size) {
  var len = strm.avail_in;

  if (len > size) { len = size; }
  if (len === 0) { return 0; }

  strm.avail_in -= len;

  // zmemcpy(buf, strm->next_in, len);
  utils.arraySet(buf, strm.input, strm.next_in, len, start);
  if (strm.state.wrap === 1) {
    strm.adler = adler32(strm.adler, buf, len, start);
  }

  else if (strm.state.wrap === 2) {
    strm.adler = crc32(strm.adler, buf, len, start);
  }

  strm.next_in += len;
  strm.total_in += len;

  return len;
}


/* ===========================================================================
 * Set match_start to the longest match starting at the given string and
 * return its length. Matches shorter or equal to prev_length are discarded,
 * in which case the result is equal to prev_length and match_start is
 * garbage.
 * IN assertions: cur_match is the head of the hash chain for the current
 *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
 * OUT assertion: the match length is not greater than s->lookahead.
 */
function longest_match(s, cur_match) {
  var chain_length = s.max_chain_length;      /* max hash chain length */
  var scan = s.strstart; /* current string */
  var match;                       /* matched string */
  var len;                           /* length of current match */
  var best_len = s.prev_length;              /* best match length so far */
  var nice_match = s.nice_match;             /* stop if match long enough */
  var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
      s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;

  var _win = s.window; // shortcut

  var wmask = s.w_mask;
  var prev  = s.prev;

  /* Stop when cur_match becomes <= limit. To simplify the code,
   * we prevent matches with the string of window index 0.
   */

  var strend = s.strstart + MAX_MATCH;
  var scan_end1  = _win[scan + best_len - 1];
  var scan_end   = _win[scan + best_len];

  /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
   * It is easy to get rid of this optimization if necessary.
   */
  // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");

  /* Do not waste too much time if we already have a good match: */
  if (s.prev_length >= s.good_match) {
    chain_length >>= 2;
  }
  /* Do not look for matches beyond the end of the input. This is necessary
   * to make deflate deterministic.
   */
  if (nice_match > s.lookahead) { nice_match = s.lookahead; }

  // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");

  do {
    // Assert(cur_match < s->strstart, "no future");
    match = cur_match;

    /* Skip to next match if the match length cannot increase
     * or if the match length is less than 2.  Note that the checks below
     * for insufficient lookahead only occur occasionally for performance
     * reasons.  Therefore uninitialized memory will be accessed, and
     * conditional jumps will be made that depend on those values.
     * However the length of the match is limited to the lookahead, so
     * the output of deflate is not affected by the uninitialized values.
     */

    if (_win[match + best_len]     !== scan_end  ||
        _win[match + best_len - 1] !== scan_end1 ||
        _win[match]                !== _win[scan] ||
        _win[++match]              !== _win[scan + 1]) {
      continue;
    }

    /* The check at best_len-1 can be removed because it will be made
     * again later. (This heuristic is not always a win.)
     * It is not necessary to compare scan[2] and match[2] since they
     * are always equal when the other bytes match, given that
     * the hash keys are equal and that HASH_BITS >= 8.
     */
    scan += 2;
    match++;
    // Assert(*scan == *match, "match[2]?");

    /* We check for insufficient lookahead only every 8th comparison;
     * the 256th check will be made at strstart+258.
     */
    do {
      /*jshint noempty:false*/
    } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
             _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
             _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
             _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
             scan < strend);

    // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");

    len = MAX_MATCH - (strend - scan);
    scan = strend - MAX_MATCH;

    if (len > best_len) {
      s.match_start = cur_match;
      best_len = len;
      if (len >= nice_match) {
        break;
      }
      scan_end1  = _win[scan + best_len - 1];
      scan_end   = _win[scan + best_len];
    }
  } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);

  if (best_len <= s.lookahead) {
    return best_len;
  }
  return s.lookahead;
}


/* ===========================================================================
 * Fill the window when the lookahead becomes insufficient.
 * Updates strstart and lookahead.
 *
 * IN assertion: lookahead < MIN_LOOKAHEAD
 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
 *    At least one byte has been read, or avail_in == 0; reads are
 *    performed for at least two bytes (required for the zip translate_eol
 *    option -- not supported here).
 */
function fill_window(s) {
  var _w_size = s.w_size;
  var p, n, m, more, str;

  //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");

  do {
    more = s.window_size - s.lookahead - s.strstart;

    // JS ints have 32 bit, block below not needed
    /* Deal with !@#$% 64K limit: */
    //if (sizeof(int) <= 2) {
    //    if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
    //        more = wsize;
    //
    //  } else if (more == (unsigned)(-1)) {
    //        /* Very unlikely, but possible on 16 bit machine if
    //         * strstart == 0 && lookahead == 1 (input done a byte at time)
    //         */
    //        more--;
    //    }
    //}


    /* If the window is almost full and there is insufficient lookahead,
     * move the upper half to the lower one to make room in the upper half.
     */
    if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {

      utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
      s.match_start -= _w_size;
      s.strstart -= _w_size;
      /* we now have strstart >= MAX_DIST */
      s.block_start -= _w_size;

      /* Slide the hash table (could be avoided with 32 bit values
       at the expense of memory usage). We slide even when level == 0
       to keep the hash table consistent if we switch back to level > 0
       later. (Using level 0 permanently is not an optimal usage of
       zlib, so we don't care about this pathological case.)
       */

      n = s.hash_size;
      p = n;
      do {
        m = s.head[--p];
        s.head[p] = (m >= _w_size ? m - _w_size : 0);
      } while (--n);

      n = _w_size;
      p = n;
      do {
        m = s.prev[--p];
        s.prev[p] = (m >= _w_size ? m - _w_size : 0);
        /* If n is not on any hash chain, prev[n] is garbage but
         * its value will never be used.
         */
      } while (--n);

      more += _w_size;
    }
    if (s.strm.avail_in === 0) {
      break;
    }

    /* If there was no sliding:
     *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
     *    more == window_size - lookahead - strstart
     * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
     * => more >= window_size - 2*WSIZE + 2
     * In the BIG_MEM or MMAP case (not yet supported),
     *   window_size == input_size + MIN_LOOKAHEAD  &&
     *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
     * Otherwise, window_size == 2*WSIZE so more >= 2.
     * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
     */
    //Assert(more >= 2, "more < 2");
    n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
    s.lookahead += n;

    /* Initialize the hash value now that we have some input: */
    if (s.lookahead + s.insert >= MIN_MATCH) {
      str = s.strstart - s.insert;
      s.ins_h = s.window[str];

      /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
      s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
//#if MIN_MATCH != 3
//        Call update_hash() MIN_MATCH-3 more times
//#endif
      while (s.insert) {
        /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
        s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;

        s.prev[str & s.w_mask] = s.head[s.ins_h];
        s.head[s.ins_h] = str;
        str++;
        s.insert--;
        if (s.lookahead + s.insert < MIN_MATCH) {
          break;
        }
      }
    }
    /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
     * but this is not important since only literal bytes will be emitted.
     */

  } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);

  /* If the WIN_INIT bytes after the end of the current data have never been
   * written, then zero those bytes in order to avoid memory check reports of
   * the use of uninitialized (or uninitialised as Julian writes) bytes by
   * the longest match routines.  Update the high water mark for the next
   * time through here.  WIN_INIT is set to MAX_MATCH since the longest match
   * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
   */
//  if (s.high_water < s.window_size) {
//    var curr = s.strstart + s.lookahead;
//    var init = 0;
//
//    if (s.high_water < curr) {
//      /* Previous high water mark below current data -- zero WIN_INIT
//       * bytes or up to end of window, whichever is less.
//       */
//      init = s.window_size - curr;
//      if (init > WIN_INIT)
//        init = WIN_INIT;
//      zmemzero(s->window + curr, (unsigned)init);
//      s->high_water = curr + init;
//    }
//    else if (s->high_water < (ulg)curr + WIN_INIT) {
//      /* High water mark at or above current data, but below current data
//       * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
//       * to end of window, whichever is less.
//       */
//      init = (ulg)curr + WIN_INIT - s->high_water;
//      if (init > s->window_size - s->high_water)
//        init = s->window_size - s->high_water;
//      zmemzero(s->window + s->high_water, (unsigned)init);
//      s->high_water += init;
//    }
//  }
//
//  Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
//    "not enough room for search");
}

/* ===========================================================================
 * Copy without compression as much as possible from the input stream, return
 * the current block state.
 * This function does not insert new strings in the dictionary since
 * uncompressible data is probably not useful. This function is used
 * only for the level=0 compression option.
 * NOTE: this function should be optimized to avoid extra copying from
 * window to pending_buf.
 */
function deflate_stored(s, flush) {
  /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
   * to pending_buf_size, and each stored block has a 5 byte header:
   */
  var max_block_size = 0xffff;

  if (max_block_size > s.pending_buf_size - 5) {
    max_block_size = s.pending_buf_size - 5;
  }

  /* Copy as much as possible from input to output: */
  for (;;) {
    /* Fill the window as much as possible: */
    if (s.lookahead <= 1) {

      //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
      //  s->block_start >= (long)s->w_size, "slide too late");
//      if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
//        s.block_start >= s.w_size)) {
//        throw  new Error("slide too late");
//      }

      fill_window(s);
      if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
        return BS_NEED_MORE;
      }

      if (s.lookahead === 0) {
        break;
      }
      /* flush the current block */
    }
    //Assert(s->block_start >= 0L, "block gone");
//    if (s.block_start < 0) throw new Error("block gone");

    s.strstart += s.lookahead;
    s.lookahead = 0;

    /* Emit a stored block if pending_buf will be full: */
    var max_start = s.block_start + max_block_size;

    if (s.strstart === 0 || s.strstart >= max_start) {
      /* strstart == 0 is possible when wraparound on 16-bit machine */
      s.lookahead = s.strstart - max_start;
      s.strstart = max_start;
      /*** FLUSH_BLOCK(s, 0); ***/
      flush_block_only(s, false);
      if (s.strm.avail_out === 0) {
        return BS_NEED_MORE;
      }
      /***/


    }
    /* Flush if we may have to slide, otherwise block_start may become
     * negative and the data will be gone:
     */
    if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
      /*** FLUSH_BLOCK(s, 0); ***/
      flush_block_only(s, false);
      if (s.strm.avail_out === 0) {
        return BS_NEED_MORE;
      }
      /***/
    }
  }

  s.insert = 0;

  if (flush === Z_FINISH) {
    /*** FLUSH_BLOCK(s, 1); ***/
    flush_block_only(s, true);
    if (s.strm.avail_out === 0) {
      return BS_FINISH_STARTED;
    }
    /***/
    return BS_FINISH_DONE;
  }

  if (s.strstart > s.block_start) {
    /*** FLUSH_BLOCK(s, 0); ***/
    flush_block_only(s, false);
    if (s.strm.avail_out === 0) {
      return BS_NEED_MORE;
    }
    /***/
  }

  return BS_NEED_MORE;
}

/* ===========================================================================
 * Compress as much as possible from the input stream, return the current
 * block state.
 * This function does not perform lazy evaluation of matches and inserts
 * new strings in the dictionary only for unmatched strings or for short
 * matches. It is used only for the fast compression options.
 */
function deflate_fast(s, flush) {
  var hash_head;        /* head of the hash chain */
  var bflush;           /* set if current block must be flushed */

  for (;;) {
    /* Make sure that we always have enough lookahead, except
     * at the end of the input file. We need MAX_MATCH bytes
     * for the next match, plus MIN_MATCH bytes to insert the
     * string following the next match.
     */
    if (s.lookahead < MIN_LOOKAHEAD) {
      fill_window(s);
      if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
        return BS_NEED_MORE;
      }
      if (s.lookahead === 0) {
        break; /* flush the current block */
      }
    }

    /* Insert the string window[strstart .. strstart+2] in the
     * dictionary, and set hash_head to the head of the hash chain:
     */
    hash_head = 0/*NIL*/;
    if (s.lookahead >= MIN_MATCH) {
      /*** INSERT_STRING(s, s.strstart, hash_head); ***/
      s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
      hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
      s.head[s.ins_h] = s.strstart;
      /***/
    }

    /* Find the longest match, discarding those <= prev_length.
     * At this point we have always match_length < MIN_MATCH
     */
    if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
      /* To simplify the code, we prevent matches with the string
       * of window index 0 (in particular we have to avoid a match
       * of the string with itself at the start of the input file).
       */
      s.match_length = longest_match(s, hash_head);
      /* longest_match() sets match_start */
    }
    if (s.match_length >= MIN_MATCH) {
      // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only

      /*** _tr_tally_dist(s, s.strstart - s.match_start,
                     s.match_length - MIN_MATCH, bflush); ***/
      bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);

      s.lookahead -= s.match_length;

      /* Insert new strings in the hash table only if the match length
       * is not too large. This saves time but degrades compression.
       */
      if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
        s.match_length--; /* string at strstart already in table */
        do {
          s.strstart++;
          /*** INSERT_STRING(s, s.strstart, hash_head); ***/
          s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
          hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
          s.head[s.ins_h] = s.strstart;
          /***/
          /* strstart never exceeds WSIZE-MAX_MATCH, so there are
           * always MIN_MATCH bytes ahead.
           */
        } while (--s.match_length !== 0);
        s.strstart++;
      } else
      {
        s.strstart += s.match_length;
        s.match_length = 0;
        s.ins_h = s.window[s.strstart];
        /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
        s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;

//#if MIN_MATCH != 3
//                Call UPDATE_HASH() MIN_MATCH-3 more times
//#endif
        /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
         * matter since it will be recomputed at next deflate call.
         */
      }
    } else {
      /* No match, output a literal byte */
      //Tracevv((stderr,"%c", s.window[s.strstart]));
      /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
      bflush = trees._tr_tally(s, 0, s.window[s.strstart]);

      s.lookahead--;
      s.strstart++;
    }
    if (bflush) {
      /*** FLUSH_BLOCK(s, 0); ***/
      flush_block_only(s, false);
      if (s.strm.avail_out === 0) {
        return BS_NEED_MORE;
      }
      /***/
    }
  }
  s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
  if (flush === Z_FINISH) {
    /*** FLUSH_BLOCK(s, 1); ***/
    flush_block_only(s, true);
    if (s.strm.avail_out === 0) {
      return BS_FINISH_STARTED;
    }
    /***/
    return BS_FINISH_DONE;
  }
  if (s.last_lit) {
    /*** FLUSH_BLOCK(s, 0); ***/
    flush_block_only(s, false);
    if (s.strm.avail_out === 0) {
      return BS_NEED_MORE;
    }
    /***/
  }
  return BS_BLOCK_DONE;
}

/* ===========================================================================
 * Same as above, but achieves better compression. We use a lazy
 * evaluation for matches: a match is finally adopted only if there is
 * no better match at the next window position.
 */
function deflate_slow(s, flush) {
  var hash_head;          /* head of hash chain */
  var bflush;              /* set if current block must be flushed */

  var max_insert;

  /* Process the input block. */
  for (;;) {
    /* Make sure that we always have enough lookahead, except
     * at the end of the input file. We need MAX_MATCH bytes
     * for the next match, plus MIN_MATCH bytes to insert the
     * string following the next match.
     */
    if (s.lookahead < MIN_LOOKAHEAD) {
      fill_window(s);
      if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
        return BS_NEED_MORE;
      }
      if (s.lookahead === 0) { break; } /* flush the current block */
    }

    /* Insert the string window[strstart .. strstart+2] in the
     * dictionary, and set hash_head to the head of the hash chain:
     */
    hash_head = 0/*NIL*/;
    if (s.lookahead >= MIN_MATCH) {
      /*** INSERT_STRING(s, s.strstart, hash_head); ***/
      s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
      hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
      s.head[s.ins_h] = s.strstart;
      /***/
    }

    /* Find the longest match, discarding those <= prev_length.
     */
    s.prev_length = s.match_length;
    s.prev_match = s.match_start;
    s.match_length = MIN_MATCH - 1;

    if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
        s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
      /* To simplify the code, we prevent matches with the string
       * of window index 0 (in particular we have to avoid a match
       * of the string with itself at the start of the input file).
       */
      s.match_length = longest_match(s, hash_head);
      /* longest_match() sets match_start */

      if (s.match_length <= 5 &&
         (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {

        /* If prev_match is also MIN_MATCH, match_start is garbage
         * but we will ignore the current match anyway.
         */
        s.match_length = MIN_MATCH - 1;
      }
    }
    /* If there was a match at the previous step and the current
     * match is not better, output the previous match:
     */
    if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
      max_insert = s.strstart + s.lookahead - MIN_MATCH;
      /* Do not insert strings in hash table beyond this. */

      //check_match(s, s.strstart-1, s.prev_match, s.prev_length);

      /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
                     s.prev_length - MIN_MATCH, bflush);***/
      bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
      /* Insert in hash table all strings up to the end of the match.
       * strstart-1 and strstart are already inserted. If there is not
       * enough lookahead, the last two strings are not inserted in
       * the hash table.
       */
      s.lookahead -= s.prev_length - 1;
      s.prev_length -= 2;
      do {
        if (++s.strstart <= max_insert) {
          /*** INSERT_STRING(s, s.strstart, hash_head); ***/
          s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
          hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
          s.head[s.ins_h] = s.strstart;
          /***/
        }
      } while (--s.prev_length !== 0);
      s.match_available = 0;
      s.match_length = MIN_MATCH - 1;
      s.strstart++;

      if (bflush) {
        /*** FLUSH_BLOCK(s, 0); ***/
        flush_block_only(s, false);
        if (s.strm.avail_out === 0) {
          return BS_NEED_MORE;
        }
        /***/
      }

    } else if (s.match_available) {
      /* If there was no match at the previous position, output a
       * single literal. If there was a match but the current match
       * is longer, truncate the previous match to a single literal.
       */
      //Tracevv((stderr,"%c", s->window[s->strstart-1]));
      /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
      bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);

      if (bflush) {
        /*** FLUSH_BLOCK_ONLY(s, 0) ***/
        flush_block_only(s, false);
        /***/
      }
      s.strstart++;
      s.lookahead--;
      if (s.strm.avail_out === 0) {
        return BS_NEED_MORE;
      }
    } else {
      /* There is no previous match to compare with, wait for
       * the next step to decide.
       */
      s.match_available = 1;
      s.strstart++;
      s.lookahead--;
    }
  }
  //Assert (flush != Z_NO_FLUSH, "no flush?");
  if (s.match_available) {
    //Tracevv((stderr,"%c", s->window[s->strstart-1]));
    /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
    bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);

    s.match_available = 0;
  }
  s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
  if (flush === Z_FINISH) {
    /*** FLUSH_BLOCK(s, 1); ***/
    flush_block_only(s, true);
    if (s.strm.avail_out === 0) {
      return BS_FINISH_STARTED;
    }
    /***/
    return BS_FINISH_DONE;
  }
  if (s.last_lit) {
    /*** FLUSH_BLOCK(s, 0); ***/
    flush_block_only(s, false);
    if (s.strm.avail_out === 0) {
      return BS_NEED_MORE;
    }
    /***/
  }

  return BS_BLOCK_DONE;
}


/* ===========================================================================
 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
 * one.  Do not maintain a hash table.  (It will be regenerated if this run of
 * deflate switches away from Z_RLE.)
 */
function deflate_rle(s, flush) {
  var bflush;            /* set if current block must be flushed */
  var prev;              /* byte at distance one to match */
  var scan, strend;      /* scan goes up to strend for length of run */

  var _win = s.window;

  for (;;) {
    /* Make sure that we always have enough lookahead, except
     * at the end of the input file. We need MAX_MATCH bytes
     * for the longest run, plus one for the unrolled loop.
     */
    if (s.lookahead <= MAX_MATCH) {
      fill_window(s);
      if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
        return BS_NEED_MORE;
      }
      if (s.lookahead === 0) { break; } /* flush the current block */
    }

    /* See how many times the previous byte repeats */
    s.match_length = 0;
    if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
      scan = s.strstart - 1;
      prev = _win[scan];
      if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
        strend = s.strstart + MAX_MATCH;
        do {
          /*jshint noempty:false*/
        } while (prev === _win[++scan] && prev === _win[++scan] &&
                 prev === _win[++scan] && prev === _win[++scan] &&
                 prev === _win[++scan] && prev === _win[++scan] &&
                 prev === _win[++scan] && prev === _win[++scan] &&
                 scan < strend);
        s.match_length = MAX_MATCH - (strend - scan);
        if (s.match_length > s.lookahead) {
          s.match_length = s.lookahead;
        }
      }
      //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
    }

    /* Emit match if have run of MIN_MATCH or longer, else emit literal */
    if (s.match_length >= MIN_MATCH) {
      //check_match(s, s.strstart, s.strstart - 1, s.match_length);

      /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
      bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);

      s.lookahead -= s.match_length;
      s.strstart += s.match_length;
      s.match_length = 0;
    } else {
      /* No match, output a literal byte */
      //Tracevv((stderr,"%c", s->window[s->strstart]));
      /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
      bflush = trees._tr_tally(s, 0, s.window[s.strstart]);

      s.lookahead--;
      s.strstart++;
    }
    if (bflush) {
      /*** FLUSH_BLOCK(s, 0); ***/
      flush_block_only(s, false);
      if (s.strm.avail_out === 0) {
        return BS_NEED_MORE;
      }
      /***/
    }
  }
  s.insert = 0;
  if (flush === Z_FINISH) {
    /*** FLUSH_BLOCK(s, 1); ***/
    flush_block_only(s, true);
    if (s.strm.avail_out === 0) {
      return BS_FINISH_STARTED;
    }
    /***/
    return BS_FINISH_DONE;
  }
  if (s.last_lit) {
    /*** FLUSH_BLOCK(s, 0); ***/
    flush_block_only(s, false);
    if (s.strm.avail_out === 0) {
      return BS_NEED_MORE;
    }
    /***/
  }
  return BS_BLOCK_DONE;
}

/* ===========================================================================
 * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.
 * (It will be regenerated if this run of deflate switches away from Huffman.)
 */
function deflate_huff(s, flush) {
  var bflush;             /* set if current block must be flushed */

  for (;;) {
    /* Make sure that we have a literal to write. */
    if (s.lookahead === 0) {
      fill_window(s);
      if (s.lookahead === 0) {
        if (flush === Z_NO_FLUSH) {
          return BS_NEED_MORE;
        }
        break;      /* flush the current block */
      }
    }

    /* Output a literal byte */
    s.match_length = 0;
    //Tracevv((stderr,"%c", s->window[s->strstart]));
    /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
    bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
    s.lookahead--;
    s.strstart++;
    if (bflush) {
      /*** FLUSH_BLOCK(s, 0); ***/
      flush_block_only(s, false);
      if (s.strm.avail_out === 0) {
        return BS_NEED_MORE;
      }
      /***/
    }
  }
  s.insert = 0;
  if (flush === Z_FINISH) {
    /*** FLUSH_BLOCK(s, 1); ***/
    flush_block_only(s, true);
    if (s.strm.avail_out === 0) {
      return BS_FINISH_STARTED;
    }
    /***/
    return BS_FINISH_DONE;
  }
  if (s.last_lit) {
    /*** FLUSH_BLOCK(s, 0); ***/
    flush_block_only(s, false);
    if (s.strm.avail_out === 0) {
      return BS_NEED_MORE;
    }
    /***/
  }
  return BS_BLOCK_DONE;
}

/* Values for max_lazy_match, good_match and max_chain_length, depending on
 * the desired pack level (0..9). The values given below have been tuned to
 * exclude worst case performance for pathological files. Better values may be
 * found for specific files.
 */
function Config(good_length, max_lazy, nice_length, max_chain, func) {
  this.good_length = good_length;
  this.max_lazy = max_lazy;
  this.nice_length = nice_length;
  this.max_chain = max_chain;
  this.func = func;
}

var configuration_table;

configuration_table = [
  /*      good lazy nice chain */
  new Config(0, 0, 0, 0, deflate_stored),          /* 0 store only */
  new Config(4, 4, 8, 4, deflate_fast),            /* 1 max speed, no lazy matches */
  new Config(4, 5, 16, 8, deflate_fast),           /* 2 */
  new Config(4, 6, 32, 32, deflate_fast),          /* 3 */

  new Config(4, 4, 16, 16, deflate_slow),          /* 4 lazy matches */
  new Config(8, 16, 32, 32, deflate_slow),         /* 5 */
  new Config(8, 16, 128, 128, deflate_slow),       /* 6 */
  new Config(8, 32, 128, 256, deflate_slow),       /* 7 */
  new Config(32, 128, 258, 1024, deflate_slow),    /* 8 */
  new Config(32, 258, 258, 4096, deflate_slow)     /* 9 max compression */
];


/* ===========================================================================
 * Initialize the "longest match" routines for a new zlib stream
 */
function lm_init(s) {
  s.window_size = 2 * s.w_size;

  /*** CLEAR_HASH(s); ***/
  zero(s.head); // Fill with NIL (= 0);

  /* Set the default configuration parameters:
   */
  s.max_lazy_match = configuration_table[s.level].max_lazy;
  s.good_match = configuration_table[s.level].good_length;
  s.nice_match = configuration_table[s.level].nice_length;
  s.max_chain_length = configuration_table[s.level].max_chain;

  s.strstart = 0;
  s.block_start = 0;
  s.lookahead = 0;
  s.insert = 0;
  s.match_length = s.prev_length = MIN_MATCH - 1;
  s.match_available = 0;
  s.ins_h = 0;
}


function DeflateState() {
  this.strm = null;            /* pointer back to this zlib stream */
  this.status = 0;            /* as the name implies */
  this.pending_buf = null;      /* output still pending */
  this.pending_buf_size = 0;  /* size of pending_buf */
  this.pending_out = 0;       /* next pending byte to output to the stream */
  this.pending = 0;           /* nb of bytes in the pending buffer */
  this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip */
  this.gzhead = null;         /* gzip header information to write */
  this.gzindex = 0;           /* where in extra, name, or comment */
  this.method = Z_DEFLATED; /* can only be DEFLATED */
  this.last_flush = -1;   /* value of flush param for previous deflate call */

  this.w_size = 0;  /* LZ77 window size (32K by default) */
  this.w_bits = 0;  /* log2(w_size)  (8..16) */
  this.w_mask = 0;  /* w_size - 1 */

  this.window = null;
  /* Sliding window. Input bytes are read into the second half of the window,
   * and move to the first half later to keep a dictionary of at least wSize
   * bytes. With this organization, matches are limited to a distance of
   * wSize-MAX_MATCH bytes, but this ensures that IO is always
   * performed with a length multiple of the block size.
   */

  this.window_size = 0;
  /* Actual size of window: 2*wSize, except when the user input buffer
   * is directly used as sliding window.
   */

  this.prev = null;
  /* Link to older string with same hash index. To limit the size of this
   * array to 64K, this link is maintained only for the last 32K strings.
   * An index in this array is thus a window index modulo 32K.
   */

  this.head = null;   /* Heads of the hash chains or NIL. */

  this.ins_h = 0;       /* hash index of string to be inserted */
  this.hash_size = 0;   /* number of elements in hash table */
  this.hash_bits = 0;   /* log2(hash_size) */
  this.hash_mask = 0;   /* hash_size-1 */

  this.hash_shift = 0;
  /* Number of bits by which ins_h must be shifted at each input
   * step. It must be such that after MIN_MATCH steps, the oldest
   * byte no longer takes part in the hash key, that is:
   *   hash_shift * MIN_MATCH >= hash_bits
   */

  this.block_start = 0;
  /* Window position at the beginning of the current output block. Gets
   * negative when the window is moved backwards.
   */

  this.match_length = 0;      /* length of best match */
  this.prev_match = 0;        /* previous match */
  this.match_available = 0;   /* set if previous match exists */
  this.strstart = 0;          /* start of string to insert */
  this.match_start = 0;       /* start of matching string */
  this.lookahead = 0;         /* number of valid bytes ahead in window */

  this.prev_length = 0;
  /* Length of the best match at previous step. Matches not greater than this
   * are discarded. This is used in the lazy match evaluation.
   */

  this.max_chain_length = 0;
  /* To speed up deflation, hash chains are never searched beyond this
   * length.  A higher limit improves compression ratio but degrades the
   * speed.
   */

  this.max_lazy_match = 0;
  /* Attempt to find a better match only when the current match is strictly
   * smaller than this value. This mechanism is used only for compression
   * levels >= 4.
   */
  // That's alias to max_lazy_match, don't use directly
  //this.max_insert_length = 0;
  /* Insert new strings in the hash table only if the match length is not
   * greater than this length. This saves time but degrades compression.
   * max_insert_length is used only for compression levels <= 3.
   */

  this.level = 0;     /* compression level (1..9) */
  this.strategy = 0;  /* favor or force Huffman coding*/

  this.good_match = 0;
  /* Use a faster search when the previous match is longer than this */

  this.nice_match = 0; /* Stop searching when current match exceeds this */

              /* used by trees.c: */

  /* Didn't use ct_data typedef below to suppress compiler warning */

  // struct ct_data_s dyn_ltree[HEAP_SIZE];   /* literal and length tree */
  // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  // struct ct_data_s bl_tree[2*BL_CODES+1];  /* Huffman tree for bit lengths */

  // Use flat array of DOUBLE size, with interleaved fata,
  // because JS does not support effective
  this.dyn_ltree  = new utils.Buf16(HEAP_SIZE * 2);
  this.dyn_dtree  = new utils.Buf16((2 * D_CODES + 1) * 2);
  this.bl_tree    = new utils.Buf16((2 * BL_CODES + 1) * 2);
  zero(this.dyn_ltree);
  zero(this.dyn_dtree);
  zero(this.bl_tree);

  this.l_desc   = null;         /* desc. for literal tree */
  this.d_desc   = null;         /* desc. for distance tree */
  this.bl_desc  = null;         /* desc. for bit length tree */

  //ush bl_count[MAX_BITS+1];
  this.bl_count = new utils.Buf16(MAX_BITS + 1);
  /* number of codes at each bit length for an optimal tree */

  //int heap[2*L_CODES+1];      /* heap used to build the Huffman trees */
  this.heap = new utils.Buf16(2 * L_CODES + 1);  /* heap used to build the Huffman trees */
  zero(this.heap);

  this.heap_len = 0;               /* number of elements in the heap */
  this.heap_max = 0;               /* element of largest frequency */
  /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
   * The same heap array is used to build all trees.
   */

  this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
  zero(this.depth);
  /* Depth of each subtree used as tie breaker for trees of equal frequency
   */

  this.l_buf = 0;          /* buffer index for literals or lengths */

  this.lit_bufsize = 0;
  /* Size of match buffer for literals/lengths.  There are 4 reasons for
   * limiting lit_bufsize to 64K:
   *   - frequencies can be kept in 16 bit counters
   *   - if compression is not successful for the first block, all input
   *     data is still in the window so we can still emit a stored block even
   *     when input comes from standard input.  (This can also be done for
   *     all blocks if lit_bufsize is not greater than 32K.)
   *   - if compression is not successful for a file smaller than 64K, we can
   *     even emit a stored file instead of a stored block (saving 5 bytes).
   *     This is applicable only for zip (not gzip or zlib).
   *   - creating new Huffman trees less frequently may not provide fast
   *     adaptation to changes in the input data statistics. (Take for
   *     example a binary file with poorly compressible code followed by
   *     a highly compressible string table.) Smaller buffer sizes give
   *     fast adaptation but have of course the overhead of transmitting
   *     trees more frequently.
   *   - I can't count above 4
   */

  this.last_lit = 0;      /* running index in l_buf */

  this.d_buf = 0;
  /* Buffer index for distances. To simplify the code, d_buf and l_buf have
   * the same number of elements. To use different lengths, an extra flag
   * array would be necessary.
   */

  this.opt_len = 0;       /* bit length of current block with optimal trees */
  this.static_len = 0;    /* bit length of current block with static trees */
  this.matches = 0;       /* number of string matches in current block */
  this.insert = 0;        /* bytes at end of window left to insert */


  this.bi_buf = 0;
  /* Output buffer. bits are inserted starting at the bottom (least
   * significant bits).
   */
  this.bi_valid = 0;
  /* Number of valid bits in bi_buf.  All bits above the last valid bit
   * are always zero.
   */

  // Used for window memory init. We safely ignore it for JS. That makes
  // sense only for pointers and memory check tools.
  //this.high_water = 0;
  /* High water mark offset in window for initialized bytes -- bytes above
   * this are set to zero in order to avoid memory check warnings when
   * longest match routines access bytes past the input.  This is then
   * updated to the new high water mark.
   */
}


function deflateResetKeep(strm) {
  var s;

  if (!strm || !strm.state) {
    return err(strm, Z_STREAM_ERROR);
  }

  strm.total_in = strm.total_out = 0;
  strm.data_type = Z_UNKNOWN;

  s = strm.state;
  s.pending = 0;
  s.pending_out = 0;

  if (s.wrap < 0) {
    s.wrap = -s.wrap;
    /* was made negative by deflate(..., Z_FINISH); */
  }
  s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  strm.adler = (s.wrap === 2) ?
    0  // crc32(0, Z_NULL, 0)
  :
    1; // adler32(0, Z_NULL, 0)
  s.last_flush = Z_NO_FLUSH;
  trees._tr_init(s);
  return Z_OK;
}


function deflateReset(strm) {
  var ret = deflateResetKeep(strm);
  if (ret === Z_OK) {
    lm_init(strm.state);
  }
  return ret;
}


function deflateSetHeader(strm, head) {
  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  strm.state.gzhead = head;
  return Z_OK;
}


function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  if (!strm) { // === Z_NULL
    return Z_STREAM_ERROR;
  }
  var wrap = 1;

  if (level === Z_DEFAULT_COMPRESSION) {
    level = 6;
  }

  if (windowBits < 0) { /* suppress zlib wrapper */
    wrap = 0;
    windowBits = -windowBits;
  }

  else if (windowBits > 15) {
    wrap = 2;           /* write gzip wrapper instead */
    windowBits -= 16;
  }


  if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
    windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
    strategy < 0 || strategy > Z_FIXED) {
    return err(strm, Z_STREAM_ERROR);
  }


  if (windowBits === 8) {
    windowBits = 9;
  }
  /* until 256-byte window bug fixed */

  var s = new DeflateState();

  strm.state = s;
  s.strm = strm;

  s.wrap = wrap;
  s.gzhead = null;
  s.w_bits = windowBits;
  s.w_size = 1 << s.w_bits;
  s.w_mask = s.w_size - 1;

  s.hash_bits = memLevel + 7;
  s.hash_size = 1 << s.hash_bits;
  s.hash_mask = s.hash_size - 1;
  s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);

  s.window = new utils.Buf8(s.w_size * 2);
  s.head = new utils.Buf16(s.hash_size);
  s.prev = new utils.Buf16(s.w_size);

  // Don't need mem init magic for JS.
  //s.high_water = 0;  /* nothing written to s->window yet */

  s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */

  s.pending_buf_size = s.lit_bufsize * 4;

  //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  //s->pending_buf = (uchf *) overlay;
  s.pending_buf = new utils.Buf8(s.pending_buf_size);

  // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
  //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  s.d_buf = 1 * s.lit_bufsize;

  //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  s.l_buf = (1 + 2) * s.lit_bufsize;

  s.level = level;
  s.strategy = strategy;
  s.method = method;

  return deflateReset(strm);
}

function deflateInit(strm, level) {
  return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
}


function deflate(strm, flush) {
  var old_flush, s;
  var beg, val; // for gzip header write only

  if (!strm || !strm.state ||
    flush > Z_BLOCK || flush < 0) {
    return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  }

  s = strm.state;

  if (!strm.output ||
      (!strm.input && strm.avail_in !== 0) ||
      (s.status === FINISH_STATE && flush !== Z_FINISH)) {
    return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  }

  s.strm = strm; /* just in case */
  old_flush = s.last_flush;
  s.last_flush = flush;

  /* Write the header */
  if (s.status === INIT_STATE) {

    if (s.wrap === 2) { // GZIP header
      strm.adler = 0;  //crc32(0L, Z_NULL, 0);
      put_byte(s, 31);
      put_byte(s, 139);
      put_byte(s, 8);
      if (!s.gzhead) { // s->gzhead == Z_NULL
        put_byte(s, 0);
        put_byte(s, 0);
        put_byte(s, 0);
        put_byte(s, 0);
        put_byte(s, 0);
        put_byte(s, s.level === 9 ? 2 :
                    (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
                     4 : 0));
        put_byte(s, OS_CODE);
        s.status = BUSY_STATE;
      }
      else {
        put_byte(s, (s.gzhead.text ? 1 : 0) +
                    (s.gzhead.hcrc ? 2 : 0) +
                    (!s.gzhead.extra ? 0 : 4) +
                    (!s.gzhead.name ? 0 : 8) +
                    (!s.gzhead.comment ? 0 : 16)
        );
        put_byte(s, s.gzhead.time & 0xff);
        put_byte(s, (s.gzhead.time >> 8) & 0xff);
        put_byte(s, (s.gzhead.time >> 16) & 0xff);
        put_byte(s, (s.gzhead.time >> 24) & 0xff);
        put_byte(s, s.level === 9 ? 2 :
                    (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
                     4 : 0));
        put_byte(s, s.gzhead.os & 0xff);
        if (s.gzhead.extra && s.gzhead.extra.length) {
          put_byte(s, s.gzhead.extra.length & 0xff);
          put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
        }
        if (s.gzhead.hcrc) {
          strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
        }
        s.gzindex = 0;
        s.status = EXTRA_STATE;
      }
    }
    else // DEFLATE header
    {
      var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
      var level_flags = -1;

      if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
        level_flags = 0;
      } else if (s.level < 6) {
        level_flags = 1;
      } else if (s.level === 6) {
        level_flags = 2;
      } else {
        level_flags = 3;
      }
      header |= (level_flags << 6);
      if (s.strstart !== 0) { header |= PRESET_DICT; }
      header += 31 - (header % 31);

      s.status = BUSY_STATE;
      putShortMSB(s, header);

      /* Save the adler32 of the preset dictionary: */
      if (s.strstart !== 0) {
        putShortMSB(s, strm.adler >>> 16);
        putShortMSB(s, strm.adler & 0xffff);
      }
      strm.adler = 1; // adler32(0L, Z_NULL, 0);
    }
  }

//#ifdef GZIP
  if (s.status === EXTRA_STATE) {
    if (s.gzhead.extra/* != Z_NULL*/) {
      beg = s.pending;  /* start of bytes to update crc */

      while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
        if (s.pending === s.pending_buf_size) {
          if (s.gzhead.hcrc && s.pending > beg) {
            strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
          }
          flush_pending(strm);
          beg = s.pending;
          if (s.pending === s.pending_buf_size) {
            break;
          }
        }
        put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
        s.gzindex++;
      }
      if (s.gzhead.hcrc && s.pending > beg) {
        strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
      }
      if (s.gzindex === s.gzhead.extra.length) {
        s.gzindex = 0;
        s.status = NAME_STATE;
      }
    }
    else {
      s.status = NAME_STATE;
    }
  }
  if (s.status === NAME_STATE) {
    if (s.gzhead.name/* != Z_NULL*/) {
      beg = s.pending;  /* start of bytes to update crc */
      //int val;

      do {
        if (s.pending === s.pending_buf_size) {
          if (s.gzhead.hcrc && s.pending > beg) {
            strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
          }
          flush_pending(strm);
          beg = s.pending;
          if (s.pending === s.pending_buf_size) {
            val = 1;
            break;
          }
        }
        // JS specific: little magic to add zero terminator to end of string
        if (s.gzindex < s.gzhead.name.length) {
          val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
        } else {
          val = 0;
        }
        put_byte(s, val);
      } while (val !== 0);

      if (s.gzhead.hcrc && s.pending > beg) {
        strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
      }
      if (val === 0) {
        s.gzindex = 0;
        s.status = COMMENT_STATE;
      }
    }
    else {
      s.status = COMMENT_STATE;
    }
  }
  if (s.status === COMMENT_STATE) {
    if (s.gzhead.comment/* != Z_NULL*/) {
      beg = s.pending;  /* start of bytes to update crc */
      //int val;

      do {
        if (s.pending === s.pending_buf_size) {
          if (s.gzhead.hcrc && s.pending > beg) {
            strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
          }
          flush_pending(strm);
          beg = s.pending;
          if (s.pending === s.pending_buf_size) {
            val = 1;
            break;
          }
        }
        // JS specific: little magic to add zero terminator to end of string
        if (s.gzindex < s.gzhead.comment.length) {
          val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
        } else {
          val = 0;
        }
        put_byte(s, val);
      } while (val !== 0);

      if (s.gzhead.hcrc && s.pending > beg) {
        strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
      }
      if (val === 0) {
        s.status = HCRC_STATE;
      }
    }
    else {
      s.status = HCRC_STATE;
    }
  }
  if (s.status === HCRC_STATE) {
    if (s.gzhead.hcrc) {
      if (s.pending + 2 > s.pending_buf_size) {
        flush_pending(strm);
      }
      if (s.pending + 2 <= s.pending_buf_size) {
        put_byte(s, strm.adler & 0xff);
        put_byte(s, (strm.adler >> 8) & 0xff);
        strm.adler = 0; //crc32(0L, Z_NULL, 0);
        s.status = BUSY_STATE;
      }
    }
    else {
      s.status = BUSY_STATE;
    }
  }
//#endif

  /* Flush as much pending output as possible */
  if (s.pending !== 0) {
    flush_pending(strm);
    if (strm.avail_out === 0) {
      /* Since avail_out is 0, deflate will be called again with
       * more output space, but possibly with both pending and
       * avail_in equal to zero. There won't be anything to do,
       * but this is not an error situation so make sure we
       * return OK instead of BUF_ERROR at next call of deflate:
       */
      s.last_flush = -1;
      return Z_OK;
    }

    /* Make sure there is something to do and avoid duplicate consecutive
     * flushes. For repeated and useless calls with Z_FINISH, we keep
     * returning Z_STREAM_END instead of Z_BUF_ERROR.
     */
  } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
    flush !== Z_FINISH) {
    return err(strm, Z_BUF_ERROR);
  }

  /* User must not provide more input after the first FINISH: */
  if (s.status === FINISH_STATE && strm.avail_in !== 0) {
    return err(strm, Z_BUF_ERROR);
  }

  /* Start a new block or continue the current one.
   */
  if (strm.avail_in !== 0 || s.lookahead !== 0 ||
    (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
    var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
      (s.strategy === Z_RLE ? deflate_rle(s, flush) :
        configuration_table[s.level].func(s, flush));

    if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
      s.status = FINISH_STATE;
    }
    if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
      if (strm.avail_out === 0) {
        s.last_flush = -1;
        /* avoid BUF_ERROR next call, see above */
      }
      return Z_OK;
      /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
       * of deflate should use the same flush parameter to make sure
       * that the flush is complete. So we don't have to output an
       * empty block here, this will be done at next call. This also
       * ensures that for a very small output buffer, we emit at most
       * one empty block.
       */
    }
    if (bstate === BS_BLOCK_DONE) {
      if (flush === Z_PARTIAL_FLUSH) {
        trees._tr_align(s);
      }
      else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */

        trees._tr_stored_block(s, 0, 0, false);
        /* For a full flush, this empty block will be recognized
         * as a special marker by inflate_sync().
         */
        if (flush === Z_FULL_FLUSH) {
          /*** CLEAR_HASH(s); ***/             /* forget history */
          zero(s.head); // Fill with NIL (= 0);

          if (s.lookahead === 0) {
            s.strstart = 0;
            s.block_start = 0;
            s.insert = 0;
          }
        }
      }
      flush_pending(strm);
      if (strm.avail_out === 0) {
        s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
        return Z_OK;
      }
    }
  }
  //Assert(strm->avail_out > 0, "bug2");
  //if (strm.avail_out <= 0) { throw new Error("bug2");}

  if (flush !== Z_FINISH) { return Z_OK; }
  if (s.wrap <= 0) { return Z_STREAM_END; }

  /* Write the trailer */
  if (s.wrap === 2) {
    put_byte(s, strm.adler & 0xff);
    put_byte(s, (strm.adler >> 8) & 0xff);
    put_byte(s, (strm.adler >> 16) & 0xff);
    put_byte(s, (strm.adler >> 24) & 0xff);
    put_byte(s, strm.total_in & 0xff);
    put_byte(s, (strm.total_in >> 8) & 0xff);
    put_byte(s, (strm.total_in >> 16) & 0xff);
    put_byte(s, (strm.total_in >> 24) & 0xff);
  }
  else
  {
    putShortMSB(s, strm.adler >>> 16);
    putShortMSB(s, strm.adler & 0xffff);
  }

  flush_pending(strm);
  /* If avail_out is zero, the application will call deflate again
   * to flush the rest.
   */
  if (s.wrap > 0) { s.wrap = -s.wrap; }
  /* write the trailer only once! */
  return s.pending !== 0 ? Z_OK : Z_STREAM_END;
}

function deflateEnd(strm) {
  var status;

  if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
    return Z_STREAM_ERROR;
  }

  status = strm.state.status;
  if (status !== INIT_STATE &&
    status !== EXTRA_STATE &&
    status !== NAME_STATE &&
    status !== COMMENT_STATE &&
    status !== HCRC_STATE &&
    status !== BUSY_STATE &&
    status !== FINISH_STATE
  ) {
    return err(strm, Z_STREAM_ERROR);
  }

  strm.state = null;

  return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
}


/* =========================================================================
 * Initializes the compression dictionary from the given byte
 * sequence without producing any compressed output.
 */
function deflateSetDictionary(strm, dictionary) {
  var dictLength = dictionary.length;

  var s;
  var str, n;
  var wrap;
  var avail;
  var next;
  var input;
  var tmpDict;

  if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
    return Z_STREAM_ERROR;
  }

  s = strm.state;
  wrap = s.wrap;

  if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
    return Z_STREAM_ERROR;
  }

  /* when using zlib wrappers, compute Adler-32 for provided dictionary */
  if (wrap === 1) {
    /* adler32(strm->adler, dictionary, dictLength); */
    strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
  }

  s.wrap = 0;   /* avoid computing Adler-32 in read_buf */

  /* if dictionary would fill window, just replace the history */
  if (dictLength >= s.w_size) {
    if (wrap === 0) {            /* already empty otherwise */
      /*** CLEAR_HASH(s); ***/
      zero(s.head); // Fill with NIL (= 0);
      s.strstart = 0;
      s.block_start = 0;
      s.insert = 0;
    }
    /* use the tail */
    // dictionary = dictionary.slice(dictLength - s.w_size);
    tmpDict = new utils.Buf8(s.w_size);
    utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
    dictionary = tmpDict;
    dictLength = s.w_size;
  }
  /* insert dictionary into window and hash */
  avail = strm.avail_in;
  next = strm.next_in;
  input = strm.input;
  strm.avail_in = dictLength;
  strm.next_in = 0;
  strm.input = dictionary;
  fill_window(s);
  while (s.lookahead >= MIN_MATCH) {
    str = s.strstart;
    n = s.lookahead - (MIN_MATCH - 1);
    do {
      /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
      s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;

      s.prev[str & s.w_mask] = s.head[s.ins_h];

      s.head[s.ins_h] = str;
      str++;
    } while (--n);
    s.strstart = str;
    s.lookahead = MIN_MATCH - 1;
    fill_window(s);
  }
  s.strstart += s.lookahead;
  s.block_start = s.strstart;
  s.insert = s.lookahead;
  s.lookahead = 0;
  s.match_length = s.prev_length = MIN_MATCH - 1;
  s.match_available = 0;
  strm.next_in = next;
  strm.input = input;
  strm.avail_in = avail;
  s.wrap = wrap;
  return Z_OK;
}


exports.deflateInit = deflateInit;
exports.deflateInit2 = deflateInit2;
exports.deflateReset = deflateReset;
exports.deflateResetKeep = deflateResetKeep;
exports.deflateSetHeader = deflateSetHeader;
exports.deflate = deflate;
exports.deflateEnd = deflateEnd;
exports.deflateSetDictionary = deflateSetDictionary;
exports.deflateInfo = 'pako deflate (from Nodeca project)';

/* Not implemented
exports.deflateBound = deflateBound;
exports.deflateCopy = deflateCopy;
exports.deflateParams = deflateParams;
exports.deflatePending = deflatePending;
exports.deflatePrime = deflatePrime;
exports.deflateTune = deflateTune;
*/

},{"../utils/common":76,"./adler32":77,"./crc32":79,"./messages":84,"./trees":85}],81:[function(require,module,exports){
'use strict';

// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
//   claim that you wrote the original software. If you use this software
//   in a product, an acknowledgment in the product documentation would be
//   appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
//   misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.

// See state defs from inflate.js
var BAD = 30;       /* got a data error -- remain here until reset */
var TYPE = 12;      /* i: waiting for type bits, including last-flag bit */

/*
   Decode literal, length, and distance codes and write out the resulting
   literal and match bytes until either not enough input or output is
   available, an end-of-block is encountered, or a data error is encountered.
   When large enough input and output buffers are supplied to inflate(), for
   example, a 16K input buffer and a 64K output buffer, more than 95% of the
   inflate execution time is spent in this routine.

   Entry assumptions:

        state.mode === LEN
        strm.avail_in >= 6
        strm.avail_out >= 258
        start >= strm.avail_out
        state.bits < 8

   On return, state.mode is one of:

        LEN -- ran out of enough output space or enough available input
        TYPE -- reached end of block code, inflate() to interpret next block
        BAD -- error in block data

   Notes:

    - The maximum input bits used by a length/distance pair is 15 bits for the
      length code, 5 bits for the length extra, 15 bits for the distance code,
      and 13 bits for the distance extra.  This totals 48 bits, or six bytes.
      Therefore if strm.avail_in >= 6, then there is enough input to avoid
      checking for available input while decoding.

    - The maximum bytes that a single length/distance pair can output is 258
      bytes, which is the maximum length that can be coded.  inflate_fast()
      requires strm.avail_out >= 258 for each loop to avoid checking for
      output space.
 */
module.exports = function inflate_fast(strm, start) {
  var state;
  var _in;                    /* local strm.input */
  var last;                   /* have enough input while in < last */
  var _out;                   /* local strm.output */
  var beg;                    /* inflate()'s initial strm.output */
  var end;                    /* while out < end, enough space available */
//#ifdef INFLATE_STRICT
  var dmax;                   /* maximum distance from zlib header */
//#endif
  var wsize;                  /* window size or zero if not using window */
  var whave;                  /* valid bytes in the window */
  var wnext;                  /* window write index */
  // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  var s_window;               /* allocated sliding window, if wsize != 0 */
  var hold;                   /* local strm.hold */
  var bits;                   /* local strm.bits */
  var lcode;                  /* local strm.lencode */
  var dcode;                  /* local strm.distcode */
  var lmask;                  /* mask for first level of length codes */
  var dmask;                  /* mask for first level of distance codes */
  var here;                   /* retrieved table entry */
  var op;                     /* code bits, operation, extra bits, or */
                              /*  window position, window bytes to copy */
  var len;                    /* match length, unused bytes */
  var dist;                   /* match distance */
  var from;                   /* where to copy match from */
  var from_source;


  var input, output; // JS specific, because we have no pointers

  /* copy state to local variables */
  state = strm.state;
  //here = state.here;
  _in = strm.next_in;
  input = strm.input;
  last = _in + (strm.avail_in - 5);
  _out = strm.next_out;
  output = strm.output;
  beg = _out - (start - strm.avail_out);
  end = _out + (strm.avail_out - 257);
//#ifdef INFLATE_STRICT
  dmax = state.dmax;
//#endif
  wsize = state.wsize;
  whave = state.whave;
  wnext = state.wnext;
  s_window = state.window;
  hold = state.hold;
  bits = state.bits;
  lcode = state.lencode;
  dcode = state.distcode;
  lmask = (1 << state.lenbits) - 1;
  dmask = (1 << state.distbits) - 1;


  /* decode literals and length/distances until end-of-block or not enough
     input data or output space */

  top:
  do {
    if (bits < 15) {
      hold += input[_in++] << bits;
      bits += 8;
      hold += input[_in++] << bits;
      bits += 8;
    }

    here = lcode[hold & lmask];

    dolen:
    for (;;) { // Goto emulation
      op = here >>> 24/*here.bits*/;
      hold >>>= op;
      bits -= op;
      op = (here >>> 16) & 0xff/*here.op*/;
      if (op === 0) {                          /* literal */
        //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
        //        "inflate:         literal '%c'\n" :
        //        "inflate:         literal 0x%02x\n", here.val));
        output[_out++] = here & 0xffff/*here.val*/;
      }
      else if (op & 16) {                     /* length base */
        len = here & 0xffff/*here.val*/;
        op &= 15;                           /* number of extra bits */
        if (op) {
          if (bits < op) {
            hold += input[_in++] << bits;
            bits += 8;
          }
          len += hold & ((1 << op) - 1);
          hold >>>= op;
          bits -= op;
        }
        //Tracevv((stderr, "inflate:         length %u\n", len));
        if (bits < 15) {
          hold += input[_in++] << bits;
          bits += 8;
          hold += input[_in++] << bits;
          bits += 8;
        }
        here = dcode[hold & dmask];

        dodist:
        for (;;) { // goto emulation
          op = here >>> 24/*here.bits*/;
          hold >>>= op;
          bits -= op;
          op = (here >>> 16) & 0xff/*here.op*/;

          if (op & 16) {                      /* distance base */
            dist = here & 0xffff/*here.val*/;
            op &= 15;                       /* number of extra bits */
            if (bits < op) {
              hold += input[_in++] << bits;
              bits += 8;
              if (bits < op) {
                hold += input[_in++] << bits;
                bits += 8;
              }
            }
            dist += hold & ((1 << op) - 1);
//#ifdef INFLATE_STRICT
            if (dist > dmax) {
              strm.msg = 'invalid distance too far back';
              state.mode = BAD;
              break top;
            }
//#endif
            hold >>>= op;
            bits -= op;
            //Tracevv((stderr, "inflate:         distance %u\n", dist));
            op = _out - beg;                /* max distance in output */
            if (dist > op) {                /* see if copy from window */
              op = dist - op;               /* distance back in window */
              if (op > whave) {
                if (state.sane) {
                  strm.msg = 'invalid distance too far back';
                  state.mode = BAD;
                  break top;
                }

// (!) This block is disabled in zlib defaults,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
//                if (len <= op - whave) {
//                  do {
//                    output[_out++] = 0;
//                  } while (--len);
//                  continue top;
//                }
//                len -= op - whave;
//                do {
//                  output[_out++] = 0;
//                } while (--op > whave);
//                if (op === 0) {
//                  from = _out - dist;
//                  do {
//                    output[_out++] = output[from++];
//                  } while (--len);
//                  continue top;
//                }
//#endif
              }
              from = 0; // window index
              from_source = s_window;
              if (wnext === 0) {           /* very common case */
                from += wsize - op;
                if (op < len) {         /* some from window */
                  len -= op;
                  do {
                    output[_out++] = s_window[from++];
                  } while (--op);
                  from = _out - dist;  /* rest from output */
                  from_source = output;
                }
              }
              else if (wnext < op) {      /* wrap around window */
                from += wsize + wnext - op;
                op -= wnext;
                if (op < len) {         /* some from end of window */
                  len -= op;
                  do {
                    output[_out++] = s_window[from++];
                  } while (--op);
                  from = 0;
                  if (wnext < len) {  /* some from start of window */
                    op = wnext;
                    len -= op;
                    do {
                      output[_out++] = s_window[from++];
                    } while (--op);
                    from = _out - dist;      /* rest from output */
                    from_source = output;
                  }
                }
              }
              else {                      /* contiguous in window */
                from += wnext - op;
                if (op < len) {         /* some from window */
                  len -= op;
                  do {
                    output[_out++] = s_window[from++];
                  } while (--op);
                  from = _out - dist;  /* rest from output */
                  from_source = output;
                }
              }
              while (len > 2) {
                output[_out++] = from_source[from++];
                output[_out++] = from_source[from++];
                output[_out++] = from_source[from++];
                len -= 3;
              }
              if (len) {
                output[_out++] = from_source[from++];
                if (len > 1) {
                  output[_out++] = from_source[from++];
                }
              }
            }
            else {
              from = _out - dist;          /* copy direct from output */
              do {                        /* minimum length is three */
                output[_out++] = output[from++];
                output[_out++] = output[from++];
                output[_out++] = output[from++];
                len -= 3;
              } while (len > 2);
              if (len) {
                output[_out++] = output[from++];
                if (len > 1) {
                  output[_out++] = output[from++];
                }
              }
            }
          }
          else if ((op & 64) === 0) {          /* 2nd level distance code */
            here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
            continue dodist;
          }
          else {
            strm.msg = 'invalid distance code';
            state.mode = BAD;
            break top;
          }

          break; // need to emulate goto via "continue"
        }
      }
      else if ((op & 64) === 0) {              /* 2nd level length code */
        here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
        continue dolen;
      }
      else if (op & 32) {                     /* end-of-block */
        //Tracevv((stderr, "inflate:         end of block\n"));
        state.mode = TYPE;
        break top;
      }
      else {
        strm.msg = 'invalid literal/length code';
        state.mode = BAD;
        break top;
      }

      break; // need to emulate goto via "continue"
    }
  } while (_in < last && _out < end);

  /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  len = bits >> 3;
  _in -= len;
  bits -= len << 3;
  hold &= (1 << bits) - 1;

  /* update state and return */
  strm.next_in = _in;
  strm.next_out = _out;
  strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  state.hold = hold;
  state.bits = bits;
  return;
};

},{}],82:[function(require,module,exports){
'use strict';

// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
//   claim that you wrote the original software. If you use this software
//   in a product, an acknowledgment in the product documentation would be
//   appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
//   misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.

var utils         = require('../utils/common');
var adler32       = require('./adler32');
var crc32         = require('./crc32');
var inflate_fast  = require('./inffast');
var inflate_table = require('./inftrees');

var CODES = 0;
var LENS = 1;
var DISTS = 2;

/* Public constants ==========================================================*/
/* ===========================================================================*/


/* Allowed flush values; see deflate() and inflate() below for details */
//var Z_NO_FLUSH      = 0;
//var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH    = 2;
//var Z_FULL_FLUSH    = 3;
var Z_FINISH        = 4;
var Z_BLOCK         = 5;
var Z_TREES         = 6;


/* Return codes for the compression/decompression functions. Negative values
 * are errors, positive values are used for special but normal events.
 */
var Z_OK            = 0;
var Z_STREAM_END    = 1;
var Z_NEED_DICT     = 2;
//var Z_ERRNO         = -1;
var Z_STREAM_ERROR  = -2;
var Z_DATA_ERROR    = -3;
var Z_MEM_ERROR     = -4;
var Z_BUF_ERROR     = -5;
//var Z_VERSION_ERROR = -6;

/* The deflate compression method */
var Z_DEFLATED  = 8;


/* STATES ====================================================================*/
/* ===========================================================================*/


var    HEAD = 1;       /* i: waiting for magic header */
var    FLAGS = 2;      /* i: waiting for method and flags (gzip) */
var    TIME = 3;       /* i: waiting for modification time (gzip) */
var    OS = 4;         /* i: waiting for extra flags and operating system (gzip) */
var    EXLEN = 5;      /* i: waiting for extra length (gzip) */
var    EXTRA = 6;      /* i: waiting for extra bytes (gzip) */
var    NAME = 7;       /* i: waiting for end of file name (gzip) */
var    COMMENT = 8;    /* i: waiting for end of comment (gzip) */
var    HCRC = 9;       /* i: waiting for header crc (gzip) */
var    DICTID = 10;    /* i: waiting for dictionary check value */
var    DICT = 11;      /* waiting for inflateSetDictionary() call */
var        TYPE = 12;      /* i: waiting for type bits, including last-flag bit */
var        TYPEDO = 13;    /* i: same, but skip check to exit inflate on new block */
var        STORED = 14;    /* i: waiting for stored size (length and complement) */
var        COPY_ = 15;     /* i/o: same as COPY below, but only first time in */
var        COPY = 16;      /* i/o: waiting for input or output to copy stored block */
var        TABLE = 17;     /* i: waiting for dynamic block table lengths */
var        LENLENS = 18;   /* i: waiting for code length code lengths */
var        CODELENS = 19;  /* i: waiting for length/lit and distance code lengths */
var            LEN_ = 20;      /* i: same as LEN below, but only first time in */
var            LEN = 21;       /* i: waiting for length/lit/eob code */
var            LENEXT = 22;    /* i: waiting for length extra bits */
var            DIST = 23;      /* i: waiting for distance code */
var            DISTEXT = 24;   /* i: waiting for distance extra bits */
var            MATCH = 25;     /* o: waiting for output space to copy string */
var            LIT = 26;       /* o: waiting for output space to write literal */
var    CHECK = 27;     /* i: waiting for 32-bit check value */
var    LENGTH = 28;    /* i: waiting for 32-bit length (gzip) */
var    DONE = 29;      /* finished check, done -- remain here until reset */
var    BAD = 30;       /* got a data error -- remain here until reset */
var    MEM = 31;       /* got an inflate() memory error -- remain here until reset */
var    SYNC = 32;      /* looking for synchronization bytes to restart inflate() */

/* ===========================================================================*/



var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH =  (ENOUGH_LENS+ENOUGH_DISTS);

var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_WBITS = MAX_WBITS;


function zswap32(q) {
  return  (((q >>> 24) & 0xff) +
          ((q >>> 8) & 0xff00) +
          ((q & 0xff00) << 8) +
          ((q & 0xff) << 24));
}


function InflateState() {
  this.mode = 0;             /* current inflate mode */
  this.last = false;          /* true if processing last block */
  this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip */
  this.havedict = false;      /* true if dictionary provided */
  this.flags = 0;             /* gzip header method and flags (0 if zlib) */
  this.dmax = 0;              /* zlib header max distance (INFLATE_STRICT) */
  this.check = 0;             /* protected copy of check value */
  this.total = 0;             /* protected copy of output count */
  // TODO: may be {}
  this.head = null;           /* where to save gzip header information */

  /* sliding window */
  this.wbits = 0;             /* log base 2 of requested window size */
  this.wsize = 0;             /* window size or zero if not using window */
  this.whave = 0;             /* valid bytes in the window */
  this.wnext = 0;             /* window write index */
  this.window = null;         /* allocated sliding window, if needed */

  /* bit accumulator */
  this.hold = 0;              /* input bit accumulator */
  this.bits = 0;              /* number of bits in "in" */

  /* for string and stored block copying */
  this.length = 0;            /* literal or length of data to copy */
  this.offset = 0;            /* distance back to copy string from */

  /* for table and code decoding */
  this.extra = 0;             /* extra bits needed */

  /* fixed and dynamic code tables */
  this.lencode = null;          /* starting table for length/literal codes */
  this.distcode = null;         /* starting table for distance codes */
  this.lenbits = 0;           /* index bits for lencode */
  this.distbits = 0;          /* index bits for distcode */

  /* dynamic table building */
  this.ncode = 0;             /* number of code length code lengths */
  this.nlen = 0;              /* number of length code lengths */
  this.ndist = 0;             /* number of distance code lengths */
  this.have = 0;              /* number of code lengths in lens[] */
  this.next = null;              /* next available space in codes[] */

  this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  this.work = new utils.Buf16(288); /* work area for code table building */

  /*
   because we don't have pointers in js, we use lencode and distcode directly
   as buffers so we don't need codes
  */
  //this.codes = new utils.Buf32(ENOUGH);       /* space for code tables */
  this.lendyn = null;              /* dynamic table for length/literal codes (JS specific) */
  this.distdyn = null;             /* dynamic table for distance codes (JS specific) */
  this.sane = 0;                   /* if false, allow invalid distance too far */
  this.back = 0;                   /* bits back of last unprocessed length/lit */
  this.was = 0;                    /* initial length of match */
}

function inflateResetKeep(strm) {
  var state;

  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  state = strm.state;
  strm.total_in = strm.total_out = state.total = 0;
  strm.msg = ''; /*Z_NULL*/
  if (state.wrap) {       /* to support ill-conceived Java test suite */
    strm.adler = state.wrap & 1;
  }
  state.mode = HEAD;
  state.last = 0;
  state.havedict = 0;
  state.dmax = 32768;
  state.head = null/*Z_NULL*/;
  state.hold = 0;
  state.bits = 0;
  //state.lencode = state.distcode = state.next = state.codes;
  state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);

  state.sane = 1;
  state.back = -1;
  //Tracev((stderr, "inflate: reset\n"));
  return Z_OK;
}

function inflateReset(strm) {
  var state;

  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  state = strm.state;
  state.wsize = 0;
  state.whave = 0;
  state.wnext = 0;
  return inflateResetKeep(strm);

}

function inflateReset2(strm, windowBits) {
  var wrap;
  var state;

  /* get the state */
  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  state = strm.state;

  /* extract wrap request from windowBits parameter */
  if (windowBits < 0) {
    wrap = 0;
    windowBits = -windowBits;
  }
  else {
    wrap = (windowBits >> 4) + 1;
    if (windowBits < 48) {
      windowBits &= 15;
    }
  }

  /* set number of window bits, free window if different */
  if (windowBits && (windowBits < 8 || windowBits > 15)) {
    return Z_STREAM_ERROR;
  }
  if (state.window !== null && state.wbits !== windowBits) {
    state.window = null;
  }

  /* update state and reset the rest of it */
  state.wrap = wrap;
  state.wbits = windowBits;
  return inflateReset(strm);
}

function inflateInit2(strm, windowBits) {
  var ret;
  var state;

  if (!strm) { return Z_STREAM_ERROR; }
  //strm.msg = Z_NULL;                 /* in case we return an error */

  state = new InflateState();

  //if (state === Z_NULL) return Z_MEM_ERROR;
  //Tracev((stderr, "inflate: allocated\n"));
  strm.state = state;
  state.window = null/*Z_NULL*/;
  ret = inflateReset2(strm, windowBits);
  if (ret !== Z_OK) {
    strm.state = null/*Z_NULL*/;
  }
  return ret;
}

function inflateInit(strm) {
  return inflateInit2(strm, DEF_WBITS);
}


/*
 Return state with length and distance decoding tables and index sizes set to
 fixed code decoding.  Normally this returns fixed tables from inffixed.h.
 If BUILDFIXED is defined, then instead this routine builds the tables the
 first time it's called, and returns those tables the first time and
 thereafter.  This reduces the size of the code by about 2K bytes, in
 exchange for a little execution time.  However, BUILDFIXED should not be
 used for threaded applications, since the rewriting of the tables and virgin
 may not be thread-safe.
 */
var virgin = true;

var lenfix, distfix; // We have no pointers in JS, so keep tables separate

function fixedtables(state) {
  /* build fixed huffman tables if first call (may not be thread safe) */
  if (virgin) {
    var sym;

    lenfix = new utils.Buf32(512);
    distfix = new utils.Buf32(32);

    /* literal/length table */
    sym = 0;
    while (sym < 144) { state.lens[sym++] = 8; }
    while (sym < 256) { state.lens[sym++] = 9; }
    while (sym < 280) { state.lens[sym++] = 7; }
    while (sym < 288) { state.lens[sym++] = 8; }

    inflate_table(LENS,  state.lens, 0, 288, lenfix,   0, state.work, { bits: 9 });

    /* distance table */
    sym = 0;
    while (sym < 32) { state.lens[sym++] = 5; }

    inflate_table(DISTS, state.lens, 0, 32,   distfix, 0, state.work, { bits: 5 });

    /* do this just once */
    virgin = false;
  }

  state.lencode = lenfix;
  state.lenbits = 9;
  state.distcode = distfix;
  state.distbits = 5;
}


/*
 Update the window with the last wsize (normally 32K) bytes written before
 returning.  If window does not exist yet, create it.  This is only called
 when a window is already in use, or when output has been written during this
 inflate call, but the end of the deflate stream has not been reached yet.
 It is also called to create a window for dictionary data when a dictionary
 is loaded.

 Providing output buffers larger than 32K to inflate() should provide a speed
 advantage, since only the last 32K of output is copied to the sliding window
 upon return from inflate(), and since all distances after the first 32K of
 output will fall in the output data, making match copies simpler and faster.
 The advantage may be dependent on the size of the processor's data caches.
 */
function updatewindow(strm, src, end, copy) {
  var dist;
  var state = strm.state;

  /* if it hasn't been done already, allocate space for the window */
  if (state.window === null) {
    state.wsize = 1 << state.wbits;
    state.wnext = 0;
    state.whave = 0;

    state.window = new utils.Buf8(state.wsize);
  }

  /* copy state->wsize or less output bytes into the circular window */
  if (copy >= state.wsize) {
    utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
    state.wnext = 0;
    state.whave = state.wsize;
  }
  else {
    dist = state.wsize - state.wnext;
    if (dist > copy) {
      dist = copy;
    }
    //zmemcpy(state->window + state->wnext, end - copy, dist);
    utils.arraySet(state.window, src, end - copy, dist, state.wnext);
    copy -= dist;
    if (copy) {
      //zmemcpy(state->window, end - copy, copy);
      utils.arraySet(state.window, src, end - copy, copy, 0);
      state.wnext = copy;
      state.whave = state.wsize;
    }
    else {
      state.wnext += dist;
      if (state.wnext === state.wsize) { state.wnext = 0; }
      if (state.whave < state.wsize) { state.whave += dist; }
    }
  }
  return 0;
}

function inflate(strm, flush) {
  var state;
  var input, output;          // input/output buffers
  var next;                   /* next input INDEX */
  var put;                    /* next output INDEX */
  var have, left;             /* available input and output */
  var hold;                   /* bit buffer */
  var bits;                   /* bits in bit buffer */
  var _in, _out;              /* save starting available input and output */
  var copy;                   /* number of stored or match bytes to copy */
  var from;                   /* where to copy match bytes from */
  var from_source;
  var here = 0;               /* current decoding table entry */
  var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  //var last;                   /* parent table entry */
  var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  var len;                    /* length to copy for repeats, bits to drop */
  var ret;                    /* return code */
  var hbuf = new utils.Buf8(4);    /* buffer for gzip header crc calculation */
  var opts;

  var n; // temporary var for NEED_BITS

  var order = /* permutation of code lengths */
    [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];


  if (!strm || !strm.state || !strm.output ||
      (!strm.input && strm.avail_in !== 0)) {
    return Z_STREAM_ERROR;
  }

  state = strm.state;
  if (state.mode === TYPE) { state.mode = TYPEDO; }    /* skip check */


  //--- LOAD() ---
  put = strm.next_out;
  output = strm.output;
  left = strm.avail_out;
  next = strm.next_in;
  input = strm.input;
  have = strm.avail_in;
  hold = state.hold;
  bits = state.bits;
  //---

  _in = have;
  _out = left;
  ret = Z_OK;

  inf_leave: // goto emulation
  for (;;) {
    switch (state.mode) {
      case HEAD:
        if (state.wrap === 0) {
          state.mode = TYPEDO;
          break;
        }
        //=== NEEDBITS(16);
        while (bits < 16) {
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
        }
        //===//
        if ((state.wrap & 2) && hold === 0x8b1f) {  /* gzip header */
          state.check = 0/*crc32(0L, Z_NULL, 0)*/;
          //=== CRC2(state.check, hold);
          hbuf[0] = hold & 0xff;
          hbuf[1] = (hold >>> 8) & 0xff;
          state.check = crc32(state.check, hbuf, 2, 0);
          //===//

          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
          state.mode = FLAGS;
          break;
        }
        state.flags = 0;           /* expect zlib header */
        if (state.head) {
          state.head.done = false;
        }
        if (!(state.wrap & 1) ||   /* check if zlib header allowed */
          (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
          strm.msg = 'incorrect header check';
          state.mode = BAD;
          break;
        }
        if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
          strm.msg = 'unknown compression method';
          state.mode = BAD;
          break;
        }
        //--- DROPBITS(4) ---//
        hold >>>= 4;
        bits -= 4;
        //---//
        len = (hold & 0x0f)/*BITS(4)*/ + 8;
        if (state.wbits === 0) {
          state.wbits = len;
        }
        else if (len > state.wbits) {
          strm.msg = 'invalid window size';
          state.mode = BAD;
          break;
        }
        state.dmax = 1 << len;
        //Tracev((stderr, "inflate:   zlib header ok\n"));
        strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
        state.mode = hold & 0x200 ? DICTID : TYPE;
        //=== INITBITS();
        hold = 0;
        bits = 0;
        //===//
        break;
      case FLAGS:
        //=== NEEDBITS(16); */
        while (bits < 16) {
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
        }
        //===//
        state.flags = hold;
        if ((state.flags & 0xff) !== Z_DEFLATED) {
          strm.msg = 'unknown compression method';
          state.mode = BAD;
          break;
        }
        if (state.flags & 0xe000) {
          strm.msg = 'unknown header flags set';
          state.mode = BAD;
          break;
        }
        if (state.head) {
          state.head.text = ((hold >> 8) & 1);
        }
        if (state.flags & 0x0200) {
          //=== CRC2(state.check, hold);
          hbuf[0] = hold & 0xff;
          hbuf[1] = (hold >>> 8) & 0xff;
          state.check = crc32(state.check, hbuf, 2, 0);
          //===//
        }
        //=== INITBITS();
        hold = 0;
        bits = 0;
        //===//
        state.mode = TIME;
        /* falls through */
      case TIME:
        //=== NEEDBITS(32); */
        while (bits < 32) {
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
        }
        //===//
        if (state.head) {
          state.head.time = hold;
        }
        if (state.flags & 0x0200) {
          //=== CRC4(state.check, hold)
          hbuf[0] = hold & 0xff;
          hbuf[1] = (hold >>> 8) & 0xff;
          hbuf[2] = (hold >>> 16) & 0xff;
          hbuf[3] = (hold >>> 24) & 0xff;
          state.check = crc32(state.check, hbuf, 4, 0);
          //===
        }
        //=== INITBITS();
        hold = 0;
        bits = 0;
        //===//
        state.mode = OS;
        /* falls through */
      case OS:
        //=== NEEDBITS(16); */
        while (bits < 16) {
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
        }
        //===//
        if (state.head) {
          state.head.xflags = (hold & 0xff);
          state.head.os = (hold >> 8);
        }
        if (state.flags & 0x0200) {
          //=== CRC2(state.check, hold);
          hbuf[0] = hold & 0xff;
          hbuf[1] = (hold >>> 8) & 0xff;
          state.check = crc32(state.check, hbuf, 2, 0);
          //===//
        }
        //=== INITBITS();
        hold = 0;
        bits = 0;
        //===//
        state.mode = EXLEN;
        /* falls through */
      case EXLEN:
        if (state.flags & 0x0400) {
          //=== NEEDBITS(16); */
          while (bits < 16) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          state.length = hold;
          if (state.head) {
            state.head.extra_len = hold;
          }
          if (state.flags & 0x0200) {
            //=== CRC2(state.check, hold);
            hbuf[0] = hold & 0xff;
            hbuf[1] = (hold >>> 8) & 0xff;
            state.check = crc32(state.check, hbuf, 2, 0);
            //===//
          }
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
        }
        else if (state.head) {
          state.head.extra = null/*Z_NULL*/;
        }
        state.mode = EXTRA;
        /* falls through */
      case EXTRA:
        if (state.flags & 0x0400) {
          copy = state.length;
          if (copy > have) { copy = have; }
          if (copy) {
            if (state.head) {
              len = state.head.extra_len - state.length;
              if (!state.head.extra) {
                // Use untyped array for more convenient processing later
                state.head.extra = new Array(state.head.extra_len);
              }
              utils.arraySet(
                state.head.extra,
                input,
                next,
                // extra field is limited to 65536 bytes
                // - no need for additional size check
                copy,
                /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
                len
              );
              //zmemcpy(state.head.extra + len, next,
              //        len + copy > state.head.extra_max ?
              //        state.head.extra_max - len : copy);
            }
            if (state.flags & 0x0200) {
              state.check = crc32(state.check, input, copy, next);
            }
            have -= copy;
            next += copy;
            state.length -= copy;
          }
          if (state.length) { break inf_leave; }
        }
        state.length = 0;
        state.mode = NAME;
        /* falls through */
      case NAME:
        if (state.flags & 0x0800) {
          if (have === 0) { break inf_leave; }
          copy = 0;
          do {
            // TODO: 2 or 1 bytes?
            len = input[next + copy++];
            /* use constant limit because in js we should not preallocate memory */
            if (state.head && len &&
                (state.length < 65536 /*state.head.name_max*/)) {
              state.head.name += String.fromCharCode(len);
            }
          } while (len && copy < have);

          if (state.flags & 0x0200) {
            state.check = crc32(state.check, input, copy, next);
          }
          have -= copy;
          next += copy;
          if (len) { break inf_leave; }
        }
        else if (state.head) {
          state.head.name = null;
        }
        state.length = 0;
        state.mode = COMMENT;
        /* falls through */
      case COMMENT:
        if (state.flags & 0x1000) {
          if (have === 0) { break inf_leave; }
          copy = 0;
          do {
            len = input[next + copy++];
            /* use constant limit because in js we should not preallocate memory */
            if (state.head && len &&
                (state.length < 65536 /*state.head.comm_max*/)) {
              state.head.comment += String.fromCharCode(len);
            }
          } while (len && copy < have);
          if (state.flags & 0x0200) {
            state.check = crc32(state.check, input, copy, next);
          }
          have -= copy;
          next += copy;
          if (len) { break inf_leave; }
        }
        else if (state.head) {
          state.head.comment = null;
        }
        state.mode = HCRC;
        /* falls through */
      case HCRC:
        if (state.flags & 0x0200) {
          //=== NEEDBITS(16); */
          while (bits < 16) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          if (hold !== (state.check & 0xffff)) {
            strm.msg = 'header crc mismatch';
            state.mode = BAD;
            break;
          }
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
        }
        if (state.head) {
          state.head.hcrc = ((state.flags >> 9) & 1);
          state.head.done = true;
        }
        strm.adler = state.check = 0;
        state.mode = TYPE;
        break;
      case DICTID:
        //=== NEEDBITS(32); */
        while (bits < 32) {
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
        }
        //===//
        strm.adler = state.check = zswap32(hold);
        //=== INITBITS();
        hold = 0;
        bits = 0;
        //===//
        state.mode = DICT;
        /* falls through */
      case DICT:
        if (state.havedict === 0) {
          //--- RESTORE() ---
          strm.next_out = put;
          strm.avail_out = left;
          strm.next_in = next;
          strm.avail_in = have;
          state.hold = hold;
          state.bits = bits;
          //---
          return Z_NEED_DICT;
        }
        strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
        state.mode = TYPE;
        /* falls through */
      case TYPE:
        if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
        /* falls through */
      case TYPEDO:
        if (state.last) {
          //--- BYTEBITS() ---//
          hold >>>= bits & 7;
          bits -= bits & 7;
          //---//
          state.mode = CHECK;
          break;
        }
        //=== NEEDBITS(3); */
        while (bits < 3) {
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
        }
        //===//
        state.last = (hold & 0x01)/*BITS(1)*/;
        //--- DROPBITS(1) ---//
        hold >>>= 1;
        bits -= 1;
        //---//

        switch ((hold & 0x03)/*BITS(2)*/) {
          case 0:                             /* stored block */
            //Tracev((stderr, "inflate:     stored block%s\n",
            //        state.last ? " (last)" : ""));
            state.mode = STORED;
            break;
          case 1:                             /* fixed block */
            fixedtables(state);
            //Tracev((stderr, "inflate:     fixed codes block%s\n",
            //        state.last ? " (last)" : ""));
            state.mode = LEN_;             /* decode codes */
            if (flush === Z_TREES) {
              //--- DROPBITS(2) ---//
              hold >>>= 2;
              bits -= 2;
              //---//
              break inf_leave;
            }
            break;
          case 2:                             /* dynamic block */
            //Tracev((stderr, "inflate:     dynamic codes block%s\n",
            //        state.last ? " (last)" : ""));
            state.mode = TABLE;
            break;
          case 3:
            strm.msg = 'invalid block type';
            state.mode = BAD;
        }
        //--- DROPBITS(2) ---//
        hold >>>= 2;
        bits -= 2;
        //---//
        break;
      case STORED:
        //--- BYTEBITS() ---// /* go to byte boundary */
        hold >>>= bits & 7;
        bits -= bits & 7;
        //---//
        //=== NEEDBITS(32); */
        while (bits < 32) {
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
        }
        //===//
        if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
          strm.msg = 'invalid stored block lengths';
          state.mode = BAD;
          break;
        }
        state.length = hold & 0xffff;
        //Tracev((stderr, "inflate:       stored length %u\n",
        //        state.length));
        //=== INITBITS();
        hold = 0;
        bits = 0;
        //===//
        state.mode = COPY_;
        if (flush === Z_TREES) { break inf_leave; }
        /* falls through */
      case COPY_:
        state.mode = COPY;
        /* falls through */
      case COPY:
        copy = state.length;
        if (copy) {
          if (copy > have) { copy = have; }
          if (copy > left) { copy = left; }
          if (copy === 0) { break inf_leave; }
          //--- zmemcpy(put, next, copy); ---
          utils.arraySet(output, input, next, copy, put);
          //---//
          have -= copy;
          next += copy;
          left -= copy;
          put += copy;
          state.length -= copy;
          break;
        }
        //Tracev((stderr, "inflate:       stored end\n"));
        state.mode = TYPE;
        break;
      case TABLE:
        //=== NEEDBITS(14); */
        while (bits < 14) {
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
        }
        //===//
        state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
        //--- DROPBITS(5) ---//
        hold >>>= 5;
        bits -= 5;
        //---//
        state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
        //--- DROPBITS(5) ---//
        hold >>>= 5;
        bits -= 5;
        //---//
        state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
        //--- DROPBITS(4) ---//
        hold >>>= 4;
        bits -= 4;
        //---//
//#ifndef PKZIP_BUG_WORKAROUND
        if (state.nlen > 286 || state.ndist > 30) {
          strm.msg = 'too many length or distance symbols';
          state.mode = BAD;
          break;
        }
//#endif
        //Tracev((stderr, "inflate:       table sizes ok\n"));
        state.have = 0;
        state.mode = LENLENS;
        /* falls through */
      case LENLENS:
        while (state.have < state.ncode) {
          //=== NEEDBITS(3);
          while (bits < 3) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
          //--- DROPBITS(3) ---//
          hold >>>= 3;
          bits -= 3;
          //---//
        }
        while (state.have < 19) {
          state.lens[order[state.have++]] = 0;
        }
        // We have separate tables & no pointers. 2 commented lines below not needed.
        //state.next = state.codes;
        //state.lencode = state.next;
        // Switch to use dynamic table
        state.lencode = state.lendyn;
        state.lenbits = 7;

        opts = { bits: state.lenbits };
        ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
        state.lenbits = opts.bits;

        if (ret) {
          strm.msg = 'invalid code lengths set';
          state.mode = BAD;
          break;
        }
        //Tracev((stderr, "inflate:       code lengths ok\n"));
        state.have = 0;
        state.mode = CODELENS;
        /* falls through */
      case CODELENS:
        while (state.have < state.nlen + state.ndist) {
          for (;;) {
            here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
            here_bits = here >>> 24;
            here_op = (here >>> 16) & 0xff;
            here_val = here & 0xffff;

            if ((here_bits) <= bits) { break; }
            //--- PULLBYTE() ---//
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
            //---//
          }
          if (here_val < 16) {
            //--- DROPBITS(here.bits) ---//
            hold >>>= here_bits;
            bits -= here_bits;
            //---//
            state.lens[state.have++] = here_val;
          }
          else {
            if (here_val === 16) {
              //=== NEEDBITS(here.bits + 2);
              n = here_bits + 2;
              while (bits < n) {
                if (have === 0) { break inf_leave; }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              //===//
              //--- DROPBITS(here.bits) ---//
              hold >>>= here_bits;
              bits -= here_bits;
              //---//
              if (state.have === 0) {
                strm.msg = 'invalid bit length repeat';
                state.mode = BAD;
                break;
              }
              len = state.lens[state.have - 1];
              copy = 3 + (hold & 0x03);//BITS(2);
              //--- DROPBITS(2) ---//
              hold >>>= 2;
              bits -= 2;
              //---//
            }
            else if (here_val === 17) {
              //=== NEEDBITS(here.bits + 3);
              n = here_bits + 3;
              while (bits < n) {
                if (have === 0) { break inf_leave; }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              //===//
              //--- DROPBITS(here.bits) ---//
              hold >>>= here_bits;
              bits -= here_bits;
              //---//
              len = 0;
              copy = 3 + (hold & 0x07);//BITS(3);
              //--- DROPBITS(3) ---//
              hold >>>= 3;
              bits -= 3;
              //---//
            }
            else {
              //=== NEEDBITS(here.bits + 7);
              n = here_bits + 7;
              while (bits < n) {
                if (have === 0) { break inf_leave; }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              //===//
              //--- DROPBITS(here.bits) ---//
              hold >>>= here_bits;
              bits -= here_bits;
              //---//
              len = 0;
              copy = 11 + (hold & 0x7f);//BITS(7);
              //--- DROPBITS(7) ---//
              hold >>>= 7;
              bits -= 7;
              //---//
            }
            if (state.have + copy > state.nlen + state.ndist) {
              strm.msg = 'invalid bit length repeat';
              state.mode = BAD;
              break;
            }
            while (copy--) {
              state.lens[state.have++] = len;
            }
          }
        }

        /* handle error breaks in while */
        if (state.mode === BAD) { break; }

        /* check for end-of-block code (better have one) */
        if (state.lens[256] === 0) {
          strm.msg = 'invalid code -- missing end-of-block';
          state.mode = BAD;
          break;
        }

        /* build code tables -- note: do not change the lenbits or distbits
           values here (9 and 6) without reading the comments in inftrees.h
           concerning the ENOUGH constants, which depend on those values */
        state.lenbits = 9;

        opts = { bits: state.lenbits };
        ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
        // We have separate tables & no pointers. 2 commented lines below not needed.
        // state.next_index = opts.table_index;
        state.lenbits = opts.bits;
        // state.lencode = state.next;

        if (ret) {
          strm.msg = 'invalid literal/lengths set';
          state.mode = BAD;
          break;
        }

        state.distbits = 6;
        //state.distcode.copy(state.codes);
        // Switch to use dynamic table
        state.distcode = state.distdyn;
        opts = { bits: state.distbits };
        ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
        // We have separate tables & no pointers. 2 commented lines below not needed.
        // state.next_index = opts.table_index;
        state.distbits = opts.bits;
        // state.distcode = state.next;

        if (ret) {
          strm.msg = 'invalid distances set';
          state.mode = BAD;
          break;
        }
        //Tracev((stderr, 'inflate:       codes ok\n'));
        state.mode = LEN_;
        if (flush === Z_TREES) { break inf_leave; }
        /* falls through */
      case LEN_:
        state.mode = LEN;
        /* falls through */
      case LEN:
        if (have >= 6 && left >= 258) {
          //--- RESTORE() ---
          strm.next_out = put;
          strm.avail_out = left;
          strm.next_in = next;
          strm.avail_in = have;
          state.hold = hold;
          state.bits = bits;
          //---
          inflate_fast(strm, _out);
          //--- LOAD() ---
          put = strm.next_out;
          output = strm.output;
          left = strm.avail_out;
          next = strm.next_in;
          input = strm.input;
          have = strm.avail_in;
          hold = state.hold;
          bits = state.bits;
          //---

          if (state.mode === TYPE) {
            state.back = -1;
          }
          break;
        }
        state.back = 0;
        for (;;) {
          here = state.lencode[hold & ((1 << state.lenbits) - 1)];  /*BITS(state.lenbits)*/
          here_bits = here >>> 24;
          here_op = (here >>> 16) & 0xff;
          here_val = here & 0xffff;

          if (here_bits <= bits) { break; }
          //--- PULLBYTE() ---//
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
          //---//
        }
        if (here_op && (here_op & 0xf0) === 0) {
          last_bits = here_bits;
          last_op = here_op;
          last_val = here_val;
          for (;;) {
            here = state.lencode[last_val +
                    ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
            here_bits = here >>> 24;
            here_op = (here >>> 16) & 0xff;
            here_val = here & 0xffff;

            if ((last_bits + here_bits) <= bits) { break; }
            //--- PULLBYTE() ---//
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
            //---//
          }
          //--- DROPBITS(last.bits) ---//
          hold >>>= last_bits;
          bits -= last_bits;
          //---//
          state.back += last_bits;
        }
        //--- DROPBITS(here.bits) ---//
        hold >>>= here_bits;
        bits -= here_bits;
        //---//
        state.back += here_bits;
        state.length = here_val;
        if (here_op === 0) {
          //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
          //        "inflate:         literal '%c'\n" :
          //        "inflate:         literal 0x%02x\n", here.val));
          state.mode = LIT;
          break;
        }
        if (here_op & 32) {
          //Tracevv((stderr, "inflate:         end of block\n"));
          state.back = -1;
          state.mode = TYPE;
          break;
        }
        if (here_op & 64) {
          strm.msg = 'invalid literal/length code';
          state.mode = BAD;
          break;
        }
        state.extra = here_op & 15;
        state.mode = LENEXT;
        /* falls through */
      case LENEXT:
        if (state.extra) {
          //=== NEEDBITS(state.extra);
          n = state.extra;
          while (bits < n) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
          //--- DROPBITS(state.extra) ---//
          hold >>>= state.extra;
          bits -= state.extra;
          //---//
          state.back += state.extra;
        }
        //Tracevv((stderr, "inflate:         length %u\n", state.length));
        state.was = state.length;
        state.mode = DIST;
        /* falls through */
      case DIST:
        for (;;) {
          here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
          here_bits = here >>> 24;
          here_op = (here >>> 16) & 0xff;
          here_val = here & 0xffff;

          if ((here_bits) <= bits) { break; }
          //--- PULLBYTE() ---//
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
          //---//
        }
        if ((here_op & 0xf0) === 0) {
          last_bits = here_bits;
          last_op = here_op;
          last_val = here_val;
          for (;;) {
            here = state.distcode[last_val +
                    ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
            here_bits = here >>> 24;
            here_op = (here >>> 16) & 0xff;
            here_val = here & 0xffff;

            if ((last_bits + here_bits) <= bits) { break; }
            //--- PULLBYTE() ---//
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
            //---//
          }
          //--- DROPBITS(last.bits) ---//
          hold >>>= last_bits;
          bits -= last_bits;
          //---//
          state.back += last_bits;
        }
        //--- DROPBITS(here.bits) ---//
        hold >>>= here_bits;
        bits -= here_bits;
        //---//
        state.back += here_bits;
        if (here_op & 64) {
          strm.msg = 'invalid distance code';
          state.mode = BAD;
          break;
        }
        state.offset = here_val;
        state.extra = (here_op) & 15;
        state.mode = DISTEXT;
        /* falls through */
      case DISTEXT:
        if (state.extra) {
          //=== NEEDBITS(state.extra);
          n = state.extra;
          while (bits < n) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
          //--- DROPBITS(state.extra) ---//
          hold >>>= state.extra;
          bits -= state.extra;
          //---//
          state.back += state.extra;
        }
//#ifdef INFLATE_STRICT
        if (state.offset > state.dmax) {
          strm.msg = 'invalid distance too far back';
          state.mode = BAD;
          break;
        }
//#endif
        //Tracevv((stderr, "inflate:         distance %u\n", state.offset));
        state.mode = MATCH;
        /* falls through */
      case MATCH:
        if (left === 0) { break inf_leave; }
        copy = _out - left;
        if (state.offset > copy) {         /* copy from window */
          copy = state.offset - copy;
          if (copy > state.whave) {
            if (state.sane) {
              strm.msg = 'invalid distance too far back';
              state.mode = BAD;
              break;
            }
// (!) This block is disabled in zlib defaults,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
//          Trace((stderr, "inflate.c too far\n"));
//          copy -= state.whave;
//          if (copy > state.length) { copy = state.length; }
//          if (copy > left) { copy = left; }
//          left -= copy;
//          state.length -= copy;
//          do {
//            output[put++] = 0;
//          } while (--copy);
//          if (state.length === 0) { state.mode = LEN; }
//          break;
//#endif
          }
          if (copy > state.wnext) {
            copy -= state.wnext;
            from = state.wsize - copy;
          }
          else {
            from = state.wnext - copy;
          }
          if (copy > state.length) { copy = state.length; }
          from_source = state.window;
        }
        else {                              /* copy from output */
          from_source = output;
          from = put - state.offset;
          copy = state.length;
        }
        if (copy > left) { copy = left; }
        left -= copy;
        state.length -= copy;
        do {
          output[put++] = from_source[from++];
        } while (--copy);
        if (state.length === 0) { state.mode = LEN; }
        break;
      case LIT:
        if (left === 0) { break inf_leave; }
        output[put++] = state.length;
        left--;
        state.mode = LEN;
        break;
      case CHECK:
        if (state.wrap) {
          //=== NEEDBITS(32);
          while (bits < 32) {
            if (have === 0) { break inf_leave; }
            have--;
            // Use '|' instead of '+' to make sure that result is signed
            hold |= input[next++] << bits;
            bits += 8;
          }
          //===//
          _out -= left;
          strm.total_out += _out;
          state.total += _out;
          if (_out) {
            strm.adler = state.check =
                /*UPDATE(state.check, put - _out, _out);*/
                (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));

          }
          _out = left;
          // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
          if ((state.flags ? hold : zswap32(hold)) !== state.check) {
            strm.msg = 'incorrect data check';
            state.mode = BAD;
            break;
          }
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
          //Tracev((stderr, "inflate:   check matches trailer\n"));
        }
        state.mode = LENGTH;
        /* falls through */
      case LENGTH:
        if (state.wrap && state.flags) {
          //=== NEEDBITS(32);
          while (bits < 32) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          if (hold !== (state.total & 0xffffffff)) {
            strm.msg = 'incorrect length check';
            state.mode = BAD;
            break;
          }
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
          //Tracev((stderr, "inflate:   length matches trailer\n"));
        }
        state.mode = DONE;
        /* falls through */
      case DONE:
        ret = Z_STREAM_END;
        break inf_leave;
      case BAD:
        ret = Z_DATA_ERROR;
        break inf_leave;
      case MEM:
        return Z_MEM_ERROR;
      case SYNC:
        /* falls through */
      default:
        return Z_STREAM_ERROR;
    }
  }

  // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"

  /*
     Return from inflate(), updating the total counts and the check value.
     If there was no progress during the inflate() call, return a buffer
     error.  Call updatewindow() to create and/or update the window state.
     Note: a memory error from inflate() is non-recoverable.
   */

  //--- RESTORE() ---
  strm.next_out = put;
  strm.avail_out = left;
  strm.next_in = next;
  strm.avail_in = have;
  state.hold = hold;
  state.bits = bits;
  //---

  if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
                      (state.mode < CHECK || flush !== Z_FINISH))) {
    if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
      state.mode = MEM;
      return Z_MEM_ERROR;
    }
  }
  _in -= strm.avail_in;
  _out -= strm.avail_out;
  strm.total_in += _in;
  strm.total_out += _out;
  state.total += _out;
  if (state.wrap && _out) {
    strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
      (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  }
  strm.data_type = state.bits + (state.last ? 64 : 0) +
                    (state.mode === TYPE ? 128 : 0) +
                    (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
    ret = Z_BUF_ERROR;
  }
  return ret;
}

function inflateEnd(strm) {

  if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
    return Z_STREAM_ERROR;
  }

  var state = strm.state;
  if (state.window) {
    state.window = null;
  }
  strm.state = null;
  return Z_OK;
}

function inflateGetHeader(strm, head) {
  var state;

  /* check state */
  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  state = strm.state;
  if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }

  /* save header structure */
  state.head = head;
  head.done = false;
  return Z_OK;
}

function inflateSetDictionary(strm, dictionary) {
  var dictLength = dictionary.length;

  var state;
  var dictid;
  var ret;

  /* check state */
  if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
  state = strm.state;

  if (state.wrap !== 0 && state.mode !== DICT) {
    return Z_STREAM_ERROR;
  }

  /* check for correct dictionary identifier */
  if (state.mode === DICT) {
    dictid = 1; /* adler32(0, null, 0)*/
    /* dictid = adler32(dictid, dictionary, dictLength); */
    dictid = adler32(dictid, dictionary, dictLength, 0);
    if (dictid !== state.check) {
      return Z_DATA_ERROR;
    }
  }
  /* copy dictionary to window using updatewindow(), which will amend the
   existing dictionary if appropriate */
  ret = updatewindow(strm, dictionary, dictLength, dictLength);
  if (ret) {
    state.mode = MEM;
    return Z_MEM_ERROR;
  }
  state.havedict = 1;
  // Tracev((stderr, "inflate:   dictionary set\n"));
  return Z_OK;
}

exports.inflateReset = inflateReset;
exports.inflateReset2 = inflateReset2;
exports.inflateResetKeep = inflateResetKeep;
exports.inflateInit = inflateInit;
exports.inflateInit2 = inflateInit2;
exports.inflate = inflate;
exports.inflateEnd = inflateEnd;
exports.inflateGetHeader = inflateGetHeader;
exports.inflateSetDictionary = inflateSetDictionary;
exports.inflateInfo = 'pako inflate (from Nodeca project)';

/* Not implemented
exports.inflateCopy = inflateCopy;
exports.inflateGetDictionary = inflateGetDictionary;
exports.inflateMark = inflateMark;
exports.inflatePrime = inflatePrime;
exports.inflateSync = inflateSync;
exports.inflateSyncPoint = inflateSyncPoint;
exports.inflateUndermine = inflateUndermine;
*/

},{"../utils/common":76,"./adler32":77,"./crc32":79,"./inffast":81,"./inftrees":83}],83:[function(require,module,exports){
'use strict';

// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
//   claim that you wrote the original software. If you use this software
//   in a product, an acknowledgment in the product documentation would be
//   appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
//   misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.

var utils = require('../utils/common');

var MAXBITS = 15;
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);

var CODES = 0;
var LENS = 1;
var DISTS = 2;

var lbase = [ /* Length codes 257..285 base */
  3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
];

var lext = [ /* Length codes 257..285 extra */
  16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
];

var dbase = [ /* Distance codes 0..29 base */
  1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  8193, 12289, 16385, 24577, 0, 0
];

var dext = [ /* Distance codes 0..29 extra */
  16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  28, 28, 29, 29, 64, 64
];

module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
{
  var bits = opts.bits;
      //here = opts.here; /* table entry for duplication */

  var len = 0;               /* a code's length in bits */
  var sym = 0;               /* index of code symbols */
  var min = 0, max = 0;          /* minimum and maximum code lengths */
  var root = 0;              /* number of index bits for root table */
  var curr = 0;              /* number of index bits for current table */
  var drop = 0;              /* code bits to drop for sub-table */
  var left = 0;                   /* number of prefix codes available */
  var used = 0;              /* code entries in table used */
  var huff = 0;              /* Huffman code */
  var incr;              /* for incrementing code, index */
  var fill;              /* index for replicating entries */
  var low;               /* low bits for current root entry */
  var mask;              /* mask for low root bits */
  var next;             /* next available space in table */
  var base = null;     /* base value table to use */
  var base_index = 0;
//  var shoextra;    /* extra bits table to use */
  var end;                    /* use base and extra for symbol > end */
  var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1];    /* number of codes of each length */
  var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1];     /* offsets in table for each length */
  var extra = null;
  var extra_index = 0;

  var here_bits, here_op, here_val;

  /*
   Process a set of code lengths to create a canonical Huffman code.  The
   code lengths are lens[0..codes-1].  Each length corresponds to the
   symbols 0..codes-1.  The Huffman code is generated by first sorting the
   symbols by length from short to long, and retaining the symbol order
   for codes with equal lengths.  Then the code starts with all zero bits
   for the first code of the shortest length, and the codes are integer
   increments for the same length, and zeros are appended as the length
   increases.  For the deflate format, these bits are stored backwards
   from their more natural integer increment ordering, and so when the
   decoding tables are built in the large loop below, the integer codes
   are incremented backwards.

   This routine assumes, but does not check, that all of the entries in
   lens[] are in the range 0..MAXBITS.  The caller must assure this.
   1..MAXBITS is interpreted as that code length.  zero means that that
   symbol does not occur in this code.

   The codes are sorted by computing a count of codes for each length,
   creating from that a table of starting indices for each length in the
   sorted table, and then entering the symbols in order in the sorted
   table.  The sorted table is work[], with that space being provided by
   the caller.

   The length counts are used for other purposes as well, i.e. finding
   the minimum and maximum length codes, determining if there are any
   codes at all, checking for a valid set of lengths, and looking ahead
   at length counts to determine sub-table sizes when building the
   decoding tables.
   */

  /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  for (len = 0; len <= MAXBITS; len++) {
    count[len] = 0;
  }
  for (sym = 0; sym < codes; sym++) {
    count[lens[lens_index + sym]]++;
  }

  /* bound code lengths, force root to be within code lengths */
  root = bits;
  for (max = MAXBITS; max >= 1; max--) {
    if (count[max] !== 0) { break; }
  }
  if (root > max) {
    root = max;
  }
  if (max === 0) {                     /* no symbols to code at all */
    //table.op[opts.table_index] = 64;  //here.op = (var char)64;    /* invalid code marker */
    //table.bits[opts.table_index] = 1;   //here.bits = (var char)1;
    //table.val[opts.table_index++] = 0;   //here.val = (var short)0;
    table[table_index++] = (1 << 24) | (64 << 16) | 0;


    //table.op[opts.table_index] = 64;
    //table.bits[opts.table_index] = 1;
    //table.val[opts.table_index++] = 0;
    table[table_index++] = (1 << 24) | (64 << 16) | 0;

    opts.bits = 1;
    return 0;     /* no symbols, but wait for decoding to report error */
  }
  for (min = 1; min < max; min++) {
    if (count[min] !== 0) { break; }
  }
  if (root < min) {
    root = min;
  }

  /* check for an over-subscribed or incomplete set of lengths */
  left = 1;
  for (len = 1; len <= MAXBITS; len++) {
    left <<= 1;
    left -= count[len];
    if (left < 0) {
      return -1;
    }        /* over-subscribed */
  }
  if (left > 0 && (type === CODES || max !== 1)) {
    return -1;                      /* incomplete set */
  }

  /* generate offsets into symbol table for each length for sorting */
  offs[1] = 0;
  for (len = 1; len < MAXBITS; len++) {
    offs[len + 1] = offs[len] + count[len];
  }

  /* sort symbols by length, by symbol order within each length */
  for (sym = 0; sym < codes; sym++) {
    if (lens[lens_index + sym] !== 0) {
      work[offs[lens[lens_index + sym]]++] = sym;
    }
  }

  /*
   Create and fill in decoding tables.  In this loop, the table being
   filled is at next and has curr index bits.  The code being used is huff
   with length len.  That code is converted to an index by dropping drop
   bits off of the bottom.  For codes where len is less than drop + curr,
   those top drop + curr - len bits are incremented through all values to
   fill the table with replicated entries.

   root is the number of index bits for the root table.  When len exceeds
   root, sub-tables are created pointed to by the root entry with an index
   of the low root bits of huff.  This is saved in low to check for when a
   new sub-table should be started.  drop is zero when the root table is
   being filled, and drop is root when sub-tables are being filled.

   When a new sub-table is needed, it is necessary to look ahead in the
   code lengths to determine what size sub-table is needed.  The length
   counts are used for this, and so count[] is decremented as codes are
   entered in the tables.

   used keeps track of how many table entries have been allocated from the
   provided *table space.  It is checked for LENS and DIST tables against
   the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
   the initial root table size constants.  See the comments in inftrees.h
   for more information.

   sym increments through all symbols, and the loop terminates when
   all codes of length max, i.e. all codes, have been processed.  This
   routine permits incomplete codes, so another loop after this one fills
   in the rest of the decoding tables with invalid code markers.
   */

  /* set up for code type */
  // poor man optimization - use if-else instead of switch,
  // to avoid deopts in old v8
  if (type === CODES) {
    base = extra = work;    /* dummy value--not used */
    end = 19;

  } else if (type === LENS) {
    base = lbase;
    base_index -= 257;
    extra = lext;
    extra_index -= 257;
    end = 256;

  } else {                    /* DISTS */
    base = dbase;
    extra = dext;
    end = -1;
  }

  /* initialize opts for loop */
  huff = 0;                   /* starting code */
  sym = 0;                    /* starting code symbol */
  len = min;                  /* starting code length */
  next = table_index;              /* current table to fill in */
  curr = root;                /* current table index bits */
  drop = 0;                   /* current bits to drop from code for index */
  low = -1;                   /* trigger new sub-table when len > root */
  used = 1 << root;          /* use root table entries */
  mask = used - 1;            /* mask for comparing low */

  /* check available table space */
  if ((type === LENS && used > ENOUGH_LENS) ||
    (type === DISTS && used > ENOUGH_DISTS)) {
    return 1;
  }

  /* process all codes and make table entries */
  for (;;) {
    /* create table entry */
    here_bits = len - drop;
    if (work[sym] < end) {
      here_op = 0;
      here_val = work[sym];
    }
    else if (work[sym] > end) {
      here_op = extra[extra_index + work[sym]];
      here_val = base[base_index + work[sym]];
    }
    else {
      here_op = 32 + 64;         /* end of block */
      here_val = 0;
    }

    /* replicate for those indices with low len bits equal to huff */
    incr = 1 << (len - drop);
    fill = 1 << curr;
    min = fill;                 /* save offset to next table */
    do {
      fill -= incr;
      table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
    } while (fill !== 0);

    /* backwards increment the len-bit code huff */
    incr = 1 << (len - 1);
    while (huff & incr) {
      incr >>= 1;
    }
    if (incr !== 0) {
      huff &= incr - 1;
      huff += incr;
    } else {
      huff = 0;
    }

    /* go to next symbol, update count, len */
    sym++;
    if (--count[len] === 0) {
      if (len === max) { break; }
      len = lens[lens_index + work[sym]];
    }

    /* create new sub-table if needed */
    if (len > root && (huff & mask) !== low) {
      /* if first time, transition to sub-tables */
      if (drop === 0) {
        drop = root;
      }

      /* increment past last table */
      next += min;            /* here min is 1 << curr */

      /* determine length of next table */
      curr = len - drop;
      left = 1 << curr;
      while (curr + drop < max) {
        left -= count[curr + drop];
        if (left <= 0) { break; }
        curr++;
        left <<= 1;
      }

      /* check for enough space */
      used += 1 << curr;
      if ((type === LENS && used > ENOUGH_LENS) ||
        (type === DISTS && used > ENOUGH_DISTS)) {
        return 1;
      }

      /* point entry in root table to sub-table */
      low = huff & mask;
      /*table.op[low] = curr;
      table.bits[low] = root;
      table.val[low] = next - opts.table_index;*/
      table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
    }
  }

  /* fill in remaining table entry if code is incomplete (guaranteed to have
   at most one remaining entry, since if the code is incomplete, the
   maximum code length that was allowed to get this far is one bit) */
  if (huff !== 0) {
    //table.op[next + huff] = 64;            /* invalid code marker */
    //table.bits[next + huff] = len - drop;
    //table.val[next + huff] = 0;
    table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  }

  /* set return parameters */
  //opts.table_index += used;
  opts.bits = root;
  return 0;
};

},{"../utils/common":76}],84:[function(require,module,exports){
'use strict';

// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
//   claim that you wrote the original software. If you use this software
//   in a product, an acknowledgment in the product documentation would be
//   appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
//   misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.

module.exports = {
  2:      'need dictionary',     /* Z_NEED_DICT       2  */
  1:      'stream end',          /* Z_STREAM_END      1  */
  0:      '',                    /* Z_OK              0  */
  '-1':   'file error',          /* Z_ERRNO         (-1) */
  '-2':   'stream error',        /* Z_STREAM_ERROR  (-2) */
  '-3':   'data error',          /* Z_DATA_ERROR    (-3) */
  '-4':   'insufficient memory', /* Z_MEM_ERROR     (-4) */
  '-5':   'buffer error',        /* Z_BUF_ERROR     (-5) */
  '-6':   'incompatible version' /* Z_VERSION_ERROR (-6) */
};

},{}],85:[function(require,module,exports){
'use strict';

// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
//   claim that you wrote the original software. If you use this software
//   in a product, an acknowledgment in the product documentation would be
//   appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
//   misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.

/* eslint-disable space-unary-ops */

var utils = require('../utils/common');

/* Public constants ==========================================================*/
/* ===========================================================================*/


//var Z_FILTERED          = 1;
//var Z_HUFFMAN_ONLY      = 2;
//var Z_RLE               = 3;
var Z_FIXED               = 4;
//var Z_DEFAULT_STRATEGY  = 0;

/* Possible values of the data_type field (though see inflate()) */
var Z_BINARY              = 0;
var Z_TEXT                = 1;
//var Z_ASCII             = 1; // = Z_TEXT
var Z_UNKNOWN             = 2;

/*============================================================================*/


function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }

// From zutil.h

var STORED_BLOCK = 0;
var STATIC_TREES = 1;
var DYN_TREES    = 2;
/* The three kinds of block type */

var MIN_MATCH    = 3;
var MAX_MATCH    = 258;
/* The minimum and maximum match lengths */

// From deflate.h
/* ===========================================================================
 * Internal compression state.
 */

var LENGTH_CODES  = 29;
/* number of length codes, not counting the special END_BLOCK code */

var LITERALS      = 256;
/* number of literal bytes 0..255 */

var L_CODES       = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */

var D_CODES       = 30;
/* number of distance codes */

var BL_CODES      = 19;
/* number of codes used to transfer the bit lengths */

var HEAP_SIZE     = 2 * L_CODES + 1;
/* maximum heap size */

var MAX_BITS      = 15;
/* All codes must not exceed MAX_BITS bits */

var Buf_size      = 16;
/* size of bit buffer in bi_buf */


/* ===========================================================================
 * Constants
 */

var MAX_BL_BITS = 7;
/* Bit length codes must not exceed MAX_BL_BITS bits */

var END_BLOCK   = 256;
/* end of block literal code */

var REP_3_6     = 16;
/* repeat previous bit length 3-6 times (2 bits of repeat count) */

var REPZ_3_10   = 17;
/* repeat a zero length 3-10 times  (3 bits of repeat count) */

var REPZ_11_138 = 18;
/* repeat a zero length 11-138 times  (7 bits of repeat count) */

/* eslint-disable comma-spacing,array-bracket-spacing */
var extra_lbits =   /* extra bits for each length code */
  [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];

var extra_dbits =   /* extra bits for each distance code */
  [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];

var extra_blbits =  /* extra bits for each bit length code */
  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];

var bl_order =
  [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
/* eslint-enable comma-spacing,array-bracket-spacing */

/* The lengths of the bit length codes are sent in order of decreasing
 * probability, to avoid transmitting the lengths for unused bit length codes.
 */

/* ===========================================================================
 * Local data. These are initialized only once.
 */

// We pre-fill arrays with 0 to avoid uninitialized gaps

var DIST_CODE_LEN = 512; /* see definition of array dist_code below */

// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
var static_ltree  = new Array((L_CODES + 2) * 2);
zero(static_ltree);
/* The static literal tree. Since the bit lengths are imposed, there is no
 * need for the L_CODES extra codes used during heap construction. However
 * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
 * below).
 */

var static_dtree  = new Array(D_CODES * 2);
zero(static_dtree);
/* The static distance tree. (Actually a trivial tree since all codes use
 * 5 bits.)
 */

var _dist_code    = new Array(DIST_CODE_LEN);
zero(_dist_code);
/* Distance codes. The first 256 values correspond to the distances
 * 3 .. 258, the last 256 values correspond to the top 8 bits of
 * the 15 bit distances.
 */

var _length_code  = new Array(MAX_MATCH - MIN_MATCH + 1);
zero(_length_code);
/* length code for each normalized match length (0 == MIN_MATCH) */

var base_length   = new Array(LENGTH_CODES);
zero(base_length);
/* First normalized length for each code (0 = MIN_MATCH) */

var base_dist     = new Array(D_CODES);
zero(base_dist);
/* First normalized distance for each code (0 = distance of 1) */


function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {

  this.static_tree  = static_tree;  /* static tree or NULL */
  this.extra_bits   = extra_bits;   /* extra bits for each code or NULL */
  this.extra_base   = extra_base;   /* base index for extra_bits */
  this.elems        = elems;        /* max number of elements in the tree */
  this.max_length   = max_length;   /* max bit length for the codes */

  // show if `static_tree` has data or dummy - needed for monomorphic objects
  this.has_stree    = static_tree && static_tree.length;
}


var static_l_desc;
var static_d_desc;
var static_bl_desc;


function TreeDesc(dyn_tree, stat_desc) {
  this.dyn_tree = dyn_tree;     /* the dynamic tree */
  this.max_code = 0;            /* largest code with non zero frequency */
  this.stat_desc = stat_desc;   /* the corresponding static tree */
}



function d_code(dist) {
  return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
}


/* ===========================================================================
 * Output a short LSB first on the stream.
 * IN assertion: there is enough room in pendingBuf.
 */
function put_short(s, w) {
//    put_byte(s, (uch)((w) & 0xff));
//    put_byte(s, (uch)((ush)(w) >> 8));
  s.pending_buf[s.pending++] = (w) & 0xff;
  s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
}


/* ===========================================================================
 * Send a value on a given number of bits.
 * IN assertion: length <= 16 and value fits in length bits.
 */
function send_bits(s, value, length) {
  if (s.bi_valid > (Buf_size - length)) {
    s.bi_buf |= (value << s.bi_valid) & 0xffff;
    put_short(s, s.bi_buf);
    s.bi_buf = value >> (Buf_size - s.bi_valid);
    s.bi_valid += length - Buf_size;
  } else {
    s.bi_buf |= (value << s.bi_valid) & 0xffff;
    s.bi_valid += length;
  }
}


function send_code(s, c, tree) {
  send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
}


/* ===========================================================================
 * Reverse the first len bits of a code, using straightforward code (a faster
 * method would use a table)
 * IN assertion: 1 <= len <= 15
 */
function bi_reverse(code, len) {
  var res = 0;
  do {
    res |= code & 1;
    code >>>= 1;
    res <<= 1;
  } while (--len > 0);
  return res >>> 1;
}


/* ===========================================================================
 * Flush the bit buffer, keeping at most 7 bits in it.
 */
function bi_flush(s) {
  if (s.bi_valid === 16) {
    put_short(s, s.bi_buf);
    s.bi_buf = 0;
    s.bi_valid = 0;

  } else if (s.bi_valid >= 8) {
    s.pending_buf[s.pending++] = s.bi_buf & 0xff;
    s.bi_buf >>= 8;
    s.bi_valid -= 8;
  }
}


/* ===========================================================================
 * Compute the optimal bit lengths for a tree and update the total bit length
 * for the current block.
 * IN assertion: the fields freq and dad are set, heap[heap_max] and
 *    above are the tree nodes sorted by increasing frequency.
 * OUT assertions: the field len is set to the optimal bit length, the
 *     array bl_count contains the frequencies for each bit length.
 *     The length opt_len is updated; static_len is also updated if stree is
 *     not null.
 */
function gen_bitlen(s, desc)
//    deflate_state *s;
//    tree_desc *desc;    /* the tree descriptor */
{
  var tree            = desc.dyn_tree;
  var max_code        = desc.max_code;
  var stree           = desc.stat_desc.static_tree;
  var has_stree       = desc.stat_desc.has_stree;
  var extra           = desc.stat_desc.extra_bits;
  var base            = desc.stat_desc.extra_base;
  var max_length      = desc.stat_desc.max_length;
  var h;              /* heap index */
  var n, m;           /* iterate over the tree elements */
  var bits;           /* bit length */
  var xbits;          /* extra bits */
  var f;              /* frequency */
  var overflow = 0;   /* number of elements with bit length too large */

  for (bits = 0; bits <= MAX_BITS; bits++) {
    s.bl_count[bits] = 0;
  }

  /* In a first pass, compute the optimal bit lengths (which may
   * overflow in the case of the bit length tree).
   */
  tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */

  for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
    n = s.heap[h];
    bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
    if (bits > max_length) {
      bits = max_length;
      overflow++;
    }
    tree[n * 2 + 1]/*.Len*/ = bits;
    /* We overwrite tree[n].Dad which is no longer needed */

    if (n > max_code) { continue; } /* not a leaf node */

    s.bl_count[bits]++;
    xbits = 0;
    if (n >= base) {
      xbits = extra[n - base];
    }
    f = tree[n * 2]/*.Freq*/;
    s.opt_len += f * (bits + xbits);
    if (has_stree) {
      s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
    }
  }
  if (overflow === 0) { return; }

  // Trace((stderr,"\nbit length overflow\n"));
  /* This happens for example on obj2 and pic of the Calgary corpus */

  /* Find the first bit length which could increase: */
  do {
    bits = max_length - 1;
    while (s.bl_count[bits] === 0) { bits--; }
    s.bl_count[bits]--;      /* move one leaf down the tree */
    s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
    s.bl_count[max_length]--;
    /* The brother of the overflow item also moves one step up,
     * but this does not affect bl_count[max_length]
     */
    overflow -= 2;
  } while (overflow > 0);

  /* Now recompute all bit lengths, scanning in increasing frequency.
   * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
   * lengths instead of fixing only the wrong ones. This idea is taken
   * from 'ar' written by Haruhiko Okumura.)
   */
  for (bits = max_length; bits !== 0; bits--) {
    n = s.bl_count[bits];
    while (n !== 0) {
      m = s.heap[--h];
      if (m > max_code) { continue; }
      if (tree[m * 2 + 1]/*.Len*/ !== bits) {
        // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
        s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
        tree[m * 2 + 1]/*.Len*/ = bits;
      }
      n--;
    }
  }
}


/* ===========================================================================
 * Generate the codes for a given tree and bit counts (which need not be
 * optimal).
 * IN assertion: the array bl_count contains the bit length statistics for
 * the given tree and the field len is set for all tree elements.
 * OUT assertion: the field code is set for all tree elements of non
 *     zero code length.
 */
function gen_codes(tree, max_code, bl_count)
//    ct_data *tree;             /* the tree to decorate */
//    int max_code;              /* largest code with non zero frequency */
//    ushf *bl_count;            /* number of codes at each bit length */
{
  var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
  var code = 0;              /* running code value */
  var bits;                  /* bit index */
  var n;                     /* code index */

  /* The distribution counts are first used to generate the code values
   * without bit reversal.
   */
  for (bits = 1; bits <= MAX_BITS; bits++) {
    next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
  }
  /* Check that the bit counts in bl_count are consistent. The last code
   * must be all ones.
   */
  //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  //        "inconsistent bit counts");
  //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));

  for (n = 0;  n <= max_code; n++) {
    var len = tree[n * 2 + 1]/*.Len*/;
    if (len === 0) { continue; }
    /* Now reverse the bits */
    tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);

    //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
    //     n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  }
}


/* ===========================================================================
 * Initialize the various 'constant' tables.
 */
function tr_static_init() {
  var n;        /* iterates over tree elements */
  var bits;     /* bit counter */
  var length;   /* length value */
  var code;     /* code value */
  var dist;     /* distance index */
  var bl_count = new Array(MAX_BITS + 1);
  /* number of codes at each bit length for an optimal tree */

  // do check in _tr_init()
  //if (static_init_done) return;

  /* For some embedded targets, global variables are not initialized: */
/*#ifdef NO_INIT_GLOBAL_POINTERS
  static_l_desc.static_tree = static_ltree;
  static_l_desc.extra_bits = extra_lbits;
  static_d_desc.static_tree = static_dtree;
  static_d_desc.extra_bits = extra_dbits;
  static_bl_desc.extra_bits = extra_blbits;
#endif*/

  /* Initialize the mapping length (0..255) -> length code (0..28) */
  length = 0;
  for (code = 0; code < LENGTH_CODES - 1; code++) {
    base_length[code] = length;
    for (n = 0; n < (1 << extra_lbits[code]); n++) {
      _length_code[length++] = code;
    }
  }
  //Assert (length == 256, "tr_static_init: length != 256");
  /* Note that the length 255 (match length 258) can be represented
   * in two different ways: code 284 + 5 bits or code 285, so we
   * overwrite length_code[255] to use the best encoding:
   */
  _length_code[length - 1] = code;

  /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  dist = 0;
  for (code = 0; code < 16; code++) {
    base_dist[code] = dist;
    for (n = 0; n < (1 << extra_dbits[code]); n++) {
      _dist_code[dist++] = code;
    }
  }
  //Assert (dist == 256, "tr_static_init: dist != 256");
  dist >>= 7; /* from now on, all distances are divided by 128 */
  for (; code < D_CODES; code++) {
    base_dist[code] = dist << 7;
    for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
      _dist_code[256 + dist++] = code;
    }
  }
  //Assert (dist == 256, "tr_static_init: 256+dist != 512");

  /* Construct the codes of the static literal tree */
  for (bits = 0; bits <= MAX_BITS; bits++) {
    bl_count[bits] = 0;
  }

  n = 0;
  while (n <= 143) {
    static_ltree[n * 2 + 1]/*.Len*/ = 8;
    n++;
    bl_count[8]++;
  }
  while (n <= 255) {
    static_ltree[n * 2 + 1]/*.Len*/ = 9;
    n++;
    bl_count[9]++;
  }
  while (n <= 279) {
    static_ltree[n * 2 + 1]/*.Len*/ = 7;
    n++;
    bl_count[7]++;
  }
  while (n <= 287) {
    static_ltree[n * 2 + 1]/*.Len*/ = 8;
    n++;
    bl_count[8]++;
  }
  /* Codes 286 and 287 do not exist, but we must include them in the
   * tree construction to get a canonical Huffman tree (longest code
   * all ones)
   */
  gen_codes(static_ltree, L_CODES + 1, bl_count);

  /* The static distance tree is trivial: */
  for (n = 0; n < D_CODES; n++) {
    static_dtree[n * 2 + 1]/*.Len*/ = 5;
    static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
  }

  // Now data ready and we can init static trees
  static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
  static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS);
  static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0,         BL_CODES, MAX_BL_BITS);

  //static_init_done = true;
}


/* ===========================================================================
 * Initialize a new block.
 */
function init_block(s) {
  var n; /* iterates over tree elements */

  /* Initialize the trees. */
  for (n = 0; n < L_CODES;  n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
  for (n = 0; n < D_CODES;  n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
  for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }

  s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
  s.opt_len = s.static_len = 0;
  s.last_lit = s.matches = 0;
}


/* ===========================================================================
 * Flush the bit buffer and align the output on a byte boundary
 */
function bi_windup(s)
{
  if (s.bi_valid > 8) {
    put_short(s, s.bi_buf);
  } else if (s.bi_valid > 0) {
    //put_byte(s, (Byte)s->bi_buf);
    s.pending_buf[s.pending++] = s.bi_buf;
  }
  s.bi_buf = 0;
  s.bi_valid = 0;
}

/* ===========================================================================
 * Copy a stored block, storing first the length and its
 * one's complement if requested.
 */
function copy_block(s, buf, len, header)
//DeflateState *s;
//charf    *buf;    /* the input data */
//unsigned len;     /* its length */
//int      header;  /* true if block header must be written */
{
  bi_windup(s);        /* align on byte boundary */

  if (header) {
    put_short(s, len);
    put_short(s, ~len);
  }
//  while (len--) {
//    put_byte(s, *buf++);
//  }
  utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  s.pending += len;
}

/* ===========================================================================
 * Compares to subtrees, using the tree depth as tie breaker when
 * the subtrees have equal frequency. This minimizes the worst case length.
 */
function smaller(tree, n, m, depth) {
  var _n2 = n * 2;
  var _m2 = m * 2;
  return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
         (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
}

/* ===========================================================================
 * Restore the heap property by moving down the tree starting at node k,
 * exchanging a node with the smallest of its two sons if necessary, stopping
 * when the heap property is re-established (each father smaller than its
 * two sons).
 */
function pqdownheap(s, tree, k)
//    deflate_state *s;
//    ct_data *tree;  /* the tree to restore */
//    int k;               /* node to move down */
{
  var v = s.heap[k];
  var j = k << 1;  /* left son of k */
  while (j <= s.heap_len) {
    /* Set j to the smallest of the two sons: */
    if (j < s.heap_len &&
      smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
      j++;
    }
    /* Exit if v is smaller than both sons */
    if (smaller(tree, v, s.heap[j], s.depth)) { break; }

    /* Exchange v with the smallest son */
    s.heap[k] = s.heap[j];
    k = j;

    /* And continue down the tree, setting j to the left son of k */
    j <<= 1;
  }
  s.heap[k] = v;
}


// inlined manually
// var SMALLEST = 1;

/* ===========================================================================
 * Send the block data compressed using the given Huffman trees
 */
function compress_block(s, ltree, dtree)
//    deflate_state *s;
//    const ct_data *ltree; /* literal tree */
//    const ct_data *dtree; /* distance tree */
{
  var dist;           /* distance of matched string */
  var lc;             /* match length or unmatched char (if dist == 0) */
  var lx = 0;         /* running index in l_buf */
  var code;           /* the code to send */
  var extra;          /* number of extra bits to send */

  if (s.last_lit !== 0) {
    do {
      dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
      lc = s.pending_buf[s.l_buf + lx];
      lx++;

      if (dist === 0) {
        send_code(s, lc, ltree); /* send a literal byte */
        //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
      } else {
        /* Here, lc is the match length - MIN_MATCH */
        code = _length_code[lc];
        send_code(s, code + LITERALS + 1, ltree); /* send the length code */
        extra = extra_lbits[code];
        if (extra !== 0) {
          lc -= base_length[code];
          send_bits(s, lc, extra);       /* send the extra length bits */
        }
        dist--; /* dist is now the match distance - 1 */
        code = d_code(dist);
        //Assert (code < D_CODES, "bad d_code");

        send_code(s, code, dtree);       /* send the distance code */
        extra = extra_dbits[code];
        if (extra !== 0) {
          dist -= base_dist[code];
          send_bits(s, dist, extra);   /* send the extra distance bits */
        }
      } /* literal or match pair ? */

      /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
      //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
      //       "pendingBuf overflow");

    } while (lx < s.last_lit);
  }

  send_code(s, END_BLOCK, ltree);
}


/* ===========================================================================
 * Construct one Huffman tree and assigns the code bit strings and lengths.
 * Update the total bit length for the current block.
 * IN assertion: the field freq is set for all tree elements.
 * OUT assertions: the fields len and code are set to the optimal bit length
 *     and corresponding code. The length opt_len is updated; static_len is
 *     also updated if stree is not null. The field max_code is set.
 */
function build_tree(s, desc)
//    deflate_state *s;
//    tree_desc *desc; /* the tree descriptor */
{
  var tree     = desc.dyn_tree;
  var stree    = desc.stat_desc.static_tree;
  var has_stree = desc.stat_desc.has_stree;
  var elems    = desc.stat_desc.elems;
  var n, m;          /* iterate over heap elements */
  var max_code = -1; /* largest code with non zero frequency */
  var node;          /* new node being created */

  /* Construct the initial heap, with least frequent element in
   * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
   * heap[0] is not used.
   */
  s.heap_len = 0;
  s.heap_max = HEAP_SIZE;

  for (n = 0; n < elems; n++) {
    if (tree[n * 2]/*.Freq*/ !== 0) {
      s.heap[++s.heap_len] = max_code = n;
      s.depth[n] = 0;

    } else {
      tree[n * 2 + 1]/*.Len*/ = 0;
    }
  }

  /* The pkzip format requires that at least one distance code exists,
   * and that at least one bit should be sent even if there is only one
   * possible code. So to avoid special checks later on we force at least
   * two codes of non zero frequency.
   */
  while (s.heap_len < 2) {
    node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
    tree[node * 2]/*.Freq*/ = 1;
    s.depth[node] = 0;
    s.opt_len--;

    if (has_stree) {
      s.static_len -= stree[node * 2 + 1]/*.Len*/;
    }
    /* node is 0 or 1 so it does not have extra bits */
  }
  desc.max_code = max_code;

  /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
   * establish sub-heaps of increasing lengths:
   */
  for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }

  /* Construct the Huffman tree by repeatedly combining the least two
   * frequent nodes.
   */
  node = elems;              /* next internal node of the tree */
  do {
    //pqremove(s, tree, n);  /* n = node of least frequency */
    /*** pqremove ***/
    n = s.heap[1/*SMALLEST*/];
    s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
    pqdownheap(s, tree, 1/*SMALLEST*/);
    /***/

    m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */

    s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
    s.heap[--s.heap_max] = m;

    /* Create a new node father of n and m */
    tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
    s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
    tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;

    /* and insert the new node in the heap */
    s.heap[1/*SMALLEST*/] = node++;
    pqdownheap(s, tree, 1/*SMALLEST*/);

  } while (s.heap_len >= 2);

  s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];

  /* At this point, the fields freq and dad are set. We can now
   * generate the bit lengths.
   */
  gen_bitlen(s, desc);

  /* The field len is now set, we can generate the bit codes */
  gen_codes(tree, max_code, s.bl_count);
}


/* ===========================================================================
 * Scan a literal or distance tree to determine the frequencies of the codes
 * in the bit length tree.
 */
function scan_tree(s, tree, max_code)
//    deflate_state *s;
//    ct_data *tree;   /* the tree to be scanned */
//    int max_code;    /* and its largest code of non zero frequency */
{
  var n;                     /* iterates over all tree elements */
  var prevlen = -1;          /* last emitted length */
  var curlen;                /* length of current code */

  var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */

  var count = 0;             /* repeat count of the current code */
  var max_count = 7;         /* max repeat count */
  var min_count = 4;         /* min repeat count */

  if (nextlen === 0) {
    max_count = 138;
    min_count = 3;
  }
  tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */

  for (n = 0; n <= max_code; n++) {
    curlen = nextlen;
    nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;

    if (++count < max_count && curlen === nextlen) {
      continue;

    } else if (count < min_count) {
      s.bl_tree[curlen * 2]/*.Freq*/ += count;

    } else if (curlen !== 0) {

      if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
      s.bl_tree[REP_3_6 * 2]/*.Freq*/++;

    } else if (count <= 10) {
      s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;

    } else {
      s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
    }

    count = 0;
    prevlen = curlen;

    if (nextlen === 0) {
      max_count = 138;
      min_count = 3;

    } else if (curlen === nextlen) {
      max_count = 6;
      min_count = 3;

    } else {
      max_count = 7;
      min_count = 4;
    }
  }
}


/* ===========================================================================
 * Send a literal or distance tree in compressed form, using the codes in
 * bl_tree.
 */
function send_tree(s, tree, max_code)
//    deflate_state *s;
//    ct_data *tree; /* the tree to be scanned */
//    int max_code;       /* and its largest code of non zero frequency */
{
  var n;                     /* iterates over all tree elements */
  var prevlen = -1;          /* last emitted length */
  var curlen;                /* length of current code */

  var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */

  var count = 0;             /* repeat count of the current code */
  var max_count = 7;         /* max repeat count */
  var min_count = 4;         /* min repeat count */

  /* tree[max_code+1].Len = -1; */  /* guard already set */
  if (nextlen === 0) {
    max_count = 138;
    min_count = 3;
  }

  for (n = 0; n <= max_code; n++) {
    curlen = nextlen;
    nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;

    if (++count < max_count && curlen === nextlen) {
      continue;

    } else if (count < min_count) {
      do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);

    } else if (curlen !== 0) {
      if (curlen !== prevlen) {
        send_code(s, curlen, s.bl_tree);
        count--;
      }
      //Assert(count >= 3 && count <= 6, " 3_6?");
      send_code(s, REP_3_6, s.bl_tree);
      send_bits(s, count - 3, 2);

    } else if (count <= 10) {
      send_code(s, REPZ_3_10, s.bl_tree);
      send_bits(s, count - 3, 3);

    } else {
      send_code(s, REPZ_11_138, s.bl_tree);
      send_bits(s, count - 11, 7);
    }

    count = 0;
    prevlen = curlen;
    if (nextlen === 0) {
      max_count = 138;
      min_count = 3;

    } else if (curlen === nextlen) {
      max_count = 6;
      min_count = 3;

    } else {
      max_count = 7;
      min_count = 4;
    }
  }
}


/* ===========================================================================
 * Construct the Huffman tree for the bit lengths and return the index in
 * bl_order of the last bit length code to send.
 */
function build_bl_tree(s) {
  var max_blindex;  /* index of last bit length code of non zero freq */

  /* Determine the bit length frequencies for literal and distance trees */
  scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  scan_tree(s, s.dyn_dtree, s.d_desc.max_code);

  /* Build the bit length tree: */
  build_tree(s, s.bl_desc);
  /* opt_len now includes the length of the tree representations, except
   * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
   */

  /* Determine the number of bit length codes to send. The pkzip format
   * requires that at least 4 bit length codes be sent. (appnote.txt says
   * 3 but the actual value used is 4.)
   */
  for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
    if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
      break;
    }
  }
  /* Update opt_len to include the bit length tree and counts */
  s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  //        s->opt_len, s->static_len));

  return max_blindex;
}


/* ===========================================================================
 * Send the header for a block using dynamic Huffman trees: the counts, the
 * lengths of the bit length codes, the literal tree and the distance tree.
 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
 */
function send_all_trees(s, lcodes, dcodes, blcodes)
//    deflate_state *s;
//    int lcodes, dcodes, blcodes; /* number of codes for each tree */
{
  var rank;                    /* index in bl_order */

  //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  //        "too many codes");
  //Tracev((stderr, "\nbl counts: "));
  send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
  send_bits(s, dcodes - 1,   5);
  send_bits(s, blcodes - 4,  4); /* not -3 as stated in appnote.txt */
  for (rank = 0; rank < blcodes; rank++) {
    //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
    send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
  }
  //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));

  send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
  //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));

  send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
  //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
}


/* ===========================================================================
 * Check if the data type is TEXT or BINARY, using the following algorithm:
 * - TEXT if the two conditions below are satisfied:
 *    a) There are no non-portable control characters belonging to the
 *       "black list" (0..6, 14..25, 28..31).
 *    b) There is at least one printable character belonging to the
 *       "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
 * - BINARY otherwise.
 * - The following partially-portable control characters form a
 *   "gray list" that is ignored in this detection algorithm:
 *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
 * IN assertion: the fields Freq of dyn_ltree are set.
 */
function detect_data_type(s) {
  /* black_mask is the bit mask of black-listed bytes
   * set bits 0..6, 14..25, and 28..31
   * 0xf3ffc07f = binary 11110011111111111100000001111111
   */
  var black_mask = 0xf3ffc07f;
  var n;

  /* Check for non-textual ("black-listed") bytes. */
  for (n = 0; n <= 31; n++, black_mask >>>= 1) {
    if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
      return Z_BINARY;
    }
  }

  /* Check for textual ("white-listed") bytes. */
  if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
      s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
    return Z_TEXT;
  }
  for (n = 32; n < LITERALS; n++) {
    if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
      return Z_TEXT;
    }
  }

  /* There are no "black-listed" or "white-listed" bytes:
   * this stream either is empty or has tolerated ("gray-listed") bytes only.
   */
  return Z_BINARY;
}


var static_init_done = false;

/* ===========================================================================
 * Initialize the tree data structures for a new zlib stream.
 */
function _tr_init(s)
{

  if (!static_init_done) {
    tr_static_init();
    static_init_done = true;
  }

  s.l_desc  = new TreeDesc(s.dyn_ltree, static_l_desc);
  s.d_desc  = new TreeDesc(s.dyn_dtree, static_d_desc);
  s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);

  s.bi_buf = 0;
  s.bi_valid = 0;

  /* Initialize the first block of the first file: */
  init_block(s);
}


/* ===========================================================================
 * Send a stored block
 */
function _tr_stored_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf;       /* input block */
//ulg stored_len;   /* length of input block */
//int last;         /* one if this is the last block for a file */
{
  send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3);    /* send block type */
  copy_block(s, buf, stored_len, true); /* with header */
}


/* ===========================================================================
 * Send one empty static block to give enough lookahead for inflate.
 * This takes 10 bits, of which 7 may remain in the bit buffer.
 */
function _tr_align(s) {
  send_bits(s, STATIC_TREES << 1, 3);
  send_code(s, END_BLOCK, static_ltree);
  bi_flush(s);
}


/* ===========================================================================
 * Determine the best encoding for the current block: dynamic trees, static
 * trees or store, and output the encoded block to the zip file.
 */
function _tr_flush_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf;       /* input block, or NULL if too old */
//ulg stored_len;   /* length of input block */
//int last;         /* one if this is the last block for a file */
{
  var opt_lenb, static_lenb;  /* opt_len and static_len in bytes */
  var max_blindex = 0;        /* index of last bit length code of non zero freq */

  /* Build the Huffman trees unless a stored block is forced */
  if (s.level > 0) {

    /* Check if the file is binary or text */
    if (s.strm.data_type === Z_UNKNOWN) {
      s.strm.data_type = detect_data_type(s);
    }

    /* Construct the literal and distance trees */
    build_tree(s, s.l_desc);
    // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
    //        s->static_len));

    build_tree(s, s.d_desc);
    // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
    //        s->static_len));
    /* At this point, opt_len and static_len are the total bit lengths of
     * the compressed block data, excluding the tree representations.
     */

    /* Build the bit length tree for the above two trees, and get the index
     * in bl_order of the last bit length code to send.
     */
    max_blindex = build_bl_tree(s);

    /* Determine the best encoding. Compute the block lengths in bytes. */
    opt_lenb = (s.opt_len + 3 + 7) >>> 3;
    static_lenb = (s.static_len + 3 + 7) >>> 3;

    // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
    //        opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
    //        s->last_lit));

    if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }

  } else {
    // Assert(buf != (char*)0, "lost buf");
    opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  }

  if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
    /* 4: two words for the lengths */

    /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
     * Otherwise we can't have processed more than WSIZE input bytes since
     * the last block flush, because compression would have been
     * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
     * transform a block into a stored block.
     */
    _tr_stored_block(s, buf, stored_len, last);

  } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {

    send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
    compress_block(s, static_ltree, static_dtree);

  } else {
    send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
    send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
    compress_block(s, s.dyn_ltree, s.dyn_dtree);
  }
  // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  /* The above check is made mod 2^32, for files larger than 512 MB
   * and uLong implemented on 32 bits.
   */
  init_block(s);

  if (last) {
    bi_windup(s);
  }
  // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  //       s->compressed_len-7*last));
}

/* ===========================================================================
 * Save the match info and tally the frequency counts. Return true if
 * the current block must be flushed.
 */
function _tr_tally(s, dist, lc)
//    deflate_state *s;
//    unsigned dist;  /* distance of matched string */
//    unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
{
  //var out_length, in_length, dcode;

  s.pending_buf[s.d_buf + s.last_lit * 2]     = (dist >>> 8) & 0xff;
  s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;

  s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  s.last_lit++;

  if (dist === 0) {
    /* lc is the unmatched char */
    s.dyn_ltree[lc * 2]/*.Freq*/++;
  } else {
    s.matches++;
    /* Here, lc is the match length - MIN_MATCH */
    dist--;             /* dist = match distance - 1 */
    //Assert((ush)dist < (ush)MAX_DIST(s) &&
    //       (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
    //       (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");

    s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
    s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  }

// (!) This block is disabled in zlib defaults,
// don't enable it for binary compatibility

//#ifdef TRUNCATE_BLOCK
//  /* Try to guess if it is profitable to stop the current block here */
//  if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
//    /* Compute an upper bound for the compressed length */
//    out_length = s.last_lit*8;
//    in_length = s.strstart - s.block_start;
//
//    for (dcode = 0; dcode < D_CODES; dcode++) {
//      out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
//    }
//    out_length >>>= 3;
//    //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
//    //       s->last_lit, in_length, out_length,
//    //       100L - out_length*100L/in_length));
//    if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
//      return true;
//    }
//  }
//#endif

  return (s.last_lit === s.lit_bufsize - 1);
  /* We avoid equality with lit_bufsize because of wraparound at 64K
   * on 16 bit machines and because stored blocks are restricted to
   * 64K-1 bytes.
   */
}

exports._tr_init  = _tr_init;
exports._tr_stored_block = _tr_stored_block;
exports._tr_flush_block  = _tr_flush_block;
exports._tr_tally = _tr_tally;
exports._tr_align = _tr_align;

},{"../utils/common":76}],86:[function(require,module,exports){
'use strict';

// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
//   claim that you wrote the original software. If you use this software
//   in a product, an acknowledgment in the product documentation would be
//   appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
//   misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.

function ZStream() {
  /* next input byte */
  this.input = null; // JS specific, because we have no pointers
  this.next_in = 0;
  /* number of bytes available at input */
  this.avail_in = 0;
  /* total number of input bytes read so far */
  this.total_in = 0;
  /* next output byte should be put there */
  this.output = null; // JS specific, because we have no pointers
  this.next_out = 0;
  /* remaining free space at output */
  this.avail_out = 0;
  /* total number of bytes output so far */
  this.total_out = 0;
  /* last error message, NULL if no error */
  this.msg = ''/*Z_NULL*/;
  /* not visible by applications */
  this.state = null;
  /* best guess about the data type: binary or text */
  this.data_type = 2/*Z_UNKNOWN*/;
  /* adler32 value of the uncompressed data */
  this.adler = 0;
}

module.exports = ZStream;

},{}],87:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};

// cached from whatever global is present so that test runners that stub it
// don't break things.  But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals.  It's inside a
// function because try/catches deoptimize in certain engines.

var cachedSetTimeout;
var cachedClearTimeout;

function defaultSetTimout() {
    throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
    throw new Error('clearTimeout has not been defined');
}
(function () {
    try {
        if (typeof setTimeout === 'function') {
            cachedSetTimeout = setTimeout;
        } else {
            cachedSetTimeout = defaultSetTimout;
        }
    } catch (e) {
        cachedSetTimeout = defaultSetTimout;
    }
    try {
        if (typeof clearTimeout === 'function') {
            cachedClearTimeout = clearTimeout;
        } else {
            cachedClearTimeout = defaultClearTimeout;
        }
    } catch (e) {
        cachedClearTimeout = defaultClearTimeout;
    }
} ())
function runTimeout(fun) {
    if (cachedSetTimeout === setTimeout) {
        //normal enviroments in sane situations
        return setTimeout(fun, 0);
    }
    // if setTimeout wasn't available but was latter defined
    if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
        cachedSetTimeout = setTimeout;
        return setTimeout(fun, 0);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedSetTimeout(fun, 0);
    } catch(e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
            return cachedSetTimeout.call(null, fun, 0);
        } catch(e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
            return cachedSetTimeout.call(this, fun, 0);
        }
    }


}
function runClearTimeout(marker) {
    if (cachedClearTimeout === clearTimeout) {
        //normal enviroments in sane situations
        return clearTimeout(marker);
    }
    // if clearTimeout wasn't available but was latter defined
    if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
        cachedClearTimeout = clearTimeout;
        return clearTimeout(marker);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedClearTimeout(marker);
    } catch (e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't  trust the global object when called normally
            return cachedClearTimeout.call(null, marker);
        } catch (e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
            // Some versions of I.E. have different rules for clearTimeout vs setTimeout
            return cachedClearTimeout.call(this, marker);
        }
    }



}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;

function cleanUpNextTick() {
    if (!draining || !currentQueue) {
        return;
    }
    draining = false;
    if (currentQueue.length) {
        queue = currentQueue.concat(queue);
    } else {
        queueIndex = -1;
    }
    if (queue.length) {
        drainQueue();
    }
}

function drainQueue() {
    if (draining) {
        return;
    }
    var timeout = runTimeout(cleanUpNextTick);
    draining = true;

    var len = queue.length;
    while(len) {
        currentQueue = queue;
        queue = [];
        while (++queueIndex < len) {
            if (currentQueue) {
                currentQueue[queueIndex].run();
            }
        }
        queueIndex = -1;
        len = queue.length;
    }
    currentQueue = null;
    draining = false;
    runClearTimeout(timeout);
}

process.nextTick = function (fun) {
    var args = new Array(arguments.length - 1);
    if (arguments.length > 1) {
        for (var i = 1; i < arguments.length; i++) {
            args[i - 1] = arguments[i];
        }
    }
    queue.push(new Item(fun, args));
    if (queue.length === 1 && !draining) {
        runTimeout(drainQueue);
    }
};

// v8 likes predictible objects
function Item(fun, array) {
    this.fun = fun;
    this.array = array;
}
Item.prototype.run = function () {
    this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};

function noop() {}

process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;

process.listeners = function (name) { return [] }

process.binding = function (name) {
    throw new Error('process.binding is not supported');
};

process.cwd = function () { return '/' };
process.chdir = function (dir) {
    throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };

},{}],88:[function(require,module,exports){
/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
/* eslint-disable node/no-deprecated-api */
var buffer = require('buffer')
var Buffer = buffer.Buffer

// alternative to using Object.keys for old browsers
function copyProps (src, dst) {
  for (var key in src) {
    dst[key] = src[key]
  }
}
if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  module.exports = buffer
} else {
  // Copy properties from require('buffer')
  copyProps(buffer, exports)
  exports.Buffer = SafeBuffer
}

function SafeBuffer (arg, encodingOrOffset, length) {
  return Buffer(arg, encodingOrOffset, length)
}

SafeBuffer.prototype = Object.create(Buffer.prototype)

// Copy static methods from Buffer
copyProps(Buffer, SafeBuffer)

SafeBuffer.from = function (arg, encodingOrOffset, length) {
  if (typeof arg === 'number') {
    throw new TypeError('Argument must not be a number')
  }
  return Buffer(arg, encodingOrOffset, length)
}

SafeBuffer.alloc = function (size, fill, encoding) {
  if (typeof size !== 'number') {
    throw new TypeError('Argument must be a number')
  }
  var buf = Buffer(size)
  if (fill !== undefined) {
    if (typeof encoding === 'string') {
      buf.fill(fill, encoding)
    } else {
      buf.fill(fill)
    }
  } else {
    buf.fill(0)
  }
  return buf
}

SafeBuffer.allocUnsafe = function (size) {
  if (typeof size !== 'number') {
    throw new TypeError('Argument must be a number')
  }
  return Buffer(size)
}

SafeBuffer.allocUnsafeSlow = function (size) {
  if (typeof size !== 'number') {
    throw new TypeError('Argument must be a number')
  }
  return buffer.SlowBuffer(size)
}

},{"buffer":"buffer"}],89:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

module.exports = Stream;

var EE = require('events').EventEmitter;
var inherits = require('inherits');

inherits(Stream, EE);
Stream.Readable = require('readable-stream/lib/_stream_readable.js');
Stream.Writable = require('readable-stream/lib/_stream_writable.js');
Stream.Duplex = require('readable-stream/lib/_stream_duplex.js');
Stream.Transform = require('readable-stream/lib/_stream_transform.js');
Stream.PassThrough = require('readable-stream/lib/_stream_passthrough.js');
Stream.finished = require('readable-stream/lib/internal/streams/end-of-stream.js')
Stream.pipeline = require('readable-stream/lib/internal/streams/pipeline.js')

// Backwards-compat with node 0.4.x
Stream.Stream = Stream;



// old-style streams.  Note that the pipe method (the only relevant
// part of this class) is overridden in the Readable class.

function Stream() {
  EE.call(this);
}

Stream.prototype.pipe = function(dest, options) {
  var source = this;

  function ondata(chunk) {
    if (dest.writable) {
      if (false === dest.write(chunk) && source.pause) {
        source.pause();
      }
    }
  }

  source.on('data', ondata);

  function ondrain() {
    if (source.readable && source.resume) {
      source.resume();
    }
  }

  dest.on('drain', ondrain);

  // If the 'end' option is not supplied, dest.end() will be called when
  // source gets the 'end' or 'close' events.  Only dest.end() once.
  if (!dest._isStdio && (!options || options.end !== false)) {
    source.on('end', onend);
    source.on('close', onclose);
  }

  var didOnEnd = false;
  function onend() {
    if (didOnEnd) return;
    didOnEnd = true;

    dest.end();
  }


  function onclose() {
    if (didOnEnd) return;
    didOnEnd = true;

    if (typeof dest.destroy === 'function') dest.destroy();
  }

  // don't leave dangling pipes when there are errors.
  function onerror(er) {
    cleanup();
    if (EE.listenerCount(this, 'error') === 0) {
      throw er; // Unhandled stream error in pipe.
    }
  }

  source.on('error', onerror);
  dest.on('error', onerror);

  // remove all the event listeners that were added.
  function cleanup() {
    source.removeListener('data', ondata);
    dest.removeListener('drain', ondrain);

    source.removeListener('end', onend);
    source.removeListener('close', onclose);

    source.removeListener('error', onerror);
    dest.removeListener('error', onerror);

    source.removeListener('end', cleanup);
    source.removeListener('close', cleanup);

    dest.removeListener('close', cleanup);
  }

  source.on('end', cleanup);
  source.on('close', cleanup);

  dest.on('close', cleanup);

  dest.emit('pipe', source);

  // Allow for unix-like usage: A.pipe(B).pipe(C)
  return dest;
};

},{"events":59,"inherits":70,"readable-stream/lib/_stream_duplex.js":91,"readable-stream/lib/_stream_passthrough.js":92,"readable-stream/lib/_stream_readable.js":93,"readable-stream/lib/_stream_transform.js":94,"readable-stream/lib/_stream_writable.js":95,"readable-stream/lib/internal/streams/end-of-stream.js":99,"readable-stream/lib/internal/streams/pipeline.js":101}],90:[function(require,module,exports){
'use strict';

function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }

var codes = {};

function createErrorType(code, message, Base) {
  if (!Base) {
    Base = Error;
  }

  function getMessage(arg1, arg2, arg3) {
    if (typeof message === 'string') {
      return message;
    } else {
      return message(arg1, arg2, arg3);
    }
  }

  var NodeError =
  /*#__PURE__*/
  function (_Base) {
    _inheritsLoose(NodeError, _Base);

    function NodeError(arg1, arg2, arg3) {
      return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
    }

    return NodeError;
  }(Base);

  NodeError.prototype.name = Base.name;
  NodeError.prototype.code = code;
  codes[code] = NodeError;
} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js


function oneOf(expected, thing) {
  if (Array.isArray(expected)) {
    var len = expected.length;
    expected = expected.map(function (i) {
      return String(i);
    });

    if (len > 2) {
      return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
    } else if (len === 2) {
      return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
    } else {
      return "of ".concat(thing, " ").concat(expected[0]);
    }
  } else {
    return "of ".concat(thing, " ").concat(String(expected));
  }
} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith


function startsWith(str, search, pos) {
  return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith


function endsWith(str, search, this_len) {
  if (this_len === undefined || this_len > str.length) {
    this_len = str.length;
  }

  return str.substring(this_len - search.length, this_len) === search;
} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes


function includes(str, search, start) {
  if (typeof start !== 'number') {
    start = 0;
  }

  if (start + search.length > str.length) {
    return false;
  } else {
    return str.indexOf(search, start) !== -1;
  }
}

createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
  return 'The value "' + value + '" is invalid for option "' + name + '"';
}, TypeError);
createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
  // determiner: 'must be' or 'must not be'
  var determiner;

  if (typeof expected === 'string' && startsWith(expected, 'not ')) {
    determiner = 'must not be';
    expected = expected.replace(/^not /, '');
  } else {
    determiner = 'must be';
  }

  var msg;

  if (endsWith(name, ' argument')) {
    // For cases like 'first argument'
    msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
  } else {
    var type = includes(name, '.') ? 'property' : 'argument';
    msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
  }

  msg += ". Received type ".concat(typeof actual);
  return msg;
}, TypeError);
createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
  return 'The ' + name + ' method is not implemented';
});
createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
createErrorType('ERR_STREAM_DESTROYED', function (name) {
  return 'Cannot call ' + name + ' after a stream was destroyed';
});
createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
  return 'Unknown encoding: ' + arg;
}, TypeError);
createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
module.exports.codes = codes;

},{}],91:[function(require,module,exports){
(function (process){(function (){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.

'use strict';

/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
  var keys = [];
  for (var key in obj) keys.push(key);
  return keys;
};
/*</replacement>*/

module.exports = Duplex;
var Readable = require('./_stream_readable');
var Writable = require('./_stream_writable');
require('inherits')(Duplex, Readable);
{
  // Allow the keys array to be GC'ed.
  var keys = objectKeys(Writable.prototype);
  for (var v = 0; v < keys.length; v++) {
    var method = keys[v];
    if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  }
}
function Duplex(options) {
  if (!(this instanceof Duplex)) return new Duplex(options);
  Readable.call(this, options);
  Writable.call(this, options);
  this.allowHalfOpen = true;
  if (options) {
    if (options.readable === false) this.readable = false;
    if (options.writable === false) this.writable = false;
    if (options.allowHalfOpen === false) {
      this.allowHalfOpen = false;
      this.once('end', onend);
    }
  }
}
Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function get() {
    return this._writableState.highWaterMark;
  }
});
Object.defineProperty(Duplex.prototype, 'writableBuffer', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function get() {
    return this._writableState && this._writableState.getBuffer();
  }
});
Object.defineProperty(Duplex.prototype, 'writableLength', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function get() {
    return this._writableState.length;
  }
});

// the no-half-open enforcer
function onend() {
  // If the writable side ended, then we're ok.
  if (this._writableState.ended) return;

  // no more data can be written.
  // But allow more writes to happen in this tick.
  process.nextTick(onEndNT, this);
}
function onEndNT(self) {
  self.end();
}
Object.defineProperty(Duplex.prototype, 'destroyed', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function get() {
    if (this._readableState === undefined || this._writableState === undefined) {
      return false;
    }
    return this._readableState.destroyed && this._writableState.destroyed;
  },
  set: function set(value) {
    // we ignore the value if the stream
    // has not been initialized yet
    if (this._readableState === undefined || this._writableState === undefined) {
      return;
    }

    // backward compatibility, the user is explicitly
    // managing destroyed
    this._readableState.destroyed = value;
    this._writableState.destroyed = value;
  }
});
}).call(this)}).call(this,require('_process'))
},{"./_stream_readable":93,"./_stream_writable":95,"_process":87,"inherits":70}],92:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.

'use strict';

module.exports = PassThrough;
var Transform = require('./_stream_transform');
require('inherits')(PassThrough, Transform);
function PassThrough(options) {
  if (!(this instanceof PassThrough)) return new PassThrough(options);
  Transform.call(this, options);
}
PassThrough.prototype._transform = function (chunk, encoding, cb) {
  cb(null, chunk);
};
},{"./_stream_transform":94,"inherits":70}],93:[function(require,module,exports){
(function (process,global){(function (){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

'use strict';

module.exports = Readable;

/*<replacement>*/
var Duplex;
/*</replacement>*/

Readable.ReadableState = ReadableState;

/*<replacement>*/
var EE = require('events').EventEmitter;
var EElistenerCount = function EElistenerCount(emitter, type) {
  return emitter.listeners(type).length;
};
/*</replacement>*/

/*<replacement>*/
var Stream = require('./internal/streams/stream');
/*</replacement>*/

var Buffer = require('buffer').Buffer;
var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
  return Buffer.from(chunk);
}
function _isUint8Array(obj) {
  return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}

/*<replacement>*/
var debugUtil = require('util');
var debug;
if (debugUtil && debugUtil.debuglog) {
  debug = debugUtil.debuglog('stream');
} else {
  debug = function debug() {};
}
/*</replacement>*/

var BufferList = require('./internal/streams/buffer_list');
var destroyImpl = require('./internal/streams/destroy');
var _require = require('./internal/streams/state'),
  getHighWaterMark = _require.getHighWaterMark;
var _require$codes = require('../errors').codes,
  ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
  ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
  ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
  ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;

// Lazy loaded to improve the startup performance.
var StringDecoder;
var createReadableStreamAsyncIterator;
var from;
require('inherits')(Readable, Stream);
var errorOrDestroy = destroyImpl.errorOrDestroy;
var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
function prependListener(emitter, event, fn) {
  // Sadly this is not cacheable as some libraries bundle their own
  // event emitter implementation with them.
  if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);

  // This is a hack to make sure that our error handler is attached before any
  // userland ones.  NEVER DO THIS. This is here only because this code needs
  // to continue to work with older versions of Node.js that do not include
  // the prependListener() method. The goal is to eventually remove this hack.
  if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
}
function ReadableState(options, stream, isDuplex) {
  Duplex = Duplex || require('./_stream_duplex');
  options = options || {};

  // Duplex streams are both readable and writable, but share
  // the same options object.
  // However, some cases require setting options to different
  // values for the readable and the writable sides of the duplex stream.
  // These options can be provided separately as readableXXX and writableXXX.
  if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex;

  // object stream flag. Used to make read(n) ignore n and to
  // make all the buffer merging and length checks go away
  this.objectMode = !!options.objectMode;
  if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;

  // the point at which it stops calling _read() to fill the buffer
  // Note: 0 is a valid value, means "don't call _read preemptively ever"
  this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex);

  // A linked list is used to store data chunks instead of an array because the
  // linked list can remove elements from the beginning faster than
  // array.shift()
  this.buffer = new BufferList();
  this.length = 0;
  this.pipes = null;
  this.pipesCount = 0;
  this.flowing = null;
  this.ended = false;
  this.endEmitted = false;
  this.reading = false;

  // a flag to be able to tell if the event 'readable'/'data' is emitted
  // immediately, or on a later tick.  We set this to true at first, because
  // any actions that shouldn't happen until "later" should generally also
  // not happen before the first read call.
  this.sync = true;

  // whenever we return null, then we set a flag to say
  // that we're awaiting a 'readable' event emission.
  this.needReadable = false;
  this.emittedReadable = false;
  this.readableListening = false;
  this.resumeScheduled = false;
  this.paused = true;

  // Should close be emitted on destroy. Defaults to true.
  this.emitClose = options.emitClose !== false;

  // Should .destroy() be called after 'end' (and potentially 'finish')
  this.autoDestroy = !!options.autoDestroy;

  // has it been destroyed
  this.destroyed = false;

  // Crypto is kind of old and crusty.  Historically, its default string
  // encoding is 'binary' so we have to make this configurable.
  // Everything else in the universe uses 'utf8', though.
  this.defaultEncoding = options.defaultEncoding || 'utf8';

  // the number of writers that are awaiting a drain event in .pipe()s
  this.awaitDrain = 0;

  // if true, a maybeReadMore has been scheduled
  this.readingMore = false;
  this.decoder = null;
  this.encoding = null;
  if (options.encoding) {
    if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
    this.decoder = new StringDecoder(options.encoding);
    this.encoding = options.encoding;
  }
}
function Readable(options) {
  Duplex = Duplex || require('./_stream_duplex');
  if (!(this instanceof Readable)) return new Readable(options);

  // Checking for a Stream.Duplex instance is faster here instead of inside
  // the ReadableState constructor, at least with V8 6.5
  var isDuplex = this instanceof Duplex;
  this._readableState = new ReadableState(options, this, isDuplex);

  // legacy
  this.readable = true;
  if (options) {
    if (typeof options.read === 'function') this._read = options.read;
    if (typeof options.destroy === 'function') this._destroy = options.destroy;
  }
  Stream.call(this);
}
Object.defineProperty(Readable.prototype, 'destroyed', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function get() {
    if (this._readableState === undefined) {
      return false;
    }
    return this._readableState.destroyed;
  },
  set: function set(value) {
    // we ignore the value if the stream
    // has not been initialized yet
    if (!this._readableState) {
      return;
    }

    // backward compatibility, the user is explicitly
    // managing destroyed
    this._readableState.destroyed = value;
  }
});
Readable.prototype.destroy = destroyImpl.destroy;
Readable.prototype._undestroy = destroyImpl.undestroy;
Readable.prototype._destroy = function (err, cb) {
  cb(err);
};

// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function (chunk, encoding) {
  var state = this._readableState;
  var skipChunkCheck;
  if (!state.objectMode) {
    if (typeof chunk === 'string') {
      encoding = encoding || state.defaultEncoding;
      if (encoding !== state.encoding) {
        chunk = Buffer.from(chunk, encoding);
        encoding = '';
      }
      skipChunkCheck = true;
    }
  } else {
    skipChunkCheck = true;
  }
  return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
};

// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function (chunk) {
  return readableAddChunk(this, chunk, null, true, false);
};
function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
  debug('readableAddChunk', chunk);
  var state = stream._readableState;
  if (chunk === null) {
    state.reading = false;
    onEofChunk(stream, state);
  } else {
    var er;
    if (!skipChunkCheck) er = chunkInvalid(state, chunk);
    if (er) {
      errorOrDestroy(stream, er);
    } else if (state.objectMode || chunk && chunk.length > 0) {
      if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
        chunk = _uint8ArrayToBuffer(chunk);
      }
      if (addToFront) {
        if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
      } else if (state.ended) {
        errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
      } else if (state.destroyed) {
        return false;
      } else {
        state.reading = false;
        if (state.decoder && !encoding) {
          chunk = state.decoder.write(chunk);
          if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
        } else {
          addChunk(stream, state, chunk, false);
        }
      }
    } else if (!addToFront) {
      state.reading = false;
      maybeReadMore(stream, state);
    }
  }

  // We can push more data if we are below the highWaterMark.
  // Also, if we have no data yet, we can stand some more bytes.
  // This is to work around cases where hwm=0, such as the repl.
  return !state.ended && (state.length < state.highWaterMark || state.length === 0);
}
function addChunk(stream, state, chunk, addToFront) {
  if (state.flowing && state.length === 0 && !state.sync) {
    state.awaitDrain = 0;
    stream.emit('data', chunk);
  } else {
    // update the buffer info.
    state.length += state.objectMode ? 1 : chunk.length;
    if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
    if (state.needReadable) emitReadable(stream);
  }
  maybeReadMore(stream, state);
}
function chunkInvalid(state, chunk) {
  var er;
  if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
    er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
  }
  return er;
}
Readable.prototype.isPaused = function () {
  return this._readableState.flowing === false;
};

// backwards compatibility.
Readable.prototype.setEncoding = function (enc) {
  if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  var decoder = new StringDecoder(enc);
  this._readableState.decoder = decoder;
  // If setEncoding(null), decoder.encoding equals utf8
  this._readableState.encoding = this._readableState.decoder.encoding;

  // Iterate over current buffer to convert already stored Buffers:
  var p = this._readableState.buffer.head;
  var content = '';
  while (p !== null) {
    content += decoder.write(p.data);
    p = p.next;
  }
  this._readableState.buffer.clear();
  if (content !== '') this._readableState.buffer.push(content);
  this._readableState.length = content.length;
  return this;
};

// Don't raise the hwm > 1GB
var MAX_HWM = 0x40000000;
function computeNewHighWaterMark(n) {
  if (n >= MAX_HWM) {
    // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.
    n = MAX_HWM;
  } else {
    // Get the next highest power of 2 to prevent increasing hwm excessively in
    // tiny amounts
    n--;
    n |= n >>> 1;
    n |= n >>> 2;
    n |= n >>> 4;
    n |= n >>> 8;
    n |= n >>> 16;
    n++;
  }
  return n;
}

// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function howMuchToRead(n, state) {
  if (n <= 0 || state.length === 0 && state.ended) return 0;
  if (state.objectMode) return 1;
  if (n !== n) {
    // Only flow one buffer at a time
    if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  }
  // If we're asking for more than the current hwm, then raise the hwm.
  if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  if (n <= state.length) return n;
  // Don't have enough
  if (!state.ended) {
    state.needReadable = true;
    return 0;
  }
  return state.length;
}

// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function (n) {
  debug('read', n);
  n = parseInt(n, 10);
  var state = this._readableState;
  var nOrig = n;
  if (n !== 0) state.emittedReadable = false;

  // if we're doing read(0) to trigger a readable event, but we
  // already have a bunch of data in the buffer, then just trigger
  // the 'readable' event and move on.
  if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
    debug('read: emitReadable', state.length, state.ended);
    if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
    return null;
  }
  n = howMuchToRead(n, state);

  // if we've ended, and we're now clear, then finish it up.
  if (n === 0 && state.ended) {
    if (state.length === 0) endReadable(this);
    return null;
  }

  // All the actual chunk generation logic needs to be
  // *below* the call to _read.  The reason is that in certain
  // synthetic stream cases, such as passthrough streams, _read
  // may be a completely synchronous operation which may change
  // the state of the read buffer, providing enough data when
  // before there was *not* enough.
  //
  // So, the steps are:
  // 1. Figure out what the state of things will be after we do
  // a read from the buffer.
  //
  // 2. If that resulting state will trigger a _read, then call _read.
  // Note that this may be asynchronous, or synchronous.  Yes, it is
  // deeply ugly to write APIs this way, but that still doesn't mean
  // that the Readable class should behave improperly, as streams are
  // designed to be sync/async agnostic.
  // Take note if the _read call is sync or async (ie, if the read call
  // has returned yet), so that we know whether or not it's safe to emit
  // 'readable' etc.
  //
  // 3. Actually pull the requested chunks out of the buffer and return.

  // if we need a readable event, then we need to do some reading.
  var doRead = state.needReadable;
  debug('need readable', doRead);

  // if we currently have less than the highWaterMark, then also read some
  if (state.length === 0 || state.length - n < state.highWaterMark) {
    doRead = true;
    debug('length less than watermark', doRead);
  }

  // however, if we've ended, then there's no point, and if we're already
  // reading, then it's unnecessary.
  if (state.ended || state.reading) {
    doRead = false;
    debug('reading or ended', doRead);
  } else if (doRead) {
    debug('do read');
    state.reading = true;
    state.sync = true;
    // if the length is currently zero, then we *need* a readable event.
    if (state.length === 0) state.needReadable = true;
    // call internal read method
    this._read(state.highWaterMark);
    state.sync = false;
    // If _read pushed data synchronously, then `reading` will be false,
    // and we need to re-evaluate how much data we can return to the user.
    if (!state.reading) n = howMuchToRead(nOrig, state);
  }
  var ret;
  if (n > 0) ret = fromList(n, state);else ret = null;
  if (ret === null) {
    state.needReadable = state.length <= state.highWaterMark;
    n = 0;
  } else {
    state.length -= n;
    state.awaitDrain = 0;
  }
  if (state.length === 0) {
    // If we have nothing in the buffer, then we want to know
    // as soon as we *do* get something into the buffer.
    if (!state.ended) state.needReadable = true;

    // If we tried to read() past the EOF, then emit end on the next tick.
    if (nOrig !== n && state.ended) endReadable(this);
  }
  if (ret !== null) this.emit('data', ret);
  return ret;
};
function onEofChunk(stream, state) {
  debug('onEofChunk');
  if (state.ended) return;
  if (state.decoder) {
    var chunk = state.decoder.end();
    if (chunk && chunk.length) {
      state.buffer.push(chunk);
      state.length += state.objectMode ? 1 : chunk.length;
    }
  }
  state.ended = true;
  if (state.sync) {
    // if we are sync, wait until next tick to emit the data.
    // Otherwise we risk emitting data in the flow()
    // the readable code triggers during a read() call
    emitReadable(stream);
  } else {
    // emit 'readable' now to make sure it gets picked up.
    state.needReadable = false;
    if (!state.emittedReadable) {
      state.emittedReadable = true;
      emitReadable_(stream);
    }
  }
}

// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow.  This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
  var state = stream._readableState;
  debug('emitReadable', state.needReadable, state.emittedReadable);
  state.needReadable = false;
  if (!state.emittedReadable) {
    debug('emitReadable', state.flowing);
    state.emittedReadable = true;
    process.nextTick(emitReadable_, stream);
  }
}
function emitReadable_(stream) {
  var state = stream._readableState;
  debug('emitReadable_', state.destroyed, state.length, state.ended);
  if (!state.destroyed && (state.length || state.ended)) {
    stream.emit('readable');
    state.emittedReadable = false;
  }

  // The stream needs another readable event if
  // 1. It is not flowing, as the flow mechanism will take
  //    care of it.
  // 2. It is not ended.
  // 3. It is below the highWaterMark, so we can schedule
  //    another readable later.
  state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
  flow(stream);
}

// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data.  that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
  if (!state.readingMore) {
    state.readingMore = true;
    process.nextTick(maybeReadMore_, stream, state);
  }
}
function maybeReadMore_(stream, state) {
  // Attempt to read more data if we should.
  //
  // The conditions for reading more data are (one of):
  // - Not enough data buffered (state.length < state.highWaterMark). The loop
  //   is responsible for filling the buffer with enough data if such data
  //   is available. If highWaterMark is 0 and we are not in the flowing mode
  //   we should _not_ attempt to buffer any extra data. We'll get more data
  //   when the stream consumer calls read() instead.
  // - No data in the buffer, and the stream is in flowing mode. In this mode
  //   the loop below is responsible for ensuring read() is called. Failing to
  //   call read here would abort the flow and there's no other mechanism for
  //   continuing the flow if the stream consumer has just subscribed to the
  //   'data' event.
  //
  // In addition to the above conditions to keep reading data, the following
  // conditions prevent the data from being read:
  // - The stream has ended (state.ended).
  // - There is already a pending 'read' operation (state.reading). This is a
  //   case where the the stream has called the implementation defined _read()
  //   method, but they are processing the call asynchronously and have _not_
  //   called push() with new data. In this case we skip performing more
  //   read()s. The execution ends in this method again after the _read() ends
  //   up calling push() with more data.
  while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
    var len = state.length;
    debug('maybeReadMore read 0');
    stream.read(0);
    if (len === state.length)
      // didn't get any data, stop spinning.
      break;
  }
  state.readingMore = false;
}

// abstract method.  to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function (n) {
  errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
};
Readable.prototype.pipe = function (dest, pipeOpts) {
  var src = this;
  var state = this._readableState;
  switch (state.pipesCount) {
    case 0:
      state.pipes = dest;
      break;
    case 1:
      state.pipes = [state.pipes, dest];
      break;
    default:
      state.pipes.push(dest);
      break;
  }
  state.pipesCount += 1;
  debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
  var endFn = doEnd ? onend : unpipe;
  if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
  dest.on('unpipe', onunpipe);
  function onunpipe(readable, unpipeInfo) {
    debug('onunpipe');
    if (readable === src) {
      if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
        unpipeInfo.hasUnpiped = true;
        cleanup();
      }
    }
  }
  function onend() {
    debug('onend');
    dest.end();
  }

  // when the dest drains, it reduces the awaitDrain counter
  // on the source.  This would be more elegant with a .once()
  // handler in flow(), but adding and removing repeatedly is
  // too slow.
  var ondrain = pipeOnDrain(src);
  dest.on('drain', ondrain);
  var cleanedUp = false;
  function cleanup() {
    debug('cleanup');
    // cleanup event handlers once the pipe is broken
    dest.removeListener('close', onclose);
    dest.removeListener('finish', onfinish);
    dest.removeListener('drain', ondrain);
    dest.removeListener('error', onerror);
    dest.removeListener('unpipe', onunpipe);
    src.removeListener('end', onend);
    src.removeListener('end', unpipe);
    src.removeListener('data', ondata);
    cleanedUp = true;

    // if the reader is waiting for a drain event from this
    // specific writer, then it would cause it to never start
    // flowing again.
    // So, if this is awaiting a drain, then we just call it now.
    // If we don't know, then assume that we are waiting for one.
    if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  }
  src.on('data', ondata);
  function ondata(chunk) {
    debug('ondata');
    var ret = dest.write(chunk);
    debug('dest.write', ret);
    if (ret === false) {
      // If the user unpiped during `dest.write()`, it is possible
      // to get stuck in a permanently paused state if that write
      // also returned false.
      // => Check whether `dest` is still a piping destination.
      if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
        debug('false write response, pause', state.awaitDrain);
        state.awaitDrain++;
      }
      src.pause();
    }
  }

  // if the dest has an error, then stop piping into it.
  // however, don't suppress the throwing behavior for this.
  function onerror(er) {
    debug('onerror', er);
    unpipe();
    dest.removeListener('error', onerror);
    if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);
  }

  // Make sure our error handler is attached before userland ones.
  prependListener(dest, 'error', onerror);

  // Both close and finish should trigger unpipe, but only once.
  function onclose() {
    dest.removeListener('finish', onfinish);
    unpipe();
  }
  dest.once('close', onclose);
  function onfinish() {
    debug('onfinish');
    dest.removeListener('close', onclose);
    unpipe();
  }
  dest.once('finish', onfinish);
  function unpipe() {
    debug('unpipe');
    src.unpipe(dest);
  }

  // tell the dest that it's being piped to
  dest.emit('pipe', src);

  // start the flow if it hasn't been started already.
  if (!state.flowing) {
    debug('pipe resume');
    src.resume();
  }
  return dest;
};
function pipeOnDrain(src) {
  return function pipeOnDrainFunctionResult() {
    var state = src._readableState;
    debug('pipeOnDrain', state.awaitDrain);
    if (state.awaitDrain) state.awaitDrain--;
    if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
      state.flowing = true;
      flow(src);
    }
  };
}
Readable.prototype.unpipe = function (dest) {
  var state = this._readableState;
  var unpipeInfo = {
    hasUnpiped: false
  };

  // if we're not piping anywhere, then do nothing.
  if (state.pipesCount === 0) return this;

  // just one destination.  most common case.
  if (state.pipesCount === 1) {
    // passed in one, but it's not the right one.
    if (dest && dest !== state.pipes) return this;
    if (!dest) dest = state.pipes;

    // got a match.
    state.pipes = null;
    state.pipesCount = 0;
    state.flowing = false;
    if (dest) dest.emit('unpipe', this, unpipeInfo);
    return this;
  }

  // slow case. multiple pipe destinations.

  if (!dest) {
    // remove all.
    var dests = state.pipes;
    var len = state.pipesCount;
    state.pipes = null;
    state.pipesCount = 0;
    state.flowing = false;
    for (var i = 0; i < len; i++) dests[i].emit('unpipe', this, {
      hasUnpiped: false
    });
    return this;
  }

  // try to find the right one.
  var index = indexOf(state.pipes, dest);
  if (index === -1) return this;
  state.pipes.splice(index, 1);
  state.pipesCount -= 1;
  if (state.pipesCount === 1) state.pipes = state.pipes[0];
  dest.emit('unpipe', this, unpipeInfo);
  return this;
};

// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function (ev, fn) {
  var res = Stream.prototype.on.call(this, ev, fn);
  var state = this._readableState;
  if (ev === 'data') {
    // update readableListening so that resume() may be a no-op
    // a few lines down. This is needed to support once('readable').
    state.readableListening = this.listenerCount('readable') > 0;

    // Try start flowing on next tick if stream isn't explicitly paused
    if (state.flowing !== false) this.resume();
  } else if (ev === 'readable') {
    if (!state.endEmitted && !state.readableListening) {
      state.readableListening = state.needReadable = true;
      state.flowing = false;
      state.emittedReadable = false;
      debug('on readable', state.length, state.reading);
      if (state.length) {
        emitReadable(this);
      } else if (!state.reading) {
        process.nextTick(nReadingNextTick, this);
      }
    }
  }
  return res;
};
Readable.prototype.addListener = Readable.prototype.on;
Readable.prototype.removeListener = function (ev, fn) {
  var res = Stream.prototype.removeListener.call(this, ev, fn);
  if (ev === 'readable') {
    // We need to check if there is someone still listening to
    // readable and reset the state. However this needs to happen
    // after readable has been emitted but before I/O (nextTick) to
    // support once('readable', fn) cycles. This means that calling
    // resume within the same tick will have no
    // effect.
    process.nextTick(updateReadableListening, this);
  }
  return res;
};
Readable.prototype.removeAllListeners = function (ev) {
  var res = Stream.prototype.removeAllListeners.apply(this, arguments);
  if (ev === 'readable' || ev === undefined) {
    // We need to check if there is someone still listening to
    // readable and reset the state. However this needs to happen
    // after readable has been emitted but before I/O (nextTick) to
    // support once('readable', fn) cycles. This means that calling
    // resume within the same tick will have no
    // effect.
    process.nextTick(updateReadableListening, this);
  }
  return res;
};
function updateReadableListening(self) {
  var state = self._readableState;
  state.readableListening = self.listenerCount('readable') > 0;
  if (state.resumeScheduled && !state.paused) {
    // flowing needs to be set to true now, otherwise
    // the upcoming resume will not flow.
    state.flowing = true;

    // crude way to check if we should resume
  } else if (self.listenerCount('data') > 0) {
    self.resume();
  }
}
function nReadingNextTick(self) {
  debug('readable nexttick read 0');
  self.read(0);
}

// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function () {
  var state = this._readableState;
  if (!state.flowing) {
    debug('resume');
    // we flow only if there is no one listening
    // for readable, but we still have to call
    // resume()
    state.flowing = !state.readableListening;
    resume(this, state);
  }
  state.paused = false;
  return this;
};
function resume(stream, state) {
  if (!state.resumeScheduled) {
    state.resumeScheduled = true;
    process.nextTick(resume_, stream, state);
  }
}
function resume_(stream, state) {
  debug('resume', state.reading);
  if (!state.reading) {
    stream.read(0);
  }
  state.resumeScheduled = false;
  stream.emit('resume');
  flow(stream);
  if (state.flowing && !state.reading) stream.read(0);
}
Readable.prototype.pause = function () {
  debug('call pause flowing=%j', this._readableState.flowing);
  if (this._readableState.flowing !== false) {
    debug('pause');
    this._readableState.flowing = false;
    this.emit('pause');
  }
  this._readableState.paused = true;
  return this;
};
function flow(stream) {
  var state = stream._readableState;
  debug('flow', state.flowing);
  while (state.flowing && stream.read() !== null);
}

// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function (stream) {
  var _this = this;
  var state = this._readableState;
  var paused = false;
  stream.on('end', function () {
    debug('wrapped end');
    if (state.decoder && !state.ended) {
      var chunk = state.decoder.end();
      if (chunk && chunk.length) _this.push(chunk);
    }
    _this.push(null);
  });
  stream.on('data', function (chunk) {
    debug('wrapped data');
    if (state.decoder) chunk = state.decoder.write(chunk);

    // don't skip over falsy values in objectMode
    if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
    var ret = _this.push(chunk);
    if (!ret) {
      paused = true;
      stream.pause();
    }
  });

  // proxy all the other methods.
  // important when wrapping filters and duplexes.
  for (var i in stream) {
    if (this[i] === undefined && typeof stream[i] === 'function') {
      this[i] = function methodWrap(method) {
        return function methodWrapReturnFunction() {
          return stream[method].apply(stream, arguments);
        };
      }(i);
    }
  }

  // proxy certain important events.
  for (var n = 0; n < kProxyEvents.length; n++) {
    stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
  }

  // when we try to consume some more bytes, simply unpause the
  // underlying stream.
  this._read = function (n) {
    debug('wrapped _read', n);
    if (paused) {
      paused = false;
      stream.resume();
    }
  };
  return this;
};
if (typeof Symbol === 'function') {
  Readable.prototype[Symbol.asyncIterator] = function () {
    if (createReadableStreamAsyncIterator === undefined) {
      createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');
    }
    return createReadableStreamAsyncIterator(this);
  };
}
Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function get() {
    return this._readableState.highWaterMark;
  }
});
Object.defineProperty(Readable.prototype, 'readableBuffer', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function get() {
    return this._readableState && this._readableState.buffer;
  }
});
Object.defineProperty(Readable.prototype, 'readableFlowing', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function get() {
    return this._readableState.flowing;
  },
  set: function set(state) {
    if (this._readableState) {
      this._readableState.flowing = state;
    }
  }
});

// exposed for testing purposes only.
Readable._fromList = fromList;
Object.defineProperty(Readable.prototype, 'readableLength', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function get() {
    return this._readableState.length;
  }
});

// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromList(n, state) {
  // nothing buffered
  if (state.length === 0) return null;
  var ret;
  if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
    // read it all, truncate the list
    if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
    state.buffer.clear();
  } else {
    // read part of list
    ret = state.buffer.consume(n, state.decoder);
  }
  return ret;
}
function endReadable(stream) {
  var state = stream._readableState;
  debug('endReadable', state.endEmitted);
  if (!state.endEmitted) {
    state.ended = true;
    process.nextTick(endReadableNT, state, stream);
  }
}
function endReadableNT(state, stream) {
  debug('endReadableNT', state.endEmitted, state.length);

  // Check that we didn't get one last unshift.
  if (!state.endEmitted && state.length === 0) {
    state.endEmitted = true;
    stream.readable = false;
    stream.emit('end');
    if (state.autoDestroy) {
      // In case of duplex streams we need a way to detect
      // if the writable side is ready for autoDestroy as well
      var wState = stream._writableState;
      if (!wState || wState.autoDestroy && wState.finished) {
        stream.destroy();
      }
    }
  }
}
if (typeof Symbol === 'function') {
  Readable.from = function (iterable, opts) {
    if (from === undefined) {
      from = require('./internal/streams/from');
    }
    return from(Readable, iterable, opts);
  };
}
function indexOf(xs, x) {
  for (var i = 0, l = xs.length; i < l; i++) {
    if (xs[i] === x) return i;
  }
  return -1;
}
}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"../errors":90,"./_stream_duplex":91,"./internal/streams/async_iterator":96,"./internal/streams/buffer_list":97,"./internal/streams/destroy":98,"./internal/streams/from":100,"./internal/streams/state":102,"./internal/streams/stream":103,"_process":87,"buffer":"buffer","events":59,"inherits":70,"string_decoder/":104,"util":54}],94:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

// a transform stream is a readable/writable stream where you do
// something with the data.  Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored.  (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation.  For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes.  When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up.  When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer.  When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks.  If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk.  However,
// a pathological inflate type of transform can cause excessive buffering
// here.  For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output.  Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output.  In this case, you could write a very small
// amount of input, and end up with a very large amount of output.  In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform.  A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.

'use strict';

module.exports = Transform;
var _require$codes = require('../errors').codes,
  ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
  ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
  ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
  ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
var Duplex = require('./_stream_duplex');
require('inherits')(Transform, Duplex);
function afterTransform(er, data) {
  var ts = this._transformState;
  ts.transforming = false;
  var cb = ts.writecb;
  if (cb === null) {
    return this.emit('error', new ERR_MULTIPLE_CALLBACK());
  }
  ts.writechunk = null;
  ts.writecb = null;
  if (data != null)
    // single equals check for both `null` and `undefined`
    this.push(data);
  cb(er);
  var rs = this._readableState;
  rs.reading = false;
  if (rs.needReadable || rs.length < rs.highWaterMark) {
    this._read(rs.highWaterMark);
  }
}
function Transform(options) {
  if (!(this instanceof Transform)) return new Transform(options);
  Duplex.call(this, options);
  this._transformState = {
    afterTransform: afterTransform.bind(this),
    needTransform: false,
    transforming: false,
    writecb: null,
    writechunk: null,
    writeencoding: null
  };

  // start out asking for a readable event once data is transformed.
  this._readableState.needReadable = true;

  // we have implemented the _read method, and done the other things
  // that Readable wants before the first _read call, so unset the
  // sync guard flag.
  this._readableState.sync = false;
  if (options) {
    if (typeof options.transform === 'function') this._transform = options.transform;
    if (typeof options.flush === 'function') this._flush = options.flush;
  }

  // When the writable side finishes, then flush out anything remaining.
  this.on('prefinish', prefinish);
}
function prefinish() {
  var _this = this;
  if (typeof this._flush === 'function' && !this._readableState.destroyed) {
    this._flush(function (er, data) {
      done(_this, er, data);
    });
  } else {
    done(this, null, null);
  }
}
Transform.prototype.push = function (chunk, encoding) {
  this._transformState.needTransform = false;
  return Duplex.prototype.push.call(this, chunk, encoding);
};

// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side.  You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk.  If you pass
// an error, then that'll put the hurt on the whole operation.  If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function (chunk, encoding, cb) {
  cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
};
Transform.prototype._write = function (chunk, encoding, cb) {
  var ts = this._transformState;
  ts.writecb = cb;
  ts.writechunk = chunk;
  ts.writeencoding = encoding;
  if (!ts.transforming) {
    var rs = this._readableState;
    if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  }
};

// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function (n) {
  var ts = this._transformState;
  if (ts.writechunk !== null && !ts.transforming) {
    ts.transforming = true;
    this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  } else {
    // mark that we need a transform, so that any data that comes in
    // will get processed, now that we've asked for it.
    ts.needTransform = true;
  }
};
Transform.prototype._destroy = function (err, cb) {
  Duplex.prototype._destroy.call(this, err, function (err2) {
    cb(err2);
  });
};
function done(stream, er, data) {
  if (er) return stream.emit('error', er);
  if (data != null)
    // single equals check for both `null` and `undefined`
    stream.push(data);

  // TODO(BridgeAR): Write a test for these two error cases
  // if there's nothing in the write buffer, then that means
  // that nothing more will ever be provided
  if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
  if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
  return stream.push(null);
}
},{"../errors":90,"./_stream_duplex":91,"inherits":70}],95:[function(require,module,exports){
(function (process,global){(function (){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

// A bit simpler than readable streams.
// Implement an async ._write(chunk, encoding, cb), and it'll handle all
// the drain event emission and buffering.

'use strict';

module.exports = Writable;

/* <replacement> */
function WriteReq(chunk, encoding, cb) {
  this.chunk = chunk;
  this.encoding = encoding;
  this.callback = cb;
  this.next = null;
}

// It seems a linked list but it is not
// there will be only 2 of these for each stream
function CorkedRequest(state) {
  var _this = this;
  this.next = null;
  this.entry = null;
  this.finish = function () {
    onCorkedFinish(_this, state);
  };
}
/* </replacement> */

/*<replacement>*/
var Duplex;
/*</replacement>*/

Writable.WritableState = WritableState;

/*<replacement>*/
var internalUtil = {
  deprecate: require('util-deprecate')
};
/*</replacement>*/

/*<replacement>*/
var Stream = require('./internal/streams/stream');
/*</replacement>*/

var Buffer = require('buffer').Buffer;
var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
  return Buffer.from(chunk);
}
function _isUint8Array(obj) {
  return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}
var destroyImpl = require('./internal/streams/destroy');
var _require = require('./internal/streams/state'),
  getHighWaterMark = _require.getHighWaterMark;
var _require$codes = require('../errors').codes,
  ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
  ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
  ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
  ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
  ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
  ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
  ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
  ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
var errorOrDestroy = destroyImpl.errorOrDestroy;
require('inherits')(Writable, Stream);
function nop() {}
function WritableState(options, stream, isDuplex) {
  Duplex = Duplex || require('./_stream_duplex');
  options = options || {};

  // Duplex streams are both readable and writable, but share
  // the same options object.
  // However, some cases require setting options to different
  // values for the readable and the writable sides of the duplex stream,
  // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
  if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex;

  // object stream flag to indicate whether or not this stream
  // contains buffers or objects.
  this.objectMode = !!options.objectMode;
  if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;

  // the point at which write() starts returning false
  // Note: 0 is a valid value, means that we always return false if
  // the entire buffer is not flushed immediately on write()
  this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex);

  // if _final has been called
  this.finalCalled = false;

  // drain event flag.
  this.needDrain = false;
  // at the start of calling end()
  this.ending = false;
  // when end() has been called, and returned
  this.ended = false;
  // when 'finish' is emitted
  this.finished = false;

  // has it been destroyed
  this.destroyed = false;

  // should we decode strings into buffers before passing to _write?
  // this is here so that some node-core streams can optimize string
  // handling at a lower level.
  var noDecode = options.decodeStrings === false;
  this.decodeStrings = !noDecode;

  // Crypto is kind of old and crusty.  Historically, its default string
  // encoding is 'binary' so we have to make this configurable.
  // Everything else in the universe uses 'utf8', though.
  this.defaultEncoding = options.defaultEncoding || 'utf8';

  // not an actual buffer we keep track of, but a measurement
  // of how much we're waiting to get pushed to some underlying
  // socket or file.
  this.length = 0;

  // a flag to see when we're in the middle of a write.
  this.writing = false;

  // when true all writes will be buffered until .uncork() call
  this.corked = 0;

  // a flag to be able to tell if the onwrite cb is called immediately,
  // or on a later tick.  We set this to true at first, because any
  // actions that shouldn't happen until "later" should generally also
  // not happen before the first write call.
  this.sync = true;

  // a flag to know if we're processing previously buffered items, which
  // may call the _write() callback in the same tick, so that we don't
  // end up in an overlapped onwrite situation.
  this.bufferProcessing = false;

  // the callback that's passed to _write(chunk,cb)
  this.onwrite = function (er) {
    onwrite(stream, er);
  };

  // the callback that the user supplies to write(chunk,encoding,cb)
  this.writecb = null;

  // the amount that is being written when _write is called.
  this.writelen = 0;
  this.bufferedRequest = null;
  this.lastBufferedRequest = null;

  // number of pending user-supplied write callbacks
  // this must be 0 before 'finish' can be emitted
  this.pendingcb = 0;

  // emit prefinish if the only thing we're waiting for is _write cbs
  // This is relevant for synchronous Transform streams
  this.prefinished = false;

  // True if the error was already emitted and should not be thrown again
  this.errorEmitted = false;

  // Should close be emitted on destroy. Defaults to true.
  this.emitClose = options.emitClose !== false;

  // Should .destroy() be called after 'finish' (and potentially 'end')
  this.autoDestroy = !!options.autoDestroy;

  // count buffered requests
  this.bufferedRequestCount = 0;

  // allocate the first CorkedRequest, there is always
  // one allocated and free to use, and we maintain at most two
  this.corkedRequestsFree = new CorkedRequest(this);
}
WritableState.prototype.getBuffer = function getBuffer() {
  var current = this.bufferedRequest;
  var out = [];
  while (current) {
    out.push(current);
    current = current.next;
  }
  return out;
};
(function () {
  try {
    Object.defineProperty(WritableState.prototype, 'buffer', {
      get: internalUtil.deprecate(function writableStateBufferGetter() {
        return this.getBuffer();
      }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
    });
  } catch (_) {}
})();

// Test _writableState for inheritance to account for Duplex streams,
// whose prototype chain only points to Readable.
var realHasInstance;
if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
  realHasInstance = Function.prototype[Symbol.hasInstance];
  Object.defineProperty(Writable, Symbol.hasInstance, {
    value: function value(object) {
      if (realHasInstance.call(this, object)) return true;
      if (this !== Writable) return false;
      return object && object._writableState instanceof WritableState;
    }
  });
} else {
  realHasInstance = function realHasInstance(object) {
    return object instanceof this;
  };
}
function Writable(options) {
  Duplex = Duplex || require('./_stream_duplex');

  // Writable ctor is applied to Duplexes, too.
  // `realHasInstance` is necessary because using plain `instanceof`
  // would return false, as no `_writableState` property is attached.

  // Trying to use the custom `instanceof` for Writable here will also break the
  // Node.js LazyTransform implementation, which has a non-trivial getter for
  // `_writableState` that would lead to infinite recursion.

  // Checking for a Stream.Duplex instance is faster here instead of inside
  // the WritableState constructor, at least with V8 6.5
  var isDuplex = this instanceof Duplex;
  if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
  this._writableState = new WritableState(options, this, isDuplex);

  // legacy.
  this.writable = true;
  if (options) {
    if (typeof options.write === 'function') this._write = options.write;
    if (typeof options.writev === 'function') this._writev = options.writev;
    if (typeof options.destroy === 'function') this._destroy = options.destroy;
    if (typeof options.final === 'function') this._final = options.final;
  }
  Stream.call(this);
}

// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function () {
  errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
};
function writeAfterEnd(stream, cb) {
  var er = new ERR_STREAM_WRITE_AFTER_END();
  // TODO: defer error events consistently everywhere, not just the cb
  errorOrDestroy(stream, er);
  process.nextTick(cb, er);
}

// Checks that a user-supplied chunk is valid, especially for the particular
// mode the stream is in. Currently this means that `null` is never accepted
// and undefined/non-string values are only allowed in object mode.
function validChunk(stream, state, chunk, cb) {
  var er;
  if (chunk === null) {
    er = new ERR_STREAM_NULL_VALUES();
  } else if (typeof chunk !== 'string' && !state.objectMode) {
    er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
  }
  if (er) {
    errorOrDestroy(stream, er);
    process.nextTick(cb, er);
    return false;
  }
  return true;
}
Writable.prototype.write = function (chunk, encoding, cb) {
  var state = this._writableState;
  var ret = false;
  var isBuf = !state.objectMode && _isUint8Array(chunk);
  if (isBuf && !Buffer.isBuffer(chunk)) {
    chunk = _uint8ArrayToBuffer(chunk);
  }
  if (typeof encoding === 'function') {
    cb = encoding;
    encoding = null;
  }
  if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
  if (typeof cb !== 'function') cb = nop;
  if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
    state.pendingcb++;
    ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  }
  return ret;
};
Writable.prototype.cork = function () {
  this._writableState.corked++;
};
Writable.prototype.uncork = function () {
  var state = this._writableState;
  if (state.corked) {
    state.corked--;
    if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  }
};
Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  // node::ParseEncoding() requires lower case.
  if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);
  this._writableState.defaultEncoding = encoding;
  return this;
};
Object.defineProperty(Writable.prototype, 'writableBuffer', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function get() {
    return this._writableState && this._writableState.getBuffer();
  }
});
function decodeChunk(state, chunk, encoding) {
  if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
    chunk = Buffer.from(chunk, encoding);
  }
  return chunk;
}
Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function get() {
    return this._writableState.highWaterMark;
  }
});

// if we're already writing something, then just put this
// in the queue, and wait our turn.  Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  if (!isBuf) {
    var newChunk = decodeChunk(state, chunk, encoding);
    if (chunk !== newChunk) {
      isBuf = true;
      encoding = 'buffer';
      chunk = newChunk;
    }
  }
  var len = state.objectMode ? 1 : chunk.length;
  state.length += len;
  var ret = state.length < state.highWaterMark;
  // we must ensure that previous needDrain will not be reset to false.
  if (!ret) state.needDrain = true;
  if (state.writing || state.corked) {
    var last = state.lastBufferedRequest;
    state.lastBufferedRequest = {
      chunk: chunk,
      encoding: encoding,
      isBuf: isBuf,
      callback: cb,
      next: null
    };
    if (last) {
      last.next = state.lastBufferedRequest;
    } else {
      state.bufferedRequest = state.lastBufferedRequest;
    }
    state.bufferedRequestCount += 1;
  } else {
    doWrite(stream, state, false, len, chunk, encoding, cb);
  }
  return ret;
}
function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  state.writelen = len;
  state.writecb = cb;
  state.writing = true;
  state.sync = true;
  if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  state.sync = false;
}
function onwriteError(stream, state, sync, er, cb) {
  --state.pendingcb;
  if (sync) {
    // defer the callback if we are being called synchronously
    // to avoid piling up things on the stack
    process.nextTick(cb, er);
    // this can emit finish, and it will always happen
    // after error
    process.nextTick(finishMaybe, stream, state);
    stream._writableState.errorEmitted = true;
    errorOrDestroy(stream, er);
  } else {
    // the caller expect this to happen before if
    // it is async
    cb(er);
    stream._writableState.errorEmitted = true;
    errorOrDestroy(stream, er);
    // this can emit finish, but finish must
    // always follow error
    finishMaybe(stream, state);
  }
}
function onwriteStateUpdate(state) {
  state.writing = false;
  state.writecb = null;
  state.length -= state.writelen;
  state.writelen = 0;
}
function onwrite(stream, er) {
  var state = stream._writableState;
  var sync = state.sync;
  var cb = state.writecb;
  if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
  onwriteStateUpdate(state);
  if (er) onwriteError(stream, state, sync, er, cb);else {
    // Check if we're actually ready to finish, but don't emit yet
    var finished = needFinish(state) || stream.destroyed;
    if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
      clearBuffer(stream, state);
    }
    if (sync) {
      process.nextTick(afterWrite, stream, state, finished, cb);
    } else {
      afterWrite(stream, state, finished, cb);
    }
  }
}
function afterWrite(stream, state, finished, cb) {
  if (!finished) onwriteDrain(stream, state);
  state.pendingcb--;
  cb();
  finishMaybe(stream, state);
}

// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
  if (state.length === 0 && state.needDrain) {
    state.needDrain = false;
    stream.emit('drain');
  }
}

// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
  state.bufferProcessing = true;
  var entry = state.bufferedRequest;
  if (stream._writev && entry && entry.next) {
    // Fast case, write everything using _writev()
    var l = state.bufferedRequestCount;
    var buffer = new Array(l);
    var holder = state.corkedRequestsFree;
    holder.entry = entry;
    var count = 0;
    var allBuffers = true;
    while (entry) {
      buffer[count] = entry;
      if (!entry.isBuf) allBuffers = false;
      entry = entry.next;
      count += 1;
    }
    buffer.allBuffers = allBuffers;
    doWrite(stream, state, true, state.length, buffer, '', holder.finish);

    // doWrite is almost always async, defer these to save a bit of time
    // as the hot path ends with doWrite
    state.pendingcb++;
    state.lastBufferedRequest = null;
    if (holder.next) {
      state.corkedRequestsFree = holder.next;
      holder.next = null;
    } else {
      state.corkedRequestsFree = new CorkedRequest(state);
    }
    state.bufferedRequestCount = 0;
  } else {
    // Slow case, write chunks one-by-one
    while (entry) {
      var chunk = entry.chunk;
      var encoding = entry.encoding;
      var cb = entry.callback;
      var len = state.objectMode ? 1 : chunk.length;
      doWrite(stream, state, false, len, chunk, encoding, cb);
      entry = entry.next;
      state.bufferedRequestCount--;
      // if we didn't call the onwrite immediately, then
      // it means that we need to wait until it does.
      // also, that means that the chunk and cb are currently
      // being processed, so move the buffer counter past them.
      if (state.writing) {
        break;
      }
    }
    if (entry === null) state.lastBufferedRequest = null;
  }
  state.bufferedRequest = entry;
  state.bufferProcessing = false;
}
Writable.prototype._write = function (chunk, encoding, cb) {
  cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
};
Writable.prototype._writev = null;
Writable.prototype.end = function (chunk, encoding, cb) {
  var state = this._writableState;
  if (typeof chunk === 'function') {
    cb = chunk;
    chunk = null;
    encoding = null;
  } else if (typeof encoding === 'function') {
    cb = encoding;
    encoding = null;
  }
  if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);

  // .end() fully uncorks
  if (state.corked) {
    state.corked = 1;
    this.uncork();
  }

  // ignore unnecessary end() calls.
  if (!state.ending) endWritable(this, state, cb);
  return this;
};
Object.defineProperty(Writable.prototype, 'writableLength', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function get() {
    return this._writableState.length;
  }
});
function needFinish(state) {
  return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
}
function callFinal(stream, state) {
  stream._final(function (err) {
    state.pendingcb--;
    if (err) {
      errorOrDestroy(stream, err);
    }
    state.prefinished = true;
    stream.emit('prefinish');
    finishMaybe(stream, state);
  });
}
function prefinish(stream, state) {
  if (!state.prefinished && !state.finalCalled) {
    if (typeof stream._final === 'function' && !state.destroyed) {
      state.pendingcb++;
      state.finalCalled = true;
      process.nextTick(callFinal, stream, state);
    } else {
      state.prefinished = true;
      stream.emit('prefinish');
    }
  }
}
function finishMaybe(stream, state) {
  var need = needFinish(state);
  if (need) {
    prefinish(stream, state);
    if (state.pendingcb === 0) {
      state.finished = true;
      stream.emit('finish');
      if (state.autoDestroy) {
        // In case of duplex streams we need a way to detect
        // if the readable side is ready for autoDestroy as well
        var rState = stream._readableState;
        if (!rState || rState.autoDestroy && rState.endEmitted) {
          stream.destroy();
        }
      }
    }
  }
  return need;
}
function endWritable(stream, state, cb) {
  state.ending = true;
  finishMaybe(stream, state);
  if (cb) {
    if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
  }
  state.ended = true;
  stream.writable = false;
}
function onCorkedFinish(corkReq, state, err) {
  var entry = corkReq.entry;
  corkReq.entry = null;
  while (entry) {
    var cb = entry.callback;
    state.pendingcb--;
    cb(err);
    entry = entry.next;
  }

  // reuse the free corkReq.
  state.corkedRequestsFree.next = corkReq;
}
Object.defineProperty(Writable.prototype, 'destroyed', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function get() {
    if (this._writableState === undefined) {
      return false;
    }
    return this._writableState.destroyed;
  },
  set: function set(value) {
    // we ignore the value if the stream
    // has not been initialized yet
    if (!this._writableState) {
      return;
    }

    // backward compatibility, the user is explicitly
    // managing destroyed
    this._writableState.destroyed = value;
  }
});
Writable.prototype.destroy = destroyImpl.destroy;
Writable.prototype._undestroy = destroyImpl.undestroy;
Writable.prototype._destroy = function (err, cb) {
  cb(err);
};
}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"../errors":90,"./_stream_duplex":91,"./internal/streams/destroy":98,"./internal/streams/state":102,"./internal/streams/stream":103,"_process":87,"buffer":"buffer","inherits":70,"util-deprecate":106}],96:[function(require,module,exports){
(function (process){(function (){
'use strict';

var _Object$setPrototypeO;
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
var finished = require('./end-of-stream');
var kLastResolve = Symbol('lastResolve');
var kLastReject = Symbol('lastReject');
var kError = Symbol('error');
var kEnded = Symbol('ended');
var kLastPromise = Symbol('lastPromise');
var kHandlePromise = Symbol('handlePromise');
var kStream = Symbol('stream');
function createIterResult(value, done) {
  return {
    value: value,
    done: done
  };
}
function readAndResolve(iter) {
  var resolve = iter[kLastResolve];
  if (resolve !== null) {
    var data = iter[kStream].read();
    // we defer if data is null
    // we can be expecting either 'end' or
    // 'error'
    if (data !== null) {
      iter[kLastPromise] = null;
      iter[kLastResolve] = null;
      iter[kLastReject] = null;
      resolve(createIterResult(data, false));
    }
  }
}
function onReadable(iter) {
  // we wait for the next tick, because it might
  // emit an error with process.nextTick
  process.nextTick(readAndResolve, iter);
}
function wrapForNext(lastPromise, iter) {
  return function (resolve, reject) {
    lastPromise.then(function () {
      if (iter[kEnded]) {
        resolve(createIterResult(undefined, true));
        return;
      }
      iter[kHandlePromise](resolve, reject);
    }, reject);
  };
}
var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
  get stream() {
    return this[kStream];
  },
  next: function next() {
    var _this = this;
    // if we have detected an error in the meanwhile
    // reject straight away
    var error = this[kError];
    if (error !== null) {
      return Promise.reject(error);
    }
    if (this[kEnded]) {
      return Promise.resolve(createIterResult(undefined, true));
    }
    if (this[kStream].destroyed) {
      // We need to defer via nextTick because if .destroy(err) is
      // called, the error will be emitted via nextTick, and
      // we cannot guarantee that there is no error lingering around
      // waiting to be emitted.
      return new Promise(function (resolve, reject) {
        process.nextTick(function () {
          if (_this[kError]) {
            reject(_this[kError]);
          } else {
            resolve(createIterResult(undefined, true));
          }
        });
      });
    }

    // if we have multiple next() calls
    // we will wait for the previous Promise to finish
    // this logic is optimized to support for await loops,
    // where next() is only called once at a time
    var lastPromise = this[kLastPromise];
    var promise;
    if (lastPromise) {
      promise = new Promise(wrapForNext(lastPromise, this));
    } else {
      // fast path needed to support multiple this.push()
      // without triggering the next() queue
      var data = this[kStream].read();
      if (data !== null) {
        return Promise.resolve(createIterResult(data, false));
      }
      promise = new Promise(this[kHandlePromise]);
    }
    this[kLastPromise] = promise;
    return promise;
  }
}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
  return this;
}), _defineProperty(_Object$setPrototypeO, "return", function _return() {
  var _this2 = this;
  // destroy(err, cb) is a private API
  // we can guarantee we have that here, because we control the
  // Readable class this is attached to
  return new Promise(function (resolve, reject) {
    _this2[kStream].destroy(null, function (err) {
      if (err) {
        reject(err);
        return;
      }
      resolve(createIterResult(undefined, true));
    });
  });
}), _Object$setPrototypeO), AsyncIteratorPrototype);
var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
  var _Object$create;
  var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
    value: stream,
    writable: true
  }), _defineProperty(_Object$create, kLastResolve, {
    value: null,
    writable: true
  }), _defineProperty(_Object$create, kLastReject, {
    value: null,
    writable: true
  }), _defineProperty(_Object$create, kError, {
    value: null,
    writable: true
  }), _defineProperty(_Object$create, kEnded, {
    value: stream._readableState.endEmitted,
    writable: true
  }), _defineProperty(_Object$create, kHandlePromise, {
    value: function value(resolve, reject) {
      var data = iterator[kStream].read();
      if (data) {
        iterator[kLastPromise] = null;
        iterator[kLastResolve] = null;
        iterator[kLastReject] = null;
        resolve(createIterResult(data, false));
      } else {
        iterator[kLastResolve] = resolve;
        iterator[kLastReject] = reject;
      }
    },
    writable: true
  }), _Object$create));
  iterator[kLastPromise] = null;
  finished(stream, function (err) {
    if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
      var reject = iterator[kLastReject];
      // reject if we are waiting for data in the Promise
      // returned by next() and store the error
      if (reject !== null) {
        iterator[kLastPromise] = null;
        iterator[kLastResolve] = null;
        iterator[kLastReject] = null;
        reject(err);
      }
      iterator[kError] = err;
      return;
    }
    var resolve = iterator[kLastResolve];
    if (resolve !== null) {
      iterator[kLastPromise] = null;
      iterator[kLastResolve] = null;
      iterator[kLastReject] = null;
      resolve(createIterResult(undefined, true));
    }
    iterator[kEnded] = true;
  });
  stream.on('readable', onReadable.bind(null, iterator));
  return iterator;
};
module.exports = createReadableStreamAsyncIterator;
}).call(this)}).call(this,require('_process'))
},{"./end-of-stream":99,"_process":87}],97:[function(require,module,exports){
'use strict';

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
var _require = require('buffer'),
  Buffer = _require.Buffer;
var _require2 = require('util'),
  inspect = _require2.inspect;
var custom = inspect && inspect.custom || 'inspect';
function copyBuffer(src, target, offset) {
  Buffer.prototype.copy.call(src, target, offset);
}
module.exports = /*#__PURE__*/function () {
  function BufferList() {
    _classCallCheck(this, BufferList);
    this.head = null;
    this.tail = null;
    this.length = 0;
  }
  _createClass(BufferList, [{
    key: "push",
    value: function push(v) {
      var entry = {
        data: v,
        next: null
      };
      if (this.length > 0) this.tail.next = entry;else this.head = entry;
      this.tail = entry;
      ++this.length;
    }
  }, {
    key: "unshift",
    value: function unshift(v) {
      var entry = {
        data: v,
        next: this.head
      };
      if (this.length === 0) this.tail = entry;
      this.head = entry;
      ++this.length;
    }
  }, {
    key: "shift",
    value: function shift() {
      if (this.length === 0) return;
      var ret = this.head.data;
      if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
      --this.length;
      return ret;
    }
  }, {
    key: "clear",
    value: function clear() {
      this.head = this.tail = null;
      this.length = 0;
    }
  }, {
    key: "join",
    value: function join(s) {
      if (this.length === 0) return '';
      var p = this.head;
      var ret = '' + p.data;
      while (p = p.next) ret += s + p.data;
      return ret;
    }
  }, {
    key: "concat",
    value: function concat(n) {
      if (this.length === 0) return Buffer.alloc(0);
      var ret = Buffer.allocUnsafe(n >>> 0);
      var p = this.head;
      var i = 0;
      while (p) {
        copyBuffer(p.data, ret, i);
        i += p.data.length;
        p = p.next;
      }
      return ret;
    }

    // Consumes a specified amount of bytes or characters from the buffered data.
  }, {
    key: "consume",
    value: function consume(n, hasStrings) {
      var ret;
      if (n < this.head.data.length) {
        // `slice` is the same for buffers and strings.
        ret = this.head.data.slice(0, n);
        this.head.data = this.head.data.slice(n);
      } else if (n === this.head.data.length) {
        // First chunk is a perfect match.
        ret = this.shift();
      } else {
        // Result spans more than one buffer.
        ret = hasStrings ? this._getString(n) : this._getBuffer(n);
      }
      return ret;
    }
  }, {
    key: "first",
    value: function first() {
      return this.head.data;
    }

    // Consumes a specified amount of characters from the buffered data.
  }, {
    key: "_getString",
    value: function _getString(n) {
      var p = this.head;
      var c = 1;
      var ret = p.data;
      n -= ret.length;
      while (p = p.next) {
        var str = p.data;
        var nb = n > str.length ? str.length : n;
        if (nb === str.length) ret += str;else ret += str.slice(0, n);
        n -= nb;
        if (n === 0) {
          if (nb === str.length) {
            ++c;
            if (p.next) this.head = p.next;else this.head = this.tail = null;
          } else {
            this.head = p;
            p.data = str.slice(nb);
          }
          break;
        }
        ++c;
      }
      this.length -= c;
      return ret;
    }

    // Consumes a specified amount of bytes from the buffered data.
  }, {
    key: "_getBuffer",
    value: function _getBuffer(n) {
      var ret = Buffer.allocUnsafe(n);
      var p = this.head;
      var c = 1;
      p.data.copy(ret);
      n -= p.data.length;
      while (p = p.next) {
        var buf = p.data;
        var nb = n > buf.length ? buf.length : n;
        buf.copy(ret, ret.length - n, 0, nb);
        n -= nb;
        if (n === 0) {
          if (nb === buf.length) {
            ++c;
            if (p.next) this.head = p.next;else this.head = this.tail = null;
          } else {
            this.head = p;
            p.data = buf.slice(nb);
          }
          break;
        }
        ++c;
      }
      this.length -= c;
      return ret;
    }

    // Make sure the linked list only shows the minimal necessary information.
  }, {
    key: custom,
    value: function value(_, options) {
      return inspect(this, _objectSpread(_objectSpread({}, options), {}, {
        // Only inspect one level.
        depth: 0,
        // It should not recurse.
        customInspect: false
      }));
    }
  }]);
  return BufferList;
}();
},{"buffer":"buffer","util":54}],98:[function(require,module,exports){
(function (process){(function (){
'use strict';

// undocumented cb() API, needed for core, not for public API
function destroy(err, cb) {
  var _this = this;
  var readableDestroyed = this._readableState && this._readableState.destroyed;
  var writableDestroyed = this._writableState && this._writableState.destroyed;
  if (readableDestroyed || writableDestroyed) {
    if (cb) {
      cb(err);
    } else if (err) {
      if (!this._writableState) {
        process.nextTick(emitErrorNT, this, err);
      } else if (!this._writableState.errorEmitted) {
        this._writableState.errorEmitted = true;
        process.nextTick(emitErrorNT, this, err);
      }
    }
    return this;
  }

  // we set destroyed to true before firing error callbacks in order
  // to make it re-entrance safe in case destroy() is called within callbacks

  if (this._readableState) {
    this._readableState.destroyed = true;
  }

  // if this is a duplex stream mark the writable part as destroyed as well
  if (this._writableState) {
    this._writableState.destroyed = true;
  }
  this._destroy(err || null, function (err) {
    if (!cb && err) {
      if (!_this._writableState) {
        process.nextTick(emitErrorAndCloseNT, _this, err);
      } else if (!_this._writableState.errorEmitted) {
        _this._writableState.errorEmitted = true;
        process.nextTick(emitErrorAndCloseNT, _this, err);
      } else {
        process.nextTick(emitCloseNT, _this);
      }
    } else if (cb) {
      process.nextTick(emitCloseNT, _this);
      cb(err);
    } else {
      process.nextTick(emitCloseNT, _this);
    }
  });
  return this;
}
function emitErrorAndCloseNT(self, err) {
  emitErrorNT(self, err);
  emitCloseNT(self);
}
function emitCloseNT(self) {
  if (self._writableState && !self._writableState.emitClose) return;
  if (self._readableState && !self._readableState.emitClose) return;
  self.emit('close');
}
function undestroy() {
  if (this._readableState) {
    this._readableState.destroyed = false;
    this._readableState.reading = false;
    this._readableState.ended = false;
    this._readableState.endEmitted = false;
  }
  if (this._writableState) {
    this._writableState.destroyed = false;
    this._writableState.ended = false;
    this._writableState.ending = false;
    this._writableState.finalCalled = false;
    this._writableState.prefinished = false;
    this._writableState.finished = false;
    this._writableState.errorEmitted = false;
  }
}
function emitErrorNT(self, err) {
  self.emit('error', err);
}
function errorOrDestroy(stream, err) {
  // We have tests that rely on errors being emitted
  // in the same tick, so changing this is semver major.
  // For now when you opt-in to autoDestroy we allow
  // the error to be emitted nextTick. In a future
  // semver major update we should change the default to this.

  var rState = stream._readableState;
  var wState = stream._writableState;
  if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
}
module.exports = {
  destroy: destroy,
  undestroy: undestroy,
  errorOrDestroy: errorOrDestroy
};
}).call(this)}).call(this,require('_process'))
},{"_process":87}],99:[function(require,module,exports){
// Ported from https://github.com/mafintosh/end-of-stream with
// permission from the author, Mathias Buus (@mafintosh).

'use strict';

var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;
function once(callback) {
  var called = false;
  return function () {
    if (called) return;
    called = true;
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    callback.apply(this, args);
  };
}
function noop() {}
function isRequest(stream) {
  return stream.setHeader && typeof stream.abort === 'function';
}
function eos(stream, opts, callback) {
  if (typeof opts === 'function') return eos(stream, null, opts);
  if (!opts) opts = {};
  callback = once(callback || noop);
  var readable = opts.readable || opts.readable !== false && stream.readable;
  var writable = opts.writable || opts.writable !== false && stream.writable;
  var onlegacyfinish = function onlegacyfinish() {
    if (!stream.writable) onfinish();
  };
  var writableEnded = stream._writableState && stream._writableState.finished;
  var onfinish = function onfinish() {
    writable = false;
    writableEnded = true;
    if (!readable) callback.call(stream);
  };
  var readableEnded = stream._readableState && stream._readableState.endEmitted;
  var onend = function onend() {
    readable = false;
    readableEnded = true;
    if (!writable) callback.call(stream);
  };
  var onerror = function onerror(err) {
    callback.call(stream, err);
  };
  var onclose = function onclose() {
    var err;
    if (readable && !readableEnded) {
      if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
      return callback.call(stream, err);
    }
    if (writable && !writableEnded) {
      if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
      return callback.call(stream, err);
    }
  };
  var onrequest = function onrequest() {
    stream.req.on('finish', onfinish);
  };
  if (isRequest(stream)) {
    stream.on('complete', onfinish);
    stream.on('abort', onclose);
    if (stream.req) onrequest();else stream.on('request', onrequest);
  } else if (writable && !stream._writableState) {
    // legacy streams
    stream.on('end', onlegacyfinish);
    stream.on('close', onlegacyfinish);
  }
  stream.on('end', onend);
  stream.on('finish', onfinish);
  if (opts.error !== false) stream.on('error', onerror);
  stream.on('close', onclose);
  return function () {
    stream.removeListener('complete', onfinish);
    stream.removeListener('abort', onclose);
    stream.removeListener('request', onrequest);
    if (stream.req) stream.req.removeListener('finish', onfinish);
    stream.removeListener('end', onlegacyfinish);
    stream.removeListener('close', onlegacyfinish);
    stream.removeListener('finish', onfinish);
    stream.removeListener('end', onend);
    stream.removeListener('error', onerror);
    stream.removeListener('close', onclose);
  };
}
module.exports = eos;
},{"../../../errors":90}],100:[function(require,module,exports){
module.exports = function () {
  throw new Error('Readable.from is not available in the browser')
};

},{}],101:[function(require,module,exports){
// Ported from https://github.com/mafintosh/pump with
// permission from the author, Mathias Buus (@mafintosh).

'use strict';

var eos;
function once(callback) {
  var called = false;
  return function () {
    if (called) return;
    called = true;
    callback.apply(void 0, arguments);
  };
}
var _require$codes = require('../../../errors').codes,
  ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
  ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
function noop(err) {
  // Rethrow the error if it exists to avoid swallowing it
  if (err) throw err;
}
function isRequest(stream) {
  return stream.setHeader && typeof stream.abort === 'function';
}
function destroyer(stream, reading, writing, callback) {
  callback = once(callback);
  var closed = false;
  stream.on('close', function () {
    closed = true;
  });
  if (eos === undefined) eos = require('./end-of-stream');
  eos(stream, {
    readable: reading,
    writable: writing
  }, function (err) {
    if (err) return callback(err);
    closed = true;
    callback();
  });
  var destroyed = false;
  return function (err) {
    if (closed) return;
    if (destroyed) return;
    destroyed = true;

    // request.destroy just do .end - .abort is what we want
    if (isRequest(stream)) return stream.abort();
    if (typeof stream.destroy === 'function') return stream.destroy();
    callback(err || new ERR_STREAM_DESTROYED('pipe'));
  };
}
function call(fn) {
  fn();
}
function pipe(from, to) {
  return from.pipe(to);
}
function popCallback(streams) {
  if (!streams.length) return noop;
  if (typeof streams[streams.length - 1] !== 'function') return noop;
  return streams.pop();
}
function pipeline() {
  for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
    streams[_key] = arguments[_key];
  }
  var callback = popCallback(streams);
  if (Array.isArray(streams[0])) streams = streams[0];
  if (streams.length < 2) {
    throw new ERR_MISSING_ARGS('streams');
  }
  var error;
  var destroys = streams.map(function (stream, i) {
    var reading = i < streams.length - 1;
    var writing = i > 0;
    return destroyer(stream, reading, writing, function (err) {
      if (!error) error = err;
      if (err) destroys.forEach(call);
      if (reading) return;
      destroys.forEach(call);
      callback(error);
    });
  });
  return streams.reduce(pipe);
}
module.exports = pipeline;
},{"../../../errors":90,"./end-of-stream":99}],102:[function(require,module,exports){
'use strict';

var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;
function highWaterMarkFrom(options, isDuplex, duplexKey) {
  return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
}
function getHighWaterMark(state, options, duplexKey, isDuplex) {
  var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
  if (hwm != null) {
    if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
      var name = isDuplex ? duplexKey : 'highWaterMark';
      throw new ERR_INVALID_OPT_VALUE(name, hwm);
    }
    return Math.floor(hwm);
  }

  // Default value
  return state.objectMode ? 16 : 16 * 1024;
}
module.exports = {
  getHighWaterMark: getHighWaterMark
};
},{"../../../errors":90}],103:[function(require,module,exports){
module.exports = require('events').EventEmitter;

},{"events":59}],104:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

'use strict';

/*<replacement>*/

var Buffer = require('safe-buffer').Buffer;
/*</replacement>*/

var isEncoding = Buffer.isEncoding || function (encoding) {
  encoding = '' + encoding;
  switch (encoding && encoding.toLowerCase()) {
    case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
      return true;
    default:
      return false;
  }
};

function _normalizeEncoding(enc) {
  if (!enc) return 'utf8';
  var retried;
  while (true) {
    switch (enc) {
      case 'utf8':
      case 'utf-8':
        return 'utf8';
      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return 'utf16le';
      case 'latin1':
      case 'binary':
        return 'latin1';
      case 'base64':
      case 'ascii':
      case 'hex':
        return enc;
      default:
        if (retried) return; // undefined
        enc = ('' + enc).toLowerCase();
        retried = true;
    }
  }
};

// Do not cache `Buffer.isEncoding` when checking encoding names as some
// modules monkey-patch it to support additional encodings
function normalizeEncoding(enc) {
  var nenc = _normalizeEncoding(enc);
  if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
  return nenc || enc;
}

// StringDecoder provides an interface for efficiently splitting a series of
// buffers into a series of JS strings without breaking apart multi-byte
// characters.
exports.StringDecoder = StringDecoder;
function StringDecoder(encoding) {
  this.encoding = normalizeEncoding(encoding);
  var nb;
  switch (this.encoding) {
    case 'utf16le':
      this.text = utf16Text;
      this.end = utf16End;
      nb = 4;
      break;
    case 'utf8':
      this.fillLast = utf8FillLast;
      nb = 4;
      break;
    case 'base64':
      this.text = base64Text;
      this.end = base64End;
      nb = 3;
      break;
    default:
      this.write = simpleWrite;
      this.end = simpleEnd;
      return;
  }
  this.lastNeed = 0;
  this.lastTotal = 0;
  this.lastChar = Buffer.allocUnsafe(nb);
}

StringDecoder.prototype.write = function (buf) {
  if (buf.length === 0) return '';
  var r;
  var i;
  if (this.lastNeed) {
    r = this.fillLast(buf);
    if (r === undefined) return '';
    i = this.lastNeed;
    this.lastNeed = 0;
  } else {
    i = 0;
  }
  if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
  return r || '';
};

StringDecoder.prototype.end = utf8End;

// Returns only complete characters in a Buffer
StringDecoder.prototype.text = utf8Text;

// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
StringDecoder.prototype.fillLast = function (buf) {
  if (this.lastNeed <= buf.length) {
    buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
    return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  }
  buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
  this.lastNeed -= buf.length;
};

// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
// continuation byte. If an invalid byte is detected, -2 is returned.
function utf8CheckByte(byte) {
  if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
  return byte >> 6 === 0x02 ? -1 : -2;
}

// Checks at most 3 bytes at the end of a Buffer in order to detect an
// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
// needed to complete the UTF-8 character (if applicable) are returned.
function utf8CheckIncomplete(self, buf, i) {
  var j = buf.length - 1;
  if (j < i) return 0;
  var nb = utf8CheckByte(buf[j]);
  if (nb >= 0) {
    if (nb > 0) self.lastNeed = nb - 1;
    return nb;
  }
  if (--j < i || nb === -2) return 0;
  nb = utf8CheckByte(buf[j]);
  if (nb >= 0) {
    if (nb > 0) self.lastNeed = nb - 2;
    return nb;
  }
  if (--j < i || nb === -2) return 0;
  nb = utf8CheckByte(buf[j]);
  if (nb >= 0) {
    if (nb > 0) {
      if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
    }
    return nb;
  }
  return 0;
}

// Validates as many continuation bytes for a multi-byte UTF-8 character as
// needed or are available. If we see a non-continuation byte where we expect
// one, we "replace" the validated continuation bytes we've seen so far with
// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
// behavior. The continuation byte check is included three times in the case
// where all of the continuation bytes for a character exist in the same buffer.
// It is also done this way as a slight performance increase instead of using a
// loop.
function utf8CheckExtraBytes(self, buf, p) {
  if ((buf[0] & 0xC0) !== 0x80) {
    self.lastNeed = 0;
    return '\ufffd';
  }
  if (self.lastNeed > 1 && buf.length > 1) {
    if ((buf[1] & 0xC0) !== 0x80) {
      self.lastNeed = 1;
      return '\ufffd';
    }
    if (self.lastNeed > 2 && buf.length > 2) {
      if ((buf[2] & 0xC0) !== 0x80) {
        self.lastNeed = 2;
        return '\ufffd';
      }
    }
  }
}

// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
function utf8FillLast(buf) {
  var p = this.lastTotal - this.lastNeed;
  var r = utf8CheckExtraBytes(this, buf, p);
  if (r !== undefined) return r;
  if (this.lastNeed <= buf.length) {
    buf.copy(this.lastChar, p, 0, this.lastNeed);
    return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  }
  buf.copy(this.lastChar, p, 0, buf.length);
  this.lastNeed -= buf.length;
}

// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
// partial character, the character's bytes are buffered until the required
// number of bytes are available.
function utf8Text(buf, i) {
  var total = utf8CheckIncomplete(this, buf, i);
  if (!this.lastNeed) return buf.toString('utf8', i);
  this.lastTotal = total;
  var end = buf.length - (total - this.lastNeed);
  buf.copy(this.lastChar, 0, end);
  return buf.toString('utf8', i, end);
}

// For UTF-8, a replacement character is added when ending on a partial
// character.
function utf8End(buf) {
  var r = buf && buf.length ? this.write(buf) : '';
  if (this.lastNeed) return r + '\ufffd';
  return r;
}

// UTF-16LE typically needs two bytes per character, but even if we have an even
// number of bytes available, we need to check if we end on a leading/high
// surrogate. In that case, we need to wait for the next two bytes in order to
// decode the last character properly.
function utf16Text(buf, i) {
  if ((buf.length - i) % 2 === 0) {
    var r = buf.toString('utf16le', i);
    if (r) {
      var c = r.charCodeAt(r.length - 1);
      if (c >= 0xD800 && c <= 0xDBFF) {
        this.lastNeed = 2;
        this.lastTotal = 4;
        this.lastChar[0] = buf[buf.length - 2];
        this.lastChar[1] = buf[buf.length - 1];
        return r.slice(0, -1);
      }
    }
    return r;
  }
  this.lastNeed = 1;
  this.lastTotal = 2;
  this.lastChar[0] = buf[buf.length - 1];
  return buf.toString('utf16le', i, buf.length - 1);
}

// For UTF-16LE we do not explicitly append special replacement characters if we
// end on a partial character, we simply let v8 handle that.
function utf16End(buf) {
  var r = buf && buf.length ? this.write(buf) : '';
  if (this.lastNeed) {
    var end = this.lastTotal - this.lastNeed;
    return r + this.lastChar.toString('utf16le', 0, end);
  }
  return r;
}

function base64Text(buf, i) {
  var n = (buf.length - i) % 3;
  if (n === 0) return buf.toString('base64', i);
  this.lastNeed = 3 - n;
  this.lastTotal = 3;
  if (n === 1) {
    this.lastChar[0] = buf[buf.length - 1];
  } else {
    this.lastChar[0] = buf[buf.length - 2];
    this.lastChar[1] = buf[buf.length - 1];
  }
  return buf.toString('base64', i, buf.length - n);
}

function base64End(buf) {
  var r = buf && buf.length ? this.write(buf) : '';
  if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
  return r;
}

// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
function simpleWrite(buf) {
  return buf.toString(this.encoding);
}

function simpleEnd(buf) {
  return buf && buf.length ? this.write(buf) : '';
}
},{"safe-buffer":88}],105:[function(require,module,exports){
(function (setImmediate,clearImmediate){(function (){
var nextTick = require('process/browser.js').nextTick;
var apply = Function.prototype.apply;
var slice = Array.prototype.slice;
var immediateIds = {};
var nextImmediateId = 0;

// DOM APIs, for completeness

exports.setTimeout = function() {
  return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
};
exports.setInterval = function() {
  return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
};
exports.clearTimeout =
exports.clearInterval = function(timeout) { timeout.close(); };

function Timeout(id, clearFn) {
  this._id = id;
  this._clearFn = clearFn;
}
Timeout.prototype.unref = Timeout.prototype.ref = function() {};
Timeout.prototype.close = function() {
  this._clearFn.call(window, this._id);
};

// Does not start the time, just sets up the members needed.
exports.enroll = function(item, msecs) {
  clearTimeout(item._idleTimeoutId);
  item._idleTimeout = msecs;
};

exports.unenroll = function(item) {
  clearTimeout(item._idleTimeoutId);
  item._idleTimeout = -1;
};

exports._unrefActive = exports.active = function(item) {
  clearTimeout(item._idleTimeoutId);

  var msecs = item._idleTimeout;
  if (msecs >= 0) {
    item._idleTimeoutId = setTimeout(function onTimeout() {
      if (item._onTimeout)
        item._onTimeout();
    }, msecs);
  }
};

// That's not how node.js implements it but the exposed api is the same.
exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
  var id = nextImmediateId++;
  var args = arguments.length < 2 ? false : slice.call(arguments, 1);

  immediateIds[id] = true;

  nextTick(function onNextTick() {
    if (immediateIds[id]) {
      // fn.call() is faster so we optimize for the common use-case
      // @see http://jsperf.com/call-apply-segu
      if (args) {
        fn.apply(null, args);
      } else {
        fn.call(null);
      }
      // Prevent ids from leaking
      exports.clearImmediate(id);
    }
  });

  return id;
};

exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
  delete immediateIds[id];
};
}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate)
},{"process/browser.js":87,"timers":105}],106:[function(require,module,exports){
(function (global){(function (){

/**
 * Module exports.
 */

module.exports = deprecate;

/**
 * Mark that a method should not be used.
 * Returns a modified function which warns once by default.
 *
 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
 *
 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
 * will throw an Error when invoked.
 *
 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
 * will invoke `console.trace()` instead of `console.error()`.
 *
 * @param {Function} fn - the function to deprecate
 * @param {String} msg - the string to print to the console when `fn` is invoked
 * @returns {Function} a new "deprecated" version of `fn`
 * @api public
 */

function deprecate (fn, msg) {
  if (config('noDeprecation')) {
    return fn;
  }

  var warned = false;
  function deprecated() {
    if (!warned) {
      if (config('throwDeprecation')) {
        throw new Error(msg);
      } else if (config('traceDeprecation')) {
        console.trace(msg);
      } else {
        console.warn(msg);
      }
      warned = true;
    }
    return fn.apply(this, arguments);
  }

  return deprecated;
}

/**
 * Checks `localStorage` for boolean values for the given `name`.
 *
 * @param {String} name
 * @returns {Boolean}
 * @api private
 */

function config (name) {
  // accessing global.localStorage can trigger a DOMException in sandboxed iframes
  try {
    if (!global.localStorage) return false;
  } catch (_) {
    return false;
  }
  var val = global.localStorage[name];
  if (null == val) return false;
  return String(val).toLowerCase() === 'true';
}

}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],107:[function(require,module,exports){
arguments[4][50][0].apply(exports,arguments)
},{"dup":50}],108:[function(require,module,exports){
// Currently in sync with Node.js lib/internal/util/types.js
// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9

'use strict';

var isArgumentsObject = require('is-arguments');
var isGeneratorFunction = require('is-generator-function');
var whichTypedArray = require('which-typed-array');
var isTypedArray = require('is-typed-array');

function uncurryThis(f) {
  return f.call.bind(f);
}

var BigIntSupported = typeof BigInt !== 'undefined';
var SymbolSupported = typeof Symbol !== 'undefined';

var ObjectToString = uncurryThis(Object.prototype.toString);

var numberValue = uncurryThis(Number.prototype.valueOf);
var stringValue = uncurryThis(String.prototype.valueOf);
var booleanValue = uncurryThis(Boolean.prototype.valueOf);

if (BigIntSupported) {
  var bigIntValue = uncurryThis(BigInt.prototype.valueOf);
}

if (SymbolSupported) {
  var symbolValue = uncurryThis(Symbol.prototype.valueOf);
}

function checkBoxedPrimitive(value, prototypeValueOf) {
  if (typeof value !== 'object') {
    return false;
  }
  try {
    prototypeValueOf(value);
    return true;
  } catch(e) {
    return false;
  }
}

exports.isArgumentsObject = isArgumentsObject;
exports.isGeneratorFunction = isGeneratorFunction;
exports.isTypedArray = isTypedArray;

// Taken from here and modified for better browser support
// https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js
function isPromise(input) {
	return (
		(
			typeof Promise !== 'undefined' &&
			input instanceof Promise
		) ||
		(
			input !== null &&
			typeof input === 'object' &&
			typeof input.then === 'function' &&
			typeof input.catch === 'function'
		)
	);
}
exports.isPromise = isPromise;

function isArrayBufferView(value) {
  if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) {
    return ArrayBuffer.isView(value);
  }

  return (
    isTypedArray(value) ||
    isDataView(value)
  );
}
exports.isArrayBufferView = isArrayBufferView;


function isUint8Array(value) {
  return whichTypedArray(value) === 'Uint8Array';
}
exports.isUint8Array = isUint8Array;

function isUint8ClampedArray(value) {
  return whichTypedArray(value) === 'Uint8ClampedArray';
}
exports.isUint8ClampedArray = isUint8ClampedArray;

function isUint16Array(value) {
  return whichTypedArray(value) === 'Uint16Array';
}
exports.isUint16Array = isUint16Array;

function isUint32Array(value) {
  return whichTypedArray(value) === 'Uint32Array';
}
exports.isUint32Array = isUint32Array;

function isInt8Array(value) {
  return whichTypedArray(value) === 'Int8Array';
}
exports.isInt8Array = isInt8Array;

function isInt16Array(value) {
  return whichTypedArray(value) === 'Int16Array';
}
exports.isInt16Array = isInt16Array;

function isInt32Array(value) {
  return whichTypedArray(value) === 'Int32Array';
}
exports.isInt32Array = isInt32Array;

function isFloat32Array(value) {
  return whichTypedArray(value) === 'Float32Array';
}
exports.isFloat32Array = isFloat32Array;

function isFloat64Array(value) {
  return whichTypedArray(value) === 'Float64Array';
}
exports.isFloat64Array = isFloat64Array;

function isBigInt64Array(value) {
  return whichTypedArray(value) === 'BigInt64Array';
}
exports.isBigInt64Array = isBigInt64Array;

function isBigUint64Array(value) {
  return whichTypedArray(value) === 'BigUint64Array';
}
exports.isBigUint64Array = isBigUint64Array;

function isMapToString(value) {
  return ObjectToString(value) === '[object Map]';
}
isMapToString.working = (
  typeof Map !== 'undefined' &&
  isMapToString(new Map())
);

function isMap(value) {
  if (typeof Map === 'undefined') {
    return false;
  }

  return isMapToString.working
    ? isMapToString(value)
    : value instanceof Map;
}
exports.isMap = isMap;

function isSetToString(value) {
  return ObjectToString(value) === '[object Set]';
}
isSetToString.working = (
  typeof Set !== 'undefined' &&
  isSetToString(new Set())
);
function isSet(value) {
  if (typeof Set === 'undefined') {
    return false;
  }

  return isSetToString.working
    ? isSetToString(value)
    : value instanceof Set;
}
exports.isSet = isSet;

function isWeakMapToString(value) {
  return ObjectToString(value) === '[object WeakMap]';
}
isWeakMapToString.working = (
  typeof WeakMap !== 'undefined' &&
  isWeakMapToString(new WeakMap())
);
function isWeakMap(value) {
  if (typeof WeakMap === 'undefined') {
    return false;
  }

  return isWeakMapToString.working
    ? isWeakMapToString(value)
    : value instanceof WeakMap;
}
exports.isWeakMap = isWeakMap;

function isWeakSetToString(value) {
  return ObjectToString(value) === '[object WeakSet]';
}
isWeakSetToString.working = (
  typeof WeakSet !== 'undefined' &&
  isWeakSetToString(new WeakSet())
);
function isWeakSet(value) {
  return isWeakSetToString(value);
}
exports.isWeakSet = isWeakSet;

function isArrayBufferToString(value) {
  return ObjectToString(value) === '[object ArrayBuffer]';
}
isArrayBufferToString.working = (
  typeof ArrayBuffer !== 'undefined' &&
  isArrayBufferToString(new ArrayBuffer())
);
function isArrayBuffer(value) {
  if (typeof ArrayBuffer === 'undefined') {
    return false;
  }

  return isArrayBufferToString.working
    ? isArrayBufferToString(value)
    : value instanceof ArrayBuffer;
}
exports.isArrayBuffer = isArrayBuffer;

function isDataViewToString(value) {
  return ObjectToString(value) === '[object DataView]';
}
isDataViewToString.working = (
  typeof ArrayBuffer !== 'undefined' &&
  typeof DataView !== 'undefined' &&
  isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1))
);
function isDataView(value) {
  if (typeof DataView === 'undefined') {
    return false;
  }

  return isDataViewToString.working
    ? isDataViewToString(value)
    : value instanceof DataView;
}
exports.isDataView = isDataView;

// Store a copy of SharedArrayBuffer in case it's deleted elsewhere
var SharedArrayBufferCopy = typeof SharedArrayBuffer !== 'undefined' ? SharedArrayBuffer : undefined;
function isSharedArrayBufferToString(value) {
  return ObjectToString(value) === '[object SharedArrayBuffer]';
}
function isSharedArrayBuffer(value) {
  if (typeof SharedArrayBufferCopy === 'undefined') {
    return false;
  }

  if (typeof isSharedArrayBufferToString.working === 'undefined') {
    isSharedArrayBufferToString.working = isSharedArrayBufferToString(new SharedArrayBufferCopy());
  }

  return isSharedArrayBufferToString.working
    ? isSharedArrayBufferToString(value)
    : value instanceof SharedArrayBufferCopy;
}
exports.isSharedArrayBuffer = isSharedArrayBuffer;

function isAsyncFunction(value) {
  return ObjectToString(value) === '[object AsyncFunction]';
}
exports.isAsyncFunction = isAsyncFunction;

function isMapIterator(value) {
  return ObjectToString(value) === '[object Map Iterator]';
}
exports.isMapIterator = isMapIterator;

function isSetIterator(value) {
  return ObjectToString(value) === '[object Set Iterator]';
}
exports.isSetIterator = isSetIterator;

function isGeneratorObject(value) {
  return ObjectToString(value) === '[object Generator]';
}
exports.isGeneratorObject = isGeneratorObject;

function isWebAssemblyCompiledModule(value) {
  return ObjectToString(value) === '[object WebAssembly.Module]';
}
exports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule;

function isNumberObject(value) {
  return checkBoxedPrimitive(value, numberValue);
}
exports.isNumberObject = isNumberObject;

function isStringObject(value) {
  return checkBoxedPrimitive(value, stringValue);
}
exports.isStringObject = isStringObject;

function isBooleanObject(value) {
  return checkBoxedPrimitive(value, booleanValue);
}
exports.isBooleanObject = isBooleanObject;

function isBigIntObject(value) {
  return BigIntSupported && checkBoxedPrimitive(value, bigIntValue);
}
exports.isBigIntObject = isBigIntObject;

function isSymbolObject(value) {
  return SymbolSupported && checkBoxedPrimitive(value, symbolValue);
}
exports.isSymbolObject = isSymbolObject;

function isBoxedPrimitive(value) {
  return (
    isNumberObject(value) ||
    isStringObject(value) ||
    isBooleanObject(value) ||
    isBigIntObject(value) ||
    isSymbolObject(value)
  );
}
exports.isBoxedPrimitive = isBoxedPrimitive;

function isAnyArrayBuffer(value) {
  return typeof Uint8Array !== 'undefined' && (
    isArrayBuffer(value) ||
    isSharedArrayBuffer(value)
  );
}
exports.isAnyArrayBuffer = isAnyArrayBuffer;

['isProxy', 'isExternal', 'isModuleNamespaceObject'].forEach(function(method) {
  Object.defineProperty(exports, method, {
    enumerable: false,
    value: function() {
      throw new Error(method + ' is not supported in userland');
    }
  });
});

},{"is-arguments":71,"is-generator-function":73,"is-typed-array":74,"which-typed-array":110}],109:[function(require,module,exports){
(function (process){(function (){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors ||
  function getOwnPropertyDescriptors(obj) {
    var keys = Object.keys(obj);
    var descriptors = {};
    for (var i = 0; i < keys.length; i++) {
      descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]);
    }
    return descriptors;
  };

var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
  if (!isString(f)) {
    var objects = [];
    for (var i = 0; i < arguments.length; i++) {
      objects.push(inspect(arguments[i]));
    }
    return objects.join(' ');
  }

  var i = 1;
  var args = arguments;
  var len = args.length;
  var str = String(f).replace(formatRegExp, function(x) {
    if (x === '%%') return '%';
    if (i >= len) return x;
    switch (x) {
      case '%s': return String(args[i++]);
      case '%d': return Number(args[i++]);
      case '%j':
        try {
          return JSON.stringify(args[i++]);
        } catch (_) {
          return '[Circular]';
        }
      default:
        return x;
    }
  });
  for (var x = args[i]; i < len; x = args[++i]) {
    if (isNull(x) || !isObject(x)) {
      str += ' ' + x;
    } else {
      str += ' ' + inspect(x);
    }
  }
  return str;
};


// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
  if (typeof process !== 'undefined' && process.noDeprecation === true) {
    return fn;
  }

  // Allow for deprecating things in the process of starting up.
  if (typeof process === 'undefined') {
    return function() {
      return exports.deprecate(fn, msg).apply(this, arguments);
    };
  }

  var warned = false;
  function deprecated() {
    if (!warned) {
      if (process.throwDeprecation) {
        throw new Error(msg);
      } else if (process.traceDeprecation) {
        console.trace(msg);
      } else {
        console.error(msg);
      }
      warned = true;
    }
    return fn.apply(this, arguments);
  }

  return deprecated;
};


var debugs = {};
var debugEnvRegex = /^$/;

if (process.env.NODE_DEBUG) {
  var debugEnv = process.env.NODE_DEBUG;
  debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, '\\$&')
    .replace(/\*/g, '.*')
    .replace(/,/g, '$|^')
    .toUpperCase();
  debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i');
}
exports.debuglog = function(set) {
  set = set.toUpperCase();
  if (!debugs[set]) {
    if (debugEnvRegex.test(set)) {
      var pid = process.pid;
      debugs[set] = function() {
        var msg = exports.format.apply(exports, arguments);
        console.error('%s %d: %s', set, pid, msg);
      };
    } else {
      debugs[set] = function() {};
    }
  }
  return debugs[set];
};


/**
 * Echos the value of a value. Trys to print the value out
 * in the best way possible given the different types.
 *
 * @param {Object} obj The object to print out.
 * @param {Object} opts Optional options object that alters the output.
 */
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
  // default options
  var ctx = {
    seen: [],
    stylize: stylizeNoColor
  };
  // legacy...
  if (arguments.length >= 3) ctx.depth = arguments[2];
  if (arguments.length >= 4) ctx.colors = arguments[3];
  if (isBoolean(opts)) {
    // legacy...
    ctx.showHidden = opts;
  } else if (opts) {
    // got an "options" object
    exports._extend(ctx, opts);
  }
  // set default options
  if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  if (isUndefined(ctx.depth)) ctx.depth = 2;
  if (isUndefined(ctx.colors)) ctx.colors = false;
  if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  if (ctx.colors) ctx.stylize = stylizeWithColor;
  return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;


// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
  'bold' : [1, 22],
  'italic' : [3, 23],
  'underline' : [4, 24],
  'inverse' : [7, 27],
  'white' : [37, 39],
  'grey' : [90, 39],
  'black' : [30, 39],
  'blue' : [34, 39],
  'cyan' : [36, 39],
  'green' : [32, 39],
  'magenta' : [35, 39],
  'red' : [31, 39],
  'yellow' : [33, 39]
};

// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
  'special': 'cyan',
  'number': 'yellow',
  'boolean': 'yellow',
  'undefined': 'grey',
  'null': 'bold',
  'string': 'green',
  'date': 'magenta',
  // "name": intentionally not styling
  'regexp': 'red'
};


function stylizeWithColor(str, styleType) {
  var style = inspect.styles[styleType];

  if (style) {
    return '\u001b[' + inspect.colors[style][0] + 'm' + str +
           '\u001b[' + inspect.colors[style][1] + 'm';
  } else {
    return str;
  }
}


function stylizeNoColor(str, styleType) {
  return str;
}


function arrayToHash(array) {
  var hash = {};

  array.forEach(function(val, idx) {
    hash[val] = true;
  });

  return hash;
}


function formatValue(ctx, value, recurseTimes) {
  // Provide a hook for user-specified inspect functions.
  // Check that value is an object with an inspect function on it
  if (ctx.customInspect &&
      value &&
      isFunction(value.inspect) &&
      // Filter out the util module, it's inspect function is special
      value.inspect !== exports.inspect &&
      // Also filter out any prototype objects using the circular check.
      !(value.constructor && value.constructor.prototype === value)) {
    var ret = value.inspect(recurseTimes, ctx);
    if (!isString(ret)) {
      ret = formatValue(ctx, ret, recurseTimes);
    }
    return ret;
  }

  // Primitive types cannot have properties
  var primitive = formatPrimitive(ctx, value);
  if (primitive) {
    return primitive;
  }

  // Look up the keys of the object.
  var keys = Object.keys(value);
  var visibleKeys = arrayToHash(keys);

  if (ctx.showHidden) {
    keys = Object.getOwnPropertyNames(value);
  }

  // IE doesn't make error fields non-enumerable
  // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  if (isError(value)
      && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
    return formatError(value);
  }

  // Some type of object without properties can be shortcutted.
  if (keys.length === 0) {
    if (isFunction(value)) {
      var name = value.name ? ': ' + value.name : '';
      return ctx.stylize('[Function' + name + ']', 'special');
    }
    if (isRegExp(value)) {
      return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
    }
    if (isDate(value)) {
      return ctx.stylize(Date.prototype.toString.call(value), 'date');
    }
    if (isError(value)) {
      return formatError(value);
    }
  }

  var base = '', array = false, braces = ['{', '}'];

  // Make Array say that they are Array
  if (isArray(value)) {
    array = true;
    braces = ['[', ']'];
  }

  // Make functions say that they are functions
  if (isFunction(value)) {
    var n = value.name ? ': ' + value.name : '';
    base = ' [Function' + n + ']';
  }

  // Make RegExps say that they are RegExps
  if (isRegExp(value)) {
    base = ' ' + RegExp.prototype.toString.call(value);
  }

  // Make dates with properties first say the date
  if (isDate(value)) {
    base = ' ' + Date.prototype.toUTCString.call(value);
  }

  // Make error with message first say the error
  if (isError(value)) {
    base = ' ' + formatError(value);
  }

  if (keys.length === 0 && (!array || value.length == 0)) {
    return braces[0] + base + braces[1];
  }

  if (recurseTimes < 0) {
    if (isRegExp(value)) {
      return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
    } else {
      return ctx.stylize('[Object]', 'special');
    }
  }

  ctx.seen.push(value);

  var output;
  if (array) {
    output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  } else {
    output = keys.map(function(key) {
      return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
    });
  }

  ctx.seen.pop();

  return reduceToSingleString(output, base, braces);
}


function formatPrimitive(ctx, value) {
  if (isUndefined(value))
    return ctx.stylize('undefined', 'undefined');
  if (isString(value)) {
    var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
                                             .replace(/'/g, "\\'")
                                             .replace(/\\"/g, '"') + '\'';
    return ctx.stylize(simple, 'string');
  }
  if (isNumber(value))
    return ctx.stylize('' + value, 'number');
  if (isBoolean(value))
    return ctx.stylize('' + value, 'boolean');
  // For some reason typeof null is "object", so special case here.
  if (isNull(value))
    return ctx.stylize('null', 'null');
}


function formatError(value) {
  return '[' + Error.prototype.toString.call(value) + ']';
}


function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  var output = [];
  for (var i = 0, l = value.length; i < l; ++i) {
    if (hasOwnProperty(value, String(i))) {
      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
          String(i), true));
    } else {
      output.push('');
    }
  }
  keys.forEach(function(key) {
    if (!key.match(/^\d+$/)) {
      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
          key, true));
    }
  });
  return output;
}


function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  var name, str, desc;
  desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  if (desc.get) {
    if (desc.set) {
      str = ctx.stylize('[Getter/Setter]', 'special');
    } else {
      str = ctx.stylize('[Getter]', 'special');
    }
  } else {
    if (desc.set) {
      str = ctx.stylize('[Setter]', 'special');
    }
  }
  if (!hasOwnProperty(visibleKeys, key)) {
    name = '[' + key + ']';
  }
  if (!str) {
    if (ctx.seen.indexOf(desc.value) < 0) {
      if (isNull(recurseTimes)) {
        str = formatValue(ctx, desc.value, null);
      } else {
        str = formatValue(ctx, desc.value, recurseTimes - 1);
      }
      if (str.indexOf('\n') > -1) {
        if (array) {
          str = str.split('\n').map(function(line) {
            return '  ' + line;
          }).join('\n').slice(2);
        } else {
          str = '\n' + str.split('\n').map(function(line) {
            return '   ' + line;
          }).join('\n');
        }
      }
    } else {
      str = ctx.stylize('[Circular]', 'special');
    }
  }
  if (isUndefined(name)) {
    if (array && key.match(/^\d+$/)) {
      return str;
    }
    name = JSON.stringify('' + key);
    if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
      name = name.slice(1, -1);
      name = ctx.stylize(name, 'name');
    } else {
      name = name.replace(/'/g, "\\'")
                 .replace(/\\"/g, '"')
                 .replace(/(^"|"$)/g, "'");
      name = ctx.stylize(name, 'string');
    }
  }

  return name + ': ' + str;
}


function reduceToSingleString(output, base, braces) {
  var numLinesEst = 0;
  var length = output.reduce(function(prev, cur) {
    numLinesEst++;
    if (cur.indexOf('\n') >= 0) numLinesEst++;
    return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  }, 0);

  if (length > 60) {
    return braces[0] +
           (base === '' ? '' : base + '\n ') +
           ' ' +
           output.join(',\n  ') +
           ' ' +
           braces[1];
  }

  return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}


// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
exports.types = require('./support/types');

function isArray(ar) {
  return Array.isArray(ar);
}
exports.isArray = isArray;

function isBoolean(arg) {
  return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;

function isNull(arg) {
  return arg === null;
}
exports.isNull = isNull;

function isNullOrUndefined(arg) {
  return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;

function isNumber(arg) {
  return typeof arg === 'number';
}
exports.isNumber = isNumber;

function isString(arg) {
  return typeof arg === 'string';
}
exports.isString = isString;

function isSymbol(arg) {
  return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;

function isUndefined(arg) {
  return arg === void 0;
}
exports.isUndefined = isUndefined;

function isRegExp(re) {
  return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
exports.types.isRegExp = isRegExp;

function isObject(arg) {
  return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;

function isDate(d) {
  return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
exports.types.isDate = isDate;

function isError(e) {
  return isObject(e) &&
      (objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
exports.types.isNativeError = isError;

function isFunction(arg) {
  return typeof arg === 'function';
}
exports.isFunction = isFunction;

function isPrimitive(arg) {
  return arg === null ||
         typeof arg === 'boolean' ||
         typeof arg === 'number' ||
         typeof arg === 'string' ||
         typeof arg === 'symbol' ||  // ES6 symbol
         typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;

exports.isBuffer = require('./support/isBuffer');

function objectToString(o) {
  return Object.prototype.toString.call(o);
}


function pad(n) {
  return n < 10 ? '0' + n.toString(10) : n.toString(10);
}


var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
              'Oct', 'Nov', 'Dec'];

// 26 Feb 16:19:34
function timestamp() {
  var d = new Date();
  var time = [pad(d.getHours()),
              pad(d.getMinutes()),
              pad(d.getSeconds())].join(':');
  return [d.getDate(), months[d.getMonth()], time].join(' ');
}


// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
  console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};


/**
 * Inherit the prototype methods from one constructor into another.
 *
 * The Function.prototype.inherits from lang.js rewritten as a standalone
 * function (not on Function.prototype). NOTE: If this file is to be loaded
 * during bootstrapping this function needs to be rewritten using some native
 * functions as prototype setup using normal JavaScript does not work as
 * expected during bootstrapping (see mirror.js in r114903).
 *
 * @param {function} ctor Constructor function which needs to inherit the
 *     prototype.
 * @param {function} superCtor Constructor function to inherit prototype from.
 */
exports.inherits = require('inherits');

exports._extend = function(origin, add) {
  // Don't do anything if add isn't an object
  if (!add || !isObject(add)) return origin;

  var keys = Object.keys(add);
  var i = keys.length;
  while (i--) {
    origin[keys[i]] = add[keys[i]];
  }
  return origin;
};

function hasOwnProperty(obj, prop) {
  return Object.prototype.hasOwnProperty.call(obj, prop);
}

var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined;

exports.promisify = function promisify(original) {
  if (typeof original !== 'function')
    throw new TypeError('The "original" argument must be of type Function');

  if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) {
    var fn = original[kCustomPromisifiedSymbol];
    if (typeof fn !== 'function') {
      throw new TypeError('The "util.promisify.custom" argument must be of type Function');
    }
    Object.defineProperty(fn, kCustomPromisifiedSymbol, {
      value: fn, enumerable: false, writable: false, configurable: true
    });
    return fn;
  }

  function fn() {
    var promiseResolve, promiseReject;
    var promise = new Promise(function (resolve, reject) {
      promiseResolve = resolve;
      promiseReject = reject;
    });

    var args = [];
    for (var i = 0; i < arguments.length; i++) {
      args.push(arguments[i]);
    }
    args.push(function (err, value) {
      if (err) {
        promiseReject(err);
      } else {
        promiseResolve(value);
      }
    });

    try {
      original.apply(this, args);
    } catch (err) {
      promiseReject(err);
    }

    return promise;
  }

  Object.setPrototypeOf(fn, Object.getPrototypeOf(original));

  if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, {
    value: fn, enumerable: false, writable: false, configurable: true
  });
  return Object.defineProperties(
    fn,
    getOwnPropertyDescriptors(original)
  );
}

exports.promisify.custom = kCustomPromisifiedSymbol

function callbackifyOnRejected(reason, cb) {
  // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M).
  // Because `null` is a special error value in callbacks which means "no error
  // occurred", we error-wrap so the callback consumer can distinguish between
  // "the promise rejected with null" or "the promise fulfilled with undefined".
  if (!reason) {
    var newReason = new Error('Promise was rejected with a falsy value');
    newReason.reason = reason;
    reason = newReason;
  }
  return cb(reason);
}

function callbackify(original) {
  if (typeof original !== 'function') {
    throw new TypeError('The "original" argument must be of type Function');
  }

  // We DO NOT return the promise as it gives the user a false sense that
  // the promise is actually somehow related to the callback's execution
  // and that the callback throwing will reject the promise.
  function callbackified() {
    var args = [];
    for (var i = 0; i < arguments.length; i++) {
      args.push(arguments[i]);
    }

    var maybeCb = args.pop();
    if (typeof maybeCb !== 'function') {
      throw new TypeError('The last argument must be of type Function');
    }
    var self = this;
    var cb = function() {
      return maybeCb.apply(self, arguments);
    };
    // In true node style we process the callback on `nextTick` with all the
    // implications (stack, `uncaughtException`, `async_hooks`)
    original.apply(this, args)
      .then(function(ret) { process.nextTick(cb.bind(null, null, ret)) },
            function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) });
  }

  Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original));
  Object.defineProperties(callbackified,
                          getOwnPropertyDescriptors(original));
  return callbackified;
}
exports.callbackify = callbackify;

}).call(this)}).call(this,require('_process'))
},{"./support/isBuffer":107,"./support/types":108,"_process":87,"inherits":70}],110:[function(require,module,exports){
(function (global){(function (){
'use strict';

var forEach = require('for-each');
var availableTypedArrays = require('available-typed-arrays');
var callBound = require('call-bind/callBound');
var gOPD = require('gopd');

var $toString = callBound('Object.prototype.toString');
var hasToStringTag = require('has-tostringtag/shams')();

var g = typeof globalThis === 'undefined' ? global : globalThis;
var typedArrays = availableTypedArrays();

var $slice = callBound('String.prototype.slice');
var toStrTags = {};
var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof');
if (hasToStringTag && gOPD && getPrototypeOf) {
	forEach(typedArrays, function (typedArray) {
		if (typeof g[typedArray] === 'function') {
			var arr = new g[typedArray]();
			if (Symbol.toStringTag in arr) {
				var proto = getPrototypeOf(arr);
				var descriptor = gOPD(proto, Symbol.toStringTag);
				if (!descriptor) {
					var superProto = getPrototypeOf(proto);
					descriptor = gOPD(superProto, Symbol.toStringTag);
				}
				toStrTags[typedArray] = descriptor.get;
			}
		}
	});
}

var tryTypedArrays = function tryAllTypedArrays(value) {
	var foundName = false;
	forEach(toStrTags, function (getter, typedArray) {
		if (!foundName) {
			try {
				var name = getter.call(value);
				if (name === typedArray) {
					foundName = name;
				}
			} catch (e) {}
		}
	});
	return foundName;
};

var isTypedArray = require('is-typed-array');

module.exports = function whichTypedArray(value) {
	if (!isTypedArray(value)) { return false; }
	if (!hasToStringTag || !(Symbol.toStringTag in value)) { return $slice($toString(value), 8, -1); }
	return tryTypedArrays(value);
};

}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"available-typed-arrays":52,"call-bind/callBound":57,"for-each":60,"gopd":64,"has-tostringtag/shams":67,"is-typed-array":74}],"@placemarkio/tokml":[function(require,module,exports){
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

/**
 * @typedef {import('unist').Node} Node
 * @typedef {import('unist').Parent} Parent
 * @typedef {import('unist').Literal} Literal
 * @typedef {Object.<string, unknown>} Props
 * @typedef {Array.<Node>|string} ChildrenOrValue
 *
 * @typedef {(<T extends string, P extends Record<string, unknown>, C extends Node[]>(type: T, props: P, children: C) => {type: T, children: C} & P)} BuildParentWithProps
 * @typedef {(<T extends string, P extends Record<string, unknown>>(type: T, props: P, value: string) => {type: T, value: string} & P)} BuildLiteralWithProps
 * @typedef {(<T extends string, P extends Record<string, unknown>>(type: T, props: P) => {type: T} & P)} BuildVoidWithProps
 * @typedef {(<T extends string, C extends Node[]>(type: T, children: C) => {type: T, children: C})} BuildParent
 * @typedef {(<T extends string>(type: T, value: string) => {type: T, value: string})} BuildLiteral
 * @typedef {(<T extends string>(type: T) => {type: T})} BuildVoid
 */

var u = /**
 * @type {BuildVoid & BuildVoidWithProps & BuildLiteral & BuildLiteralWithProps & BuildParent & BuildParentWithProps}
 */ (
  /**
   * @param {string} type Type of node
   * @param {Props|ChildrenOrValue} [props] Additional properties for node (or `children` or `value`)
   * @param {ChildrenOrValue} [value] `children` or `value` of node
   * @returns {Node}
   */
  function (type, props, value) {
    /** @type {Node} */
    var node = {type: String(type)};

    if (
      (value === undefined || value === null) &&
      (typeof props === 'string' || Array.isArray(props))
    ) {
      value = props;
    } else {
      Object.assign(node, props);
    }

    if (Array.isArray(value)) {
      node.children = value;
    } else if (value !== undefined && value !== null) {
      node.value = String(value);
    }

    return node
  }
);

/**
 * @typedef {import('xast').Root} Root
 * @typedef {import('xast').Element} Element
 * @typedef {Root['children'][number]} Child
 * @typedef {Child|Root} Node
 * @typedef {Root|Element} XResult
 * @typedef {string|number|boolean|null|undefined} XValue
 * @typedef {{[attribute: string]: XValue}} XAttributes Attributes to support JS primitive types
 *
 * @typedef {string|number|null|undefined} XPrimitiveChild
 * @typedef {Array.<Node|XPrimitiveChild>} XArrayChild
 * @typedef {Node|XPrimitiveChild|XArrayChild} XChild
 * @typedef {import('./jsx-classic').Element} x.JSX.Element
 * @typedef {import('./jsx-classic').IntrinsicAttributes} x.JSX.IntrinsicAttributes
 * @typedef {import('./jsx-classic').IntrinsicElements} x.JSX.IntrinsicElements
 * @typedef {import('./jsx-classic').ElementChildrenAttribute} x.JSX.ElementChildrenAttribute
 */

/**
 * Create XML trees in xast.
 *
 * @param name Qualified name. Case sensitive and can contain a namespace prefix (such as `rdf:RDF`). Pass `null|undefined` to build a root.
 * @param attributes Map of attributes. Nullish (null or undefined) or NaN values are ignored, other values (strings, booleans) are cast to strings.
 * @param children (Lists of) child nodes. When strings are encountered, they are mapped to Text nodes.
 */
const x =
  /**
   * @type {{
   *   (): Root
   *   (name: null|undefined, ...children: XChild[]): Root
   *   (name: string, attributes: XAttributes, ...children: XChild[]): Element
   *   (name: string, ...children: XChild[]): Element
   * }}
   */
  (
    /**
     * Hyperscript compatible DSL for creating virtual xast trees.
     *
     * @param {string|null} [name]
     * @param {XAttributes|XChild} [attributes]
     * @param {XChild[]} children
     * @returns {XResult}
     */
    function (name, attributes, ...children) {
      var index = -1;
      /** @type {XResult} */
      var node;
      /** @type {string} */
      var key;

      if (name === undefined || name === null) {
        node = {type: 'root', children: []};
        // @ts-ignore Root builder doesn’t accept attributes.
        children.unshift(attributes);
      } else if (typeof name === 'string') {
        node = {type: 'element', name, attributes: {}, children: []};

        if (isAttributes(attributes)) {
          for (key in attributes) {
            // Ignore nullish and NaN values.
            if (
              attributes[key] !== undefined &&
              attributes[key] !== null &&
              (typeof attributes[key] !== 'number' ||
                !Number.isNaN(attributes[key]))
            ) {
              // @ts-ignore Pretty sure we just set it.
              node.attributes[key] = String(attributes[key]);
            }
          }
        } else {
          children.unshift(attributes);
        }
      } else {
        throw new TypeError('Expected element name, got `' + name + '`')
      }

      // Handle children.
      while (++index < children.length) {
        addChild(node.children, children[index]);
      }

      return node
    }
  );

/**
 * @param {Array.<Child>} nodes
 * @param {XChild} value
 */
function addChild(nodes, value) {
  var index = -1;

  if (value === undefined || value === null) ; else if (typeof value === 'string' || typeof value === 'number') {
    nodes.push({type: 'text', value: String(value)});
  } else if (Array.isArray(value)) {
    while (++index < value.length) {
      addChild(nodes, value[index]);
    }
  } else if (typeof value === 'object' && 'type' in value) {
    if (value.type === 'root') {
      addChild(nodes, value.children);
    } else {
      nodes.push(value);
    }
  } else {
    throw new TypeError('Expected node, nodes, string, got `' + value + '`')
  }
}

/**
 * @param {XAttributes|XChild} value
 * @returns {value is XAttributes}
 */
function isAttributes(value) {
  if (
    value === null ||
    value === undefined ||
    typeof value !== 'object' ||
    Array.isArray(value)
  ) {
    return false
  }

  return true
}

/**
 * @typedef {import('./index.js').Parent} Parent
 * @typedef {import('./index.js').Context} Context
 * @typedef {import('./index.js').Child} Child
 */

/**
 * Serialize all children of `parent`.
 *
 * @param {Parent} parent
 * @param {Context} ctx
 * @returns {string}
 *
 */
function all(parent, ctx) {
  /** @type {Array.<Child>} */
  var children = (parent && parent.children) || [];
  var index = -1;
  /** @type {Array.<string>} */
  var results = [];

  while (++index < children.length) {
    results[index] = one(children[index], ctx);
  }

  return results.join('')
}

/**
 * @typedef {Object} CoreOptions
 * @property {string[]} [subset=[]]
 *   Whether to only escape the given subset of characters.
 * @property {boolean} [escapeOnly=false]
 *   Whether to only escape possibly dangerous characters.
 *   Those characters are `"`, `&`, `'`, `<`, `>`, and `` ` ``.
 *
 * @typedef {Object} FormatOptions
 * @property {(code: number, next: number, options: CoreWithFormatOptions) => string} format
 *   Format strategy.
 *
 * @typedef {CoreOptions & FormatOptions & import('./util/format-smart.js').FormatSmartOptions} CoreWithFormatOptions
 */

/**
 * Encode certain characters in `value`.
 *
 * @param {string} value
 * @param {CoreWithFormatOptions} options
 * @returns {string}
 */
function core(value, options) {
  value = value.replace(
    options.subset ? charactersToExpression(options.subset) : /["&'<>`]/g,
    basic
  );

  if (options.subset || options.escapeOnly) {
    return value
  }

  return (
    value
      // Surrogate pairs.
      .replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, surrogate)
      // BMP control characters (C0 except for LF, CR, SP; DEL; and some more
      // non-ASCII ones).
      .replace(
        // eslint-disable-next-line no-control-regex, unicorn/no-hex-escape
        /[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g,
        basic
      )
  )

  /**
   * @param {string} pair
   * @param {number} index
   * @param {string} all
   */
  function surrogate(pair, index, all) {
    return options.format(
      (pair.charCodeAt(0) - 0xd800) * 0x400 +
        pair.charCodeAt(1) -
        0xdc00 +
        0x10000,
      all.charCodeAt(index + 2),
      options
    )
  }

  /**
   * @param {string} character
   * @param {number} index
   * @param {string} all
   */
  function basic(character, index, all) {
    return options.format(
      character.charCodeAt(0),
      all.charCodeAt(index + 1),
      options
    )
  }
}

/**
 * @param {string[]} subset
 * @returns {RegExp}
 */
function charactersToExpression(subset) {
  /** @type {string[]} */
  const groups = [];
  let index = -1;

  while (++index < subset.length) {
    groups.push(subset[index].replace(/[|\\{}()[\]^$+*?.]/g, '\\$&'));
  }

  return new RegExp('(?:' + groups.join('|') + ')', 'g')
}

/**
 * The smallest way to encode a character.
 *
 * @param {number} code
 * @returns {string}
 */
function formatBasic(code) {
  return '&#x' + code.toString(16).toUpperCase() + ';'
}

/**
 * @typedef {import('./core.js').CoreOptions & import('./util/format-smart.js').FormatSmartOptions} Options
 * @typedef {import('./core.js').CoreOptions} LightOptions
 */

/**
 * Encode special characters in `value` as hexadecimals.
 *
 * @param {string} value
 *   Value to encode.
 * @param {LightOptions} [options]
 *   Configuration.
 * @returns {string}
 *   Encoded value.
 */
function stringifyEntitiesLight(value, options) {
  return core(value, Object.assign({format: formatBasic}, options))
}

var noncharacter = /[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g;

/**
 * Escape a string.
 *
 * @param {string} value
 * @param {Array.<string>} subset
 * @param {RegExp} [unsafe]
 * @returns {string}
 */
function escape(value, subset, unsafe) {
  var result = clean(value);

  return unsafe ? result.replace(unsafe, encode) : encode(result)

  /**
   * @param {string} $0
   * @returns {string}
   */
  function encode($0) {
    return stringifyEntitiesLight($0, {subset})
  }
}

/**
 * @param {string} value
 * @returns {string}
 */
function clean(value) {
  return String(value || '').replace(noncharacter, '')
}

var subset$3 = ['\t', '\n', ' ', '"', '&', "'", '/', '<', '=', '>'];

/**
 * Serialize a node name.
 *
 * @param {string} value
 * @returns {string}
 */
function name(value) {
  return escape(value, subset$3)
}

/**
 * Count how often a character (or substring) is used in a string.
 *
 * @param {string} value
 *   Value to search in.
 * @param {string} character
 *   Character (or substring) to look for.
 * @return {number}
 *   Number of times `character` occurred in `value`.
 */
function ccount(value, character) {
  const source = String(value);

  if (typeof character !== 'string') {
    throw new TypeError('Expected character')
  }

  let count = 0;
  let index = source.indexOf(character);

  while (index !== -1) {
    count++;
    index = source.indexOf(character, index + character.length);
  }

  return count
}

/**
 * @typedef {import('./index.js').Context} Context
 */

/**
 * Serialize an attribute value.
 *
 * @param {string} value
 * @param {Context} ctx
 * @returns {string}
 */
function value(value, ctx) {
  var primary = ctx.quote;
  var secondary = ctx.alternative;
  var result = String(value);
  var quote =
    secondary && ccount(result, primary) > ccount(result, secondary)
      ? secondary
      : primary;

  return quote + escape(result, ['<', '&', quote]) + quote
}

/**
 * @typedef {import('./index.js').Handle} Handle
 * @typedef {import('./index.js').Element} Element
 * @typedef {import('./index.js').Attributes} Attributes
 */

var own$1 = {}.hasOwnProperty;

/**
 * Serialize an element.
 *
 * @type {Handle}
 * @param {Element} node
 */
function element(node, ctx) {
  var nodeName = name(node.name);
  var content = all(node, ctx);
  /** @type {Attributes} */
  var attributes = node.attributes || {};
  var close = content ? false : ctx.close;
  /** @type {Array.<string>} */
  var attrs = [];
  /** @type {string} */
  var key;
  /** @type {Attributes[keyof Attributes]} */
  var result;

  for (key in attributes) {
    if (own$1.call(attributes, key)) {
      result = attributes[key];

      if (result !== null && result !== undefined) {
        attrs.push(name(key) + '=' + value(result, ctx));
      }
    }
  }

  return (
    '<' +
    nodeName +
    (attrs.length === 0 ? '' : ' ' + attrs.join(' ')) +
    (close ? (ctx.tight ? '' : ' ') + '/' : '') +
    '>' +
    content +
    (close ? '' : '</' + nodeName + '>')
  )
}

/**
 * @typedef {import('./index.js').Handle} Handle
 * @typedef {import('./index.js').Text} Text
 */

var subset$2 = ['&', '<'];

/**
 * Serialize a text.
 *
 * @type {Handle}
 * @param {Text} node
 */
function text(node) {
  return escape(node.value, subset$2)
}

/**
 * @typedef {import('./index.js').Handle} Handle
 * @typedef {import('./index.js').Comment} Comment
 */

/**
 * Serialize a comment.
 *
 * @type {Handle}
 * @param {Comment} node
 */
function comment(node) {
  return '<!--' + escape(node.value, ['-']) + '-->'
}

/**
 * @typedef {import('./index.js').Handle} Handle
 * @typedef {import('./index.js').Doctype} Doctype
 */

/**
 * Serialize a doctype.
 *
 * @type {Handle}
 * @param {Doctype} node
 */
function doctype(node, ctx) {
  var nodeName = name(node.name);
  var pub = node.public;
  var sys = node.system;
  var result = '<!DOCTYPE';

  if (nodeName !== '') {
    result += ' ' + nodeName;
  }

  if (pub !== null && pub !== undefined && pub !== '') {
    result += ' PUBLIC ' + value(pub, ctx);
  } else if (sys !== null && sys !== undefined && sys !== '') {
    result += ' SYSTEM';
  }

  if (sys !== null && sys !== undefined && sys !== '') {
    result += ' ' + value(sys, ctx);
  }

  return result + '>'
}

/**
 * @typedef {import('./index.js').Handle} Handle
 * @typedef {import('./index.js').Instruction} Instruction
 */

var unsafe$1 = /\?>/g;
var subset$1 = ['>'];

/**
 * Serialize an instruction.
 *
 * @type {Handle}
 * @param {Instruction} node
 */
function instruction(node) {
  var nodeName = name(node.name) || 'x';
  var result = escape(node.value, subset$1, unsafe$1);
  return '<?' + nodeName + (result ? ' ' + result : '') + '?>'
}

/**
 * @typedef {import('./index.js').Handle} Handle
 * @typedef {import('./index.js').Cdata} Cdata
 */

var unsafe = /]]>/g;
var subset = ['>'];

/**
 * Serialize a CDATA section.
 *
 * @type {Handle}
 * @param {Cdata} node
 */
function cdata(node) {
  return '<![CDATA[' + escape(node.value, subset, unsafe) + ']]>'
}

/**
 * @typedef {import('./index.js').Handle} Handle
 * @typedef {import('./index.js').Raw} Raw
 */

/**
 * Serialize a (non-standard) raw.
 *
 * @type {Handle}
 * @param {Raw} node
 */
function raw(node, ctx) {
  // @ts-ignore Looks like a text.
  return ctx.dangerous ? node.value : text(node)
}

/**
 * @typedef {import('./index.js').Handle} Handle
 */

var own = {}.hasOwnProperty;

var handlers = {
  root: all,
  element,
  text,
  comment,
  doctype,
  instruction,
  cdata,
  raw
};

/**
 * Serialize a node.
 *
 * @type {Handle}
 */
function one(node, ctx) {
  var type = node && node.type;

  if (!type) {
    throw new Error('Expected node, not `' + node + '`')
  }

  if (!own.call(handlers, type)) {
    throw new Error('Cannot compile unknown node `' + type + '`')
  }

  // @ts-ignore Hush, it works.
  return handlers[type](node, ctx)
}

/**
 * @typedef {import('xast').Root} Root
 * @typedef {import('xast').Element} Element
 * @typedef {import('xast').Cdata} Cdata
 * @typedef {import('xast').Comment} Comment
 * @typedef {import('xast').Doctype} Doctype
 * @typedef {import('xast').Instruction} Instruction
 * @typedef {import('xast').Text} Text
 * @typedef {import('xast').Literal & {type: 'raw'}} Raw
 * @typedef {Root|Element} Parent
 * @typedef {import('xast').Attributes} Attributes
 * @typedef {Root['children'][number]} Child
 * @typedef {Child|Root} Node
 *
 * @typedef {'"'|"'"} Quote
 *
 * @typedef Options
 * @property {Quote} [quote='"'] Preferred quote to use
 * @property {boolean} [quoteSmart=false] Use the other quote if that results in
 *   less bytes
 * @property {boolean} [closeEmptyElements=false] Close elements without any
 *   content with slash (/) on the opening tag instead of an end tag:
 *   `<circle />` instead of `<circle></circle>`.
 *   See `tightClose` to control whether a space is used before the slash.
 * @property {boolean} [tightClose=false] Do not use an extra space when closing
 *    self-closing elements: `<circle/>` instead of `<circle />`.
 * @property {boolean} [allowDangerousXml=false] Allow `raw` nodes and insert
 *   them as raw XML. When falsey, encodes `raw` nodes.
 *   Only set this if you completely trust the content!
 *
 * @typedef Context
 * @property {Quote} quote
 * @property {Quote} alternative
 * @property {boolean} close
 * @property {boolean} tight
 * @property {boolean} dangerous
 *
 * @callback Handle
 * @param {Node} node
 * @param {Context} context
 * @returns {string}
 */

/**
 * Serialize the given xast tree (or list of nodes).
 *
 * @param {Node|Array.<Node>} node
 * @param {Options} [options]
 * @returns {string}
 */
function toXml(node, options = {}) {
  var quote = options.quote || '"';
  /** @type {Quote} */
  var alternative = quote === '"' ? "'" : '"';
  var smart = options.quoteSmart;
  /** @type {Node} */
  // @ts-ignore Assume no `root` in `node`.
  var value = Array.isArray(node) ? {type: 'root', children: node} : node;

  if (quote !== '"' && quote !== "'") {
    throw new Error('Invalid quote `' + quote + '`, expected `\'` or `"`')
  }

  return one(value, {
    dangerous: options.allowDangerousXml,
    close: options.closeEmptyElements,
    tight: options.tightClose,
    quote,
    alternative: smart ? alternative : null
  })
}

const BR = u('text', '\n');
const TAB = u('text', '  ');
/**
 * Convert nested folder structure to KML. This expects
 * input that follows the same patterns as [toGeoJSON](https://github.com/placemark/togeojson)'s
 * kmlWithFolders method: a tree of folders and features,
 * starting with a root element.
 */
function foldersToKML(root) {
    return toXml(u('root', [
        x('kml', { xmlns: 'http://www.opengis.net/kml/2.2' }, x('Document', root.children.flatMap((child) => convertChild(child)))),
    ]));
}
/**
 * Convert a GeoJSON FeatureCollection to a string of
 * KML data.
 */
function toKML(featureCollection) {
    return toXml(u('root', [
        x('kml', { xmlns: 'http://www.opengis.net/kml/2.2' }, x('Document', featureCollection.features.flatMap((feature) => convertFeature(feature)))),
    ]));
}
function convertChild(child) {
    switch (child.type) {
        case 'Feature':
            return convertFeature(child);
        case 'folder':
            return convertFolder(child);
    }
}
function convertFolder(folder) {
    const id = ['string', 'number'].includes(typeof folder.meta.id)
        ? {
            id: String(folder.meta.id),
        }
        : {};
    return [
        BR,
        x('Folder', id, [
            BR,
            ...folderMeta(folder.meta),
            BR,
            TAB,
            ...folder.children.flatMap((child) => convertChild(child)),
        ]),
    ];
}
const META_PROPERTIES = [
    'address',
    'description',
    'name',
    'open',
    'visibility',
    'phoneNumber',
];
function folderMeta(meta) {
    return META_PROPERTIES.filter((p) => meta[p] !== undefined).map((p) => {
        return x(p, [u('text', String(meta[p]))]);
    });
}
function convertFeature(feature) {
    const { id } = feature;
    const idMember = ['string', 'number'].includes(typeof id)
        ? {
            id: id,
        }
        : {};
    return [
        BR,
        x('Placemark', idMember, [
            BR,
            ...propertiesToTags(feature.properties),
            BR,
            TAB,
            ...(feature.geometry ? [convertGeometry(feature.geometry)] : []),
        ]),
    ];
}
function join(position) {
    return `${position[0]},${position[1]}`;
}
function coord1(coordinates) {
    return x('coordinates', [u('text', join(coordinates))]);
}
function coord2(coordinates) {
    return x('coordinates', [u('text', coordinates.map(join).join('\n'))]);
}
function toString(value) {
    switch (typeof value) {
        case 'string': {
            return value;
        }
        case 'boolean':
        case 'number': {
            return String(value);
        }
        case 'object': {
            try {
                return JSON.stringify(value);
            }
            catch (e) {
                return '';
            }
        }
    }
    return '';
}
function maybeCData(value) {
    if (value &&
        typeof value === 'object' &&
        '@type' in value &&
        value['@type'] === 'html' &&
        'value' in value &&
        typeof value.value === 'string') {
        return u('cdata', value.value);
    }
    return toString(value);
}
function propertiesToTags(properties) {
    if (!properties)
        return [];
    const { name, description, visibility, ...otherProperties } = properties;
    return [
        name && x('name', [u('text', toString(name))]),
        description && x('description', [u('text', maybeCData(description))]),
        visibility !== undefined &&
            x('visibility', [u('text', visibility ? '1' : '0')]),
        x('ExtendedData', Object.entries(otherProperties).flatMap(([name, value]) => [
            BR,
            TAB,
            x('Data', { name: name }, [
                x('value', [
                    u('text', typeof value === 'string' ? value : JSON.stringify(value)),
                ]),
            ]),
        ])),
    ].filter(Boolean);
}
const linearRing = (ring) => x('LinearRing', [coord2(ring)]);
function convertMultiPoint(geometry) {
    return x('MultiGeometry', geometry.coordinates.flatMap((coordinates) => [
        BR,
        convertGeometry({
            type: 'Point',
            coordinates,
        }),
    ]));
}
function convertMultiLineString(geometry) {
    return x('MultiGeometry', geometry.coordinates.flatMap((coordinates) => [
        BR,
        convertGeometry({
            type: 'LineString',
            coordinates,
        }),
    ]));
}
function convertMultiPolygon(geometry) {
    return x('MultiGeometry', geometry.coordinates.flatMap((coordinates) => [
        BR,
        convertGeometry({
            type: 'Polygon',
            coordinates,
        }),
    ]));
}
function convertPolygon(geometry) {
    const [outerBoundary, ...innerRings] = geometry.coordinates;
    return x('Polygon', [
        BR,
        x('outerBoundaryIs', [BR, TAB, linearRing(outerBoundary)]),
        ...innerRings.flatMap((innerRing) => [
            BR,
            x('innerBoundaryIs', [BR, TAB, linearRing(innerRing)]),
        ]),
    ]);
}
function convertGeometry(geometry) {
    switch (geometry.type) {
        case 'Point':
            return x('Point', [coord1(geometry.coordinates)]);
        case 'MultiPoint':
            return convertMultiPoint(geometry);
        case 'LineString':
            return x('LineString', [coord2(geometry.coordinates)]);
        case 'MultiLineString':
            return convertMultiLineString(geometry);
        case 'Polygon':
            return convertPolygon(geometry);
        case 'MultiPolygon':
            return convertMultiPolygon(geometry);
        case 'GeometryCollection':
            return x('MultiGeometry', geometry.geometries.flatMap((geometry) => [
                BR,
                convertGeometry(geometry),
            ]));
    }
}

exports.foldersToKML = foldersToKML;
exports.toKML = toKML;


},{}],"@tmcw/togeojson":[function(require,module,exports){
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).toGeoJSON={})}(this,(function(t){"use strict";function e(t,e){return Array.from(t.getElementsByTagName(e))}function n(t){return"#"===t[0]?t:`#${t}`}function o(t){return t?.normalize(),t&&t.textContent||""}function r(t,e,n){const o=t.getElementsByTagName(e),r=o.length?o[0]:null;return r&&n&&n(r),r}function i(t,e,n){const o={};if(!t)return o;const r=t.getElementsByTagName(e),i=r.length?r[0]:null;return i&&n?n(i,o):o}function s(t,e,n){const i=o(r(t,e));return i&&n&&n(i)||{}}function c(t,e,n){const i=parseFloat(o(r(t,e)));if(!isNaN(i))return i&&n&&n(i)||{}}function a(t,e,n){const i=parseFloat(o(r(t,e)));if(!isNaN(i))return i&&n&&n(i),i}function l(t,e){const n={};for(const o of e)s(t,o,(t=>{n[o]=t}));return n}function u(t){return 1===t?.nodeType}function f(t){return i(t,"line",(t=>Object.assign({},s(t,"color",(t=>({stroke:`#${t}`}))),c(t,"opacity",(t=>({"stroke-opacity":t}))),c(t,"width",(t=>({"stroke-width":96*t/25.4}))))))}function p(t){let e=[];if(null===t)return e;for(const n of Array.from(t.childNodes)){if(!u(n))continue;const t=g(n.nodeName);if("gpxtpx:TrackPointExtension"===t)e=e.concat(p(n));else{const r=o(n);e.push([t,d(r)])}}return e}function g(t){return["heart","gpxtpx:hr","hr"].includes(t)?"heart":t}function d(t){const e=parseFloat(t);return isNaN(e)?t:e}function h(t){const e=[parseFloat(t.getAttribute("lon")||""),parseFloat(t.getAttribute("lat")||"")];if(isNaN(e[0])||isNaN(e[1]))return null;a(t,"ele",(t=>{e.push(t)}));const n=r(t,"time");return{coordinates:e,time:n?o(n):null,extendedValues:p(r(t,"extensions"))}}function m(t){const n=l(t,["name","cmt","desc","type","time","keywords"]),r=Array.from(t.getElementsByTagNameNS("http://www.garmin.com/xmlschemas/GpxExtensions/v3","*"));for(const e of r)e.parentNode?.parentNode===t&&(n[e.tagName.replace(":","_")]=o(e));const i=e(t,"link");return i.length&&(n.links=i.map((t=>Object.assign({href:t.getAttribute("href")},l(t,["text","type"]))))),n}function y(t,n){const o=e(t,n),r=[],i=[],s={};for(let t=0;t<o.length;t++){const e=h(o[t]);if(e){r.push(e.coordinates),e.time&&i.push(e.time);for(const[n,r]of e.extendedValues){const e="heart"===n?n:n.replace("gpxtpx:","")+"s";s[e]||(s[e]=Array(o.length).fill(null)),s[e][t]=r}}}if(!(r.length<2))return{line:r,times:i,extendedValues:s}}function b(t){const e=y(t,"rtept");if(e)return{type:"Feature",properties:Object.assign({_gpxType:"rte"},m(t),f(r(t,"extensions"))),geometry:{type:"LineString",coordinates:e.line}}}function N(t){const n=e(t,"trkseg"),o=[],i=[],s=[];for(const t of n){const e=y(t,"trkpt");e&&(s.push(e),e.times&&e.times.length&&i.push(e.times))}if(0===s.length)return null;const c=s.length>1,a=Object.assign({_gpxType:"trk"},m(t),f(r(t,"extensions")),i.length?{coordinateProperties:{times:c?i:i[0]}}:{});for(const t of s){o.push(t.line),a.coordinateProperties||(a.coordinateProperties={});const e=a.coordinateProperties,n=Object.entries(t.extendedValues);for(let t=0;t<n.length;t++){const[o,r]=n[t];c?(e[o]||(e[o]=s.map((t=>new Array(t.line.length).fill(null)))),e[o][t]=r):e[o]=r}}return{type:"Feature",properties:a,geometry:c?{type:"MultiLineString",coordinates:o}:{type:"LineString",coordinates:o[0]}}}function x(t){const e=Object.assign(m(t),l(t,["sym"])),n=h(t);return n?{type:"Feature",properties:e,geometry:{type:"Point",coordinates:n.coordinates}}:null}function*k(t){for(const n of e(t,"trk")){const t=N(n);t&&(yield t)}for(const n of e(t,"rte")){const t=b(n);t&&(yield t)}for(const n of e(t,"wpt")){const t=x(n);t&&(yield t)}}const A=[["heartRate","heartRates"],["Cadence","cadences"],["Speed","speeds"],["Watts","watts"]],S=[["TotalTimeSeconds","totalTimeSeconds"],["DistanceMeters","distanceMeters"],["MaximumSpeed","maxSpeed"],["AverageHeartRateBpm","avgHeartRate"],["MaximumHeartRateBpm","maxHeartRate"],["AvgSpeed","avgSpeed"],["AvgWatts","avgWatts"],["MaxWatts","maxWatts"]];function v(t,e){const n=[];for(const[i,s]of e){let e=r(t,i);if(!e){const n=t.getElementsByTagNameNS("http://www.garmin.com/xmlschemas/ActivityExtension/v2",i);n.length&&(e=n[0])}const c=parseFloat(o(e));isNaN(c)||n.push([s,c])}return n}function T(t){const e=[a(t,"LongitudeDegrees"),a(t,"LatitudeDegrees")];if(void 0===e[0]||isNaN(e[0])||void 0===e[1]||isNaN(e[1]))return null;const n=r(t,"HeartRateBpm"),i=o(r(t,"Time"));return r(t,"AltitudeMeters",(t=>{const n=parseFloat(o(t));isNaN(n)||e.push(n)})),{coordinates:e,time:i||null,heartRate:n?parseFloat(o(n)):null,extensions:v(t,A)}}function F(t){const n=e(t,"Trackpoint"),o=[],r=[],i=[];if(n.length<2)return null;const s={},c={extendedProperties:s};for(let t=0;t<n.length;t++){const e=T(n[t]);if(null===e)continue;o.push(e.coordinates);const{time:c,heartRate:a,extensions:l}=e;c&&r.push(c),a&&i.push(a);for(const[e,o]of l)s[e]||(s[e]=Array(n.length).fill(null)),s[e][t]=o}return o.length<2?null:Object.assign(c,{line:o,times:r,heartRates:i})}function P(t){const n=e(t,"Track"),r=[],s=[],c=[],a=[];let l;const u=Object.assign(Object.fromEntries(v(t,S)),i(t,"Name",(t=>({name:o(t)}))));for(const t of n)l=F(t),l&&(r.push(l.line),l.times.length&&s.push(l.times),l.heartRates.length&&c.push(l.heartRates),a.push(l.extendedProperties));for(let t=0;t<a.length;t++){const e=a[t];for(const o in e)1===n.length?l&&(u[o]=l.extendedProperties[o]):(u[o]||(u[o]=r.map((t=>Array(t.length).fill(null)))),u[o][t]=e[o])}return 0===r.length?null:((s.length||c.length)&&(u.coordinateProperties=Object.assign(s.length?{times:1===r.length?s[0]:s}:{},c.length?{heart:1===r.length?c[0]:c}:{})),{type:"Feature",properties:u,geometry:1===r.length?{type:"LineString",coordinates:r[0]}:{type:"MultiLineString",coordinates:r}})}function*O(t){for(const n of e(t,"Lap")){const t=P(n);t&&(yield t)}for(const n of e(t,"Courses")){const t=P(n);t&&(yield t)}}function w(t,e){const n={},o="stroke"==e||"fill"===e?e:e+"-color";return"#"===t[0]&&(t=t.substring(1)),6===t.length||3===t.length?n[o]="#"+t:8===t.length&&(n[e+"-opacity"]=parseInt(t.substring(0,2),16)/255,n[o]="#"+t.substring(6,8)+t.substring(4,6)+t.substring(2,4)),n}function M(t,e,n){const o={};return a(t,e,(t=>{o[n]=t})),o}function j(t,e){return i(t,"color",(t=>w(o(t),e)))}function L(t){return i(t,"Icon",((t,e)=>(s(t,"href",(t=>{e.icon=t})),e)))}function R(t){return Object.assign({},function(t){return i(t,"PolyStyle",((t,e)=>Object.assign(e,i(t,"color",(t=>w(o(t),"fill"))),s(t,"fill",(t=>{if("0"===t)return{"fill-opacity":0}})),s(t,"outline",(t=>{if("0"===t)return{"stroke-opacity":0}})))))}(t),function(t){return i(t,"LineStyle",(t=>Object.assign(j(t,"stroke"),M(t,"width","stroke-width"))))}(t),function(t){return i(t,"LabelStyle",(t=>Object.assign(j(t,"label"),M(t,"scale","label-scale"))))}(t),function(t){return i(t,"IconStyle",(t=>Object.assign(j(t,"icon"),M(t,"scale","icon-scale"),M(t,"heading","icon-heading"),i(t,"hotSpot",(t=>{const e=parseFloat(t.getAttribute("x")||""),n=parseFloat(t.getAttribute("y")||""),o=t.getAttribute("xunits")||"",r=t.getAttribute("yunits")||"";return isNaN(e)||isNaN(n)?{}:{"icon-offset":[e,n],"icon-offset-units":[o,r]}})),L(t))))}(t))}const B=t=>Number(t),E={string:t=>t,int:B,uint:B,short:B,ushort:B,float:B,double:B,bool:t=>Boolean(t)};function G(t,n){return i(t,"ExtendedData",((t,i)=>{for(const n of e(t,"Data"))i[n.getAttribute("name")||""]=o(r(n,"value"));for(const r of e(t,"SimpleData")){const t=r.getAttribute("name")||"",e=n[t]||E.string;i[t]=e(o(r))}return i}))}function C(t){const e=r(t,"description");for(const t of Array.from(e?.childNodes||[]))if(4===t.nodeType)return{description:{"@type":"html",value:o(t)}};return{}}function D(t){return i(t,"TimeSpan",(t=>({timespan:{begin:o(r(t,"begin")),end:o(r(t,"end"))}})))}function W(t){return i(t,"TimeStamp",(t=>({timestamp:o(r(t,"when"))})))}function H(t,e){return s(t,"styleUrl",(t=>(t=n(t),e[t]?Object.assign({styleUrl:t},e[t]):{styleUrl:t})))}const _=/\s*/g,I=/^\s*|\s*$/g,U=/\s+/;function V(t){return t.replace(_,"").split(",").map(parseFloat).filter((t=>!isNaN(t))).slice(0,3)}function $(t){return t.replace(I,"").split(U).map(V).filter((t=>t.length>=2))}function q(t){let n=e(t,"coord");var r,i,s;0===n.length&&(r=t,i="coord",s="*",n=Array.from(r.getElementsByTagNameNS(s,i)));const c=n.map((t=>o(t).split(" ").map(parseFloat)));return 0===c.length?null:{geometry:c.length>2?{type:"LineString",coordinates:c}:{type:"Point",coordinates:c[0]},times:e(t,"when").map((t=>o(t)))}}function z(t){if(0===t.length)return t;const e=t[0],n=t[t.length-1];let o=!0;for(let t=0;t<Math.max(e.length,n.length);t++)if(e[t]!==n[t]){o=!1;break}return o?t:t.concat([t[0]])}function J(t){return o(r(t,"coordinates"))}function Q(t){let n=[],o=[];for(let r=0;r<t.childNodes.length;r++){const i=t.childNodes.item(r);if(u(i))switch(i.tagName){case"MultiGeometry":case"MultiTrack":case"gx:MultiTrack":{const t=Q(i);n=n.concat(t.geometries),o=o.concat(t.coordTimes);break}case"Point":{const t=V(J(i));t.length>=2&&n.push({type:"Point",coordinates:t});break}case"LinearRing":case"LineString":{const t=$(J(i));t.length>=2&&n.push({type:"LineString",coordinates:t});break}case"Polygon":{const t=[];for(const n of e(i,"LinearRing")){const e=z($(J(n)));e.length>=4&&t.push(e)}t.length&&n.push({type:"Polygon",coordinates:t});break}case"Track":case"gx:Track":{const t=q(i);if(!t)break;const{times:e,geometry:r}=t;n.push(r),e.length&&o.push(e);break}}}return{geometries:n,coordTimes:o}}function K(t){return 0===t.length?null:1===t.length?t[0]:{type:"GeometryCollection",geometries:t}}function X(t,e,n){const{coordTimes:o,geometries:r}=Q(t),i={type:"Feature",geometry:K(r),properties:Object.assign(l(t,["name","address","visibility","open","phoneNumber","description"]),C(t),H(t,e),R(t),G(t,n),D(t),W(t),o.length?{coordinateProperties:{times:1===o.length?o[0]:o}}:{})};void 0!==i.properties?.visibility&&(i.properties.visibility="0"!==i.properties.visibility);const s=t.getAttribute("id");return null!==s&&""!==s&&(i.id=s),i}function Y(t){if(r(t,"gx:LatLonQuad")){return{type:"Polygon",coordinates:[z($(J(t)))]}}return function(t){const e=r(t,"LatLonBox");if(e){const t=a(e,"north"),n=a(e,"west"),o=a(e,"east"),r=a(e,"south"),i=a(e,"rotation");if("number"==typeof t&&"number"==typeof r&&"number"==typeof n&&"number"==typeof o){const e=[n,r,o,t];let s=[[[n,t],[o,t],[o,r],[n,r],[n,t]]];return"number"==typeof i&&(s=function(t,e,n){const o=[(t[0]+t[2])/2,(t[1]+t[3])/2];return[e[0].map((t=>{const e=t[1]-o[1],r=t[0]-o[0],i=Math.sqrt(Math.pow(e,2)+Math.pow(r,2)),s=Math.atan2(e,r)-n*Z;return[o[0]+Math.cos(s)*i,o[1]+Math.sin(s)*i]}))]}(e,s,i)),{type:"Polygon",coordinates:s}}}return null}(t)}const Z=Math.PI/180;function tt(t,e,n){const o={type:"Feature",geometry:Y(t),properties:Object.assign({"@geometry-type":"groundoverlay"},l(t,["name","address","visibility","open","phoneNumber","description"]),C(t),H(t,e),R(t),L(t),G(t,n),D(t),W(t))};void 0!==o.properties?.visibility&&(o.properties.visibility="0"!==o.properties.visibility);const r=t.getAttribute("id");return null!==r&&""!==r&&(o.id=r),o}function et(t){let e=t.getAttribute("id");const o=t.parentNode;return!e&&u(o)&&"CascadingStyle"===o.localName&&(e=o.getAttribute("kml:id")||o.getAttribute("id")),n(e||"")}function nt(t){const o={};for(const n of e(t,"Style"))o[et(n)]=R(n);for(const r of e(t,"StyleMap")){const t=n(r.getAttribute("id")||"");s(r,"styleUrl",(e=>{e=n(e),o[e]&&(o[t]=o[e])}))}return o}function ot(t){const n={};for(const o of e(t,"SimpleField"))n[o.getAttribute("name")||""]=E[o.getAttribute("type")||""]||E.string;return n}const rt=["name","visibility","open","address","description","phoneNumber","visibility"];function*it(t){const n=nt(t),o=ot(t);for(const r of e(t,"Placemark")){const t=X(r,n,o);t&&(yield t)}for(const r of e(t,"GroundOverlay")){const t=tt(r,n,o);t&&(yield t)}}t.gpx=function(t){return{type:"FeatureCollection",features:Array.from(k(t))}},t.gpxGen=k,t.kml=function(t){return{type:"FeatureCollection",features:Array.from(it(t))}},t.kmlGen=it,t.kmlWithFolders=function(t){const e=nt(t),n=ot(t),r={type:"root",children:[]};return function t(r,i){if(u(r))switch(r.tagName){case"GroundOverlay":{const t=tt(r,e,n);t&&i.children.push(t);break}case"Placemark":{const t=X(r,e,n);t&&i.children.push(t);break}case"Folder":{const t=function(t){const e={};for(const n of Array.from(t.childNodes))u(n)&&rt.includes(n.tagName)&&(e[n.tagName]=o(n));return{type:"folder",meta:e,children:[]}}(r);i.children.push(t),i=t;break}}if(r.childNodes)for(let e=0;e<r.childNodes.length;e++)t(r.childNodes[e],i)}(t,r),r},t.tcx=function(t){return{type:"FeatureCollection",features:Array.from(O(t))}},t.tcxGen=O,Object.defineProperty(t,"__esModule",{value:!0})}));


},{}],"buffer":[function(require,module,exports){
(function (Buffer){(function (){
/*!
 * The buffer module from node.js, for the browser.
 *
 * @author   Feross Aboukhadijeh <https://feross.org>
 * @license  MIT
 */
/* eslint-disable no-proto */

'use strict'

var base64 = require('base64-js')
var ieee754 = require('ieee754')

exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50

var K_MAX_LENGTH = 0x7fffffff
exports.kMaxLength = K_MAX_LENGTH

/**
 * If `Buffer.TYPED_ARRAY_SUPPORT`:
 *   === true    Use Uint8Array implementation (fastest)
 *   === false   Print warning and recommend using `buffer` v4.x which has an Object
 *               implementation (most compatible, even IE6)
 *
 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
 * Opera 11.6+, iOS 4.2+.
 *
 * We report that the browser does not support typed arrays if the are not subclassable
 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
 * for __proto__ and has a buggy typed array implementation.
 */
Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()

if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
    typeof console.error === 'function') {
  console.error(
    'This browser lacks typed array (Uint8Array) support which is required by ' +
    '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
  )
}

function typedArraySupport () {
  // Can typed array instances can be augmented?
  try {
    var arr = new Uint8Array(1)
    arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
    return arr.foo() === 42
  } catch (e) {
    return false
  }
}

Object.defineProperty(Buffer.prototype, 'parent', {
  enumerable: true,
  get: function () {
    if (!Buffer.isBuffer(this)) return undefined
    return this.buffer
  }
})

Object.defineProperty(Buffer.prototype, 'offset', {
  enumerable: true,
  get: function () {
    if (!Buffer.isBuffer(this)) return undefined
    return this.byteOffset
  }
})

function createBuffer (length) {
  if (length > K_MAX_LENGTH) {
    throw new RangeError('The value "' + length + '" is invalid for option "size"')
  }
  // Return an augmented `Uint8Array` instance
  var buf = new Uint8Array(length)
  buf.__proto__ = Buffer.prototype
  return buf
}

/**
 * The Buffer constructor returns instances of `Uint8Array` that have their
 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
 * returns a single octet.
 *
 * The `Uint8Array` prototype remains unmodified.
 */

function Buffer (arg, encodingOrOffset, length) {
  // Common case.
  if (typeof arg === 'number') {
    if (typeof encodingOrOffset === 'string') {
      throw new TypeError(
        'The "string" argument must be of type string. Received type number'
      )
    }
    return allocUnsafe(arg)
  }
  return from(arg, encodingOrOffset, length)
}

// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
if (typeof Symbol !== 'undefined' && Symbol.species != null &&
    Buffer[Symbol.species] === Buffer) {
  Object.defineProperty(Buffer, Symbol.species, {
    value: null,
    configurable: true,
    enumerable: false,
    writable: false
  })
}

Buffer.poolSize = 8192 // not used by this implementation

function from (value, encodingOrOffset, length) {
  if (typeof value === 'string') {
    return fromString(value, encodingOrOffset)
  }

  if (ArrayBuffer.isView(value)) {
    return fromArrayLike(value)
  }

  if (value == null) {
    throw TypeError(
      'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
      'or Array-like Object. Received type ' + (typeof value)
    )
  }

  if (isInstance(value, ArrayBuffer) ||
      (value && isInstance(value.buffer, ArrayBuffer))) {
    return fromArrayBuffer(value, encodingOrOffset, length)
  }

  if (typeof value === 'number') {
    throw new TypeError(
      'The "value" argument must not be of type number. Received type number'
    )
  }

  var valueOf = value.valueOf && value.valueOf()
  if (valueOf != null && valueOf !== value) {
    return Buffer.from(valueOf, encodingOrOffset, length)
  }

  var b = fromObject(value)
  if (b) return b

  if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
      typeof value[Symbol.toPrimitive] === 'function') {
    return Buffer.from(
      value[Symbol.toPrimitive]('string'), encodingOrOffset, length
    )
  }

  throw new TypeError(
    'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
    'or Array-like Object. Received type ' + (typeof value)
  )
}

/**
 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
 * if value is a number.
 * Buffer.from(str[, encoding])
 * Buffer.from(array)
 * Buffer.from(buffer)
 * Buffer.from(arrayBuffer[, byteOffset[, length]])
 **/
Buffer.from = function (value, encodingOrOffset, length) {
  return from(value, encodingOrOffset, length)
}

// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array

function assertSize (size) {
  if (typeof size !== 'number') {
    throw new TypeError('"size" argument must be of type number')
  } else if (size < 0) {
    throw new RangeError('The value "' + size + '" is invalid for option "size"')
  }
}

function alloc (size, fill, encoding) {
  assertSize(size)
  if (size <= 0) {
    return createBuffer(size)
  }
  if (fill !== undefined) {
    // Only pay attention to encoding if it's a string. This
    // prevents accidentally sending in a number that would
    // be interpretted as a start offset.
    return typeof encoding === 'string'
      ? createBuffer(size).fill(fill, encoding)
      : createBuffer(size).fill(fill)
  }
  return createBuffer(size)
}

/**
 * Creates a new filled Buffer instance.
 * alloc(size[, fill[, encoding]])
 **/
Buffer.alloc = function (size, fill, encoding) {
  return alloc(size, fill, encoding)
}

function allocUnsafe (size) {
  assertSize(size)
  return createBuffer(size < 0 ? 0 : checked(size) | 0)
}

/**
 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
 * */
Buffer.allocUnsafe = function (size) {
  return allocUnsafe(size)
}
/**
 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
 */
Buffer.allocUnsafeSlow = function (size) {
  return allocUnsafe(size)
}

function fromString (string, encoding) {
  if (typeof encoding !== 'string' || encoding === '') {
    encoding = 'utf8'
  }

  if (!Buffer.isEncoding(encoding)) {
    throw new TypeError('Unknown encoding: ' + encoding)
  }

  var length = byteLength(string, encoding) | 0
  var buf = createBuffer(length)

  var actual = buf.write(string, encoding)

  if (actual !== length) {
    // Writing a hex string, for example, that contains invalid characters will
    // cause everything after the first invalid character to be ignored. (e.g.
    // 'abxxcd' will be treated as 'ab')
    buf = buf.slice(0, actual)
  }

  return buf
}

function fromArrayLike (array) {
  var length = array.length < 0 ? 0 : checked(array.length) | 0
  var buf = createBuffer(length)
  for (var i = 0; i < length; i += 1) {
    buf[i] = array[i] & 255
  }
  return buf
}

function fromArrayBuffer (array, byteOffset, length) {
  if (byteOffset < 0 || array.byteLength < byteOffset) {
    throw new RangeError('"offset" is outside of buffer bounds')
  }

  if (array.byteLength < byteOffset + (length || 0)) {
    throw new RangeError('"length" is outside of buffer bounds')
  }

  var buf
  if (byteOffset === undefined && length === undefined) {
    buf = new Uint8Array(array)
  } else if (length === undefined) {
    buf = new Uint8Array(array, byteOffset)
  } else {
    buf = new Uint8Array(array, byteOffset, length)
  }

  // Return an augmented `Uint8Array` instance
  buf.__proto__ = Buffer.prototype
  return buf
}

function fromObject (obj) {
  if (Buffer.isBuffer(obj)) {
    var len = checked(obj.length) | 0
    var buf = createBuffer(len)

    if (buf.length === 0) {
      return buf
    }

    obj.copy(buf, 0, 0, len)
    return buf
  }

  if (obj.length !== undefined) {
    if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
      return createBuffer(0)
    }
    return fromArrayLike(obj)
  }

  if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
    return fromArrayLike(obj.data)
  }
}

function checked (length) {
  // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  // length is NaN (which is otherwise coerced to zero.)
  if (length >= K_MAX_LENGTH) {
    throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
                         'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
  }
  return length | 0
}

function SlowBuffer (length) {
  if (+length != length) { // eslint-disable-line eqeqeq
    length = 0
  }
  return Buffer.alloc(+length)
}

Buffer.isBuffer = function isBuffer (b) {
  return b != null && b._isBuffer === true &&
    b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
}

Buffer.compare = function compare (a, b) {
  if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
  if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
  if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
    throw new TypeError(
      'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
    )
  }

  if (a === b) return 0

  var x = a.length
  var y = b.length

  for (var i = 0, len = Math.min(x, y); i < len; ++i) {
    if (a[i] !== b[i]) {
      x = a[i]
      y = b[i]
      break
    }
  }

  if (x < y) return -1
  if (y < x) return 1
  return 0
}

Buffer.isEncoding = function isEncoding (encoding) {
  switch (String(encoding).toLowerCase()) {
    case 'hex':
    case 'utf8':
    case 'utf-8':
    case 'ascii':
    case 'latin1':
    case 'binary':
    case 'base64':
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return true
    default:
      return false
  }
}

Buffer.concat = function concat (list, length) {
  if (!Array.isArray(list)) {
    throw new TypeError('"list" argument must be an Array of Buffers')
  }

  if (list.length === 0) {
    return Buffer.alloc(0)
  }

  var i
  if (length === undefined) {
    length = 0
    for (i = 0; i < list.length; ++i) {
      length += list[i].length
    }
  }

  var buffer = Buffer.allocUnsafe(length)
  var pos = 0
  for (i = 0; i < list.length; ++i) {
    var buf = list[i]
    if (isInstance(buf, Uint8Array)) {
      buf = Buffer.from(buf)
    }
    if (!Buffer.isBuffer(buf)) {
      throw new TypeError('"list" argument must be an Array of Buffers')
    }
    buf.copy(buffer, pos)
    pos += buf.length
  }
  return buffer
}

function byteLength (string, encoding) {
  if (Buffer.isBuffer(string)) {
    return string.length
  }
  if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
    return string.byteLength
  }
  if (typeof string !== 'string') {
    throw new TypeError(
      'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
      'Received type ' + typeof string
    )
  }

  var len = string.length
  var mustMatch = (arguments.length > 2 && arguments[2] === true)
  if (!mustMatch && len === 0) return 0

  // Use a for loop to avoid recursion
  var loweredCase = false
  for (;;) {
    switch (encoding) {
      case 'ascii':
      case 'latin1':
      case 'binary':
        return len
      case 'utf8':
      case 'utf-8':
        return utf8ToBytes(string).length
      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return len * 2
      case 'hex':
        return len >>> 1
      case 'base64':
        return base64ToBytes(string).length
      default:
        if (loweredCase) {
          return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
        }
        encoding = ('' + encoding).toLowerCase()
        loweredCase = true
    }
  }
}
Buffer.byteLength = byteLength

function slowToString (encoding, start, end) {
  var loweredCase = false

  // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  // property of a typed array.

  // This behaves neither like String nor Uint8Array in that we set start/end
  // to their upper/lower bounds if the value passed is out of range.
  // undefined is handled specially as per ECMA-262 6th Edition,
  // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  if (start === undefined || start < 0) {
    start = 0
  }
  // Return early if start > this.length. Done here to prevent potential uint32
  // coercion fail below.
  if (start > this.length) {
    return ''
  }

  if (end === undefined || end > this.length) {
    end = this.length
  }

  if (end <= 0) {
    return ''
  }

  // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  end >>>= 0
  start >>>= 0

  if (end <= start) {
    return ''
  }

  if (!encoding) encoding = 'utf8'

  while (true) {
    switch (encoding) {
      case 'hex':
        return hexSlice(this, start, end)

      case 'utf8':
      case 'utf-8':
        return utf8Slice(this, start, end)

      case 'ascii':
        return asciiSlice(this, start, end)

      case 'latin1':
      case 'binary':
        return latin1Slice(this, start, end)

      case 'base64':
        return base64Slice(this, start, end)

      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return utf16leSlice(this, start, end)

      default:
        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
        encoding = (encoding + '').toLowerCase()
        loweredCase = true
    }
  }
}

// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
// reliably in a browserify context because there could be multiple different
// copies of the 'buffer' package in use. This method works even for Buffer
// instances that were created from another copy of the `buffer` package.
// See: https://github.com/feross/buffer/issues/154
Buffer.prototype._isBuffer = true

function swap (b, n, m) {
  var i = b[n]
  b[n] = b[m]
  b[m] = i
}

Buffer.prototype.swap16 = function swap16 () {
  var len = this.length
  if (len % 2 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 16-bits')
  }
  for (var i = 0; i < len; i += 2) {
    swap(this, i, i + 1)
  }
  return this
}

Buffer.prototype.swap32 = function swap32 () {
  var len = this.length
  if (len % 4 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 32-bits')
  }
  for (var i = 0; i < len; i += 4) {
    swap(this, i, i + 3)
    swap(this, i + 1, i + 2)
  }
  return this
}

Buffer.prototype.swap64 = function swap64 () {
  var len = this.length
  if (len % 8 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 64-bits')
  }
  for (var i = 0; i < len; i += 8) {
    swap(this, i, i + 7)
    swap(this, i + 1, i + 6)
    swap(this, i + 2, i + 5)
    swap(this, i + 3, i + 4)
  }
  return this
}

Buffer.prototype.toString = function toString () {
  var length = this.length
  if (length === 0) return ''
  if (arguments.length === 0) return utf8Slice(this, 0, length)
  return slowToString.apply(this, arguments)
}

Buffer.prototype.toLocaleString = Buffer.prototype.toString

Buffer.prototype.equals = function equals (b) {
  if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  if (this === b) return true
  return Buffer.compare(this, b) === 0
}

Buffer.prototype.inspect = function inspect () {
  var str = ''
  var max = exports.INSPECT_MAX_BYTES
  str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
  if (this.length > max) str += ' ... '
  return '<Buffer ' + str + '>'
}

Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  if (isInstance(target, Uint8Array)) {
    target = Buffer.from(target, target.offset, target.byteLength)
  }
  if (!Buffer.isBuffer(target)) {
    throw new TypeError(
      'The "target" argument must be one of type Buffer or Uint8Array. ' +
      'Received type ' + (typeof target)
    )
  }

  if (start === undefined) {
    start = 0
  }
  if (end === undefined) {
    end = target ? target.length : 0
  }
  if (thisStart === undefined) {
    thisStart = 0
  }
  if (thisEnd === undefined) {
    thisEnd = this.length
  }

  if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
    throw new RangeError('out of range index')
  }

  if (thisStart >= thisEnd && start >= end) {
    return 0
  }
  if (thisStart >= thisEnd) {
    return -1
  }
  if (start >= end) {
    return 1
  }

  start >>>= 0
  end >>>= 0
  thisStart >>>= 0
  thisEnd >>>= 0

  if (this === target) return 0

  var x = thisEnd - thisStart
  var y = end - start
  var len = Math.min(x, y)

  var thisCopy = this.slice(thisStart, thisEnd)
  var targetCopy = target.slice(start, end)

  for (var i = 0; i < len; ++i) {
    if (thisCopy[i] !== targetCopy[i]) {
      x = thisCopy[i]
      y = targetCopy[i]
      break
    }
  }

  if (x < y) return -1
  if (y < x) return 1
  return 0
}

// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  // Empty buffer means no match
  if (buffer.length === 0) return -1

  // Normalize byteOffset
  if (typeof byteOffset === 'string') {
    encoding = byteOffset
    byteOffset = 0
  } else if (byteOffset > 0x7fffffff) {
    byteOffset = 0x7fffffff
  } else if (byteOffset < -0x80000000) {
    byteOffset = -0x80000000
  }
  byteOffset = +byteOffset // Coerce to Number.
  if (numberIsNaN(byteOffset)) {
    // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
    byteOffset = dir ? 0 : (buffer.length - 1)
  }

  // Normalize byteOffset: negative offsets start from the end of the buffer
  if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  if (byteOffset >= buffer.length) {
    if (dir) return -1
    else byteOffset = buffer.length - 1
  } else if (byteOffset < 0) {
    if (dir) byteOffset = 0
    else return -1
  }

  // Normalize val
  if (typeof val === 'string') {
    val = Buffer.from(val, encoding)
  }

  // Finally, search either indexOf (if dir is true) or lastIndexOf
  if (Buffer.isBuffer(val)) {
    // Special case: looking for empty string/buffer always fails
    if (val.length === 0) {
      return -1
    }
    return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  } else if (typeof val === 'number') {
    val = val & 0xFF // Search for a byte value [0-255]
    if (typeof Uint8Array.prototype.indexOf === 'function') {
      if (dir) {
        return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
      } else {
        return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
      }
    }
    return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  }

  throw new TypeError('val must be string, number or Buffer')
}

function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  var indexSize = 1
  var arrLength = arr.length
  var valLength = val.length

  if (encoding !== undefined) {
    encoding = String(encoding).toLowerCase()
    if (encoding === 'ucs2' || encoding === 'ucs-2' ||
        encoding === 'utf16le' || encoding === 'utf-16le') {
      if (arr.length < 2 || val.length < 2) {
        return -1
      }
      indexSize = 2
      arrLength /= 2
      valLength /= 2
      byteOffset /= 2
    }
  }

  function read (buf, i) {
    if (indexSize === 1) {
      return buf[i]
    } else {
      return buf.readUInt16BE(i * indexSize)
    }
  }

  var i
  if (dir) {
    var foundIndex = -1
    for (i = byteOffset; i < arrLength; i++) {
      if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
        if (foundIndex === -1) foundIndex = i
        if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
      } else {
        if (foundIndex !== -1) i -= i - foundIndex
        foundIndex = -1
      }
    }
  } else {
    if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
    for (i = byteOffset; i >= 0; i--) {
      var found = true
      for (var j = 0; j < valLength; j++) {
        if (read(arr, i + j) !== read(val, j)) {
          found = false
          break
        }
      }
      if (found) return i
    }
  }

  return -1
}

Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  return this.indexOf(val, byteOffset, encoding) !== -1
}

Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}

Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}

function hexWrite (buf, string, offset, length) {
  offset = Number(offset) || 0
  var remaining = buf.length - offset
  if (!length) {
    length = remaining
  } else {
    length = Number(length)
    if (length > remaining) {
      length = remaining
    }
  }

  var strLen = string.length

  if (length > strLen / 2) {
    length = strLen / 2
  }
  for (var i = 0; i < length; ++i) {
    var parsed = parseInt(string.substr(i * 2, 2), 16)
    if (numberIsNaN(parsed)) return i
    buf[offset + i] = parsed
  }
  return i
}

function utf8Write (buf, string, offset, length) {
  return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}

function asciiWrite (buf, string, offset, length) {
  return blitBuffer(asciiToBytes(string), buf, offset, length)
}

function latin1Write (buf, string, offset, length) {
  return asciiWrite(buf, string, offset, length)
}

function base64Write (buf, string, offset, length) {
  return blitBuffer(base64ToBytes(string), buf, offset, length)
}

function ucs2Write (buf, string, offset, length) {
  return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}

Buffer.prototype.write = function write (string, offset, length, encoding) {
  // Buffer#write(string)
  if (offset === undefined) {
    encoding = 'utf8'
    length = this.length
    offset = 0
  // Buffer#write(string, encoding)
  } else if (length === undefined && typeof offset === 'string') {
    encoding = offset
    length = this.length
    offset = 0
  // Buffer#write(string, offset[, length][, encoding])
  } else if (isFinite(offset)) {
    offset = offset >>> 0
    if (isFinite(length)) {
      length = length >>> 0
      if (encoding === undefined) encoding = 'utf8'
    } else {
      encoding = length
      length = undefined
    }
  } else {
    throw new Error(
      'Buffer.write(string, encoding, offset[, length]) is no longer supported'
    )
  }

  var remaining = this.length - offset
  if (length === undefined || length > remaining) length = remaining

  if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
    throw new RangeError('Attempt to write outside buffer bounds')
  }

  if (!encoding) encoding = 'utf8'

  var loweredCase = false
  for (;;) {
    switch (encoding) {
      case 'hex':
        return hexWrite(this, string, offset, length)

      case 'utf8':
      case 'utf-8':
        return utf8Write(this, string, offset, length)

      case 'ascii':
        return asciiWrite(this, string, offset, length)

      case 'latin1':
      case 'binary':
        return latin1Write(this, string, offset, length)

      case 'base64':
        // Warning: maxLength not taken into account in base64Write
        return base64Write(this, string, offset, length)

      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return ucs2Write(this, string, offset, length)

      default:
        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
        encoding = ('' + encoding).toLowerCase()
        loweredCase = true
    }
  }
}

Buffer.prototype.toJSON = function toJSON () {
  return {
    type: 'Buffer',
    data: Array.prototype.slice.call(this._arr || this, 0)
  }
}

function base64Slice (buf, start, end) {
  if (start === 0 && end === buf.length) {
    return base64.fromByteArray(buf)
  } else {
    return base64.fromByteArray(buf.slice(start, end))
  }
}

function utf8Slice (buf, start, end) {
  end = Math.min(buf.length, end)
  var res = []

  var i = start
  while (i < end) {
    var firstByte = buf[i]
    var codePoint = null
    var bytesPerSequence = (firstByte > 0xEF) ? 4
      : (firstByte > 0xDF) ? 3
        : (firstByte > 0xBF) ? 2
          : 1

    if (i + bytesPerSequence <= end) {
      var secondByte, thirdByte, fourthByte, tempCodePoint

      switch (bytesPerSequence) {
        case 1:
          if (firstByte < 0x80) {
            codePoint = firstByte
          }
          break
        case 2:
          secondByte = buf[i + 1]
          if ((secondByte & 0xC0) === 0x80) {
            tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
            if (tempCodePoint > 0x7F) {
              codePoint = tempCodePoint
            }
          }
          break
        case 3:
          secondByte = buf[i + 1]
          thirdByte = buf[i + 2]
          if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
            tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
            if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
              codePoint = tempCodePoint
            }
          }
          break
        case 4:
          secondByte = buf[i + 1]
          thirdByte = buf[i + 2]
          fourthByte = buf[i + 3]
          if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
            tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
            if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
              codePoint = tempCodePoint
            }
          }
      }
    }

    if (codePoint === null) {
      // we did not generate a valid codePoint so insert a
      // replacement char (U+FFFD) and advance only 1 byte
      codePoint = 0xFFFD
      bytesPerSequence = 1
    } else if (codePoint > 0xFFFF) {
      // encode to utf16 (surrogate pair dance)
      codePoint -= 0x10000
      res.push(codePoint >>> 10 & 0x3FF | 0xD800)
      codePoint = 0xDC00 | codePoint & 0x3FF
    }

    res.push(codePoint)
    i += bytesPerSequence
  }

  return decodeCodePointsArray(res)
}

// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000

function decodeCodePointsArray (codePoints) {
  var len = codePoints.length
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  }

  // Decode in chunks to avoid "call stack size exceeded".
  var res = ''
  var i = 0
  while (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    )
  }
  return res
}

function asciiSlice (buf, start, end) {
  var ret = ''
  end = Math.min(buf.length, end)

  for (var i = start; i < end; ++i) {
    ret += String.fromCharCode(buf[i] & 0x7F)
  }
  return ret
}

function latin1Slice (buf, start, end) {
  var ret = ''
  end = Math.min(buf.length, end)

  for (var i = start; i < end; ++i) {
    ret += String.fromCharCode(buf[i])
  }
  return ret
}

function hexSlice (buf, start, end) {
  var len = buf.length

  if (!start || start < 0) start = 0
  if (!end || end < 0 || end > len) end = len

  var out = ''
  for (var i = start; i < end; ++i) {
    out += toHex(buf[i])
  }
  return out
}

function utf16leSlice (buf, start, end) {
  var bytes = buf.slice(start, end)
  var res = ''
  for (var i = 0; i < bytes.length; i += 2) {
    res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
  }
  return res
}

Buffer.prototype.slice = function slice (start, end) {
  var len = this.length
  start = ~~start
  end = end === undefined ? len : ~~end

  if (start < 0) {
    start += len
    if (start < 0) start = 0
  } else if (start > len) {
    start = len
  }

  if (end < 0) {
    end += len
    if (end < 0) end = 0
  } else if (end > len) {
    end = len
  }

  if (end < start) end = start

  var newBuf = this.subarray(start, end)
  // Return an augmented `Uint8Array` instance
  newBuf.__proto__ = Buffer.prototype
  return newBuf
}

/*
 * Need to make sure that buffer isn't trying to write out of bounds.
 */
function checkOffset (offset, ext, length) {
  if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}

Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) checkOffset(offset, byteLength, this.length)

  var val = this[offset]
  var mul = 1
  var i = 0
  while (++i < byteLength && (mul *= 0x100)) {
    val += this[offset + i] * mul
  }

  return val
}

Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) {
    checkOffset(offset, byteLength, this.length)
  }

  var val = this[offset + --byteLength]
  var mul = 1
  while (byteLength > 0 && (mul *= 0x100)) {
    val += this[offset + --byteLength] * mul
  }

  return val
}

Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 1, this.length)
  return this[offset]
}

Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 2, this.length)
  return this[offset] | (this[offset + 1] << 8)
}

Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 2, this.length)
  return (this[offset] << 8) | this[offset + 1]
}

Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)

  return ((this[offset]) |
      (this[offset + 1] << 8) |
      (this[offset + 2] << 16)) +
      (this[offset + 3] * 0x1000000)
}

Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)

  return (this[offset] * 0x1000000) +
    ((this[offset + 1] << 16) |
    (this[offset + 2] << 8) |
    this[offset + 3])
}

Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) checkOffset(offset, byteLength, this.length)

  var val = this[offset]
  var mul = 1
  var i = 0
  while (++i < byteLength && (mul *= 0x100)) {
    val += this[offset + i] * mul
  }
  mul *= 0x80

  if (val >= mul) val -= Math.pow(2, 8 * byteLength)

  return val
}

Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) checkOffset(offset, byteLength, this.length)

  var i = byteLength
  var mul = 1
  var val = this[offset + --i]
  while (i > 0 && (mul *= 0x100)) {
    val += this[offset + --i] * mul
  }
  mul *= 0x80

  if (val >= mul) val -= Math.pow(2, 8 * byteLength)

  return val
}

Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 1, this.length)
  if (!(this[offset] & 0x80)) return (this[offset])
  return ((0xff - this[offset] + 1) * -1)
}

Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 2, this.length)
  var val = this[offset] | (this[offset + 1] << 8)
  return (val & 0x8000) ? val | 0xFFFF0000 : val
}

Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 2, this.length)
  var val = this[offset + 1] | (this[offset] << 8)
  return (val & 0x8000) ? val | 0xFFFF0000 : val
}

Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)

  return (this[offset]) |
    (this[offset + 1] << 8) |
    (this[offset + 2] << 16) |
    (this[offset + 3] << 24)
}

Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)

  return (this[offset] << 24) |
    (this[offset + 1] << 16) |
    (this[offset + 2] << 8) |
    (this[offset + 3])
}

Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)
  return ieee754.read(this, offset, true, 23, 4)
}

Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)
  return ieee754.read(this, offset, false, 23, 4)
}

Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 8, this.length)
  return ieee754.read(this, offset, true, 52, 8)
}

Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 8, this.length)
  return ieee754.read(this, offset, false, 52, 8)
}

function checkInt (buf, value, offset, ext, max, min) {
  if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  if (offset + ext > buf.length) throw new RangeError('Index out of range')
}

Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) {
    var maxBytes = Math.pow(2, 8 * byteLength) - 1
    checkInt(this, value, offset, byteLength, maxBytes, 0)
  }

  var mul = 1
  var i = 0
  this[offset] = value & 0xFF
  while (++i < byteLength && (mul *= 0x100)) {
    this[offset + i] = (value / mul) & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) {
    var maxBytes = Math.pow(2, 8 * byteLength) - 1
    checkInt(this, value, offset, byteLength, maxBytes, 0)
  }

  var i = byteLength - 1
  var mul = 1
  this[offset + i] = value & 0xFF
  while (--i >= 0 && (mul *= 0x100)) {
    this[offset + i] = (value / mul) & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  this[offset] = (value & 0xff)
  return offset + 1
}

Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  this[offset] = (value & 0xff)
  this[offset + 1] = (value >>> 8)
  return offset + 2
}

Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  this[offset] = (value >>> 8)
  this[offset + 1] = (value & 0xff)
  return offset + 2
}

Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  this[offset + 3] = (value >>> 24)
  this[offset + 2] = (value >>> 16)
  this[offset + 1] = (value >>> 8)
  this[offset] = (value & 0xff)
  return offset + 4
}

Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  this[offset] = (value >>> 24)
  this[offset + 1] = (value >>> 16)
  this[offset + 2] = (value >>> 8)
  this[offset + 3] = (value & 0xff)
  return offset + 4
}

Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) {
    var limit = Math.pow(2, (8 * byteLength) - 1)

    checkInt(this, value, offset, byteLength, limit - 1, -limit)
  }

  var i = 0
  var mul = 1
  var sub = 0
  this[offset] = value & 0xFF
  while (++i < byteLength && (mul *= 0x100)) {
    if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
      sub = 1
    }
    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) {
    var limit = Math.pow(2, (8 * byteLength) - 1)

    checkInt(this, value, offset, byteLength, limit - 1, -limit)
  }

  var i = byteLength - 1
  var mul = 1
  var sub = 0
  this[offset + i] = value & 0xFF
  while (--i >= 0 && (mul *= 0x100)) {
    if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
      sub = 1
    }
    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  if (value < 0) value = 0xff + value + 1
  this[offset] = (value & 0xff)
  return offset + 1
}

Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  this[offset] = (value & 0xff)
  this[offset + 1] = (value >>> 8)
  return offset + 2
}

Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  this[offset] = (value >>> 8)
  this[offset + 1] = (value & 0xff)
  return offset + 2
}

Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  this[offset] = (value & 0xff)
  this[offset + 1] = (value >>> 8)
  this[offset + 2] = (value >>> 16)
  this[offset + 3] = (value >>> 24)
  return offset + 4
}

Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  if (value < 0) value = 0xffffffff + value + 1
  this[offset] = (value >>> 24)
  this[offset + 1] = (value >>> 16)
  this[offset + 2] = (value >>> 8)
  this[offset + 3] = (value & 0xff)
  return offset + 4
}

function checkIEEE754 (buf, value, offset, ext, max, min) {
  if (offset + ext > buf.length) throw new RangeError('Index out of range')
  if (offset < 0) throw new RangeError('Index out of range')
}

function writeFloat (buf, value, offset, littleEndian, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) {
    checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  }
  ieee754.write(buf, value, offset, littleEndian, 23, 4)
  return offset + 4
}

Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  return writeFloat(this, value, offset, true, noAssert)
}

Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  return writeFloat(this, value, offset, false, noAssert)
}

function writeDouble (buf, value, offset, littleEndian, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) {
    checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  }
  ieee754.write(buf, value, offset, littleEndian, 52, 8)
  return offset + 8
}

Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  return writeDouble(this, value, offset, true, noAssert)
}

Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  return writeDouble(this, value, offset, false, noAssert)
}

// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
  if (!start) start = 0
  if (!end && end !== 0) end = this.length
  if (targetStart >= target.length) targetStart = target.length
  if (!targetStart) targetStart = 0
  if (end > 0 && end < start) end = start

  // Copy 0 bytes; we're done
  if (end === start) return 0
  if (target.length === 0 || this.length === 0) return 0

  // Fatal error conditions
  if (targetStart < 0) {
    throw new RangeError('targetStart out of bounds')
  }
  if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
  if (end < 0) throw new RangeError('sourceEnd out of bounds')

  // Are we oob?
  if (end > this.length) end = this.length
  if (target.length - targetStart < end - start) {
    end = target.length - targetStart + start
  }

  var len = end - start

  if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
    // Use built-in when available, missing from IE11
    this.copyWithin(targetStart, start, end)
  } else if (this === target && start < targetStart && targetStart < end) {
    // descending copy from end
    for (var i = len - 1; i >= 0; --i) {
      target[i + targetStart] = this[i + start]
    }
  } else {
    Uint8Array.prototype.set.call(
      target,
      this.subarray(start, end),
      targetStart
    )
  }

  return len
}

// Usage:
//    buffer.fill(number[, offset[, end]])
//    buffer.fill(buffer[, offset[, end]])
//    buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
  // Handle string cases:
  if (typeof val === 'string') {
    if (typeof start === 'string') {
      encoding = start
      start = 0
      end = this.length
    } else if (typeof end === 'string') {
      encoding = end
      end = this.length
    }
    if (encoding !== undefined && typeof encoding !== 'string') {
      throw new TypeError('encoding must be a string')
    }
    if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
      throw new TypeError('Unknown encoding: ' + encoding)
    }
    if (val.length === 1) {
      var code = val.charCodeAt(0)
      if ((encoding === 'utf8' && code < 128) ||
          encoding === 'latin1') {
        // Fast path: If `val` fits into a single byte, use that numeric value.
        val = code
      }
    }
  } else if (typeof val === 'number') {
    val = val & 255
  }

  // Invalid ranges are not set to a default, so can range check early.
  if (start < 0 || this.length < start || this.length < end) {
    throw new RangeError('Out of range index')
  }

  if (end <= start) {
    return this
  }

  start = start >>> 0
  end = end === undefined ? this.length : end >>> 0

  if (!val) val = 0

  var i
  if (typeof val === 'number') {
    for (i = start; i < end; ++i) {
      this[i] = val
    }
  } else {
    var bytes = Buffer.isBuffer(val)
      ? val
      : Buffer.from(val, encoding)
    var len = bytes.length
    if (len === 0) {
      throw new TypeError('The value "' + val +
        '" is invalid for argument "value"')
    }
    for (i = 0; i < end - start; ++i) {
      this[i + start] = bytes[i % len]
    }
  }

  return this
}

// HELPER FUNCTIONS
// ================

var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g

function base64clean (str) {
  // Node takes equal signs as end of the Base64 encoding
  str = str.split('=')[0]
  // Node strips out invalid characters like \n and \t from the string, base64-js does not
  str = str.trim().replace(INVALID_BASE64_RE, '')
  // Node converts strings with length < 2 to ''
  if (str.length < 2) return ''
  // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  while (str.length % 4 !== 0) {
    str = str + '='
  }
  return str
}

function toHex (n) {
  if (n < 16) return '0' + n.toString(16)
  return n.toString(16)
}

function utf8ToBytes (string, units) {
  units = units || Infinity
  var codePoint
  var length = string.length
  var leadSurrogate = null
  var bytes = []

  for (var i = 0; i < length; ++i) {
    codePoint = string.charCodeAt(i)

    // is surrogate component
    if (codePoint > 0xD7FF && codePoint < 0xE000) {
      // last char was a lead
      if (!leadSurrogate) {
        // no lead yet
        if (codePoint > 0xDBFF) {
          // unexpected trail
          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
          continue
        } else if (i + 1 === length) {
          // unpaired lead
          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
          continue
        }

        // valid lead
        leadSurrogate = codePoint

        continue
      }

      // 2 leads in a row
      if (codePoint < 0xDC00) {
        if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
        leadSurrogate = codePoint
        continue
      }

      // valid surrogate pair
      codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
    } else if (leadSurrogate) {
      // valid bmp char, but last char was a lead
      if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
    }

    leadSurrogate = null

    // encode utf8
    if (codePoint < 0x80) {
      if ((units -= 1) < 0) break
      bytes.push(codePoint)
    } else if (codePoint < 0x800) {
      if ((units -= 2) < 0) break
      bytes.push(
        codePoint >> 0x6 | 0xC0,
        codePoint & 0x3F | 0x80
      )
    } else if (codePoint < 0x10000) {
      if ((units -= 3) < 0) break
      bytes.push(
        codePoint >> 0xC | 0xE0,
        codePoint >> 0x6 & 0x3F | 0x80,
        codePoint & 0x3F | 0x80
      )
    } else if (codePoint < 0x110000) {
      if ((units -= 4) < 0) break
      bytes.push(
        codePoint >> 0x12 | 0xF0,
        codePoint >> 0xC & 0x3F | 0x80,
        codePoint >> 0x6 & 0x3F | 0x80,
        codePoint & 0x3F | 0x80
      )
    } else {
      throw new Error('Invalid code point')
    }
  }

  return bytes
}

function asciiToBytes (str) {
  var byteArray = []
  for (var i = 0; i < str.length; ++i) {
    // Node's code seems to be doing this and not & 0x7F..
    byteArray.push(str.charCodeAt(i) & 0xFF)
  }
  return byteArray
}

function utf16leToBytes (str, units) {
  var c, hi, lo
  var byteArray = []
  for (var i = 0; i < str.length; ++i) {
    if ((units -= 2) < 0) break

    c = str.charCodeAt(i)
    hi = c >> 8
    lo = c % 256
    byteArray.push(lo)
    byteArray.push(hi)
  }

  return byteArray
}

function base64ToBytes (str) {
  return base64.toByteArray(base64clean(str))
}

function blitBuffer (src, dst, offset, length) {
  for (var i = 0; i < length; ++i) {
    if ((i + offset >= dst.length) || (i >= src.length)) break
    dst[i + offset] = src[i]
  }
  return i
}

// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
// the `instanceof` check but they should be treated as of that type.
// See: https://github.com/feross/buffer/issues/166
function isInstance (obj, type) {
  return obj instanceof type ||
    (obj != null && obj.constructor != null && obj.constructor.name != null &&
      obj.constructor.name === type.name)
}
function numberIsNaN (obj) {
  // For IE11 support
  return obj !== obj // eslint-disable-line no-self-compare
}

}).call(this)}).call(this,require("buffer").Buffer)
},{"base64-js":53,"buffer":"buffer","ieee754":69}],"flatbush":[function(require,module,exports){
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Flatbush = factory());
})(this, (function () { 'use strict';

var FlatQueue = function FlatQueue() {
    this.ids = [];
    this.values = [];
    this.length = 0;
};

FlatQueue.prototype.clear = function clear () {
    this.length = 0;
};

FlatQueue.prototype.push = function push (id, value) {
    var pos = this.length++;
    this.ids[pos] = id;
    this.values[pos] = value;

    while (pos > 0) {
        var parent = (pos - 1) >> 1;
        var parentValue = this.values[parent];
        if (value >= parentValue) { break; }
        this.ids[pos] = this.ids[parent];
        this.values[pos] = parentValue;
        pos = parent;
    }

    this.ids[pos] = id;
    this.values[pos] = value;
};

FlatQueue.prototype.pop = function pop () {
    if (this.length === 0) { return undefined; }

    var top = this.ids[0];
    this.length--;

    if (this.length > 0) {
        var id = this.ids[0] = this.ids[this.length];
        var value = this.values[0] = this.values[this.length];
        var halfLength = this.length >> 1;
        var pos = 0;

        while (pos < halfLength) {
            var left = (pos << 1) + 1;
            var right = left + 1;
            var bestIndex = this.ids[left];
            var bestValue = this.values[left];
            var rightValue = this.values[right];

            if (right < this.length && rightValue < bestValue) {
                left = right;
                bestIndex = this.ids[right];
                bestValue = rightValue;
            }
            if (bestValue >= value) { break; }

            this.ids[pos] = bestIndex;
            this.values[pos] = bestValue;
            pos = left;
        }

        this.ids[pos] = id;
        this.values[pos] = value;
    }

    return top;
};

FlatQueue.prototype.peek = function peek () {
    if (this.length === 0) { return undefined; }
    return this.ids[0];
};

FlatQueue.prototype.peekValue = function peekValue () {
    if (this.length === 0) { return undefined; }
    return this.values[0];
};

var ARRAY_TYPES = [
    Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array,
    Int32Array, Uint32Array, Float32Array, Float64Array
];

var VERSION = 3; // serialized format version

var Flatbush = function Flatbush(numItems, nodeSize, ArrayType, data) {
    if ( nodeSize === void 0 ) nodeSize = 16;
    if ( ArrayType === void 0 ) ArrayType = Float64Array;

    if (numItems === undefined) { throw new Error('Missing required argument: numItems.'); }
    if (isNaN(numItems) || numItems <= 0) { throw new Error(("Unpexpected numItems value: " + numItems + ".")); }

    this.numItems = +numItems;
    this.nodeSize = Math.min(Math.max(+nodeSize, 2), 65535);

    // calculate the total number of nodes in the R-tree to allocate space for
    // and the index of each tree level (used in search later)
    var n = numItems;
    var numNodes = n;
    this._levelBounds = [n * 4];
    do {
        n = Math.ceil(n / this.nodeSize);
        numNodes += n;
        this._levelBounds.push(numNodes * 4);
    } while (n !== 1);

    this.ArrayType = ArrayType || Float64Array;
    this.IndexArrayType = numNodes < 16384 ? Uint16Array : Uint32Array;

    var arrayTypeIndex = ARRAY_TYPES.indexOf(this.ArrayType);
    var nodesByteSize = numNodes * 4 * this.ArrayType.BYTES_PER_ELEMENT;

    if (arrayTypeIndex < 0) {
        throw new Error(("Unexpected typed array class: " + ArrayType + "."));
    }

    if (data && (data instanceof ArrayBuffer)) {
        this.data = data;
        this._boxes = new this.ArrayType(this.data, 8, numNodes * 4);
        this._indices = new this.IndexArrayType(this.data, 8 + nodesByteSize, numNodes);

        this._pos = numNodes * 4;
        this.minX = this._boxes[this._pos - 4];
        this.minY = this._boxes[this._pos - 3];
        this.maxX = this._boxes[this._pos - 2];
        this.maxY = this._boxes[this._pos - 1];

    } else {
        this.data = new ArrayBuffer(8 + nodesByteSize + numNodes * this.IndexArrayType.BYTES_PER_ELEMENT);
        this._boxes = new this.ArrayType(this.data, 8, numNodes * 4);
        this._indices = new this.IndexArrayType(this.data, 8 + nodesByteSize, numNodes);
        this._pos = 0;
        this.minX = Infinity;
        this.minY = Infinity;
        this.maxX = -Infinity;
        this.maxY = -Infinity;

        new Uint8Array(this.data, 0, 2).set([0xfb, (VERSION << 4) + arrayTypeIndex]);
        new Uint16Array(this.data, 2, 1)[0] = nodeSize;
        new Uint32Array(this.data, 4, 1)[0] = numItems;
    }

    // a priority queue for k-nearest-neighbors queries
    this._queue = new FlatQueue();
};

Flatbush.from = function from (data) {
    if (!(data instanceof ArrayBuffer)) {
        throw new Error('Data must be an instance of ArrayBuffer.');
    }
    var ref = new Uint8Array(data, 0, 2);
        var magic = ref[0];
        var versionAndType = ref[1];
    if (magic !== 0xfb) {
        throw new Error('Data does not appear to be in a Flatbush format.');
    }
    if (versionAndType >> 4 !== VERSION) {
        throw new Error(("Got v" + (versionAndType >> 4) + " data when expected v" + VERSION + "."));
    }
    var ref$1 = new Uint16Array(data, 2, 1);
        var nodeSize = ref$1[0];
    var ref$2 = new Uint32Array(data, 4, 1);
        var numItems = ref$2[0];

    return new Flatbush(numItems, nodeSize, ARRAY_TYPES[versionAndType & 0x0f], data);
};

Flatbush.prototype.add = function add (minX, minY, maxX, maxY) {
    var index = this._pos >> 2;
    this._indices[index] = index;
    this._boxes[this._pos++] = minX;
    this._boxes[this._pos++] = minY;
    this._boxes[this._pos++] = maxX;
    this._boxes[this._pos++] = maxY;

    if (minX < this.minX) { this.minX = minX; }
    if (minY < this.minY) { this.minY = minY; }
    if (maxX > this.maxX) { this.maxX = maxX; }
    if (maxY > this.maxY) { this.maxY = maxY; }

    return index;
};

Flatbush.prototype.finish = function finish () {
    if (this._pos >> 2 !== this.numItems) {
        throw new Error(("Added " + (this._pos >> 2) + " items when expected " + (this.numItems) + "."));
    }

    if (this.numItems <= this.nodeSize) {
        // only one node, skip sorting and just fill the root box
        this._boxes[this._pos++] = this.minX;
        this._boxes[this._pos++] = this.minY;
        this._boxes[this._pos++] = this.maxX;
        this._boxes[this._pos++] = this.maxY;
        return;
    }

    var width = (this.maxX - this.minX) || 1;
    var height = (this.maxY - this.minY) || 1;
    var hilbertValues = new Uint32Array(this.numItems);
    var hilbertMax = (1 << 16) - 1;

    // map item centers into Hilbert coordinate space and calculate Hilbert values
    for (var i = 0; i < this.numItems; i++) {
        var pos = 4 * i;
        var minX = this._boxes[pos++];
        var minY = this._boxes[pos++];
        var maxX = this._boxes[pos++];
        var maxY = this._boxes[pos++];
        var x = Math.floor(hilbertMax * ((minX + maxX) / 2 - this.minX) / width);
        var y = Math.floor(hilbertMax * ((minY + maxY) / 2 - this.minY) / height);
        hilbertValues[i] = hilbert(x, y);
    }

    // sort items by their Hilbert value (for packing later)
    sort(hilbertValues, this._boxes, this._indices, 0, this.numItems - 1, this.nodeSize);

    // generate nodes at each tree level, bottom-up
    for (var i$1 = 0, pos$1 = 0; i$1 < this._levelBounds.length - 1; i$1++) {
        var end = this._levelBounds[i$1];

        // generate a parent node for each block of consecutive <nodeSize> nodes
        while (pos$1 < end) {
            var nodeIndex = pos$1;

            // calculate bbox for the new node
            var nodeMinX = Infinity;
            var nodeMinY = Infinity;
            var nodeMaxX = -Infinity;
            var nodeMaxY = -Infinity;
            for (var i$2 = 0; i$2 < this.nodeSize && pos$1 < end; i$2++) {
                nodeMinX = Math.min(nodeMinX, this._boxes[pos$1++]);
                nodeMinY = Math.min(nodeMinY, this._boxes[pos$1++]);
                nodeMaxX = Math.max(nodeMaxX, this._boxes[pos$1++]);
                nodeMaxY = Math.max(nodeMaxY, this._boxes[pos$1++]);
            }

            // add the new node to the tree data
            this._indices[this._pos >> 2] = nodeIndex;
            this._boxes[this._pos++] = nodeMinX;
            this._boxes[this._pos++] = nodeMinY;
            this._boxes[this._pos++] = nodeMaxX;
            this._boxes[this._pos++] = nodeMaxY;
        }
    }
};

Flatbush.prototype.search = function search (minX, minY, maxX, maxY, filterFn) {
    if (this._pos !== this._boxes.length) {
        throw new Error('Data not yet indexed - call index.finish().');
    }

    var nodeIndex = this._boxes.length - 4;
    var queue = [];
    var results = [];

    while (nodeIndex !== undefined) {
        // find the end index of the node
        var end = Math.min(nodeIndex + this.nodeSize * 4, upperBound(nodeIndex, this._levelBounds));

        // search through child nodes
        for (var pos = nodeIndex; pos < end; pos += 4) {
            var index = this._indices[pos >> 2] | 0;

            // check if node bbox intersects with query bbox
            if (maxX < this._boxes[pos]) { continue; } // maxX < nodeMinX
            if (maxY < this._boxes[pos + 1]) { continue; } // maxY < nodeMinY
            if (minX > this._boxes[pos + 2]) { continue; } // minX > nodeMaxX
            if (minY > this._boxes[pos + 3]) { continue; } // minY > nodeMaxY

            if (nodeIndex < this.numItems * 4) {
                if (filterFn === undefined || filterFn(index)) {
                    results.push(index); // leaf item
                }

            } else {
                queue.push(index); // node; add it to the search queue
            }
        }

        nodeIndex = queue.pop();
    }

    return results;
};

Flatbush.prototype.neighbors = function neighbors (x, y, maxResults, maxDistance, filterFn) {
        if ( maxResults === void 0 ) maxResults = Infinity;
        if ( maxDistance === void 0 ) maxDistance = Infinity;

    if (this._pos !== this._boxes.length) {
        throw new Error('Data not yet indexed - call index.finish().');
    }

    var nodeIndex = this._boxes.length - 4;
    var q = this._queue;
    var results = [];
    var maxDistSquared = maxDistance * maxDistance;

    while (nodeIndex !== undefined) {
        // find the end index of the node
        var end = Math.min(nodeIndex + this.nodeSize * 4, upperBound(nodeIndex, this._levelBounds));

        // add child nodes to the queue
        for (var pos = nodeIndex; pos < end; pos += 4) {
            var index = this._indices[pos >> 2] | 0;

            var dx = axisDist(x, this._boxes[pos], this._boxes[pos + 2]);
            var dy = axisDist(y, this._boxes[pos + 1], this._boxes[pos + 3]);
            var dist = dx * dx + dy * dy;

            if (nodeIndex < this.numItems * 4) { // leaf node
                if (filterFn === undefined || filterFn(index)) {
                    // put an odd index if it's an item rather than a node, to recognize later
                    q.push((index << 1) + 1, dist);
                }
            } else {
                q.push(index << 1, dist);
            }
        }

        // pop items from the queue
        while (q.length && (q.peek() & 1)) {
            var dist$1 = q.peekValue();
            if (dist$1 > maxDistSquared) {
                q.clear();
                return results;
            }
            results.push(q.pop() >> 1);

            if (results.length === maxResults) {
                q.clear();
                return results;
            }
        }

        nodeIndex = q.pop() >> 1;
    }

    q.clear();
    return results;
};

function axisDist(k, min, max) {
    return k < min ? min - k : k <= max ? 0 : k - max;
}

// binary search for the first value in the array bigger than the given
function upperBound(value, arr) {
    var i = 0;
    var j = arr.length - 1;
    while (i < j) {
        var m = (i + j) >> 1;
        if (arr[m] > value) {
            j = m;
        } else {
            i = m + 1;
        }
    }
    return arr[i];
}

// custom quicksort that partially sorts bbox data alongside the hilbert values
function sort(values, boxes, indices, left, right, nodeSize) {
    if (Math.floor(left / nodeSize) >= Math.floor(right / nodeSize)) { return; }

    var pivot = values[(left + right) >> 1];
    var i = left - 1;
    var j = right + 1;

    while (true) {
        do { i++; } while (values[i] < pivot);
        do { j--; } while (values[j] > pivot);
        if (i >= j) { break; }
        swap(values, boxes, indices, i, j);
    }

    sort(values, boxes, indices, left, j, nodeSize);
    sort(values, boxes, indices, j + 1, right, nodeSize);
}

// swap two values and two corresponding boxes
function swap(values, boxes, indices, i, j) {
    var temp = values[i];
    values[i] = values[j];
    values[j] = temp;

    var k = 4 * i;
    var m = 4 * j;

    var a = boxes[k];
    var b = boxes[k + 1];
    var c = boxes[k + 2];
    var d = boxes[k + 3];
    boxes[k] = boxes[m];
    boxes[k + 1] = boxes[m + 1];
    boxes[k + 2] = boxes[m + 2];
    boxes[k + 3] = boxes[m + 3];
    boxes[m] = a;
    boxes[m + 1] = b;
    boxes[m + 2] = c;
    boxes[m + 3] = d;

    var e = indices[i];
    indices[i] = indices[j];
    indices[j] = e;
}

// Fast Hilbert curve algorithm by http://threadlocalmutex.com/
// Ported from C++ https://github.com/rawrunprotected/hilbert_curves (public domain)
function hilbert(x, y) {
    var a = x ^ y;
    var b = 0xFFFF ^ a;
    var c = 0xFFFF ^ (x | y);
    var d = x & (y ^ 0xFFFF);

    var A = a | (b >> 1);
    var B = (a >> 1) ^ a;
    var C = ((c >> 1) ^ (b & (d >> 1))) ^ c;
    var D = ((a & (c >> 1)) ^ (d >> 1)) ^ d;

    a = A; b = B; c = C; d = D;
    A = ((a & (a >> 2)) ^ (b & (b >> 2)));
    B = ((a & (b >> 2)) ^ (b & ((a ^ b) >> 2)));
    C ^= ((a & (c >> 2)) ^ (b & (d >> 2)));
    D ^= ((b & (c >> 2)) ^ ((a ^ b) & (d >> 2)));

    a = A; b = B; c = C; d = D;
    A = ((a & (a >> 4)) ^ (b & (b >> 4)));
    B = ((a & (b >> 4)) ^ (b & ((a ^ b) >> 4)));
    C ^= ((a & (c >> 4)) ^ (b & (d >> 4)));
    D ^= ((b & (c >> 4)) ^ ((a ^ b) & (d >> 4)));

    a = A; b = B; c = C; d = D;
    C ^= ((a & (c >> 8)) ^ (b & (d >> 8)));
    D ^= ((b & (c >> 8)) ^ ((a ^ b) & (d >> 8)));

    a = C ^ (C >> 1);
    b = D ^ (D >> 1);

    var i0 = x ^ y;
    var i1 = b | (0xFFFF ^ (i0 | a));

    i0 = (i0 | (i0 << 8)) & 0x00FF00FF;
    i0 = (i0 | (i0 << 4)) & 0x0F0F0F0F;
    i0 = (i0 | (i0 << 2)) & 0x33333333;
    i0 = (i0 | (i0 << 1)) & 0x55555555;

    i1 = (i1 | (i1 << 8)) & 0x00FF00FF;
    i1 = (i1 | (i1 << 4)) & 0x0F0F0F0F;
    i1 = (i1 | (i1 << 2)) & 0x33333333;
    i1 = (i1 | (i1 << 1)) & 0x55555555;

    return ((i1 << 1) | i0) >>> 0;
}

return Flatbush;

}));

},{}],"fs":[function(require,module,exports){
arguments[4][54][0].apply(exports,arguments)
},{"dup":54}],"iconv-lite":[function(require,module,exports){
"use strict";

var Buffer = require("safer-buffer").Buffer;

var bomHandling = require("./bom-handling"),
    iconv = module.exports;

// All codecs and aliases are kept here, keyed by encoding name/alias.
// They are lazy loaded in `iconv.getCodec` from `encodings/index.js`.
iconv.encodings = null;

// Characters emitted in case of error.
iconv.defaultCharUnicode = '�';
iconv.defaultCharSingleByte = '?';

// Public API.
iconv.encode = function encode(str, encoding, options) {
    str = "" + (str || ""); // Ensure string.

    var encoder = iconv.getEncoder(encoding, options);

    var res = encoder.write(str);
    var trail = encoder.end();
    
    return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res;
}

iconv.decode = function decode(buf, encoding, options) {
    if (typeof buf === 'string') {
        if (!iconv.skipDecodeWarning) {
            console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding');
            iconv.skipDecodeWarning = true;
        }

        buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer.
    }

    var decoder = iconv.getDecoder(encoding, options);

    var res = decoder.write(buf);
    var trail = decoder.end();

    return trail ? (res + trail) : res;
}

iconv.encodingExists = function encodingExists(enc) {
    try {
        iconv.getCodec(enc);
        return true;
    } catch (e) {
        return false;
    }
}

// Legacy aliases to convert functions
iconv.toEncoding = iconv.encode;
iconv.fromEncoding = iconv.decode;

// Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache.
iconv._codecDataCache = {};
iconv.getCodec = function getCodec(encoding) {
    if (!iconv.encodings)
        iconv.encodings = require("../encodings"); // Lazy load all encoding definitions.
    
    // Canonicalize encoding name: strip all non-alphanumeric chars and appended year.
    var enc = iconv._canonicalizeEncoding(encoding);

    // Traverse iconv.encodings to find actual codec.
    var codecOptions = {};
    while (true) {
        var codec = iconv._codecDataCache[enc];
        if (codec)
            return codec;

        var codecDef = iconv.encodings[enc];

        switch (typeof codecDef) {
            case "string": // Direct alias to other encoding.
                enc = codecDef;
                break;

            case "object": // Alias with options. Can be layered.
                for (var key in codecDef)
                    codecOptions[key] = codecDef[key];

                if (!codecOptions.encodingName)
                    codecOptions.encodingName = enc;
                
                enc = codecDef.type;
                break;

            case "function": // Codec itself.
                if (!codecOptions.encodingName)
                    codecOptions.encodingName = enc;

                // The codec function must load all tables and return object with .encoder and .decoder methods.
                // It'll be called only once (for each different options object).
                codec = new codecDef(codecOptions, iconv);

                iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later.
                return codec;

            default:
                throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')");
        }
    }
}

iconv._canonicalizeEncoding = function(encoding) {
    // Canonicalize encoding name: strip all non-alphanumeric chars and appended year.
    return (''+encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, "");
}

iconv.getEncoder = function getEncoder(encoding, options) {
    var codec = iconv.getCodec(encoding),
        encoder = new codec.encoder(options, codec);

    if (codec.bomAware && options && options.addBOM)
        encoder = new bomHandling.PrependBOM(encoder, options);

    return encoder;
}

iconv.getDecoder = function getDecoder(encoding, options) {
    var codec = iconv.getCodec(encoding),
        decoder = new codec.decoder(options, codec);

    if (codec.bomAware && !(options && options.stripBOM === false))
        decoder = new bomHandling.StripBOM(decoder, options);

    return decoder;
}

// Streaming API
// NOTE: Streaming API naturally depends on 'stream' module from Node.js. Unfortunately in browser environments this module can add
// up to 100Kb to the output bundle. To avoid unnecessary code bloat, we don't enable Streaming API in browser by default.
// If you would like to enable it explicitly, please add the following code to your app:
// > iconv.enableStreamingAPI(require('stream'));
iconv.enableStreamingAPI = function enableStreamingAPI(stream_module) {
    if (iconv.supportsStreams)
        return;

    // Dependency-inject stream module to create IconvLite stream classes.
    var streams = require("./streams")(stream_module);

    // Not public API yet, but expose the stream classes.
    iconv.IconvLiteEncoderStream = streams.IconvLiteEncoderStream;
    iconv.IconvLiteDecoderStream = streams.IconvLiteDecoderStream;

    // Streaming API.
    iconv.encodeStream = function encodeStream(encoding, options) {
        return new iconv.IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options);
    }

    iconv.decodeStream = function decodeStream(encoding, options) {
        return new iconv.IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options);
    }

    iconv.supportsStreams = true;
}

// Enable Streaming API automatically if 'stream' module is available and non-empty (the majority of environments).
var stream_module;
try {
    stream_module = require("stream");
} catch (e) {}

if (stream_module && stream_module.Transform) {
    iconv.enableStreamingAPI(stream_module);

} else {
    // In rare cases where 'stream' module is not available by default, throw a helpful exception.
    iconv.encodeStream = iconv.decodeStream = function() {
        throw new Error("iconv-lite Streaming API is not enabled. Use iconv.enableStreamingAPI(require('stream')); to enable it.");
    };
}

if ("Ā" != "\u0100") {
    console.error("iconv-lite warning: js files use non-utf8 encoding. See https://github.com/ashtuchkin/iconv-lite/wiki/Javascript-source-file-encodings for more info.");
}

},{"../encodings":13,"./bom-handling":29,"./streams":30,"safer-buffer":45,"stream":54}],"idb-keyval":[function(require,module,exports){
'use strict';

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

Object.defineProperty(exports, '__esModule', {
  value: true
});

function promisifyRequest(request) {
  return new Promise(function (resolve, reject) {
    // @ts-ignore - file size hacks
    request.oncomplete = request.onsuccess = function () {
      return resolve(request.result);
    }; // @ts-ignore - file size hacks


    request.onabort = request.onerror = function () {
      return reject(request.error);
    };
  });
}

function createStore(dbName, storeName) {
  var request = indexedDB.open(dbName);

  request.onupgradeneeded = function () {
    return request.result.createObjectStore(storeName);
  };

  var dbp = promisifyRequest(request);
  return function (txMode, callback) {
    return dbp.then(function (db) {
      return callback(db.transaction(storeName, txMode).objectStore(storeName));
    });
  };
}

var defaultGetStoreFunc;

function defaultGetStore() {
  if (!defaultGetStoreFunc) {
    defaultGetStoreFunc = createStore('keyval-store', 'keyval');
  }

  return defaultGetStoreFunc;
}
/**
 * Get a value by its key.
 *
 * @param key
 * @param customStore Method to get a custom store. Use with caution (see the docs).
 */


function get(key) {
  var customStore = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultGetStore();
  return customStore('readonly', function (store) {
    return promisifyRequest(store.get(key));
  });
}
/**
 * Set a value with a key.
 *
 * @param key
 * @param value
 * @param customStore Method to get a custom store. Use with caution (see the docs).
 */


function set(key, value) {
  var customStore = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : defaultGetStore();
  return customStore('readwrite', function (store) {
    store.put(value, key);
    return promisifyRequest(store.transaction);
  });
}
/**
 * Set multiple values at once. This is faster than calling set() multiple times.
 * It's also atomic – if one of the pairs can't be added, none will be added.
 *
 * @param entries Array of entries, where each entry is an array of `[key, value]`.
 * @param customStore Method to get a custom store. Use with caution (see the docs).
 */


function setMany(entries) {
  var customStore = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultGetStore();
  return customStore('readwrite', function (store) {
    entries.forEach(function (entry) {
      return store.put(entry[1], entry[0]);
    });
    return promisifyRequest(store.transaction);
  });
}
/**
 * Get multiple values by their keys
 *
 * @param keys
 * @param customStore Method to get a custom store. Use with caution (see the docs).
 */


function getMany(keys) {
  var customStore = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultGetStore();
  return customStore('readonly', function (store) {
    return Promise.all(keys.map(function (key) {
      return promisifyRequest(store.get(key));
    }));
  });
}
/**
 * Update a value. This lets you see the old value and update it as an atomic operation.
 *
 * @param key
 * @param updater A callback that takes the old value and returns a new value.
 * @param customStore Method to get a custom store. Use with caution (see the docs).
 */


function update(key, updater) {
  var customStore = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : defaultGetStore();
  return customStore('readwrite', function (store) {
    return (// Need to create the promise manually.
      // If I try to chain promises, the transaction closes in browsers
      // that use a promise polyfill (IE10/11).
      new Promise(function (resolve, reject) {
        store.get(key).onsuccess = function () {
          try {
            store.put(updater(this.result), key);
            resolve(promisifyRequest(store.transaction));
          } catch (err) {
            reject(err);
          }
        };
      })
    );
  });
}
/**
 * Delete a particular key from the store.
 *
 * @param key
 * @param customStore Method to get a custom store. Use with caution (see the docs).
 */


function del(key) {
  var customStore = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultGetStore();
  return customStore('readwrite', function (store) {
    store.delete(key);
    return promisifyRequest(store.transaction);
  });
}
/**
 * Delete multiple keys at once.
 *
 * @param keys List of keys to delete.
 * @param customStore Method to get a custom store. Use with caution (see the docs).
 */


function delMany(keys) {
  var customStore = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultGetStore();
  return customStore('readwrite', function (store) {
    keys.forEach(function (key) {
      return store.delete(key);
    });
    return promisifyRequest(store.transaction);
  });
}
/**
 * Clear all values in the store.
 *
 * @param customStore Method to get a custom store. Use with caution (see the docs).
 */


function clear() {
  var customStore = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultGetStore();
  return customStore('readwrite', function (store) {
    store.clear();
    return promisifyRequest(store.transaction);
  });
}

function eachCursor(store, callback) {
  store.openCursor().onsuccess = function () {
    if (!this.result) return;
    callback(this.result);
    this.result.continue();
  };

  return promisifyRequest(store.transaction);
}
/**
 * Get all keys in the store.
 *
 * @param customStore Method to get a custom store. Use with caution (see the docs).
 */


function keys() {
  var customStore = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultGetStore();
  return customStore('readonly', function (store) {
    // Fast path for modern browsers
    if (store.getAllKeys) {
      return promisifyRequest(store.getAllKeys());
    }

    var items = [];
    return eachCursor(store, function (cursor) {
      return items.push(cursor.key);
    }).then(function () {
      return items;
    });
  });
}
/**
 * Get all values in the store.
 *
 * @param customStore Method to get a custom store. Use with caution (see the docs).
 */


function values() {
  var customStore = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultGetStore();
  return customStore('readonly', function (store) {
    // Fast path for modern browsers
    if (store.getAll) {
      return promisifyRequest(store.getAll());
    }

    var items = [];
    return eachCursor(store, function (cursor) {
      return items.push(cursor.value);
    }).then(function () {
      return items;
    });
  });
}
/**
 * Get all entries in the store. Each entry is an array of `[key, value]`.
 *
 * @param customStore Method to get a custom store. Use with caution (see the docs).
 */


function entries() {
  var customStore = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultGetStore();
  return customStore('readonly', function (store) {
    // Fast path for modern browsers
    // (although, hopefully we'll get a simpler path some day)
    if (store.getAll && store.getAllKeys) {
      return Promise.all([promisifyRequest(store.getAllKeys()), promisifyRequest(store.getAll())]).then(function (_ref) {
        var _ref2 = _slicedToArray(_ref, 2),
            keys = _ref2[0],
            values = _ref2[1];

        return keys.map(function (key, i) {
          return [key, values[i]];
        });
      });
    }

    var items = [];
    return customStore('readonly', function (store) {
      return eachCursor(store, function (cursor) {
        return items.push([cursor.key, cursor.value]);
      }).then(function () {
        return items;
      });
    });
  });
}

exports.clear = clear;
exports.createStore = createStore;
exports.del = del;
exports.delMany = delMany;
exports.entries = entries;
exports.get = get;
exports.getMany = getMany;
exports.keys = keys;
exports.promisifyRequest = promisifyRequest;
exports.set = set;
exports.setMany = setMany;
exports.update = update;
exports.values = values;

},{}],"kdbush":[function(require,module,exports){
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.KDBush = factory());
}(this, (function () { 'use strict';

function sortKD(ids, coords, nodeSize, left, right, depth) {
    if (right - left <= nodeSize) { return; }

    var m = (left + right) >> 1;

    select(ids, coords, m, left, right, depth % 2);

    sortKD(ids, coords, nodeSize, left, m - 1, depth + 1);
    sortKD(ids, coords, nodeSize, m + 1, right, depth + 1);
}

function select(ids, coords, k, left, right, inc) {

    while (right > left) {
        if (right - left > 600) {
            var n = right - left + 1;
            var m = k - left + 1;
            var z = Math.log(n);
            var s = 0.5 * Math.exp(2 * z / 3);
            var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
            var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
            var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
            select(ids, coords, k, newLeft, newRight, inc);
        }

        var t = coords[2 * k + inc];
        var i = left;
        var j = right;

        swapItem(ids, coords, left, k);
        if (coords[2 * right + inc] > t) { swapItem(ids, coords, left, right); }

        while (i < j) {
            swapItem(ids, coords, i, j);
            i++;
            j--;
            while (coords[2 * i + inc] < t) { i++; }
            while (coords[2 * j + inc] > t) { j--; }
        }

        if (coords[2 * left + inc] === t) { swapItem(ids, coords, left, j); }
        else {
            j++;
            swapItem(ids, coords, j, right);
        }

        if (j <= k) { left = j + 1; }
        if (k <= j) { right = j - 1; }
    }
}

function swapItem(ids, coords, i, j) {
    swap(ids, i, j);
    swap(coords, 2 * i, 2 * j);
    swap(coords, 2 * i + 1, 2 * j + 1);
}

function swap(arr, i, j) {
    var tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}

function range(ids, coords, minX, minY, maxX, maxY, nodeSize) {
    var stack = [0, ids.length - 1, 0];
    var result = [];
    var x, y;

    while (stack.length) {
        var axis = stack.pop();
        var right = stack.pop();
        var left = stack.pop();

        if (right - left <= nodeSize) {
            for (var i = left; i <= right; i++) {
                x = coords[2 * i];
                y = coords[2 * i + 1];
                if (x >= minX && x <= maxX && y >= minY && y <= maxY) { result.push(ids[i]); }
            }
            continue;
        }

        var m = Math.floor((left + right) / 2);

        x = coords[2 * m];
        y = coords[2 * m + 1];

        if (x >= minX && x <= maxX && y >= minY && y <= maxY) { result.push(ids[m]); }

        var nextAxis = (axis + 1) % 2;

        if (axis === 0 ? minX <= x : minY <= y) {
            stack.push(left);
            stack.push(m - 1);
            stack.push(nextAxis);
        }
        if (axis === 0 ? maxX >= x : maxY >= y) {
            stack.push(m + 1);
            stack.push(right);
            stack.push(nextAxis);
        }
    }

    return result;
}

function within(ids, coords, qx, qy, r, nodeSize) {
    var stack = [0, ids.length - 1, 0];
    var result = [];
    var r2 = r * r;

    while (stack.length) {
        var axis = stack.pop();
        var right = stack.pop();
        var left = stack.pop();

        if (right - left <= nodeSize) {
            for (var i = left; i <= right; i++) {
                if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) { result.push(ids[i]); }
            }
            continue;
        }

        var m = Math.floor((left + right) / 2);

        var x = coords[2 * m];
        var y = coords[2 * m + 1];

        if (sqDist(x, y, qx, qy) <= r2) { result.push(ids[m]); }

        var nextAxis = (axis + 1) % 2;

        if (axis === 0 ? qx - r <= x : qy - r <= y) {
            stack.push(left);
            stack.push(m - 1);
            stack.push(nextAxis);
        }
        if (axis === 0 ? qx + r >= x : qy + r >= y) {
            stack.push(m + 1);
            stack.push(right);
            stack.push(nextAxis);
        }
    }

    return result;
}

function sqDist(ax, ay, bx, by) {
    var dx = ax - bx;
    var dy = ay - by;
    return dx * dx + dy * dy;
}

var defaultGetX = function (p) { return p[0]; };
var defaultGetY = function (p) { return p[1]; };

var KDBush = function KDBush(points, getX, getY, nodeSize, ArrayType) {
    if ( getX === void 0 ) getX = defaultGetX;
    if ( getY === void 0 ) getY = defaultGetY;
    if ( nodeSize === void 0 ) nodeSize = 64;
    if ( ArrayType === void 0 ) ArrayType = Float64Array;

    this.nodeSize = nodeSize;
    this.points = points;

    var IndexArrayType = points.length < 65536 ? Uint16Array : Uint32Array;

    var ids = this.ids = new IndexArrayType(points.length);
    var coords = this.coords = new ArrayType(points.length * 2);

    for (var i = 0; i < points.length; i++) {
        ids[i] = i;
        coords[2 * i] = getX(points[i]);
        coords[2 * i + 1] = getY(points[i]);
    }

    sortKD(ids, coords, nodeSize, 0, ids.length - 1, 0);
};

KDBush.prototype.range = function range$1 (minX, minY, maxX, maxY) {
    return range(this.ids, this.coords, minX, minY, maxX, maxY, this.nodeSize);
};

KDBush.prototype.within = function within$1 (x, y, r) {
    return within(this.ids, this.coords, x, y, r, this.nodeSize);
};

return KDBush;

})));

},{}],"mproj":[function(require,module,exports){
(function (__filename){(function (){
(function(){

// add math.h functions to library scope
// (to make porting projection functions simpler)
var fabs = Math.abs,
    floor = Math.floor,
    sin = Math.sin,
    cos = Math.cos,
    tan = Math.tan,
    asin = Math.asin,
    acos = Math.acos,
    atan = Math.atan,
    atan2 = Math.atan2,
    sqrt = Math.sqrt,
    pow = Math.pow,
    exp = Math.exp,
    log = Math.log,
    hypot = Math.hypot,
    sinh = Math.sinh,
    cosh = Math.cosh,
    MIN = Math.min,
    MAX = Math.max;

// constants from math.h
var HUGE_VAL = Infinity,
    M_PI = Math.PI;

// from proj_api.h
var RAD_TO_DEG = 57.295779513082321,
    DEG_TO_RAD = 0.017453292519943296;

// from pj_transform.c
var SRS_WGS84_SEMIMAJOR = 6378137;
var SRS_WGS84_ESQUARED = 0.0066943799901413165;

// math constants from project.h
var M_FORTPI = M_PI / 4,
    M_HALFPI = M_PI / 2,
    M_PI_HALFPI = 1.5 * M_PI,
    M_TWOPI = 2 * M_PI,
    M_TWO_D_PI = 2 / M_PI,
    M_TWOPI_HALFPI = 2.5 * M_PI;

// datum types
var PJD_UNKNOWN = 0,
    PJD_3PARAM = 1,
    PJD_7PARAM = 2,
    PJD_GRIDSHIFT = 3,
    PJD_WGS84 = 4;

// named errors
var PJD_ERR_GEOCENTRIC = -45,
    PJD_ERR_AXIS = -47,
    PJD_ERR_GRID_AREA = -48,
    PJD_ERR_CATALOG = -49;

// common
var EPS10 = 1e-10;


var PJ_LOG_NONE = 0,
    PJ_LOG_ERROR = 1,
    PJ_LOG_DEBUG_MAJOR = 2,
    PJ_LOG_DEBUG_MINOR = 3;

// context of currently running projection function
// (Unlike Proj.4, we use a single ctx object)
var ctx = {
  last_errno: 0,
  debug_level:  PJ_LOG_NONE,
  logger: null // TODO: implement
};



var pj_err_list = [
  "no arguments in initialization list",  /*  -1 */
  "no options found in 'init' file",    /*  -2 */
  "invalid init= string",   /*  -3 */ // Proj.4 text: "no colon in init= string",
  "projection not named",       /*  -4 */
  "unknown projection id",      /*  -5 */
  "effective eccentricity = 1",      /*  -6 */
  "unknown unit conversion id",     /*  -7 */
  "invalid boolean param argument",   /*  -8 */
  "unknown elliptical parameter name",          /*  -9 */
  "reciprocal flattening (1/f) = 0",    /* -10 */
  "|radius reference latitude| > 90",   /* -11 */
  "squared eccentricity < 0",     /* -12 */
  "major axis or radius = 0 or not given",  /* -13 */
  "latitude or longitude exceeded limits",  /* -14 */
  "invalid x or y",       /* -15 */
  "improperly formed DMS value",      /* -16 */
  "non-convergent inverse meridional dist", /* -17 */
  "non-convergent inverse phi2",      /* -18 */
  "acos/asin: |arg| >1+1e-14",     /* -19 */
  "tolerance condition error",      /* -20 */
  "conic lat_1 = -lat_2",       /* -21 */
  "lat_1 >= 90",          /* -22 */
  "lat_1 = 0",          /* -23 */
  "lat_ts >= 90",         /* -24 */
  "no distance between control points",   /* -25 */
  "projection not selected to be rotated",  /* -26 */
  "W <= 0 or M <= 0",       /* -27 */
  "lsat not in 1-5 range",      /* -28 */
  "path not in range",        /* -29 */
  "h <= 0",         /* -30 */
  "k <= 0",         /* -31 */
  "lat_0 = 0 or 90 or alpha = 90",    /* -32 */
  "lat_1=lat_2 or lat_1=0 or lat_2=90",   /* -33 */
  "elliptical usage required",      /* -34 */
  "invalid UTM zone number",      /* -35 */
  "arg(s) out of range for Tcheby eval",    /* -36 */
  "failed to find projection to be rotated",  /* -37 */
  "failed to load datum shift file",            /* -38 */
  "both n & m must be spec'd and > 0",    /* -39 */
  "n <= 0, n > 1 or not specified",   /* -40 */
  "lat_1 or lat_2 not specified",     /* -41 */
  "|lat_1| == |lat_2|",       /* -42 */
  "lat_0 is pi/2 from mean lat",      /* -43 */
  "unparseable coordinate system definition", /* -44 */
  "geocentric transformation missing z or ellps", /* -45 */
  "unknown prime meridian conversion id",   /* -46 */
  "illegal axis orientation combination",   /* -47 */
  "point not within available datum shift grids", /* -48 */
  "invalid sweep axis, choose x or y"
];


// see pj_transform.c CHECK_RETURN()
function check_fatal_error() {
  var code = ctx.last_errno;
  if (!code) return;
  if (code > 0 || !is_transient_error(code)) {
    e_error(code);
  } else {
    // transient error
    // TODO: consider a strict mode that throws an error
  }
}

function is_transient_error(code) {
  return transient_error.indexOf(code) > -1;
}

var transient_error = [-14, -15, -17, -18, -19, -20, -27, -48];

function pj_ctx_set_errno(code) {
  ctx.last_errno = code;
}

function f_error() {
  pj_ctx_set_errno(-20);
}

function i_error() {
  pj_ctx_set_errno(-20);
}

function error_msg(code) {
  return pj_err_list[~code] || "unknown error";
}

// alias for e_error()
function error(code) {
  e_error(code);
}

// a fatal error
// see projects.h E_ERROR macro
function e_error(code) {
  pj_ctx_set_errno(code);
  fatal();
}

function fatal(msg, o) {
  if (!o) o = {};
  if (!o.code) o.code = ctx.last_errno || 0;
  if (!msg) msg = error_msg(o.code);
  // reset error code, so processing can continue after this error is handled
  ctx.last_errno = 0;
  throw new ProjError(msg, o);
}

function ProjError(msg, o) {
  var err = new Error(msg);
  err.name = 'ProjError';
  Object.keys(o).forEach(function(k) {
    err[k] = o[k];
  });
  return err;
}


function dmstor(str) {
  return dmstod(str) * DEG_TO_RAD;
}

// Parse a formatted value in DMS DM or D to a numeric value
// Delimiters: D|d (degrees), ' (minutes), " (seconds)
function dmstod(str) {
  var match = /(-?[0-9.]+)d?([0-9.]*)'?([0-9.]*)"?([nsew]?)$/i.exec(str);
  var d = NaN;
  var deg, min, sec;
  if (match) {
    deg = match[1] || '0';
    min = match[2] || '0';
    sec = match[3] || '0';
    d = (+deg) + (+min) / 60 + (+sec) / 3600;
    if (/[ws]/i.test(match[4])) {
      d = -d;
    }
  }
  if (isNaN(d)) {
    // throw an exception instead of just setting an error code
    // (assumes this function is called by pj_init() or a cli program,
    // where an exception is more appropriate)
    e_error(-16);
    // pj_ctx_set_errno(-16);
    // d = HUGE_VAL;
  }
  return d;
}



function pj_atof(str) {
  return pj_strtod(str);
}

function pj_strtod(str) {
  return parseFloat(str);
}


/* types
  t  test for presence
  i  integer
  d  simple real
  r  dms or decimal degrees
  s  string
  b  boolean
*/


// see pj_param.c
// this implementation is slightly different
function pj_param(params, code) {
  var type = code[0],
      name = code.substr(1),
      obj = params[name],
      isset = obj !== void 0,
      val, param;

  if (type == 't') {
    val = isset;
  } else if (isset) {
    param = obj.param;
    obj.used = true;
    if (type == 'i') {
      val = parseInt(param);
    } else if (type == 'd') {
      // Proj.4 handles locale-specific decimal mark
      // TODO: what to do about NaNs
      val = pj_atof(param);
    } else if (type == 'r') {
      val = dmstor(param);
    } else if (type == 's') {
      val = String(param);
    } else if (type == 'b') {
      if (param == 'T' || param == 't' || param === true) {
        val = true;
      } else if (param == 'F' || param == 'f') {
        val = false;
      } else {
        pj_ctx_set_errno(-8);
        val = false;
      }
    }
  } else {
    // value is not set; use default
    val = {
      i: 0,
      b: false,
      d: 0,
      r: 0,
      s: ''
    }[type];
  }
  if (val === void 0) {
    fatal("invalid request to pj_param, fatal");
  }
  return val;
}

// convert arguments in a proj4 definition string into object properties
// (not in Proj.4)
function pj_get_params(args) {
  var rxp = /\+([a-z][a-z0-9_]*(?:=[^\s]*)?)/gi;
  var params = {};
  var match;
  while (match = rxp.exec(args)) {
    pj_mkparam(params, match[1]);
  }
  return params;
}

// different from Proj.4
function pj_mkparam(params, token) {
  var parts = token.split('=');
  var name, val;
  if (parts.length == 1) {
    name = token;
    val = true;
  } else {
    name = parts[0];
    val = token.substr(parts[0].length + 1);
  }
  params[name] = {used: false, param: val};
}



var pj_list = {};

function pj_add(func, key, name, desc) {
  pj_list[key] = {
    init: func,
    name: name,
    description: desc
  };
}


/* @pj_param */

function pj_is_latlong(P) {
  return !P || P.is_latlong;
}

function pj_is_geocent(P) {
  return !P || P.is_geocent;
}

function get_geod_defn(P) {
  var got_datum = false,
      defn = '';
  if ('datum' in P.params) {
    got_datum = true;
    defn += get_param(P, 'datum');
  } else if ('ellps' in P.params) {
    defn += get_param(P, 'ellps');
  } else if ('a' in P.params) {
    defn += get_param(P, 'a');
    if ('b' in P.params) {
      defn += get_param(P, 'b');
    } else if ('es' in P.params) {
      defn += get_param(P, 'es');
    } else if ('f' in P.params) {
      defn += get_param(P, 'f');
    } else {
      defn += ' +es=' + P.es;
    }
  } else {
    error(-13);
  }
  if (!got_datum) {
    defn += get_param(P, 'towgs84');
    defn += get_param(P, 'nadgrids');
  }
  defn += get_param(P, 'R');
  defn += get_param(P, 'R_A');
  defn += get_param(P, 'R_V');
  defn += get_param(P, 'R_a');
  defn += get_param(P, 'R_lat_a');
  defn += get_param(P, 'R_lat_g');
  defn += get_param(P, 'pm');
  return defn;
}

// Convert an initialized proj object back to a Proj.4 string
function get_proj_defn(P) {
  // skip geodetic params and some initialization-related params
  var skip = 'datum,ellps,a,b,es,rf,f,towgs84,nadgrids,R,R_A,R_V,R_a,R_lat_a,R_lat_g,pm,init,no_defs'.split(',');
  var defn = '';
  Object.keys(P.params).forEach(function(name) {
    if (skip.indexOf(name) == -1) {
      defn += get_param(P, name);
    }
  });
  // add geodetic params
  defn += get_geod_defn(P);
  return defn.trim();
}

function get_param(P, name) {
  var param = '';
  if (name in P.params) {
    param = ' +' + name;
    if (P.params[name].param !== true) {
      param += '=' + pj_param(P.params, 's' + name);
    }
  }
  return param;
}



var pj_datums = [
  /* id defn ellipse_id comments */
  ["WGS84", "towgs84=0,0,0", "WGS84", "WGS_1984"], // added comment for wkt creation
  ["GGRS87", "towgs84=-199.87,74.79,246.62", "GRS80", "Greek_Geodetic_Reference_System_1987"],
  ["NAD83", "towgs84=0,0,0", "GRS80", "North_American_Datum_1983"],
  // nadgrids not supported; NAD27 will trigger an error
  ["NAD27", "nadgrids=@conus,@alaska,@ntv2_0.gsb,@ntv1_can.dat", "clrk66", "North_American_Datum_1927"],
  ["potsdam", "towgs84=598.1,73.7,418.2,0.202,0.045,-2.455,6.7", "bessel", "Potsdam Rauenberg 1950 DHDN"],
  ["carthage","towgs84=-263.0,6.0,431.0", "clrk80ign", "Carthage 1934 Tunisia"],
  ["hermannskogel", "towgs84=577.326,90.129,463.919,5.137,1.474,5.297,2.4232", "bessel", "Hermannskogel"],
  ["ire65", "towgs84=482.530,-130.596,564.557,-1.042,-0.214,-0.631,8.15", "mod_airy", "Ireland 1965"],
  ["nzgd49", "towgs84=59.47,-5.04,187.44,0.47,-0.1,1.024,-4.5993", "intl", "New Zealand Geodetic Datum 1949"],
  ["OSGB36", "towgs84=446.448,-125.157,542.060,0.1502,0.2470,0.8421,-20.4894", "airy", "OSGB 1936"],
  [null, null, null, null]
];


var pj_prime_meridians = [
  // id definition
  ["greenwich", "0dE"],
  ["lisbon",    "9d07'54.862\"W"],
  ["paris",     "2d20'14.025\"E"],
  ["bogota",    "74d04'51.3\"W"],
  ["madrid",    "3d41'16.58\"W"],
  ["rome",      "12d27'8.4\"E"],
  ["bern",      "7d26'22.5\"E"],
  ["jakarta",   "106d48'27.79\"E"],
  ["ferro",     "17d40'W"],
  ["brussels",  "4d22'4.71\"E"],
  ["stockholm", "18d3'29.8\"E"],
  ["athens",    "23d42'58.815\"E"],
  ["oslo",      "10d43'22.5\"E"],
  [null,        null]
];

function find_prime_meridian(id) {
  var defn = pj_prime_meridians.reduce(function(memo, arr) {
    return arr[0] === id ? arr : memo;
  }, null);
  return defn ? {id: defn[0], definition: defn[1]} : null;
}

function find_datum(id) {
  var defn = pj_datums.reduce(function(memo, arr) {
    return arr[0] === id ? arr : memo;
  }, null);
  return defn ? {id: defn[0], defn: defn[1], ellipse_id: defn[2], name: defn[3]} : null;
}


function pj_datum_set(P) {
  var SEC_TO_RAD = 4.84813681109535993589914102357e-6;
  var params = P.datum_params = [0,0,0,0,0,0,0];
  var name, datum, nadgrids, catalog, towgs84;

  P.datum_type = PJD_UNKNOWN;

  if (name = pj_param(P.params, 'sdatum')) {
    datum = find_datum(name);
    if (!datum) {
      error(-9);
    }
    if (datum.ellipse_id) {
      pj_mkparam(P.params, 'ellps=' + datum.ellipse_id);
    }
    if (datum.defn) {
      pj_mkparam(P.params, datum.defn);
    }
  }

  nadgrids = pj_param(P.params, "snadgrids");
  if (nadgrids && nadgrids != '@null') {
    fatal("+nadgrids is not implemented");
  }
  if (catalog = pj_param(P.params, "scatalog")) {
    fatal("+catalog is not implemented");
  }
  if (towgs84 = pj_param(P.params, "stowgs84")) {
    towgs84.split(',').forEach(function(s, i) {
      params[i] = pj_atof(s) || 0;
    });
    if (params[3] != 0 || params[4] != 0 || params[5] != 0 || params[6] != 0) {
      P.datum_type = PJD_7PARAM;
      params[3] *= SEC_TO_RAD;
      params[4] *= SEC_TO_RAD;
      params[5] *= SEC_TO_RAD;
      params[6] =  params[6] / 1e6 + 1;
    } else {
      P.datum_type = PJD_3PARAM;
      /* Note that pj_init() will later switch datum_type to
         PJD_WGS84 if shifts are all zero, and ellipsoid is WGS84 or GRS80 */
    }
  }
}



var pj_ellps = [
  // id major ell name
  ["MERIT", "a=6378137.0", "rf=298.257", "MERIT 1983"],
  ["SGS85", "a=6378136.0", "rf=298.257", "Soviet Geodetic System 85"],
  ["GRS80", "a=6378137.0", "rf=298.257222101", "GRS 1980(IUGG, 1980)"],
  ["IAU76", "a=6378140.0", "rf=298.257", "IAU 1976"],
  ["airy", "a=6377563.396", "b=6356256.910", "Airy 1830"],
  ["APL4.9", "a=6378137.0", "rf=298.25", "Appl. Physics. 1965"],
  ["NWL9D", "a=6378145.0", "rf=298.25", "Naval Weapons Lab., 1965"],
  ["mod_airy", "a=6377340.189", "b=6356034.446", "Modified Airy"],
  ["andrae", "a=6377104.43", "rf=300.0", "Andrae 1876 (Den., Iclnd.)"],
  ["aust_SA", "a=6378160.0", "rf=298.25", "Australian Natl & S. Amer. 1969"],
  ["GRS67", "a=6378160.0", "rf=298.2471674270", "GRS 67(IUGG 1967)"],
  ["bessel", "a=6377397.155", "rf=299.1528128", "Bessel 1841"],
  ["bess_nam", "a=6377483.865", "rf=299.1528128", "Bessel 1841 (Namibia)"],
  ["clrk66", "a=6378206.4", "b=6356583.8", "Clarke 1866"],
  ["clrk80", "a=6378249.145", "rf=293.4663", "Clarke 1880 mod."],
  ["clrk80ign", "a=6378249.2", "rf=293.4660212936269", "Clarke 1880 (IGN)."],
  ["CPM", "a=6375738.7", "rf=334.29", "Comm. des Poids et Mesures 1799"],
  ["delmbr", "a=6376428", "rf=311.5", "Delambre 1810 (Belgium)"],
  ["engelis", "a=6378136.05", "rf=298.2566", "Engelis 1985"],
  ["evrst30", "a=6377276.345", "rf=300.8017", "Everest 1830"],
  ["evrst48", "a=6377304.063", "rf=300.8017", "Everest 1948"],
  ["evrst56", "a=6377301.243", "rf=300.8017", "Everest 1956"],
  ["evrst69", "a=6377295.664", "rf=300.8017", "Everest 1969"],
  ["evrstSS", "a=6377298.556", "rf=300.8017", "Everest (Sabah & Sarawak)"],
  ["fschr60", "a=6378166", "rf=298.3", "Fischer (Mercury Datum) 1960"],
  ["fschr60m", "a=6378155", "rf=298.3", "Modified Fischer 1960"],
  ["fschr68", "a=6378150", "rf=298.3", "Fischer 1968"],
  ["helmert", "a=6378200", "rf=298.3", "Helmert 1906"],
  ["hough", "a=6378270.0", "rf=297", "Hough"],
  ["intl", "a=6378388.0", "rf=297", "International 1909 (Hayford)"],
  ["krass", "a=6378245.0", "rf=298.3", "Krasovsky 1940"], // Proj.4 has "Krassovsky, 1942"
  ["kaula", "a=6378163", "rf=298.24", "Kaula 1961"],
  ["lerch", "a=6378139", "rf=298.257", "Lerch 1979"],
  ["mprts", "a=6397300", "rf=191", "Maupertius 1738"],
  ["new_intl", "a=6378157.5", "b=6356772.2", "New International 1967"],
  ["plessis", "a=6376523", "b=6355863",  "Plessis 1817 (France)"],
  ["SEasia", "a=6378155.0", "b=6356773.3205", "Southeast Asia"],
  ["walbeck", "a=6376896.0", "b=6355834.8467", "Walbeck"],
  ["WGS60", "a=6378165.0", "rf=298.3", "WGS 60"],
  ["WGS66", "a=6378145.0", "rf=298.25", "WGS 66"],
  ["WGS72", "a=6378135.0", "rf=298.26", "WGS 72"],
  ["WGS84", "a=6378137.0", "rf=298.257223563", "WGS 84"],
  ["sphere", "a=6370997.0", "b=6370997.0", "Normal Sphere (r=6370997)"],
  [null, null,  null,  null]
];

function find_ellps(id) {
  var defn = pj_ellps.reduce(function(memo, arr) {
    return arr[0] === id ? arr : memo;
  }, null);
  return defn ? {id: defn[0], major: defn[1], ell: defn[2], name: defn[3]} : null;
}


function pj_ell_set(P) {
  var SIXTH = 0.1666666666666666667, /* 1/6 */
      RA4 = 0.04722222222222222222, /* 17/360 */
      RA6 = 0.02215608465608465608, /* 67/3024 */
      RV4 = 0.06944444444444444444, /* 5/72 */
      RV6 = 0.04243827160493827160; /* 55/1296 */
  var params = P.params;
  var a = 0;
  var es = 0;
  var name, ellps, tmp, b, i;
  if (pj_param(params, 'tR')) {
    a = pj_param(params, 'dR');
  } else {
    if (name = pj_param(params, 'sellps')) {
      ellps = find_ellps(name);
      if (!ellps) {
        error(-9);
      }
      pj_mkparam(params, ellps.major);
      pj_mkparam(params, ellps.ell);
    }
    a = pj_param(params, 'da');
    if (pj_param(params, 'tes')) {
      es = pj_param(params, 'des');
    } else if (pj_param(params, 'te')) {
      tmp = pj_param(params, 'de');
      es = tmp * tmp;
    } else if (pj_param(params, 'trf')) {
      tmp = pj_param(params, 'drf');
      if (!tmp) {
        error(-10);
      }
      tmp = 1 / tmp;
      es = tmp * (2 - tmp);
    } else if (pj_param(params, 'tf')) {
      tmp = pj_param(params, 'df');
      es = tmp * (2 - tmp);
    } else if (pj_param(params, 'tb')) {
      b = pj_param(params, 'db');
      es = 1 - (b * b) / (a * a);
    }
    if (!b) {
      b = a * sqrt(1 - es);
    }

    if (pj_param(params, 'bR_A')) {
      a *= 1 - es * (SIXTH + es * (RA4 + es * RA6));
      es = 0;
    } else if (pj_param(params, 'bR_V')) {
      a *= 1 - es * (SIXTH + es * (RV4 + es * RV6));
    } else if (pj_param(params, 'bR_a')) {
      a = 0.5 * (a + b);
      es = 0;
    } else if (pj_param(params, 'bR_g')) {
      a = sqrt(a * b);
      es = 0;
    } else if (pj_param(params, 'bR_h')) {
      if (a + b === 0) {
        error(-20);
      }
      a = 2 * a * b / (a + b);
      es = 0;
    } else if (i = pj_param(params, 'tR_lat_a') || pj_param(params, 'tR_lat_g')) {
      tmp = sin(pj_param(params, i ? 'rR_lat_a' : 'rR_lat_g'));
      if (fabs(tmp) > M_HALFPI) {
        error(-11);
      }
      tmp = 1 - es * tmp * tmp;
      a *= i ? 0.5 * (1 - es + tmp) / (tmp * sqrt(tmp)) : sqrt(1 - es) / tmp;
      es = 0;
    }
  }

  if (es < 0) error(-12);
  if (a <= 0) error(-13);
  P.es = es;
  P.a = a;
}



var pj_units = [
  // id to_meter name
  ["km", "1000", "Kilometer"],
  ["m", "1", "Meter"],
  ["dm", "1/10", "Decimeter"],
  ["cm", "1/100", "Centimeter"],
  ["mm", "1/1000", "Millimeter"],
  ["kmi", "1852.0", "International Nautical Mile"],
  ["in", "0.0254", "International Inch"],
  ["ft", "0.3048", "International Foot"],
  ["yd", "0.9144", "International Yard"],
  ["mi", "1609.344", "International Statute Mile"],
  ["fath", "1.8288", "International Fathom"],
  ["ch", "20.1168", "International Chain"],
  ["link", "0.201168", "International Link"],
  ["us-in", "1/39.37", "U.S. Surveyor's Inch"],
  ["us-ft", "0.304800609601219", "U.S. Surveyor's Foot"],
  ["us-yd", "0.914401828803658", "U.S. Surveyor's Yard"],
  ["us-ch", "20.11684023368047", "U.S. Surveyor's Chain"],
  ["us-mi", "1609.347218694437", "U.S. Surveyor's Statute Mile"],
  ["ind-yd", "0.91439523", "Indian Yard"],
  ["ind-ft", "0.30479841", "Indian Foot"],
  ["ind-ch", "20.11669506", "Indian Chain"],
  [null, null, null]
];

function find_units_by_value(val) {
  return pj_units.reduce(function(memo, defn) {
    if (val == +defn[1]) {
      memo = find_units(defn[0]);
    }
    return memo;
  }, null);
}

function find_units(id) {
  var arr = pj_units.reduce(function(memo, defn) {
    return id === defn[0] ? defn : memo;
  }, null);
  return arr ? {id: arr[0], to_meter: arr[1], name: arr[2]} : null;
}



var initcache = {};

function pj_search_initcache(key) {
  return initcache[key.toLowerCase()] || null;
}

function pj_insert_initcache(key, defn) {
  initcache[key.toLowerCase()] = defn;
}


// Replacement functions for Proj.4 pj_open_lib() (see pj_open_lib.c)
// and get_opt() (see pj_init.c)

var libcache = {};

// add a definition library without reading from a file (for use by web app)
function mproj_insert_libcache(libId, contents) {
  libcache[libId] = contents;
}

function mproj_search_libcache(libId) {
  return libcache[libId] || null;
}

function mproj_read_lib_anycase(libFile) {
  var fs = require('fs'),
      path = require('path'),
      // path to library assumes mproj script is in the dist/ directory
      dir = path.join(path.dirname(__filename), '../nad'),
      pathUC = path.join(dir, libFile.toUpperCase()),
      pathLC = path.join(dir, libFile.toLowerCase()),
      contents;
  if (fs.existsSync(pathUC)) {
    contents = fs.readFileSync(pathUC, 'utf8');
  } else if (fs.existsSync(pathLC)) {
    contents = fs.readFileSync(pathLC, 'utf8');
  } else {
    fatal('unable to read from \'init\' file named ' + libFile); // not in Proj.4
  }
  return contents;
}

// Return opts from a section of a config file,
//   or null if not found or unable to read file
function pj_read_init_opts(initStr) {
  var parts = initStr.split(':'),
      libId = parts[0],
      crsId = parts[1],
      libStr, o;
  if (!crsId || !libId) {
    error(-3);
  }
  libId = libId.toLowerCase(); // not in Proj.4
  libStr = mproj_search_libcache(libId);
  if (!libStr) {
    libStr = mproj_read_lib_anycase(libId);
    libcache[libId] = libStr;
  }
  return libStr ? pj_find_opts(libStr, crsId) : null;
}

// Find params in contents of an init file
function pj_find_opts(contents, id) {
  var opts = '', comment = '',
      idx, idx2;
  // get requested parameters
  idx = contents.indexOf('<' + id + '>');
  if (idx > -1) {
    // get comment text
    idx2 = contents.lastIndexOf('#', idx);
    if (idx2 > -1) {
      comment = contents.substring(idx2 + 1, idx).trim();
      if (/\n/.test(comment)) {
        comment = '';
      }
    }
    // get projection params
    opts = contents.substr(idx + id.length + 2);
    opts = opts.substr(0, opts.indexOf('<'));
    // remove comments
    opts = opts.replace(/#.*/g, '');
    // convert all whitespace to single <sp>
    opts = opts.replace(/[\s]+/g, ' ');

    // if '+' is missing from args, add it
    // kludge: protect spaces in +title= opts
    opts = opts.replace(/\+title=[^+]*[^ +]/g, function(match) {
      return match.replace(/ /g, '\t');
    });
    opts = ' ' + opts;
    opts = opts.replace(/ (?=[a-z])/ig, ' +');
    opts = opts.replace(/\t/g, ' ').trim();
  }
  return opts ? {opts: opts, comment: comment} : null;
}


// Returns an initialized projection object
// @args a proj4 string
function pj_init(args) {
  var params = pj_get_params(args);
  var P = {
    params: params,
    is_latlong: false,
    is_geocent: false,
    is_long_wrap_set: false,
    long_wrap_center: 0,
    axis: "enu",
    gridlist: null,
    gridlist_count: 0,
    vgridlist_geoid: null,
    vgridlist_geoid_count: 0
  };
  var name, defn;
  if (!Object.keys(params).length) {
    error(-1);
  }

  if (pj_param(params, "tinit")) {
    get_init(params, pj_param(params, "sinit"));
  }

  name = pj_param(params, "sproj");
  if (!name) {
    error(-4);
  }

  defn = pj_list[name];
  if (!defn) {
    error(-5);
  }

  if (!pj_param(params, "bno_defs")) {
    get_defaults(P.params, name);
  }

  pj_datum_set(P);
  pj_ell_set(P);

  P.a_orig = P.a;
  P.es_orig = P.es;
  P.e = sqrt(P.es);
  P.ra = 1 / P.a;
  P.one_es = 1 - P.es;
  if (!P.one_es) {
    error(-6);
  }
  P.rone_es = 1 / P.one_es;

  if (is_wgs84(P)) {
    P.datum_type = PJD_WGS84;
  }

  P.geoc = !!P.es && pj_param(params, 'bgeoc');
  P.over = pj_param(params, 'bover');
  P.has_geoid_vgrids = pj_param(params, 'tgeoidgrids');
  if (P.has_geoid_vgrids) {
    pj_param(params, "sgeoidgrids"); // mark as used
  }

  P.is_long_wrap_set = pj_param(params, 'tlon_wrap');
  if (P.is_long_wrap_set) {
    P.long_wrap_center = pj_param(params, 'rlon_wrap');
    // Don't accept excessive values otherwise we might perform badly
    // when correcting longitudes around it
    // The test is written this way to error on long_wrap_center "=" NaN
    if (fabs(P.long_wrap_center) < 10 * M_TWOPI === false) {
      error(-14);
    }
  }

  if (pj_param(params, 'saxis')) {
    init_axis(P);
  }

  P.lam0 = pj_param(params, 'rlon_0');
  P.phi0 = pj_param(params, 'rlat_0');
  P.x0 = pj_param(params, 'dx_0');
  P.y0 = pj_param(params, 'dy_0');

  if (pj_param(params, 'tk_0')) {
    P.k0 = pj_param(params, 'dk_0');
  } else if (pj_param(params, 'tk')) {
    P.k0 = pj_param(params, 'dk');
  } else {
    P.k0 = 1;
  }
  if (P.k0 <= 0) {
    error(-31);
  }

  init_units(P);
  init_prime_meridian(P);
  defn.init(P);
  return P;
}

// Merge default params
// NOTE: Proj.4 loads defaults from the file nad/proj_def.dat
// This function applies the default ellipsoid from proj_def.dat but
//   ignores the other defaults, which could be considered undesirable
//   (see e.g. https://github.com/OSGeo/proj.4/issues/201)
function get_defaults(params, name) {
  get_opt(params, '+ellps=WGS84');
}

function get_init(params, initStr) {
  var defn = pj_search_initcache(initStr);
  if (!defn) {
    defn = pj_read_init_opts(initStr);
    pj_insert_initcache(initStr, defn);
  }
  if (!defn) {
    error(-2);
  }
  // merge init params
  get_opt(params, defn.opts);
}

// Merge params from a proj4 string
// (Slightly different interface from Proj.4 get_opts())
function get_opt(params, args) {
  var newParams = pj_get_params(args);
  var geoIsSet = ['datum', 'ellps', 'a', 'b', 'rf', 'f'].reduce(function(memo, key) {
    return memo || key in params;
  }, false);
  Object.keys(newParams).forEach(function(key) {
    // don't override existing params
    if (key in params) return;
    // don't set ellps if earth model info is set
    if (key == 'ellps' && geoIsSet) return;
    params[key] = newParams[key];
  });
}

function init_prime_meridian(P) {
  var params = P.params,
  name, pm, offs;
  name = pj_param(params, 'spm');
  if (name) {
    pm = find_prime_meridian(name);
    offs = dmstor(pm ? pm.definition : name);
    if (isNaN(offs)) {
      error(-46);
    }
    P.from_greenwich = offs;
  } else {
    P.from_greenwich = 0;
  }
}

function init_units(P) {
  var params = P.params;
  var name, s, units;
  if (name = pj_param(params, 'sunits')) {
    units = find_units(name);
    if (!units) {
      error(-7);
    }
    s = units.to_meter;
  }
  if (s || (s = pj_param(params, 'sto_meter'))) {
    P.to_meter = parse_to_meter(s);
    P.fr_meter = 1 / P.to_meter;
  } else {
    P.to_meter = P.fr_meter = 1;
  }

  // vertical units
  s = null;
  if (name = pj_param(params, 'svunits')) {
    units = find_units(name);
    if (!units) {
      error(-7);
    }
    s = units.to_meter;
  }
  if (s || (pj_param(params, 'svto_meter'))) {
    P.vto_meter = parse_to_meter(s);
    P.vfr_meter = 1 / P.vto_meter;
  } else {
    P.vto_meter = P.to_meter;
    P.vfr_meter = P.fr_meter;
  }
}

function parse_to_meter(s) {
  var parts = s.split('/');
  var val = pj_strtod(parts[0]);
  if (parts.length > 1) {
    val /= pj_strtod(parts[1]);
  }
  return val;
}

function init_axis(P) {
  var axis_legal = "ewnsud";
  var axis = pj_param(P.params, 'saxis');
  if (axis.length != 3) {
    error(PJD_ERR_AXIS);
  }
  if (axis_legal.indexOf(axis[0]) == -1 ||
      axis_legal.indexOf(axis[1]) == -1 ||
      axis_legal.indexOf(axis[2]) == -1) {
    error(PJD_ERR_AXIS);
  }
  P.axis = axis;
}

function is_wgs84(P) {
  return P.datum_type == PJD_3PARAM &&
    P.datum_params[0] == P.datum_params[1] == P.datum_params[2] === 0 &&
    P.a == 6378137 && Math.abs(P.es - 0.006694379990) < 0.000000000050;
}



// TODO: remove error codes (Proj.4 doesn't do anything with them)
var GEOCENT_NO_ERROR = 0x0000,
    GEOCENT_LAT_ERROR = 0x0001,
    GEOCENT_LON_ERROR = 0x0002,
    GEOCENT_A_ERROR = 0x0004,
    GEOCENT_B_ERROR = 0x0008,
    GEOCENT_A_LESS_B_ERROR = 0x0010;

// a: Semi-major axis, in meters.
// b: Semi-minor axis, in meters.
function pj_Set_Geocentric_Parameters(a, b) {
  var err = GEOCENT_NO_ERROR,
      a2 = a * a,
      b2 = b * b;
  if (a <= 0.0) err |= GEOCENT_A_ERROR;
  if (b <= 0.0) err |= GEOCENT_B_ERROR;
  if (a < b) err |= GEOCENT_A_LESS_B_ERROR;
  return err ? null : {
    a: a,
    b: b,
    a2: a2,
    b2: b2,
    e2: (a2 - b2) / a2,
    ep2: (a2 - b2) / b2
  };
}


function pj_Convert_Geodetic_To_Geocentric(gi, i, xx, yy, zz) {
  var err = GEOCENT_NO_ERROR,
      lng = xx[i],
      lat = yy[i],
      height = zz[i],
      x, y, z,
      rn, sinlat, sin2lat, coslat;
  if (lat < -M_HALFPI && lat > -1.001 * M_HALFPI) {
    lat = -M_HALFPI;
  } else if (lat > M_HALFPI && lat < 1.001 * M_HALFPI) {
    lat = M_HALFPI;
  } else if (lat < -M_HALFPI || lat > M_HALFPI) {
    err |= GEOCENT_LAT_ERROR;
  }

  if (!err) {
    if (lng > M_PI) lng -= 2 * M_PI;
    sinlat = sin(lat);
    coslat = cos(lat);
    sin2lat = sinlat * sinlat;
    rn = gi.a / sqrt(1 - gi.e2 * sin2lat);
    xx[i] = (rn + height) * coslat * cos(lng);
    yy[i] = (rn + height) * coslat * sin(lng);
    zz[i] = ((rn * (1 - gi.e2)) + height) * sinlat;
  }
  return err;
}


function pj_Convert_Geocentric_To_Geodetic(gi, i, xx, yy, zz) {
  var EPS = 1e-12,
      EPS2 = EPS * EPS,
      MAXITER = 30,
      x = xx[i],
      y = yy[i],
      z = zz[i],
      lat, lng, height,
      p, rr, ct, st, rx, rn, rk, cphi0, sphi0, cphi, sphi, sdphi, iter;

  p = sqrt(x * x + y * y);
  rr = sqrt(x * x + y * y + z * z);

  if (p / gi.a < EPS) {
    lng = 0;
    if (rr / gi.a < EPS) {
      xx[i] = 0;
      yy[i] = M_HALFPI;
      zz[i] = -gi.b;
      return 0;
    }
  } else {
    lng = atan2(y, x);
  }

  ct = z / rr;
  st = p / rr;
  rx = 1 / sqrt(1 - gi.e2 * (2 - gi.e2) * st * st);
  cphi0 = st * (1 - gi.e2) * rx;
  sphi0 = ct * rx;
  iter = 0;

  do {
    iter++;
    rn = gi.a / sqrt(1 - gi.e2 * sphi0 * sphi0);
    height = p * cphi0 + z * sphi0 - rn * (1 - gi.e2 * sphi0 * sphi0);
    rk = gi.e2 * rn / (rn + height);
    rx = 1 / sqrt(1 - rk * (2 - rk) * st * st);
    cphi = st * (1 - rk) * rx;
    sphi = ct * rx;
    sdphi = sphi * cphi0 - cphi * sphi0;
    cphi0 = cphi;
    sphi0 = sphi;
  } while (sdphi * sdphi > EPS2 && iter < MAXITER);
  lat = atan(sphi / fabs(cphi));
  xx[i] = lng;
  yy[i] = lat;
  zz[i] = height;
}



// A convenience function for transforming a single point (not in Proj.4)
// @p an array containing [x, y] or [x, y, z] coordinates
//     latlong coordinates are assumed to be in decimal degrees
function pj_transform_point(srcdefn, dstdefn, p) {
  var z = p.length > 2,
      xx = [p[0]],
      yy = [p[1]],
      zz = [z ? p[2] : 0];
  if (srcdefn.is_latlong) {
    xx[0] *= DEG_TO_RAD;
    yy[0] *= DEG_TO_RAD;
  }
  ctx.last_errno = 0;
  pj_transform(srcdefn, dstdefn, xx, yy, zz);
  if (ctx.last_errno || xx[0] == HUGE_VAL) {
    // throw error if translation fails
    fatal(null, {point: p});
  }
  if (dstdefn.is_latlong) {
    xx[0] *= RAD_TO_DEG;
    yy[0] *= RAD_TO_DEG;
  }
  p[0] = xx[0];
  p[1] = yy[0];
  if (z) p[2] = zz[0];
}

// Transform arrays of coordinates; latlong coords are in radians
// @xx, @yy[, @zz] coordinate arrays
//
function pj_transform(srcdefn, dstdefn, xx, yy, zz) {
  var point_count = xx.length;
  var lp = {};
  var xy = {};
  var err, i, tmp;

  if (srcdefn.axis != 'enu') {
    pj_adjust_axis(srcdefn.axis, false, xx, yy, zz);
  }

  if (srcdefn.vto_meter != 1 && zz) {
   for ( i = 0; i < point_count; i++ )
      zz[i] *= srcdefn.vto_meter;
  }

  // convert to lat/lng, if needed
  if (srcdefn.is_geocent) {
    if (!zz) {
      error(PJD_ERR_GEOCENTRIC);
    }
    if (srcdefn.to_meter != 1) {
      for (i = 0; i < point_count; i++) {
        if (xx[i] != HUGE_VAL ) {
          xx[i] *= srcdefn.to_meter;
          yy[i] *= srcdefn.to_meter;
        }
      }
    }
    pj_geocentric_to_geodetic(srcdefn.a_orig, srcdefn.es_orig, xx, yy, zz);

  } else if (!srcdefn.is_latlong) {
    if (!srcdefn.inv3d && !srcdefn.inv) {
      // Proj.4 returns error code -17 (a bug?)
      fatal("source projection not invertible");
    }
    if (srcdefn.inv3d) {
      fatal("inverse 3d transformations not supported");
    } else {
      for (i=0; i<point_count; i++) {
        xy.x = xx[i];
        xy.y = yy[i];
        tmp = pj_inv(xy, srcdefn);
        xx[i] = tmp.lam;
        yy[i] = tmp.phi;
        check_fatal_error(); // Proj.4 is a bit different
      }
    }
  }

  if (srcdefn.from_greenwich !== 0) {
    for (i=0; i<point_count; i++) {
      if (xx[i] != HUGE_VAL) {
        xx[i] += srcdefn.from_greenwich;
      }
    }
  }

  if (srcdefn.has_geoid_vgrids && zz) {
    fatal("vgrid transformation not supported");
  }

  pj_datum_transform(srcdefn, dstdefn, xx, yy, zz);

  if (dstdefn.has_geoid_vgrids && zz) {
    fatal("vgrid transformation not supported");
  }

  if (dstdefn.from_greenwich !== 0) {
    for (i=0; i<point_count; i++) {
      if (xx[i] != HUGE_VAL) {
        xx[i] -= dstdefn.from_greenwich;
      }
    }
  }

  if (dstdefn.is_geocent) {
    if (!zz) {
      error(PJD_ERR_GEOCENTRIC);
    }
    pj_geodetic_to_geocentric(dstdefn.a_orig, dstdefn.es_orig, xx, yy, zz);

    if (dstdefn.fr_meter != 1) {
      for (i = 0; i<point_count; i++) {
        if (xx[i] != HUGE_VAL) {
          xx[i] *= dstdefn.fr_meter;
          yy[i] *= dstdefn.fr_meter;
        }
      }
    }
  } else if (!dstdefn.is_latlong) {
    if (dstdefn.fwd3d) {
      fatal("3d transformation not supported");
    } else {
      for (i=0; i<point_count; i++) {
        lp.lam = xx[i];
        lp.phi = yy[i];
        tmp = pj_fwd(lp, dstdefn);
        xx[i] = tmp.x;
        yy[i] = tmp.y;
        check_fatal_error(); // Proj.4 is a bit different
      }
    }
  } else if (dstdefn.is_latlong && dstdefn.is_long_wrap_set) {
    for (i=0; i<point_count; i++) {
      if (xx[i] == HUGE_VAL) continue;
      while (xx[i] < dstdefn.long_wrap_center - M_PI) {
        xx[i] += M_TWOPI;
      }
      while (xx[i] > dstdefn.long_wrap_center + M_PI) {
        xx[i] -= M_TWOPI;
      }
    }
  }

  if (dstdefn.vto_meter != 1 && zz) {
    for (i=0; i<point_count; i++) {
      zz[i] *= dstdefn.vfr_meter;
    }
  }
  if (dstdefn.axis != 'enu') {
    pj_adjust_axis(dstdefn.axis, true, xx, yy, zz);
  }

  return point_count == 1 ? ctx.last_errno : 0;
}

function pj_adjust_axis(axis, denormalize_flag, xx, yy, zz) {
  var point_count = xx.length;
  var x_in, y_in, z_in = 0;
  var i, i_axis, value, target;

  if (!denormalize_flag) {
    for (i = 0; i < point_count; i++) {
      x_in = xx[i];
      y_in = yy[i];
      if (x_in == HUGE_VAL) continue; // not in Proj.4
      if (zz)
        z_in = zz[i];

      for (i_axis = 0; i_axis < 3; i_axis++) {
        if (i_axis == 0)
            value = x_in;
        else if (i_axis == 1)
            value = y_in;
        else
            value = z_in;

        switch (axis[i_axis]) {
          case 'e':
            xx[i] = value; break;
          case 'w':
            xx[i] = -value; break;
          case 'n':
            yy[i] = value; break;
          case 's':
            yy[i] = -value; break;
          case 'u':
            if( zz ) zz[i] = value; break;
          case 'd':
            if( zz ) zz[i] = -value; break;
          default:
            error(PJD_ERR_AXIS);
        }
      } /* i_axis */
    } /* i (point) */
  }

  else {/* denormalize */
    for (i = 0; i < point_count; i++) {
      x_in = xx[i];
      y_in = yy[i];
      if (x_in == HUGE_VAL) continue; // not in Proj.4
      if (zz)
        z_in = zz[i];
      for (i_axis = 0; i_axis < 3; i_axis++) {
        if (i_axis == 2 && !zz)
          continue;
        if (i_axis == 0)
            target = xx;
        else if (i_axis == 1)
            target = yy;
        else
            target = zz;
        switch (axis[i_axis]) {
          case 'e':
            target[i] = x_in; break;
          case 'w':
            target[i] = -x_in; break;
          case 'n':
            target[i] = y_in; break;
          case 's':
            target[i] = -y_in; break;
          case 'u':
            target[i] = z_in; break;
          case 'd':
            target[i] = -z_in; break;
          default:
            error(PJD_ERR_AXIS);
        }
      } /* i_axis */
    } /* i (point) */
  }
}

function pj_datum_transform(srcdefn, dstdefn, xx, yy, zz) {
  var point_count = xx.length;
  var src_a, src_es, dst_a, dst_es;
  var z_is_temp = false;
  /*      We cannot do any meaningful datum transformation if either      */
  /*      the source or destination are of an unknown datum type          */
  /*      (ie. only a +ellps declaration, no +datum).  This is new        */
  /*      behavior for PROJ 4.6.0                                        */
  if (srcdefn.datum_type == PJD_UNKNOWN || dstdefn.datum_type == PJD_UNKNOWN) {
    return;
  }

  /*      Short cut if the datums are identical.                          */
  if (pj_compare_datums(srcdefn, dstdefn)) {
    return;
  }
  src_a = srcdefn.a_orig;
  src_es = srcdefn.es_orig;
  dst_a = dstdefn.a_orig;
  dst_es = dstdefn.es_orig;
  /*      Create a temporary Z array if one is not provided.              */
  if (!zz) {
    zz = new Float64Array(point_count);
    z_is_temp = true;
  }

  if (srcdefn.datum_type == PJD_GRIDSHIFT) {
    fatal("gridshift not implemented");
    // pj_apply_gridshift_2()
    src_a = SRS_WGS84_SEMIMAJOR;
    src_es = SRS_WGS84_ESQUARED;
  }

  if (dstdefn.datum_type == PJD_GRIDSHIFT) {
    dst_a = SRS_WGS84_SEMIMAJOR;
    dst_es = SRS_WGS84_ESQUARED;
  }

  /*      Do we need to go through geocentric coordinates?                */
  if (src_es != dst_es || src_a != dst_a ||
      srcdefn.datum_type == PJD_3PARAM || srcdefn.datum_type == PJD_7PARAM ||
      dstdefn.datum_type == PJD_3PARAM || dstdefn.datum_type == PJD_7PARAM) {

    pj_geodetic_to_geocentric(src_a, src_es, xx, yy, zz);

    if (srcdefn.datum_type == PJD_3PARAM || srcdefn.datum_type == PJD_7PARAM) {
      pj_geocentric_to_wgs84(srcdefn, xx, yy, zz);
    }

    if (dstdefn.datum_type == PJD_3PARAM || dstdefn.datum_type == PJD_7PARAM) {
      pj_geocentric_from_wgs84(dstdefn, xx, yy, zz);
    }

    /*      Convert back to geodetic coordinates.                           */
    pj_geocentric_to_geodetic(dst_a, dst_es, xx, yy, zz);

    /*      Apply grid shift to destination if required.                    */
    if (dstdefn.datum_type == PJD_GRIDSHIFT) {
      pj_apply_gridshift_2(dstdefn, 1, xx, yy, zz);
    }
  }
}

// returns true if datums are equivalent
function pj_compare_datums(srcdefn, dstdefn) {
  if (srcdefn.datum_type != dstdefn.datum_type) return false;
  if (srcdefn.a_orig != dstdefn.a_orig ||
    Math.abs(srcdefn.es_orig - dstdefn.es_orig) > 0.000000000050) {
    /* the tolerance for es is to ensure that GRS80 and WGS84 are considered identical */
    return false;
  }
  if (srcdefn.datum_type == PJD_3PARAM) {
    return (srcdefn.datum_params[0] == dstdefn.datum_params[0] &&
        srcdefn.datum_params[1] == dstdefn.datum_params[1] &&
        srcdefn.datum_params[2] == dstdefn.datum_params[2]);
  }
  if (srcdefn.datum_type == PJD_7PARAM) {
    return (srcdefn.datum_params[0] == dstdefn.datum_params[0] &&
      srcdefn.datum_params[1] == dstdefn.datum_params[1] &&
      srcdefn.datum_params[2] == dstdefn.datum_params[2] &&
      srcdefn.datum_params[3] == dstdefn.datum_params[3] &&
      srcdefn.datum_params[4] == dstdefn.datum_params[4] &&
      srcdefn.datum_params[5] == dstdefn.datum_params[5] &&
      srcdefn.datum_params[6] == dstdefn.datum_params[6]);
  }
  if (srcdefn.datum_type == PJD_GRIDSHIFT) {
    return pj_param(srcdefn.params, "snadgrids") ==
        pj_param(dstdefn.params, "snadgrids");
  }
  return true;
}

function pj_geocentric_to_wgs84(defn, xx, yy, zz) {
  var point_count = xx.length,
      pp = defn.datum_params,
      Dx_BF = pp[0],
      Dy_BF = pp[1],
      Dz_BF = pp[2],
      x, y, z, Rx_BF, Ry_BF, Rz_BF, M_BF,
      i;

  if (defn.datum_type == PJD_3PARAM) {
    for (i=0; i<point_count; i++) {
      if (xx[i] == HUGE_VAL) continue;
      xx[i] += Dx_BF;
      yy[i] += Dy_BF;
      zz[i] += Dz_BF;
    }
  } else if (defn.datum_type == PJD_7PARAM) {
    Rx_BF = pp[3];
    Ry_BF = pp[4];
    Rz_BF = pp[5];
    M_BF = pp[6];
    for (i=0; i<point_count; i++) {
      if (xx[i] == HUGE_VAL) continue;
      x = M_BF * (xx[i] - Rz_BF * yy[i] + Ry_BF *  zz[i]) + Dx_BF;
      y = M_BF * (Rz_BF * xx[i] + yy[i] - Rx_BF * zz[i]) + Dy_BF;
      z = M_BF * (-Ry_BF * xx[i] + Rx_BF * yy[i] + zz[i]) + Dz_BF;
      xx[i] = x;
      yy[i] = y;
      zz[i] = z;
    }
  }
}

function pj_geocentric_from_wgs84(defn, xx, yy, zz) {
  var point_count = xx.length,
      pp = defn.datum_params,
      Dx_BF = pp[0],
      Dy_BF = pp[1],
      Dz_BF = pp[2],
      x, y, z, Rx_BF, Ry_BF, Rz_BF, M_BF,
      i;

  if (defn.datum_type == PJD_3PARAM) {
    for (i=0; i<point_count; i++) {
      if (xx[i] == HUGE_VAL) continue;
      xx[i] -= Dx_BF;
      yy[i] -= Dy_BF;
      zz[i] -= Dz_BF;
    }
  } else if (defn.datum_type == PJD_7PARAM) {
    Rx_BF = pp[3];
    Ry_BF = pp[4];
    Rz_BF = pp[5];
    M_BF = pp[6];
    for (i=0; i<point_count; i++) {
      if (xx[i] == HUGE_VAL) continue;
      x = (xx[i] - Dx_BF) / M_BF;
      y = (yy[i] - Dy_BF) / M_BF;
      z = (zz[i] - Dz_BF) / M_BF;
      xx[i] = x + Rz_BF * y - Ry_BF * z;
      yy[i] = -Rz_BF * x + y + Rx_BF * z;
      zz[i] = Ry_BF * x - Rx_BF * y + z;
    }
  }
}

function pj_geocentric_to_geodetic(a, es, xx, yy, zz) {
  var point_count = xx.length;
  var b, i, gi;
  if (es == 0.0)
    b = a;
  else
    b = a * sqrt(1-es);

  gi = pj_Set_Geocentric_Parameters(a, b);
  if (!gi) {
    error(PJD_ERR_GEOCENTRIC);
  }

  for (i = 0; i < point_count; i++) {
    if (xx[i] != HUGE_VAL) {
      pj_Convert_Geocentric_To_Geodetic(gi, i, xx, yy, zz);
    }
  }
}

function pj_geodetic_to_geocentric(a, es, xx, yy, zz) {
  var point_count = xx.length,
      b, i, gi;
  if (es === 0) {
    b = a;
  } else {
    b = a * sqrt(1 - es);
  }
  gi = pj_Set_Geocentric_Parameters(a, b);
  if (!gi) {
    error(PJD_ERR_GEOCENTRIC);
  }
  for (i=0; i<point_count; i++) {
    if (xx[i] == HUGE_VAL) continue;
    if (pj_Convert_Geodetic_To_Geocentric(gi, i, xx, yy, zz)) {
      xx[i] = yy[i] = HUGE_VAL;
    }
  }
}


function adjlon(lon) {
  var SPI = 3.14159265359,
      TWOPI = 6.2831853071795864769,
      ONEPI = 3.14159265358979323846;

  if (fabs(lon) > SPI) {
    lon += ONEPI;  /* adjust to 0.0.2pi rad */
    lon -= TWOPI * floor(lon / TWOPI); /* remove integral # of 'revolutions'*/
    lon -= ONEPI;  /* adjust back to -pi..pi rad */
  }
  return lon;
}


function pj_fwd_deg(lp, P) {
  var lp2 = {lam: lp.lam * DEG_TO_RAD, phi: lp.phi * DEG_TO_RAD};
  return pj_fwd(lp2, P);
}

function pj_fwd(lp, P) {
  var xy = {x: 0, y: 0};
  var EPS = 1e-12;
  var t = fabs(lp.phi) - M_HALFPI;

  // if (t > EPS || fabs(lp.lam) > 10) {
  if (!(t <= EPS && fabs(lp.lam) <= 10)) { // catch NaNs
    pj_ctx_set_errno(-14);
  } else {
    ctx.last_errno = 0; // clear a previous error
    if (fabs(t) <= EPS) {
      lp.phi = lp.phi < 0 ? -M_HALFPI : M_HALFPI;
    } else if (P.geoc) {
      lp.phi = atan(P.rone_es * tan(lp.phi));
    }
    lp.lam -= P.lam0;
    if (!P.over) {
      lp.lam = adjlon(lp.lam);
    }
    if (P.fwd) {
      P.fwd(lp, xy);
      xy.x = P.fr_meter * (P.a * xy.x + P.x0);
      xy.y = P.fr_meter * (P.a * xy.y + P.y0);
    } else {
      xy.x = xy.y = HUGE_VAL;
    }
  }
  if (ctx.last_errno || !isFinite(xy.x) || !isFinite(xy.y)) {
    // isFinite() catches NaN and +/- Infinity but not null
    xy.x = xy.y = HUGE_VAL;
  }
  return xy;
}


function pj_inv_deg(xy, P) {
  var lp = pj_inv(xy, P);
  return {
    lam: lp.lam * RAD_TO_DEG,
    phi: lp.phi * RAD_TO_DEG
  };
}

function pj_inv(xy, P) {
  var EPS = 1e-12;
  var lp = {lam: 0, phi: 0};

  // if (xy.x == HUGE_VAL || xy.y == HUGE_VAL) {
  if (!(xy.x < HUGE_VAL && xy.y < HUGE_VAL)) { // catch NaNs
    pj_ctx_set_errno(-15);
  } else {
    ctx.last_errno = 0;
    if (P.inv) {
      xy.x = (xy.x * P.to_meter - P.x0) * P.ra;
      xy.y = (xy.y * P.to_meter - P.y0) * P.ra;
      P.inv(xy, lp);
      lp.lam += P.lam0;
      if (!P.over) {
        lp.lam = adjlon(lp.lam);
      }
      if (P.geoc && fabs(fabs(lp.phi) - M_HALFPI) > EPS) {
        lp.phi = atan(P.one_es * tan(lp.phi));
      }
    } else {
      lp.lam = lp.phi = HUGE_VAL;
    }
  }
  if (ctx.last_errno || !isFinite(lp.lam) || !isFinite(lp.phi)) {
    // isFinite() catches NaN and +/- Infinity but not null
    lp.lam = lp.phi = HUGE_VAL;
  }
  return lp;
}


function get_rtodms(decimals, fixedWidth, pos, neg) {
  var dtodms = get_dtodms(decimals, fixedWidth, pos, neg);
  return function(r) {
    return dtodms(r * RAD_TO_DEG);
  };
}

// returns function for formatting as DMS
// See Proj.4 rtodms.c
// @pos: 'N' or 'E'
// @neg: 'S' or 'W'
function get_dtodms(decimals, fixedWidth, pos, neg) {
  var RES, CONV, i;
  if (decimals < 0 || decimals >= 9) {
    decimals = 3;
  }
  RES = 1;
  for (i=0; i<decimals; i++) {
    RES *= 10;
  }
  CONV = 3600 * RES;

  return function(r) {
    var sign = '',
        mstr = '',
        sstr = '',
        min, sec, suff, dstr;
    if (r === HUGE_VAL || isNaN(r)) return '';
    if (r < 0) {
      r = -r;
      suff = neg || '';
      if (!suff) {
        sign = '-';
      }
    } else {
      suff = pos || '';
    }
    r = floor(r * CONV + 0.5);
    sec = (r / RES) % 60;
    r = floor(r / (RES * 60));
    min = r % 60;
    dstr = floor(r / 60) + 'd';
    sstr = sec.toFixed(decimals);
    sec = parseFloat(sstr);
    if (sec) {
      sstr = (fixedWidth ? sstr : String(sec)) + '"';
    } else {
      sstr = '';
    }
    if (sec || min) {
      mstr = String(min) + "'";
      if (mstr.length == 2 && fixedWidth) {
        mstr = '0' + mstr;
      }
    }
    return sign + dstr + mstr + sstr + suff;
  };
}


// Support for the proj4js api:
//    proj4(fromProjection[, toProjection, coordinates])

function proj4js(arg1, arg2, arg3) {
  var p, fromStr, toStr, P1, P2, transform;
  if (typeof arg1 != 'string') {
    // E.g. Webpack's require function tries to initialize mproj by calling
    // the module function.
    return api;
  } else if (typeof arg2 != 'string') {
    fromStr = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'; // '+datum=WGS84 +proj=lonlat';
    toStr = arg1;
    p = arg2;
  } else {
    fromStr = arg1;
    toStr = arg2;
    p = arg3;
  }
  P1 = pj_init(fromStr);
  P2 = pj_init(toStr);
  transform = get_proj4js_transform(P1, P2);
  if (p) {
    return transform(p);
  } else {
    return {forward: transform, inverse: get_proj4js_transform(P2, P1)};
  }
}

proj4js.WGS84 = '+proj=longlat +datum=WGS84'; // for compatibility with proj4js tests

// for compatibility with proj4js tests
proj4js.toPoint = function(array) {
  var out = {
    x: array[0],
    y: array[1]
  };
  if (array.length>2) {
    out.z = array[2];
  }
  if (array.length>3) {
    out.m = array[3];
  }
  return out;
};

function get_proj4js_transform(P1, P2) {
  return function(p) {
    var useArray = Array.isArray(p);
    p = useArray ? p.concat() : [p.x, p.y];
    pj_transform_point(P1, P2, p);
    if (!useArray) {
      p = {x: p[0], y: p[1]};
    }
    return p;
  };
}



// Fallback WKT definitions include a Proj.4 string in an EXTENSION property.
// They should be readable by QGIS and gdal/ogr, but will not work
// with most other GIS software.

function get_fallback_wkt_maker(P) {
  // TODO: validate P?
  return make_fallback_wkt;
}

function make_fallback_wkt(P) {
  var projName = P.proj in pj_list ? pj_list[P.proj].name : '';
  var proj4 = get_proj_defn(P);
  var geogcs = wkt_make_geogcs(P);
  // GDAL seems to use "unnamed" all the time
  var name = projName ? geogcs.NAME + ' / ' + projName : 'unnamed';
  return {PROJCS: {
    NAME: name,
    GEOGCS: geogcs,
    PROJECTION: 'custom_proj4',
    PARAMETER: [],
    UNIT: wkt_make_unit(P),
    EXTENSION: ['PROJ4', proj4 + ' +wktext']
  }};
}

function get_fallback_wkt_parser(projcs) {
  var proj4 = get_proj4_from_extension(projcs);
  // TODO: try parsing proj4 string to validate?
  return proj4 ? get_proj4_from_extension : null;
}

function get_proj4_from_extension(projcs) {
  var ext = projcs.EXTENSION;
  if (ext && ext[0] == 'PROJ4') {
    return (ext[1] || '').replace(' +wktext', '');
  }
  return null;
}


// Global collections of WKT parsers and makers
// arr[0] is test function; arr[1] is conversion function
var wkt_makers = [];
var wkt_parsers = [];

// TODO: use utility library
function wkt_is_object(val) {
  return !!val && typeof val == 'object' && !Array.isArray(val);
}

function wkt_is_string(val) {
  return typeof val == 'string';
}

function find_wkt_parser(projcs) {
  var parser = find_wkt_conversion_function(projcs, wkt_parsers);
  if (!parser) {
    parser = get_fallback_wkt_parser(projcs);
  }
  if (!parser) {
    wkt_error('unsupported WKT definition: ' + get_wkt_label(projcs));
  }
  return parser;
}

function find_wkt_maker(P) {
  var maker = find_wkt_conversion_function(P, wkt_makers);
  if (!maker) {
    maker = get_fallback_wkt_maker(P);
  }
  if (!maker) {
    wkt_error('unsupported projection: ' + get_proj_label(P));
  }
  return maker;
}

function find_wkt_conversion_function(o, arr) {
  var is_match;
  for (var i=0; i<arr.length; i++) {
    is_match = arr[i][0];
    if (is_match(o)) return arr[i][1];
  }
  return null;
}

function get_proj_label(P) {
  return get_proj_id(P) || '[unknown]';
}

function get_wkt_label(o) {
  return o.NAME || '[unknown]';
}

function get_proj_id(P) {
  return  pj_param(P.params, 'sproj');
}

function wkt_name_to_slug(name) {
  return name.replace(/[-_ \/]+/g, '_').toLowerCase();
}

function wkt_split_names(names) {
  var arr;
  if (Array.isArray(names)) {
    arr = names;
  } else if (names && names.length > 0) {
    arr = names.split(',');
  }
  return arr;
}

function wkt_error(msg) {
  throw new Error(msg);
}

function wkt_warn(msg) {
  // TODO: consider option to inhibit logging
  //       consider strict mode to throw error
  console.error('[wkt] ' + msg);
}




function wkt_get_unit_defn(projcs) {
  // TODO: consider using unit names
  return {
    to_meter: projcs.UNIT[1]
  };
}

function wkt_convert_unit(PROJCS) {
  var defn = wkt_get_unit_defn(PROJCS);
  var proj4 = "";
  if (defn.to_meter != 1) {
    proj4 = '+to_meter=' + defn.to_meter;
  } else if (!WKT_OMIT_DEFAULTS) {
    proj4 = '+units=m';
  }
  return proj4;
}

function wkt_make_unit(P) {
  return ['Meter', P.to_meter || 1];
}

/*
// OLD -- merge into wkt_make_unit()
function wkt_get_unit(P) {
  var defn = pj_find_units_by_value(P.to_meter);
  var name = defn ? defn.name : 'Unknown';
  return ['UNIT', name, P.to_meter];
}
*/


function wkt_convert_geogcs(geogcs, opts) {
  var datum = geogcs.DATUM,
      spheroid = datum.SPHEROID,
      datumId = wkt_find_datum_id(datum),
      ellId = wkt_find_ellps_id(spheroid),
      aux_sphere = opts && opts.aux_sphere,
      a = spheroid[1],
      rf = spheroid[2],
      str, pm;

  wkt_check_units(geogcs.UNIT, 'degree');
  if (aux_sphere) {
    // TODO: in addition to semimajor, ESRI supports spheres based on
    //   semiminor and authalic radii; could support these
    str = '+a=' + spheroid[1];
  } else if (datumId) {
    str = '+datum=' + datumId;
  } else if (ellId) {
    str = '+ellps=' + ellId;
  } else {
   str = '+a=' + a;
    if (rf > 0) {
      str += ' +rf=' + rf;
    }
  }
  if (datum.TOWGS84 && !aux_sphere && !datumId) {
    str += ' +towgs84=' + datum.TOWGS84.join(',');
  }

  pm = geogcs.PRIMEM ? geogcs.PRIMEM[1] : 0;
  if (pm > 0 || pm < 0) {
    str += ' +pm=' + pm; // assuming degrees
  }
  return str;
}

function wkt_find_ellps_id(spheroid) {
  // TODO: match on ellipsoid parameters rather than name
  var aliases = {
    international1924: "intl"
  };
  var key = wkt_harmonize_geo_name(spheroid[0]);
  var defn;
  if (key in aliases) {
    return aliases[key];
  }
  if (/^grs1980/.test(key)) {
    // handle cases like "GRS 1980(IUGG, 1980)")
    return 'GRS80';
  }
  if (key == 'sphere') {
    // not a well defined ellipsoid
    // TODO: if we check ellipsoid params, this test can go away
    return null;
  }
  for (var i=0; i<pj_ellps.length; i++) {
    defn = pj_ellps[i];
    if (wkt_harmonize_geo_name(defn[3]) == key ||
        wkt_harmonize_geo_name(defn[0]) == key) {
      break;
    }
  }
  return defn ? defn[0] : null;
}

function wkt_find_datum_id(datum) {
  var aliases = { // ESRI aliases
    northamerican1983: 'NAD83',
    newzealand1949: 'nzgd49'
  };
  var key = wkt_harmonize_geo_name(datum.NAME);
  var defn;
  if (key in aliases) {
    return aliases[key];
  }
  for (var i=0; i<pj_datums.length; i++) {
    defn = pj_datums[i];
    if (wkt_harmonize_geo_name(defn[3]) == key ||
        wkt_harmonize_geo_name(defn[0]) == key) {
      break;
    }
  }
  return defn ? defn[0] : null;
}

function wkt_harmonize_geo_name(name) {
  return (name || '').replace(/^(GCS|D)_/i, '').replace(/[ _]/g, '').toLowerCase();
}

function wkt_check_units(UNIT, expect) {
  if (UNIT && UNIT[0].toLowerCase() != expect) {
    wkt_error("unexpected geographic units: " + geogcs.UNIT[0]);
  }
}


// Converts a PROJCS WKT in object format to a Proj.4 string
// Throws an Error if unable to convert
function wkt_convert_projcs(projcs) {
  return find_wkt_parser(projcs)(projcs);
}

function wkt_simple_projcs_converter(projId, paramIds) {
  return wkt_projcs_converter({
    PROJECTION: wkt_simple_projection_converter(projId),
    PARAMETER: wkt_parameter_converter(paramIds)
  });
}

function wkt_simple_projection_converter(id) {
  return function() {return '+proj=' + id;};
}

function wkt_projcs_converter(o) {
  return function(projcs) {
    var projStr = o.PROJECTION(projcs);
    var paramStr = o.PARAMETER(projcs);
    var geogStr = o.GEOGCS ? o.GEOGCS(projcs) : wkt_convert_geogcs(projcs.GEOGCS);
    var unitStr = wkt_convert_unit(projcs);
    return [projStr, paramStr, geogStr, unitStr, '+no_defs'].filter(function(s) {return !!s;}).join(' ');
  };
}


// Functions for exporting a wkt GEOGCS definition

function wkt_make_geogcs(P) {
  var geogcs = {
    NAME: wkt_get_geogcs_name(P),
    DATUM: wkt_make_datum(P),
    PRIMEM: ['Greenwich', 0], // TODO: don't assume greenwich
    UNIT: ['degree', 0.017453292519943295] // TODO: support other units
  };
  return geogcs;
}

function wkt_make_datum(P) {
  var datum = {
    NAME: wkt_get_datum_name(P),
    SPHEROID: wkt_make_spheroid(P)
  };
  var towgs84 = pj_param(P.params, 'stowgs84');
  if (/[1-9]/.test(towgs84)) { // only adding TOWGS84 if transformation is non-zero
    datum.TOWGS84 = towgs84;
  }
  return datum;
}

function wkt_make_spheroid(P) {
  var rf;
  if (pj_param(P.params, 'trf')) {
    rf = pj_param(P.params, 'drf');
  } else if (P.es) {
    rf = 1 / (1 - Math.sqrt(1 - P.es));
  } else {
    rf = 0;
  }
  return [wkt_get_ellps_name(P), P.a, rf];
}

function wkt_get_geogcs_name(P) {
  var name;
  if (pj_is_latlong(P)) {
    name = wkt_get_init_name(P);
  }
  if (!name) {
    name = wkt_get_datum_id(P);
    if (/^[a-z]+$/.test(name)) {
      name = name[0].toUpperCase() + name.substr(1);
    } else {
      name = name.toUpperCase();
    }
  }
  return name || 'UNK';
}

function wkt_get_ellps_name(P) {
  var ellps = find_ellps(wkt_get_ellps_id(P));
  return ellps ? ellps.name : 'Unknown ellipsoid';
}

function wkt_get_datum_name(P) {
  var defn = find_datum(wkt_get_datum_id(P));
  return defn && defn.name || 'Unknown datum';
}

function wkt_get_datum_id(P) {
  return pj_param(P.params, 'sdatum');
}

function wkt_get_ellps_id(P) {
  var datumId = wkt_get_datum_id(P),
      datum = datumId ? find_datum(datumId) : null,
      ellpsId;
  if (datum) {
    ellpsId = datum.ellipse_id;
  } else {
    ellpsId = pj_param(P.params, 'sellps');
  }
  return ellpsId || '';
}


// Converts a Proj object to a WKT in object format
function wkt_make_projcs(P) {
  return find_wkt_maker(P)(P);
}

function wkt_simple_projcs_maker(wktProjection, paramIds) {
  return wkt_projcs_maker({
    PROJECTION: wktProjection,
    PARAMETER: wkt_parameter_maker(paramIds)
  });
}

function wkt_projcs_maker(o) {
  return function(P) {
    var projcs = {
      // if o.NAME GEOGCS exists and returns falsy value, use default function
      GEOGCS: o.GEOGCS && o.GEOGCS(P) || wkt_make_geogcs(P),
      PROJECTION: wkt_is_string(o.PROJECTION) ? o.PROJECTION : o.PROJECTION(P),
      PARAMETER: o.PARAMETER(P),
      UNIT: wkt_make_unit(P)
    };
    // if o.NAME function exists and returns falsy value, use default name
    projcs.NAME = o.NAME && o.NAME(P, projcs) || wkt_make_default_projcs_name(P, projcs);
    return {PROJCS: projcs};
  };
}

// Get CS name from comment in +init source (if +init param is present)
function wkt_get_init_name(P) {
  var o;
  if (pj_param(P.params, 'tinit')) {
    o = pj_read_init_opts(pj_param(P.params, 'sinit'));
  }
  return o ? o.comment : '';
}

function wkt_make_default_projcs_name(P, projcs) {
  var initName = wkt_get_init_name(P);
  return initName || projcs.GEOGCS.NAME + ' / ' + projcs.PROJECTION;
}


function add_simple_wkt_parser(projId, wktProjections, params) {
  var is_match = get_simple_parser_test(wktProjections);
  var convert = wkt_simple_projcs_converter(projId, params);
  add_wkt_parser(is_match, convert);
}

function add_simple_wkt_maker(projId, wktProjection, params) {
  var is_match = get_simple_maker_test(projId);
  var make = wkt_simple_projcs_maker(wktProjection, params);
  // add_wkt_maker(is_match, wkt_make_projcs);
  add_wkt_maker(is_match, make);
}

function get_simple_parser_test(wktNames) {
  var slugs = wkt_split_names(wktNames).map(wkt_name_to_slug);
  return function(obj) {
    var wktName = obj.PROJECTION[0]; // TODO: handle unexpected structure
    return slugs.indexOf(wkt_name_to_slug(wktName)) > -1;
  };
}

function get_simple_maker_test(projId) {
  return function(P) {
    var id = get_proj_id(P);
    return id && id == projId;
  };
}

function add_wkt_parser(is_match, parse) {
  if (typeof is_match != 'function') wkt_error("Missing WKT parser test");
  if (typeof parse != 'function') wkt_error("Missing WKT parse function");
  wkt_parsers.push([is_match, parse]);
}

function add_wkt_maker(is_match, make) {
  if (typeof is_match != 'function') wkt_error("Missing WKT maker test");
  if (typeof make != 'function') wkt_error("Missing WKT maker function");
  wkt_makers.push([is_match, make]);
}


add_wkt_parser(wkt_is_utm, wkt_to_utm);
add_wkt_parser(wkt_is_ups, wkt_to_ups);

add_wkt_maker(get_simple_maker_test('utm'), wkt_from_utm);
add_wkt_maker(get_simple_maker_test('ups'), wkt_from_ups);

var WKT_UTM = /UTM_zone_([0-9]{1,2})(N|S)/i;
var WKT_UPS = /UPS_(North|South)/i;

function wkt_is_utm(projcs) {
  return WKT_UTM.test(wkt_name_to_slug(projcs.NAME));
}

function wkt_is_ups(projcs) {
  return WKT_UPS.test(wkt_name_to_slug(projcs.NAME));
}

function wkt_to_utm(projcs) {
  return wkt_projcs_converter({
    PROJECTION: wkt_simple_projection_converter('utm'),
    PARAMETER: utm_params
  })(projcs);

  function utm_params(projcs) {
    var match = WKT_UTM.exec(wkt_name_to_slug(projcs.NAME));
    var params = '+zone=' + match[1];
    if (match[2].toLowerCase() == 's') params += ' +south';
    return params;
  }
}

function wkt_to_ups(projcs) {
  return wkt_projcs_converter({
    PROJECTION: wkt_simple_projection_converter('ups'),
    PARAMETER: ups_params
  })(projcs);

  function ups_params(projcs) {
    var match = WKT_UPS.exec(wkt_name_to_slug(projcs.NAME));
    return match[1].toLowerCase() == 'south' ? '+south' : '';
  }
}

function wkt_from_utm(P) {
  return wkt_projcs_maker({
    NAME: wkt_make_utm_name,
    PROJECTION: function () {return 'Transverse_Mercator';},
    PARAMETER: wkt_make_utm_params
  })(P);
}

function wkt_from_ups(P) {
  return wkt_projcs_maker({
    NAME: wkt_make_ups_name,
    PROJECTION: function () {return 'Polar_Stereographic';},
    PARAMETER: wkt_make_ups_params
  })(P);
}

function wkt_make_utm_name(P, projcs) {
  return projcs.GEOGCS.NAME + ' / UTM zone ' + pj_param(P.params, 'szone') + (pj_param(P.params, 'tsouth') ? 'S' : 'N');
}

function wkt_make_ups_name(P, projcs) {
  return projcs.GEOGCS.NAME + ' / UPS ' + (pj_param(P.params, 'tsouth') ? 'South' : 'North');
}

function wkt_make_utm_params(P) {
  var lon0 = P.lam0 * 180 / M_PI;
  return [
    ["latitude_of_origin", 0],
    ["central_meridian", lon0],
    ["scale_factor", P.k0],
    ["false_easting", P.x0],
    ["false_northing", P.y0]
  ];
}

function wkt_make_ups_params(P) {
  return [
    ["latitude_of_origin", -90],
    ["central_meridian", 0],
    ["scale_factor", 0.994],
    ["false_easting", 2000000],
    ["false_northing", 2000000]
  ];
}


// Mercator_2SP references:
//    http://geotiff.maptools.org/proj_list/mercator_2sp.html
//    http://www.remotesensing.org/geotiff/proj_list/mercator_2sp.html
//    https://trac.osgeo.org/gdal/ticket/4861

add_wkt_parser(get_simple_parser_test('Mercator_2SP,Mercator_1SP,Mercator,Mercator_Auxiliary_Sphere'),
  wkt_projcs_converter({
    GEOGCS: wkt_convert_merc_geogcs,
    PROJECTION: wkt_simple_projection_converter('merc'),
    PARAMETER: wkt_convert_merc_params
  }));

add_wkt_maker(get_simple_maker_test('merc'),
  wkt_projcs_maker({
    GEOGCS: wkt_make_merc_geogcs,
    PROJECTION: wkt_make_merc_projection,
    PARAMETER: wkt_make_merc_params,
    NAME: wkt_make_merc_name
  }));

function wkt_make_merc_name(P) {
  return wkt_proj4_is_webmercator(P) ? 'WGS 84 / Pseudo-Mercator' : null;
}

function wkt_make_merc_geogcs(P) {
  // PROBLEM: no clear way to get geographic cs from proj4 string
  // ... so assuming WGS 84 (consider using spherical datum instead)
  if (wkt_proj4_is_webmercator(P)) {
    return wkt_make_geogcs(pj_init('+proj=longlat +datum=WGS84'));
  }
  return null;
}

function wkt_convert_merc_geogcs(projcs) {
  var opts = wkt_projcs_is_webmercator(projcs) ? {aux_sphere: true} : null;
  return wkt_convert_geogcs(projcs.GEOGCS, opts);
}

function wkt_make_merc_projection(P) {
  return wkt_proj4_is_merc_2sp(P) ? 'Mercator_2SP' : 'Mercator_1SP';
}

function wkt_convert_merc_params(projcs) {
  // TODO: handle (esri) standard_parallel_1 in 1sp version
  // 1sp version accepts latitude_of_origin (ogc) or standard_parallel_1 (esri)
  // var rules = wkt_projcs_is_merc_2sp(projcs) ? 'lat_ts,lat_0b' : 'lat_tsb,lat_ts';
  var rules = wkt_projcs_is_merc_2sp(projcs) ? 'lat_ts,lat_0b' : 'lat_tsb,lat_ts';
  return wkt_parameter_converter(rules)(projcs);
}

function wkt_make_merc_params(P) {
  var rules = wkt_proj4_is_merc_2sp(P) ? 'lat_ts,lat_0b' : 'lat_tsb';
  return wkt_parameter_maker(rules)(P);
}

function wkt_projcs_is_merc_2sp(projcs) {
  var param = wkt_find_parameter_by_name(projcs, 'standard_parallel_1');
  return param && param[1] != 0;
}

function wkt_proj4_is_merc_2sp(P) {
  return pj_param(P.params, 'tlat_ts') && pj_param(P.params, 'dlat_ts') != 0;
}

function wkt_projcs_is_webmercator(projcs) {
  return /(Web_Mercator|Pseudo_Mercator)/i.test(wkt_name_to_slug(projcs.NAME));
}

// TODO: support other spheroids (web mercator may be used for other planets)
function wkt_proj4_is_webmercator(P) {
  return P.es === 0 && P.a == 6378137;
}




// Reference:
// http://proj4.org/parameters.html

var wkt_common_params = [
  ['x_0', 'false_easting', 'm'],
  ['y_0', 'false_northing', 'm'],
  ['k_0', 'scale_factor', 'f'],
  ['lat_0', 'latitude_of_center'],
  ['lon_0', 'central_meridian']
];

var wkt_param_table = {
  lat_0b:  ['lat_0', 'latitude_of_origin'],
  lat_0c:  ['lat_0', null], // lcc 1sp, stere
  lat_0d:  ['lat_0', 'standard_parallel_1'],  // stere (esri), merc (esri)
  lat_1:   ['lat_1', 'standard_parallel_1'],
  lat_1b:  ['lat_1', 'latitude_of_point_1'],  // omerc,tpeqd
  lat_1c:  ['lat_1', 'latitude_of_origin'],   // lcc
  lat_2:   ['lat_2', 'standard_parallel_2'],
  lat_2b:  ['lat_2', 'latitude_of_point_2'],  // omerc,tpeqd
  lat_ts:  ['lat_ts', 'standard_parallel_1'], // cea,eqc,merc,stere,wag3,wink1
  lat_tsb: ['lat_ts', 'latitude_of_origin'],  // merc
  lonc:    ['lonc', 'central_meridian'],      // omerc,ocea
  lon_1:   ['lon_1', 'longitude_of_point_1'], // omerc,tpeqd
  lon_2:   ['lon_2', 'longitude_of_point_2'], // omerc,tpeqd
  alpha:   ['alpha', 'azimuth'],              // omerc,ocea
  gamma:   ['gamma', 'rectified_grid_angle'], // omerc
  h:       ['h', 'height', 'f'] // nsper
};

// non-standard name -> standard name
// TODO: consider accepting standard_parallel_1 as (esri) alias for latitude_of_center / latitude_of_origin
var wkt_param_aliases = {
  longitude_of_center: 'central_meridian',
  latitude_of_origin: 'latitude_of_center',
  latitude_of_center: 'latitude_of_origin',
  longitude_of_1st_point: 'longitude_of_point_1',
  longitude_of_2nd_point: 'longitude_of_point_2',
  latitude_of_1st_point: 'latitude_of_point_1',
  latitude_of_2nd_point: 'latitude_of_point_2',
  // proj4
  k: 'k_0'
};

// Convert a wkt PARAMETER name to a proj4 param id
function wkt_convert_param_name_old(wktName, proj) {
  var defn = wkt_find_param_defn_old(proj, function(defn) {
    return defn[1] == wktName;
  });
  return defn ? defn[0] : '';
}

// @proj Proj.4 projection id
function wkt_find_param_defn_old(proj, test) {
  var defn, projs;
  for (var i=0; i<wkt_params.length; i++) {
    defn = wkt_params[i];
    projs = defn[3];
    if (projs && projs.split(',').indexOf(proj) == -1) continue;
    if (test(defn)) return defn;
  }
  return null;
}


function wkt_find_defn(name, idx, arr) {
  for (var i=0; i<arr.length; i++) {
    // returns first match (additional matches -- aliases -- may be present)
    if (arr[i][idx] === name) return arr[i];
  }
  return null;
}

function wkt_find_parameter_defn(name, idx, rules) {
  var defn = null;
  name = name.toLowerCase();
  defn = wkt_find_defn(name, idx, rules);
  if (!defn && (name in wkt_param_aliases)) {
    defn = wkt_find_defn(wkt_param_aliases[name], idx, rules);
  }
  return defn;
}

function wkt_convert_parameter(defn, value, unitDefn) {
  var name = defn[0],
      type = defn[2];
  if (type == 'm') {
    value *= unitDefn.to_meter;
  }
  if (WKT_OMIT_DEFAULTS) {
    if ('x_0,y_0,lat_0,lon_0'.indexOf(name) > -1 && value === 0 ||
      name == 'k_0' && value == 1) {
      return;
    }
  }
  return '+' + name + '=' + value;
}

function wkt_make_parameter(defn, strVal, toMeter) {
  var type = defn[2],
      val;
  if (type == 'm') {
    val = parseFloat(strVal) / toMeter;
  } else if (type == 'f') {
    val = parseFloat(strVal);
  } else {
    val = dmstod(strVal); // default is decimal degrees or DMS
  }
  return [defn[1], val];
}

function wkt_find_parameter_by_name(projcs, name) {
  var params = projcs.PARAMETER || [];
  var paramName;
  for (var i=0; i<params.length; i++) {
    paramName = params[i][0].toLowerCase();
    if (name === paramName || name === wkt_param_aliases[paramName]) {
      return params[i];
    }
  }
  return null;
}

function wkt_get_parameter_value(projcs, name) {
  var param = wkt_find_parameter_by_name(projcs, name);
  return param === null ? null : param[1];
}

function wkt_get_parameter_rules(ids) {
  var rules = null;
  if (ids) {
    rules = wkt_split_names(ids).reduce(function(memo, id) {
      var rule = wkt_param_table[id];
      if (!rule) wkt_error("missing parameter rule: " + id);
      memo.push(rule);
      return memo;
    }, []);
  }
  return (rules || []).concat(wkt_common_params);
}

function wkt_parameter_converter(extraRules) {
  return function(projcs) {
    var parts = [];
    var rules = wkt_get_parameter_rules(extraRules);
    var unitDefn = wkt_get_unit_defn(projcs);
    (projcs.PARAMETER || []).forEach(function(param) { // handle no params
      var defn = wkt_find_parameter_defn(param[0], 1, rules);
      var proj4;
      if (!defn) {
        wkt_warn('unhandled parameter: ' + param[0]);
      } else {
        proj4 = wkt_convert_parameter(defn, param[1], unitDefn);
        if (proj4) parts.push(proj4);
      }
    });
    return parts.join(' ');
  };
}

function wkt_parameter_maker(extraRules) {
  return function(P) {
    var params = [];
    var rules = wkt_get_parameter_rules(extraRules);
    // TODO: think about how to add default params omitted from proj4 defn
    // TODO: think about detecting unused params in proj4 defn
    Object.keys(P.params).forEach(function(key) {
      var defn = wkt_find_parameter_defn(key, 0, rules);
      var sval;
      if (defn && defn[1]) { // handle dummy rules with null wkt param name (see wkt_lcc.js)
        sval = pj_param(P.params, 's' + key);
        params.push(wkt_make_parameter(defn, sval, P.to_meter));
      }
    });
    return params;
  };
}


add_wkt_parser(get_simple_parser_test(
  'Lambert_Conformal_Conic,Lambert_Conformal_Conic_1SP,Lambert_Conformal_Conic_2SP'),
  wkt_projcs_converter({
    PROJECTION: wkt_simple_projection_converter('lcc'),
    PARAMETER: wkt_convert_lcc_params
  }));

add_wkt_maker(get_simple_maker_test('lcc'),
  wkt_projcs_maker({
    PROJECTION: wkt_make_lcc_projection,
    PARAMETER: wkt_make_lcc_params
  }));

function wkt_make_lcc_params(P) {
  var params = wkt_proj4_is_lcc_1sp(P) ? 'lat_1c,lat_0c' : 'lat_0b,lat_1,lat_2';
  return wkt_parameter_maker(params)(P);
}

function wkt_convert_lcc_params(projcs) {
  var params = wkt_projcs_is_lcc_1sp(projcs) ? 'lat_1c' : 'lat_0b,lat_1,lat_2';
  return wkt_parameter_converter(params)(projcs);
}

function wkt_make_lcc_projection(P) {
  return wkt_proj4_is_lcc_1sp(P) ? 'Lambert_Conformal_Conic_1SP' : 'Lambert_Conformal_Conic_2SP';
}

function wkt_projcs_is_lcc_1sp(projcs) {
  return !wkt_find_parameter_by_name(projcs, 'standard_parallel_2');
}

function wkt_proj4_is_lcc_1sp(P) {
  return !('lat_1' in P.params && 'lat_2' in P.params);
}


// Type A
add_wkt_parser(
  get_simple_parser_test('Hotine_Oblique_Mercator,Hotine_Oblique_Mercator_Azimuth_Natural_Origin'),
  wkt_projcs_converter({
    PROJECTION: wkt_simple_projection_converter('omerc'),
    PARAMETER: function(P) {return wkt_parameter_converter('alpha,gamma,lonc')(P) + ' +no_uoff';}
  })
);
add_wkt_maker(wkt_proj4_is_omerc_A, wkt_simple_projcs_maker('Hotine_Oblique_Mercator', 'alpha,gamma,lonc'));

// Type B
add_simple_wkt_parser('omerc', 'Oblique_Mercator,Hotine_Oblique_Mercator_Azimuth_Center', 'alpha,gamma,lonc');
add_wkt_maker(wkt_proj4_is_omerc_B, wkt_simple_projcs_maker('Oblique_Mercator', 'alpha,gamma,lonc'));

// Two-point version
add_simple_wkt_parser('omerc', 'Hotine_Oblique_Mercator_Two_Point_Natural_Origin', 'lat_1b,lat_2b,lon_1,lon_2');
add_wkt_maker(
  wkt_proj4_is_omerc_2pt,
  wkt_simple_projcs_maker('Hotine_Oblique_Mercator_Two_Point_Natural_Origin', 'lat_1b,lat_2b,lon_1,lon_2')
);

function wkt_proj4_is_omerc_2pt(P) {
  return get_proj_id(P) == 'omerc' && 'lat_2' in P.params && 'lon_2' in P.params;
}

function wkt_proj4_is_omerc(P) {
  return get_proj_id(P) == 'omerc' && ('alpha' in P.params || 'gamma' in P.params);
}

function wkt_proj4_is_omerc_A(P) {
  return wkt_proj4_is_omerc(P) && ('no_uoff' in P.params || 'no_off' in P.params);
}

function wkt_proj4_is_omerc_B(P) {
  return wkt_proj4_is_omerc(P) && !wkt_proj4_is_omerc_A(P);
}


// add_simple_wkt_parser('stere', ['Stereographic', 'Polar_Stereographic', 'Stereographic_North_Pole', 'Stereographic_South_Pole']);

/*
  Stereographic vs. Polar Stereographic from geotiff
  http://geotiff.maptools.org/proj_list/polar_stereographic.html
  http://geotiff.maptools.org/proj_list/stereographic.html
  http://geotiff.maptools.org/proj_list/random_issues.html#stereographic
*/

add_wkt_parser(get_simple_parser_test('Stereographic,Polar_Stereographic,Stereographic_North_Pole,Stereographic_South_Pole'),
  wkt_projcs_converter({
    PROJECTION: wkt_simple_projection_converter('stere'),
    PARAMETER: wkt_convert_stere_params
  }));

add_wkt_maker(get_simple_maker_test('stere'),
  wkt_projcs_maker({
    PROJECTION: wkt_make_stere_projection,
    PARAMETER: wkt_make_stere_params
  }));

function wkt_convert_stere_params(projcs) {
  // assuming not oblique; TOOD: verify not oblique
  var params = wkt_parameter_converter('lat_ts,lat_tsb')(projcs);
  var match = /lat_ts=([^ ]+)/.exec(params);
  if (match && params.indexOf('lat_0=') == -1) {
    // Add +lat_0=90 or +lat_0=-90
    params = '+lat_0=' + (parseFloat(match[1]) < 0 ? -90 : 90) + ' ' + params;
  }
  return params;
}

function wkt_make_stere_projection(P) {
  // switching to stere -> Stereographic, to match ogr2ogr output
  // return wkt_proj4_is_stere_polar(P) ? 'Polar_Stereographic' : 'Oblique_Stereographic';
  return wkt_proj4_is_stere_polar(P) ? 'Polar_Stereographic' : 'Stereographic';
}

function wkt_make_stere_params(P) {
  return wkt_proj4_is_stere_polar(P) ?
    wkt_parameter_maker('lat_tsb,lat_0c')(P) : // lat_ts -> latitude_of_origin, lat_0 -> null
    wkt_parameter_maker('lat_0b')(P);      // lat_0 -> latitude_of_origin
}

function wkt_proj4_is_stere_polar(P) {
  return pj_param(P.params, 'tlat_ts');
}


add_simple_wkt_maker('vandg', 'VanDerGrinten');
add_wkt_parser(
  get_simple_parser_test('VanDerGrinten,Van_der_Grinten_I'),
  wkt_projcs_converter({
    PROJECTION: wkt_simple_projection_converter('vandg'),
    PARAMETER: function(P) {
      var params = wkt_parameter_converter('')(P);
      if (params) params += ' ';
      return params + '+R_A';
    }
  })
);


/*
// projections still missing WKT conversion
[
  ['airy', ''],
  ['boggs', ''],
  ['crast', 'Craster_Parabolic'],
  ['gn_sinu', ''],
  ['gstmerc', 'Gauss_Schreiber_Transverse_Mercator'], // https://trac.osgeo.org/gdal/ticket/2663
  ['geos', 'Geostationary_Satellite'],
  ['goode', 'Goode_Homolosine'],
  ['igh', 'Interrupted_Goode_Homolosine'],
  ['imw_p', 'International_Map_of_the_World_Polyconic'],
  ['kav7', ''],
  ['krovak', 'Krovak'],
  ['laborde', 'Laborde_Oblique_Mercator'],
  ['mbtfps', ''],
  ['nell_h', ''],
  ['ocea', ''], // see OneNote notes
  ['qua_aut', 'Quartic_Authalic'],
  ['', 'Swiss_Oblique_Cylindrical'], // http://www.remotesensing.org/geotiff/proj_list/swiss_oblique_cylindrical.html
  ['', 'Transverse_Mercator_South_Orientated'], // http://www.remotesensing.org/geotiff/proj_list/transverse_mercator_south_oriented.html
]
*/

// Add simple conversion functions
// optional third field gives alternate parameters (defined in wkt_parameters.js)
[
  ['aitoff', 'Aitoff', 'lat1'],
  ['aea', 'Albers_Conic_Equal_Area,Albers', 'lat_1,lat_2'],
  ['aeqd', 'Azimuthal_Equidistant'],
  ['bonne', 'Bonne', 'lat_1'],
  ['cass', 'Cassini_Soldner,Cassini'],
  ['cea', 'Cylindrical_Equal_Area', 'lat_ts'],
  ['eck1', 'Eckert_I'],
  ['eck2', 'Eckert_II'],
  ['eck3', 'Eckert_III'],
  ['eck4', 'Eckert_IV'],
  ['eck5', 'Eckert_V'],
  ['eck6', 'Eckert_VI'],
  ['eqdc', 'Equidistant_Conic', 'lat_1,lat_2'],
  ['eqc', 'Plate_Carree,Equirectangular,Equidistant_Cylindrical', 'lat_ts'],
  ['gall', 'Gall_Stereographic'],
  ['gnom', 'Gnomonic'],
  ['laea', 'Lambert_Azimuthal_Equal_Area'],
  ['loxim', 'Loximuthal', 'lat_1'],
  ['mill', 'Miller_Cylindrical'],
  ['moll', 'Mollweide'],
  ['nsper', 'Vertical_Near_Side_Perspective', 'h'],
  ['nzmg', 'New_Zealand_Map_Grid', 'lat_0b'],
  ['ortho', 'Orthographic', 'lat_0b'],
  ['poly', 'Polyconic'],
  ['robin', 'Robinson'],
  ['sinu', 'Sinusoidal'],
  ['sterea', 'Oblique_Stereographic,Double_Stereographic'], // http://geotiff.maptools.org/proj_list/oblique_stereographic.html
  ['tmerc', 'Transverse_Mercator,Gauss_Kruger', 'lat_0b'],
  ['tpeqd', 'Two_Point_Equidistant', 'lat_1b,lat_2b,lon_1,lon_2'],
  // ['vandg', 'VanDerGrinten,Van_der_Grinten_I'], // slight complication, see wkt_vandg.js
  ['wag1', 'Wagner_I'],
  ['wag2', 'Wagner_II'],
  ['wag3', 'Wagner_III', 'lat_ts'],
  ['wag4', 'Wagner_IV'],
  ['wag5', 'Wagner_V'],
  ['wag6', 'Wagner_VI'],
  ['wag7', 'Wagner_VII'],
  ['wink1', 'Winkel_I', 'lat_ts'],
  ['wink2', 'Winkel_II'],
  ['wintri', 'Winkel_Tripel', 'lat_1']
].forEach(function(arr) {
  var alternateParams = arr[2] || null;
  add_simple_wkt_parser(arr[0], arr[1], alternateParams);
  add_simple_wkt_maker(arr[0], arr[1].split(',')[0], alternateParams);
});



function wkt_stringify(o) {
  var str = JSON.stringify(wkt_stringify_reorder(o));
  str = str.replace(/\["([A-Z0-9]+)",/g, '$1['); // convert JSON arrays to WKT
  // remove quotes from AXIS values (not supported: UP|DOWN|OTHER etc.)
  // see (http://www.geoapi.org/apidocs/org/opengis/referencing/doc-files/WKT.html)
  str = str.replace(/"(EAST|NORTH|SOUTH|WEST)"/g, '$1');
  return str;
}

function wkt_sort_order(key) {
  // supported WKT names in sorted order
  var names = 'NAME,PROJCS,GEOGCS,GEOCCS,DATUM,SPHEROID,PRIMEM,PROJECTION,PARAMETER,UNIT,AXIS';
  return names.indexOf(key) + 1 || 999;
}

function wkt_keys(o) {
  var keys = Object.keys(o);
  return keys.sort(function(a, b) {
    return wkt_sort_order(a) - wkt_sort_order(b);
  });
}

// Rearrange a generated WKT object for easier string conversion
// inverse of wkt_parse_reorder()
function wkt_stringify_reorder(o, depth) {
  var arr = [], e;
  depth = depth || 0;
  wkt_keys(o).forEach(function(name) {
    var val = o[name];
    if (wkt_is_object(val)) {
      arr.push([name].concat(wkt_stringify_reorder(val, depth + 1)));
    } else if (name == 'NAME') {
      arr.push(wkt_is_string(val) ? val : val[0]);
    } else if (name == 'PARAMETER' || name == 'AXIS') {
      val.forEach(function(param) {
        arr.push([name].concat(param));
      });
    } else if (wkt_is_string(val)) {
      arr.push([name, val]);
    } else if (Array.isArray(val)) {
       arr.push([name].concat(val));
    } else {
      e = {};
      e[name] = val;
      wkt_error("Incorrectly formatted WKT element: " + JSON.stringify(e));
    }
  });
  if (depth === 0 && arr.length == 1) {
    arr = arr[0]; // kludge to remove top-level array
  }
  return arr;
}




function wkt_parse(str) {
  var obj = {};
  wkt_unpack(str).forEach(function(part) {
    wkt_parse_reorder(part, obj);
  });
  return obj;
}

// Convert WKT string to a JS object
// WKT format: http://docs.opengeospatial.org/is/12-063r5/12-063r5.html#11
function wkt_unpack(str) {
  var obj;
  // Convert WKT escaped quotes to JSON escaped quotes
  // str = str.replace(/""/g, '\\"'); // BUGGY
  str = convert_wkt_quotes(str);

  // Convert WKT entities to JSON arrays
  str = str.replace(/([A-Z0-9]+)\[/g, '["$1",');

  // Enclose axis keywords in quotes to create valid JSON strings
  str = str.replace(/, *([a-zA-Z]+) *(?=[,\]])/g, ',"$1"');

  // str = str.replace(/[^\]]*$/, ''); // esri .prj string may have extra stuff appended

  // WKT may have a "VERTCS" section after "PROJCS" section; enclosing contents
  //   in brackets to create valid JSON array.
  str = '[' + str + ']';

  try {
    obj = JSON.parse(str);
  } catch(e) {
    wkt_error('unparsable WKT format');
  }
  return obj;
}

// Convert WKT escaped quotes to JSON escaped quotes ("" -> \")
function convert_wkt_quotes(str) {
  var c = 0;
  return str.replace(/"+/g, function(s) {
    var even = c % 2 == 0;
    c += s.length;
    // ordinary, unescaped quotes
    if (s == '"' || s == '""' && even) return s;
    // WKT-escaped quotes
    if (even) {
      return '"' + s.substring(1).replace(/""/g, '\\"');
    } else {
      return s.replace(/""/g, '\\"');
    }
  });
}

// Rearrange a subarray of a parsed WKT file for easier traversal
// E.g.
//   ["WGS84", ...]  to  {NAME: "WGS84"}
//   ["PROJECTION", "Mercator"]  to  {PROJECTION: "Mercator"}
//   ["PARAMETER", <param1>], ...  to  {PARAMETER: [<param1>, ...]}
function wkt_parse_reorder(arr, obj) {
  var name = arr[0], // TODO: handle alternate OGC names
      i;
  if (name == 'GEOGCS' || name == 'GEOCCS' || name == 'PROJCS' || name == 'DATUM' || name == 'VERTCS') {
    obj[name] = {
      NAME: arr[1]
    };
    for (i=2; i<arr.length; i++) {
      if (Array.isArray(arr[i])) {
        wkt_parse_reorder(arr[i], obj[name]);
      } else {
        throw wkt_error("WKT parse error");
      }
    }
  } else if (name == 'AXIS' || name == 'PARAMETER') {
    if (name in obj === false) {
      obj[name] = [];
    }
    obj[name].push(arr.slice(1));

  } else {
    obj[name] = arr.slice(1);
  }
  return obj;
}


var WKT_OMIT_DEFAULTS = true;

function wkt_from_proj4(P) {
  var obj;
  if (P.length) P = pj_init(P); // convert proj4 string
  if (pj_is_latlong(P)) {
    obj = {GEOGCS: wkt_make_geogcs(P)};
  } else {
    obj = wkt_make_projcs(P);
  }
  return wkt_stringify(obj);
}

// @str A WKT CRS definition string (e.g. contents of a .prj file)
function wkt_to_proj4(str) {
  var o = wkt_parse(str);
  var proj4;

  if (o.PROJCS) {
    proj4 = wkt_convert_projcs(o.PROJCS);

  } else if (o.GEOGCS) {
    proj4 = '+proj=longlat ' + wkt_convert_geogcs(o.GEOGCS);

  } else if (o.GEOCCS) {
    wkt_error('geocentric coordinates are not supported');

  } else {
    wkt_error('missing a supported WKT CS type');
  }
  return proj4;
}



/*
 * Math.js
 * Transcription of Math.hpp, Constants.hpp, and Accumulator.hpp into
 * JavaScript.
 *
 * Copyright (c) Charles Karney (2011-2017) <charles@karney.com> and licensed
 * under the MIT/X11 License.  For more information, see
 * https://geographiclib.sourceforge.io/
 */

/**
 * @namespace GeographicLib
 * @description The parent namespace for the following modules:
 * - {@link module:GeographicLib/Geodesic GeographicLib/Geodesic} The main
 *   engine for solving geodesic problems via the
 *   {@link module:GeographicLib/Geodesic.Geodesic Geodesic} class.
 * - {@link module:GeographicLib/GeodesicLine GeographicLib/GeodesicLine}
 *   computes points along a single geodesic line via the
 *   {@link module:GeographicLib/GeodesicLine.GeodesicLine GeodesicLine}
 *   class.
 * - {@link module:GeographicLib/PolygonArea GeographicLib/PolygonArea}
 *   computes the area of a geodesic polygon via the
 *   {@link module:GeographicLib/PolygonArea.PolygonArea PolygonArea}
 *   class.
 * - {@link module:GeographicLib/DMS GeographicLib/DMS} handles the decoding
 *   and encoding of angles in degree, minutes, and seconds, via static
 *   functions in this module.
 * - {@link module:GeographicLib/Constants GeographicLib/Constants} defines
 *   constants specifying the version numbers and the parameters for the WGS84
 *   ellipsoid.
 *
 * The following modules are used internally by the package:
 * - {@link module:GeographicLib/Math GeographicLib/Math} defines various
 *   mathematical functions.
 * - {@link module:GeographicLib/Accumulator GeographicLib/Accumulator}
 *   interally used by
 *   {@link module:GeographicLib/PolygonArea.PolygonArea PolygonArea} (via the
 *   {@link module:GeographicLib/Accumulator.Accumulator Accumulator} class)
 *   for summing the contributions to the area of a polygon.
 */
"use strict";
var GeographicLib = {};
GeographicLib.Constants = {};
GeographicLib.Math = {};
GeographicLib.Accumulator = {};

(function(
  /**
   * @exports GeographicLib/Constants
   * @description Define constants defining the version and WGS84 parameters.
   */
  c) {

  /**
   * @constant
   * @summary WGS84 parameters.
   * @property {number} a the equatorial radius (meters).
   * @property {number} f the flattening.
   */
  c.WGS84 = { a: 6378137, f: 1/298.257223563 };
  /**
   * @constant
   * @summary an array of version numbers.
   * @property {number} major the major version number.
   * @property {number} minor the minor version number.
   * @property {number} patch the patch number.
   */
  c.version = { major: 1, minor: 48, patch: 0 };
  /**
   * @constant
   * @summary version string
   */
  c.version_string = "1.48";
})(GeographicLib.Constants);

(function(
  /**
   * @exports GeographicLib/Math
   * @description Some useful mathematical constants and functions (mainly for
   *   internal use).
   */
  m) {

  /**
   * @summary The number of digits of precision in floating-point numbers.
   * @constant {number}
   */
  m.digits = 53;
  /**
   * @summary The machine epsilon.
   * @constant {number}
   */
  m.epsilon = Math.pow(0.5, m.digits - 1);
  /**
   * @summary The factor to convert degrees to radians.
   * @constant {number}
   */
  m.degree = Math.PI/180;

  /**
   * @summary Square a number.
   * @param {number} x the number.
   * @returns {number} the square.
   */
  m.sq = function(x) { return x * x; };

  /**
   * @summary The hypotenuse function.
   * @param {number} x the first side.
   * @param {number} y the second side.
   * @returns {number} the hypotenuse.
   */
  m.hypot = function(x, y) {
    var a, b;
    x = Math.abs(x);
    y = Math.abs(y);
    a = Math.max(x, y); b = Math.min(x, y) / (a ? a : 1);
    return a * Math.sqrt(1 + b * b);
  };

  /**
   * @summary Cube root function.
   * @param {number} x the argument.
   * @returns {number} the real cube root.
   */
  m.cbrt = function(x) {
    var y = Math.pow(Math.abs(x), 1/3);
    return x < 0 ? -y : y;
  };

  /**
   * @summary The log1p function.
   * @param {number} x the argument.
   * @returns {number} log(1 + x).
   */
  m.log1p = function(x) {
    var y = 1 + x,
        z = y - 1;
    // Here's the explanation for this magic: y = 1 + z, exactly, and z
    // approx x, thus log(y)/z (which is nearly constant near z = 0) returns
    // a good approximation to the true log(1 + x)/x.  The multiplication x *
    // (log(y)/z) introduces little additional error.
    return z === 0 ? x : x * Math.log(y) / z;
  };

  /**
   * @summary Inverse hyperbolic tangent.
   * @param {number} x the argument.
   * @returns {number} tanh<sup>&minus;1</sup> x.
   */
  m.atanh = function(x) {
    var y = Math.abs(x);          // Enforce odd parity
    y = m.log1p(2 * y/(1 - y))/2;
    return x < 0 ? -y : y;
  };

  /**
   * @summary Copy the sign.
   * @param {number} x gives the magitude of the result.
   * @param {number} y gives the sign of the result.
   * @returns {number} value with the magnitude of x and with the sign of y.
   */
  m.copysign = function(x, y) {
    return Math.abs(x) * (y < 0 || (y === 0 && 1/y < 0) ? -1 : 1);
  };

  /**
   * @summary An error-free sum.
   * @param {number} u
   * @param {number} v
   * @returns {object} sum with sum.s = round(u + v) and sum.t is u + v &minus;
   *   round(u + v)
   */
  m.sum = function(u, v) {
    var s = u + v,
        up = s - v,
        vpp = s - up,
        t;
    up -= u;
    vpp -= v;
    t = -(up + vpp);
    // u + v =       s      + t
    //       = round(u + v) + t
    return {s: s, t: t};
  };

  /**
   * @summary Evaluate a polynomial.
   * @param {integer} N the order of the polynomial.
   * @param {array} p the coefficient array (of size N + 1) (leading
   *   order coefficient first)
   * @param {number} x the variable.
   * @returns {number} the value of the polynomial.
   */
  m.polyval = function(N, p, s, x) {
    var y = N < 0 ? 0 : p[s++];
    while (--N >= 0) y = y * x + p[s++];
    return y;
  };

  /**
   * @summary Coarsen a value close to zero.
   * @param {number} x
   * @returns {number} the coarsened value.
   */
  m.AngRound = function(x) {
    // The makes the smallest gap in x = 1/16 - nextafter(1/16, 0) = 1/2^57 for
    // reals = 0.7 pm on the earth if x is an angle in degrees.  (This is about
    // 1000 times more resolution than we get with angles around 90 degrees.)
    // We use this to avoid having to deal with near singular cases when x is
    // non-zero but tiny (e.g., 1.0e-200).  This converts -0 to +0; however
    // tiny negative numbers get converted to -0.
    if (x === 0) return x;
    var z = 1/16,
        y = Math.abs(x);
    // The compiler mustn't "simplify" z - (z - y) to y
    y = y < z ? z - (z - y) : y;
    return x < 0 ? -y : y;
  };

  /**
   * @summary Normalize an angle.
   * @param {number} x the angle in degrees.
   * @returns {number} the angle reduced to the range (&minus;180&deg;,
   *   180&deg;].
   */
  m.AngNormalize = function(x) {
    // Place angle in [-180, 180).
    x = x % 360;
    return x <= -180 ? x + 360 : (x <= 180 ? x : x - 360);
  };

  /**
   * @summary Normalize a latitude.
   * @param {number} x the angle in degrees.
   * @returns {number} x if it is in the range [&minus;90&deg;, 90&deg;],
   *   otherwise return NaN.
   */
  m.LatFix = function(x) {
    // Replace angle with NaN if outside [-90, 90].
    return Math.abs(x) > 90 ? Number.NaN : x;
  };

  /**
   * @summary The exact difference of two angles reduced to (&minus;180&deg;,
   *   180&deg;]
   * @param {number} x the first angle in degrees.
   * @param {number} y the second angle in degrees.
   * @return {object} diff the exact difference, y &minus; x.
   *
   * This computes z = y &minus; x exactly, reduced to (&minus;180&deg;,
   * 180&deg;]; and then sets diff.s = d = round(z) and diff.t = e = z &minus;
   * round(z).  If d = &minus;180, then e &gt; 0; If d = 180, then e &le; 0.
   */
  m.AngDiff = function(x, y) {
    // Compute y - x and reduce to [-180,180] accurately.
    var r = m.sum(m.AngNormalize(-x), m.AngNormalize(y)),
        d = m.AngNormalize(r.s),
        t = r.t;
    return m.sum(d === 180 && t > 0 ? -180 : d, t);
  };

  /**
   * @summary Evaluate the sine and cosine function with the argument in
   *   degrees
   * @param {number} x in degrees.
   * @returns {object} r with r.s = sin(x) and r.c = cos(x).
   */
  m.sincosd = function(x) {
    // In order to minimize round-off errors, this function exactly reduces
    // the argument to the range [-45, 45] before converting it to radians.
    var r, q, s, c, sinx, cosx;
    r = x % 360;
    q = Math.floor(r / 90 + 0.5);
    r -= 90 * q;
    // now abs(r) <= 45
    r *= this.degree;
    // Possibly could call the gnu extension sincos
    s = Math.sin(r); c = Math.cos(r);
    switch (q & 3) {
      case 0:  sinx =  s; cosx =  c; break;
      case 1:  sinx =  c; cosx = -s; break;
      case 2:  sinx = -s; cosx = -c; break;
      default: sinx = -c; cosx =  s; break; // case 3
    }
    if (x) { sinx += 0; cosx += 0; }
    return {s: sinx, c: cosx};
  };

  /**
   * @summary Evaluate the atan2 function with the result in degrees
   * @param {number} y
   * @param {number} x
   * @returns atan2(y, x) in degrees, in the range (&minus;180&deg;
   *   180&deg;].
   */
  m.atan2d = function(y, x) {
    // In order to minimize round-off errors, this function rearranges the
    // arguments so that result of atan2 is in the range [-pi/4, pi/4] before
    // converting it to degrees and mapping the result to the correct
    // quadrant.
    var q = 0, t, ang;
    if (Math.abs(y) > Math.abs(x)) { t = x; x = y; y = t; q = 2; }
    if (x < 0) { x = -x; ++q; }
    // here x >= 0 and x >= abs(y), so angle is in [-pi/4, pi/4]
    ang = Math.atan2(y, x) / this.degree;
    switch (q) {
      // Note that atan2d(-0.0, 1.0) will return -0.  However, we expect that
      // atan2d will not be called with y = -0.  If need be, include
      //
      //   case 0: ang = 0 + ang; break;
      //
      // and handle mpfr as in AngRound.
      case 1: ang = (y >= 0 ? 180 : -180) - ang; break;
      case 2: ang =  90 - ang; break;
      case 3: ang = -90 + ang; break;
    }
    return ang;
  };
})(GeographicLib.Math);

(function(
  /**
   * @exports GeographicLib/Accumulator
   * @description Accurate summation via the
   *   {@link module:GeographicLib/Accumulator.Accumulator Accumulator} class
   *   (mainly for internal use).
   */
  a, m) {

  /**
   * @class
   * @summary Accurate summation of many numbers.
   * @classdesc This allows many numbers to be added together with twice the
   *   normal precision.  In the documentation of the member functions, sum
   *   stands for the value currently held in the accumulator.
   * @param {number | Accumulator} [y = 0]  set sum = y.
   */
  a.Accumulator = function(y) {
    this.Set(y);
  };

  /**
   * @summary Set the accumulator to a number.
   * @param {number | Accumulator} [y = 0] set sum = y.
   */
  a.Accumulator.prototype.Set = function(y) {
    if (!y) y = 0;
    if (y.constructor === a.Accumulator) {
      this._s = y._s;
      this._t = y._t;
    } else {
      this._s = y;
      this._t = 0;
    }
  };

  /**
   * @summary Add a number to the accumulator.
   * @param {number} [y = 0] set sum += y.
   */
  a.Accumulator.prototype.Add = function(y) {
    // Here's Shewchuk's solution...
    // Accumulate starting at least significant end
    var u = m.sum(y, this._t),
        v = m.sum(u.s, this._s);
    u = u.t;
    this._s = v.s;
    this._t = v.t;
    // Start is _s, _t decreasing and non-adjacent.  Sum is now (s + t + u)
    // exactly with s, t, u non-adjacent and in decreasing order (except
    // for possible zeros).  The following code tries to normalize the
    // result.  Ideally, we want _s = round(s+t+u) and _u = round(s+t+u -
    // _s).  The follow does an approximate job (and maintains the
    // decreasing non-adjacent property).  Here are two "failures" using
    // 3-bit floats:
    //
    // Case 1: _s is not equal to round(s+t+u) -- off by 1 ulp
    // [12, -1] - 8 -> [4, 0, -1] -> [4, -1] = 3 should be [3, 0] = 3
    //
    // Case 2: _s+_t is not as close to s+t+u as it shold be
    // [64, 5] + 4 -> [64, 8, 1] -> [64,  8] = 72 (off by 1)
    //                    should be [80, -7] = 73 (exact)
    //
    // "Fixing" these problems is probably not worth the expense.  The
    // representation inevitably leads to small errors in the accumulated
    // values.  The additional errors illustrated here amount to 1 ulp of
    // the less significant word during each addition to the Accumulator
    // and an additional possible error of 1 ulp in the reported sum.
    //
    // Incidentally, the "ideal" representation described above is not
    // canonical, because _s = round(_s + _t) may not be true.  For
    // example, with 3-bit floats:
    //
    // [128, 16] + 1 -> [160, -16] -- 160 = round(145).
    // But [160, 0] - 16 -> [128, 16] -- 128 = round(144).
    //
    if (this._s === 0)          // This implies t == 0,
      this._s = u;              // so result is u
    else
      this._t += u;             // otherwise just accumulate u to t.
  };

  /**
   * @summary Return the result of adding a number to sum (but
   *   don't change sum).
   * @param {number} [y = 0] the number to be added to the sum.
   * @return sum + y.
   */
  a.Accumulator.prototype.Sum = function(y) {
    var b;
    if (!y)
      return this._s;
    else {
      b = new a.Accumulator(this);
      b.Add(y);
      return b._s;
    }
  };

  /**
   * @summary Set sum = &minus;sum.
   */
  a.Accumulator.prototype.Negate = function() {
    this._s *= -1;
    this._t *= -1;
  };
})(GeographicLib.Accumulator, GeographicLib.Math);


/*
 * Geodesic.js
 * Transcription of Geodesic.[ch]pp into JavaScript.
 *
 * See the documentation for the C++ class.  The conversion is a literal
 * conversion from C++.
 *
 * The algorithms are derived in
 *
 *    Charles F. F. Karney,
 *    Algorithms for geodesics, J. Geodesy 87, 43-55 (2013);
 *    https://doi.org/10.1007/s00190-012-0578-z
 *    Addenda: https://geographiclib.sourceforge.io/geod-addenda.html
 *
 * Copyright (c) Charles Karney (2011-2017) <charles@karney.com> and licensed
 * under the MIT/X11 License.  For more information, see
 * https://geographiclib.sourceforge.io/
 */

// Load AFTER Math.js

GeographicLib.Geodesic = {};
GeographicLib.GeodesicLine = {};
GeographicLib.PolygonArea = {};

(function(
  /**
   * @exports GeographicLib/Geodesic
   * @description Solve geodesic problems via the
   *   {@link module:GeographicLib/Geodesic.Geodesic Geodesic} class.
   */
  g, l, p, m, c) {

  var GEOGRAPHICLIB_GEODESIC_ORDER = 6,
      nA1_ = GEOGRAPHICLIB_GEODESIC_ORDER,
      nA2_ = GEOGRAPHICLIB_GEODESIC_ORDER,
      nA3_ = GEOGRAPHICLIB_GEODESIC_ORDER,
      nA3x_ = nA3_,
      nC3x_, nC4x_,
      maxit1_ = 20,
      maxit2_ = maxit1_ + m.digits + 10,
      tol0_ = m.epsilon,
      tol1_ = 200 * tol0_,
      tol2_ = Math.sqrt(tol0_),
      tolb_ = tol0_ * tol1_,
      xthresh_ = 1000 * tol2_,
      CAP_NONE = 0,
      CAP_ALL  = 0x1F,
      CAP_MASK = CAP_ALL,
      OUT_ALL  = 0x7F80,
      astroid,
      A1m1f_coeff, C1f_coeff, C1pf_coeff,
      A2m1f_coeff, C2f_coeff,
      A3_coeff, C3_coeff, C4_coeff;

  g.tiny_ = Math.sqrt(Number.MIN_VALUE);
  g.nC1_ = GEOGRAPHICLIB_GEODESIC_ORDER;
  g.nC1p_ = GEOGRAPHICLIB_GEODESIC_ORDER;
  g.nC2_ = GEOGRAPHICLIB_GEODESIC_ORDER;
  g.nC3_ = GEOGRAPHICLIB_GEODESIC_ORDER;
  g.nC4_ = GEOGRAPHICLIB_GEODESIC_ORDER;
  nC3x_ = (g.nC3_ * (g.nC3_ - 1)) / 2;
  nC4x_ = (g.nC4_ * (g.nC4_ + 1)) / 2;
  g.CAP_C1   = 1<<0;
  g.CAP_C1p  = 1<<1;
  g.CAP_C2   = 1<<2;
  g.CAP_C3   = 1<<3;
  g.CAP_C4   = 1<<4;

  g.NONE          = 0;
  g.ARC           = 1<<6;
  g.LATITUDE      = 1<<7  | CAP_NONE;
  g.LONGITUDE     = 1<<8  | g.CAP_C3;
  g.AZIMUTH       = 1<<9  | CAP_NONE;
  g.DISTANCE      = 1<<10 | g.CAP_C1;
  g.STANDARD      = g.LATITUDE | g.LONGITUDE | g.AZIMUTH | g.DISTANCE;
  g.DISTANCE_IN   = 1<<11 | g.CAP_C1 | g.CAP_C1p;
  g.REDUCEDLENGTH = 1<<12 | g.CAP_C1 | g.CAP_C2;
  g.GEODESICSCALE = 1<<13 | g.CAP_C1 | g.CAP_C2;
  g.AREA          = 1<<14 | g.CAP_C4;
  g.ALL           = OUT_ALL| CAP_ALL;
  g.LONG_UNROLL   = 1<<15;
  g.OUT_MASK      = OUT_ALL| g.LONG_UNROLL;

  g.SinCosSeries = function(sinp, sinx, cosx, c) {
    // Evaluate
    // y = sinp ? sum(c[i] * sin( 2*i    * x), i, 1, n) :
    //            sum(c[i] * cos((2*i+1) * x), i, 0, n-1)
    // using Clenshaw summation.  N.B. c[0] is unused for sin series
    // Approx operation count = (n + 5) mult and (2 * n + 2) add
    var k = c.length,           // Point to one beyond last element
        n = k - (sinp ? 1 : 0),
        ar = 2 * (cosx - sinx) * (cosx + sinx), // 2 * cos(2 * x)
        y0 = n & 1 ? c[--k] : 0, y1 = 0;        // accumulators for sum
    // Now n is even
    n = Math.floor(n/2);
    while (n--) {
      // Unroll loop x 2, so accumulators return to their original role
      y1 = ar * y0 - y1 + c[--k];
      y0 = ar * y1 - y0 + c[--k];
    }
    return (sinp ? 2 * sinx * cosx * y0 : // sin(2 * x) * y0
            cosx * (y0 - y1));            // cos(x) * (y0 - y1)
  };

  astroid = function(x, y) {
    // Solve k^4+2*k^3-(x^2+y^2-1)*k^2-2*y^2*k-y^2 = 0 for positive
    // root k.  This solution is adapted from Geocentric::Reverse.
    var k,
        p = m.sq(x),
        q = m.sq(y),
        r = (p + q - 1) / 6,
        S, r2, r3, disc, u, T3, T, ang, v, uv, w;
    if ( !(q === 0 && r <= 0) ) {
      // Avoid possible division by zero when r = 0 by multiplying
      // equations for s and t by r^3 and r, resp.
      S = p * q / 4;            // S = r^3 * s
      r2 = m.sq(r);
      r3 = r * r2;
      // The discriminant of the quadratic equation for T3.  This is
      // zero on the evolute curve p^(1/3)+q^(1/3) = 1
      disc = S * (S + 2 * r3);
      u = r;
      if (disc >= 0) {
        T3 = S + r3;
        // Pick the sign on the sqrt to maximize abs(T3).  This
        // minimizes loss of precision due to cancellation.  The
        // result is unchanged because of the way the T is used
        // in definition of u.
        T3 += T3 < 0 ? -Math.sqrt(disc) : Math.sqrt(disc);    // T3 = (r * t)^3
        // N.B. cbrt always returns the real root.  cbrt(-8) = -2.
        T = m.cbrt(T3);     // T = r * t
        // T can be zero; but then r2 / T -> 0.
        u += T + (T !== 0 ? r2 / T : 0);
      } else {
        // T is complex, but the way u is defined the result is real.
        ang = Math.atan2(Math.sqrt(-disc), -(S + r3));
        // There are three possible cube roots.  We choose the
        // root which avoids cancellation.  Note that disc < 0
        // implies that r < 0.
        u += 2 * r * Math.cos(ang / 3);
      }
      v = Math.sqrt(m.sq(u) + q);       // guaranteed positive
      // Avoid loss of accuracy when u < 0.
      uv = u < 0 ? q / (v - u) : u + v; // u+v, guaranteed positive
      w = (uv - q) / (2 * v);           // positive?
      // Rearrange expression for k to avoid loss of accuracy due to
      // subtraction.  Division by 0 not possible because uv > 0, w >= 0.
      k = uv / (Math.sqrt(uv + m.sq(w)) + w); // guaranteed positive
    } else {                                  // q == 0 && r <= 0
      // y = 0 with |x| <= 1.  Handle this case directly.
      // for y small, positive root is k = abs(y)/sqrt(1-x^2)
      k = 0;
    }
    return k;
  };

  A1m1f_coeff = [
    // (1-eps)*A1-1, polynomial in eps2 of order 3
      +1, 4, 64, 0, 256
  ];

  // The scale factor A1-1 = mean value of (d/dsigma)I1 - 1
  g.A1m1f = function(eps) {
    var p = Math.floor(nA1_/2),
        t = m.polyval(p, A1m1f_coeff, 0, m.sq(eps)) / A1m1f_coeff[p + 1];
    return (t + eps) / (1 - eps);
  };

  C1f_coeff = [
    // C1[1]/eps^1, polynomial in eps2 of order 2
      -1, 6, -16, 32,
    // C1[2]/eps^2, polynomial in eps2 of order 2
      -9, 64, -128, 2048,
    // C1[3]/eps^3, polynomial in eps2 of order 1
      +9, -16, 768,
    // C1[4]/eps^4, polynomial in eps2 of order 1
      +3, -5, 512,
    // C1[5]/eps^5, polynomial in eps2 of order 0
      -7, 1280,
    // C1[6]/eps^6, polynomial in eps2 of order 0
      -7, 2048
  ];

  // The coefficients C1[l] in the Fourier expansion of B1
  g.C1f = function(eps, c) {
    var eps2 = m.sq(eps),
        d = eps,
        o = 0,
        l, p;
    for (l = 1; l <= g.nC1_; ++l) {     // l is index of C1p[l]
      p = Math.floor((g.nC1_ - l) / 2); // order of polynomial in eps^2
      c[l] = d * m.polyval(p, C1f_coeff, o, eps2) / C1f_coeff[o + p + 1];
      o += p + 2;
      d *= eps;
    }
  };

  C1pf_coeff = [
    // C1p[1]/eps^1, polynomial in eps2 of order 2
      +205, -432, 768, 1536,
    // C1p[2]/eps^2, polynomial in eps2 of order 2
      +4005, -4736, 3840, 12288,
    // C1p[3]/eps^3, polynomial in eps2 of order 1
      -225, 116, 384,
    // C1p[4]/eps^4, polynomial in eps2 of order 1
      -7173, 2695, 7680,
    // C1p[5]/eps^5, polynomial in eps2 of order 0
      +3467, 7680,
    // C1p[6]/eps^6, polynomial in eps2 of order 0
      +38081, 61440
  ];

  // The coefficients C1p[l] in the Fourier expansion of B1p
  g.C1pf = function(eps, c) {
    var eps2 = m.sq(eps),
        d = eps,
        o = 0,
        l, p;
    for (l = 1; l <= g.nC1p_; ++l) {     // l is index of C1p[l]
      p = Math.floor((g.nC1p_ - l) / 2); // order of polynomial in eps^2
      c[l] = d * m.polyval(p, C1pf_coeff, o, eps2) / C1pf_coeff[o + p + 1];
      o += p + 2;
      d *= eps;
    }
  };

  A2m1f_coeff = [
    // (eps+1)*A2-1, polynomial in eps2 of order 3
      -11, -28, -192, 0, 256
  ];

  // The scale factor A2-1 = mean value of (d/dsigma)I2 - 1
  g.A2m1f = function(eps) {
    var p = Math.floor(nA2_/2),
        t = m.polyval(p, A2m1f_coeff, 0, m.sq(eps)) / A2m1f_coeff[p + 1];
    return (t - eps) / (1 + eps);
  };

  C2f_coeff = [
    // C2[1]/eps^1, polynomial in eps2 of order 2
      +1, 2, 16, 32,
    // C2[2]/eps^2, polynomial in eps2 of order 2
      +35, 64, 384, 2048,
    // C2[3]/eps^3, polynomial in eps2 of order 1
      +15, 80, 768,
    // C2[4]/eps^4, polynomial in eps2 of order 1
      +7, 35, 512,
    // C2[5]/eps^5, polynomial in eps2 of order 0
      +63, 1280,
    // C2[6]/eps^6, polynomial in eps2 of order 0
      +77, 2048
  ];

  // The coefficients C2[l] in the Fourier expansion of B2
  g.C2f = function(eps, c) {
    var eps2 = m.sq(eps),
        d = eps,
        o = 0,
        l, p;
    for (l = 1; l <= g.nC2_; ++l) {     // l is index of C2[l]
      p = Math.floor((g.nC2_ - l) / 2); // order of polynomial in eps^2
      c[l] = d * m.polyval(p, C2f_coeff, o, eps2) / C2f_coeff[o + p + 1];
      o += p + 2;
      d *= eps;
    }
  };

  /**
   * @class
   * @property {number} a the equatorial radius (meters).
   * @property {number} f the flattening.
   * @summary Initialize a Geodesic object for a specific ellipsoid.
   * @classdesc Performs geodesic calculations on an ellipsoid of revolution.
   *   The routines for solving the direct and inverse problems return an
   *   object with some of the following fields set: lat1, lon1, azi1, lat2,
   *   lon2, azi2, s12, a12, m12, M12, M21, S12.  See {@tutorial 2-interface},
   *   "The results".
   * @example
   * var GeographicLib = require("geographiclib"),
   *     geod = GeographicLib.Geodesic.WGS84;
   * var inv = geod.Inverse(1,2,3,4);
   * console.log("lat1 = " + inv.lat1 + ", lon1 = " + inv.lon1 +
   *             ", lat2 = " + inv.lat2 + ", lon2 = " + inv.lon2 +
   *             ",\nazi1 = " + inv.azi1 + ", azi2 = " + inv.azi2 +
   *             ", s12 = " + inv.s12);
   * @param {number} a the equatorial radius of the ellipsoid (meters).
   * @param {number} f the flattening of the ellipsoid.  Setting f = 0 gives
   *   a sphere (on which geodesics are great circles).  Negative f gives a
   *   prolate ellipsoid.
   * @throws an error if the parameters are illegal.
   */
  g.Geodesic = function(a, f) {
    this.a = a;
    this.f = f;
    this._f1 = 1 - this.f;
    this._e2 = this.f * (2 - this.f);
    this._ep2 = this._e2 / m.sq(this._f1); // e2 / (1 - e2)
    this._n = this.f / ( 2 - this.f);
    this._b = this.a * this._f1;
    // authalic radius squared
    this._c2 = (m.sq(this.a) + m.sq(this._b) *
                (this._e2 === 0 ? 1 :
                 (this._e2 > 0 ? m.atanh(Math.sqrt(this._e2)) :
                  Math.atan(Math.sqrt(-this._e2))) /
                 Math.sqrt(Math.abs(this._e2))))/2;
    // The sig12 threshold for "really short".  Using the auxiliary sphere
    // solution with dnm computed at (bet1 + bet2) / 2, the relative error in
    // the azimuth consistency check is sig12^2 * abs(f) * min(1, 1-f/2) / 2.
    // (Error measured for 1/100 < b/a < 100 and abs(f) >= 1/1000.  For a given
    // f and sig12, the max error occurs for lines near the pole.  If the old
    // rule for computing dnm = (dn1 + dn2)/2 is used, then the error increases
    // by a factor of 2.)  Setting this equal to epsilon gives sig12 = etol2.
    // Here 0.1 is a safety factor (error decreased by 100) and max(0.001,
    // abs(f)) stops etol2 getting too large in the nearly spherical case.
    this._etol2 = 0.1 * tol2_ /
      Math.sqrt( Math.max(0.001, Math.abs(this.f)) *
                 Math.min(1.0, 1 - this.f/2) / 2 );
    if (!(isFinite(this.a) && this.a > 0))
      throw new Error("Equatorial radius is not positive");
    if (!(isFinite(this._b) && this._b > 0))
      throw new Error("Polar semi-axis is not positive");
    this._A3x = new Array(nA3x_);
    this._C3x = new Array(nC3x_);
    this._C4x = new Array(nC4x_);
    this.A3coeff();
    this.C3coeff();
    this.C4coeff();
  };

  A3_coeff = [
    // A3, coeff of eps^5, polynomial in n of order 0
      -3, 128,
    // A3, coeff of eps^4, polynomial in n of order 1
      -2, -3, 64,
    // A3, coeff of eps^3, polynomial in n of order 2
      -1, -3, -1, 16,
    // A3, coeff of eps^2, polynomial in n of order 2
      +3, -1, -2, 8,
    // A3, coeff of eps^1, polynomial in n of order 1
      +1, -1, 2,
    // A3, coeff of eps^0, polynomial in n of order 0
      +1, 1
  ];

  // The scale factor A3 = mean value of (d/dsigma)I3
  g.Geodesic.prototype.A3coeff = function() {
    var o = 0, k = 0,
        j, p;
    for (j = nA3_ - 1; j >= 0; --j) { // coeff of eps^j
      p = Math.min(nA3_ - j - 1, j);  // order of polynomial in n
      this._A3x[k++] = m.polyval(p, A3_coeff, o, this._n) /
        A3_coeff[o + p + 1];
      o += p + 2;
    }
  };

  C3_coeff = [
    // C3[1], coeff of eps^5, polynomial in n of order 0
      +3, 128,
    // C3[1], coeff of eps^4, polynomial in n of order 1
      +2, 5, 128,
    // C3[1], coeff of eps^3, polynomial in n of order 2
      -1, 3, 3, 64,
    // C3[1], coeff of eps^2, polynomial in n of order 2
      -1, 0, 1, 8,
    // C3[1], coeff of eps^1, polynomial in n of order 1
      -1, 1, 4,
    // C3[2], coeff of eps^5, polynomial in n of order 0
      +5, 256,
    // C3[2], coeff of eps^4, polynomial in n of order 1
      +1, 3, 128,
    // C3[2], coeff of eps^3, polynomial in n of order 2
      -3, -2, 3, 64,
    // C3[2], coeff of eps^2, polynomial in n of order 2
      +1, -3, 2, 32,
    // C3[3], coeff of eps^5, polynomial in n of order 0
      +7, 512,
    // C3[3], coeff of eps^4, polynomial in n of order 1
      -10, 9, 384,
    // C3[3], coeff of eps^3, polynomial in n of order 2
      +5, -9, 5, 192,
    // C3[4], coeff of eps^5, polynomial in n of order 0
      +7, 512,
    // C3[4], coeff of eps^4, polynomial in n of order 1
      -14, 7, 512,
    // C3[5], coeff of eps^5, polynomial in n of order 0
      +21, 2560
  ];

  // The coefficients C3[l] in the Fourier expansion of B3
  g.Geodesic.prototype.C3coeff = function() {
    var o = 0, k = 0,
        l, j, p;
    for (l = 1; l < g.nC3_; ++l) {        // l is index of C3[l]
      for (j = g.nC3_ - 1; j >= l; --j) { // coeff of eps^j
        p = Math.min(g.nC3_ - j - 1, j);  // order of polynomial in n
        this._C3x[k++] = m.polyval(p, C3_coeff, o, this._n) /
          C3_coeff[o + p + 1];
        o += p + 2;
      }
    }
  };

  C4_coeff = [
    // C4[0], coeff of eps^5, polynomial in n of order 0
      +97, 15015,
    // C4[0], coeff of eps^4, polynomial in n of order 1
      +1088, 156, 45045,
    // C4[0], coeff of eps^3, polynomial in n of order 2
      -224, -4784, 1573, 45045,
    // C4[0], coeff of eps^2, polynomial in n of order 3
      -10656, 14144, -4576, -858, 45045,
    // C4[0], coeff of eps^1, polynomial in n of order 4
      +64, 624, -4576, 6864, -3003, 15015,
    // C4[0], coeff of eps^0, polynomial in n of order 5
      +100, 208, 572, 3432, -12012, 30030, 45045,
    // C4[1], coeff of eps^5, polynomial in n of order 0
      +1, 9009,
    // C4[1], coeff of eps^4, polynomial in n of order 1
      -2944, 468, 135135,
    // C4[1], coeff of eps^3, polynomial in n of order 2
      +5792, 1040, -1287, 135135,
    // C4[1], coeff of eps^2, polynomial in n of order 3
      +5952, -11648, 9152, -2574, 135135,
    // C4[1], coeff of eps^1, polynomial in n of order 4
      -64, -624, 4576, -6864, 3003, 135135,
    // C4[2], coeff of eps^5, polynomial in n of order 0
      +8, 10725,
    // C4[2], coeff of eps^4, polynomial in n of order 1
      +1856, -936, 225225,
    // C4[2], coeff of eps^3, polynomial in n of order 2
      -8448, 4992, -1144, 225225,
    // C4[2], coeff of eps^2, polynomial in n of order 3
      -1440, 4160, -4576, 1716, 225225,
    // C4[3], coeff of eps^5, polynomial in n of order 0
      -136, 63063,
    // C4[3], coeff of eps^4, polynomial in n of order 1
      +1024, -208, 105105,
    // C4[3], coeff of eps^3, polynomial in n of order 2
      +3584, -3328, 1144, 315315,
    // C4[4], coeff of eps^5, polynomial in n of order 0
      -128, 135135,
    // C4[4], coeff of eps^4, polynomial in n of order 1
      -2560, 832, 405405,
    // C4[5], coeff of eps^5, polynomial in n of order 0
      +128, 99099
  ];

  g.Geodesic.prototype.C4coeff = function() {
    var o = 0, k = 0,
        l, j, p;
    for (l = 0; l < g.nC4_; ++l) {        // l is index of C4[l]
      for (j = g.nC4_ - 1; j >= l; --j) { // coeff of eps^j
        p = g.nC4_ - j - 1;               // order of polynomial in n
        this._C4x[k++] = m.polyval(p, C4_coeff, o, this._n) /
          C4_coeff[o + p + 1];
        o += p + 2;
      }
    }
  };

  g.Geodesic.prototype.A3f = function(eps) {
    // Evaluate A3
    return m.polyval(nA3x_ - 1, this._A3x, 0, eps);
  };

  g.Geodesic.prototype.C3f = function(eps, c) {
    // Evaluate C3 coeffs
    // Elements c[1] thru c[nC3_ - 1] are set
    var mult = 1,
        o = 0,
        l, p;
    for (l = 1; l < g.nC3_; ++l) { // l is index of C3[l]
      p = g.nC3_ - l - 1;          // order of polynomial in eps
      mult *= eps;
      c[l] = mult * m.polyval(p, this._C3x, o, eps);
      o += p + 1;
    }
  };

  g.Geodesic.prototype.C4f = function(eps, c) {
    // Evaluate C4 coeffs
    // Elements c[0] thru c[g.nC4_ - 1] are set
    var mult = 1,
        o = 0,
        l, p;
    for (l = 0; l < g.nC4_; ++l) { // l is index of C4[l]
      p = g.nC4_ - l - 1;          // order of polynomial in eps
      c[l] = mult * m.polyval(p, this._C4x, o, eps);
      o += p + 1;
      mult *= eps;
    }
  };

  // return s12b, m12b, m0, M12, M21
  g.Geodesic.prototype.Lengths = function(eps, sig12,
                                          ssig1, csig1, dn1, ssig2, csig2, dn2,
                                          cbet1, cbet2, outmask,
                                          C1a, C2a) {
    // Return m12b = (reduced length)/_b; also calculate s12b =
    // distance/_b, and m0 = coefficient of secular term in
    // expression for reduced length.
    outmask &= g.OUT_MASK;
    var vals = {},
        m0x = 0, J12 = 0, A1 = 0, A2 = 0,
        B1, B2, l, csig12, t;
    if (outmask & (g.DISTANCE | g.REDUCEDLENGTH | g.GEODESICSCALE)) {
      A1 = g.A1m1f(eps);
      g.C1f(eps, C1a);
      if (outmask & (g.REDUCEDLENGTH | g.GEODESICSCALE)) {
        A2 = g.A2m1f(eps);
        g.C2f(eps, C2a);
        m0x = A1 - A2;
        A2 = 1 + A2;
      }
      A1 = 1 + A1;
    }
    if (outmask & g.DISTANCE) {
      B1 = g.SinCosSeries(true, ssig2, csig2, C1a) -
        g.SinCosSeries(true, ssig1, csig1, C1a);
      // Missing a factor of _b
      vals.s12b = A1 * (sig12 + B1);
      if (outmask & (g.REDUCEDLENGTH | g.GEODESICSCALE)) {
        B2 = g.SinCosSeries(true, ssig2, csig2, C2a) -
          g.SinCosSeries(true, ssig1, csig1, C2a);
        J12 = m0x * sig12 + (A1 * B1 - A2 * B2);
      }
    } else if (outmask & (g.REDUCEDLENGTH | g.GEODESICSCALE)) {
      // Assume here that nC1_ >= nC2_
      for (l = 1; l <= g.nC2_; ++l)
        C2a[l] = A1 * C1a[l] - A2 * C2a[l];
      J12 = m0x * sig12 + (g.SinCosSeries(true, ssig2, csig2, C2a) -
                           g.SinCosSeries(true, ssig1, csig1, C2a));
    }
    if (outmask & g.REDUCEDLENGTH) {
      vals.m0 = m0x;
      // Missing a factor of _b.
      // Add parens around (csig1 * ssig2) and (ssig1 * csig2) to ensure
      // accurate cancellation in the case of coincident points.
      vals.m12b = dn2 * (csig1 * ssig2) - dn1 * (ssig1 * csig2) -
        csig1 * csig2 * J12;
    }
    if (outmask & g.GEODESICSCALE) {
      csig12 = csig1 * csig2 + ssig1 * ssig2;
      t = this._ep2 * (cbet1 - cbet2) * (cbet1 + cbet2) / (dn1 + dn2);
      vals.M12 = csig12 + (t * ssig2 - csig2 * J12) * ssig1 / dn1;
      vals.M21 = csig12 - (t * ssig1 - csig1 * J12) * ssig2 / dn2;
    }
    return vals;
  };

  // return sig12, salp1, calp1, salp2, calp2, dnm
  g.Geodesic.prototype.InverseStart = function(sbet1, cbet1, dn1,
                                               sbet2, cbet2, dn2,
                                               lam12, slam12, clam12,
                                               C1a, C2a) {
    // Return a starting point for Newton's method in salp1 and calp1
    // (function value is -1).  If Newton's method doesn't need to be
    // used, return also salp2 and calp2 and function value is sig12.
    // salp2, calp2 only updated if return val >= 0.
    var vals = {},
        // bet12 = bet2 - bet1 in [0, pi); bet12a = bet2 + bet1 in (-pi, 0]
        sbet12 = sbet2 * cbet1 - cbet2 * sbet1,
        cbet12 = cbet2 * cbet1 + sbet2 * sbet1,
        sbet12a, shortline, omg12, sbetm2, somg12, comg12, t, ssig12, csig12,
        x, y, lamscale, betscale, k2, eps, cbet12a, bet12a, m12b, m0, nvals,
        k, omg12a, lam12x;
    vals.sig12 = -1;        // Return value
    // Volatile declaration needed to fix inverse cases
    // 88.202499451857 0 -88.202499451857 179.981022032992859592
    // 89.262080389218 0 -89.262080389218 179.992207982775375662
    // 89.333123580033 0 -89.333123580032997687 179.99295812360148422
    // which otherwise fail with g++ 4.4.4 x86 -O3
    sbet12a = sbet2 * cbet1;
    sbet12a += cbet2 * sbet1;

    shortline = cbet12 >= 0 && sbet12 < 0.5 && cbet2 * lam12 < 0.5;
    if (shortline) {
      sbetm2 = m.sq(sbet1 + sbet2);
      // sin((bet1+bet2)/2)^2
      // =  (sbet1 + sbet2)^2 / ((sbet1 + sbet2)^2 + (cbet1 + cbet2)^2)
      sbetm2 /= sbetm2 + m.sq(cbet1 + cbet2);
      vals.dnm = Math.sqrt(1 + this._ep2 * sbetm2);
      omg12 = lam12 / (this._f1 * vals.dnm);
      somg12 = Math.sin(omg12); comg12 = Math.cos(omg12);
    } else {
      somg12 = slam12; comg12 = clam12;
    }

    vals.salp1 = cbet2 * somg12;
    vals.calp1 = comg12 >= 0 ?
      sbet12 + cbet2 * sbet1 * m.sq(somg12) / (1 + comg12) :
      sbet12a - cbet2 * sbet1 * m.sq(somg12) / (1 - comg12);

    ssig12 = m.hypot(vals.salp1, vals.calp1);
    csig12 = sbet1 * sbet2 + cbet1 * cbet2 * comg12;
    if (shortline && ssig12 < this._etol2) {
      // really short lines
      vals.salp2 = cbet1 * somg12;
      vals.calp2 = sbet12 - cbet1 * sbet2 *
        (comg12 >= 0 ? m.sq(somg12) / (1 + comg12) : 1 - comg12);
      // norm(vals.salp2, vals.calp2);
      t = m.hypot(vals.salp2, vals.calp2); vals.salp2 /= t; vals.calp2 /= t;
      // Set return value
      vals.sig12 = Math.atan2(ssig12, csig12);
    } else if (Math.abs(this._n) > 0.1 || // Skip astroid calc if too eccentric
               csig12 >= 0 ||
               ssig12 >= 6 * Math.abs(this._n) * Math.PI * m.sq(cbet1)) {
      // Nothing to do, zeroth order spherical approximation is OK
    } else {
      // Scale lam12 and bet2 to x, y coordinate system where antipodal
      // point is at origin and singular point is at y = 0, x = -1.
      lam12x = Math.atan2(-slam12, -clam12); // lam12 - pi
      if (this.f >= 0) {       // In fact f == 0 does not get here
        // x = dlong, y = dlat
        k2 = m.sq(sbet1) * this._ep2;
        eps = k2 / (2 * (1 + Math.sqrt(1 + k2)) + k2);
        lamscale = this.f * cbet1 * this.A3f(eps) * Math.PI;
        betscale = lamscale * cbet1;

        x = lam12x / lamscale;
        y = sbet12a / betscale;
      } else {                  // f < 0
        // x = dlat, y = dlong
        cbet12a = cbet2 * cbet1 - sbet2 * sbet1;
        bet12a = Math.atan2(sbet12a, cbet12a);
        // In the case of lon12 = 180, this repeats a calculation made
        // in Inverse.
        nvals = this.Lengths(this._n, Math.PI + bet12a,
                             sbet1, -cbet1, dn1, sbet2, cbet2, dn2,
                             cbet1, cbet2, g.REDUCEDLENGTH, C1a, C2a);
        m12b = nvals.m12b; m0 = nvals.m0;
        x = -1 + m12b / (cbet1 * cbet2 * m0 * Math.PI);
        betscale = x < -0.01 ? sbet12a / x :
          -this.f * m.sq(cbet1) * Math.PI;
        lamscale = betscale / cbet1;
        y = lam12 / lamscale;
      }

      if (y > -tol1_ && x > -1 - xthresh_) {
        // strip near cut
        if (this.f >= 0) {
          vals.salp1 = Math.min(1, -x);
          vals.calp1 = -Math.sqrt(1 - m.sq(vals.salp1));
        } else {
          vals.calp1 = Math.max(x > -tol1_ ? 0 : -1, x);
          vals.salp1 = Math.sqrt(1 - m.sq(vals.calp1));
        }
      } else {
        // Estimate alp1, by solving the astroid problem.
        //
        // Could estimate alpha1 = theta + pi/2, directly, i.e.,
        //   calp1 = y/k; salp1 = -x/(1+k);  for f >= 0
        //   calp1 = x/(1+k); salp1 = -y/k;  for f < 0 (need to check)
        //
        // However, it's better to estimate omg12 from astroid and use
        // spherical formula to compute alp1.  This reduces the mean number of
        // Newton iterations for astroid cases from 2.24 (min 0, max 6) to 2.12
        // (min 0 max 5).  The changes in the number of iterations are as
        // follows:
        //
        // change percent
        //    1       5
        //    0      78
        //   -1      16
        //   -2       0.6
        //   -3       0.04
        //   -4       0.002
        //
        // The histogram of iterations is (m = number of iterations estimating
        // alp1 directly, n = number of iterations estimating via omg12, total
        // number of trials = 148605):
        //
        //  iter    m      n
        //    0   148    186
        //    1 13046  13845
        //    2 93315 102225
        //    3 36189  32341
        //    4  5396      7
        //    5   455      1
        //    6    56      0
        //
        // Because omg12 is near pi, estimate work with omg12a = pi - omg12
        k = astroid(x, y);
        omg12a = lamscale * ( this.f >= 0 ? -x * k/(1 + k) : -y * (1 + k)/k );
        somg12 = Math.sin(omg12a); comg12 = -Math.cos(omg12a);
        // Update spherical estimate of alp1 using omg12 instead of
        // lam12
        vals.salp1 = cbet2 * somg12;
        vals.calp1 = sbet12a -
          cbet2 * sbet1 * m.sq(somg12) / (1 - comg12);
      }
    }
    // Sanity check on starting guess.  Backwards check allows NaN through.
    if (!(vals.salp1 <= 0.0)) {
      // norm(vals.salp1, vals.calp1);
      t = m.hypot(vals.salp1, vals.calp1); vals.salp1 /= t; vals.calp1 /= t;
    } else {
      vals.salp1 = 1; vals.calp1 = 0;
    }
    return vals;
  };

  // return lam12, salp2, calp2, sig12, ssig1, csig1, ssig2, csig2, eps,
  // domg12, dlam12,
  g.Geodesic.prototype.Lambda12 = function(sbet1, cbet1, dn1, sbet2, cbet2, dn2,
                                           salp1, calp1, slam120, clam120,
                                           diffp, C1a, C2a, C3a) {
    var vals = {},
        t, salp0, calp0,
        somg1, comg1, somg2, comg2, somg12, comg12, B312, eta, k2, nvals;
    if (sbet1 === 0 && calp1 === 0)
      // Break degeneracy of equatorial line.  This case has already been
      // handled.
      calp1 = -g.tiny_;

    // sin(alp1) * cos(bet1) = sin(alp0)
    salp0 = salp1 * cbet1;
    calp0 = m.hypot(calp1, salp1 * sbet1); // calp0 > 0

    // tan(bet1) = tan(sig1) * cos(alp1)
    // tan(omg1) = sin(alp0) * tan(sig1) = tan(omg1)=tan(alp1)*sin(bet1)
    vals.ssig1 = sbet1; somg1 = salp0 * sbet1;
    vals.csig1 = comg1 = calp1 * cbet1;
    // norm(vals.ssig1, vals.csig1);
    t = m.hypot(vals.ssig1, vals.csig1); vals.ssig1 /= t; vals.csig1 /= t;
    // norm(somg1, comg1); -- don't need to normalize!

    // Enforce symmetries in the case abs(bet2) = -bet1.  Need to be careful
    // about this case, since this can yield singularities in the Newton
    // iteration.
    // sin(alp2) * cos(bet2) = sin(alp0)
    vals.salp2 = cbet2 !== cbet1 ? salp0 / cbet2 : salp1;
    // calp2 = sqrt(1 - sq(salp2))
    //       = sqrt(sq(calp0) - sq(sbet2)) / cbet2
    // and subst for calp0 and rearrange to give (choose positive sqrt
    // to give alp2 in [0, pi/2]).
    vals.calp2 = cbet2 !== cbet1 || Math.abs(sbet2) !== -sbet1 ?
      Math.sqrt(m.sq(calp1 * cbet1) + (cbet1 < -sbet1 ?
                                       (cbet2 - cbet1) * (cbet1 + cbet2) :
                                       (sbet1 - sbet2) * (sbet1 + sbet2))) /
      cbet2 : Math.abs(calp1);
    // tan(bet2) = tan(sig2) * cos(alp2)
    // tan(omg2) = sin(alp0) * tan(sig2).
    vals.ssig2 = sbet2; somg2 = salp0 * sbet2;
    vals.csig2 = comg2 = vals.calp2 * cbet2;
    // norm(vals.ssig2, vals.csig2);
    t = m.hypot(vals.ssig2, vals.csig2); vals.ssig2 /= t; vals.csig2 /= t;
    // norm(somg2, comg2); -- don't need to normalize!

    // sig12 = sig2 - sig1, limit to [0, pi]
    vals.sig12 = Math.atan2(Math.max(0, vals.csig1 * vals.ssig2 -
                                        vals.ssig1 * vals.csig2),
                                        vals.csig1 * vals.csig2 +
                                        vals.ssig1 * vals.ssig2);

    // omg12 = omg2 - omg1, limit to [0, pi]
    somg12 = Math.max(0, comg1 * somg2 - somg1 * comg2);
    comg12 =             comg1 * comg2 + somg1 * somg2;
    // eta = omg12 - lam120
    eta = Math.atan2(somg12 * clam120 - comg12 * slam120,
                     comg12 * clam120 + somg12 * slam120);
    k2 = m.sq(calp0) * this._ep2;
    vals.eps = k2 / (2 * (1 + Math.sqrt(1 + k2)) + k2);
    this.C3f(vals.eps, C3a);
    B312 = (g.SinCosSeries(true, vals.ssig2, vals.csig2, C3a) -
            g.SinCosSeries(true, vals.ssig1, vals.csig1, C3a));
    vals.domg12 =  -this.f * this.A3f(vals.eps) * salp0 * (vals.sig12 + B312);
    vals.lam12 = eta + vals.domg12;
    if (diffp) {
      if (vals.calp2 === 0)
        vals.dlam12 = -2 * this._f1 * dn1 / sbet1;
      else {
        nvals = this.Lengths(vals.eps, vals.sig12,
                             vals.ssig1, vals.csig1, dn1,
                             vals.ssig2, vals.csig2, dn2,
                             cbet1, cbet2, g.REDUCEDLENGTH, C1a, C2a);
        vals.dlam12 = nvals.m12b;
        vals.dlam12 *= this._f1 / (vals.calp2 * cbet2);
      }
    }
    return vals;
  };

  /**
   * @summary Solve the inverse geodesic problem.
   * @param {number} lat1 the latitude of the first point in degrees.
   * @param {number} lon1 the longitude of the first point in degrees.
   * @param {number} lat2 the latitude of the second point in degrees.
   * @param {number} lon2 the longitude of the second point in degrees.
   * @param {bitmask} [outmask = STANDARD] which results to include.
   * @returns {object} the requested results
   * @description The lat1, lon1, lat2, lon2, and a12 fields of the result are
   *   always set.  For details on the outmask parameter, see {@tutorial
   *   2-interface}, "The outmask and caps parameters".
   */
  g.Geodesic.prototype.Inverse = function(lat1, lon1, lat2, lon2, outmask) {
    var r, vals;
    if (!outmask) outmask = g.STANDARD;
    if (outmask === g.LONG_UNROLL) outmask |= g.STANDARD;
    outmask &= g.OUT_MASK;
    r = this.InverseInt(lat1, lon1, lat2, lon2, outmask);
    vals = r.vals;
    if (outmask & g.AZIMUTH) {
      vals.azi1 = m.atan2d(r.salp1, r.calp1);
      vals.azi2 = m.atan2d(r.salp2, r.calp2);
    }
    return vals;
  };

  g.Geodesic.prototype.InverseInt = function(lat1, lon1, lat2, lon2, outmask) {
    var vals = {},
        lon12, lon12s, lonsign, t, swapp, latsign,
        sbet1, cbet1, sbet2, cbet2, s12x, m12x,
        dn1, dn2, lam12, slam12, clam12,
        sig12, calp1, salp1, calp2, salp2, C1a, C2a, C3a, meridian, nvals,
        ssig1, csig1, ssig2, csig2, eps, omg12, dnm,
        numit, salp1a, calp1a, salp1b, calp1b,
        tripn, tripb, v, dv, dalp1, sdalp1, cdalp1, nsalp1,
        lengthmask, salp0, calp0, alp12, k2, A4, C4a, B41, B42,
        somg12, comg12, domg12, dbet1, dbet2, salp12, calp12, sdomg12, cdomg12;
    // Compute longitude difference (AngDiff does this carefully).  Result is
    // in [-180, 180] but -180 is only for west-going geodesics.  180 is for
    // east-going and meridional geodesics.
    vals.lat1 = lat1 = m.LatFix(lat1); vals.lat2 = lat2 = m.LatFix(lat2);
    // If really close to the equator, treat as on equator.
    lat1 = m.AngRound(lat1);
    lat2 = m.AngRound(lat2);
    lon12 = m.AngDiff(lon1, lon2); lon12s = lon12.t; lon12 = lon12.s;
    if (outmask & g.LONG_UNROLL) {
      vals.lon1 = lon1; vals.lon2 = (lon1 + lon12) + lon12s;
    } else {
      vals.lon1 = m.AngNormalize(lon1); vals.lon2 = m.AngNormalize(lon2);
    }
    // Make longitude difference positive.
    lonsign = lon12 >= 0 ? 1 : -1;
    // If very close to being on the same half-meridian, then make it so.
    lon12 = lonsign * m.AngRound(lon12);
    lon12s = m.AngRound((180 - lon12) - lonsign * lon12s);
    lam12 = lon12 * m.degree;
    t = m.sincosd(lon12 > 90 ? lon12s : lon12);
    slam12 = t.s; clam12 = (lon12 > 90 ? -1 : 1) * t.c;

    // Swap points so that point with higher (abs) latitude is point 1
    // If one latitude is a nan, then it becomes lat1.
    swapp = Math.abs(lat1) < Math.abs(lat2) ? -1 : 1;
    if (swapp < 0) {
      lonsign *= -1;
      t = lat1;
      lat1 = lat2;
      lat2 = t;
      // swap(lat1, lat2);
    }
    // Make lat1 <= 0
    latsign = lat1 < 0 ? 1 : -1;
    lat1 *= latsign;
    lat2 *= latsign;
    // Now we have
    //
    //     0 <= lon12 <= 180
    //     -90 <= lat1 <= 0
    //     lat1 <= lat2 <= -lat1
    //
    // longsign, swapp, latsign register the transformation to bring the
    // coordinates to this canonical form.  In all cases, 1 means no change was
    // made.  We make these transformations so that there are few cases to
    // check, e.g., on verifying quadrants in atan2.  In addition, this
    // enforces some symmetries in the results returned.

    t = m.sincosd(lat1); sbet1 = this._f1 * t.s; cbet1 = t.c;
    // norm(sbet1, cbet1);
    t = m.hypot(sbet1, cbet1); sbet1 /= t; cbet1 /= t;
    // Ensure cbet1 = +epsilon at poles
    cbet1 = Math.max(g.tiny_, cbet1);

    t = m.sincosd(lat2); sbet2 = this._f1 * t.s; cbet2 = t.c;
    // norm(sbet2, cbet2);
    t = m.hypot(sbet2, cbet2); sbet2 /= t; cbet2 /= t;
    // Ensure cbet2 = +epsilon at poles
    cbet2 = Math.max(g.tiny_, cbet2);

    // If cbet1 < -sbet1, then cbet2 - cbet1 is a sensitive measure of the
    // |bet1| - |bet2|.  Alternatively (cbet1 >= -sbet1), abs(sbet2) + sbet1 is
    // a better measure.  This logic is used in assigning calp2 in Lambda12.
    // Sometimes these quantities vanish and in that case we force bet2 = +/-
    // bet1 exactly.  An example where is is necessary is the inverse problem
    // 48.522876735459 0 -48.52287673545898293 179.599720456223079643
    // which failed with Visual Studio 10 (Release and Debug)

    if (cbet1 < -sbet1) {
      if (cbet2 === cbet1)
        sbet2 = sbet2 < 0 ? sbet1 : -sbet1;
    } else {
      if (Math.abs(sbet2) === -sbet1)
        cbet2 = cbet1;
    }

    dn1 = Math.sqrt(1 + this._ep2 * m.sq(sbet1));
    dn2 = Math.sqrt(1 + this._ep2 * m.sq(sbet2));

    // index zero elements of these arrays are unused
    C1a = new Array(g.nC1_ + 1);
    C2a = new Array(g.nC2_ + 1);
    C3a = new Array(g.nC3_);

    meridian = lat1 === -90 || slam12 === 0;
    if (meridian) {

      // Endpoints are on a single full meridian, so the geodesic might
      // lie on a meridian.

      calp1 = clam12; salp1 = slam12; // Head to the target longitude
      calp2 = 1; salp2 = 0;           // At the target we're heading north

      // tan(bet) = tan(sig) * cos(alp)
      ssig1 = sbet1; csig1 = calp1 * cbet1;
      ssig2 = sbet2; csig2 = calp2 * cbet2;

      // sig12 = sig2 - sig1
      sig12 = Math.atan2(Math.max(0, csig1 * ssig2 - ssig1 * csig2),
                                     csig1 * csig2 + ssig1 * ssig2);
      nvals = this.Lengths(this._n, sig12,
                           ssig1, csig1, dn1, ssig2, csig2, dn2, cbet1, cbet2,
                           outmask | g.DISTANCE | g.REDUCEDLENGTH,
                           C1a, C2a);
      s12x = nvals.s12b;
      m12x = nvals.m12b;
      // Ignore m0
      if ((outmask & g.GEODESICSCALE) !== 0) {
        vals.M12 = nvals.M12;
        vals.M21 = nvals.M21;
      }
      // Add the check for sig12 since zero length geodesics might yield
      // m12 < 0.  Test case was
      //
      //    echo 20.001 0 20.001 0 | GeodSolve -i
      //
      // In fact, we will have sig12 > pi/2 for meridional geodesic
      // which is not a shortest path.
      if (sig12 < 1 || m12x >= 0) {
        // Need at least 2, to handle 90 0 90 180
        if (sig12 < 3 * g.tiny_)
          sig12 = m12x = s12x = 0;
        m12x *= this._b;
        s12x *= this._b;
        vals.a12 = sig12 / m.degree;
      } else
        // m12 < 0, i.e., prolate and too close to anti-podal
        meridian = false;
    }

    somg12 = 2;
    if (!meridian &&
        sbet1 === 0 &&           // and sbet2 == 0
        (this.f <= 0 || lon12s >= this.f * 180)) {

      // Geodesic runs along equator
      calp1 = calp2 = 0; salp1 = salp2 = 1;
      s12x = this.a * lam12;
      sig12 = omg12 = lam12 / this._f1;
      m12x = this._b * Math.sin(sig12);
      if (outmask & g.GEODESICSCALE)
        vals.M12 = vals.M21 = Math.cos(sig12);
      vals.a12 = lon12 / this._f1;

    } else if (!meridian) {

      // Now point1 and point2 belong within a hemisphere bounded by a
      // meridian and geodesic is neither meridional or equatorial.

      // Figure a starting point for Newton's method
      nvals = this.InverseStart(sbet1, cbet1, dn1, sbet2, cbet2, dn2,
                                lam12, slam12, clam12, C1a, C2a);
      sig12 = nvals.sig12;
      salp1 = nvals.salp1;
      calp1 = nvals.calp1;

      if (sig12 >= 0) {
        salp2 = nvals.salp2;
        calp2 = nvals.calp2;
        // Short lines (InverseStart sets salp2, calp2, dnm)

        dnm = nvals.dnm;
        s12x = sig12 * this._b * dnm;
        m12x = m.sq(dnm) * this._b * Math.sin(sig12 / dnm);
        if (outmask & g.GEODESICSCALE)
          vals.M12 = vals.M21 = Math.cos(sig12 / dnm);
        vals.a12 = sig12 / m.degree;
        omg12 = lam12 / (this._f1 * dnm);
      } else {

        // Newton's method.  This is a straightforward solution of f(alp1) =
        // lambda12(alp1) - lam12 = 0 with one wrinkle.  f(alp) has exactly one
        // root in the interval (0, pi) and its derivative is positive at the
        // root.  Thus f(alp) is positive for alp > alp1 and negative for alp <
        // alp1.  During the course of the iteration, a range (alp1a, alp1b) is
        // maintained which brackets the root and with each evaluation of
        // f(alp) the range is shrunk if possible.  Newton's method is
        // restarted whenever the derivative of f is negative (because the new
        // value of alp1 is then further from the solution) or if the new
        // estimate of alp1 lies outside (0,pi); in this case, the new starting
        // guess is taken to be (alp1a + alp1b) / 2.
        numit = 0;
        // Bracketing range
        salp1a = g.tiny_; calp1a = 1; salp1b = g.tiny_; calp1b = -1;
        for (tripn = false, tripb = false; numit < maxit2_; ++numit) {
          // the WGS84 test set: mean = 1.47, sd = 1.25, max = 16
          // WGS84 and random input: mean = 2.85, sd = 0.60
          nvals = this.Lambda12(sbet1, cbet1, dn1, sbet2, cbet2, dn2,
                                salp1, calp1, slam12, clam12, numit < maxit1_,
                                C1a, C2a, C3a);
          v = nvals.lam12;
          salp2 = nvals.salp2;
          calp2 = nvals.calp2;
          sig12 = nvals.sig12;
          ssig1 = nvals.ssig1;
          csig1 = nvals.csig1;
          ssig2 = nvals.ssig2;
          csig2 = nvals.csig2;
          eps = nvals.eps;
          domg12 = nvals.domg12;
          dv = nvals.dlam12;

          // 2 * tol0 is approximately 1 ulp for a number in [0, pi].
          // Reversed test to allow escape with NaNs
          if (tripb || !(Math.abs(v) >= (tripn ? 8 : 1) * tol0_))
            break;
          // Update bracketing values
          if (v > 0 && (numit < maxit1_ || calp1/salp1 > calp1b/salp1b)) {
            salp1b = salp1; calp1b = calp1;
          } else if (v < 0 &&
                     (numit < maxit1_ || calp1/salp1 < calp1a/salp1a)) {
            salp1a = salp1; calp1a = calp1;
          }
          if (numit < maxit1_ && dv > 0) {
            dalp1 = -v/dv;
            sdalp1 = Math.sin(dalp1); cdalp1 = Math.cos(dalp1);
            nsalp1 = salp1 * cdalp1 + calp1 * sdalp1;
            if (nsalp1 > 0 && Math.abs(dalp1) < Math.PI) {
              calp1 = calp1 * cdalp1 - salp1 * sdalp1;
              salp1 = nsalp1;
              // norm(salp1, calp1);
              t = m.hypot(salp1, calp1); salp1 /= t; calp1 /= t;
              // In some regimes we don't get quadratic convergence because
              // slope -> 0.  So use convergence conditions based on epsilon
              // instead of sqrt(epsilon).
              tripn = Math.abs(v) <= 16 * tol0_;
              continue;
            }
          }
          // Either dv was not positive or updated value was outside legal
          // range.  Use the midpoint of the bracket as the next estimate.
          // This mechanism is not needed for the WGS84 ellipsoid, but it does
          // catch problems with more eccentric ellipsoids.  Its efficacy is
          // such for the WGS84 test set with the starting guess set to alp1 =
          // 90deg:
          // the WGS84 test set: mean = 5.21, sd = 3.93, max = 24
          // WGS84 and random input: mean = 4.74, sd = 0.99
          salp1 = (salp1a + salp1b)/2;
          calp1 = (calp1a + calp1b)/2;
          // norm(salp1, calp1);
          t = m.hypot(salp1, calp1); salp1 /= t; calp1 /= t;
          tripn = false;
          tripb = (Math.abs(salp1a - salp1) + (calp1a - calp1) < tolb_ ||
                   Math.abs(salp1 - salp1b) + (calp1 - calp1b) < tolb_);
        }
        lengthmask = outmask |
            (outmask & (g.REDUCEDLENGTH | g.GEODESICSCALE) ?
             g.DISTANCE : g.NONE);
        nvals = this.Lengths(eps, sig12,
                             ssig1, csig1, dn1, ssig2, csig2, dn2, cbet1, cbet2,
                             lengthmask, C1a, C2a);
        s12x = nvals.s12b;
        m12x = nvals.m12b;
        // Ignore m0
        if ((outmask & g.GEODESICSCALE) !== 0) {
          vals.M12 = nvals.M12;
          vals.M21 = nvals.M21;
        }
        m12x *= this._b;
        s12x *= this._b;
        vals.a12 = sig12 / m.degree;
        if (outmask & g.AREA) {
          // omg12 = lam12 - domg12
          sdomg12 = Math.sin(domg12); cdomg12 = Math.cos(domg12);
          somg12 = slam12 * cdomg12 - clam12 * sdomg12;
          comg12 = clam12 * cdomg12 + slam12 * sdomg12;
        }
      }
    }

    if (outmask & g.DISTANCE)
      vals.s12 = 0 + s12x;      // Convert -0 to 0

    if (outmask & g.REDUCEDLENGTH)
      vals.m12 = 0 + m12x;      // Convert -0 to 0

    if (outmask & g.AREA) {
      // From Lambda12: sin(alp1) * cos(bet1) = sin(alp0)
      salp0 = salp1 * cbet1;
      calp0 = m.hypot(calp1, salp1 * sbet1); // calp0 > 0
      if (calp0 !== 0 && salp0 !== 0) {
        // From Lambda12: tan(bet) = tan(sig) * cos(alp)
        ssig1 = sbet1; csig1 = calp1 * cbet1;
        ssig2 = sbet2; csig2 = calp2 * cbet2;
        k2 = m.sq(calp0) * this._ep2;
        eps = k2 / (2 * (1 + Math.sqrt(1 + k2)) + k2);
        // Multiplier = a^2 * e^2 * cos(alpha0) * sin(alpha0).
        A4 = m.sq(this.a) * calp0 * salp0 * this._e2;
        // norm(ssig1, csig1);
        t = m.hypot(ssig1, csig1); ssig1 /= t; csig1 /= t;
        // norm(ssig2, csig2);
        t = m.hypot(ssig2, csig2); ssig2 /= t; csig2 /= t;
        C4a = new Array(g.nC4_);
        this.C4f(eps, C4a);
        B41 = g.SinCosSeries(false, ssig1, csig1, C4a);
        B42 = g.SinCosSeries(false, ssig2, csig2, C4a);
        vals.S12 = A4 * (B42 - B41);
      } else
        // Avoid problems with indeterminate sig1, sig2 on equator
        vals.S12 = 0;
      if (!meridian && somg12 > 1) {
        somg12 = Math.sin(omg12); comg12 = Math.cos(omg12);
      }
      if (!meridian &&
          comg12 > -0.7071 &&      // Long difference not too big
          sbet2 - sbet1 < 1.75) { // Lat difference not too big
        // Use tan(Gamma/2) = tan(omg12/2)
        // * (tan(bet1/2)+tan(bet2/2))/(1+tan(bet1/2)*tan(bet2/2))
        // with tan(x/2) = sin(x)/(1+cos(x))
        domg12 = 1 + comg12; dbet1 = 1 + cbet1; dbet2 = 1 + cbet2;
        alp12 = 2 * Math.atan2( somg12 * (sbet1*dbet2 + sbet2*dbet1),
                                domg12 * (sbet1*sbet2 + dbet1*dbet2) );
      } else {
        // alp12 = alp2 - alp1, used in atan2 so no need to normalize
        salp12 = salp2 * calp1 - calp2 * salp1;
        calp12 = calp2 * calp1 + salp2 * salp1;
        // The right thing appears to happen if alp1 = +/-180 and alp2 = 0, viz
        // salp12 = -0 and alp12 = -180.  However this depends on the sign
        // being attached to 0 correctly.  The following ensures the correct
        // behavior.
        if (salp12 === 0 && calp12 < 0) {
          salp12 = g.tiny_ * calp1;
          calp12 = -1;
        }
        alp12 = Math.atan2(salp12, calp12);
      }
      vals.S12 += this._c2 * alp12;
      vals.S12 *= swapp * lonsign * latsign;
      // Convert -0 to 0
      vals.S12 += 0;
    }

    // Convert calp, salp to azimuth accounting for lonsign, swapp, latsign.
    if (swapp < 0) {
      t = salp1;
      salp1 = salp2;
      salp2 = t;
      // swap(salp1, salp2);
      t = calp1;
      calp1 = calp2;
      calp2 = t;
      // swap(calp1, calp2);
      if (outmask & g.GEODESICSCALE) {
        t = vals.M12;
        vals.M12 = vals.M21;
        vals.M21 = t;
        // swap(vals.M12, vals.M21);
      }
    }

    salp1 *= swapp * lonsign; calp1 *= swapp * latsign;
    salp2 *= swapp * lonsign; calp2 *= swapp * latsign;

    return {vals: vals,
            salp1: salp1, calp1: calp1,
            salp2: salp2, calp2: calp2};
  };

  /**
   * @summary Solve the general direct geodesic problem.
   * @param {number} lat1 the latitude of the first point in degrees.
   * @param {number} lon1 the longitude of the first point in degrees.
   * @param {number} azi1 the azimuth at the first point in degrees.
   * @param {bool} arcmode is the next parameter an arc length?
   * @param {number} s12_a12 the (arcmode ? arc length : distance) from the
   *   first point to the second in (arcmode ? degrees : meters).
   * @param {bitmask} [outmask = STANDARD] which results to include.
   * @returns {object} the requested results.
   * @description The lat1, lon1, azi1, and a12 fields of the result are always
   *   set; s12 is included if arcmode is false.  For details on the outmask
   *   parameter, see {@tutorial 2-interface}, "The outmask and caps
   *   parameters".
   */
  g.Geodesic.prototype.GenDirect = function(lat1, lon1, azi1,
                                            arcmode, s12_a12, outmask) {
    var line;
    if (!outmask) outmask = g.STANDARD;
    else if (outmask === g.LONG_UNROLL) outmask |= g.STANDARD;
    // Automatically supply DISTANCE_IN if necessary
    if (!arcmode) outmask |= g.DISTANCE_IN;
    line = new l.GeodesicLine(this, lat1, lon1, azi1, outmask);
    return line.GenPosition(arcmode, s12_a12, outmask);
  };

  /**
   * @summary Solve the direct geodesic problem.
   * @param {number} lat1 the latitude of the first point in degrees.
   * @param {number} lon1 the longitude of the first point in degrees.
   * @param {number} azi1 the azimuth at the first point in degrees.
   * @param {number} s12 the distance from the first point to the second in
   *   meters.
   * @param {bitmask} [outmask = STANDARD] which results to include.
   * @returns {object} the requested results.
   * @description The lat1, lon1, azi1, s12, and a12 fields of the result are
   *   always set.  For details on the outmask parameter, see {@tutorial
   *   2-interface}, "The outmask and caps parameters".
   */
  g.Geodesic.prototype.Direct = function(lat1, lon1, azi1, s12, outmask) {
    return this.GenDirect(lat1, lon1, azi1, false, s12, outmask);
  };

  /**
   * @summary Solve the direct geodesic problem with arc length.
   * @param {number} lat1 the latitude of the first point in degrees.
   * @param {number} lon1 the longitude of the first point in degrees.
   * @param {number} azi1 the azimuth at the first point in degrees.
   * @param {number} a12 the arc length from the first point to the second in
   *   degrees.
   * @param {bitmask} [outmask = STANDARD] which results to include.
   * @returns {object} the requested results.
   * @description The lat1, lon1, azi1, and a12 fields of the result are
   *   always set.  For details on the outmask parameter, see {@tutorial
   *   2-interface}, "The outmask and caps parameters".
   */
  g.Geodesic.prototype.ArcDirect = function(lat1, lon1, azi1, a12, outmask) {
    return this.GenDirect(lat1, lon1, azi1, true, a12, outmask);
  };

  /**
   * @summary Create a {@link module:GeographicLib/GeodesicLine.GeodesicLine
   *   GeodesicLine} object.
   * @param {number} lat1 the latitude of the first point in degrees.
   * @param {number} lon1 the longitude of the first point in degrees.
   * @param {number} azi1 the azimuth at the first point in degrees.
   *   degrees.
   * @param {bitmask} [caps = STANDARD | DISTANCE_IN] which capabilities to
   *   include.
   * @returns {object} the
   *   {@link module:GeographicLib/GeodesicLine.GeodesicLine
   *   GeodesicLine} object
   * @description For details on the caps parameter, see {@tutorial
   *   2-interface}, "The outmask and caps parameters".
   */
  g.Geodesic.prototype.Line = function(lat1, lon1, azi1, caps) {
    return new l.GeodesicLine(this, lat1, lon1, azi1, caps);
  };

  /**
   * @summary Define a {@link module:GeographicLib/GeodesicLine.GeodesicLine
   *   GeodesicLine} in terms of the direct geodesic problem specified in terms
   *   of distance.
   * @param {number} lat1 the latitude of the first point in degrees.
   * @param {number} lon1 the longitude of the first point in degrees.
   * @param {number} azi1 the azimuth at the first point in degrees.
   *   degrees.
   * @param {number} s12 the distance between point 1 and point 2 (meters); it
   *   can be negative.
   * @param {bitmask} [caps = STANDARD | DISTANCE_IN] which capabilities to
   *   include.
   * @returns {object} the
   *   {@link module:GeographicLib/GeodesicLine.GeodesicLine
   *   GeodesicLine} object
   * @description This function sets point 3 of the GeodesicLine to correspond
   *   to point 2 of the direct geodesic problem.  For details on the caps
   *   parameter, see {@tutorial 2-interface}, "The outmask and caps
   *   parameters".
   */
  g.Geodesic.prototype.DirectLine = function(lat1, lon1, azi1, s12, caps) {
    return this.GenDirectLine(lat1, lon1, azi1, false, s12, caps);
  };

  /**
   * @summary Define a {@link module:GeographicLib/GeodesicLine.GeodesicLine
   *   GeodesicLine} in terms of the direct geodesic problem specified in terms
   *   of arc length.
   * @param {number} lat1 the latitude of the first point in degrees.
   * @param {number} lon1 the longitude of the first point in degrees.
   * @param {number} azi1 the azimuth at the first point in degrees.
   *   degrees.
   * @param {number} a12 the arc length between point 1 and point 2 (degrees);
   *   it can be negative.
   * @param {bitmask} [caps = STANDARD | DISTANCE_IN] which capabilities to
   *   include.
   * @returns {object} the
   *   {@link module:GeographicLib/GeodesicLine.GeodesicLine
   *   GeodesicLine} object
   * @description This function sets point 3 of the GeodesicLine to correspond
   *   to point 2 of the direct geodesic problem.  For details on the caps
   *   parameter, see {@tutorial 2-interface}, "The outmask and caps
   *   parameters".
   */
  g.Geodesic.prototype.ArcDirectLine = function(lat1, lon1, azi1, a12, caps) {
    return this.GenDirectLine(lat1, lon1, azi1, true, a12, caps);
  };

  /**
   * @summary Define a {@link module:GeographicLib/GeodesicLine.GeodesicLine
   *   GeodesicLine} in terms of the direct geodesic problem specified in terms
   *   of either distance or arc length.
   * @param {number} lat1 the latitude of the first point in degrees.
   * @param {number} lon1 the longitude of the first point in degrees.
   * @param {number} azi1 the azimuth at the first point in degrees.
   *   degrees.
   * @param {bool} arcmode boolean flag determining the meaning of the
   *   s12_a12.
   * @param {number} s12_a12 if arcmode is false, this is the distance between
   *   point 1 and point 2 (meters); otherwise it is the arc length between
   *   point 1 and point 2 (degrees); it can be negative.
   * @param {bitmask} [caps = STANDARD | DISTANCE_IN] which capabilities to
   *   include.
   * @returns {object} the
   *   {@link module:GeographicLib/GeodesicLine.GeodesicLine
   *   GeodesicLine} object
   * @description This function sets point 3 of the GeodesicLine to correspond
   *   to point 2 of the direct geodesic problem.  For details on the caps
   *   parameter, see {@tutorial 2-interface}, "The outmask and caps
   *   parameters".
   */
  g.Geodesic.prototype.GenDirectLine = function(lat1, lon1, azi1,
                                                arcmode, s12_a12, caps) {
    var t;
    if (!caps) caps = g.STANDARD | g.DISTANCE_IN;
    // Automatically supply DISTANCE_IN if necessary
    if (!arcmode) caps |= g.DISTANCE_IN;
    t = new l.GeodesicLine(this, lat1, lon1, azi1, caps);
    t.GenSetDistance(arcmode, s12_a12);
    return t;
  };

  /**
   * @summary Define a {@link module:GeographicLib/GeodesicLine.GeodesicLine
   *   GeodesicLine} in terms of the inverse geodesic problem.
   * @param {number} lat1 the latitude of the first point in degrees.
   * @param {number} lon1 the longitude of the first point in degrees.
   * @param {number} lat2 the latitude of the second point in degrees.
   * @param {number} lon2 the longitude of the second point in degrees.
   * @param {bitmask} [caps = STANDARD | DISTANCE_IN] which capabilities to
   *   include.
   * @returns {object} the
   *   {@link module:GeographicLib/GeodesicLine.GeodesicLine
   *   GeodesicLine} object
   * @description This function sets point 3 of the GeodesicLine to correspond
   *   to point 2 of the inverse geodesic problem.  For details on the caps
   *   parameter, see {@tutorial 2-interface}, "The outmask and caps
   *   parameters".
   */
  g.Geodesic.prototype.InverseLine = function(lat1, lon1, lat2, lon2, caps) {
    var r, t, azi1;
    if (!caps) caps = g.STANDARD | g.DISTANCE_IN;
    r = this.InverseInt(lat1, lon1, lat2, lon2, g.ARC);
    azi1 = m.atan2d(r.salp1, r.calp1);
    // Ensure that a12 can be converted to a distance
    if (caps & (g.OUT_MASK & g.DISTANCE_IN)) caps |= g.DISTANCE;
    t = new l.GeodesicLine(this, lat1, lon1, azi1, caps, r.salp1, r.calp1);
    t.SetArc(r.vals.a12);
    return t;
  };

  /**
   * @summary Create a {@link module:GeographicLib/PolygonArea.PolygonArea
   *   PolygonArea} object.
   * @param {bool} [polyline = false] if true the new PolygonArea object
   *   describes a polyline instead of a polygon.
   * @returns {object} the
   *   {@link module:GeographicLib/PolygonArea.PolygonArea
   *   PolygonArea} object
   */
  g.Geodesic.prototype.Polygon = function(polyline) {
    return new p.PolygonArea(this, polyline);
  };

  /**
   * @summary a {@link module:GeographicLib/Geodesic.Geodesic Geodesic} object
   *   initialized for the WGS84 ellipsoid.
   * @constant {object}
   */
  g.WGS84 = new g.Geodesic(c.WGS84.a, c.WGS84.f);
})(GeographicLib.Geodesic, GeographicLib.GeodesicLine,
   GeographicLib.PolygonArea, GeographicLib.Math, GeographicLib.Constants);


/*
 * GeodesicLine.js
 * Transcription of GeodesicLine.[ch]pp into JavaScript.
 *
 * See the documentation for the C++ class.  The conversion is a literal
 * conversion from C++.
 *
 * The algorithms are derived in
 *
 *    Charles F. F. Karney,
 *    Algorithms for geodesics, J. Geodesy 87, 43-55 (2013);
 *    https://doi.org/10.1007/s00190-012-0578-z
 *    Addenda: https://geographiclib.sourceforge.io/geod-addenda.html
 *
 * Copyright (c) Charles Karney (2011-2016) <charles@karney.com> and licensed
 * under the MIT/X11 License.  For more information, see
 * https://geographiclib.sourceforge.io/
 */

// Load AFTER GeographicLib/Math.js, GeographicLib/Geodesic.js

(function(
  g,
  /**
   * @exports GeographicLib/GeodesicLine
   * @description Solve geodesic problems on a single geodesic line via the
   *   {@link module:GeographicLib/GeodesicLine.GeodesicLine GeodesicLine}
   *   class.
   */
  l, m) {

  /**
   * @class
   * @property {number} a the equatorial radius (meters).
   * @property {number} f the flattening.
   * @property {number} lat1 the initial latitude (degrees).
   * @property {number} lon1 the initial longitude (degrees).
   * @property {number} azi1 the initial azimuth (degrees).
   * @property {number} salp1 the sine of the azimuth at the first point.
   * @property {number} calp1 the cosine the azimuth at the first point.
   * @property {number} s13 the distance to point 3 (meters).
   * @property {number} a13 the arc length to point 3 (degrees).
   * @property {bitmask} caps the capabilities of the object.
   * @summary Initialize a GeodesicLine object.  For details on the caps
   *   parameter, see {@tutorial 2-interface}, "The outmask and caps
   *   parameters".
   * @classdesc Performs geodesic calculations along a given geodesic line.
   *   This object is usually instantiated by
   *   {@link module:GeographicLib/Geodesic.Geodesic#Line Geodesic.Line}.
   *   The methods
   *   {@link module:GeographicLib/Geodesic.Geodesic#DirectLine
   *   Geodesic.DirectLine} and
   *   {@link module:GeographicLib/Geodesic.Geodesic#InverseLine
   *   Geodesic.InverseLine} set in addition the position of a reference point
   *   3.
   * @param {object} geod a {@link module:GeographicLib/Geodesic.Geodesic
   *   Geodesic} object.
   * @param {number} lat1 the latitude of the first point in degrees.
   * @param {number} lon1 the longitude of the first point in degrees.
   * @param {number} azi1 the azimuth at the first point in degrees.
   * @param {bitmask} [caps = STANDARD | DISTANCE_IN] which capabilities to
   *   include; LATITUDE | AZIMUTH are always included.
   */
  l.GeodesicLine = function(geod, lat1, lon1, azi1, caps, salp1, calp1) {
    var t, cbet1, sbet1, eps, s, c;
    if (!caps) caps = g.STANDARD | g.DISTANCE_IN;

    this.a = geod.a;
    this.f = geod.f;
    this._b = geod._b;
    this._c2 = geod._c2;
    this._f1 = geod._f1;
    this.caps = caps | g.LATITUDE | g.AZIMUTH | g.LONG_UNROLL;

    this.lat1 = m.LatFix(lat1);
    this.lon1 = lon1;
    if (typeof salp1 === 'undefined' || typeof calp1 === 'undefined') {
      this.azi1 = m.AngNormalize(azi1);
      t = m.sincosd(m.AngRound(this.azi1)); this.salp1 = t.s; this.calp1 = t.c;
    } else {
      this.azi1 = azi1; this.salp1 = salp1; this.calp1 = calp1;
    }
    t = m.sincosd(m.AngRound(this.lat1)); sbet1 = this._f1 * t.s; cbet1 = t.c;
    // norm(sbet1, cbet1);
    t = m.hypot(sbet1, cbet1); sbet1 /= t; cbet1 /= t;
    // Ensure cbet1 = +epsilon at poles
    cbet1 = Math.max(g.tiny_, cbet1);
    this._dn1 = Math.sqrt(1 + geod._ep2 * m.sq(sbet1));

    // Evaluate alp0 from sin(alp1) * cos(bet1) = sin(alp0),
    this._salp0 = this.salp1 * cbet1; // alp0 in [0, pi/2 - |bet1|]
    // Alt: calp0 = hypot(sbet1, calp1 * cbet1).  The following
    // is slightly better (consider the case salp1 = 0).
    this._calp0 = m.hypot(this.calp1, this.salp1 * sbet1);
    // Evaluate sig with tan(bet1) = tan(sig1) * cos(alp1).
    // sig = 0 is nearest northward crossing of equator.
    // With bet1 = 0, alp1 = pi/2, we have sig1 = 0 (equatorial line).
    // With bet1 =  pi/2, alp1 = -pi, sig1 =  pi/2
    // With bet1 = -pi/2, alp1 =  0 , sig1 = -pi/2
    // Evaluate omg1 with tan(omg1) = sin(alp0) * tan(sig1).
    // With alp0 in (0, pi/2], quadrants for sig and omg coincide.
    // No atan2(0,0) ambiguity at poles since cbet1 = +epsilon.
    // With alp0 = 0, omg1 = 0 for alp1 = 0, omg1 = pi for alp1 = pi.
    this._ssig1 = sbet1; this._somg1 = this._salp0 * sbet1;
    this._csig1 = this._comg1 =
      sbet1 !== 0 || this.calp1 !== 0 ? cbet1 * this.calp1 : 1;
    // norm(this._ssig1, this._csig1); // sig1 in (-pi, pi]
    t = m.hypot(this._ssig1, this._csig1);
    this._ssig1 /= t; this._csig1 /= t;
    // norm(this._somg1, this._comg1); -- don't need to normalize!

    this._k2 = m.sq(this._calp0) * geod._ep2;
    eps = this._k2 / (2 * (1 + Math.sqrt(1 + this._k2)) + this._k2);

    if (this.caps & g.CAP_C1) {
      this._A1m1 = g.A1m1f(eps);
      this._C1a = new Array(g.nC1_ + 1);
      g.C1f(eps, this._C1a);
      this._B11 = g.SinCosSeries(true, this._ssig1, this._csig1, this._C1a);
      s = Math.sin(this._B11); c = Math.cos(this._B11);
      // tau1 = sig1 + B11
      this._stau1 = this._ssig1 * c + this._csig1 * s;
      this._ctau1 = this._csig1 * c - this._ssig1 * s;
      // Not necessary because C1pa reverts C1a
      //    _B11 = -SinCosSeries(true, _stau1, _ctau1, _C1pa);
    }

    if (this.caps & g.CAP_C1p) {
      this._C1pa = new Array(g.nC1p_ + 1);
      g.C1pf(eps, this._C1pa);
    }

    if (this.caps & g.CAP_C2) {
      this._A2m1 = g.A2m1f(eps);
      this._C2a = new Array(g.nC2_ + 1);
      g.C2f(eps, this._C2a);
      this._B21 = g.SinCosSeries(true, this._ssig1, this._csig1, this._C2a);
    }

    if (this.caps & g.CAP_C3) {
      this._C3a = new Array(g.nC3_);
      geod.C3f(eps, this._C3a);
      this._A3c = -this.f * this._salp0 * geod.A3f(eps);
      this._B31 = g.SinCosSeries(true, this._ssig1, this._csig1, this._C3a);
    }

    if (this.caps & g.CAP_C4) {
      this._C4a = new Array(g.nC4_); // all the elements of _C4a are used
      geod.C4f(eps, this._C4a);
      // Multiplier = a^2 * e^2 * cos(alpha0) * sin(alpha0)
      this._A4 = m.sq(this.a) * this._calp0 * this._salp0 * geod._e2;
      this._B41 = g.SinCosSeries(false, this._ssig1, this._csig1, this._C4a);
    }

    this.a13 = this.s13 = Number.NaN;
  };

  /**
   * @summary Find the position on the line (general case).
   * @param {bool} arcmode is the next parameter an arc length?
   * @param {number} s12_a12 the (arcmode ? arc length : distance) from the
   *   first point to the second in (arcmode ? degrees : meters).
   * @param {bitmask} [outmask = STANDARD] which results to include; this is
   *   subject to the capabilities of the object.
   * @returns {object} the requested results.
   * @description The lat1, lon1, azi1, and a12 fields of the result are
   *   always set; s12 is included if arcmode is false.  For details on the
   *   outmask parameter, see {@tutorial 2-interface}, "The outmask and caps
   *   parameters".
   */
  l.GeodesicLine.prototype.GenPosition = function(arcmode, s12_a12,
                                                  outmask) {
    var vals = {},
        sig12, ssig12, csig12, B12, AB1, ssig2, csig2, tau12, s, c, serr,
        omg12, lam12, lon12, E, sbet2, cbet2, somg2, comg2, salp2, calp2, dn2,
        B22, AB2, J12, t, B42, salp12, calp12;
    if (!outmask) outmask = g.STANDARD;
    else if (outmask === g.LONG_UNROLL) outmask |= g.STANDARD;
    outmask &= this.caps & g.OUT_MASK;
    vals.lat1 = this.lat1; vals.azi1 = this.azi1;
    vals.lon1 = outmask & g.LONG_UNROLL ?
      this.lon1 : m.AngNormalize(this.lon1);
    if (arcmode)
      vals.a12 = s12_a12;
    else
      vals.s12 = s12_a12;
    if (!( arcmode || (this.caps & g.DISTANCE_IN & g.OUT_MASK) )) {
      // Uninitialized or impossible distance calculation requested
      vals.a12 = Number.NaN;
      return vals;
    }

    // Avoid warning about uninitialized B12.
    B12 = 0; AB1 = 0;
    if (arcmode) {
      // Interpret s12_a12 as spherical arc length
      sig12 = s12_a12 * m.degree;
      t = m.sincosd(s12_a12); ssig12 = t.s; csig12 = t.c;
    } else {
      // Interpret s12_a12 as distance
      tau12 = s12_a12 / (this._b * (1 + this._A1m1));
      s = Math.sin(tau12);
      c = Math.cos(tau12);
      // tau2 = tau1 + tau12
      B12 = -g.SinCosSeries(true,
                            this._stau1 * c + this._ctau1 * s,
                            this._ctau1 * c - this._stau1 * s,
                            this._C1pa);
      sig12 = tau12 - (B12 - this._B11);
      ssig12 = Math.sin(sig12); csig12 = Math.cos(sig12);
      if (Math.abs(this.f) > 0.01) {
        // Reverted distance series is inaccurate for |f| > 1/100, so correct
        // sig12 with 1 Newton iteration.  The following table shows the
        // approximate maximum error for a = WGS_a() and various f relative to
        // GeodesicExact.
        //     erri = the error in the inverse solution (nm)
        //     errd = the error in the direct solution (series only) (nm)
        //     errda = the error in the direct solution (series + 1 Newton) (nm)
        //
        //       f     erri  errd errda
        //     -1/5    12e6 1.2e9  69e6
        //     -1/10  123e3  12e6 765e3
        //     -1/20   1110 108e3  7155
        //     -1/50  18.63 200.9 27.12
        //     -1/100 18.63 23.78 23.37
        //     -1/150 18.63 21.05 20.26
        //      1/150 22.35 24.73 25.83
        //      1/100 22.35 25.03 25.31
        //      1/50  29.80 231.9 30.44
        //      1/20   5376 146e3  10e3
        //      1/10  829e3  22e6 1.5e6
        //      1/5   157e6 3.8e9 280e6
        ssig2 = this._ssig1 * csig12 + this._csig1 * ssig12;
        csig2 = this._csig1 * csig12 - this._ssig1 * ssig12;
        B12 = g.SinCosSeries(true, ssig2, csig2, this._C1a);
        serr = (1 + this._A1m1) * (sig12 + (B12 - this._B11)) -
          s12_a12 / this._b;
        sig12 = sig12 - serr / Math.sqrt(1 + this._k2 * m.sq(ssig2));
        ssig12 = Math.sin(sig12); csig12 = Math.cos(sig12);
        // Update B12 below
      }
    }

    // sig2 = sig1 + sig12
    ssig2 = this._ssig1 * csig12 + this._csig1 * ssig12;
    csig2 = this._csig1 * csig12 - this._ssig1 * ssig12;
    dn2 = Math.sqrt(1 + this._k2 * m.sq(ssig2));
    if (outmask & (g.DISTANCE | g.REDUCEDLENGTH | g.GEODESICSCALE)) {
      if (arcmode || Math.abs(this.f) > 0.01)
        B12 = g.SinCosSeries(true, ssig2, csig2, this._C1a);
      AB1 = (1 + this._A1m1) * (B12 - this._B11);
    }
    // sin(bet2) = cos(alp0) * sin(sig2)
    sbet2 = this._calp0 * ssig2;
    // Alt: cbet2 = hypot(csig2, salp0 * ssig2);
    cbet2 = m.hypot(this._salp0, this._calp0 * csig2);
    if (cbet2 === 0)
      // I.e., salp0 = 0, csig2 = 0.  Break the degeneracy in this case
      cbet2 = csig2 = g.tiny_;
    // tan(alp0) = cos(sig2)*tan(alp2)
    salp2 = this._salp0; calp2 = this._calp0 * csig2; // No need to normalize

    if (arcmode && (outmask & g.DISTANCE))
      vals.s12 = this._b * ((1 + this._A1m1) * sig12 + AB1);

    if (outmask & g.LONGITUDE) {
      // tan(omg2) = sin(alp0) * tan(sig2)
      somg2 = this._salp0 * ssig2; comg2 = csig2; // No need to normalize
      E = m.copysign(1, this._salp0);
      // omg12 = omg2 - omg1
      omg12 = outmask & g.LONG_UNROLL ?
        E * (sig12 -
             (Math.atan2(ssig2, csig2) -
              Math.atan2(this._ssig1, this._csig1)) +
             (Math.atan2(E * somg2, comg2) -
              Math.atan2(E * this._somg1, this._comg1))) :
        Math.atan2(somg2 * this._comg1 - comg2 * this._somg1,
                     comg2 * this._comg1 + somg2 * this._somg1);
      lam12 = omg12 + this._A3c *
        ( sig12 + (g.SinCosSeries(true, ssig2, csig2, this._C3a) -
                   this._B31));
      lon12 = lam12 / m.degree;
      vals.lon2 = outmask & g.LONG_UNROLL ? this.lon1 + lon12 :
        m.AngNormalize(m.AngNormalize(this.lon1) + m.AngNormalize(lon12));
    }

    if (outmask & g.LATITUDE)
      vals.lat2 = m.atan2d(sbet2, this._f1 * cbet2);

    if (outmask & g.AZIMUTH)
      vals.azi2 = m.atan2d(salp2, calp2);

    if (outmask & (g.REDUCEDLENGTH | g.GEODESICSCALE)) {
      B22 = g.SinCosSeries(true, ssig2, csig2, this._C2a);
      AB2 = (1 + this._A2m1) * (B22 - this._B21);
      J12 = (this._A1m1 - this._A2m1) * sig12 + (AB1 - AB2);
      if (outmask & g.REDUCEDLENGTH)
        // Add parens around (_csig1 * ssig2) and (_ssig1 * csig2) to ensure
        // accurate cancellation in the case of coincident points.
        vals.m12 = this._b * ((      dn2 * (this._csig1 * ssig2) -
                               this._dn1 * (this._ssig1 * csig2)) -
                              this._csig1 * csig2 * J12);
      if (outmask & g.GEODESICSCALE) {
        t = this._k2 * (ssig2 - this._ssig1) * (ssig2 + this._ssig1) /
          (this._dn1 + dn2);
        vals.M12 = csig12 + (t * ssig2 - csig2 * J12) * this._ssig1 / this._dn1;
        vals.M21 = csig12 - (t * this._ssig1 - this._csig1 * J12) * ssig2 / dn2;
      }
    }

    if (outmask & g.AREA) {
      B42 = g.SinCosSeries(false, ssig2, csig2, this._C4a);
      if (this._calp0 === 0 || this._salp0 === 0) {
        // alp12 = alp2 - alp1, used in atan2 so no need to normalize
        salp12 = salp2 * this.calp1 - calp2 * this.salp1;
        calp12 = calp2 * this.calp1 + salp2 * this.salp1;
      } else {
        // tan(alp) = tan(alp0) * sec(sig)
        // tan(alp2-alp1) = (tan(alp2) -tan(alp1)) / (tan(alp2)*tan(alp1)+1)
        // = calp0 * salp0 * (csig1-csig2) / (salp0^2 + calp0^2 * csig1*csig2)
        // If csig12 > 0, write
        //   csig1 - csig2 = ssig12 * (csig1 * ssig12 / (1 + csig12) + ssig1)
        // else
        //   csig1 - csig2 = csig1 * (1 - csig12) + ssig12 * ssig1
        // No need to normalize
        salp12 = this._calp0 * this._salp0 *
          (csig12 <= 0 ? this._csig1 * (1 - csig12) + ssig12 * this._ssig1 :
           ssig12 * (this._csig1 * ssig12 / (1 + csig12) + this._ssig1));
        calp12 = m.sq(this._salp0) + m.sq(this._calp0) * this._csig1 * csig2;
      }
      vals.S12 = this._c2 * Math.atan2(salp12, calp12) +
        this._A4 * (B42 - this._B41);
    }

    if (!arcmode)
      vals.a12 = sig12 / m.degree;
    return vals;
  };

  /**
   * @summary Find the position on the line given s12.
   * @param {number} s12 the distance from the first point to the second in
   *   meters.
   * @param {bitmask} [outmask = STANDARD] which results to include; this is
   *   subject to the capabilities of the object.
   * @returns {object} the requested results.
   * @description The lat1, lon1, azi1, s12, and a12 fields of the result are
   *   always set; s12 is included if arcmode is false.  For details on the
   *   outmask parameter, see {@tutorial 2-interface}, "The outmask and caps
   *   parameters".
   */
  l.GeodesicLine.prototype.Position = function(s12, outmask) {
    return this.GenPosition(false, s12, outmask);
  };

  /**
   * @summary Find the position on the line given a12.
   * @param {number} a12 the arc length from the first point to the second in
   *   degrees.
   * @param {bitmask} [outmask = STANDARD] which results to include; this is
   *   subject to the capabilities of the object.
   * @returns {object} the requested results.
   * @description The lat1, lon1, azi1, and a12 fields of the result are
   *   always set.  For details on the outmask parameter, see {@tutorial
   *   2-interface}, "The outmask and caps parameters".
   */
  l.GeodesicLine.prototype.ArcPosition = function(a12, outmask) {
    return this.GenPosition(true, a12, outmask);
  };

  /**
   * @summary Specify position of point 3 in terms of either distance or arc
   *   length.
   * @param {bool} arcmode boolean flag determining the meaning of the second
   *   parameter; if arcmode is false, then the GeodesicLine object must have
   *   been constructed with caps |= DISTANCE_IN.
   * @param {number} s13_a13 if arcmode is false, this is the distance from
   *   point 1 to point 3 (meters); otherwise it is the arc length from
   *   point 1 to point 3 (degrees); it can be negative.
   **********************************************************************/
  l.GeodesicLine.prototype.GenSetDistance = function(arcmode, s13_a13) {
    if (arcmode)
      this.SetArc(s13_a13);
    else
      this.SetDistance(s13_a13);
  };

  /**
   * @summary Specify position of point 3 in terms distance.
   * @param {number} s13 the distance from point 1 to point 3 (meters); it
   *   can be negative.
   **********************************************************************/
  l.GeodesicLine.prototype.SetDistance = function(s13) {
    var r;
    this.s13 = s13;
    r = this.GenPosition(false, this.s13, g.ARC);
    this.a13 = 0 + r.a12;       // the 0+ converts undefined into NaN
  };

  /**
   * @summary Specify position of point 3 in terms of arc length.
   * @param {number} a13 the arc length from point 1 to point 3 (degrees);
   *   it can be negative.
   **********************************************************************/
  l.GeodesicLine.prototype.SetArc = function(a13) {
    var r;
    this.a13 = a13;
    r = this.GenPosition(true, this.a13, g.DISTANCE);
    this.s13 = 0 + r.s12;       // the 0+ converts undefined into NaN
  };

})(GeographicLib.Geodesic, GeographicLib.GeodesicLine, GeographicLib.Math);


/*
 * PolygonArea.js
 * Transcription of PolygonArea.[ch]pp into JavaScript.
 *
 * See the documentation for the C++ class.  The conversion is a literal
 * conversion from C++.
 *
 * The algorithms are derived in
 *
 *    Charles F. F. Karney,
 *    Algorithms for geodesics, J. Geodesy 87, 43-55 (2013);
 *    https://doi.org/10.1007/s00190-012-0578-z
 *    Addenda: https://geographiclib.sourceforge.io/geod-addenda.html
 *
 * Copyright (c) Charles Karney (2011-2017) <charles@karney.com> and licensed
 * under the MIT/X11 License.  For more information, see
 * https://geographiclib.sourceforge.io/
 */

// Load AFTER GeographicLib/Math.js and GeographicLib/Geodesic.js

(function(
  /**
   * @exports GeographicLib/PolygonArea
   * @description Compute the area of geodesic polygons via the
   *   {@link module:GeographicLib/PolygonArea.PolygonArea PolygonArea}
   *   class.
   */
  p, g, m, a) {

  var transit, transitdirect;
  transit = function(lon1, lon2) {
    // Return 1 or -1 if crossing prime meridian in east or west direction.
    // Otherwise return zero.
    var lon12, cross;
    // Compute lon12 the same way as Geodesic::Inverse.
    lon1 = m.AngNormalize(lon1);
    lon2 = m.AngNormalize(lon2);
    lon12 = m.AngDiff(lon1, lon2).s;
    cross = lon1 <= 0 && lon2 > 0 && lon12 > 0 ? 1 :
      (lon2 <= 0 && lon1 > 0 && lon12 < 0 ? -1 : 0);
    return cross;
  };

  // an alternate version of transit to deal with longitudes in the direct
  // problem.
  transitdirect = function(lon1, lon2) {
    // We want to compute exactly
    //   int(floor(lon2 / 360)) - int(floor(lon1 / 360))
    // Since we only need the parity of the result we can use std::remquo but
    // this is buggy with g++ 4.8.3 and requires C++11.  So instead we do
    lon1 = lon1 % 720.0; lon2 = lon2 % 720.0;
    return ( ((lon2 >= 0 && lon2 < 360) || lon2 < -360 ? 0 : 1) -
             ((lon1 >= 0 && lon1 < 360) || lon1 < -360 ? 0 : 1) );
  };

  /**
   * @class
   * @property {number} a the equatorial radius (meters).
   * @property {number} f the flattening.
   * @property {bool} polyline whether the PolygonArea object describes a
   *   polyline or a polygon.
   * @property {number} num the number of vertices so far.
   * @property {number} lat the current latitude (degrees).
   * @property {number} lon the current longitude (degrees).
   * @summary Initialize a PolygonArea object.
   * @classdesc Computes the area and perimeter of a geodesic polygon.
   *   This object is usually instantiated by
   *   {@link module:GeographicLib/Geodesic.Geodesic#Polygon Geodesic.Polygon}.
   * @param {object} geod a {@link module:GeographicLib/Geodesic.Geodesic
   *   Geodesic} object.
   * @param {bool} [polyline = false] if true the new PolygonArea object
   *   describes a polyline instead of a polygon.
   */
  p.PolygonArea = function(geod, polyline) {
    this._geod = geod;
    this.a = this._geod.a;
    this.f = this._geod.f;
    this._area0 = 4 * Math.PI * geod._c2;
    this.polyline = !polyline ? false : polyline;
    this._mask = g.LATITUDE | g.LONGITUDE | g.DISTANCE |
          (this.polyline ? g.NONE : g.AREA | g.LONG_UNROLL);
    if (!this.polyline)
      this._areasum = new a.Accumulator(0);
    this._perimetersum = new a.Accumulator(0);
    this.Clear();
  };

  /**
   * @summary Clear the PolygonArea object, setting the number of vertices to
   *   0.
   */
  p.PolygonArea.prototype.Clear = function() {
    this.num = 0;
    this._crossings = 0;
    if (!this.polyline)
      this._areasum.Set(0);
    this._perimetersum.Set(0);
    this._lat0 = this._lon0 = this.lat = this.lon = Number.NaN;
  };

  /**
   * @summary Add the next vertex to the polygon.
   * @param {number} lat the latitude of the point (degrees).
   * @param {number} lon the longitude of the point (degrees).
   * @description This adds an edge from the current vertex to the new vertex.
   */
  p.PolygonArea.prototype.AddPoint = function(lat, lon) {
    var t;
    if (this.num === 0) {
      this._lat0 = this.lat = lat;
      this._lon0 = this.lon = lon;
    } else {
      t = this._geod.Inverse(this.lat, this.lon, lat, lon, this._mask);
      this._perimetersum.Add(t.s12);
      if (!this.polyline) {
        this._areasum.Add(t.S12);
        this._crossings += transit(this.lon, lon);
      }
      this.lat = lat;
      this.lon = lon;
    }
    ++this.num;
  };

  /**
   * @summary Add the next edge to the polygon.
   * @param {number} azi the azimuth at the current the point (degrees).
   * @param {number} s the length of the edge (meters).
   * @description This specifies the new vertex in terms of the edge from the
   *   current vertex.
   */
  p.PolygonArea.prototype.AddEdge = function(azi, s) {
    var t;
    if (this.num) {
      t = this._geod.Direct(this.lat, this.lon, azi, s, this._mask);
      this._perimetersum.Add(s);
      if (!this.polyline) {
        this._areasum.Add(t.S12);
        this._crossings += transitdirect(this.lon, t.lon2);
      }
      this.lat = t.lat2;
      this.lon = t.lon2;
    }
    ++this.num;
  };

  /**
   * @summary Compute the perimeter and area of the polygon.
   * @param {bool} reverse if true then clockwise (instead of
   *   counter-clockwise) traversal counts as a positive area.
   * @param {bool} sign if true then return a signed result for the area if the
   *   polygon is traversed in the "wrong" direction instead of returning the
   *   area for the rest of the earth.
   * @returns {object} r where r.number is the number of vertices, r.perimeter
   *   is the perimeter (meters), and r.area (only returned if polyline is
   *   false) is the area (meters<sup>2</sup>).
   * @description If the object is a polygon (and not a polygon), the perimeter
   *   includes the length of a final edge connecting the current point to the
   *   initial point.  If the object is a polyline, then area is nan.  More
   *   points can be added to the polygon after this call.
   */
  p.PolygonArea.prototype.Compute = function(reverse, sign) {
    var vals = {number: this.num}, t, tempsum, crossings;
    if (this.num < 2) {
      vals.perimeter = 0;
      if (!this.polyline)
        vals.area = 0;
      return vals;
    }
    if (this.polyline) {
      vals.perimeter = this._perimetersum.Sum();
      return vals;
    }
    t = this._geod.Inverse(this.lat, this.lon, this._lat0, this._lon0,
                           this._mask);
    vals.perimeter = this._perimetersum.Sum(t.s12);
    tempsum = new a.Accumulator(this._areasum);
    tempsum.Add(t.S12);
    crossings = this._crossings + transit(this.lon, this._lon0);
    if (crossings & 1)
      tempsum.Add( (tempsum.Sum() < 0 ? 1 : -1) * this._area0/2 );
    // area is with the clockwise sense.  If !reverse convert to
    // counter-clockwise convention.
    if (!reverse)
      tempsum.Negate();
    // If sign put area in (-area0/2, area0/2], else put area in [0, area0)
    if (sign) {
      if (tempsum.Sum() > this._area0/2)
        tempsum.Add( -this._area0 );
      else if (tempsum.Sum() <= -this._area0/2)
        tempsum.Add( +this._area0 );
    } else {
      if (tempsum.Sum() >= this._area0)
        tempsum.Add( -this._area0 );
      else if (tempsum < 0)
        tempsum.Add( -this._area0 );
    }
    vals.area = tempsum.Sum();
    return vals;
  };

  /**
   * @summary Compute the perimeter and area of the polygon with a tentative
   *   new vertex.
   * @param {number} lat the latitude of the point (degrees).
   * @param {number} lon the longitude of the point (degrees).
   * @param {bool} reverse if true then clockwise (instead of
   *   counter-clockwise) traversal counts as a positive area.
   * @param {bool} sign if true then return a signed result for the area if the
   *   polygon is traversed in the "wrong" direction instead of returning the
   * @returns {object} r where r.number is the number of vertices, r.perimeter
   *   is the perimeter (meters), and r.area (only returned if polyline is
   *   false) is the area (meters<sup>2</sup>).
   * @description A new vertex is *not* added to the polygon.
   */
  p.PolygonArea.prototype.TestPoint = function(lat, lon, reverse, sign) {
    var vals = {number: this.num + 1}, t, tempsum, crossings, i;
    if (this.num === 0) {
      vals.perimeter = 0;
      if (!this.polyline)
        vals.area = 0;
      return vals;
    }
    vals.perimeter = this._perimetersum.Sum();
    tempsum = this.polyline ? 0 : this._areasum.Sum();
    crossings = this._crossings;
    for (i = 0; i < (this.polyline ? 1 : 2); ++i) {
      t = this._geod.Inverse(
       i === 0 ? this.lat : lat, i === 0 ? this.lon : lon,
       i !== 0 ? this._lat0 : lat, i !== 0 ? this._lon0 : lon,
       this._mask);
      vals.perimeter += t.s12;
      if (!this.polyline) {
        tempsum += t.S12;
        crossings += transit(i === 0 ? this.lon : lon,
                               i !== 0 ? this._lon0 : lon);
      }
    }

    if (this.polyline)
      return vals;

    if (crossings & 1)
      tempsum += (tempsum < 0 ? 1 : -1) * this._area0/2;
    // area is with the clockwise sense.  If !reverse convert to
    // counter-clockwise convention.
    if (!reverse)
      tempsum *= -1;
    // If sign put area in (-area0/2, area0/2], else put area in [0, area0)
    if (sign) {
      if (tempsum > this._area0/2)
        tempsum -= this._area0;
      else if (tempsum <= -this._area0/2)
        tempsum += this._area0;
    } else {
      if (tempsum >= this._area0)
        tempsum -= this._area0;
      else if (tempsum < 0)
        tempsum += this._area0;
    }
    vals.area = tempsum;
    return vals;
  };

  /**
   * @summary Compute the perimeter and area of the polygon with a tentative
   *   new edge.
   * @param {number} azi the azimuth of the edge (degrees).
   * @param {number} s the length of the edge (meters).
   * @param {bool} reverse if true then clockwise (instead of
   *   counter-clockwise) traversal counts as a positive area.
   * @param {bool} sign if true then return a signed result for the area if the
   *   polygon is traversed in the "wrong" direction instead of returning the
   * @returns {object} r where r.number is the number of vertices, r.perimeter
   *   is the perimeter (meters), and r.area (only returned if polyline is
   *   false) is the area (meters<sup>2</sup>).
   * @description A new vertex is *not* added to the polygon.
   */
  p.PolygonArea.prototype.TestEdge = function(azi, s, reverse, sign) {
    var vals = {number: this.num ? this.num + 1 : 0}, t, tempsum, crossings;
    if (this.num === 0)
      return vals;
    vals.perimeter = this._perimetersum.Sum() + s;
    if (this.polyline)
      return vals;

    tempsum = this._areasum.Sum();
    crossings = this._crossings;
    t = this._geod.Direct(this.lat, this.lon, azi, s, this._mask);
    tempsum += t.S12;
    crossings += transitdirect(this.lon, t.lon2);
    t = this._geod.Inverse(t.lat2, t.lon2, this._lat0, this._lon0, this._mask);
    vals.perimeter += t.s12;
    tempsum += t.S12;
    crossings += transit(t.lon2, this._lon0);

    if (crossings & 1)
      tempsum += (tempsum < 0 ? 1 : -1) * this._area0/2;
    // area is with the clockwise sense.  If !reverse convert to
    // counter-clockwise convention.
    if (!reverse)
      tempsum *= -1;
    // If sign put area in (-area0/2, area0/2], else put area in [0, area0)
    if (sign) {
      if (tempsum > this._area0/2)
        tempsum -= this._area0;
      else if (tempsum <= -this._area0/2)
        tempsum += this._area0;
    } else {
      if (tempsum >= this._area0)
        tempsum -= this._area0;
      else if (tempsum < 0)
        tempsum += this._area0;
    }
    vals.area = tempsum;
    return vals;
  };

})(GeographicLib.PolygonArea, GeographicLib.Geodesic,
   GeographicLib.Math, GeographicLib.Accumulator);


function pj_qsfn(sinphi, e, one_es) {
  var EPS = 1e-7;
  var con;
  if (e >= EPS) {
    con = e * sinphi;
    // Proj.4 check for div0 and returns HUGE_VAL
    // this returns +/- Infinity; effect should be same
    return (one_es * (sinphi / (1 - con * con) -
       (0.5 / e) * log ((1 - con) / (1 + con))));
  } else
    return (sinphi + sinphi);
}


function pj_msfn(sinphi, cosphi, es) {
  return (cosphi / sqrt (1 - es * sinphi * sinphi));
}


pj_add(pj_aea, 'aea', 'Albers Equal Area', 'Conic Sph&Ell\nlat_1= lat_2=');
pj_add(pj_leac, 'leac', 'Lambert Equal Area Conic', 'Conic, Sph&Ell\nlat_1= south');

function pj_aea(P) {
  var phi1 = pj_param(P.params, "rlat_1");
  var phi2 = pj_param(P.params, "rlat_2");
  pj_aea_init(P, phi1, phi2);
}

function pj_leac(P) {
  var phi1 = pj_param(P.params, "rlat_1");
  var phi2 = pj_param(P.params, "bsouth") ? -M_HALFPI : M_HALFPI;
  pj_aea_init(P, phi1, phi2);
}

function pj_aea_init(P, phi1, phi2) {
  var ec, n, c, dd, n2, rho0, rho, en, ellips,
      cosphi, sinphi, secant, ml2, m2, ml1, m1;

  P.fwd = e_fwd;
  P.inv = e_inv;

  if (fabs(phi1 + phi2) < EPS10) e_error(-21);
  n = sinphi = sin(phi1);
  cosphi = cos(phi1);
  secant = fabs(phi1 - phi2) >= EPS10;
  if ((ellips = (P.es > 0))) {
    en = pj_enfn(P.es);
    m1 = pj_msfn(sinphi, cosphi, P.es);
    ml1 = pj_qsfn(sinphi, P.e, P.one_es);
    if (secant) { /* secant cone */
      sinphi = sin(phi2);
      cosphi = cos(phi2);
      m2 = pj_msfn(sinphi, cosphi, P.es);
      ml2 = pj_qsfn(sinphi, P.e, P.one_es);
      // Ignoring Proj.4 div0 check (above checks should prevent this)
      n = (m1 * m1 - m2 * m2) / (ml2 - ml1);
    }
    ec = 1 - 0.5 * P.one_es * log((1 - P.e) / (1 + P.e)) / P.e;
    c = m1 * m1 + n * ml1;
    dd = 1 / n;
    rho0 = dd * sqrt(c - n * pj_qsfn(sin(P.phi0), P.e, P.one_es));
  } else {
    if (secant) n = 0.5 * (n + sin(phi2));
    n2 = n + n;
    c = cosphi * cosphi + n2 * sinphi;
    dd = 1 / n;
    rho0 = dd * sqrt(c - n2 * sin(P.phi0));
  }

  function e_fwd(lp, xy) {
    var lam = lp.lam;
    var rho;
    if ((rho = c - (ellips ? n * pj_qsfn(sin(lp.phi),
      P.e, P.one_es) : n2 * sin(lp.phi))) < 0) f_error();
    rho = dd * sqrt(rho);
    xy.x = rho * sin(lam *= n);
    xy.y = rho0 - rho * cos(lam);
  }

  function e_inv(xy, lp) {
    var TOL7 = 1e-7,
        x = xy.x,
        y = rho0 - xy.y,
        rho = hypot(x, y);
    if (rho != 0) {
      if (n < 0) {
        rho = -rho;
        x = -x;
        y = -y;
      }
      lp.phi = rho / dd;
      if (ellips) {
        lp.phi = (c - lp.phi * lp.phi) / n;
        if (fabs(ec - fabs(lp.phi)) > TOL7) {
          if ((lp.phi = phi1_(lp.phi, P.e, P.one_es)) == HUGE_VAL)
            i_error();
        } else
          lp.phi = lp.phi < 0 ? -M_HALFPI : M_HALFPI;
      } else if (fabs(lp.phi = (c - lp.phi * lp.phi) / n2) <= 1)
        lp.phi = asin(lp.phi);
      else
        lp.phi = lp.phi < 0 ? -M_HALFPI : M_HALFPI;
      lp.lam = atan2(x, y) / n;
    } else {
      lp.lam = 0;
      lp.phi = n > 0 ? M_HALFPI : -M_HALFPI;
    }
  }

  /* determine latitude angle phi-1 */
  function phi1_(qs, Te, Tone_es) {
    var N_ITER = 15,
        EPSILON = 1e-7,
        TOL = 1e-10;
    var Phi, sinpi, cospi, con, com, dphi, i;
    Phi = asin (0.5 * qs);
    if (Te < EPSILON)
      return Phi;
    i = N_ITER;
    do {
      sinpi = sin(Phi);
      cospi = cos(Phi);
      con = Te * sinpi;
      com = 1 - con * con;
      dphi = 0.5 * com * com / cospi * (qs / Tone_es -
         sinpi / com + 0.5 / Te * log ((1 - con) / (1 + con)));
      Phi += dphi;
    } while (fabs(dphi) > TOL && --i);
    return i ? Phi : HUGE_VAL;
  }
}



function pj_enfn(es) {
  var C00 = 1,
      C02 = 0.25,
      C04 = 0.046875,
      C06 = 0.01953125,
      C08 = 0.01068115234375,
      C22 = 0.75,
      C44 = 0.46875,
      C46 = 0.01302083333333333333,
      C48 = 0.00712076822916666666,
      C66 = 0.36458333333333333333,
      C68 = 0.00569661458333333333,
      C88 = 0.3076171875;
  var en = [], t;
  en[0] = C00 - es * (C02 + es * (C04 + es * (C06 + es * C08)));
  en[1] = es * (C22 - es * (C04 + es * (C06 + es * C08)));
  en[2] = (t = es * es) * (C44 - es * (C46 + es * C48));
  en[3] = (t *= es) * (C66 - es * C68);
  en[4] = t * es * C88;
  return en;
}

function pj_mlfn(phi, sphi, cphi, en) {
  cphi *= sphi;
  sphi *= sphi;
  return (en[0] * phi - cphi * (en[1] + sphi*(en[2] + sphi*(en[3] + sphi*en[4]))));
}

function pj_inv_mlfn(arg, es, en) {
  var EPS = 1e-11,
      MAX_ITER = 10,
      EN_SIZE = 5;

  var k = 1 / (1 - es),
      s, t, phi;

  phi = arg;
  for (var i = MAX_ITER; i>0; --i) { /* rarely goes over 2 iterations */
    s = sin(phi);
    t = 1 - es * s * s;
    phi -= t = (pj_mlfn(phi, s, cos(phi), en) - arg) * (t * sqrt(t)) * k;
    if (fabs(t) < EPS) {
      return phi;
    }
  }
  pj_ctx_set_errno( ctx, -17 );
  return phi;
}



function aasin(v) {
  var ONE_TOL = 1.00000000000001;
  var av = fabs(v);
  if (av >= 1) {
    if (av > ONE_TOL) pj_ctx_set_errno(-19);
    return v < 0 ? -M_HALFPI : M_HALFPI;
  }
  return asin(v);
}

function aacos(v) {
  var ONE_TOL = 1.00000000000001;
  var av = fabs(v);
  if (av >= 1) {
    if (av > ONE_TOL) pj_ctx_set_errno(-19);
    return (v < 0 ? M_PI : 0);
  }
  return acos(v);
}

function asqrt(v) { return ((v <= 0) ? 0 : sqrt(v)); }

function aatan2(n, d) {
  var ATOL = 1e-50;
  return ((fabs(n) < ATOL && fabs(d) < ATOL) ? 0 : atan2(n,d));
}


pj_add(pj_aeqd, 'aeqd', 'Azimuthal Equidistant', 'Azi, Sph&Ell\nlat_0 guam');

function pj_aeqd(P) {
  var EPS10 = 1.e-10,
      TOL = 1.e-14,
      N_POLE = 0,
      S_POLE = 1,
      EQUIT = 2,
      OBLIQ = 3;

  var sinph0, cosph0, M1, N1, Mp, He, G, mode, en, g;
  P.phi0 = pj_param(P.params, "rlat_0");
  if (fabs(fabs(P.phi0) - M_HALFPI) < EPS10) {
    mode = P.phi0 < 0 ? S_POLE : N_POLE;
    sinph0 = P.phi0 < 0 ? -1 : 1;
    cosph0 = 0;
  } else if (fabs(P.phi0) < EPS10) {
    mode = EQUIT;
    sinph0 = 0;
    cosph0 = 1;
  } else {
    mode = OBLIQ;
    sinph0 = sin(P.phi0);
    cosph0 = cos(P.phi0);
  }
  if (!P.es) {
    P.inv = s_inv;
    P.fwd = s_fwd;
  } else {
    g = new GeographicLib.Geodesic.Geodesic(P.a, P.es / (1 + sqrt(P.one_es)));
    en = pj_enfn(P.es);
    if (pj_param(P.params, "bguam")) {
      M1 = pj_mlfn(P.phi0, sinph0, cosph0, en);
      P.inv = e_guam_inv;
      P.fwd = e_guam_fwd;
    } else {
      switch (mode) {
        case N_POLE:
          Mp = pj_mlfn(M_HALFPI, 1, 0, en);
          break;
        case S_POLE:
          Mp = pj_mlfn(-M_HALFPI, -1, 0, en);
          break;
        case EQUIT:
        case OBLIQ:
          P.inv = e_inv;
          P.fwd = e_fwd;
          N1 = 1 / sqrt(1 - P.es * sinph0 * sinph0);
          G = sinph0 * (He = P.e / sqrt(P.one_es));
          He *= cosph0;
          break;
      }
      P.inv = e_inv;
      P.fwd = e_fwd;
    }
  }

  function e_fwd(lp, xy) {
    var coslam, cosphi, sinphi, rho;
    var azi1, azi2, s12;
    var lam1, phi1, lam2, phi2;
    var vars;

    coslam = cos(lp.lam);
    cosphi = cos(lp.phi);
    sinphi = sin(lp.phi);
    switch (mode) {
      case N_POLE:
        coslam = - coslam;
        /* falls through */
      case S_POLE:
        xy.x = (rho = fabs(Mp - pj_mlfn(lp.phi, sinphi, cosphi, en))) *
            sin(lp.lam);
        xy.y = rho * coslam;
        break;
      case EQUIT:
      case OBLIQ:
        if (fabs(lp.lam) < EPS10 && fabs(lp.phi - P.phi0) < EPS10) {
            xy.x = xy.y = 0;
            break;
        }
        phi1 = P.phi0 / DEG_TO_RAD; lam1 = P.lam0 / DEG_TO_RAD;
        phi2 = lp.phi / DEG_TO_RAD;  lam2 = (lp.lam+P.lam0) / DEG_TO_RAD;
        vars = g.Inverse(phi1, lam1, phi2, lam2, g.AZIMUTH); // , &s12, &azi1, &azi2);
        azi1 = vars.azi1 * DEG_TO_RAD;
        s12 = vars.s12;
        xy.x = s12 * sin(azi1) / P.a;
        xy.y = s12 * cos(azi1) / P.a;
        break;
    }
  }

  function e_inv(xy, lp) {
    var c, azi1, azi2, s12, x2, y2, lat1, lon1, lat2, lon2;
    var vars;
    if ((c = hypot(xy.x, xy.y)) < EPS10) {
      lp.phi = P.phi0;
      lp.lam = 0;
      return (lp);
    }
    if (mode == OBLIQ || mode == EQUIT) {
      x2 = xy.x * P.a;
      y2 = xy.y * P.a;
      lat1 = P.phi0 / DEG_TO_RAD;
      lon1 = P.lam0 / DEG_TO_RAD;
      azi1 = atan2(x2, y2) / DEG_TO_RAD;
      s12 = sqrt(x2 * x2 + y2 * y2);
      vars = g.Direct(lat1, lon1, azi1, s12, g.STANDARD); // , &lat2, &lon2, &azi2);
      lp.phi = vars.lat2 * DEG_TO_RAD;
      lp.lam = vars.lon2 * DEG_TO_RAD;
      lp.lam -= P.lam0;
    } else { /* Polar */
      lp.phi = pj_inv_mlfn(mode == N_POLE ? Mp - c : Mp + c,
          P.es, en);
      lp.lam = atan2(xy.x, mode == N_POLE ? -xy.y : xy.y);
    }
  }

  function s_fwd(lp, xy) {
    var coslam, cosphi, sinphi;
    sinphi = sin(lp.phi);
    cosphi = cos(lp.phi);
    coslam = cos(lp.lam);
    switch (mode) {
      case EQUIT:
      case OBLIQ:
        if (mode == EQUIT) {
          xy.y = cosphi * coslam;
        } else {
          xy.y = sinph0 * sinphi + cosph0 * cosphi * coslam;
        }
        if (fabs(fabs(xy.y) - 1) < TOL)
            if (xy.y < 0) f_error();
            else xy.x = xy.y = 0;
        else {
          xy.y = acos(xy.y);
          xy.y /= sin(xy.y);
          xy.x = xy.y * cosphi * sin(lp.lam);
          xy.y *= (mode == EQUIT) ? sinphi :
              cosph0 * sinphi - sinph0 * cosphi * coslam;
        }
        break;
      case N_POLE:
        lp.phi = -lp.phi;
        coslam = -coslam;
        /* falls through */
      case S_POLE:
        if (fabs(lp.phi - M_HALFPI) < EPS10) f_error();
        xy.x = (xy.y = (M_HALFPI + lp.phi)) * sin(lp.lam);
        xy.y *= coslam;
        break;
    }
  }

  function s_inv(xy, lp) {
    var x = xy.x, y = xy.y;
    var cosc, c_rh, sinc;
    if ((c_rh = hypot(x, y)) > M_PI) {
        if (c_rh - EPS10 > M_PI) i_error();
        c_rh = M_PI;
    } else if (c_rh < EPS10) {
      lp.phi = P.phi0;
      lp.lam = 0;
      return;
    }
    if (mode == OBLIQ || mode == EQUIT) {
      sinc = sin(c_rh);
      cosc = cos(c_rh);
      if (mode == EQUIT) {
        lp.phi = aasin(y * sinc / c_rh);
        x *= sinc;
        y = cosc * c_rh;
      } else {
        lp.phi = aasin(cosc * sinph0 + y * sinc * cosph0 / c_rh);
        y = (cosc - sinph0 * sin(lp.phi)) * c_rh;
        x *= sinc * cosph0;
      }
      lp.lam = y == 0 ? 0 : atan2(x, y);
    } else if (mode == N_POLE) {
      lp.phi = M_HALFPI - c_rh;
      lp.lam = atan2(x, -y);
    } else {
      lp.phi = c_rh - M_HALFPI;
      lp.lam = atan2(x, y);
    }
  }

  function e_guam_fwd(lp, xy) {
    var cosphi, sinphi, t;
    cosphi = cos(lp.phi);
    sinphi = sin(lp.phi);
    t = 1 / sqrt(1 - P.es * sinphi * sinphi);
    xy.x = lp.lam * cosphi * t;
    xy.y = pj_mlfn(lp.phi, sinphi, cosphi, en) - M1 +
        0.5 * lp.lam * lp.lam * cosphi * sinphi * t;
  }

  function e_guam_inv(xy, lp) {
    var x2, t, i;
    x2 = 0.5 * xy.x * xy.x;
    lp.phi = P.phi0;
    for (i = 0; i < 3; ++i) {
      t = P.e * sin(lp.phi);
      lp.phi = pj_inv_mlfn(M1 + xy.y -
        x2 * tan(lp.phi) * (t = sqrt(1 - t * t)), P.es, en);
    }
    lp.lam = xy.x * t / cos(lp.phi);
  }
}


pj_add(pj_airy, 'airy', 'Airy', 'Misc Sph, no inv.\nno_cut lat_b=');

function pj_airy(P) {
  var EPS = 1e-10,
      N_POLE = 0,
      S_POLE = 1,
      EQUIT = 2,
      OBLIQ = 3,
      p_halfphi, sinph0, cosph0, Cb, mode, no_cut, beta;

  P.es = 0;
  P.fwd = s_fwd;

  no_cut = pj_param(P.params, "bno_cut");
  beta = 0.5 * (M_HALFPI - pj_param(P.params, "rlat_b"));
  if (fabs(beta) < EPS)
    Cb = -0.5;
  else {
    Cb = 1/tan(beta);
    Cb *= Cb * log(cos(beta));
  }

  if (fabs(fabs(P.phi0) - M_HALFPI) < EPS)
    if (P.phi0 < 0) {
      p_halfpi = -M_HALFPI;
      mode = S_POLE;
    } else {
      p_halfpi =  M_HALFPI;
      mode = N_POLE;
    }
  else {
    if (fabs(P.phi0) < EPS)
      mode = EQUIT;
    else {
      mode = OBLIQ;
      sinph0 = sin(P.phi0);
      cosph0 = cos(P.phi0);
    }
  }

  function s_fwd(lp, xy) {
    var sinlam, coslam, cosphi, sinphi, t, s, Krho, cosz;
    sinlam = sin(lp.lam);
    coslam = cos(lp.lam);
    switch (mode) {
      case EQUIT:
      case OBLIQ:
        sinphi = sin(lp.phi);
        cosphi = cos(lp.phi);
        cosz = cosphi * coslam;
        if (mode == OBLIQ)
          cosz = sinph0 * sinphi + cosph0 * cosz;
        if (!no_cut && cosz < -EPS)
          f_error();
        if (fabs(s = 1 - cosz) > EPS) {
          t = 0.5 * (1 + cosz);
          Krho = -log(t)/s - Cb / t;
        } else {
          Krho = 0.5 - Cb;
        }
        xy.x = Krho * cosphi * sinlam;
        if (mode == OBLIQ)
          xy.y = Krho * (cosph0 * sinphi - sinph0 * cosphi * coslam);
        else
          xy.y = Krho * sinphi;
        break;
      case S_POLE:
      case N_POLE:
        lp.phi = fabs(p_halfpi - lp.phi);
        if (!no_cut && (lp.phi - EPS) > M_HALFPI)
          f_error();
        if ((lp.phi *= 0.5) > EPS) {
          t = tan(lp.phi);
          Krho = -2*(log(cos(lp.phi)) / t + t * Cb);
          xy.x = Krho * sinlam;
          xy.y = Krho * coslam;
          if (mode == N_POLE)
            xy.y = -xy.y;
        } else
          xy.x = xy.y = 0;
    }
  }
}


pj_add(pj_wintri, 'wintri', 'Winkel Tripel', 'Misc Sph\nlat_1');
pj_add(pj_aitoff, 'aitoff', 'Aitoff', 'Misc Sph');

function pj_wintri(P) {
  var Q = P.opaque = {mode: 1};
  if (pj_param(P.params, "tlat_1")) {
    if ((Q.cosphi1 = cos(pj_param(P.params, "rlat_1"))) === 0) {
      e_error(-22);
    }
  } else { /* 50d28' or acos(2/pi) */
    Q.cosphi1 = 0.636619772367581343;
  }
  pj_aitoff(P);
}

function pj_aitoff(P) {
  var Q = P.opaque || {mode: 0};

  P.inv = s_inv;
  P.fwd = s_fwd;
  P.es = 0;

  function s_fwd(lp, xy) {
    var c, d;
    if((d = acos(cos(lp.phi) * cos(c = 0.5 * lp.lam)))) {/* basic Aitoff */
      xy.x = 2 * d * cos(lp.phi) * sin(c) * (xy.y = 1 / sin(d));
      xy.y *= d * sin(lp.phi);
    } else
      xy.x = xy.y = 0;
    if (Q.mode) { /* Winkel Tripel */
      xy.x = (xy.x + lp.lam * Q.cosphi1) * 0.5;
      xy.y = (xy.y + lp.phi) * 0.5;
    }
  }

  function s_inv(xy, lp) {
    var MAXITER = 10,
        MAXROUND = 20,
        EPSILON = 1e-12,
        round = 0,
        iter, D, C, f1, f2, f1p, f1l, f2p, f2l, dp, dl, sl, sp, cp, cl, x, y;

    if ((fabs(xy.x) < EPSILON) && (fabs(xy.y) < EPSILON )) {
      lp.phi = 0;
      lp.lam = 0;
      return;
    }

    /* intial values for Newton-Raphson method */
    lp.phi = xy.y; lp.lam = xy.x;
    do {
      iter = 0;
      do {
        sl = sin(lp.lam * 0.5); cl = cos(lp.lam * 0.5);
        sp = sin(lp.phi); cp = cos(lp.phi);
        D = cp * cl;
        C = 1 - D * D;
        D = acos(D) / pow(C, 1.5);
        f1 = 2 * D * C * cp * sl;
        f2 = D * C * sp;
        f1p = 2 * (sl * cl * sp * cp / C - D * sp * sl);
        f1l = cp * cp * sl * sl / C + D * cp * cl * sp * sp;
        f2p = sp * sp * cl / C + D * sl * sl * cp;
        f2l = 0.5 * (sp * cp * sl / C - D * sp * cp * cp * sl * cl);
        if (Q.mode) { /* Winkel Tripel */
          f1 = 0.5 * (f1 + lp.lam * Q.cosphi1);
          f2 = 0.5 * (f2 + lp.phi);
          f1p *= 0.5;
          f1l = 0.5 * (f1l + Q.cosphi1);
          f2p = 0.5 * (f2p + 1);
          f2l *= 0.5;
        }
        f1 -= xy.x; f2 -= xy.y;
        dl = (f2 * f1p - f1 * f2p) / (dp = f1p * f2l - f2p * f1l);
        dp = (f1 * f2l - f2 * f1l) / dp;
        while (dl > M_PI) dl -= M_PI; /* set to interval [-M_PI, M_PI]  */
        while (dl < -M_PI) dl += M_PI; /* set to interval [-M_PI, M_PI]  */
        lp.phi -= dp; lp.lam -= dl;
      } while ((fabs(dp) > EPSILON || fabs(dl) > EPSILON) && (iter++ < MAXITER));
      if (lp.phi > M_HALFPI) lp.phi -= 2*(lp.phi-M_HALFPI); /* correct if symmetrical solution for Aitoff */
      if (lp.phi < -M_HALFPI) lp.phi -= 2*(lp.phi+M_HALFPI); /* correct if symmetrical solution for Aitoff */
      if ((fabs(fabs(lp.phi) - M_HALFPI) < EPSILON) && (!Q.mode)) lp.lam = 0; /* if pole in Aitoff, return longitude of 0 */

      /* calculate x,y coordinates with solution obtained */
      if((D = acos(cos(lp.phi) * cos(C = 0.5 * lp.lam)))) {/* Aitoff */
        x = 2 * D * cos(lp.phi) * sin(C) * (y = 1 / sin(D));
        y *= D * sin(lp.phi);
      } else
        x = y = 0;
      if (Q.mode) { /* Winkel Tripel */
        x = (x + lp.lam * Q.cosphi1) * 0.5;
        y = (y + lp.phi) * 0.5;
      }
    /* if too far from given values of x,y, repeat with better approximation of phi,lam */
    } while (((fabs(xy.x-x) > EPSILON) || (fabs(xy.y-y) > EPSILON)) && (round++ < MAXROUND));

    if (iter == MAXITER && round == MAXROUND) {
      // not ported: warning message
      // fprintf(stderr, "Warning: Accuracy of 1e-12 not reached. Last increments: dlat=%e and dlon=%e\n", dp, dl);
    }
  }
}


pj_add(pj_august, 'august', 'August Epicycloidal', 'Misc Sph, no inv.');

function pj_august(P) {
  P.fwd = s_fwd;
  P.es = 0;

  function s_fwd(lp, xy) {
    var M = 4 / 3;
    var lam = lp.lam;
    var t, c1, c, x1, x12, y1, y12;
    t = tan(0.5 * lp.phi);
    c1 = sqrt(1 - t * t);
    c = 1 + c1 * cos(lam *= 0.5);
    x1 = sin(lam) *  c1 / c;
    y1 =  t / c;
    xy.x = M * x1 * (3 + (x12 = x1 * x1) - 3 * (y12 = y1 *  y1));
    xy.y = M * y1 * (3 + 3 * x12 - y12);
  }
}


pj_add(pj_apian, 'apian', 'Apian Globular I', 'Misc Sph, no inv.');
pj_add(pj_ortel, 'ortel', 'Ortelius Oval', 'Misc Sph, no inv.');
pj_add(pj_bacon, 'bacon', 'Bacon Globular', 'Misc Sph, no inv.');

function pj_bacon(P) {
  pj_bacon_init(P, true, false);
}

function pj_apian(P) {
  pj_bacon_init(P, false, false);
}

function pj_ortel(P) {
  pj_bacon_init(P, false, true);
}

function pj_bacon_init(P, bacn, ortl) {
  P.es = 0;
  P.fwd = s_fwd;

  function s_fwd(lp, xy) {
    var HLFPI2 = 2.46740110027233965467; /* (pi/2)^2 */
    var EPS = 1e-10;
    var ax, f;
    xy.y = bacn ? M_HALFPI * sin(lp.phi) : lp.phi;
    if ((ax = fabs(lp.lam)) >= EPS) {
      if (ortl && ax >= M_HALFPI)
        xy.x = sqrt(HLFPI2 - lp.phi * lp.phi + EPS) + ax - M_HALFPI;
      else {
        f = 0.5 * (HLFPI2 / ax + ax);
        xy.x = ax - f + sqrt(f * f - xy.y * xy.y);
      }
      if (lp.lam < 0) xy.x = - xy.x;
    } else
      xy.x = 0;
  }
}



/*
  Created by Jacques Bertin in 1953, this projection was the go-to choice
  of the French cartographic school when they wished to represent phenomena
  on a global scale.

  Formula designed by Philippe Rivière, 2017.
  https://visionscarto.net/bertin-projection-1953
  Port to PROJ by Philippe Rivière, 21 September 2018
  Port to JavaScript by Matthew Bloch October 2018
*/
pj_add(pj_bertin1953, 'bertin1953', 'Bertin 1953', 'Misc., Sph., NoInv.');

function pj_bertin1953(P) {
  var cos_delta_phi, sin_delta_phi, cos_delta_gamma, sin_delta_gamma;

  P.es = 0;
  P.fwd = s_fwd;
  P.lam0 = 0;
  P.phi0 = DEG_TO_RAD * -42;

  cos_delta_phi = cos(P.phi0);
  sin_delta_phi = sin(P.phi0);
  cos_delta_gamma = 1;
  sin_delta_gamma = 0;

  function s_fwd(lp, xy) {
    var fu = 1.4, k = 12, w = 1.68, d;
    /* Rotate */
    var cosphi, x, y, z, z0;
    lp.lam += DEG_TO_RAD * -16.5;
    cosphi = cos(lp.phi);
    x = cos(lp.lam) * cosphi;
    y = sin(lp.lam) * cosphi;
    z = sin(lp.phi);
    z0 = z * cos_delta_phi + x * sin_delta_phi;
    lp.lam = atan2(y * cos_delta_gamma - z0 * sin_delta_gamma,
       x * cos_delta_phi - z * sin_delta_phi);
    z0 = z0 * cos_delta_gamma + y * sin_delta_gamma;
    lp.phi = asin(z0);
    lp.lam = adjlon(lp.lam);

    /* Adjust pre-projection */
    if (lp.lam + lp.phi < -fu) {
      d = (lp.lam - lp.phi + 1.6) * (lp.lam + lp.phi + fu) / 8;
      lp.lam += d;
      lp.phi -= 0.8 * d * sin(lp.phi + M_PI / 2);
    }

    /* Project with Hammer (1.68,2) */
    cosphi = cos(lp.phi);
    d = sqrt(2/(1 + cosphi * cos(lp.lam / 2)));
    xy.x = w * d * cosphi * sin(lp.lam / 2);
    xy.y = d * sin(lp.phi);

    /* Adjust post-projection */
    d = (1 - cos(lp.lam * lp.phi)) / k;
    if (xy.y < 0) {
      xy.x *= 1 + d;
    }
    if (xy.y > 0) {
      xy.y *= 1 + d / 1.5 * xy.x * xy.x;
    }

    return xy;
  }
}


pj_add(pj_boggs, 'boggs', 'Boggs Eumorphic', 'PCyl., no inv., Sph.');

function pj_boggs(P) {
  var NITER = 20,
      EPS = 1e-7,
      ONETOL = 1.000001,
      M_SQRT2 = sqrt(2),
      FXC = 2.00276,
      FXC2 = 1.11072,
      FYC = 0.49931;
  P.fwd = s_fwd;
  P.es = 0;

  function s_fwd(lp, xy) {
    var theta, th1, c, i;
    theta = lp.phi;
    if (fabs(fabs(lp.phi) - M_HALFPI) < EPS)
      xy.x = 0;
    else {
      c = sin(theta) * M_PI;
      for (i = NITER; i; --i) {
        theta -= th1 = (theta + sin(theta) - c) /
          (1 + cos(theta));
        if (fabs(th1) < EPS) break;
      }
      theta *= 0.5;
      xy.x = FXC * lp.lam / (1 / cos(lp.phi) + FXC2 / cos(theta));
    }
    xy.y = FYC * (lp.phi + M_SQRT2 * sin(theta));
  }
}


pj_add(pj_bonne, 'bonne', 'Bonne (Werner lat_1=90)', 'Conic Sph&Ell\nlat_1=');

function pj_bonne(P) {
  var EPS10 = 1e-10;
  var phi1, cphi1, am1, m1, en, c;

  phi1 = pj_param(P.params, "rlat_1");
  if (fabs(phi1) < EPS10) e_error(-23);
  if (P.es) {
    en = pj_enfn(P.es);
    m1 = pj_mlfn(phi1, am1 = sin(phi1),
      c = cos(phi1), en);
    am1 = c / (sqrt(1 - P.es * am1 * am1) * am1);
    P.inv = e_inv;
    P.fwd = e_fwd;
  } else {
    if (fabs(phi1) + EPS10 >= M_HALFPI)
      cphi1 = 0;
    else
      cphi1 = 1 / tan(phi1);
    P.inv = s_inv;
    P.fwd = s_fwd;
  }

  function e_fwd(lp, xy) {
    var rh, E, c;
    rh = am1 + m1 - pj_mlfn(lp.phi, E = sin(lp.phi), c = cos(lp.phi), en);
    E = c * lp.lam / (rh * sqrt(1 - P.es * E * E));
    xy.x = rh * sin(E);
    xy.y = am1 - rh * cos(E);
  }

  function e_inv(xy, lp) {
    var s, rh;
    rh = hypot(xy.x, xy.y = am1 - xy.y);
    lp.phi = pj_inv_mlfn(am1 + m1 - rh, P.es, en);
    if ((s = fabs(lp.phi)) < M_HALFPI) {
      s = sin(lp.phi);
      lp.lam = rh * atan2(xy.x, xy.y) * sqrt(1 - P.es * s * s) / cos(lp.phi);
    } else if (fabs(s - M_HALFPI) <= EPS10)
      lp.lam = 0;
    else i_error();
  }

  function s_fwd(lp, xy) {
    var E, rh;
    rh = cphi1 + phi1 - lp.phi;
    if (fabs(rh) > EPS10) {
      xy.x = rh * sin(E = lp.lam * cos(lp.phi) / rh);
      xy.y = cphi1 - rh * cos(E);
    } else
      xy.x = xy.y = 0;
  }

  function s_inv(xy, lp) {
    var rh = hypot(xy.x, xy.y = cphi1 - xy.y);
    lp.phi = cphi1 + phi1 - rh;
    if (fabs(lp.phi) > M_HALFPI) i_error();
    if (fabs(fabs(lp.phi) - M_HALFPI) <= EPS10)
      lp.lam = 0;
    else
      lp.lam = rh * atan2(xy.x, xy.y) / cos(lp.phi);
  }
}


pj_add(pj_cass, 'cass', 'Cassini', 'Cyl, Sph&Ell');

function pj_cass(P) {
  var C1 = 0.16666666666666666666,
      C2 = 0.00833333333333333333,
      C3 = 0.04166666666666666666,
      C4 = 0.33333333333333333333,
      C5 = 0.06666666666666666666;
  var m0, en;

  if (P.es) {
    en = pj_enfn(P.es);
    m0 = pj_mlfn(P.phi0,  sin(P.phi0),  cos(P.phi0), en);
    P.fwd = e_fwd;
    P.inv = e_inv;
  } else {
    P.fwd = s_fwd;
    P.inv = s_inv;
  }

  function e_fwd(lp, xy) {
    var n, t, a1, c, a2, tn;
    xy.y = pj_mlfn(lp.phi, n = sin(lp.phi), c = cos(lp.phi), en);

    n  = 1/sqrt(1 - P.es * n*n);
    tn = tan(lp.phi); t = tn * tn;
    a1 = lp.lam * c;
    c *= P.es * c / (1 - P.es);
    a2 = a1 * a1;

    xy.x = n * a1 * (1 - a2 * t * (C1 - (8 - t + 8 * c) * a2 * C2));
    xy.y -= m0 - n * tn * a2 * (0.5 + (5 - t + 6 * c) * a2 * C3);
  }

  function e_inv(xy, lp) {
    var n, t, r, dd, d2, tn, ph1;
    ph1 = pj_inv_mlfn (m0 + xy.y, P.es, en);
    tn  = tan(ph1); t = tn*tn;
    n   = sin(ph1);
    r   = 1 / (1 - P.es * n * n);
    n   = sqrt (r);
    r  *= (1 - P.es) * n;
    dd  = xy.x / n;
    d2  = dd * dd;
    lp.phi = ph1 - (n * tn / r) * d2 *(0.5 - (1 + 3 * t) * d2 * C3);
    lp.lam = dd * (1 + t * d2 * (-C4 + (1 + 3 * t) * d2 * C5)) / cos(ph1);
  }

  function s_fwd(lp, xy) {
    xy.x  =  asin(cos(lp.phi) * sin(lp.lam));
    xy.y  =  atan2(tan(lp.phi), cos(lp.lam)) - P.phi0;
  }

  function s_inv(xy, lp) {
    var dd =  xy.y + P.phi0;
    lp.phi = asin(sin(dd) * cos(xy.x));
    lp.lam = atan2(tan(xy.x), cos(dd));
  }
}



function pj_authset(es) {
  var P00 = 0.33333333333333333333 /*   1 /     3 */,
      P01 = 0.17222222222222222222 /*  31 /   180 */,
      P02 = 0.10257936507936507937 /* 517 /  5040 */,
      P10 = 0.06388888888888888888 /*  23 /   360 */,
      P11 = 0.06640211640211640212 /* 251 /  3780 */,
      P20 = 0.01677689594356261023 /* 761 / 45360 */,
      APA = [];
  var t;

  APA[0] = es * P00;
  t = es * es;
  APA[0] += t * P01;
  APA[1] = t * P10;
  t *= es;
  APA[0] += t * P02;
  APA[1] += t * P11;
  APA[2] = t * P20;
  return APA;
}

function pj_authlat(beta, APA) {
  var t = beta + beta;
  return(beta + APA[0] * sin(t) + APA[1] * sin(t+t) + APA[2] * sin(t+t+t));
}


pj_add(pj_cea, 'cea', 'Equal Area Cylindrical', 'Cyl, Sph&Ell\nlat_ts=');

function pj_cea(P) {
  var t = 0, qp, apa;
  if (pj_param(P.params, "tlat_ts")) {
    P.k0 = cos(t = pj_param(P.params, "rlat_ts"));
    if (P.k0 < 0) {
      e_error(-24);
    }
  }
  if (P.es) {
    t = sin(t);
    P.k0 /= sqrt(1 - P.es * t * t);
    P.e = sqrt(P.es);
    if (!(apa = pj_authset(P.es))) e_error_0();
    qp = pj_qsfn(1, P.e, P.one_es);
    P.fwd = e_fwd;
    P.inv = e_inv;
  } else {
    P.fwd = s_fwd;
    P.inv = s_inv;
  }

  function e_fwd(lp, xy) {
    xy.x = P.k0 * lp.lam;
    xy.y = 0.5 * pj_qsfn(sin (lp.phi), P.e, P.one_es) / P.k0;
  }

  function e_inv(xy, lp) {
    lp.phi = pj_authlat(asin(2 * xy.y * P.k0 / qp), apa);
    lp.lam = xy.x / P.k0;
  }

  function s_fwd(lp, xy) {
    xy.x = P.k0 * lp.lam;
    xy.y = sin(lp.phi) / P.k0;
  }

  function s_inv(xy, lp) {
    var x = xy.x, y = xy.y;
    var t;
    if ((t = fabs(y *= P.k0)) - EPS10 <= 1) {
      if (t >= 1)
        lp.phi = y < 0 ? -M_HALFPI : M_HALFPI;
      else
        lp.phi = asin(y);
      lp.lam = x / P.k0;
    } else i_error();
  }
}


pj_add(pj_chamb, 'chamb', 'Chamberlin Trimetric', 'Misc Sph, no inv.\nlat_1= lon_1= lat_2= lon_2= lat_3= lon_3=');

function pj_chamb(P) {
  var THIRD  = 1/3,
      TOL = 1e-9,
      c = [],
      x0, y0,
      v, beta_0, beta_1, beta_2, i, j;

  for (i = 0; i < 3; ++i) { /* get control point locations */
    c[i] = {p: {}};
    c[i].phi = pj_param(P.params, 'rlat_' + (i+1));
    c[i].lam = pj_param(P.params, 'rlon_' + (i+1));
    c[i].lam = adjlon(c[i].lam - P.lam0);
    c[i].cosphi = cos(c[i].phi);
    c[i].sinphi = sin(c[i].phi);
  }
  for (i = 0; i < 3; ++i) { /* inter ctl pt. distances and azimuths */
    j = i == 2 ? 0 : i + 1;
    c[i].v = vect(c[j].phi - c[i].phi, c[i].cosphi, c[i].sinphi,
        c[j].cosphi, c[j].sinphi, c[j].lam - c[i].lam);

    if (!c[i].v.r) e_error(-25);
    /* co-linearity problem ignored for now */
  }
  beta_0 = lc(c[0].v.r, c[2].v.r, c[1].v.r);
  beta_1 = lc(c[0].v.r, c[1].v.r, c[2].v.r);
  beta_2 = M_PI - beta_0;
  y0 = 2 * (c[0].p.y = c[1].p.y = c[2].v.r * sin(beta_0));
  c[2].p.y = 0;
  c[0].p.x = -(c[1].p.x = 0.5 * c[0].v.r);
  x0 = c[2].p.x = c[0].p.x + c[2].v.r * cos(beta_0);

  P.es = 0;
  P.fwd = s_fwd;

  function s_fwd(lp, xy) {
    var sinphi, cosphi, a, i, j, x, y;
    var v = [];
    sinphi = sin(lp.phi);
    cosphi = cos(lp.phi);
    for (i = 0; i < 3; ++i) { /* dist/azimiths from control */
      v[i] = vect(lp.phi - c[i].phi, c[i].cosphi, c[i].sinphi,
          cosphi, sinphi, lp.lam - c[i].lam);
      if (!v[i].r)
          break;
      v[i].Az = adjlon(v[i].Az - c[i].v.Az);
    }
    if (i < 3) { /* current point at control point */
      x = c[i].p.x;
      y = c[i].p.y;
    } else { /* point mean of intercepts */
      x = x0;
      y = y0;
      for (i = 0; i < 3; ++i) {
        j = i == 2 ? 0 : i + 1;
        a = lc(c[i].v.r, v[i].r, v[j].r);
        if (v[i].Az < 0)
          a = -a;
        if (! i) { /* coord comp unique to each arc */
          x += v[i].r * cos(a);
          y -= v[i].r * sin(a);
        } else if (i == 1) {
          a = beta_1 - a;
          x -= v[i].r * cos(a);
          y -= v[i].r * sin(a);
        } else {
          a = beta_2 - a;
          x += v[i].r * cos(a);
          y += v[i].r * sin(a);
        }
      }
      x *= THIRD; /* mean of arc intercepts */
      y *= THIRD;
    }
    xy.x = x;
    xy.y = y;
  }

  function vect(dphi, c1, s1, c2, s2, dlam) {
    var v = {};
    var cdl, dp, dl;
    cdl = cos(dlam);
    if (fabs(dphi) > 1 || fabs(dlam) > 1)
      v.r = aacos(cs1 * s2 + c1 * c2 * cdl);
    else { /* more accurate for smaller distances */
      dp = sin(0.5 * dphi);
      dl = sin(0.5 * dlam);
      v.r = 2 * aasin(sqrt(dp * dp + c1 * c2 * dl * dl));
    }
    if (fabs(v.r) > TOL)
      v.Az = atan2(c2 * sin(dlam), c1 * s2 - s1 * c2 * cdl);
    else
      v.r = v.Az = 0;
    return v;
  }

  /* law of cosines */
  function lc(b, c, a) {
    return aacos(0.5 * (b * b + c * c - a * a) / (b * c));
  }
}


pj_add(pj_crast, 'crast', 'Craster Parabolic (Putnins P4)', 'PCyl., Sph.');

function pj_crast(P) {
  var XM = 0.97720502380583984317;
  var RXM = 1.02332670794648848847;
  var YM = 3.06998012383946546542;
  var RYM = 0.32573500793527994772;
  var THIRD = 1/3;
  P.inv = s_inv;
  P.fwd = s_fwd;
  P.es = 0;

  function s_fwd(lp, xy) {
    lp.phi *= THIRD;
    xy.x = XM * lp.lam * (2 * cos(lp.phi + lp.phi) - 1);
    xy.y = YM * sin(lp.phi);
  }

  function s_inv(xy, lp) {
    lp.phi = 3 * asin(xy.y * RYM);
    lp.lam = xy.x * RXM / (2 * cos((lp.phi + lp.phi) * THIRD) - 1);
  }
}


pj_add(pj_cupola, 'cupola', 'Cupola', 'PCyl., Sph., NoInv.');

// Source: https://www.tandfonline.com/eprint/EE7Y8RK4GXA4ITWUTQPY/full?target=10.1080/23729333.2020.1862962
// See also: http://www.at-a-lanta.nl/weia/cupola.html

function pj_cupola(P) {
  var de = 0.5253;  // part of the equator on intermediate sphere, default = 1
  var dp = 0.7264;  // sin of angle of polar line, default = 1
  var ri = 1 / Math.sqrt(de * dp);
  var he = 0.4188; // height of equator (can be negative, default = 0)
  var se = 0.9701; // stretch in plane, default = 1
  var phi0 = 22 * DEG_TO_RAD; // phi of projection center
  // center of projection on intermediate sphere
  var pc = calcP(phi0);
  var qc = calcQ(0);
  var spc = sin(pc);
  var cpc = cos(pc);

  // apply default central meridian
  if (!pj_param(P.params, 'tlon_0')) {
    P.lam0 = 11.023 * DEG_TO_RAD;
  }

  P.es = 0;
  P.fwd = s_fwd;

  function calcP(phi) {
    return asin(dp * sin(phi) + he * sqrt(de * dp));
  }

  function calcQ(lam) {
    return de * lam;
  }

  function s_fwd(lp, xy) {
    var p = calcP(lp.phi);
    var q = calcQ(lp.lam);
    var sp = sin(p);
    var cp = cos(p);
    var sqqc = sin(q - qc);
    var cqqc = cos(q - qc);
    var K = sqrt(2 / (1 + sin(pc) * sp + cpc * cp * cqqc));
    xy.x = ri * K * cp * sqqc * se;
    xy.y = ri * K * (cpc * sp - spc * cp * cqqc) / se;
  }
}


pj_add(pj_denoy, 'denoy', 'Denoyer Semi-Elliptical', 'PCyl, Sph., no inv.');

function pj_denoy(P) {
  P.fwd = s_fwd;
  P.es = 0;

  function s_fwd(lp, xy) {
    var C0 = 0.95;
    var C1 = -0.08333333333333333333;
    var C3 = 0.00166666666666666666;
    var D1 = 0.9;
    var D5 = 0.03;
    var lam = fabs(lp.lam);
    xy.y = lp.phi;
    xy.x = lp.lam;
    xy.x *= cos((C0 + lam * (C1 + lam * lam * C3)) *
            (lp.phi * (D1 + D5 * lp.phi * lp.phi * lp.phi * lp.phi)));

  }
}


pj_add(pj_eck1, 'eck1', 'Eckert I', 'PCyl Sph');
pj_add(pj_eck2, 'eck2', 'Eckert II', 'PCyl Sph');
pj_add(pj_eck3, 'eck3', 'Eckert III', 'PCyl Sph');
pj_add(pj_wag6, 'wag6', 'Wagner VI', 'PCyl Sph');
pj_add(pj_kav7, 'kav7', 'Kavraisky VII', 'PCyl Sph');
pj_add(pj_putp1, 'putp1', 'Putnins P1', 'PCyl Sph');
pj_add(pj_eck4, 'eck4', 'Eckert IV', 'PCyl Sph');
pj_add(pj_eck5, 'eck5', 'Eckert V', 'PCyl Sph');

function pj_eck1(P) {
  var FC = 0.92131773192356127802,
      RP = 0.31830988618379067154;
  P.es = 0;
  P.fwd = s_fwd;
  P.inv = s_inv;

  function s_fwd(lp, xy) {
    xy.x = FC * lp.lam * (1 - RP * fabs(lp.phi));
    xy.y = FC * lp.phi;
  }

  function s_inv(xy, lp) {
    lp.phi = xy.y / FC;
    lp.lam = xy.x / (FC * (1 - RP * fabs(lp.phi)));
  }
}

function pj_eck2(P) {
  var FXC = 0.46065886596178063902,
      FYC = 1.44720250911653531871,
      C13 = 0.33333333333333333333,
      ONEEPS = 1.0000001;
  P.es = 0;
  P.fwd = s_fwd;
  P.inv = s_inv;

  function s_fwd(lp, xy) {
    xy.x = FXC * lp.lam * (xy.y = sqrt(4 - 3 * sin(fabs(lp.phi))));
    xy.y = FYC * (2 - xy.y);
    if (lp.phi < 0) xy.y = -xy.y;
  }

  function s_inv(xy, lp) {
    lp.lam = xy.x / (FXC * (lp.phi = 2 - fabs(xy.y) / FYC));
    lp.phi = (4 - lp.phi * lp.phi) * C13;
    if (fabs(lp.phi) >= 1) {
      if (fabs(lp.phi) > ONEEPS) i_error();
      else
        lp.phi = lp.phi < 0 ? -M_HALFPI : M_HALFPI;
    } else
      lp.phi = asin(lp.phi);
    if (xy.y < 0)
      lp.phi = -lp.phi;
  }
}

function pj_eck3(P) {
  var Q = {
    C_x: 0.42223820031577120149,
    C_y: 0.84447640063154240298,
    A: 1,
    B: 0.4052847345693510857755
  };
  pj_eck3_init(P, Q);
}

function pj_kav7(P) {
  var Q = {
    C_x: 0.8660254037844,
    C_y: 1,
    A: 0,
    B: 0.30396355092701331433
  };
  pj_eck3_init(P, Q);
}

function pj_wag6(P) {
  var Q = {
    C_x: 0.94745,
    C_y: 0.94745,
    A: 0,
    B: 0.30396355092701331433
  };
  pj_eck3_init(P, Q);
}

function pj_putp1(P) {
  var Q = {
    C_x: 1.89490,
    C_y: 0.94745,
    A: -0.5,
    B: 0.30396355092701331433
  };
  pj_eck3_init(P, Q);
}

function pj_eck3_init(P, Q) {
  P.es = 0;
  P.fwd = s_fwd;
  P.inv = s_inv;

  function s_fwd(lp, xy) {
    xy.y = Q.C_y * lp.phi;
    xy.x = Q.C_x * lp.lam * (Q.A + asqrt(1 - Q.B * lp.phi * lp.phi));
  }

  function s_inv(xy, lp) {
    lp.phi = xy.y / Q.C_y;
    lp.lam = xy.x / (Q.C_x * (Q.A + asqrt(1 - Q.B * lp.phi * lp.phi)));
  }
}

function pj_eck4(P) {
  var C_x = 0.42223820031577120149,
      C_y = 1.32650042817700232218,
      RC_y = 0.75386330736002178205,
      C_p = 3.57079632679489661922,
      RC_p = 0.28004957675577868795,
      EPS = 1e-7,
      NITER = 6;

  P.es = 0;
  P.fwd = s_fwd;
  P.inv = s_inv;

  function s_fwd(lp, xy) {
    var p, V, s, c, i;
    p = C_p * sin(lp.phi);
    V = lp.phi * lp.phi;
    lp.phi *= 0.895168 + V * ( 0.0218849 + V * 0.00826809 );
    for (i = NITER; i; --i) {
      c = cos(lp.phi);
      s = sin(lp.phi);
      lp.phi -= V = (lp.phi + s * (c + 2) - p) /
          (1 + c * (c + 2) - s * s);
      if (fabs(V) < EPS)
        break;
    }
    if (!i) {
      xy.x = C_x * lp.lam;
      xy.y = lp.phi < 0 ? -C_y : C_y;
    } else {
      xy.x = C_x * lp.lam * (1 + cos(lp.phi));
      xy.y = C_y * sin(lp.phi);
    }
  }

  function s_inv(xy, lp) {
    var c;
    lp.phi = aasin(xy.y / C_y);
    lp.lam = xy.x / (C_x * (1 + (c = cos(lp.phi))));
    lp.phi = aasin((lp.phi + sin(lp.phi) * (c + 2)) / C_p);
  }
}

function pj_eck5(P) {
  var XF = 0.44101277172455148219,
      RXF = 2.26750802723822639137,
      YF = 0.88202554344910296438,
      RYF = 1.13375401361911319568;

  P.es = 0;
  P.fwd = s_fwd;
  P.inv = s_inv;

  function s_fwd(lp, xy) {
    xy.x = XF * (1 + cos(lp.phi)) * lp.lam;
    xy.y = YF * lp.phi;
  }

  function s_inv(xy, lp) {
    lp.lam = RXF * xy.x / (1 + cos(lp.phi = RYF * xy.y));
  }
}


pj_add(pj_eqc, 'eqc', 'Equidistant Cylindrical (Plate Caree)', 'Cyl, Sph\nlat_ts=[, lat_0=0]');

function pj_eqc(P) {
  var rc = cos(pj_param(P.params, "rlat_ts"));
  if (rc <= 0) e_error(-24);
  P.es = 0;
  P.fwd = s_fwd;
  P.inv = s_inv;

  function s_fwd(lp, xy) {
    xy.x = rc * lp.lam;
    xy.y = lp.phi -P.phi0;
  }

  function s_inv(xy, lp) {
    lp.lam = xy.x / rc;
    lp.phi = xy.y + P.phi0;
  }
}


pj_add(pj_eqdc, 'eqdc', 'Equidistant Conic', 'Conic, Sph&Ell\nlat_1= lat_2=');

function pj_eqdc(P) {
  var phi1, phi2, n, rho, rho0, c, en, ellips, cosphi, sinphi, secant;
  var ml1, m1;
  phi1 = pj_param(P.params, "rlat_1");
  phi2 = pj_param(P.params, "rlat_2");
  if (fabs(phi1 + phi2) < EPS10) e_error(-21);
  if (!(en = pj_enfn(P.es)))
      e_error_0();
  n = sinphi = sin(phi1);
  cosphi = cos(phi1);
  secant = fabs(phi1 - phi2) >= EPS10;
  if ((ellips = (P.es > 0)) ) {
    m1 = pj_msfn(sinphi, cosphi, P.es);
    ml1 = pj_mlfn(phi1, sinphi, cosphi, en);
    if (secant) { /* secant cone */
      sinphi = sin(phi2);
      cosphi = cos(phi2);
      n = (m1 - pj_msfn(sinphi, cosphi, P.es)) /
          (pj_mlfn(phi2, sinphi, cosphi, en) - ml1);
    }
    c = ml1 + m1 / n;
    rho0 = c - pj_mlfn(P.phi0, sin(P.phi0),
      cos(P.phi0), en);
  } else {
    if (secant)
       n = (cosphi - cos(phi2)) / (phi2 - phi1);
    c = phi1 + cos(phi1) / n;
    rho0 = c - P.phi0;
  }

  P.fwd = e_fwd;
  P.inv = e_inv;

  function e_fwd(lp, xy) {
    rho = c - (ellips ? pj_mlfn(lp.phi, sin(lp.phi),
        cos(lp.phi), en) : lp.phi);
    xy.x = rho * sin( lp.lam *= n );
    xy.y = rho0 - rho * cos(lp.lam);
  }

  function e_inv(xy, lp) {
    if ((rho = hypot(xy.x, xy.y = rho0 - xy.y)) != 0.0 ) {
      if (n < 0) {
        rho = -rho;
        xy.x = -xy.x;
        xy.y = -xy.y;
      }
      lp.phi = c - rho;
      if (ellips)
        lp.phi = pj_inv_mlfn(lp.phi, P.es, en);
      lp.lam = atan2(xy.x, xy.y) / n;
    } else {
      lp.lam = 0;
      lp.phi = n > 0 ? M_HALFPI : -M_HALFPI;
    }
  }
}


/**
 * Copyright 2018 Bernie Jenny, Monash University, Melbourne, Australia.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Equal Earth is a projection inspired by the Robinson projection, but unlike
 * the Robinson projection retains the relative size of areas. The projection
 * was designed in 2018 by Bojan Savric, Tom Patterson and Bernhard Jenny.
 *
 * Publication:
 * Bojan Savric, Tom Patterson & Bernhard Jenny (2018). The Equal Earth map
 * projection, International Journal of Geographical Information Science,
 * DOI: 10.1080/13658816.2018.1504949
 *
 * Code released August 2018
 * Ported to JavaScript and adapted for mapshaper-proj by Matthew Bloch August 2018
 */
pj_add(pj_eqearth, 'eqearth', 'Equal Earth', 'PCyl., Sph.');

function pj_eqearth(P) {
  var A1 = 1.340264,
      A2 = -0.081106,
      A3 = 0.000893,
      A4 = 0.003796,
      M = Math.sqrt(3) / 2.0;

  P.es = 0;
  P.fwd = s_fwd;
  P.inv = s_inv;

  function s_fwd(lp, xy) {
    var paramLat = Math.asin(M * Math.sin(lp.phi)),
        paramLatSq = paramLat * paramLat,
        paramLatPow6 = paramLatSq * paramLatSq * paramLatSq;
    xy.x = lp.lam * Math.cos(paramLat) /
            (M * (A1 + 3 * A2 * paramLatSq + paramLatPow6 * (7 * A3 + 9 * A4 * paramLatSq)));
    xy.y = paramLat * (A1 + A2 * paramLatSq + paramLatPow6 * (A3 + A4 * paramLatSq));
  }

  function s_inv(xy, lp) {
    var EPS = 1e-9,
        NITER = 12,
        paramLat = xy.y,
        paramLatSq, paramLatPow6, fy, fpy, dlat, i;

    for (i = 0; i < NITER; ++i) {
      paramLatSq = paramLat * paramLat;
      paramLatPow6 = paramLatSq * paramLatSq * paramLatSq;
      fy = paramLat * (A1 + A2 * paramLatSq + paramLatPow6 * (A3 + A4 * paramLatSq)) - xy.y;
      fpy = A1 + 3 * A2 * paramLatSq + paramLatPow6 * (7 * A3 + 9 * A4 * paramLatSq);
      paramLat -= dlat = fy / fpy;
      if (Math.abs(dlat) < EPS) {
          break;
      }
    }
    paramLatSq = paramLat * paramLat;
    paramLatPow6 = paramLatSq * paramLatSq * paramLatSq;
    lp.lam = M * xy.x * (A1 + 3 * A2 * paramLatSq + paramLatPow6 * (7 * A3 + 9 * A4 * paramLatSq)) /
            Math.cos(paramLat);
    lp.phi = Math.asin(Math.sin(paramLat) / M);
  }
}


pj_add(pj_etmerc, 'etmerc', 'Extended Transverse Mercator', 'Cyl, Sph\nlat_ts=(0)\nlat_0=(0)');

function pj_etmerc(P) {
  var cgb = [],
      cbg = [],
      utg = [],
      gtu = [],
      Qn, Zb, f, n, np, Z;
  if (P.es <= 0) e_error(-34);
  /* flattening */
  f = P.es / (1 + sqrt(1 - P.es)); /* Replaces: f = 1 - sqrt(1-P.es); */
  /* third flattening */
  np = n = f/(2 - f);
  /* COEF. OF TRIG SERIES GEO <-> GAUSS */
  /* cgb := Gaussian -> Geodetic, KW p190 - 191 (61) - (62) */
  /* cbg := Geodetic -> Gaussian, KW p186 - 187 (51) - (52) */
  /* PROJ_ETMERC_ORDER = 6th degree : Engsager and Poder: ICC2007 */
  cgb[0] = n*(2 + n*(-2/3 + n * (-2 + n*(116/45 + n * (26/45 + n*(-2854/675 ))))));
  cbg[0] = n*(-2 + n*( 2/3 + n*( 4/3 + n*(-82/45 + n*(32/45 + n*(4642/4725))))));
  np *= n;
  cgb[1] = np*(7/3 + n*(-8/5 + n*(-227/45 + n*(2704/315 + n*(2323/945)))));
  cbg[1] = np*(5/3 + n*(-16/15 + n*( -13/9 + n*(904/315 + n*(-1522/945)))));
  np *= n;
  /* n^5 coeff corrected from 1262/105 -> -1262/105 */
  cgb[2] = np*(56/15 + n*(-136/35 + n*(-1262/105 + n*(73814/2835))));
  cbg[2] = np*(-26/15 + n*(34/21 + n*(8/5 + n*(-12686/2835))));
  np *= n;
  /* n^5 coeff corrected from 322/35 -> 332/35 */
  cgb[3] = np*(4279/630 + n*(-332/35 + n*(-399572/14175)));
  cbg[3] = np*(1237/630 + n*(-12/5 + n*( -24832/14175)));
  np *= n;
  cgb[4] = np*(4174/315 + n*(-144838/6237));
  cbg[4] = np*(-734/315 + n*(109598/31185));
  np *= n;
  cgb[5] = np*(601676/22275);
  cbg[5] = np*(444337/155925);

  /* Constants of the projections */
  /* Transverse Mercator (UTM, ITM, etc) */
  np = n*n;
  /* Norm. mer. quad, K&W p.50 (96), p.19 (38b), p.5 (2) */
  Qn = P.k0/(1 + n) * (1 + np*(1/4 + np*(1/64 + np/256)));
  /* coef of trig series */
  /* utg := ell. N, E -> sph. N, E,  KW p194 (65) */
  /* gtu := sph. N, E -> ell. N, E,  KW p196 (69) */
  utg[0] = n*(-0.5 + n*( 2/3 + n*(-37/96 + n*( 1/360 + n*(81/512 + n*(-96199/604800))))));
  gtu[0] = n*(0.5 + n*(-2/3 + n*(5/16 + n*(41/180 + n*(-127/288 + n*(7891/37800))))));
  utg[1] = np*(-1/48 + n*(-1/15 + n*(437/1440 + n*(-46/105 + n*(1118711/3870720)))));
  gtu[1] = np*(13/48 + n*(-3/5 + n*(557/1440 + n*(281/630 + n*(-1983433/1935360)))));
  np *= n;
  utg[2] = np*(-17/480 + n*(37/840 + n*(209/4480 + n*(-5569/90720 ))));
  gtu[2] = np*(61/240 + n*(-103/140 + n*(15061/26880 + n*(167603/181440))));
  np *= n;
  utg[3] = np*(-4397/161280 + n*(11/504 + n*(830251/7257600)));
  gtu[3] = np*(49561/161280 + n*(-179/168 + n*(6601661/7257600)));
  np *= n;
  utg[4] = np*(-4583/161280 + n*(108847/3991680));
  gtu[4] = np*(34729/80640  + n*(-3418889/1995840));
  np *= n;
  utg[5] = np*(-20648693/638668800);
  gtu[5] = np*(212378941/319334400);

   /* Gaussian latitude value of the origin latitude */
  Z = gatg(cbg, P.phi0);

  /* Origin northing minus true northing at the origin latitude */
  /* i.e. true northing = N - P.Zb  */
  Zb = -Qn*(Z + clens(gtu, 2*Z));
  P.fwd = e_fwd;
  P.inv = e_inv;

  function e_fwd(lp, xy) {
    var sin_Cn, cos_Cn, cos_Ce, sin_Ce, tmp;
    var Cn = lp.phi, Ce = lp.lam;

    /* ell. LAT, LNG -> Gaussian LAT, LNG */
    Cn = gatg(cbg, Cn);
    /* Gaussian LAT, LNG -> compl. sph. LAT */
    sin_Cn = sin(Cn);
    cos_Cn = cos(Cn);
    sin_Ce = sin(Ce);
    cos_Ce = cos(Ce);
    Cn = atan2(sin_Cn, cos_Ce*cos_Cn);
    Ce = atan2(sin_Ce*cos_Cn, hypot(sin_Cn, cos_Cn*cos_Ce));
    /* compl. sph. N, E -> ell. norm. N, E */
    Ce = asinhy(tan(Ce));
    tmp = clenS(gtu, 2*Cn, 2*Ce);
    Cn += tmp[0];
    Ce += tmp[1];
    if (fabs (Ce) <= 2.623395162778) {
        xy.y  = Qn * Cn + Zb;  /* Northing */
        xy.x  = Qn * Ce;       /* Easting  */
    } else {
      xy.x = xy.y = HUGE_VAL;
    }
  }

  function e_inv(xy, lp) {
    var sin_Cn, cos_Cn, cos_Ce, sin_Ce, tmp;
    var Cn = xy.y, Ce = xy.x;
    /* normalize N, E */
    Cn = (Cn - Zb)/Qn;
    Ce = Ce/Qn;
    if (fabs(Ce) <= 2.623395162778) { /* 150 degrees */
      /* norm. N, E -> compl. sph. LAT, LNG */
      tmp = clenS(utg, 2*Cn, 2*Ce);
      Cn += tmp[0];
      Ce += tmp[1];
      Ce = atan(sinh(Ce)); /* Replaces: Ce = 2*(atan(exp(Ce)) - M_FORTPI); */
      /* compl. sph. LAT -> Gaussian LAT, LNG */
      sin_Cn = sin(Cn);
      cos_Cn = cos(Cn);
      sin_Ce = sin(Ce);
      cos_Ce = cos(Ce);
      Ce = atan2(sin_Ce, cos_Ce*cos_Cn);
      Cn = atan2(sin_Cn*cos_Ce, hypot(sin_Ce, cos_Ce*cos_Cn));
      /* Gaussian LAT, LNG -> ell. LAT, LNG */
      lp.phi = gatg (cgb, Cn);
      lp.lam = Ce;
    }
    else {
      lp.phi = lp.lam = HUGE_VAL;
    }
  }

  function log1py(x) {
    var y = 1 + x,
        z = y - 1;
    return z === 0 ? x : x * log(y) / z;
  }

  function asinhy(x) {
    var y = fabs(x);
    y = log1py(y * (1 + y/(hypot(1, y) + 1)));
    return x < 0 ? -y : y;
  }

  function gatg(pp, B) {
    var cos_2B = 2 * cos(2 * B),
        i = pp.length - 1,
        h1 = pp[i],
        h2 = 0,
        h;
    while (--i >= 0) {
      h = -h2 + cos_2B * h1 + pp[i];
      h2 = h1;
      h1 = h;
    }
    return (B + h * sin(2 * B));
  }

  function clens(pp, arg_r) {
    var r = 2 * cos(arg_r),
        i = pp.length - 1,
        hr1 = pp[i],
        hr2 = 0,
        hr;
    while (--i >= 0) {
      hr = -hr2 + r * hr1 + pp[i];
      hr2 = hr1;
      hr1 = hr;
    }
    return sin(arg_r) * hr;
  }

  function clenS(pp, arg_r, arg_i) {
    var sin_arg_r = sin(arg_r),
        cos_arg_r = cos(arg_r),
        sinh_arg_i = sinh(arg_i),
        cosh_arg_i = cosh(arg_i),
        r = 2 * cos_arg_r * cosh_arg_i,
        i = -2 * sin_arg_r * sinh_arg_i,
        j = pp.length - 1,
        hr = pp[j],
        hi1 = 0,
        hr1 = 0,
        hi = 0,
        hr2, hi2;
    while (--j >= 0) {
      hr2 = hr1;
      hi2 = hi1;
      hr1 = hr;
      hi1 = hi;
      hr = -hr2 + r*hr1 - i * hi1 + pp[j];
      hi = -hi2 + i*hr1 + r * hi1;
    }
    r = sin_arg_r * cosh_arg_i;
    i = cos_arg_r * sinh_arg_i;
    return [r * hr - i * hi, r * hi + i * hr];
  }
}


pj_add(pj_gall, 'gall', 'Gall (Gall Stereographic)', 'Cyl, Sph');

function pj_gall(P) {
  var YF = 1.70710678118654752440,
      XF = 0.70710678118654752440,
      RYF = 0.58578643762690495119,
      RXF = 1.41421356237309504880;

  P.fwd = s_fwd;
  P.inv = s_inv;
  P.es = 0;

  function s_fwd(lp, xy) {
    xy.x = XF * lp.lam;
    xy.y = YF * tan(0.5 * lp.phi);
  }

  function s_inv(xy, lp) {
    lp.lam = RXF * xy.x;
    lp.phi = 2 * atan(xy.y * RYF);
  }
}


pj_add(pj_geocent, 'geocent', 'Geocentric', '');

function pj_geocent(P) {
  P.is_geocent = true;
  P.x0 = 0;
  P.y0 = 0;

  P.fwd = function (lp, xy) {
    xy.x = lp.lam;
    xy.y = lp.phi;
  };

  P.inv = function(xy, lp) {
    lp.phi = xy.y;
    lp.lam = xy.x;
  };
}


// from

pj_add(pj_gilbert, 'gilbert', 'Gilbert Two World Perspective', 'PCyl., Sph., NoInv.\nlat_1=');

function pj_gilbert(P) {
  var lat1 = pj_param(P.params, 'tlat_1') ? pj_param(P.params, 'rlat_1') : 0,
      phi1 = phiprime(lat1),
      sp1 = sin(phi1),
      cp1 = cos(phi1);
  P.fwd = s_fwd;
  P.es = 0;

  function s_fwd(lp, xy) {
    var lam = lp.lam * 0.5,
        phi = phiprime(lp.phi),
        sp = sin(phi),
        cp = cos(phi),
        cl = cos(lam);
    if ((sp1*sp + cp1*cp*cl) >= 0) {
      xy.x = cp * sin(lam);
      xy.y = cp1 * sp - sp1 * cp * cl;
    } else {
      f_error();
    }
  }

  function phiprime(phi) {
    return aasin(tan(0.5 * phi));
  }
}


pj_add(pj_gins8, 'gins8', 'Ginsburg VIII (TsNIIGAiK)', 'PCyl, Sph., no inv.');

function pj_gins8(P) {
  P.fwd = s_fwd;
  P.es = 0;

  function s_fwd(lp, xy) {
    var Cl = 0.000952426;
    var Cp = 0.162388;
    var C12 = 0.08333333333333333;
    var t = lp.phi * lp.phi;
    xy.y = lp.phi * (1 + t * C12);
    xy.x = lp.lam * (1 - Cp * t);
    t = lp.lam * lp.lam;
    xy.x *= (0.87 - Cl * t * t);
  }
}


pj_add(pj_gn_sinu, 'gn_sinu', 'General Sinusoidal Series', 'PCyl, Sph.\nm= n=');
pj_add(pj_sinu, 'sinu', 'Sinusoidal (Sanson-Flamsteed)', 'PCyl, Sph&Ell');
pj_add(pj_eck6, 'eck6', 'Eckert VI', 'PCyl, Sph.\nm= n=');
pj_add(pj_mbtfps, 'mbtfps', 'McBryde-Thomas Flat-Polar Sinusoidal', 'PCyl, Sph.');

function pj_gn_sinu(P) {
  if (pj_param(P.params, 'tn'), pj_param(P.params, 'tm')) {
    pj_sinu_init(P, pj_param(P.params, 'dm'), pj_param(P.params, 'dn'));
  } else {
    e_error(-99);
  }
}

function pj_sinu(P) {
  var en;
  if (P.es) {
    en = pj_enfn(P.es);
    P.fwd = e_fwd;
    P.inv = e_inv;
  } else {
    pj_sinu_init(P, 0, 1);
  }

  function e_fwd(lp, xy) {
    var s, c;
    xy.y = pj_mlfn(lp.phi, s = sin(lp.phi), c = cos(lp.phi), en);
    xy.x = lp.lam * c / sqrt(1 - P.es * s * s);
  }

  function e_inv(xy, lp) {
    var s = fabs(lp.phi = pj_inv_mlfn(xy.y, P.es, en));
    if (s < M_HALFPI) {
        s = sin(lp.phi);
        lp.lam = xy.x * sqrt(1 - P.es * s * s) / cos(lp.phi);
    } else if ((s - EPS10) < M_HALFPI) {
        lp.lam = 0;
    } else {
        i_error();
    }
  }
}

function pj_eck6(P) {
  pj_sinu_init(P, 1, 2.570796326794896619231321691);
}

function pj_mbtfps(P) {
  pj_sinu_init(P, 0.5, 1.785398163397448309615660845);
}

function pj_sinu_init(P, m, n) {
  var MAX_ITER = 8,
      LOOP_TOL = 1e-7,
      C_x, C_y;
  C_x = (C_y = sqrt((m + 1) / n))/(m + 1);
  P.es = 0;
  P.fwd = s_fwd;
  P.inv = s_inv;

  function s_fwd(lp, xy) {
    var k, V, i;
    if (!m)
      lp.phi = n != 1 ? aasin(n * sin(lp.phi)): lp.phi;
    else {
        k = n * sin(lp.phi);
        for (i = MAX_ITER; i ; --i) {
            lp.phi -= V = (m * lp.phi + sin(lp.phi) - k) /
                (m + cos(lp.phi));
            if (fabs(V) < LOOP_TOL)
                break;
        }
        if (!i)
          f_error();
    }
    xy.x = C_x * lp.lam * (m + cos(lp.phi));
    xy.y = C_y * lp.phi;
  }

  function s_inv(xy, lp) {
    xy.y /= C_y;
    lp.phi = m ? aasin((m * xy.y + sin(xy.y)) / n) :
        ( n != 1 ? aasin(sin(xy.y) / n) : xy.y );
    lp.lam = xy.x / (C_x * (m + cos(xy.y)));
  }
}



pj_add(pj_gnom, 'gnom', 'Gnomonic', 'Azi, Sph.');

function pj_gnom(P) {
  var EPS10 = 1.e-10,
      N_POLE = 0,
      S_POLE = 1,
      EQUIT = 2,
      OBLIQ = 3;
  var sinphi0, cosph0, mode;
  if (fabs(fabs(P.phi0) - M_HALFPI) < EPS10) {
      mode = P.phi0 < 0 ? S_POLE : N_POLE;
  } else if (fabs(P.phi0) < EPS10) {
      mode = EQUIT;
  } else {
      mode = OBLIQ;
      sinph0 = sin(P.phi0);
      cosph0 = cos(P.phi0);
  }

  P.inv = s_inv;
  P.fwd = s_fwd;
  P.es = 0;

  function s_fwd(lp, xy) {
    var coslam, cosphi, sinphi;
    sinphi = sin(lp.phi);
    cosphi = cos(lp.phi);
    coslam = cos(lp.lam);

    switch (mode) {
        case EQUIT:
            xy.y = cosphi * coslam;
            break;
        case OBLIQ:
            xy.y = sinph0 * sinphi + cosph0 * cosphi * coslam;
            break;
        case S_POLE:
            xy.y = - sinphi;
            break;
        case N_POLE:
            xy.y = sinphi;
            break;
    }

    if (xy.y <= EPS10) f_error();

    xy.x = (xy.y = 1 / xy.y) * cosphi * sin(lp.lam);
    switch (mode) {
        case EQUIT:
            xy.y *= sinphi;
            break;
        case OBLIQ:
            xy.y *= cosph0 * sinphi - sinph0 * cosphi * coslam;
            break;
        case N_POLE:
            coslam = - coslam;
            /* falls through */
        case S_POLE:
            xy.y *= cosphi * coslam;
            break;
    }
  }

  function s_inv(xy, lp) {
    var x = xy.x, y = xy.y; // modified below
    var rh, cosz, sinz;
    rh = hypot(x, y);
    sinz = sin(lp.phi = atan(rh));
    cosz = sqrt(1 - sinz * sinz);

    if (fabs(rh) <= EPS10) {
        lp.phi = P.phi0;
        lp.lam = 0;
    } else {
        switch (mode) {
            case OBLIQ:
                lp.phi = cosz * sinph0 + y * sinz * cosph0 / rh;
                if (fabs(lp.phi) >= 1)
                    lp.phi = lp.phi > 0 ? M_HALFPI : -M_HALFPI;
                else
                    lp.phi = asin(lp.phi);
                y = (cosz - sinph0 * sin(lp.phi)) * rh;
                x *= sinz * cosph0;
                break;
            case EQUIT:
                lp.phi = y * sinz / rh;
                if (fabs(lp.phi) >= 1)
                    lp.phi = lp.phi > 0 ? M_HALFPI : -M_HALFPI;
                else
                    lp.phi = asin(lp.phi);
                y = cosz * rh;
                x *= sinz;
                break;
            case S_POLE:
                lp.phi -= M_HALFPI;
                break;
            case N_POLE:
                lp.phi = M_HALFPI - lp.phi;
                y = -y;
                break;
        }
        lp.lam = atan2(x, y);
    }
  }
}


pj_add(pj_moll, 'moll', 'Mollweide', 'PCyl Sph');
pj_add(pj_wag4, 'wag4', 'Wagner IV', 'PCyl Sph');
pj_add(pj_wag5, 'wag5', 'Wagner V', 'PCyl Sph');

function pj_moll(P) {
  pj_moll_init(P, pj_moll_init_Q(P, M_HALFPI));
}

function pj_wag4(P) {
  pj_moll_init(P, pj_moll_init_Q(P, M_PI/3));
}

function pj_wag5(P) {
  var Q = {
    C_x: 0.90977,
    C_y: 1.65014,
    C_p: 3.00896
  };
  pj_moll_init(P, Q);
}

function pj_moll_init_Q(P, p) {
  var sp = sin(p),
      p2 = p + p,
      r = sqrt(M_TWOPI * sp / (p2 + sin(p2)));
  return {
    C_x: 2 * r / M_PI,
    C_y: r / sp,
    C_p: p2 + sin(p2)
  };
}

function pj_moll_init(P, Q) {
  var MAX_ITER = 10,
      LOOP_TOL = 1e-7;
  P.fwd = s_fwd;
  P.inv = s_inv;
  P.es = 0;

  function s_fwd(lp, xy) {
    var k, V, i;
    k = Q.C_p * sin(lp.phi);
    for (i = MAX_ITER; i;--i) {
      lp.phi -= V = (lp.phi + sin(lp.phi) - k) /
        (1 + cos(lp.phi));
      if (fabs(V) < LOOP_TOL)
        break;
    }
    if (!i)
      lp.phi = (lp.phi < 0) ? -M_HALFPI : M_HALFPI;
    else
      lp.phi *= 0.5;
    xy.x = Q.C_x * lp.lam * cos(lp.phi);
    xy.y = Q.C_y * sin(lp.phi);
  }

  function s_inv(xy, lp) {
    lp.phi = aasin(xy.y / Q.C_y);
    lp.lam = xy.x / (Q.C_x * cos(lp.phi));
    // if (fabs(lp.lam) < M_PI) { // from Proj.4; fails for edge coordinates
    if (fabs(lp.lam) - M_PI < EPS10) { // allows inv projection of world layer
      lp.phi += lp.phi;
      lp.phi = aasin((lp.phi + sin(lp.phi)) / Q.C_p);
    } else {
      lp.lam = lp.phi = HUGE_VAL;
    }
  }
}


pj_add(pj_goode, 'goode', 'Goode Homolosine', 'PCyl, Sph.');

function pj_goode(P) {
  var Y_COR = 0.05280,
      PHI_LIM = 0.71093078197902358062,
      sinuFwd, sinuInv, mollFwd, mollInv;
  P.es = 0;
  pj_sinu(P);
  sinuFwd = P.fwd;
  sinuInv = P.inv;
  pj_moll(P);
  mollFwd = P.fwd;
  mollInv = P.inv;
  P.fwd = function(lp, xy) {
    if (fabs(lp.phi) < PHI_LIM) {
      sinuFwd(lp, xy);
    } else {
      mollFwd(lp, xy);
      xy.y -= lp.phi > 0 ? Y_COR : -Y_COR;
    }
  };
  P.inv = function(xy, lp) {
    if (fabs(xy.y) <= PHI_LIM) {
      sinuInv(xy, lp);
    } else {
      xy.y += xy.y > 0 ? Y_COR : -Y_COR;
      mollInv(xy, lp);
    }
  };
}


pj_add(pj_hammer, 'hammer', 'Hammer & Eckert-Greifendorff', 'Misc Sph,\nW= M=');

function pj_hammer(P) {
  var w, m, rm;
  var EPS = 1e-10;
  P.inv = s_inv;
  P.fwd = s_fwd;
  P.es = 0;

  if (pj_param(P.params, "tW")) {
    if ((w = fabs(pj_param(P.params, "dW"))) <= 0) e_error(-27);
  } else
    w = 0.5;
  if (pj_param(P.params, "tM")) {
      if ((m = fabs(pj_param(P.params, "dM"))) <= 0) e_error(-27);
  } else
      m = 1;
  rm = 1 / m;
  m /= w;

  function s_fwd(lp, xy) {
    var cosphi, d;
    d = sqrt(2/(1 + (cosphi = cos(lp.phi)) * cos(lp.lam *= w)));
    xy.x = m * d * cosphi * sin(lp.lam);
    xy.y = rm * d * sin(lp.phi);
  }

  function s_inv(xy, lp) {
    var z = sqrt(1 - 0.25*w*w*xy.x*xy.x - 0.25*xy.y*xy.y);
    if (fabs(2*z*z-1) < EPS) {
      lp.lam = HUGE_VAL;
      lp.phi = HUGE_VAL;
      pj_errno = -14;
    } else {
      lp.lam = aatan2(w * xy.x * z,2 * z * z - 1)/w;
      lp.phi = aasin(z * xy.y);
    }
  }
}


pj_add(pj_hatano, 'hatano', 'Hatano Asymmetrical Equal Area', 'PCyl., Sph.');

function pj_hatano(P) {
  var NITER = 20;
  var EPS = 1e-7;
  var ONETOL = 1.000001;
  var CN = 2.67595;
  var CS = 2.43763;
  var RCN = 0.37369906014686373063;
  var RCS = 0.41023453108141924738;
  var FYCN = 1.75859;
  var FYCS = 1.93052;
  var RYCN = 0.56863737426006061674;
  var RYCS = 0.51799515156538134803;
  var FXC = 0.85;
  var RXC = 1.17647058823529411764;

  P.inv = s_inv;
  P.fwd = s_fwd;
  P.es = 0;

  function s_fwd(lp, xy) {
    var th1, c;
    var i;
    c = sin(lp.phi) * (lp.phi < 0 ? CS : CN);
    for (i = NITER; i; --i) {
      lp.phi -= th1 = (lp.phi + sin(lp.phi) - c) / (1 + cos(lp.phi));
      if (fabs(th1) < EPS) break;
    }
    xy.x = FXC * lp.lam * cos(lp.phi *= 0.5);
    xy.y = sin(lp.phi) * (lp.phi < 0 ? FYCS : FYCN);
  }

  function s_inv(xy, lp) {
    var th = xy.y * (xy.y < 0 ? RYCS : RYCN);
    if (fabs(th) > 1) {
      if (fabs(th) > ONETOL) {
        i_error();
      } else {
        th = th > 0 ? M_HALFPI : -M_HALFPI;
      }
    } else {
      th = asin(th);
    }

    lp.lam = RXC * xy.x / cos(th);
    th += th;
    lp.phi = (th + sin(th)) * (xy.y < 0 ? RCS : RCN);
    if (fabs(lp.phi) > 1) {
      if (fabs(lp.phi) > ONETOL) {
        i_error();
      } else {
        lp.phi = lp.phi > 0 ? M_HALFPI : -M_HALFPI;
      }
    } else {
      lp.phi = asin(lp.phi);
    }
  }
}


pj_add(pj_healpix, 'healpix', 'HEALPix', 'Sph., Ellps.');
pj_add(pj_rhealpix, 'rhealpix', 'rHEALPix', 'Sph., Ellps.\nnorth_square= south_square=');

function pj_rhealpix(P) {
  pj_healpix(P, true);
}

function pj_healpix(P, rhealpix) {
  var R1 = [
    [0, -1],
    [1, 0]
  ];
  var R2 = [
    [-1, 0],
    [0, -1]
  ];
  var R3 = [
    [0, 1],
    [-1, 0]
  ];
  var IDENT = [
    [1, 0],
    [0, 1]
  ];
  var rot = [IDENT, R1, R2, R3, R3, R2, R1];
  var EPS = 1e-15;

  var north_square;
  var south_square;
  var qp;
  var apa;
  var vertsJit;

  if (rhealpix) {
    north_square = pj_param(P.params, "inorth_square");
    south_square = pj_param(P.params, "isouth_square");

    /* Check for valid north_square and south_square inputs. */
    if (north_square < 0 || north_square > 3) {
      e_error(-47);
    }
    if (south_square < 0 || south_square > 3) {
      e_error(-47);
    }
    vertsJit = [
      [-M_PI - EPS, M_FORTPI + EPS],
      [-M_PI + north_square * M_HALFPI - EPS, M_FORTPI + EPS],
      [-M_PI + north_square * M_HALFPI - EPS, 3 * M_FORTPI + EPS],
      [-M_PI + (north_square + 1.0) * M_HALFPI + EPS, 3 * M_FORTPI + EPS],
      [-M_PI + (north_square + 1.0) * M_HALFPI + EPS, M_FORTPI + EPS],
      [M_PI + EPS, M_FORTPI + EPS],
      [M_PI + EPS, -M_FORTPI - EPS],
      [-M_PI + (south_square + 1.0) * M_HALFPI + EPS, -M_FORTPI - EPS],
      [-M_PI + (south_square + 1.0) * M_HALFPI + EPS, -3 * M_FORTPI - EPS],
      [-M_PI + south_square * M_HALFPI - EPS, -3 * M_FORTPI - EPS],
      [-M_PI + south_square * M_HALFPI - EPS, -M_FORTPI - EPS],
      [-M_PI - EPS, -M_FORTPI - EPS]
    ];

    if (P.es != 0.0) {
      apa = pj_authset(P.es); /* For auth_lat(). */
      qp = pj_qsfn(1.0, P.e, P.one_es); /* For auth_lat(). */
      P.a = P.a * sqrt(0.5 * qp); /* Set P.a to authalic radius. */
      P.ra = 1.0 / P.a;
      P.fwd = e_rhealpix_forward;
      P.inv = e_rhealpix_inverse;
    } else {
      P.fwd = s_rhealpix_forward;
      P.inv = s_rhealpix_inverse;
    }

  } else { // healpix
    vertsJit = [
      [-M_PI - EPS, M_FORTPI],
      [-3 * M_FORTPI, M_HALFPI + EPS],
      [-M_HALFPI, M_FORTPI + EPS],
      [-M_FORTPI, M_HALFPI + EPS],
      [0.0, M_FORTPI + EPS],
      [M_FORTPI, M_HALFPI + EPS],
      [M_HALFPI, M_FORTPI + EPS],
      [3 * M_FORTPI, M_HALFPI + EPS],
      [M_PI + EPS, M_FORTPI],
      [M_PI + EPS, -M_FORTPI],
      [3 * M_FORTPI, -M_HALFPI - EPS],
      [M_HALFPI, -M_FORTPI - EPS],
      [M_FORTPI, -M_HALFPI - EPS],
      [0.0, -M_FORTPI - EPS],
      [-M_FORTPI, -M_HALFPI - EPS],
      [-M_HALFPI, -M_FORTPI - EPS],
      [-3 * M_FORTPI, -M_HALFPI - EPS],
      [-M_PI - EPS, -M_FORTPI]
    ];

    if (P.es != 0.0) {
      apa = pj_authset(P.es); /* For auth_lat(). */
      qp = pj_qsfn(1.0, P.e, P.one_es); /* For auth_lat(). */
      P.a = P.a * sqrt(0.5 * qp); /* Set P.a to authalic radius. */
      P.ra = 1.0 / P.a;
      P.fwd = e_healpix_forward;
      P.inv = e_healpix_inverse;
    } else {
      P.fwd = s_healpix_forward;
      P.inv = s_healpix_inverse;
    }
  }

  function s_healpix_forward(lp, xy) {
    healpix_sphere(lp, xy);
  }

  function e_healpix_forward(lp, xy) {
    lp.phi = auth_lat(P, lp.phi, 0);
    healpix_sphere(lp, xy);
  }

  function s_healpix_inverse(xy, lp) {
    if (!in_image(xy.x, xy.y)) {
      lp.lam = HUGE_VAL;
      lp.phi = HUGE_VAL;
      pj_ctx_set_errno(-15);
      return;
    }
    healpix_sphere_inverse(xy, lp);
  }

  function e_healpix_inverse(xy, lp) {
    if (!in_image(xy.x, xy.y)) {
      lp.lam = HUGE_VAL;
      lp.phi = HUGE_VAL;
      pj_ctx_set_errno(-15);
      return;
    }
    healpix_sphere_inverse(xy, lp);
    lp.phi = auth_lat(P, lp.phi, 1);
  }

  function s_rhealpix_forward(lp, xy) {
    healpix_sphere(lp, xy);
    combine_caps(xy, north_square, south_square, 0);
  }

  function e_rhealpix_forward(lp, xy) {
    lp.phi = auth_lat(P, lp.phi, 0);
    healpix_sphere(lp, xy);
    return combine_caps(xy, north_square, south_square, 0);
  }

  function s_rhealpix_inverse(xy, lp) {
    if (!in_image(xy.x, xy.y)) {
      lp.lam = HUGE_VAL;
      lp.phi = HUGE_VAL;
      pj_ctx_set_errno(-15);
      return;
    }
    combine_caps(xy, north_square, south_square, 1);
    healpix_sphere_inverse(xy, lp);
  }

  function e_rhealpix_inverse(xy, lp) {
    if (!in_image(xy.x, xy.y)) {
      lp.lam = HUGE_VAL;
      lp.phi = HUGE_VAL;
      pj_ctx_set_errno(-15);
      return;
    }
    combine_caps(xy, north_square, south_square, 1);
    healpix_sphere_inverse(xy, lp);
    lp.phi = auth_lat(P, lp.phi, 1);
  }

  function healpix_sphere(lp, xy) {
    var lam = lp.lam;
    var phi = lp.phi;
    var phi0 = asin(2.0 / 3.0);

    /* equatorial region */
    if (fabs(phi) <= phi0) {
      xy.x = lam;
      xy.y = 3 * M_PI / 8 * sin(phi);
    } else {
      var lamc;
      var sigma = sqrt(3 * (1 - fabs(sin(phi))));
      var cn = floor(2 * lam / M_PI + 2);
      if (cn >= 4) {
        cn = 3;
      }
      lamc = -3 * M_FORTPI + M_HALFPI * cn;
      xy.x = lamc + (lam - lamc) * sigma;
      xy.y = pj_sign(phi) * M_FORTPI * (2 - sigma);
    }
  }

  function healpix_sphere_inverse(xy, lp) {
    var x = xy.x;
    var y = xy.y;
    var y0 = M_FORTPI;

    /* Equatorial region. */
    if (fabs(y) <= y0) {
      lp.lam = x;
      lp.phi = asin(8 * y / (3 * M_PI));
    } else if (fabs(y) < M_HALFPI) {
      var cn = floor(2 * x / M_PI + 2);
      var xc, tau;
      if (cn >= 4) {
        cn = 3;
      }
      xc = -3 * M_FORTPI + M_HALFPI * cn;
      tau = 2.0 - 4 * fabs(y) / M_PI;
      lp.lam = xc + (x - xc) / tau;
      lp.phi = pj_sign(y) * asin(1.0 - pow(tau, 2) / 3.0);
    } else {
      lp.lam = -M_PI;
      lp.phi = pj_sign(y) * M_HALFPI;
    }
  }

  function pj_sign(v) {
    return v > 0 ? 1 : (v < 0 ? -1 : 0);
  }

  /**
   * Return the index of the matrix in ROT.
   * @param index ranges from -3 to 3.
   */
  function get_rotate_index(index) {
    switch (index) {
      case 0:
        return 0;
      case 1:
        return 1;
      case 2:
        return 2;
      case 3:
        return 3;
      case -1:
        return 4;
      case -2:
        return 5;
      case -3:
        return 6;
    }
    return 0;
  }

  /**
   * Return true if point (testx, testy) lies in the interior of the polygon
   * determined by the vertices in vert, and return false otherwise.
   * See http://paulbourke.net/geometry/polygonmesh/ for more details.
   * @param nvert the number of vertices in the polygon.
   * @param vert the (x, y)-coordinates of the polygon's vertices
   **/
  function pnpoly(vert, testx, testy) {
    var counter = 0;
    var nvert = vert.length;
    var x1, y1, x2, y2;
    var xinters;
    var i;

    /* Check for boundary cases */
    for (i = 0; i < nvert; i++) {
      if (testx == vert[i][0] && testy == vert[i][1]) {
        return true;
      }
    }

    x1 = vert[0][0];
    y1 = vert[0][1];

    for (i = 1; i < nvert; i++) {
      x2 = vert[i % nvert][0];
      y2 = vert[i % nvert][1];
      if (testy > MIN(y1, y2) &&
        testy <= MAX(y1, y2) &&
        testx <= MAX(x1, x2) &&
        y1 != y2) {
        xinters = (testy - y1) * (x2 - x1) / (y2 - y1) + x1;
        if (x1 == x2 || testx <= xinters)
          counter++;
      }
      x1 = x2;
      y1 = y2;
    }
    return counter % 2 != 0;
  }

  function in_image(x, y) {
    return pnpoly(vertsJit, x, y);
  }

  /**
   * Return the authalic latitude of latitude alpha (if inverse=0) or
   * return the approximate latitude of authalic latitude alpha (if inverse=1).
   * P contains the relevant ellipsoid parameters.
   **/
  function auth_lat(P, alpha, inverse) {
    if (!inverse) {
      /* Authalic latitude. */
      var q = pj_qsfn(sin(alpha), P.e, 1.0 - P.es);
      var ratio = q / qp;

      if (fabs(ratio) > 1) {
        /* Rounding error. */
        ratio = pj_sign(ratio);
      }
      return asin(ratio);
    } else {
      /* Approximation to inverse authalic latitude. */
      return pj_authlat(alpha, apa);
    }
  }

  function vector_add(a, b) {
    return [a[0] + b[0], a[1] + b[1]];
  }

  function vector_sub(a, b) {
    return [a[0] - b[0], a[1] - b[1]];
  }

  function dot_product(a, b) {
    var i, j;
    var ret = [0, 0];
    for (i = 0; i < 2; i++) {
      for (j = 0; j < 2; j++) {
        ret[i] += a[i][j] * b[j];
      }
    }
    return ret;
  }

  /**
   * Return the number of the polar cap, the pole point coordinates, and
   * the region that (x, y) lies in.
   * If inverse=0, then assume (x,y) lies in the image of the HEALPix
   * projection of the unit sphere.
   * If inverse=1, then assume (x,y) lies in the image of the
   * (north_square, south_square)-rHEALPix projection of the unit sphere.
   **/
  function get_cap(x, y, north_square, south_square, inverse) {
    var capmap = {};
    var c;
    capmap.x = x;
    capmap.y = y;
    if (!inverse) {
      if (y > M_FORTPI) {
        capmap.region = 'north';
        c = M_HALFPI;
      } else if (y < -M_FORTPI) {
        capmap.region = 'south';
        c = -M_HALFPI;
      } else {
        capmap.region = 'equatorial';
        capmap.cn = 0;
        return capmap;
      }
      /* polar region */
      if (x < -M_HALFPI) {
        capmap.cn = 0;
        capmap.x = (-3 * M_FORTPI);
        capmap.y = c;
      } else if (x >= -M_HALFPI && x < 0) {
        capmap.cn = 1;
        capmap.x = -M_FORTPI;
        capmap.y = c;
      } else if (x >= 0 && x < M_HALFPI) {
        capmap.cn = 2;
        capmap.x = M_FORTPI;
        capmap.y = c;
      } else {
        capmap.cn = 3;
        capmap.x = 3 * M_FORTPI;
        capmap.y = c;
      }
    } else {
      if (y > M_FORTPI) {
        capmap.region = 'north';
        capmap.x = -3 * M_FORTPI + north_square * M_HALFPI;
        capmap.y = M_HALFPI;
        x = x - north_square * M_HALFPI;
      } else if (y < -M_FORTPI) {
        capmap.region = 'south';
        capmap.x = -3 * M_FORTPI + south_square * M_HALFPI;
        capmap.y = -M_HALFPI;
        x = x - south_square * M_HALFPI;
      } else {
        capmap.region = 'equatorial';
        capmap.cn = 0;
        return capmap;
      }
      /* Polar Region, find the HEALPix polar cap number that
         x, y moves to when rHEALPix polar square is disassembled. */
      if (capmap.region == 'north') {
        if (y >= -x - M_FORTPI - EPS && y < x + 5 * M_FORTPI - EPS) {
          capmap.cn = (north_square + 1) % 4;
        } else if (y > -x - M_FORTPI + EPS && y >= x + 5 * M_FORTPI - EPS) {
          capmap.cn = (north_square + 2) % 4;
        } else if (y <= -x - M_FORTPI + EPS && y > x + 5 * M_FORTPI + EPS) {
          capmap.cn = (north_square + 3) % 4;
        } else {
          capmap.cn = north_square;
        }
      } else if (capmap.region == 'south') {
        if (y <= x + M_FORTPI + EPS && y > -x - 5 * M_FORTPI + EPS) {
          capmap.cn = (south_square + 1) % 4;
        } else if (y < x + M_FORTPI - EPS && y <= -x - 5 * M_FORTPI + EPS) {
          capmap.cn = (south_square + 2) % 4;
        } else if (y >= x + M_FORTPI - EPS && y < -x - 5 * M_FORTPI - EPS) {
          capmap.cn = (south_square + 3) % 4;
        } else {
          capmap.cn = south_square;
        }
      }
    }
    return capmap;
  }

  /**
   * Rearrange point (x, y) in the HEALPix projection by
   * combining the polar caps into two polar squares.
   * Put the north polar square in position north_square and
   * the south polar square in position south_square.
   * If inverse=1, then uncombine the polar caps.
   * @param north_square integer between 0 and 3.
   * @param south_square integer between 0 and 3.
   **/
  function combine_caps(xy, north_square, south_square, inverse) {
    var v, c, vector, v_min_c, ret_dot, tmpRot, a;
    var pole = 0;
    var capmap = get_cap(xy.x, xy.y, north_square, south_square, inverse);
    if (capmap.region == 'equatorial') {
      xy.x = capmap.x;
      xy.y = capmap.y;
      return;
    }
    v = [xy.x, xy.y];
    c = [capmap.x, capmap.y];

    if (!inverse) {
      /* Rotate (x, y) about its polar cap tip and then translate it to
         north_square or south_square. */

      if (capmap.region == 'north') {
        pole = north_square;
        tmpRot = rot[get_rotate_index(capmap.cn - pole)];
      } else {
        pole = south_square;
        tmpRot = rot[get_rotate_index(-1 * (capmap.cn - pole))];
      }
    } else {
      /* Inverse function.
       Unrotate (x, y) and then translate it back. */

      /* disassemble */
      if (capmap.region == 'north') {
        pole = north_square;
        tmpRot = rot[get_rotate_index(-1 * (capmap.cn - pole))];
      } else {
        pole = south_square;
        tmpRot = rot[get_rotate_index(capmap.cn - pole)];
      }
    }
    v_min_c = vector_sub(v, c);
    ret_dot = dot_product(tmpRot, v_min_c);
    a = [-3 * M_FORTPI + ((!inverse) ? 0 : capmap.cn) * M_HALFPI, M_HALFPI];
    vector = vector_add(ret_dot, a);
    xy.x = vector[0];
    xy.y = vector[1];
  }
}


pj_add(pj_hill, 'hill', 'Hill Eucyclic', 'PCyl., Sph.');

// Adapted from: https://github.com/d3/d3-geo-projection/blob/master/src/hill.js
// License: https://github.com/d3/d3-geo-projection/blob/master/LICENSE

function pj_hill(P) {
  var K = 1, // TODO: expose as parameter
      L = 1 + K,
      sinBt = sin(1 / L),
      Bt = asin(sinBt),
      A = 2 * sqrt(M_PI / (B = M_PI + 4 * Bt * L)),
      B,
      rho0 = 0.5 * A * (L + sqrt(K * (2 + K))),
      K2 = K * K,
      L2 = L * L,
      EPS = 1e-12;

  P.es = 0;
  P.fwd = s_fwd;
  P.inv = s_inv;

  function s_fwd(lp, xy) {
    var t = 1 - sin(lp.phi),
        rho, omega;
    if (t && t < 2) {
      var theta = M_HALFPI - lp.phi,
          i = 25,
          delta, sinTheta, cosTheta, C, Bt_Bt1;
      do {
        sinTheta = sin(theta);
        cosTheta = cos(theta);
        Bt_Bt1 = Bt + atan2(sinTheta, L - cosTheta);
        C = 1 + L2 - 2 * L * cosTheta;
        theta -= delta = (theta - K2 * Bt - L * sinTheta + C * Bt_Bt1 -0.5 * t * B) / (2 * L * sinTheta * Bt_Bt1);
      } while (fabs(delta) > EPS && --i > 0);
      rho = A * sqrt(C);
      omega = lp.lam * Bt_Bt1 / M_PI;
    } else {
      rho = A * (K + t);
      omega = lp.lam * Bt / M_PI;
    }

    xy.x = rho * sin(omega);
    xy.y = rho0 - rho * cos(omega);
  }

  function s_inv(xy, lp) {
    var x = xy.x,
        y = xy.y,
        rho2 = x * x + (y -= rho0) * y,
        cosTheta = (1 + L2 - rho2 / (A * A)) / (2 * L),
        theta = acos(cosTheta),
        sinTheta = sin(theta),
        Bt_Bt1 = Bt + atan2(sinTheta, L - cosTheta);
    lp.lam = asin(x / sqrt(rho2)) * M_PI / Bt_Bt1,
    lp.phi = asin(1 - 2 * (theta - K2 * Bt - L * sinTheta + (1 + L2 - 2 * L * cosTheta) * Bt_Bt1) / B);
  }
}


pj_add(pj_krovak, 'krovak', 'Krovak', 'PCyl., Ellps.');

function pj_krovak(P) {
  var u0, n0, g;
  var alpha, k, n, rho0, ad, czech;
  var EPS = 1e-15;
  var S45 = 0.785398163397448; /* 45 deg */
  var S90 = 1.570796326794896; /* 90 deg */
  var UQ = 1.04216856380474;   /* DU(2, 59, 42, 42.69689) */
  var S0 = 1.37008346281555;   /* Latitude of pseudo standard parallel 78deg 30'00" N */

  /* we want Bessel as fixed ellipsoid */
  P.a = 6377397.155;
  P.e = sqrt(P.es = 0.006674372230614);

  /* if latitude of projection center is not set, use 49d30'N */
  if (!pj_param(P.params, "tlat_0"))
    P.phi0 = 0.863937979737193;

  /* if center long is not set use 42d30'E of Ferro - 17d40' for Ferro */
  /* that will correspond to using longitudes relative to greenwich    */
  /* as input and output, instead of lat/long relative to Ferro */
  if (!pj_param(P.params, "tlon_0"))
          P.lam0 = 0.7417649320975901 - 0.308341501185665;

  /* if scale not set default to 0.9999 */
  if (!pj_param(P.params, "tk"))
          P.k0 = 0.9999;
  czech = 1;
  if (!pj_param(P.params, "tczech"))
    czech = -1;

  /* Set up shared parameters between forward and inverse */
  alpha = sqrt(1 + (P.es * pow(cos(P.phi0), 4)) / (1 - P.es));
  u0 = asin(sin(P.phi0) / alpha);
  g = pow((1 + P.e * sin(P.phi0)) / (1 - P.e * sin(P.phi0)), alpha * P.e / 2);
  k = tan( u0 / 2 + S45) / pow  (tan(P.phi0 / 2 + S45) , alpha) * g;
  n0 = sqrt(1 - P.es) / (1 - P.es * pow(sin(P.phi0), 2));
  n = sin(S0);
  rho0 = P.k0 * n0 / tan(S0);
  ad = S90 - UQ;
  P.inv = e_inv;
  P.fwd = e_fwd;

  function e_fwd(lp, xy) {
    var gfi, u, deltav, s, d, eps, rho;

    gfi = pow ( (1 + P.e * sin(lp.phi)) / (1 - P.e * sin(lp.phi)), alpha * P.e / 2);

    u = 2 * (atan(k * pow( tan(lp.phi / 2 + S45), alpha) / gfi)-S45);
    deltav = -lp.lam * alpha;

    s = asin(cos(ad) * sin(u) + sin(ad) * cos(u) * cos(deltav));
    d = asin(cos(u) * sin(deltav) / cos(s));
    eps = n * d;
    rho = rho0 * pow(tan(S0 / 2 + S45) , n) / pow(tan(s / 2 + S45) , n);
    xy.y = rho * cos(eps);
    xy.x = rho * sin(eps);
    xy.y *= czech;
    xy.x *= czech;
  }

  function e_inv(xy, lp) {
    var u, deltav, s, d, eps, rho, fi1, xy0;
    var ok;
    xy0 = xy.x;
    xy.x = xy.y;
    xy.y = xy0;
    xy.x *= czech;
    xy.y *= czech;

    rho = sqrt(xy.x * xy.x + xy.y * xy.y);
    eps = atan2(xy.y, xy.x);
    d = eps / sin(S0);
    s = 2 * (atan(  pow(rho0 / rho, 1 / n) * tan(S0 / 2 + S45)) - S45);
    u = asin(cos(ad) * sin(s) - sin(ad) * cos(s) * cos(d));
    deltav = asin(cos(s) * sin(d) / cos(u));
    lp.lam = P.lam0 - deltav / alpha;

    /* ITERATION FOR lp.phi */
    fi1 = u;
    ok = 0;
    do {
      lp.phi = 2 * (atan(pow( k, -1 / alpha) * pow( tan(u / 2 + S45), 1 / alpha) *
        pow( (1 + P.e * sin(fi1)) / (1 - P.e * sin(fi1)) , P.e / 2))  - S45);
      if (fabs(fi1 - lp.phi) < EPS) ok=1;
      fi1 = lp.phi;
   } while (ok===0);
   lp.lam -= P.lam0;
  }
}


pj_add(pj_laea, 'laea', 'Lambert Azimuthal Equal Area', 'Azi, Sph&Ell');

function pj_laea(P) {
  var EPS10 = 1e-10,
      NITER = 20,
      CONV = 1e-10,
      N_POLE = 0,
      S_POLE = 1,
      EQUIT = 2,
      OBLIQ = 3;
  var sinb1, cosb1, xmf, ymf, mmf, qp, dd, rq, apa, mode, t, sinphi;

  t = fabs(P.phi0);
  if (fabs(t - M_HALFPI) < EPS10)
      mode = P.phi0 < 0 ? S_POLE : N_POLE;
  else if (fabs(t) < EPS10)
      mode = EQUIT;
  else
      mode = OBLIQ;
  if (P.es) {
      P.e = sqrt(P.es);
      qp = pj_qsfn(1, P.e, P.one_es);
      mmf = 0.5 / (1 - P.es);
      apa = pj_authset(P.es);
      switch (mode) {
        case N_POLE:
        case S_POLE:
          dd = 1;
          break;
        case EQUIT:
          dd = 1 / (rq = sqrt(0.5 * qp));
          xmf = 1;
          ymf = 0.5 * qp;
          break;
        case OBLIQ:
          rq = sqrt(0.5 * qp);
          sinphi = sin(P.phi0);
          sinb1 = pj_qsfn(sinphi, P.e, P.one_es) / qp;
          cosb1 = sqrt(1 - sinb1 * sinb1);
          dd = cos(P.phi0) / (sqrt(1 - P.es * sinphi * sinphi) *
             rq * cosb1);
          ymf = (xmf = rq) / dd;
          xmf *= dd;
          break;
      }
      P.inv = e_inv;
      P.fwd = e_fwd;
  } else {
      if (mode == OBLIQ) {
          sinb1 = sin(P.phi0);
          cosb1 = cos(P.phi0);
      }
      P.inv = s_inv;
      P.fwd = s_fwd;
  }

  function e_fwd(lp, xy) {
    var coslam, sinlam, sinphi, q, sinb=0.0, cosb=0.0, b=0.0;
    coslam = cos(lp.lam);
    sinlam = sin(lp.lam);
    sinphi = sin(lp.phi);
    q = pj_qsfn(sinphi, P.e, P.one_es);

    if (mode == OBLIQ || mode == EQUIT) {
        sinb = q / qp;
        cosb = sqrt(1 - sinb * sinb);
    }

    switch (mode) {
      case OBLIQ:
        b = 1 + sinb1 * sinb + cosb1 * cosb * coslam;
        break;
      case EQUIT:
        b = 1 + cosb * coslam;
        break;
      case N_POLE:
        b = M_HALFPI + lp.phi;
        q = qp - q;
        break;
      case S_POLE:
        b = lp.phi - M_HALFPI;
        q = qp + q;
        break;
    }
    if (fabs(b) < EPS10) f_error();

    switch (mode) {
      case OBLIQ:
      case EQUIT:
        if (mode == OBLIQ) {
          b = sqrt(2 / b);
          xy.y = ymf * b * (cosb1 * sinb - sinb1 * cosb * coslam);
        } else {
          b = sqrt(2 / (1 + cosb * coslam));
          xy.y = b * sinb * ymf;
        }
        xy.x = xmf * b * cosb * sinlam;
        break;
      case N_POLE:
      case S_POLE:
        if (q >= 0) {
            b = sqrt(q);
            xy.x = b * sinlam;
            xy.y = coslam * (mode == S_POLE ? b : -b);
        } else
            xy.x = xy.y = 0;
        break;
    }
  }

  function e_inv(xy, lp) {
    var cCe, sCe, q, rho, ab=0.0;

    switch (mode) {
      case EQUIT:
      case OBLIQ:
        xy.x /= dd;
        xy.y *=  dd;
        rho = hypot(xy.x, xy.y);
        if (rho < EPS10) {
            lp.lam = 0;
            lp.phi = P.phi0;
            return lp;
        }
        sCe = 2 * asin(0.5 * rho / rq);
        cCe = cos(sCe);
        sCe = sin(sCe);
        xy.x *= sCe;
        if (mode == OBLIQ) {
            ab = cCe * sinb1 + xy.y * sCe * cosb1 / rho;
            xy.y = rho * cosb1 * cCe - xy.y * sinb1 * sCe;
        } else {
            ab = xy.y * sCe / rho;
            xy.y = rho * cCe;
        }
        break;
      case N_POLE:
        xy.y = -xy.y;
        /* falls through */
      case S_POLE:
        q = (xy.x * xy.x + xy.y * xy.y);
        if (!q) {
            lp.lam = 0;
            lp.phi = P.phi0;
            return (lp);
        }
        ab = 1 - q / qp;
        if (mode == S_POLE)
            ab = - ab;
        break;
    }
    lp.lam = atan2(xy.x, xy.y);
    lp.phi = pj_authlat(asin(ab), apa);
    return lp;
  }

  function s_fwd(lp, xy) {
    var coslam, cosphi, sinphi;
    sinphi = sin(lp.phi);
    cosphi = cos(lp.phi);
    coslam = cos(lp.lam);
    switch (mode) {
      case EQUIT:
      case OBLIQ:
        if (mode == EQUIT) {
          xy.y = 1 + cosphi * coslam;
        } else {
          xy.y = 1 + sinb1 * sinphi + cosb1 * cosphi * coslam;
        }
        if (xy.y <= EPS10) f_error();
        xy.y = sqrt(2 / xy.y);
        xy.x = xy.y * cosphi * sin(lp.lam);
        xy.y *= mode == EQUIT ? sinphi :
           cosb1 * sinphi - sinb1 * cosphi * coslam;
        break;
      case N_POLE:
        coslam = -coslam;
        /* falls through */
      case S_POLE:
        if (fabs(lp.phi + P.phi0) < EPS10) f_error();
        xy.y = M_FORTPI - lp.phi * 0.5;
        xy.y = 2 * (mode == S_POLE ? cos(xy.y) : sin(xy.y));
        xy.x = xy.y * sin(lp.lam);
        xy.y *= coslam;
        break;
    }
  }

  function s_inv(xy, lp) {
    var cosz=0.0, rh, sinz=0.0;

    rh = hypot(xy.x, xy.y);
    if ((lp.phi = rh * 0.5 ) > 1) i_error();
    lp.phi = 2 * asin(lp.phi);
    if (mode == OBLIQ || mode == EQUIT) {
        sinz = sin(lp.phi);
        cosz = cos(lp.phi);
    }
    switch (mode) {
      case EQUIT:
        lp.phi = fabs(rh) <= EPS10 ? 0 : asin(xy.y * sinz / rh);
        xy.x *= sinz;
        xy.y = cosz * rh;
        break;
      case OBLIQ:
        lp.phi = fabs(rh) <= EPS10 ? P.phi0 :
           asin(cosz * sinb1 + xy.y * sinz * cosb1 / rh);
        xy.x *= sinz * cosb1;
        xy.y = (cosz - sin(lp.phi) * sinb1) * rh;
        break;
      case N_POLE:
        xy.y = -xy.y;
        lp.phi = M_HALFPI - lp.phi;
        break;
      case S_POLE:
        lp.phi -= M_HALFPI;
        break;
    }
    lp.lam = (xy.y == 0 && (mode == EQUIT || mode == OBLIQ)) ?
        0 : atan2(xy.x, xy.y);
  }
}


pj_add(pj_lonlat, 'lonlat', 'Lat/long (Geodetic)', '');
pj_add(pj_lonlat, 'longlat', 'Lat/long (Geodetic alias)', '');
pj_add(pj_lonlat, 'latlon', 'Lat/long (Geodetic alias)', '');
pj_add(pj_lonlat, 'latlong', 'Lat/long (Geodetic alias)', '');

function pj_lonlat(P) {
  P.x0 = 0;
  P.y0 = 0;
  P.is_latlong = true;

  P.fwd = function(lp, xy) {
    xy.x = lp.lam / P.a;
    xy.y = lp.phi / P.a;
  };

  P.inv = function(xy, lp) {
    lp.lam = xy.x * P.a;
    lp.phi = xy.y * P.a;
  };
}



function pj_tsfn(phi, sinphi, e) {
	sinphi *= e;
  // Proj.4 returns HUGE_VAL on div0; this returns +/- Infinity; effect should be same
	return (tan(0.5 * (M_HALFPI - phi)) /
	  pow((1 - sinphi) / (1 + sinphi), 0.5 * e));
}


pj_add(pj_lcc, 'lcc', 'Lambert Conformal Conic', 'Conic, Sph&Ell\nlat_1= and lat_2= or lat_0=');

function pj_lcc(P) {
  var EPS10 = 1e-10;
  var cosphi, sinphi, secant;
  var phi1, phi2, n, rho0, c, ellips, ml1, m1;

  P.inv = e_inv;
  P.fwd = e_fwd;

  phi1 = pj_param(P.params, "rlat_1");
  if (pj_param(P.params, "tlat_2"))
    phi2 = pj_param(P.params, "rlat_2");
  else {
    phi2 = phi1;
    if (!pj_param(P.params, "tlat_0"))
      P.phi0 = phi1;
  }
  if (fabs(phi1 + phi2) < EPS10) e_error(-21);
  n = sinphi = sin(phi1);
  cosphi = cos(phi1);
  secant = fabs(phi1 - phi2) >= EPS10;
  if ((ellips = (P.es != 0))) {
    P.e = sqrt(P.es);
    m1 = pj_msfn(sinphi, cosphi, P.es);
    ml1 = pj_tsfn(phi1, sinphi, P.e);
    if (secant) { /* secant cone */
      sinphi = sin(phi2);
      n = log(m1 / pj_msfn(sinphi, cos(phi2), P.es));
      n /= log(ml1 / pj_tsfn(phi2, sinphi, P.e));
    }
    c = (rho0 = m1 * pow(ml1, -n) / n);
    rho0 *= (fabs(fabs(P.phi0) - M_HALFPI) < EPS10) ? 0 :
        pow(pj_tsfn(P.phi0, sin(P.phi0), P.e), n);
  } else {
    if (secant)
      n = log(cosphi / cos(phi2)) /
          log(tan(M_FORTPI + 0.5 * phi2) /
          tan(M_FORTPI + 0.5 * phi1));
    c = cosphi * pow(tan(M_FORTPI + 0.5 * phi1), n) / n;
    rho0 = (fabs(fabs(P.phi0) - M_HALFPI) < EPS10) ? 0 :
        c * pow(tan(M_FORTPI + 0.5 * P.phi0), -n);
  }

  function e_fwd(lp, xy) {
    var lam = lp.lam;
    var rho;
    if (fabs(fabs(lp.phi) - M_HALFPI) < EPS10) {
      if ((lp.phi * n) <= 0) f_error();
      rho = 0;
    } else {
      rho = c * (ellips ? pow(pj_tsfn(lp.phi, sin(lp.phi),
            P.e), n) : pow(tan(M_FORTPI + 0.5 * lp.phi), -n));
    }
    lam *= n;
    xy.x = P.k0 * (rho * sin(lam));
    xy.y = P.k0 * (rho0 - rho * cos(lam));
  }

  function e_inv(xy, lp) {
    var x = xy.x, y = xy.y;
    var rho;
    x /= P.k0;
    y /= P.k0;

    y = rho0 - y;
    rho = hypot(x, y);
    if (rho != 0) {
      if (n < 0) {
        rho = -rho;
        x = -x;
        y = -y;
      }
      if (ellips) {
        lp.phi = pj_phi2(pow(rho / c, 1/n), P.e);
        if (lp.phi == HUGE_VAL) i_error();
      } else
        lp.phi = 2 * atan(pow(c / rho, 1/n)) - M_HALFPI;
      lp.lam = atan2(x, y) / n;
    } else {
      lp.lam = 0;
      lp.phi = n > 0 ? M_HALFPI : -M_HALFPI;
    }
  }

}


pj_add(pj_loxim, 'loxim', 'Loximuthal', 'PCyl Sph');

function pj_loxim(P) {
  var EPS = 1e-8;
  var phi1, cosphi1, tanphi1;
      phi1 = pj_param(P.params, "rlat_1");
      cosphi1 = cos(phi1);
      tanphi1 = tan(M_FORTPI + 0.5 * phi1);
  if (cosphi1 < EPS) e_error(-22);
  P.fwd = s_fwd;
  P.inv = s_inv;
  P.es = 0;

  function s_fwd(lp, xy) {
    xy.y = lp.phi - phi1;
    if (fabs(xy.y) < EPS)
      xy.x = lp.lam * cosphi1;
    else {
      xy.x = M_FORTPI + 0.5 * lp.phi;
      if (fabs(xy.x) < EPS || fabs(fabs(xy.x) - M_HALFPI) < EPS)
        xy.x = 0;
      else
        xy.x = lp.lam * xy.y / log(tan(xy.x) / tanphi1);
    }
  }

  function s_inv(xy, lp) {
    lp.phi = xy.y + phi1;
    if (fabs(xy.y) < EPS) {
      lp.lam = xy.x / cosphi1;
    } else {
      lp.lam = M_FORTPI + 0.5 * lp.phi;
      if (fabs(lp.lam) < EPS || fabs(fabs(lp.lam) - M_HALFPI) < EPS)
        lp.lam = 0;
      else
        lp.lam = xy.x * log(tan(lp.lam) / tanphi1) / xy.y;
    }
  }
}


pj_add(pj_mbt_fpp, 'mbt_fpp', 'McBride-Thomas Flat-Polar Parabolic', 'Cyl., Sph.');

function pj_mbt_fpp(P) {
  var CS = 0.95257934441568037152,
      FXC = 0.92582009977255146156,
      FYC = 3.40168025708304504493,
      C23 = 2 / 3,
      C13 = 1 / 3,
      ONEEPS = 1.0000001;

  P.fwd = s_fwd;
  P.inv = s_inv;
  P.es = 0;

  function s_fwd(lp, xy) {
    lp.phi = asin(CS * sin(lp.phi));
    xy.x = FXC * lp.lam * (2 * cos(C23 * lp.phi) - 1);
    xy.y = FYC * sin(C13 * lp.phi);
  }

  function s_inv(xy, lp) {
    lp.phi = xy.y / FYC;
    if (fabs(lp.phi) >= 1) {
      if (fabs(lp.phi) > ONEEPS)
        i_error();
      else
        lp.phi = (lp.phi < 0) ? -M_HALFPI : M_HALFPI;
    } else
      lp.phi = asin(lp.phi);

    lp.lam = xy.x / (FXC * (2 * cos(C23 * (lp.phi *= 3)) - 1));
    if (fabs(lp.phi = sin(lp.phi) / CS) >= 1) {
      if (fabs(lp.phi) > ONEEPS)
        i_error();
      else
        lp.phi = (lp.phi < 0) ? -M_HALFPI : M_HALFPI;
    } else
      lp.phi = asin(lp.phi);
  }
}


pj_add(pj_mbt_fpq, 'mbt_fpq', 'McBryde-Thomas Flat-Polar Quartic', 'Cyl., Sph.');

function pj_mbt_fpq(P) {
  var NITER = 20,
      EPS = 1e-7,
      ONETOL = 1.000001,
      C = 1.70710678118654752440,
      RC = 0.58578643762690495119,
      FYC = 1.87475828462269495505,
      RYC = 0.53340209679417701685,
      FXC = 0.31245971410378249250,
      RXC = 3.20041258076506210122;

  P.fwd = s_fwd;
  P.inv = s_inv;
  P.es = 0;

  function s_fwd(lp, xy) {
    var th1, c, i;
    c = C * sin(lp.phi);
    for (i = NITER; i; --i) {
      lp.phi -= th1 = (sin(0.5 * lp.phi) + sin(lp.phi) - c) /
        (0.5 * cos(0.5 * lp.phi) + cos(lp.phi));
      if (fabs(th1) < EPS) break;
    }
    xy.x = FXC * lp.lam * (1.0 + 2 * cos(lp.phi) / cos(0.5 * lp.phi));
    xy.y = FYC * sin(0.5 * lp.phi);
  }

  function s_inv(xy, lp) {
    var t;
    lp.phi = RYC * xy.y;
    if (fabs(lp.phi) > 1) {
      if (fabs(lp.phi) > ONETOL) i_error();
      else if (lp.phi < 0) {
        t = -1;
        lp.phi = -M_PI;
      } else {
        t = 1;
        lp.phi = M_PI;
      }
    } else
      lp.phi = 2 * asin(t = lp.phi);
    lp.lam = RXC * xy.x / (1 + 2 * cos(lp.phi) / cos(0.5 * lp.phi));
    lp.phi = RC * (t + sin(lp.phi));
    if (fabs(lp.phi) > 1)
      if (fabs(lp.phi) > ONETOL) i_error();
      else
        lp.phi = lp.phi < 0 ? -M_HALFPI : M_HALFPI;
    else
      lp.phi = asin(lp.phi);
  }
}


pj_add(pj_mbt_fps, 'mbt_fps', 'McBryde-Thomas Flat-Pole Sine (No. 2)', 'Cyl., Sph.');

function pj_mbt_fps(P) {
  var MAX_ITER = 10,
      LOOP_TOL = 1e-7,
      C1 = 0.45503,
      C2 = 1.36509,
      C3 = 1.41546,
      C_x = 0.22248,
      C_y = 1.44492,
      C1_2 = 1 / 3;

  P.fwd = s_fwd;
  P.inv = s_inv;
  P.es = 0;

  function s_fwd(lp, xy) {
    var k, V, t, i;
    k = C3 * sin(lp.phi);
    for (i = MAX_ITER; i; --i) {
      t = lp.phi / C2;
      lp.phi -= V = (C1 * sin(t) + sin(lp.phi) - k) /
        (C1_2 * cos(t) + cos(lp.phi));
      if (fabs(V) < LOOP_TOL)
        break;
    }
    t = lp.phi / C2;
    xy.x = C_x * lp.lam * (1 + 3 * cos(lp.phi) / cos(t));
    xy.y = C_y * sin(t);
  }

  function s_inv(xy, lp) {
    var t;
    lp.phi = C2 * (t = aasin(xy.y / C_y));
    lp.lam = xy.x / (C_x * (1 + 3 * cos(lp.phi) / cos(t)));
    lp.phi = aasin((C1 * sin(t) + sin(lp.phi)) / C3);
  }
}


function pj_phi2(ts, e) {
  var N_ITER = 15,
      TOL = 1e-10,
      eccnth = 0.5 * e,
      Phi = M_HALFPI - 2 * atan(ts),
      i = N_ITER,
      con, dphi;

  do {
    con = e * sin(Phi);
    dphi = M_HALFPI - 2 * atan(ts * pow((1 - con) /
       (1 + con), eccnth)) - Phi;
    Phi += dphi;
  } while (fabs(dphi) > TOL && --i);
  if (i <= 0) {
    pj_ctx_set_errno(-18);
  }
  return Phi;
}


pj_add(pj_merc, 'merc', 'Mercator', 'Cyl, Sph&Ell\nlat_ts=');

function pj_merc(P) {
  var EPS10 = 1e-10;
  var phits = 0;
  var is_phits = pj_param(P.params, 'tlat_ts');

  if (is_phits) {
    phits = pj_param(P.params, 'rlat_ts');
    if (phits >= M_HALFPI) {
      e_error(-24);
    }
  }

  if (P.es) { // ellipsoid
    if (is_phits) {
      P.k0 = pj_msfn(sin(phits), cos(phits), P.es);
    }
    P.inv = e_inv;
    P.fwd = e_fwd;
  } else {
    P.inv = s_inv;
    P.fwd = s_fwd;
  }

  function e_fwd(lp, xy) {
    if (fabs(fabs(lp.phi) - M_HALFPI) <= EPS10) {
      f_error();
    }
    xy.x = P.k0 * lp.lam;
    xy.y = -P.k0 * log(pj_tsfn(lp.phi, sin(lp.phi), P.e));
  }

  function e_inv(xy, lp) {
    lp.phi = pj_phi2(exp(-xy.y / P.k0), P.e);
    if (lp.phi === HUGE_VAL) {
      i_error();
    }
    lp.lam = xy.x / P.k0;
  }

  function s_fwd(lp, xy) {
    if (fabs(fabs(lp.phi) - M_HALFPI) <= EPS10) {
      f_error();
    }
    xy.x = P.k0 * lp.lam;
    xy.y = P.k0 * log(tan(M_FORTPI + 0.5 * lp.phi));
  }

  function s_inv(xy, lp) {
    lp.phi = M_HALFPI - 2 * atan(exp(-xy.y / P.k0));
    lp.lam = xy.x / P.k0;
  }
}


pj_add(pj_mill, 'mill', 'Miller Cylindrical', 'Cyl, Sph');

function pj_mill(P) {

  P.fwd = s_fwd;
  P.inv = s_inv;
  P.es = 0;

  function s_fwd(lp, xy) {
    xy.x = lp.lam;
    xy.y = log(tan(M_FORTPI + lp.phi * 0.4)) * 1.25;
  }

  function s_inv(xy, lp) {
    lp.lam = xy.x;
    lp.phi = 2.5 * (atan(exp(0.8 * xy.y)) - M_FORTPI);
  }
}


/* evaluate complex polynomial */

/* note: coefficients are always from C_1 to C_n
**  i.e. C_0 == (0., 0)
**  n should always be >= 1 though no checks are made
*/
// z: Complex number (object with r and i properties)
// C: Array of complex numbers
// returns: complex number
function pj_zpoly1(z, C) {
  var t, r, i;
  var n = C.length - 1;
  r = C[n][0];
  i = C[n][1];
  while (--n >= 0) {
    t = r;
    r = C[n][0] + z.r * t - z.i * i;
    i = C[n][1] + z.r * i + z.i * t;
  }
  return {
    r: z.r * r - z.i * i,
    i: z.r * i + z.i * r
  };
}

/* evaluate complex polynomial and derivative */
function pj_zpolyd1(z, C, der) {
  var ai, ar, bi, br, t;
  var first = true;
  var n = C.length - 1;
  ar = br = C[n][0];
  ai = bi = C[n][1];
  while (--n >= 0) {
    if (first) {
      first = false;
    } else {
      br = ar + z.r * (t = br) - z.i * bi;
      bi = ai + z.r * bi + z.i * t;
    }
    ar = C[n][0] + z.r * (t = ar) - z.i * ai;
    ai = C[n][1] + z.r * ai + z.i * t;
  }
  der.r = ar + z.r * br - z.i * bi;
  der.i = ai + z.r * bi + z.i * br;
  return {
    r: z.r * ar - z.i * ai,
    i: z.r * ai + z.i * ar
  };
}


pj_add(pj_mil_os, 'mil_os', 'Miller Oblated Stereographic', 'Azi(mod)');
pj_add(pj_lee_os, 'lee_os', 'Lee Oblated Stereographic', 'Azi(mod)');
pj_add(pj_gs48, 'gs48', 'Mod Stereographic of 48 U.S.', 'Azi(mod)');
pj_add(pj_alsk, 'alsk', 'Mod Stereographic of Alaska', 'Azi(mod)');
pj_add(pj_gs50, 'gs50', 'Mod Stereographic of 50 U.S.', 'Azi(mod)');

function pj_mil_os(P) {
  var AB = [
    [0.924500, 0],
    [0,        0],
    [0.019430, 0]
  ];
  P.lam0 = DEG_TO_RAD * 20;
  P.phi0 = DEG_TO_RAD * 18;
  P.es = 0;
  pj_mod_ster(P, AB);
}

function pj_lee_os(P) {
  var AB = [
    [0.721316,    0],
    [0,           0],
    [-0.0088162, -0.00617325]
  ];
  P.lam0 = DEG_TO_RAD * -165;
  P.phi0 = DEG_TO_RAD * -10;
  P.es = 0;
  pj_mod_ster(P, AB);
}

function pj_gs48(P) {
  var AB = [
    [0.98879,   0],
    [0,         0],
    [-0.050909, 0],
    [0,         0],
    [0.075528,  0]
  ];
  P.lam0 = DEG_TO_RAD * -96;
  P.phi0 = DEG_TO_RAD * 39;
  P.es = 0;
  P.a = 6370997;
  pj_mod_ster(P, AB);
}

function pj_alsk(P) {
  var ABe = [ /* Alaska ellipsoid */
    [ 0.9945303, 0],
    [ 0.0052083, -0.0027404],
    [ 0.0072721,  0.0048181],
    [-0.0151089, -0.1932526],
    [ 0.0642675, -0.1381226],
    [ 0.3582802, -0.2884586],
  ];
  var ABs = [ /* Alaska sphere */
    [ 0.9972523,  0],
    [ 0.0052513, -0.0041175],
    [ 0.0074606,  0.0048125],
    [-0.0153783, -0.1968253],
    [ 0.0636871, -0.1408027],
    [ 0.3660976, -0.2937382]
  ];
  var AB;
  P.lam0 = DEG_TO_RAD * -152;
  P.phi0 = DEG_TO_RAD * 64;
  if (P.es != 0.0) { /* fixed ellipsoid/sphere */
    AB = ABe;
    P.a = 6378206.4;
    P.e = sqrt(P.es = 0.00676866);
  } else {
    AB = ABs;
    P.a = 6370997;
  }
  pj_mod_ster(P, AB);
}

function pj_gs50(P) {
  var ABe = [
    [ 0.9827497,  0],
    [ 0.0210669,  0.0053804],
    [-0.1031415, -0.0571664],
    [-0.0323337, -0.0322847],
    [ 0.0502303,  0.1211983],
    [ 0.0251805,  0.0895678],
    [-0.0012315, -0.1416121],
    [ 0.0072202, -0.1317091],
    [-0.0194029,  0.0759677],
    [-0.0210072,  0.0834037]
  ];
  var ABs = [
    [ 0.9842990,  0],
    [ 0.0211642,  0.0037608],
    [-0.1036018, -0.0575102],
    [-0.0329095, -0.0320119],
    [ 0.0499471,  0.1223335],
    [ 0.0260460,  0.0899805],
    [ 0.0007388, -0.1435792],
    [ 0.0075848, -0.1334108],
    [-0.0216473,  0.0776645],
    [-0.0225161,  0.0853673]
  ];
  var AB;
  P.lam0 = DEG_TO_RAD * -120;
  P.phi0 = DEG_TO_RAD * 45;
  if (P.es != 0.0) { /* fixed ellipsoid/sphere */
    AB = ABe;
    P.a = 6378206.4;
    P.e = sqrt(P.es = 0.00676866);
  } else {
    AB = ABs;
    P.a = 6370997;
  }
  pj_mod_ster(P, AB);
}

function pj_mod_ster(P, zcoeff) {
  var EPSLN = 1e-12;
  var esphi, chio;
  var cchio, schio;
  if (P.es != 0.0) {
    esphi = P.e * sin(P.phi0);
    chio = 2 * atan(tan((M_HALFPI + P.phi0) * 0.5) *
        pow((1 - esphi) / (1 + esphi), P.e * 0.5)) - M_HALFPI;
  } else
    chio = P.phi0;
  schio = sin(chio);
  cchio = cos(chio);
  P.inv = e_inv;
  P.fwd = e_fwd;

  function e_fwd(lp, xy) {
    var sinlon, coslon, esphi, chi, schi, cchi, s;
    var p = {};

    sinlon = sin(lp.lam);
    coslon = cos(lp.lam);
    esphi = P.e * sin(lp.phi);
    chi = 2 * atan(tan((M_HALFPI + lp.phi) * 0.5) *
        pow((1 - esphi) / (1 + esphi), P.e * 0.5)) - M_HALFPI;
    schi = sin(chi);
    cchi = cos(chi);
    s = 2 / (1 + schio * schi + cchio * cchi * coslon);
    p.r = s * cchi * sinlon;
    p.i = s * (cchio * schi - schio * cchi * coslon);
    p = pj_zpoly1(p, zcoeff);
    xy.x = p.r;
    xy.y = p.i;
  }

  function e_inv(xy, lp) {
    var nn;
    var p = {}, fxy, fpxy = {}, dp = {}; // complex numbers
    var den, rh = 0.0, z, sinz = 0.0, cosz = 0.0, chi, phi = 0.0, esphi;
    var dphi;

    p.r = xy.x;
    p.i = xy.y;
    for (nn = 20; nn ;--nn) {
      fxy = pj_zpolyd1(p, zcoeff, fpxy);
      fxy.r -= xy.x;
      fxy.i -= xy.y;
      den = fpxy.r * fpxy.r + fpxy.i * fpxy.i;
      dp.r = -(fxy.r * fpxy.r + fxy.i * fpxy.i) / den;
      dp.i = -(fxy.i * fpxy.r - fxy.r * fpxy.i) / den;
      p.r += dp.r;
      p.i += dp.i;
      if ((fabs(dp.r) + fabs(dp.i)) <= EPSLN)
          break;
    }
    if (nn) {
      rh = hypot(p.r, p.i);
      z = 2 * atan(0.5 * rh);
      sinz = sin(z);
      cosz = cos(z);
      lp.lam = P.lam0;
      if (fabs(rh) <= EPSLN) {
        /* if we end up here input coordinates were (0,0).
         * pj_inv() adds P.lam0 to lp.lam, this way we are
         * sure to get the correct offset */
        lp.lam = 0.0;
        lp.phi = P.phi0;
        return;
      }
      chi = aasin(cosz * schio + p.i * sinz * cchio / rh);
      phi = chi;
      for (nn = 20; nn ;--nn) {
        esphi = P.e * sin(phi);
        dphi = 2 * atan(tan((M_HALFPI + chi) * 0.5) *
            pow((1 + esphi) / (1 - esphi), P.e * 0.5)) - M_HALFPI - phi;
        phi += dphi;
        if (fabs(dphi) <= EPSLN)
          break;
      }
    }
    if (nn) {
      lp.phi = phi;
      lp.lam = atan2(p.r * sinz, rh * cchio * cosz - p.i * schio * sinz);
    } else
      lp.lam = lp.phi = HUGE_VAL;
  }
}


pj_add(pj_natearth, 'natearth', 'Natural Earth', 'PCyl., Sph.');
pj_add(pj_natearth2, 'natearth2', 'Natural Earth 2', 'PCyl., Sph.');

function pj_natearth(P) {
  var A0 = 0.8707,
  A1 = -0.131979,
  A2 = -0.013791,
  A3 = 0.003971,
  A4 = -0.001529,
  B0 = 1.007226,
  B1 = 0.015085,
  B2 = -0.044475,
  B3 = 0.028874,
  B4 = -0.005916,
  C0 = B0,
  C1 = (3 * B1),
  C2 = (7 * B2),
  C3 = (9 * B3),
  C4 = (11 * B4),
  EPS = 1e-11,
  MAX_Y = (0.8707 * 0.52 * M_PI);

  P.es = 0;
  P.fwd = s_fwd;
  P.inv = s_inv;

  function s_fwd(lp, xy) {
    var phi2, phi4;
    phi2 = lp.phi * lp.phi;
    phi4 = phi2 * phi2;
    xy.x = lp.lam * (A0 + phi2 * (A1 + phi2 * (A2 + phi4 * phi2 * (A3 + phi2 * A4))));
    xy.y = lp.phi * (B0 + phi2 * (B1 + phi4 * (B2 + B3 * phi2 + B4 * phi4)));
  }

  function s_inv(xy, lp) {
    var x = xy.x, y = xy.y;
    var yc, tol, y2, y4, f, fder;
    if (y > MAX_Y) {
      y = MAX_Y;
    } else if (y < -MAX_Y) {
      y = -MAX_Y;
    }

    yc = y;
      for (;;) { /* Newton-Raphson */
      y2 = yc * yc;
      y4 = y2 * y2;
      f = (yc * (B0 + y2 * (B1 + y4 * (B2 + B3 * y2 + B4 * y4)))) - y;
      fder = C0 + y2 * (C1 + y4 * (C2 + C3 * y2 + C4 * y4));
      yc -= tol = f / fder;
      if (fabs(tol) < EPS) {
          break;
      }
    }
    lp.phi = yc;
    y2 = yc * yc;
    lp.lam = x / (A0 + y2 * (A1 + y2 * (A2 + y2 * y2 * y2 * (A3 + y2 * A4))));
  }
}

function pj_natearth2(P) {
  var A0 = 0.84719,
      A1 = -0.13063,
      A2 = -0.04515,
      A3 = 0.05494,
      A4 = -0.02326,
      A5 = 0.00331,
      B0 = 1.01183,
      B1 = -0.02625,
      B2 = 0.01926,
      B3 = -0.00396,
      C0 = B0,
      C1 = (9 * B1),
      C2 = (11 * B2),
      C3 = (13 * B3),
      EPS = 1e-11,
      MAX_Y = (0.84719 * 0.535117535153096 * M_PI);

  P.es = 0;
  P.fwd = s_fwd;
  P.inv = s_inv;

  function s_fwd(lp, xy) {
    var phi2, phi4, phi6;
    phi2 = lp.phi * lp.phi;
    phi4 = phi2 * phi2;
    phi6 = phi2 * phi4;
    xy.x = lp.lam * (A0 + A1 * phi2 + phi6 * phi6 * (A2 + A3 * phi2 + A4 * phi4 + A5 * phi6));
    xy.y = lp.phi * (B0 + phi4 * phi4 * (B1 + B2 * phi2 + B3 * phi4));
  }

  function s_inv(xy, lp) {
    var x = xy.x, y = xy.y;
    var yc, tol, y2, y4, y6, f, fder;
    if (y > MAX_Y) {
      y = MAX_Y;
    } else if (y < -MAX_Y) {
      y = -MAX_Y;
    }
    yc = y;
    for (;;) { /* Newton-Raphson */
      y2 = yc * yc;
      y4 = y2 * y2;
      f = (yc * (B0 + y4 * y4 * (B1 + B2 * y2 + B3 * y4))) - y;
      fder = C0 + y4 * y4 * (C1 + C2 * y2 + C3 * y4);
      yc -= tol = f / fder;
      if (fabs(tol) < EPS) {
        break;
      }
    }
    lp.phi = yc;
    y2 = yc * yc;
    y4 = y2 * y2;
    y6 = y2 * y4;
    lp.lam = x / (A0 + A1 * y2 + y6 * y6 * (A2 + A3 * y2 + A4 * y4 + A5 * y6));
  }
}


pj_add(pj_nell, 'nell', 'Nell', 'PCyl., Sph.');

function pj_nell(P) {
  var MAX_ITER = 10;
  var LOOP_TOL = 1e-7;
  P.inv = s_inv;
  P.fwd = s_fwd;
  P.es = 0;

  function s_fwd(lp, xy) {
    var k, V, i;
    k = 2 * sin(lp.phi);
    V = lp.phi * lp.phi;
    lp.phi *= 1.00371 + V * (-0.0935382 + V * -0.011412);
    for (i = MAX_ITER; i ; --i) {
        lp.phi -= V = (lp.phi + sin(lp.phi) - k) /
            (1 + cos(lp.phi));
        if (fabs(V) < LOOP_TOL)
            break;
    }
    xy.x = 0.5 * lp.lam * (1 + cos(lp.phi));
    xy.y = lp.phi;
  }

  function s_inv(xy, lp) {
    lp.lam = 2 * xy.x / (1 + cos(xy.y));
    lp.phi = aasin(0.5 * (xy.y + sin(xy.y)));
  }
}


pj_add(pj_nell_h, 'nell_h', 'Nell-Hammer', 'PCyl., Sph.');

function pj_nell_h(P) {
var NITER = 9,
    EPS = 1e-7;
  P.es = 0;
  P.fwd = s_fwd;
  P.inv = s_inv;

  function s_fwd(lp, xy) {
    xy.x = 0.5 * lp.lam * (1 + cos(lp.phi));
    xy.y = 2.0 * (lp.phi - tan(0.5 *lp.phi));
  }

  function s_inv(xy, lp) {
    var V, c, p, i;
    p = 0.5 * xy.y;
    for (i = NITER; i>0; --i) {
      c = cos(0.5 * lp.phi);
      lp.phi -= V = (lp.phi - tan(lp.phi/2) - p)/(1 - 0.5/(c*c));
      if (fabs(V) < EPS)
        break;
    }
    if (!i) {
      lp.phi = p < 0 ? -M_HALFPI : M_HALFPI;
      lp.lam = 2 * xy.x;
    } else
      lp.lam = 2 * xy.x / (1 + cos(lp.phi));
  }
}


pj_add(pj_nsper, 'nsper', 'Near-sided perspective', 'Azi, Sph\nh=');
pj_add(pj_tpers, 'tpers', 'Tilted perspective', 'Azi, Sph\ntilt= azi= h=');

function pj_nsper(P) {
  pj_tpers_init(P, pj_param(P.params, "dh"));
}

function pj_tpers(P) {
  var tilt = pj_param(P.params, 'dtilt') * DEG_TO_RAD;
  var azi = pj_param(P.params, 'dazi') * DEG_TO_RAD;
  var height = pj_param(P.params, "dh");
  pj_tpers_init(P, height, tilt, azi);
}

function pj_tpers_init(P, height, tiltAngle, azimuth) {
  var N_POLE = 0,
      S_POLE = 1,
      EIT = 2,
      OBLI= 3,
      tilt = !isNaN(tiltAngle) && !isNaN(azimuth),
      mode, sinph0, cosph0, p, rp, pn1, pfact, h, cg, sg, sw, cw;

  if (height <= 0) e_error(-30);
  if (tilt) {
    cg = cos(azimuth);
    sg = sin(azimuth);
    cw = cos(tiltAngle);
    sw = sin(tiltAngle);
  }
  if (fabs(fabs(P.phi0) - M_HALFPI) < EPS10)
    mode = P.phi0 < 0 ? S_POLE : N_POLE;
  else if (fabs(P.phi0) < EPS10)
    mode = EIT;
  else {
    mode = OBLI;
    sinph0 = sin(P.phi0);
    cosph0 = cos(P.phi0);
  }
  pn1 = height / P.a; /* normalize by radius */
  p = 1 + pn1;
  rp = 1 / p;
  h = 1 / pn1;
  pfact = (p + 1) * h;

  P.fwd = s_fwd;
  P.inv = s_inv;
  P.es = 0;

  function s_fwd(lp, xy) {
    var coslam, cosphi, sinphi;
    var yt, ba;
    sinphi = sin(lp.phi);
    cosphi = cos(lp.phi);
    coslam = cos(lp.lam);
    switch (mode) {
      case OBLI:
        xy.y = sinph0 * sinphi + cosph0 * cosphi * coslam;
        break;
      case EIT:
        xy.y = cosphi * coslam;
        break;
      case S_POLE:
        xy.y = - sinphi;
        break;
      case N_POLE:
        xy.y = sinphi;
        break;
    }
    if (xy.y < rp) f_error();
    xy.y = pn1 / (p - xy.y);
    xy.x = xy.y * cosphi * sin(lp.lam);
    switch (mode) {
      case OBLI:
        xy.y *= (cosph0 * sinphi -
           sinph0 * cosphi * coslam);
        break;
      case EIT:
        xy.y *= sinphi;
        break;
      case N_POLE:
        coslam = - coslam;
        /* falls through */
      case S_POLE:
        xy.y *= cosphi * coslam;
        break;
    }
    if (tilt) {
      yt = xy.y * cg + xy.x * sg;
      ba = 1 / (yt * sw * h + cw);
      xy.x = (xy.x * cg - xy.y * sg) * cw * ba;
      xy.y = yt * ba;
    }
  }

  function s_inv(xy, lp) {
    var rh, cosz, sinz;
    var bm, bq, yt;
    if (tilt) {
      yt = 1/(pn1 - xy.y * sw);
      bm = pn1 * xy.x * yt;
      bq = pn1 * xy.y * cw * yt;
      xy.x = bm * cg + bq * sg;
      xy.y = bq * cg - bm * sg;
    }
    rh = hypot(xy.x, xy.y);
    if ((sinz = 1 - rh * rh * pfact) < 0) i_error();
    sinz = (p - sqrt(sinz)) / (pn1 / rh + rh / pn1);
    cosz = sqrt(1 - sinz * sinz);
    if (fabs(rh) <= EPS10) {
        lp.lam = 0;
        lp.phi = P.phi0;
    } else {
      switch (mode) {
        case OBLI:
          lp.phi = asin(cosz * sinph0 + xy.y * sinz * cosph0 / rh);
          xy.y = (cosz - sinph0 * sin(lp.phi)) * rh;
          xy.x *= sinz * cosph0;
          break;
        case EIT:
          lp.phi = asin(xy.y * sinz / rh);
          xy.y = cosz * rh;
          xy.x *= sinz;
          break;
        case N_POLE:
          lp.phi = asin(cosz);
          xy.y = -xy.y;
          break;
        case S_POLE:
          lp.phi = - asin(cosz);
          break;
      }
      lp.lam = atan2(xy.x, xy.y);
    }
  }
}


pj_add(pj_nzmg, 'nzmg', 'New Zealand Map Grid', 'fixed Earth');

function pj_nzmg(P) {
  var EPSLN = 1e-10;
  var SEC5_TO_RAD = 0.4848136811095359935899141023;
  var RAD_TO_SEC5 = 2.062648062470963551564733573;
  var bf = [
    [ 0.7557853228, 0.0],
    [ 0.249204646,  0.003371507],
    [-0.001541739,  0.041058560],
    [-0.10162907,   0.01727609],
    [-0.26623489,  -0.36249218],
    [-0.6870983,   -1.1651967]];

  var tphi= [1.5627014243, 0.5185406398, -0.03333098,
    -0.1052906, -0.0368594, 0.007317, 0.01220, 0.00394, -0.0013];

  var tpsi = [0.6399175073, -0.1358797613, 0.063294409, -0.02526853, 0.0117879,
    -0.0055161, 0.0026906, -0.001333, 0.00067, -0.00034];

  /* force to International major axis */
  P.ra = 1 / (P.a = 6378388.0);
  P.lam0 = DEG_TO_RAD * 173;
  P.phi0 = DEG_TO_RAD * -41;
  P.x0 = 2510000;
  P.y0 = 6023150;

  P.inv = e_inv;
  P.fwd = e_fwd;

  function e_fwd(lp, xy) {
    var i = tpsi.length - 1;
    var p = {r: tpsi[i]};
    var phi = (lp.phi - P.phi0) * RAD_TO_SEC5;
    for (--i; i >= 0; --i)
      p.r = tpsi[i] + phi * p.r;
    p.r *= phi;
    p.i = lp.lam;
    p = pj_zpoly1(p, bf);
    xy.x = p.i;
    xy.y = p.r;
  }

  function e_inv(xy, lp) {
    var nn, i, dr, di, f, den;
    var p = {r: xy.y, i: xy.x};
    var fp = {};
    for (nn = 20; nn > 0 ;--nn) {
      f = pj_zpolyd1(p, bf, fp);
      f.r -= xy.y;
      f.i -= xy.x;
      den = fp.r * fp.r + fp.i * fp.i;
      p.r += dr = -(f.r * fp.r + f.i * fp.i) / den;
      p.i += di = -(f.i * fp.r - f.r * fp.i) / den;
      if ((fabs(dr) + fabs(di)) <= EPSLN) break;
    }
    if (nn > 0) {
      lp.lam = p.i;
      i = tphi.length - 1;
      lp.phi = tphi[i];
      for (--i; i >= 0; --i)
        lp.phi = tphi[i] + p.r * lp.phi;
      lp.phi = P.phi0 + p.r * lp.phi * SEC5_TO_RAD;
    } else
      lp.lam = lp.phi = HUGE_VAL;
  }
}


pj_add(pj_ob_tran, 'ob_tran', 'General Oblique Transformation', 'Misc Sph\n' +
  'o_proj= plus parameters for projection\n' +
  'o_lat_p= o_lon_p= (new pole) or\n' +
  'o_alpha= o_lon_c= o_lat_c= or\n' +
  'o_lon_1= o_lat_1= o_lon_2= o_lat_2=');

function pj_ob_tran(P) {
  var name, defn, P2;
  var lamp, cphip, sphip, phip;
  var lamc, phic, alpha;
  var lam1, lam2, phi1, phi2, con;
  var TOL = 1e-10;

  name = pj_param(P.params, 'so_proj');
  defn = pj_list[name];
  if (!name) e_error(-26);
  if (!defn || name == 'ob_tran') e_error(-37);
  P.es = 0;
  // copy params to second object
  P2 = {};
  Object.keys(P).forEach(function(key) {
    // TODO: remove o_ params?
    P2[key] = P[key];
  });
  defn.init(P2);

  // NOT in Proj.4
  // fix output units when doing latlong transform (see pj_transform.js)
  if (P2.is_latlong && P.to_meter == 1) {
    P.to_meter = DEG_TO_RAD;
    P.fr_meter = RAD_TO_DEG;
  }

  if (pj_param(P.params, 'to_alpha')) {
    lamc  = pj_param(P.params, 'ro_lon_c');
    phic  = pj_param(P.params, 'ro_lat_c');
    alpha = pj_param(P.params, 'ro_alpha');

    if (fabs(fabs(phic) - M_HALFPI) <= TOL) e_error(-32);
    lamp = lamc + aatan2(-cos(alpha), -sin(alpha) * sin(phic));
    phip = aasin(cos(phic) * sin(alpha));

  } else if (pj_param(P.params, 'to_lat_p')) { /* specified new pole */
    lamp = pj_param(P.params, 'ro_lon_p');
    phip = pj_param(P.params, 'ro_lat_p');

  } else { /* specified new 'equator' points */

    lam1 = pj_param(P.params, 'ro_lon_1');
    phi1 = pj_param(P.params, 'ro_lat_1');
    lam2 = pj_param(P.params, 'ro_lon_2');
    phi2 = pj_param(P.params, 'ro_lat_2');
    if (fabs(phi1 - phi2) <= TOL ||
        (con = fabs(phi1)) <= TOL ||
        fabs(con - M_HALFPI) <= TOL ||
        fabs(fabs(phi2) - M_HALFPI) <= TOL) e_error(-33);
    lamp = atan2(cos(phi1) * sin(phi2) * cos(lam1) -
        sin(phi1) * cos(phi2) * cos(lam2),
        sin(phi1) * cos(phi2) * sin(lam2) -
        cos(phi1) * sin(phi2) * sin(lam1));
    phip = atan(-cos(lamp - lam1) / tan(phi1));
  }
  if (fabs(phip) > TOL) { /* oblique */
    cphip = cos(phip);
    sphip = sin(phip);
    P.fwd = o_fwd;
    P.inv = P2.inv ? o_inv : null;
  } else { /* transverse */
    P.fwd = t_fwd;
    P.inv = P2.inv ? t_inv : null;
  }

  function o_fwd(lp, xy) {
    var coslam, sinphi, cosphi;
    coslam = cos(lp.lam);
    sinphi = sin(lp.phi);
    cosphi = cos(lp.phi);
    lp.lam = adjlon(aatan2(cosphi * sin(lp.lam), sphip * cosphi * coslam +
        cphip * sinphi) + lamp);
    lp.phi = aasin(sphip * sinphi - cphip * cosphi * coslam);
    P2.fwd(lp, xy);
  }

  function t_fwd(lp, xy) {
    var cosphi, coslam;
    cosphi = cos(lp.phi);
    coslam = cos(lp.lam);
    lp.lam = adjlon(aatan2(cosphi * sin(lp.lam), sin(lp.phi)) + lamp);
    lp.phi = aasin(-cosphi * coslam);
    P2.fwd(lp, xy);
  }

  function o_inv(xy, lp) {
    var coslam, sinphi, cosphi;
    P2.inv(xy, lp);
    if (lp.lam != HUGE_VAL) {
      coslam = cos(lp.lam -= lamp);
      sinphi = sin(lp.phi);
      cosphi = cos(lp.phi);
      lp.phi = aasin(sphip * sinphi + cphip * cosphi * coslam);
      lp.lam = aatan2(cosphi * sin(lp.lam), sphip * cosphi * coslam -
        cphip * sinphi);
    }
  }

  function t_inv(xy, lp) {
    var cosphi, t;
    P2.inv(xy, lp);
    if (lp.lam != HUGE_VAL) {
      cosphi = cos(lp.phi);
      t = lp.lam - lamp;
      lp.lam = aatan2(cosphi * sin(t), - sin(lp.phi));
      lp.phi = aasin(cosphi * cos(t));
    }
  }
}


pj_add(pj_ocea, 'ocea', 'Oblique Cylindrical Equal Area', 'Cyl, Sph lonc= alpha= or\nlat_1= lat_2= lon_1= lon_2=');

function pj_ocea(P) {
  var phi_0 = 0,
      phi_1, phi_2, lam_1, lam_2, lonz, alpha,
      rok, rtk, sinphi, cosphi, singam, cosgam;
  rok = 1 / P.k0;
  rtk = P.k0;
  /*If the keyword "alpha" is found in the sentence then use 1point+1azimuth*/
  if (pj_param(P.params, "talpha")) {
    /*Define Pole of oblique transformation from 1 point & 1 azimuth*/
    alpha   = pj_param(P.params, "ralpha");
    lonz = pj_param(P.params, "rlonc");
    /*Equation 9-8 page 80 (http://pubs.usgs.gov/pp/1395/report.pdf)*/
    singam = atan(-cos(alpha)/(-sin(phi_0) * sin(alpha))) + lonz;
    /*Equation 9-7 page 80 (http://pubs.usgs.gov/pp/1395/report.pdf)*/
    sinphi = asin(cos(phi_0) * sin(alpha));
  /*If the keyword "alpha" is NOT found in the sentence then use 2points*/
  } else {
    /*Define Pole of oblique transformation from 2 points*/
    phi_1 = pj_param(P.params, "rlat_1");
    phi_2 = pj_param(P.params, "rlat_2");
    lam_1 = pj_param(P.params, "rlon_1");
    lam_2 = pj_param(P.params, "rlon_2");
    /*Equation 9-1 page 80 (http://pubs.usgs.gov/pp/1395/report.pdf)*/
    singam = atan2(cos(phi_1) * sin(phi_2) * cos(lam_1) -
      sin(phi_1) * cos(phi_2) * cos(lam_2),
      sin(phi_1) * cos(phi_2) * sin(lam_2) -
      cos(phi_1) * sin(phi_2) * sin(lam_1) );

    /* take care of P->lam0 wrap-around when +lam_1=-90*/
    if (lam_1 == -M_HALFPI)
      singam = -singam;

    /*Equation 9-2 page 80 (http://pubs.usgs.gov/pp/1395/report.pdf)*/
    sinphi = atan(-cos(singam - lam_1) / tan(phi_1));
  }
  P.lam0 = singam + M_HALFPI;
  cosphi = cos(sinphi);
  sinphi = sin(sinphi);
  cosgam = cos(singam);
  singam = sin(singam);
  P.es = 0;
  P.fwd = s_fwd;
  P.inv = s_inv;

  function s_fwd(lp, xy) {
    var t;
    xy.y = sin(lp.lam);
    t = cos(lp.lam);
    xy.x = atan((tan(lp.phi) * cosphi + sinphi * xy.y) / t);
    if (t < 0)
        xy.x += M_PI;
    xy.x *= rtk;
    xy.y = rok * (sinphi * sin(lp.phi) - cosphi * cos(lp.phi) * xy.y);
  }

  function s_inv(xy, lp) {
    var t, s;
    xy.y /= rok;
    xy.x /= rtk;
    t = sqrt(1 - xy.y * xy.y);
    lp.phi = asin(xy.y * sinphi + t * cosphi * (s = sin(xy.x)));
    lp.lam = atan2(t * sinphi * s - xy.y * cosphi,
        t * cos(xy.x));
  }
}


pj_add(pj_omerc, 'omerc', 'Oblique Mercator', 'Cyl, Sph&Ell no_rot\n' +
    'alpha= [gamma=] [no_off] lonc= or\nlon_1= lat_1= lon_2= lat_2=');

function pj_omerc(P) {
  var TOL = 1e-7;
  var con, com, cosph0, D, F, H, L, sinph0, p, J, gamma=0,
      gamma0, lamc=0, lam1=0, lam2=0, phi1=0, phi2=0, alpha_c=0;
  var alp, gam, no_off = 0;
  var A, B, E, AB, ArB, BrA, rB, singam, cosgam, sinrot, cosrot;
  var v_pole_n, v_pole_s, u_0;
  var no_rot;

  no_rot = pj_param(P.params, "tno_rot");
  if ((alp = pj_param(P.params, "talpha")) != 0)
  alpha_c = pj_param(P.params, "ralpha");
  if ((gam = pj_param(P.params, "tgamma")) != 0)
  gamma = pj_param(P.params, "rgamma");
  if (alp || gam) {
    lamc = pj_param(P.params, "rlonc");
    no_off =
      /* For libproj4 compatibility ... for backward compatibility */
      pj_param(P.params, "tno_off") || pj_param(P.params, "tno_uoff");
    if (no_off) {
      /* Mark the parameter as used, so that the pj_get_def() return them */
      pj_param(P.params, "sno_uoff");
      pj_param(P.params, "sno_off");
    }
  } else {
    lam1 = pj_param(P.params, "rlon_1");
    phi1 = pj_param(P.params, "rlat_1");
    lam2 = pj_param(P.params, "rlon_2");
    phi2 = pj_param(P.params, "rlat_2");
    if (fabs(phi1 - phi2) <= TOL || (con = fabs(phi1)) <= TOL ||
        fabs(con - M_HALFPI) <= TOL || fabs(fabs(P.phi0) - M_HALFPI) <= TOL ||
        fabs(fabs(phi2) - M_HALFPI) <= TOL) e_error(-33);
  }
  com = sqrt(P.one_es);
  if (fabs(P.phi0) > EPS10) {
    sinph0 = sin(P.phi0);
    cosph0 = cos(P.phi0);
    con = 1 - P.es * sinph0 * sinph0;
    B = cosph0 * cosph0;
    B = sqrt(1 + P.es * B * B / P.one_es);
    A = B * P.k0 * com / con;
    D = B * com / (cosph0 * sqrt(con));
    if ((F = D * D - 1) <= 0)
      F = 0;
    else {
      F = sqrt(F);
      if (P.phi0 < 0)
        F = -F;
    }
    E = F += D;
    E *= pow(pj_tsfn(P.phi0, sinph0, P.e), B);
  } else {
    B = 1 / com;
    A = P.k0;
    E = D = F = 1;
  }
  if (alp || gam) {
    if (alp) {
      gamma0 = asin(sin(alpha_c) / D);
      if (!gam)
          gamma = alpha_c;
    } else
        alpha_c = asin(D*sin(gamma0 = gamma));
    P.lam0 = lamc - asin(0.5 * (F - 1 / F) * tan(gamma0)) / B;
  } else {
    H = pow(pj_tsfn(phi1, sin(phi1), P.e), B);
    L = pow(pj_tsfn(phi2, sin(phi2), P.e), B);
    F = E / H;
    p = (L - H) / (L + H);
    J = E * E;
    J = (J - L * H) / (J + L * H);
    if ((con = lam1 - lam2) < -M_PI)
        lam2 -= M_TWOPI;
    else if (con > M_PI)
        lam2 += M_TWOPI;
    P.lam0 = adjlon(0.5 * (lam1 + lam2) - atan(J * tan(0.5 * B * (lam1 - lam2)) / p) / B);
    gamma0 = atan(2 * sin(B * adjlon(lam1 - P.lam0)) / (F - 1 / F));
    gamma = alpha_c = asin(D * sin(gamma0));
  }
  singam = sin(gamma0);
  cosgam = cos(gamma0);
  sinrot = sin(gamma);
  cosrot = cos(gamma);
  BrA = 1 / (ArB = A * (rB = 1 / B));
  AB = A * B;
  if (no_off)
    u_0 = 0;
  else {
    u_0 = fabs(ArB * atan(sqrt(D * D - 1) / cos(alpha_c)));
    if (P.phi0 < 0)
        u_0 = - u_0;
  }
  F = 0.5 * gamma0;
  v_pole_n = ArB * log(tan(M_FORTPI - F));
  v_pole_s = ArB * log(tan(M_FORTPI + F));

  P.fwd = e_fwd;
  P.inv = e_inv;

  function e_fwd(lp, xy) {
    var S, T, U, V, W, temp, u, v;

    if (fabs(fabs(lp.phi) - M_HALFPI) > EPS10) {
      W = E / pow(pj_tsfn(lp.phi, sin(lp.phi), P.e), B);
      temp = 1 / W;
      S = 0.5 * (W - temp);
      T = 0.5 * (W + temp);
      V = sin(B * lp.lam);
      U = (S * singam - V * cosgam) / T;
      if (fabs(fabs(U) - 1.0) < EPS10)
        f_error();
      v = 0.5 * ArB * log((1 - U)/(1 + U));
      temp = cos(B * lp.lam);
      if(fabs(temp) < TOL) {
          u = A * lp.lam;
      } else {
          u = ArB * atan2((S * cosgam + V * singam), temp);
      }
    } else {
        v = lp.phi > 0 ? v_pole_n : v_pole_s;
        u = ArB * lp.phi;
    }
    if (no_rot) {
        xy.x = u;
        xy.y = v;
    } else {
        u -= u_0;
        xy.x = v * cosrot + u * sinrot;
        xy.y = u * cosrot - v * sinrot;
    }
  }

  function e_inv(xy, lp) {
    var u, v, Qp, Sp, Tp, Vp, Up;
    if (no_rot) {
      v = xy.y;
      u = xy.x;
    } else {
      v = xy.x * cosrot - xy.y * sinrot;
      u = xy.y * cosrot + xy.x * sinrot + u_0;
    }
    Qp = exp(- BrA * v);
    Sp = 0.5 * (Qp - 1 / Qp);
    Tp = 0.5 * (Qp + 1 / Qp);
    Vp = sin(BrA * u);
    Up = (Vp * cosgam + Sp * singam) / Tp;
    if (fabs(fabs(Up) - 1) < EPS10) {
      lp.lam = 0;
      lp.phi = Up < 0 ? -M_HALFPI : M_HALFPI;
    } else {
      lp.phi = E / sqrt((1 + Up) / (1 - Up));
      if ((lp.phi = pj_phi2(pow(lp.phi, 1 / B), P.e)) == HUGE_VAL)
          i_error();
      lp.lam = - rB * atan2((Sp * cosgam - Vp * singam), cos(BrA * u));
    }
  }
}


pj_add(pj_ortho, 'ortho', 'Orthographic', 'Azi, Sph.');

function pj_ortho(P) {
  var EPS10 = 1.e-10,
      N_POLE = 0,
      S_POLE = 1,
      EQUIT = 2,
      OBLIQ = 3;
  var Q = {};

  if (fabs(fabs(P.phi0) - M_HALFPI) <= EPS10)
    Q.mode = P.phi0 < 0 ? S_POLE : N_POLE;
  else if (fabs(P.phi0) > EPS10) {
    Q.mode = OBLIQ;
    Q.sinph0 = sin(P.phi0);
    Q.cosph0 = cos(P.phi0);
  } else
    Q.mode = EQUIT;

  P.fwd = s_fwd;
  P.inv = s_inv;
  P.es = 0;

  function s_fwd(lp, xy) {
    var coslam, cosphi, sinphi;
    cosphi = cos(lp.phi);
    coslam = cos(lp.lam);
    switch (Q.mode) {
    case EQUIT:
      if (cosphi * coslam < - EPS10) f_error();
      xy.y = sin(lp.phi);
      break;
    case OBLIQ:
      if (Q.sinph0 * (sinphi = sin(lp.phi)) +
         Q.cosph0 * cosphi * coslam < - EPS10) f_error();
      xy.y = Q.cosph0 * sinphi - Q.sinph0 * cosphi * coslam;
      break;
    case N_POLE:
      coslam = -coslam;
      /* falls through */
    case S_POLE:
      if (fabs(lp.phi - P.phi0) - EPS10 > M_HALFPI) f_error();
      xy.y = cosphi * coslam;
      break;
    }
    xy.x = cosphi * sin(lp.lam);
  }

  function s_inv(xy, lp) {
    var rh, cosc, sinc;

    if ((sinc = (rh = hypot(xy.x, xy.y))) > 1) {
        if ((sinc - 1) > EPS10) i_error();
        sinc = 1;
    }
    cosc = sqrt(1 - sinc * sinc); /* in this range OK */
    if (fabs(rh) <= EPS10) {
        lp.phi = P.phi0;
        lp.lam = 0.0;
    } else {
        switch (Q.mode) {
        case N_POLE:
            xy.y = -xy.y;
            lp.phi = acos(sinc);
            break;
        case S_POLE:
            lp.phi = - acos(sinc);
            break;
        case EQUIT:
        case OBLIQ:
          if (Q.mode == EQUIT) {
            lp.phi = xy.y * sinc / rh;
            xy.x *= sinc;
            xy.y = cosc * rh;
          } else {
            lp.phi = cosc * Q.sinph0 + xy.y * sinc * Q.cosph0 /rh;
            xy.y = (cosc - Q.sinph0 * lp.phi) * rh;
            xy.x *= sinc * Q.cosph0;
          }
          if (fabs(lp.phi) >= 1)
              lp.phi = lp.phi < 0 ? -M_HALFPI : M_HALFPI;
          else
              lp.phi = asin(lp.phi);
          break;
        }
        lp.lam = (xy.y == 0 && (Q.mode == OBLIQ || Q.mode == EQUIT)) ?
          (xy.x == 0 ? 0 : xy.x < 0 ? -M_HALFPI : M_HALFPI) : atan2(xy.x, xy.y);
    }
  }
}


pj_add(pj_patterson, 'patterson', 'Patterson Cylindrical', 'Cyl., Sph.');

function pj_patterson(P) {
  var K1 = 1.0148,
    K2 = 0.23185,
    K3 = -0.14499,
    K4 = 0.02406,
    C1 = K1,
    C2 = (5.0 * K2),
    C3 = (7.0 * K3),
    C4 = (9.0 * K4),
    EPS = 1e-11,
    MAX_Y =  908571831.7;

  P.es = 0;
  P.fwd = s_fwd;
  P.inv = s_inv;

  function s_fwd(lp, xy) {
    var phi2 = lp.phi * lp.phi;
    xy.x = lp.lam;
    xy.y = lp.phi * (K1 + phi2 * phi2 * (K2 + phi2 * (K3 + K4 * phi2)));
  }

  function s_inv(xy, lp) {
    var MAX_ITER = 100;
    var yc, tol, y2, f, fder;
    var i;

    yc = xy.y;

    /* make sure y is inside valid range */
    if (xy.y > MAX_Y) {
      xy.y = MAX_Y;
    } else if (xy.y < -MAX_Y) {
      xy.y = -MAX_Y;
    }

    for (i = MAX_ITER; i ; --i) { /* Newton-Raphson */
      y2 = yc * yc;
      f = (yc * (K1 + y2 * y2 * (K2 + y2 * (K3 + K4 * y2)))) - xy.y;
      fder = C1 + y2 * y2 * (C2 + y2 * (C3 + C4 * y2));
      yc -= tol = f / fder;
      if (fabs(tol) < EPS) {
        break;
      }
    }
    // other projections don't error if non-convergent
    // if (i === 0) error(PJD_ERR_NON_CONVERGENT);
    lp.phi = yc;

    /* longitude */
    lp.lam = xy.x;
  }
}


pj_add(pj_poly, 'poly', 'Polyconic (American)', 'Conic, Sph&Ell');

function pj_poly(P) {
  var TOL = 1e-10,
      CONV = 1e-10,
      N_ITER = 10,
      I_ITER = 20,
      ITOL = 1.e-12,
      ml0, en;

  if (P.es) {
    en = pj_enfn(P.es);
    ml0 = pj_mlfn(P.phi0, sin(P.phi0), cos(P.phi0), en);
    P.fwd = e_fwd;
    P.inv = e_inv;
  } else {
    ml0 = -P.phi0;
    P.fwd = s_fwd;
    P.inv = s_inv;
  }

  function e_fwd(lp, xy) {
    var ms, sp, cp;

    if (fabs(lp.phi) <= TOL) {
      xy.x = lp.lam;
      xy.y = -ml0;
    } else {
      sp = sin(lp.phi);
      ms = fabs(cp = cos(lp.phi)) > TOL ? pj_msfn(sp, cp, P.es) / sp : 0;
      xy.x = ms * sin(lp.lam *= sp);
      xy.y = (pj_mlfn(lp.phi, sp, cp, en) - ml0) + ms * (1 - cos(lp.lam));
    }
  }

  function e_inv(xy, lp) {
    var x = xy.x, y = xy.y;
    var r, c, sp, cp, s2ph, ml, mlb, mlp, dPhi, i;
    y += ml0;
    if (fabs(y) <= TOL) {
      lp.lam = x;
      lp.phi = 0;
    } else {
      r = y * y + x * x;
      for (lp.phi = y, i = I_ITER; i>0 ; --i) {
        sp = sin(lp.phi);
        s2ph = sp * (cp = cos(lp.phi));
        if (fabs(cp) < ITOL)
          i_error();
        c = sp * (mlp = sqrt(1 - P.es * sp * sp)) / cp;
        ml = pj_mlfn(lp.phi, sp, cp, en);
        mlb = ml * ml + r;
        mlp = P.one_es / (mlp * mlp * mlp);
        lp.phi += (dPhi =
          ( ml + ml + c * mlb - 2 * y * (c * ml + 1) ) / (
          P.es * s2ph * (mlb - 2 * y * ml) / c +
          2 * (y - ml) * (c * mlp - 1 / s2ph) - mlp - mlp));
        if (fabs(dPhi) <= ITOL)
          break;
      }
      if (!i) {
        i_error();
      }
      c = sin(lp.phi);
      lp.lam = asin(x * tan(lp.phi) * sqrt(1 - P.es * c * c)) / sin(lp.phi);
    }
  }

  function s_fwd(lp, xy) {
    var cot, E;
    if (fabs(lp.phi) <= TOL) {
      xy.x = lp.lam;
      xy.y = ml0;
    } else {
      cot = 1 / tan(lp.phi);
      xy.x = sin(E = lp.lam * sin(lp.phi)) * cot;
      xy.y = lp.phi - P.phi0 + cot * (1 - cos(E));
    }
  }

  function s_inv(xy, lp) {
    var B, dphi, tp, i;
    if (fabs(xy.y = P.phi0 + xy.y) <= TOL) {
      lp.lam = xy.x;
      lp.phi = 0;
    } else {
      lp.phi = xy.y;
      B = xy.x * xy.x + xy.y * xy.y;
      i = N_ITER;
      do {
        tp = tan(lp.phi);
        lp.phi -= (dphi = (xy.y * (lp.phi * tp + 1) - lp.phi -
          0.5 * ( lp.phi * lp.phi + B) * tp) /
          ((lp.phi - xy.y) / tp - 1));
      } while (fabs(dphi) > CONV && --i);
      if (!i) i_error();
      lp.lam = asin(xy.x * tan(lp.phi)) / sin(lp.phi);
    }
  }
}


pj_add(pj_putp2, 'putp2', 'Putnins P2', 'PCyl., Sph.');

function pj_putp2(P) {
  var C_x = 1.89490,
      C_y = 1.71848,
      C_p = 0.6141848493043784,
      EPS = 1e-10,
      NITER = 10,
      PI_DIV_3 = 1.0471975511965977;
  P.es = 0;
  P.fwd = s_fwd;
  P.inv = s_inv;

  function s_fwd(lp, xy) {
    var p, c, s, V, i;
    p = C_p * sin(lp.phi);
    s = lp.phi * lp.phi;
    lp.phi *= 0.615709 + s * ( 0.00909953 + s * 0.0046292 );
    for (i = NITER; i ; --i) {
      c = cos(lp.phi);
      s = sin(lp.phi);
      lp.phi -= V = (lp.phi + s * (c - 1) - p) /
        (1 + c * (c - 1) - s * s);
      if (fabs(V) < EPS)
        break;
    }
    if (!i)
      lp.phi = lp.phi < 0 ? - PI_DIV_3 : PI_DIV_3;
    xy.x = C_x * lp.lam * (cos(lp.phi) - 0.5);
    xy.y = C_y * sin(lp.phi);
  }

  function s_inv(xy, lp) {
    var c;
    lp.phi = aasin(xy.y / C_y);
    lp.lam = xy.x / (C_x * ((c = cos(lp.phi)) - 0.5));
    lp.phi = aasin((lp.phi + sin(lp.phi) * (c - 1)) / C_p);
  }
}


pj_add(pj_putp3, 'putp3', 'Putnins P3', 'PCyl., Sph.');
pj_add(pj_putp3p, 'putp3p', 'Putnins P3\'', 'PCyl., Sph.');

function pj_putp3p(P) {
  pj_putp3(P, true);
}

function pj_putp3(P, prime) {
  var C = 0.79788456,
      RPISQ = 0.1013211836,
      A = (prime ? 2 : 4) * RPISQ;
  P.es = 0;
  P.fwd = s_fwd;
  P.inv = s_inv;

  function s_fwd(lp, xy) {
    xy.x = C * lp.lam * (1 - A * lp.phi * lp.phi);
    xy.y = C * lp.phi;
  }

  function s_inv(xy, lp) {
    lp.phi = xy.y / C;
    lp.lam = xy.x / (C * (1 - A * lp.phi * lp.phi));
  }
}


pj_add(pj_putp4p, 'putp4p', 'Putnins P4\'', 'PCyl., Sph.');
pj_add(pj_weren, 'weren', 'Werenskiold I', 'PCyl., Sph.');

function pj_putp4p(P) {
  pj_putp4p_init(P, 0.874038744, 3.883251825);
}

function pj_weren(P) {
  pj_putp4p_init(P, 1, 4.442882938);
}

function pj_putp4p_init(P, C_x, C_y) {
  P.es = 0;
  P.fwd = s_fwd;
  P.inv = s_inv;

  function s_fwd(lp, xy) {
    lp.phi = aasin(0.883883476 * sin(lp.phi));
    xy.x = C_x * lp.lam * cos(lp.phi);
    xy.x /= cos(lp.phi *= 0.333333333333333);
    xy.y = C_y * sin(lp.phi);
  }

  function s_inv(xy, lp) {
    lp.phi = aasin(xy.y / C_y);
    lp.lam = xy.x * cos(lp.phi) / C_x;
    lp.phi *= 3;
    lp.lam /= cos(lp.phi);
    lp.phi = aasin(1.13137085 * sin(lp.phi));
  }
}


pj_add(pj_putp5, 'putp5', 'Putnins P5', 'PCyl., Sph.');
pj_add(pj_putp5p, 'putp5p', 'Putnins P5\'', 'PCyl., Sph.');

function pj_putp5p(P) {
  pj_putp5(P, true);
}

function pj_putp5(P, prime) {
  var A = (prime ? 1.5 : 2),
      B = (prime ? 0.5 : 1),
      C = 1.01346,
      D = 1.2158542;

  P.es = 0;
  P.fwd = s_fwd;
  P.inv = s_inv;

  function s_fwd(lp, xy) {
    xy.x = C * lp.lam * (A - B * sqrt(1 + D * lp.phi * lp.phi));
    xy.y = C * lp.phi;
  }

  function s_inv(xy, lp) {
    lp.phi = xy.y / C;
    lp.lam = xy.x / (C * (A - B * sqrt(1 + D * lp.phi * lp.phi)));
  }
}


pj_add(pj_putp6, 'putp6', 'Putnins P6', 'PCyl., Sph.');
pj_add(pj_putp6p, 'putp6p', 'Putnins P6\'', 'PCyl., Sph.');

function pj_putp6p(P) {
  pj_putp6(P, true);
}

function pj_putp6(P, prime) {
  var EPS = 1e-10,
      NITER = 10,
      CON_POLE = 1.732050807568877,
      A, B, C_x, C_y, D;

  if (prime) {
    C_x = 0.44329;
    C_y = 0.80404;
    A   = 6;
    B   = 5.61125;
    D   = 3;
  } else {
    C_x = 1.01346;
    C_y = 0.91910;
    A   = 4;
    B   = 2.1471437182129378784;
    D   = 2;
  }

  P.es = 0;
  P.fwd = s_fwd;
  P.inv = s_inv;

  function s_fwd(lp, xy) {
    var p, r, V, i;
    p = B * sin(lp.phi);
    lp.phi *=  1.10265779;
    for (i = NITER; i ; --i) {
        r = sqrt(1 + lp.phi * lp.phi);
        lp.phi -= V = ( (A - r) * lp.phi - log(lp.phi + r) - p ) /
            (A - 2 * r);
        if (fabs(V) < EPS)
            break;
    }
    if (!i)
        lp.phi = p < 0 ? -CON_POLE : CON_POLE;
    xy.x = C_x * lp.lam * (D - sqrt(1 + lp.phi * lp.phi));
    xy.y = C_y * lp.phi;
  }

  function s_inv(xy, lp) {
    var r;
    lp.phi = xy.y / C_y;
    r = sqrt(1 + lp.phi * lp.phi);
    lp.lam = xy.x / (C_x * (D - r));
    lp.phi = aasin(((A - r) * lp.phi - log(lp.phi + r)) / B);
  }
}


pj_add(pj_qsc, 'qsc', 'Quadrilateralized Spherical Cube', 'Azi, Sph.');

function pj_qsc(P) {
  var EPS10 = 1.e-10;

  /* The six cube faces. */
  var FACE_FRONT = 0;
  var FACE_RIGHT = 1;
  var FACE_BACK = 2;
  var FACE_LEFT = 3;
  var FACE_TOP = 4;
  var FACE_BOTTOM = 5;

  /* The four areas on a cube face. AREA_0 is the area of definition,
   * the other three areas are counted counterclockwise. */
  var AREA_0 = 0;
  var AREA_1 = 1;
  var AREA_2 = 2;
  var AREA_3 = 3;
  var face;
  var a_squared;
  var b;
  var one_minus_f;
  var one_minus_f_squared;

  /* Determine the cube face from the center of projection. */
  if (P.phi0 >= M_HALFPI - M_FORTPI / 2.0) {
    face = FACE_TOP;
  } else if (P.phi0 <= -(M_HALFPI - M_FORTPI / 2.0)) {
    face = FACE_BOTTOM;
  } else if (fabs(P.lam0) <= M_FORTPI) {
    face = FACE_FRONT;
  } else if (fabs(P.lam0) <= M_HALFPI + M_FORTPI) {
    face = (P.lam0 > 0.0 ? FACE_RIGHT : FACE_LEFT);
  } else {
    face = FACE_BACK;
  }
  /* Fill in useful values for the ellipsoid <-> sphere shift
   * described in [LK12]. */
  if (P.es !== 0.0) {
    a_squared = P.a * P.a;
    b = P.a * sqrt(1.0 - P.es);
    one_minus_f = 1.0 - (P.a - b) / P.a;
    one_minus_f_squared = one_minus_f * one_minus_f;
  }

  P.fwd = e_fwd;
  P.inv = e_inv;

  function e_fwd(lp, xy) {
    var lat, lon;
    var theta, phi;
    var t, mu; /* nu; */
    var area;
    var q, r, s;
    var sinlat, coslat;
    var sinlon, coslon;
    var tmp;

    /* Convert the geodetic latitude to a geocentric latitude.
     * This corresponds to the shift from the ellipsoid to the sphere
     * described in [LK12]. */
    if (P.es !== 0.0) {
      lat = atan(one_minus_f_squared * tan(lp.phi));
    } else {
      lat = lp.phi;
    }

    /* Convert the input lat, lon into theta, phi as used by QSC.
     * This depends on the cube face and the area on it.
     * For the top and bottom face, we can compute theta and phi
     * directly from phi, lam. For the other faces, we must use
     * unit sphere cartesian coordinates as an intermediate step. */
    lon = lp.lam;
    if (face == FACE_TOP) {
      phi = M_HALFPI - lat;
      if (lon >= M_FORTPI && lon <= M_HALFPI + M_FORTPI) {
        area = AREA_0;
        theta = lon - M_HALFPI;
      } else if (lon > M_HALFPI + M_FORTPI || lon <= -(M_HALFPI + M_FORTPI)) {
        area = AREA_1;
        theta = (lon > 0.0 ? lon - M_PI : lon + M_PI);
      } else if (lon > -(M_HALFPI + M_FORTPI) && lon <= -M_FORTPI) {
        area = AREA_2;
        theta = lon + M_HALFPI;
      } else {
        area = AREA_3;
        theta = lon;
      }
    } else if (face == FACE_BOTTOM) {
      phi = M_HALFPI + lat;
      if (lon >= M_FORTPI && lon <= M_HALFPI + M_FORTPI) {
        area = AREA_0;
        theta = -lon + M_HALFPI;
      } else if (lon < M_FORTPI && lon >= -M_FORTPI) {
        area = AREA_1;
        theta = -lon;
      } else if (lon < -M_FORTPI && lon >= -(M_HALFPI + M_FORTPI)) {
        area = AREA_2;
        theta = -lon - M_HALFPI;
      } else {
        area = AREA_3;
        theta = (lon > 0.0 ? -lon + M_PI : -lon - M_PI);
      }
    } else {
      if (face == FACE_RIGHT) {
        lon = qsc_shift_lon_origin(lon, +M_HALFPI);
      } else if (face == FACE_BACK) {
        lon = qsc_shift_lon_origin(lon, +M_PI);
      } else if (face == FACE_LEFT) {
        lon = qsc_shift_lon_origin(lon, -M_HALFPI);
      }
      sinlat = sin(lat);
      coslat = cos(lat);
      sinlon = sin(lon);
      coslon = cos(lon);
      q = coslat * coslon;
      r = coslat * sinlon;
      s = sinlat;

      if (face == FACE_FRONT) {
        phi = acos(q);
        tmp = qsc_fwd_equat_face_theta(phi, s, r);
      } else if (face == FACE_RIGHT) {
        phi = acos(r);
        tmp = qsc_fwd_equat_face_theta(phi, s, -q);
      } else if (face == FACE_BACK) {
        phi = acos(-q);
        tmp = qsc_fwd_equat_face_theta(phi, s, -r);
      } else if (face == FACE_LEFT) {
        phi = acos(-r);
        tmp = qsc_fwd_equat_face_theta(phi, s, q);
      } else {
        /* Impossible */
        phi = 0.0;
        tmp = {
          area: AREA_0,
          theta: 0
        };
      }
      theta = tmp.theta;
      area = tmp.area;
    }

    /* Compute mu and nu for the area of definition.
     * For mu, see Eq. (3-21) in [OL76], but note the typos:
     * compare with Eq. (3-14). For nu, see Eq. (3-38). */
    mu = atan((12.0 / M_PI) * (theta + acos(sin(theta) * cos(M_FORTPI)) - M_HALFPI));
    t = sqrt((1.0 - cos(phi)) / (cos(mu) * cos(mu)) / (1.0 - cos(atan(1.0 / cos(theta)))));
    /* nu = atan(t);        We don't really need nu, just t, see below. */

    /* Apply the result to the real area. */
    if (area == AREA_1) {
      mu += M_HALFPI;
    } else if (area == AREA_2) {
      mu += M_PI;
    } else if (area == AREA_3) {
      mu += M_PI_HALFPI;
    }

    /* Now compute x, y from mu and nu */
    /* t = tan(nu); */
    xy.x = t * cos(mu);
    xy.y = t * sin(mu);
  }

  function e_inv(xy, lp) {
    var mu, nu, cosmu, tannu;
    var tantheta, theta, cosphi, phi;
    var t;
    var area;

    /* Convert the input x, y to the mu and nu angles as used by QSC.
     * This depends on the area of the cube face. */
    nu = atan(sqrt(xy.x * xy.x + xy.y * xy.y));
    mu = atan2(xy.y, xy.x);
    if (xy.x >= 0.0 && xy.x >= fabs(xy.y)) {
      area = AREA_0;
    } else if (xy.y >= 0.0 && xy.y >= fabs(xy.x)) {
      area = AREA_1;
      mu -= M_HALFPI;
    } else if (xy.x < 0.0 && -xy.x >= fabs(xy.y)) {
      area = AREA_2;
      mu = (mu < 0.0 ? mu + M_PI : mu - M_PI);
    } else {
      area = AREA_3;
      mu += M_HALFPI;
    }

    /* Compute phi and theta for the area of definition.
     * The inverse projection is not described in the original paper, but some
     * good hints can be found here (as of 2011-12-14):
     * http://fits.gsfc.nasa.gov/fitsbits/saf.93/saf.9302
     * (search for "Message-Id: <9302181759.AA25477 at fits.cv.nrao.edu>") */
    t = (M_PI / 12.0) * tan(mu);
    tantheta = sin(t) / (cos(t) - (1.0 / sqrt(2.0)));
    theta = atan(tantheta);
    cosmu = cos(mu);
    tannu = tan(nu);
    cosphi = 1.0 - cosmu * cosmu * tannu * tannu * (1.0 - cos(atan(1.0 / cos(theta))));
    if (cosphi < -1.0) {
      cosphi = -1.0;
    } else if (cosphi > +1.0) {
      cosphi = +1.0;
    }

    /* Apply the result to the real area on the cube face.
     * For the top and bottom face, we can compute phi and lam directly.
     * For the other faces, we must use unit sphere cartesian coordinates
     * as an intermediate step. */
    if (face == FACE_TOP) {
      phi = acos(cosphi);
      lp.phi = M_HALFPI - phi;
      if (area == AREA_0) {
        lp.lam = theta + M_HALFPI;
      } else if (area == AREA_1) {
        lp.lam = (theta < 0.0 ? theta + M_PI : theta - M_PI);
      } else if (area == AREA_2) {
        lp.lam = theta - M_HALFPI;
      } else /* area == AREA_3 */ {
        lp.lam = theta;
      }
    } else if (face == FACE_BOTTOM) {
      phi = acos(cosphi);
      lp.phi = phi - M_HALFPI;
      if (area == AREA_0) {
        lp.lam = -theta + M_HALFPI;
      } else if (area == AREA_1) {
        lp.lam = -theta;
      } else if (area == AREA_2) {
        lp.lam = -theta - M_HALFPI;
      } else /* area == AREA_3 */ {
        lp.lam = (theta < 0.0 ? -theta - M_PI : -theta + M_PI);
      }
    } else {
      /* Compute phi and lam via cartesian unit sphere coordinates. */
      var q, r, s;
      q = cosphi;
      t = q * q;
      if (t >= 1.0) {
        s = 0.0;
      } else {
        s = sqrt(1.0 - t) * sin(theta);
      }
      t += s * s;
      if (t >= 1.0) {
        r = 0.0;
      } else {
        r = sqrt(1.0 - t);
      }
      /* Rotate q,r,s into the correct area. */
      if (area == AREA_1) {
        t = r;
        r = -s;
        s = t;
      } else if (area == AREA_2) {
        r = -r;
        s = -s;
      } else if (area == AREA_3) {
        t = r;
        r = s;
        s = -t;
      }
      /* Rotate q,r,s into the correct cube face. */
      if (face == FACE_RIGHT) {
        t = q;
        q = -r;
        r = t;
      } else if (face == FACE_BACK) {
        q = -q;
        r = -r;
      } else if (face == FACE_LEFT) {
        t = q;
        q = r;
        r = -t;
      }
      /* Now compute phi and lam from the unit sphere coordinates. */
      lp.phi = acos(-s) - M_HALFPI;
      lp.lam = atan2(r, q);
      if (face == FACE_RIGHT) {
        lp.lam = qsc_shift_lon_origin(lp.lam, -M_HALFPI);
      } else if (face == FACE_BACK) {
        lp.lam = qsc_shift_lon_origin(lp.lam, -M_PI);
      } else if (face == FACE_LEFT) {
        lp.lam = qsc_shift_lon_origin(lp.lam, +M_HALFPI);
      }
    }

    /* Apply the shift from the sphere to the ellipsoid as described
     * in [LK12]. */
    if (P.es !== 0) {
      var invert_sign;
      var tanphi, xa;
      invert_sign = (lp.phi < 0.0 ? 1 : 0);
      tanphi = tan(lp.phi);
      xa = b / sqrt(tanphi * tanphi + one_minus_f_squared);
      lp.phi = atan(sqrt(P.a * P.a - xa * xa) / (one_minus_f * xa));
      if (invert_sign) {
        lp.phi = -lp.phi;
      }
    }
  }

  /* Helper function for forward projection: compute the theta angle
   * and determine the area number. */
  function qsc_fwd_equat_face_theta(phi, y, x) {
    var area, theta;
    if (phi < EPS10) {
      area = AREA_0;
      theta = 0.0;
    } else {
      theta = atan2(y, x);
      if (fabs(theta) <= M_FORTPI) {
        area = AREA_0;
      } else if (theta > M_FORTPI && theta <= M_HALFPI + M_FORTPI) {
        area = AREA_1;
        theta -= M_HALFPI;
      } else if (theta > M_HALFPI + M_FORTPI || theta <= -(M_HALFPI + M_FORTPI)) {
        area = AREA_2;
        theta = (theta >= 0.0 ? theta - M_PI : theta + M_PI);
      } else {
        area = AREA_3;
        theta += M_HALFPI;
      }
    }
    return {
      area: area,
      theta: theta
    };
  }

  /* Helper function: shift the longitude. */
  function qsc_shift_lon_origin(lon, offset) {
    var slon = lon + offset;
    if (slon < -M_PI) {
      slon += M_TWOPI;
    } else if (slon > +M_PI) {
      slon -= M_TWOPI;
    }
    return slon;
  }
}


pj_add(pj_robin, 'robin', 'Robinson', 'PCyl., Sph.');

function pj_robin(P) {
  var X = to_float([
    [1, 2.2199e-17, -7.15515e-05, 3.1103e-06],
    [0.9986, -0.000482243, -2.4897e-05, -1.3309e-06],
    [0.9954, -0.00083103, -4.48605e-05, -9.86701e-07],
    [0.99, -0.00135364, -5.9661e-05, 3.6777e-06],
    [0.9822, -0.00167442, -4.49547e-06, -5.72411e-06],
    [0.973, -0.00214868, -9.03571e-05, 1.8736e-08],
    [0.96, -0.00305085, -9.00761e-05, 1.64917e-06],
    [0.9427, -0.00382792, -6.53386e-05, -2.6154e-06],
    [0.9216, -0.00467746, -0.00010457, 4.81243e-06],
    [0.8962, -0.00536223, -3.23831e-05, -5.43432e-06],
    [0.8679, -0.00609363, -0.000113898, 3.32484e-06],
    [0.835, -0.00698325, -6.40253e-05, 9.34959e-07],
    [0.7986, -0.00755338, -5.00009e-05, 9.35324e-07],
    [0.7597, -0.00798324, -3.5971e-05, -2.27626e-06],
    [0.7186, -0.00851367, -7.01149e-05, -8.6303e-06],
    [0.6732, -0.00986209, -0.000199569, 1.91974e-05],
    [0.6213, -0.010418, 8.83923e-05, 6.24051e-06],
    [0.5722, -0.00906601, 0.000182, 6.24051e-06],
    [0.5322, -0.00677797, 0.000275608, 6.24051e-06]
  ]);

  var Y = to_float([
    [-5.20417e-18, 0.0124, 1.21431e-18, -8.45284e-11],
    [0.062, 0.0124, -1.26793e-09, 4.22642e-10],
    [0.124, 0.0124, 5.07171e-09, -1.60604e-09],
    [0.186, 0.0123999, -1.90189e-08, 6.00152e-09],
    [0.248, 0.0124002, 7.10039e-08, -2.24e-08],
    [0.31, 0.0123992, -2.64997e-07, 8.35986e-08],
    [0.372, 0.0124029, 9.88983e-07, -3.11994e-07],
    [0.434, 0.0123893, -3.69093e-06, -4.35621e-07],
    [0.4958, 0.0123198, -1.02252e-05, -3.45523e-07],
    [0.5571, 0.0121916, -1.54081e-05, -5.82288e-07],
    [0.6176, 0.0119938, -2.41424e-05, -5.25327e-07],
    [0.6769, 0.011713, -3.20223e-05, -5.16405e-07],
    [0.7346, 0.0113541, -3.97684e-05, -6.09052e-07],
    [0.7903, 0.0109107, -4.89042e-05, -1.04739e-06],
    [0.8435, 0.0103431, -6.4615e-05, -1.40374e-09],
    [0.8936, 0.00969686, -6.4636e-05, -8.547e-06],
    [0.9394, 0.00840947, -0.000192841, -4.2106e-06],
    [0.9761, 0.00616527, -0.000256, -4.2106e-06],
    [1, 0.00328947, -0.000319159, -4.2106e-06]
  ]);

  var FXC = 0.8487,
      FYC = 1.3523,
      C1 = 11.45915590261646417544,
      RC1 = 0.08726646259971647884,
      NODES = 18,
      ONEEPS = 1.000001,
      EPS = 1e-8;

  P.es = 0;
  P.fwd = s_fwd;
  P.inv = s_inv;

  function s_fwd(lp, xy) {
    var i, dphi;
    i = floor((dphi = fabs(lp.phi)) * C1);
    if (i < 0) f_error();
    if (i >= NODES) i = NODES - 1;
    dphi = RAD_TO_DEG * (dphi - RC1 * i);
    xy.x = V(X[i], dphi) * FXC * lp.lam;
    xy.y = V(Y[i], dphi) * FYC;
    if (lp.phi < 0) xy.y = -xy.y;
  }

  function s_inv(xy, lp) {
    var t, t1, T, i;
    lp.lam = xy.x / FXC;
    lp.phi = fabs(xy.y / FYC);
    if (lp.phi >= 1) { /* simple pathologic cases */
      if (lp.phi > ONEEPS) i_error();
      else {
        lp.phi = xy.y < 0 ? -M_HALFPI : M_HALFPI;
        lp.lam /= X[NODES][0];
      }
    } else { /* general problem */
      /* in Y space, reduce to table interval */
      i = floor(lp.phi * NODES);
      if (i < 0 || i >= NODES) {
        return i_error();
      }
      for (;;) {
        if (Y[i][0] > lp.phi) --i;
        else if (Y[i+1][0] <= lp.phi) ++i;
        else break;
      }
      T = new Float32Array(Y[i]); // copy row to avoid mutating constants
      /* first guess, linear interp */
      t = 5 * (lp.phi - T[0])/(Y[i+1][0] - T[0]);
      /* make into root */
      T[0] -= lp.phi;
      for (;;) { /* Newton-Raphson reduction */
        t -= t1 = V(T,t) / DV(T,t);
        if (fabs(t1) < EPS) break;
      }
      lp.phi = (5 * i + t) * DEG_TO_RAD;
      if (xy.y < 0) lp.phi = -lp.phi;
      lp.lam /= V(X[i], t);
    }
  }

  function V(C, z) {
    return C[0] + z * (C[1] + z * (C[2] + z * C[3]));
  }

  function DV(C, z) {
    return C[1] + z * (C[2] + C[2] + z * 3 * C[3]);
  }

  // convert constants to single-precision floats, for compatibility with
  // Proj.4 tests (PJ_robin.c uses floats instead of doubles)
  function to_float(rows) {
    return rows.map(function(row) {
      return new Float32Array(row);
    });
  }
}


pj_add(pj_get_sconic('EULER'), 'euler', 'Euler', 'Conic, Sph\nlat_1= and lat_2=');
pj_add(pj_get_sconic('MURD1'), 'murd1', 'Murdoch I', 'Conic, Sph\nlat_1= and lat_2=');
pj_add(pj_get_sconic('MURD2'), 'murd2', 'Murdoch II', 'Conic, Sph\nlat_1= and lat_2=');
pj_add(pj_get_sconic('MURD3'), 'murd3', 'Murdoch III', 'Conic, Sph\nlat_1= and lat_2=');
pj_add(pj_get_sconic('PCONIC'), 'pconic', 'Perspective Conic', 'Conic, Sph\nlat_1= and lat_2=');
pj_add(pj_get_sconic('TISSOT'), 'tissot', 'Tissot', 'Conic, Sph\nlat_1= and lat_2=');
pj_add(pj_get_sconic('VITK1'), 'vitk1', 'Vitkovsky I', 'Conic, Sph\nlat_1= and lat_2=');

function pj_get_sconic(type) {
  return function(P) {
    pj_sconic(P, type);
  };
}

function pj_sconic(P, type) {
  var del, cs;
  var p1, p2;
  var n;
  var rho_c;
  var rho_0;
  var sig;
  var c1, c2;
  var EPS = 1e-10;

  if (!pj_param(P.params, "tlat_1") || !pj_param(P.params, "tlat_2")) {
    e_error(-41);
  } else {
    p1 = pj_param(P.params, "rlat_1");
    p2 = pj_param(P.params, "rlat_2");
    del = 0.5 * (p2 - p1);
    sig = 0.5 * (p2 + p1);
    if (fabs(del) < EPS || fabs(sig) < EPS) {
      e_error(-42);
    }
  }

  switch (type) {
    case 'TISSOT':
      n = sin(sig);
      cs = cos(del);
      rho_c = n / cs + cs / n;
      rho_0 = sqrt((rho_c - 2 * sin(P.phi0)) / n);
      break;

    case 'MURD1':
      rho_c = sin(del) / (del * tan(sig)) + sig;
      rho_0 = rho_c - P.phi0;
      n = sin(sig);
      break;

    case 'MURD2':
      rho_c = (cs = sqrt(cos(del))) / tan(sig);
      rho_0 = rho_c + tan(sig - P.phi0);
      n = sin(sig) * cs;
      break;

    case 'MURD3':
      rho_c = del / (tan(sig) * tan(del)) + sig;
      rho_0 = rho_c - P.phi0;
      n = sin(sig) * sin(del) * tan(del) / (del * del);
      break;

    case 'EULER':
      n = sin(sig) * sin(del) / del;
      del *= 0.5;
      rho_c = del / (tan(del) * tan(sig)) + sig;
      rho_0 = rho_c - P.phi0;
      break;

    case 'PCONIC':
      n = sin(sig);
      c2 = cos(del);
      c1 = 1 / tan(sig);
      if (fabs(del = P.phi0 - sig) - EPS >= M_HALFPI)
        e_error(-43);
      rho_0 = c2 * (c1 - tan(del));
      break;

    case 'VITK1':
      n = (cs = tan(del)) * sin(sig) / del;
      rho_c = del / (cs * tan(sig)) + sig;
      rho_0 = rho_c - P.phi0;
      break;
  }

  P.inv = s_inv;
  P.fwd = s_fwd;
  P.es = 0;

  function s_fwd(lp, xy) {
    var rho;

    switch (type) {
      case 'MURD2':
        rho = rho_c + tan(sig - lp.phi);
        break;
      case 'PCONIC':
        rho = c2 * (c1 - tan(lp.phi - sig));
        break;
      default:
        rho = rho_c - lp.phi;
        break;
    }
    xy.x = rho * sin(lp.lam *= n);
    xy.y = rho_0 - rho * cos(lp.lam);
  }

  function s_inv(xy, lp) {
    var rho;

    rho = hypot(xy.x, xy.y = rho_0 - xy.y);
    if (n < 0) {
      rho = -rho;
      xy.x = -xy.x;
      xy.y = -xy.y;
    }

    lp.lam = atan2(xy.x, xy.y) / n;

    switch (type) {
      case 'PCONIC':
        lp.phi = atan(c1 - rho / c2) + sig;
        break;
      case 'MURD2':
        lp.phi = sig - atan(rho - rho_c);
        break;
      default:
        lp.phi = rho_c - rho;
    }
  }
}


pj_add(pj_somerc, 'somerc', 'Swiss. Obl. Mercator', 'Cyl, Ell\nFor CH1903');

function pj_somerc(P) {
  var K, c, hlf_e, kR, cosp0, sinp0;
  var EPS = 1.e-10;
  var NITER = 6;
  var cp, phip0, sp;
  hlf_e = 0.5 * P.e;
  cp = cos (P.phi0);
  cp *= cp;
  c = sqrt (1 + P.es * cp * cp * P.rone_es);
  sp = sin (P.phi0);
  cosp0 = cos(phip0 = aasin(sinp0 = sp / c));
  sp *= P.e;
  K = log (tan(M_FORTPI + 0.5 * phip0)) - c * (
      log (tan(M_FORTPI + 0.5 * P.phi0)) - hlf_e *
      log ((1 + sp) / (1 - sp)));
  kR = P.k0 * sqrt(P.one_es) / (1 - sp * sp);
  P.inv = e_inv;
  P.fwd = e_fwd;

  function e_fwd(lp, xy) {
    var phip, lamp, phipp, lampp, sp, cp;
    sp = P.e * sin(lp.phi);
    phip = 2* atan(exp(c * (log(tan(M_FORTPI + 0.5 * lp.phi)) -
        hlf_e * log((1 + sp)/(1 - sp))) + K)) - M_HALFPI;
    lamp = c * lp.lam;
    cp = cos(phip);
    phipp = aasin(cosp0 * sin(phip) - sinp0 * cp * cos(lamp));
    lampp = aasin(cp * sin(lamp) / cos(phipp));
    xy.x = kR * lampp;
    xy.y = kR * log(tan(M_FORTPI + 0.5 * phipp));
  }

  function e_inv(xy, lp) {
    var phip, lamp, phipp, lampp, cp, esp, con, delp;
    var i;
    phipp = 2 * (atan(exp(xy.y / kR)) - M_FORTPI);
    lampp = xy.x / kR;
    cp = cos (phipp);
    phip = aasin(cosp0 * sin(phipp) + sinp0 * cp * cos(lampp));
    lamp = aasin(cp * sin(lampp) / cos(phip));
    con = (K - log(tan(M_FORTPI + 0.5 * phip)))/c;
    for (i = NITER; i; --i) {
      esp = P.e * sin(phip);
      delp = (con + log(tan(M_FORTPI + 0.5 * phip)) - hlf_e *
        log((1 + esp)/(1 - esp))) * (1 - esp * esp) * cos(phip) * P.rone_es;
      phip -= delp;
      if (fabs(delp) < EPS)
        break;
    }
    if (i) {
      lp.phi = phip;
      lp.lam = lamp / c;
    } else
      i_error();
  }
}


pj_add(pj_stere, 'stere', 'Stereographic', 'Azi, Sph&Ell\nlat_ts=');
pj_add(pj_ups, 'ups', 'Universal Polar Stereographic', 'Azi, Sph&Ell\nsouth');

function pj_ups(P) {
  P.phi0 = pj_param(P.params, "bsouth") ? -M_HALFPI : M_HALFPI;
  P.k0 = 0.994;
  P.x0 = 2000000;
  P.y0 = 2000000;
  P.lam0 = 0;
  if (!P.es) e_error(-34);
  pj_stere_init(P, M_HALFPI);
}

function pj_stere(P) {
  var phits = pj_param (P.params, "tlat_ts") ? pj_param (P.params, "rlat_ts") : M_HALFPI;
  pj_stere_init(P, phits);
}

function pj_stere_init(P, phits) {
  var EPS10 = 1.e-10,
      TOL = 1.e-8,
      NITER = 8,
      CONV = 1.e-10,
      S_POLE = 0,
      N_POLE = 1,
      OBLIQ= 2,
      EQUIT = 3;
  var X, t, sinph0, cosph0;
  var sinX1, cosX1, akm1, mode;

  if (fabs((t = fabs (P.phi0)) - M_HALFPI) < EPS10)
      mode = P.phi0 < 0 ? S_POLE : N_POLE;
  else
      mode = t > EPS10 ? OBLIQ: EQUIT;
  phits = fabs (phits);

  if (P.es) {
    switch (mode) {
      case N_POLE:
      case S_POLE:
        if (fabs (phits - M_HALFPI) < EPS10)
            akm1 = 2 * P.k0 /
               sqrt(pow(1 + P.e, 1 + P.e) * pow(1 - P.e, 1 - P.e));
        else {
            akm1 = cos(phits) /
               pj_tsfn(phits, t = sin(phits), P.e);
            t *= P.e;
            akm1 /= sqrt(1 - t * t);
        }
        break;
      case EQUIT:
      case OBLIQ:
        t = sin(P.phi0);
        X = 2 * atan(ssfn(P.phi0, t, P.e)) - M_HALFPI;
        t *= P.e;
        akm1 = 2 * P.k0 * cos(P.phi0) / sqrt(1 - t * t);
        sinX1 = sin(X);
        cosX1 = cos(X);
        break;
    }
    P.fwd = e_fwd;
    P.inv = e_inv;
  } else {
    switch (mode) {
      case OBLIQ:
        sinph0 = sin(P.phi0);
        cosph0 = cos(P.phi0);
        /* falls through */
      case EQUIT:
        akm1 = 2 * P.k0;
        break;
      case S_POLE:
      case N_POLE:
        akm1 = fabs(phits - M_HALFPI) >= EPS10 ?
           cos(phits) / tan(M_FORTPI - 0.5 * phits) : 2 * P.k0;
        break;
    }
    P.fwd = s_fwd;
    P.inv = s_inv;
  }

  function e_fwd(lp, xy) {
    var coslam, sinlam, sinX = 0, cosX = 0, X, A, sinphi;
    coslam = cos(lp.lam);
    sinlam = sin(lp.lam);
    sinphi = sin(lp.phi);
    if (mode == OBLIQ|| mode == EQUIT) {
        sinX = sin(X = 2 * atan(ssfn(lp.phi, sinphi, P.e)) - M_HALFPI);
        cosX = cos(X);
    }

    switch (mode) {
      case OBLIQ:
        A = akm1 / (cosX1 * (1 + sinX1 * sinX +
           cosX1 * cosX * coslam));
        xy.y = A * (cosX1 * sinX - sinX1 * cosX * coslam);
        xy.x = A * cosX;
        break;
      case EQUIT:
        /* zero division is handled in pj_fwd */
        A = akm1 / (1 + cosX * coslam);
        xy.y = A * sinX;
        xy.x = A * cosX;
        break;
      case S_POLE:
        lp.phi = -lp.phi;
        coslam = -coslam;
        sinphi = -sinphi;
        /* falls through */
      case N_POLE:
        xy.x = akm1 * pj_tsfn (lp.phi, sinphi, P.e);
        xy.y = - xy.x * coslam;
        break;
    }
    xy.x = xy.x * sinlam;
  }

  function s_fwd(lp, xy) {
    var phi = lp.phi,
        sinphi = sin(phi),
        cosphi = cos(phi),
        coslam = cos(lp.lam),
        sinlam = sin(lp.lam);

    switch (mode) {
    case EQUIT:
    case OBLIQ:
      if (mode == EQUIT) {
        xy.y = 1 + cosphi * coslam;
      } else {
        xy.y = 1 + sinph0 * sinphi + cosph0 * cosphi * coslam;
      }
      if (xy.y <= EPS10) f_error();
      xy.x = (xy.y = akm1 / xy.y) * cosphi * sinlam;
      xy.y *= (mode == EQUIT) ? sinphi :
         cosph0 * sinphi - sinph0 * cosphi * coslam;
      break;
    case N_POLE:
      coslam = - coslam;
      phi = - phi;
      /* falls through */
    case S_POLE:
      if (fabs(phi - M_HALFPI) < TOL) f_error();
      xy.x = sinlam * (xy.y = akm1 * tan (M_FORTPI + 0.5 * phi));
      xy.y *= coslam;
      break;
    }
  }

  function e_inv(xy, lp) {
    var phi = lp.phi,
        tp=0, phi_l=0, halfe=0, halfpi=0,
        cosphi, sinphi, rho, i;
    rho = hypot (xy.x, xy.y);

    switch (mode) {
      case OBLIQ:
      case EQUIT:
        cosphi = cos ( tp = 2 * atan2(rho * cosX1 , akm1));
        sinphi = sin (tp);
                if ( rho == 0 )
            phi_l = asin (cosphi * sinX1);
                else
            phi_l = asin (cosphi * sinX1 + (xy.y * sinphi * cosX1 / rho));

        tp = tan (0.5 * (M_HALFPI + phi_l));
        xy.x *= sinphi;
        xy.y = rho * cosX1 * cosphi - xy.y * sinX1* sinphi;
        halfpi = M_HALFPI;
        halfe = 0.5 * P.e;
        break;
      case N_POLE:
        xy.y = -xy.y;
        /* falls through */
      case S_POLE:
        phi_l = M_HALFPI - 2 * atan (tp = - rho / akm1);
        halfpi = -M_HALFPI;
        halfe = -0.5 * P.e;
        break;
    }

    for (i = 0; i < NITER; i++, phi_l = lp.phi) {
      sinphi = P.e * sin(phi_l);
      lp.phi = 2 * atan (tp * pow ((1+sinphi)/(1-sinphi), halfe)) - halfpi;
      if (fabs(phi_l - lp.phi) < CONV) {
        if (mode == S_POLE)
          lp.phi = -lp.phi;
        lp.lam = (xy.x == 0 && xy.y == 0) ? 0 : atan2 (xy.x, xy.y);
        return;
      }
    }
    i_error();
  }

  function s_inv(xy, lp) {
    var c, rh, sinc, cosc;
    sinc = sin(c = 2 * atan ((rh = hypot(xy.x, xy.y)) / akm1));
    cosc = cos(c);
    lp.lam = 0;

    switch (mode) {
      case EQUIT:
        if (fabs (rh) <= EPS10)
            lp.phi = 0;
        else
            lp.phi = asin (xy.y * sinc / rh);
        if (cosc != 0 || xy.x != 0)
            lp.lam = atan2 (xy.x * sinc, cosc * rh);
        break;
      case OBLIQ:
        if (fabs (rh) <= EPS10)
            lp.phi = P.phi0;
        else
            lp.phi = asin (cosc * sinph0 + xy.y * sinc * cosph0 / rh);
        if ((c = cosc - sinph0 * sin (lp.phi)) != 0 || xy.x != 0)
            lp.lam = atan2 (xy.x * sinc * cosph0, c * rh);
        break;
      case N_POLE:
        xy.y = -xy.y;
        /* falls through */
      case S_POLE:
        if (fabs (rh) <= EPS10)
            lp.phi = P.phi0;
        else
            lp.phi = asin (mode == S_POLE ? - cosc : cosc);
        lp.lam = (xy.x == 0 && xy.y == 0) ? 0 : atan2 (xy.x, xy.y);
        break;
    }
  }

  function ssfn(phit, sinphi, eccen) {
    sinphi *= eccen;
    return tan(0.5 * (M_HALFPI + phit)) *
       pow ((1 - sinphi) / (1 + sinphi), 0.5 * eccen);
  }
}




function srat(esinp, exp) {
  return pow((1-esinp)/(1+esinp), exp);
}

function pj_gauss_ini(e, phi0) {
  var es = e * e,
      sphi = sin(phi0),
      cphi = cos(phi0),
      rc = sqrt(1 - es) / (1 - es * sphi * sphi),
      C = sqrt(1 + es * cphi * cphi * cphi * cphi / (1 - es)),
      // ignoring Proj.4 div0 check (seems unneccessary)
      chi = asin(sphi / C),
      ratexp = 0.5 * C * e,
      K = tan(0.5 * chi + M_FORTPI) / (pow(tan(0.5 * phi0 + M_FORTPI), C) *
        srat(e * sphi, ratexp));
  return {e: e, K: K, C: C, chi: chi, ratexp: ratexp, rc: rc};
}

function pj_gauss(elp, en) {
  return {
    phi: 2 * atan( en.K * pow(tan(0.5 * elp.phi + M_FORTPI), en.C) *
      srat(en.e * sin(elp.phi), en.ratexp) ) - M_HALFPI,
    lam: en.C * elp.lam
  };
}

function pj_inv_gauss(lp, en) {
  var MAX_ITER = 20,
      DEL_TOL = 1e-14,
      phi1 = lp.phi,
      num = pow(tan(0.5 * lp.phi + M_FORTPI)/en.K, 1/en.C),
      i, phi;
  lp.lam /= en.C;
  for (i = MAX_ITER; i>0; --i) {
    phi = 2 * atan(num * srat(en.e * sin(lp.phi), -0.5 * en.e)) - M_HALFPI;
    if (fabs(phi - lp.phi) < DEL_TOL) break;
    lp.phi = phi;
  }
  if (!i) pj_ctx_set_errno(-17); /* convergence failed */
}


pj_add(pj_sterea, 'sterea', 'Oblique Stereographic Alternative', 'Azimuthal, Sph&Ell');

function pj_sterea(P) {
  var en = pj_gauss_ini(P.e, P.phi0),
      phic0 = en.chi,
      R = en.rc,
      R2 = 2 * R,
      sinc0 = sin(phic0),
      cosc0 = cos(phic0);

  P.fwd = e_fwd;
  P.inv = e_inv;

  function e_fwd(lp, xy) {
    var cosc, sinc, cosl, k;
    lp = pj_gauss(lp, en);
    sinc = sin(lp.phi);
    cosc = cos(lp.phi);
    cosl = cos(lp.lam);
    k = P.k0 * R2 / (1 + sinc0 * sinc + cosc0 * cosc * cosl);
    xy.x = k * cosc * sin(lp.lam);
    xy.y = k * (cosc0 * sinc - sinc0 * cosc * cosl);
  }

  function e_inv(xy, lp) {
    var x = xy.x / P.k0,
        y = xy.y / P.k0,
        rho, c, sinc, cosc;
    if ((rho = hypot(x, y))) {
      c = 2 * atan2(rho, R2);
      sinc = sin(c);
      cosc = cos(c);
      lp.phi = asin(cosc * sinc0 + y * sinc * cosc0 / rho);
      lp.lam = atan2(x * sinc, rho * cosc0 * cosc - y * sinc0 * sinc);
    } else {
      lp.phi = phic0;
      lp.lam = 0;
    }
    pj_inv_gauss(lp, en);
  }
}


pj_add(pj_kav5, 'kav5', 'Kavraisky V', 'PCyl., Sph.');
pj_add(pj_qua_aut, 'qua_aut', 'Quartic Authalic', 'PCyl., Sph.');
pj_add(pj_fouc, 'fouc', 'Foucaut', 'PCyl., Sph.');
pj_add(pj_mbt_s, 'mbt_s', 'McBryde-Thomas Flat-Polar Sine (No. 1)', 'PCyl., Sph.');

function pj_kav5(P) {
  pj_sts(P, 1.50488, 1.35439, false);
}

function pj_qua_aut(P) {
  pj_sts(P, 2, 2, false);
}

function pj_fouc(P) {
  pj_sts(P, 2, 2, true);
}

function pj_mbt_s(P) {
  pj_sts(P, 1.48875, 1.36509, false);
}

function pj_sts(P, p, q, tan_mode) {
  var C_x = q / p;
  var C_y = p;
  var C_p = 1 / q;
  P.inv = s_inv;
  P.fwd = s_fwd;
  P.es = 0;

  function s_fwd(lp, xy) {
    var c;
    xy.x = C_x * lp.lam * cos(lp.phi);
    xy.y = C_y;
    lp.phi *= C_p;
    c = cos(lp.phi);
    if (tan_mode) {
      xy.x *= c * c;
      xy.y *= tan(lp.phi);
    } else {
      xy.x /= c;
      xy.y *= sin (lp.phi);
    }
  }

  function s_inv(xy, lp) {
    var c;
    xy.y /= C_y;
    c = cos (lp.phi = tan_mode ? atan(xy.y) : aasin(xy.y));
    lp.phi /= C_p;
    lp.lam = xy.x / (C_x * cos(lp.phi));
    if (tan_mode)
      lp.lam /= c * c;
    else
      lp.lam *= c;
  }
}


pj_add(pj_tcea, 'tcea', 'Transverse Cylindrical Equal Area', 'Cyl, Sph');

function pj_tcea(P) {
  P.es = 0;
  P.fwd = s_fwd;
  P.inv = s_inv;

  function s_fwd(lp, xy) {
    xy.x = cos (lp.phi) * sin (lp.lam) / P.k0;
    xy.y = P.k0 * (atan2 (tan (lp.phi), cos (lp.lam)) - P.phi0);
  }

  function s_inv(xy, lp) {
    var t;
    xy.y = xy.y / P.k0 + P.phi0;
    xy.x *= P.k0;
    t = sqrt (1 - xy.x * xy.x);
    lp.phi = asin (t * sin (xy.y));
    lp.lam = atan2 (xy.x, t * cos (xy.y));
  }
}


pj_add(pj_times, 'times', 'Times', 'Cyl, Sph');

function pj_times(P) {
  P.es = 0;
  P.fwd = function(lp, xy) {
    var t = tan(lp.phi / 2);
    var s = sin(M_FORTPI * t);
    xy.x = lp.lam * (0.74482 - 0.34588 * s * s);
    xy.y = 1.70711 *  t;
  };
  P.inv = function (xy, lp) {
    var t = xy.y / 1.70711;
    var s = sin(M_FORTPI * t);
    lp.lam = xy.x / (0.74482 - 0.34588 * s * s);
    lp.phi = 2 * atan(t);
  };
}


pj_add(pj_tmerc, 'tmerc', 'Transverse Mercator', 'Cyl, Sph&Ell');
pj_add(pj_utm, 'utm', 'Universal Transverse Mercator (UTM)', 'Cyl, Sph\nzone= south');

function pj_utm_zone(P) {

}

function pj_utm(P) {
  var zone;
  if (!P.es) e_error(-34);
  P.y0 = pj_param(P.params, "bsouth") ? 10000000 : 0;
  P.x0 = 500000;
  if (pj_param(P.params, "tzone")) {
    if ((zone = pj_param(P.params, "izone")) > 0 && zone <= 60)
      --zone;
    else
      e_error(-35);
  } else { /* nearest central meridian input */
    zone = floor((adjlon(P.lam0) + M_PI) * 30 / M_PI);
    if (zone < 0)
      zone = 0;
    else if (zone >= 60)
      zone = 59;
  }
  P.lam0 = (zone + 0.5) * M_PI / 30 - M_PI;
  P.k0 = 0.9996;
  P.phi0 = 0;
  pj_etmerc(P);
}

function pj_tmerc(P) {
  // TODO: support +algo option
  if (pj_param(P.params, "bapprox")) {
    pj_tmerc_approx(P);
  } else {
    pj_tmerc_auto(P);
  }
}

function pj_tmerc_auto(P) {
  if (P.es === 0) {
    return pj_tmerc_approx(P);
  }
  pj_etmerc(P);
  var etfwd = P.fwd;
  var etinv = P.inv;
  pj_tmerc_approx(P);
  var fwd = P.fwd;
  var inv = P.inv;

  P.fwd = function(lp, xy) {
    if (fabs(lp.lam) > 3 * DEG_TO_RAD) etfwd(lp, xy);
    else fwd(lp, xy);
  };

  P.inv = function(xy, lp) {
    // See https://github.com/OSGeo/PROJ/blob/master/src/projections/tmerc.cpp
    if (fabs(xy.x) > 0.053 - 0.022 * xy.y * xy.y) etinv(xy, lp);
    else inv(xy, lp);
  };
}

function pj_tmerc_approx(P) {
  var EPS10 = 1e-10,
      FC1 = 1,
      FC2 = 0.5,
      FC3 = 0.16666666666666666666,
      FC4 = 0.08333333333333333333,
      FC5 = 0.05,
      FC6 = 0.03333333333333333333,
      FC7 = 0.02380952380952380952,
      FC8 = 0.01785714285714285714;
  var esp, ml0, en;

  if (P.es) {
    if (!(en = pj_enfn(P.es))) // in pj_mlfn.js
        e_error_0();
    ml0 = pj_mlfn(P.phi0, sin(P.phi0), cos(P.phi0), en);
    esp = P.es / (1 - P.es);
    P.fwd = e_fwd;
    P.inv = e_inv;
  } else {
    esp = P.k0;
    ml0 = 0.5 * esp;
    P.fwd = s_fwd;
    P.inv = s_inv;
  }

  function e_fwd(lp, xy) {
    var sinphi, cosphi, t, al, als, n;
    if ( lp.lam < -M_HALFPI || lp.lam > M_HALFPI ) {
      pj_ctx_set_errno(-14);
      return;
    }

    sinphi = sin (lp.phi);
    cosphi = cos (lp.phi);
    t = fabs(cosphi) > EPS10 ? sinphi/cosphi : 0;
    t *= t;
    al = cosphi * lp.lam;
    als = al * al;
    al /= sqrt(1 - P.es * sinphi * sinphi);
    n = esp * cosphi * cosphi;
    xy.x = P.k0 * al * (FC1 +
        FC3 * als * (1 - t + n +
        FC5 * als * (5 + t * (t - 18) + n * (14 - 58 * t) +
        FC7 * als * (61 + t * ( t * (179 - t) - 479 ) )
        )));
    xy.y = P.k0 * (pj_mlfn(lp.phi, sinphi, cosphi, en) - ml0 +
        sinphi * al * lp.lam * FC2 * ( 1 +
        FC4 * als * (5 - t + n * (9 + 4 * n) +
        FC6 * als * (61 + t * (t - 58) + n * (270 - 330 * t) +
        FC8 * als * (1385 + t * ( t * (543 - t) - 3111) )
        ))));
  }

  function s_fwd(lp, xy) {
    var b, cosphi;
    /*
     * Fail if our longitude is more than 90 degrees from the
     * central meridian since the results are essentially garbage.
     * Is error -20 really an appropriate return value?
     *
     *  http://trac.osgeo.org/proj/ticket/5
     */
    if( lp.lam < -M_HALFPI || lp.lam > M_HALFPI ) {
        pj_ctx_set_errno(-14);
        return;
    }
    cosphi = cos(lp.phi);
    b = cosphi * sin (lp.lam);
    if (fabs(fabs(b) - 1) <= EPS10) f_error();

    xy.x = ml0 * log ((1 + b) / (1 - b));
    xy.y = cosphi * cos(lp.lam) / sqrt(1 - b * b);

    b = fabs ( xy.y );
    if (b >= 1) {
      if ((b - 1) > EPS10) {
        f_error();
      } else {
        xy.y = 0;
      }
    } else
      xy.y = acos(xy.y);

    if (lp.phi < 0)
      xy.y = -xy.y;
    xy.y = esp * (xy.y - P.phi0);
  }

  function e_inv(xy, lp) {
    var n, con, cosphi, d, ds, sinphi, t;
    lp.phi = pj_inv_mlfn(ml0 + xy.y / P.k0, P.es, en);
    if (fabs(lp.phi) >= M_HALFPI) {
      lp.phi = xy.y < 0 ? -M_HALFPI : M_HALFPI;
      lp.lam = 0;
    } else {
      sinphi = sin(lp.phi);
      cosphi = cos(lp.phi);
      t = fabs (cosphi) > 1e-10 ? sinphi/cosphi : 0;
      n = esp * cosphi * cosphi;
      d = xy.x * sqrt (con = 1 - P.es * sinphi * sinphi) / P.k0;
      con *= t;
      t *= t;
      ds = d * d;
      lp.phi -= (con * ds / (1-P.es)) * FC2 * (1 -
        ds * FC4 * (5 + t * (3 - 9 *  n) + n * (1 - 4 * n) -
        ds * FC6 * (61 + t * (90 - 252 * n + 45 * t) + 46 * n -
        ds * FC8 * (1385 + t * (3633 + t * (4095 + 1575 * t)))
        )));
      lp.lam = d * (FC1 - ds * FC3 * (1 + 2 * t + n -
        ds * FC5 * (5 + t * (28 + 24*t + 8*n) + 6 * n -
        ds * FC7 * (61 + t * (662 + t * (1320 + 720 * t)))
        ))) / cosphi;
    }
  }

  function s_inv(xy, lp) {
    var h = exp(xy.x / esp);
    var g = 0.5 * (h - 1 / h);
    h = cos (P.phi0 + xy.y / esp);
    lp.phi = asin(sqrt((1 - h * h) / (1 + g * g)));
    /* Make sure that phi is on the correct hemisphere when false northing is used */
    if (xy.y < 0 && -lp.phi + P.phi0 < 0) lp.phi = -lp.phi;
    lp.lam = (g || h) ? atan2(g, h) : 0;
  }
}


pj_add(pj_tpeqd, 'tpeqd', 'Two Point Equidistant', 'Misc Sph\nlat_1= lon_1= lat_2= lon_2=');

function pj_tpeqd(P) {
  var cp1, sp1, cp2, sp2, ccs, cs, sc, r2z0, z02, dlam2;
  var hz0, thz0, rhshz0, ca, sa, lamp, lamc;
  var lam_1, lam_2, phi_1, phi_2, A12, pp;

  /* get control point locations */
  phi_1 = pj_param(P.params, "rlat_1");
  lam_1 = pj_param(P.params, "rlon_1");
  phi_2 = pj_param(P.params, "rlat_2");
  lam_2 = pj_param(P.params, "rlon_2");

  if (phi_1 == phi_2 && lam_1 == lam_2)
      e_error(-25);
  P.lam0  = adjlon(0.5 * (lam_1 + lam_2));
  dlam2 = adjlon(lam_2 - lam_1);
  cp1 = cos (phi_1);
  cp2 = cos (phi_2);
  sp1 = sin (phi_1);
  sp2 = sin (phi_2);
  cs = cp1 * sp2;
  sc = sp1 * cp2;
  ccs = cp1 * cp2 * sin(dlam2);
  z02 = aacos(sp1 * sp2 + cp1 * cp2 * cos(dlam2));
  hz0 = 0.5 * z02;
  A12 = atan2(cp2 * sin(dlam2),
    cp1 * sp2 - sp1 * cp2 * cos(dlam2));
  ca = cos(pp = aasin(cp1 * sin(A12)));
  sa = sin(pp);
  lamp = adjlon(atan2(cp1 * cos(A12), sp1) - hz0);
  dlam2 *= 0.5;
  lamc = M_HALFPI - atan2(sin(A12) * sp1, cos(A12)) - dlam2;
  thz0 = tan (hz0);
  rhshz0 = 0.5 / sin(hz0);
  r2z0 = 0.5 / z02;
  z02 *= z02;

  P.fwd = s_fwd;
  P.inv = s_inv;
  P.es = 0;

  function s_fwd(lp, xy) {
    var t, z1, z2, dl1, dl2, sp, cp;
    sp = sin(lp.phi);
    cp = cos(lp.phi);
    z1 = aacos(sp1 * sp + cp1 * cp * cos (dl1 = lp.lam + dlam2));
    z2 = aacos(sp2 * sp + cp2 * cp * cos (dl2 = lp.lam - dlam2));
    z1 *= z1;
    z2 *= z2;
    xy.x = r2z0 * (t = z1 - z2);
    t = z02 - t;
    xy.y = r2z0 * asqrt (4 * z02 * z2 - t * t);
    if ((ccs * sp - cp * (cs * sin(dl1) - sc * sin(dl2))) < 0)
      xy.y = -xy.y;
  }

  function s_inv(xy, lp) {
    var cz1, cz2, s, d, cp, sp;
    cz1 = cos(hypot(xy.y, xy.x + hz0));
    cz2 = cos(hypot(xy.y, xy.x - hz0));
    s = cz1 + cz2;
    d = cz1 - cz2;
    lp.lam = - atan2(d, (s * thz0));
    lp.phi = aacos(hypot(thz0 * s, d) * rhshz0);
    if ( xy.y < 0 )
      lp.phi = - lp.phi;
    /* lam--phi now in system relative to P1--P2 base equator */
    sp = sin(lp.phi);
    cp = cos(lp.phi);
    lp.phi = aasin(sa * sp + ca * cp * (s = cos(lp.lam -= lamp)));
    lp.lam = atan2(cp * sin(lp.lam), sa * cp * s - ca * sp) + lamc;
  }
}


pj_add(pj_urm5, 'urm5', 'Urmaev V', 'PCyl., Sph., no inv.\nn= q= alpha=');

function pj_urm5(P) {
  var m, rmn, q3, n;
  var alpha, t;
  n = pj_param(P.params, "dn");
  if (n > 0 && n <= 1 === false) {
    e_error(-40);
  }
  q3 = pj_param(P.params, "dq") / 3;
  alpha = pj_param(P.params, "ralpha");
  t = n * sin (alpha);
  m = cos (alpha) / sqrt (1 - t * t);
  rmn = 1 / (m * n);

  P.fwd = s_fwd;
  P.es = 0;

  function s_fwd(lp, xy) {
    var t = lp.phi = aasin (n * sin (lp.phi));
    xy.x = m * lp.lam * cos (lp.phi);
    t *= t;
    xy.y = lp.phi * (1 + t * q3) * rmn;
  }
}


pj_add(pj_urmfps, 'urmfps', 'Urmaev Flat-Polar Sinusoidal', 'PCyl, Sph.\nn=');
pj_add(pj_wag1, 'wag1', 'Wagner I (Kavraisky VI)', 'PCyl, Sph.');


function pj_wag1(P) {
  pj_urmfps_init(P, 0.8660254037844386467637231707);
}

function pj_urmfps(P) {
  var n = pj_param(P.params, "dn");
  if (n <= 0 || n > 1) e_error(-40);
  pj_urmfps_init(P, n);
}

function pj_urmfps_init(P, n) {
  var C_x = 0.8773826753,
      C_y = 1.139753528477 / n;

  P.es = 0;
  P.fwd = s_fwd;
  P.inv = s_inv;

  function s_fwd(lp, xy) {
    var phi = aasin(n * sin(lp.phi));
    xy.x = C_x * lp.lam * cos(phi);
    xy.y = C_y * phi;
  }

  function s_inv(xy, lp) {
    xy.y /= C_y;
    lp.phi = aasin(sin(xy.y) / n);
    lp.lam = xy.x / (C_x * cos(xy.y));
  }
}


pj_add(pj_vandg, 'vandg', 'van der Grinten (I)', 'Misc Sph');
pj_add(pj_vandg2, 'vandg2', 'van der Grinten II', 'Misc Sph, no inv.');
pj_add(pj_vandg3, 'vandg3', 'van der Grinten III', 'Misc Sph, no inv.');
pj_add(pj_vandg4, 'vandg4', 'van der Grinten IV', 'Misc Sph, no inv.');

function pj_vandg(P) {
  var TOL = 1.e-10,
      THIRD = 0.33333333333333333333,
      TWO_THRD = 0.66666666666666666666,
      C2_27 = 0.07407407407407407407,
      PI4_3 = 4.18879020478639098458,
      PISQ = 9.86960440108935861869,
      TPISQ = 19.73920880217871723738,
      HPISQ = 4.93480220054467930934;

  P.fwd = s_fwd;
  P.inv = s_inv;

  function s_fwd(lp, xy) {
    var al, al2, g, g2, p2;
    p2 = fabs(lp.phi / M_HALFPI);
    if ((p2 - TOL) > 1) f_error();
    if (p2 > 1)
      p2 = 1;
    if (fabs(lp.phi) <= TOL) {
      xy.x = lp.lam;
      xy.y = 0;
    } else if (fabs(lp.lam) <= TOL || fabs(p2 - 1) < TOL) {
      xy.x = 0;
      xy.y = M_PI * tan(0.5 * asin(p2));
      if (lp.phi < 0) xy.y = -xy.y;
    } else {
      al = 0.5 * fabs(M_PI / lp.lam - lp.lam / M_PI);
      al2 = al * al;
      g = sqrt(1 - p2 * p2);
      g = g / (p2 + g - 1);
      g2 = g * g;
      p2 = g * (2 / p2 - 1);
      p2 = p2 * p2;
      xy.x = g - p2; g = p2 + al2;
      xy.x = M_PI * (al * xy.x + sqrt(al2 * xy.x * xy.x - g * (g2 - p2))) / g;
      if (lp.lam < 0) xy.x = -xy.x;
      xy.y = fabs(xy.x / M_PI);
      xy.y = 1 - xy.y * (xy.y + 2 * al);
      if (xy.y < -TOL) f_error();
      if (xy.y < 0)
        xy.y = 0;
      else
        xy.y = sqrt(xy.y) * (lp.phi < 0 ? -M_PI : M_PI);
    }
  }

  function s_inv(xy, lp) {
    var t, c0, c1, c2, c3, al, r2, r, m, d, ay, x2, y2;
    x2 = xy.x * xy.x;
    if ((ay = fabs(xy.y)) < TOL) {
      lp.phi = 0;
      t = x2 * x2 + TPISQ * (x2 + HPISQ);
      lp.lam = fabs(xy.x) <= TOL ? 0 :
         0.5 * (x2 - PISQ + sqrt(t)) / xy.x;
      return (lp);
    }
    y2 = xy.y * xy.y;
    r = x2 + y2;    r2 = r * r;
    c1 = - M_PI * ay * (r + PISQ);
    c3 = r2 + M_TWOPI * (ay * r + M_PI * (y2 + M_PI * (ay + M_HALFPI)));
    c2 = c1 + PISQ * (r - 3 *  y2);
    c0 = M_PI * ay;
    c2 /= c3;
    al = c1 / c3 - THIRD * c2 * c2;
    m = 2 * sqrt(-THIRD * al);
    d = C2_27 * c2 * c2 * c2 + (c0 * c0 - THIRD * c2 * c1) / c3;
    if (((t = fabs(d = 3 * d / (al * m))) - TOL) <= 1) {
      d = t > 1 ? (d > 0 ? 0 : M_PI) : acos(d);
      lp.phi = M_PI * (m * cos(d * THIRD + PI4_3) - THIRD * c2);
      if (xy.y < 0) lp.phi = -lp.phi;
      t = r2 + TPISQ * (x2 - y2 + HPISQ);
      lp.lam = fabs(xy.x) <= TOL ? 0 :
         0.5 * (r - PISQ + (t <= 0 ? 0 : sqrt(t))) / xy.x;
    } else
        i_error();
  }
}

function pj_vandg2(P) {
  pj_vandg2_init(P, false);
}

function pj_vandg3(P) {
  pj_vandg2_init(P, true);
}

function pj_vandg2_init(P, vdg3) {
  var TOL = 1e-10;
  P.fwd = s_fwd;
  P.es = 0;

  function s_fwd(lp, xy) {
    var x1, at, bt, ct;
    bt = fabs(M_TWO_D_PI * lp.phi);
    if ((ct = 1 - bt * bt) < 0)
      ct = 0;
    else
      ct = sqrt(ct);
    if (fabs(lp.lam) < TOL) {
      xy.x = 0;
      xy.y = M_PI * (lp.phi < 0 ? -bt : bt) / (1 + ct);
    } else {
      at = 0.5 * fabs(M_PI / lp.lam - lp.lam / M_PI);
      if (vdg3) {
          x1 = bt / (1 + ct);
          xy.x = M_PI * (sqrt(at * at + 1 - x1 * x1) - at);
          xy.y = M_PI * x1;
      } else {
          x1 = (ct * sqrt(1 + at * at) - at * ct * ct) /
              (1 + at * at * bt * bt);
          xy.x = M_PI * x1;
          xy.y = M_PI * sqrt(1 - x1 * (x1 + 2 * at) + TOL);
      }
      if ( lp.lam < 0) xy.x = -xy.x;
      if ( lp.phi < 0) xy.y = -xy.y;
    }
  }
}

function pj_vandg4(P) {
  P.es = 0;
  P.fwd = function(lp, xy) {
    var TOL = 1e-10;
    var x1, t, bt, ct, ft, bt2, ct2, dt, dt2;
    if (fabs(lp.phi) < TOL) {
      xy.x = lp.lam;
      xy.y = 0;
    } else if (fabs(lp.lam) < TOL || fabs(fabs(lp.phi) - M_HALFPI) < TOL) {
      xy.x = 0;
      xy.y = lp.phi;
    } else {
      bt = fabs(M_TWO_D_PI * lp.phi);
      bt2 = bt * bt;
      ct = 0.5 * (bt * (8 - bt * (2 + bt2)) - 5) / (bt2 * (bt - 1));
      ct2 = ct * ct;
      dt = M_TWO_D_PI * lp.lam;
      dt = dt + 1 / dt;
      dt = sqrt(dt * dt - 4);
      if ((fabs(lp.lam) - M_HALFPI) < 0) dt = -dt;
      dt2 = dt * dt;
      x1 = bt + ct; x1 *= x1;
      t = bt + 3*ct;
      ft = x1 * (bt2 + ct2 * dt2 - 1) + (1-bt2) * (
          bt2 * (t * t + 4 * ct2) +
          ct2 * (12 * bt * ct + 4 * ct2) );
      x1 = (dt*(x1 + ct2 - 1) + 2*sqrt(ft)) /
          (4* x1 + dt2);
      xy.x = M_HALFPI * x1;
      xy.y = M_HALFPI * sqrt(1 + dt * fabs(x1) - x1 * x1);
      if (lp.lam < 0) xy.x = -xy.x;
      if (lp.phi < 0) xy.y = -xy.y;
    }
  };
}


pj_add(pj_wag2, 'wag2', 'Wagner II', 'PCyl., Sph.');
pj_add(pj_wag3, 'wag3', 'Wagner III', 'PCyl., Sph.\nlat_ts=');
pj_add(pj_wag7, 'wag7', 'Wagner VII', 'Misc Sph, no inv.');

function pj_wag2(P) {
  var C_x = 0.92483,
      C_y = 1.38725,
      C_p1 = 0.88022,
      C_p2 = 0.88550;

  P.fwd = s_fwd;
  P.inv = s_inv;

  function s_fwd(lp, xy) {
    lp.phi = aasin(C_p1 * sin (C_p2 * lp.phi));
    xy.x = C_x * lp.lam * cos (lp.phi);
    xy.y = C_y * lp.phi;
  }

  function s_inv(xy, lp) {
    lp.phi = xy.y / C_y;
    lp.lam = xy.x / (C_x * cos(lp.phi));
    lp.phi = aasin(sin(lp.phi) / C_p1) / C_p2;
  }
}

function pj_wag3(P) {
  var TWOTHIRD = 0.6666666666666666666667,
      ts = pj_param(P.params, "rlat_ts"),
      C_x = cos(ts) / cos(2*ts/3);

  P.es = 0;
  P.fwd = s_fwd;
  P.inv = s_inv;

  function s_fwd(lp, xy) {
    xy.x = C_x * lp.lam * cos(TWOTHIRD * lp.phi);
    xy.y = lp.phi;
  }

  function s_inv(xy, lp) {
    lp.phi = xy.y;
    lp.lam = xy.x / (C_x * cos(TWOTHIRD * lp.phi));
  }
}

function pj_wag7(P) {
  P.es = 0;
  P.fwd = function(lp, xy) {
    var theta, ct, D;
    theta = asin (xy.y = 0.90630778703664996 * sin(lp.phi));
    xy.x  = 2.66723 * (ct = cos (theta)) * sin (lp.lam /= 3);
    xy.y *= 1.24104 * (D = 1/(sqrt (0.5 * (1 + ct * cos(lp.lam)))));
    xy.x *= D;
  };
}



pj_add(pj_wink1, 'wink1', 'Winkel I', 'PCyl., Sph.\nlat_ts=');
pj_add(pj_wink2, 'wink2', 'Winkel II', 'PCyl., Sph., no inv.\nlat_1=');

function pj_wink1(P) {
  var cosphi1 = cos(pj_param(P.params, "rlat_ts"));
  P.fwd = s_fwd;
  P.inv = s_inv;
  P.es = 0;

  function s_fwd(lp, xy) {
    xy.x = 0.5 * lp.lam * (cosphi1 + cos(lp.phi));
    xy.y = lp.phi;
  }

  function s_inv(xy, lp) {
    lp.phi = xy.y;
    lp.lam = 2 * xy.x / (cosphi1 + cos(lp.phi));
  }
}

function pj_wink2(P) {
  var cosphi1 = cos(pj_param(P.params, "rlat_1"));
  var MAX_ITER = 10,
      LOOP_TOL = 1e-7;
  P.fwd = s_fwd;
  P.inv = null;
  P.es = 0;

  function s_fwd(lp, xy) {
    var k, V, i, phi = lp.phi;
    xy.y = phi * M_TWO_D_PI;
    k = M_PI * sin(phi);
    phi *= 1.8;
    for (i = MAX_ITER; i ; --i) {
      phi -= V = (phi + sin (phi) - k) /
        (1 + cos(phi));
      if (fabs(V) < LOOP_TOL)
        break;
    }
    if (!i)
      phi = (phi < 0) ? -M_HALFPI : M_HALFPI;
    else
      phi *= 0.5;
    xy.x = 0.5 * lp.lam * (cos(phi) + cosphi1);
    xy.y = M_FORTPI * (sin(phi) + xy.y);
  }
}


// Projections are inserted here by the build script

var api = proj4js; // (partial) support for proj4js api

// Add Proj.4-style api
api.pj_init = pj_init;
api.pj_fwd = pj_fwd;
api.pj_inv = pj_inv;
api.pj_transform = pj_transform;
api.pj_add = pj_add;

// Convenience functions not in Proj.4
api.pj_fwd_deg = pj_fwd_deg;
api.pj_inv_deg = pj_inv_deg;
api.pj_transform_point = pj_transform_point;

// Export some functions for testing
api.internal = {
  dmstod: dmstod,
  dmstor: dmstor,
  get_rtodms: get_rtodms,
  get_dtodms: get_dtodms,
  get_proj_defn: get_proj_defn,
  pj_latlong_from_proj: pj_latlong_from_proj,
  pj_get_params: pj_get_params,
  pj_datums: pj_datums,
  pj_list: pj_list,
  pj_ellps: pj_ellps,
  pj_units: pj_units,
  pj_read_init_opts: pj_read_init_opts,
  find_datum: find_datum,
  DEG_TO_RAD: DEG_TO_RAD,
  RAD_TO_DEG: RAD_TO_DEG,
  wkt_parse: wkt_parse,
  wkt_unpack: wkt_unpack,
  convert_wkt_quotes: convert_wkt_quotes,
  wkt_to_proj4: wkt_to_proj4,
  wkt_from_proj4: wkt_from_proj4,
  wkt_make_projcs: wkt_make_projcs,
  wkt_get_geogcs_name: wkt_get_geogcs_name,
  wkt_stringify: wkt_stringify,
  mproj_insert_libcache: mproj_insert_libcache,
  mproj_search_libcache: mproj_search_libcache,
  GeographicLib: GeographicLib
};

if (typeof define == 'function' && define.amd) {
  define('mproj', api);
} else if (typeof exports == 'object') {
  module.exports = api;
} else {
  this.mproj = api;
}

// TODO: move to better file
function pj_latlong_from_proj(P) {
  var defn = '+proj=latlong' + get_geod_defn(P);
  return pj_init(defn);
}

}());

}).call(this)}).call(this,"/node_modules/mproj/dist/mproj.js")
},{"fs":"fs","path":"path"}],"path":[function(require,module,exports){
(function (process){(function (){
// 'path' module extracted from Node.js v8.11.1 (only the posix part)
// transplited with Babel

// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

'use strict';

function assertPath(path) {
  if (typeof path !== 'string') {
    throw new TypeError('Path must be a string. Received ' + JSON.stringify(path));
  }
}

// Resolves . and .. elements in a path with directory names
function normalizeStringPosix(path, allowAboveRoot) {
  var res = '';
  var lastSegmentLength = 0;
  var lastSlash = -1;
  var dots = 0;
  var code;
  for (var i = 0; i <= path.length; ++i) {
    if (i < path.length)
      code = path.charCodeAt(i);
    else if (code === 47 /*/*/)
      break;
    else
      code = 47 /*/*/;
    if (code === 47 /*/*/) {
      if (lastSlash === i - 1 || dots === 1) {
        // NOOP
      } else if (lastSlash !== i - 1 && dots === 2) {
        if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 /*.*/ || res.charCodeAt(res.length - 2) !== 46 /*.*/) {
          if (res.length > 2) {
            var lastSlashIndex = res.lastIndexOf('/');
            if (lastSlashIndex !== res.length - 1) {
              if (lastSlashIndex === -1) {
                res = '';
                lastSegmentLength = 0;
              } else {
                res = res.slice(0, lastSlashIndex);
                lastSegmentLength = res.length - 1 - res.lastIndexOf('/');
              }
              lastSlash = i;
              dots = 0;
              continue;
            }
          } else if (res.length === 2 || res.length === 1) {
            res = '';
            lastSegmentLength = 0;
            lastSlash = i;
            dots = 0;
            continue;
          }
        }
        if (allowAboveRoot) {
          if (res.length > 0)
            res += '/..';
          else
            res = '..';
          lastSegmentLength = 2;
        }
      } else {
        if (res.length > 0)
          res += '/' + path.slice(lastSlash + 1, i);
        else
          res = path.slice(lastSlash + 1, i);
        lastSegmentLength = i - lastSlash - 1;
      }
      lastSlash = i;
      dots = 0;
    } else if (code === 46 /*.*/ && dots !== -1) {
      ++dots;
    } else {
      dots = -1;
    }
  }
  return res;
}

function _format(sep, pathObject) {
  var dir = pathObject.dir || pathObject.root;
  var base = pathObject.base || (pathObject.name || '') + (pathObject.ext || '');
  if (!dir) {
    return base;
  }
  if (dir === pathObject.root) {
    return dir + base;
  }
  return dir + sep + base;
}

var posix = {
  // path.resolve([from ...], to)
  resolve: function resolve() {
    var resolvedPath = '';
    var resolvedAbsolute = false;
    var cwd;

    for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
      var path;
      if (i >= 0)
        path = arguments[i];
      else {
        if (cwd === undefined)
          cwd = process.cwd();
        path = cwd;
      }

      assertPath(path);

      // Skip empty entries
      if (path.length === 0) {
        continue;
      }

      resolvedPath = path + '/' + resolvedPath;
      resolvedAbsolute = path.charCodeAt(0) === 47 /*/*/;
    }

    // At this point the path should be resolved to a full absolute path, but
    // handle relative paths to be safe (might happen when process.cwd() fails)

    // Normalize the path
    resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute);

    if (resolvedAbsolute) {
      if (resolvedPath.length > 0)
        return '/' + resolvedPath;
      else
        return '/';
    } else if (resolvedPath.length > 0) {
      return resolvedPath;
    } else {
      return '.';
    }
  },

  normalize: function normalize(path) {
    assertPath(path);

    if (path.length === 0) return '.';

    var isAbsolute = path.charCodeAt(0) === 47 /*/*/;
    var trailingSeparator = path.charCodeAt(path.length - 1) === 47 /*/*/;

    // Normalize the path
    path = normalizeStringPosix(path, !isAbsolute);

    if (path.length === 0 && !isAbsolute) path = '.';
    if (path.length > 0 && trailingSeparator) path += '/';

    if (isAbsolute) return '/' + path;
    return path;
  },

  isAbsolute: function isAbsolute(path) {
    assertPath(path);
    return path.length > 0 && path.charCodeAt(0) === 47 /*/*/;
  },

  join: function join() {
    if (arguments.length === 0)
      return '.';
    var joined;
    for (var i = 0; i < arguments.length; ++i) {
      var arg = arguments[i];
      assertPath(arg);
      if (arg.length > 0) {
        if (joined === undefined)
          joined = arg;
        else
          joined += '/' + arg;
      }
    }
    if (joined === undefined)
      return '.';
    return posix.normalize(joined);
  },

  relative: function relative(from, to) {
    assertPath(from);
    assertPath(to);

    if (from === to) return '';

    from = posix.resolve(from);
    to = posix.resolve(to);

    if (from === to) return '';

    // Trim any leading backslashes
    var fromStart = 1;
    for (; fromStart < from.length; ++fromStart) {
      if (from.charCodeAt(fromStart) !== 47 /*/*/)
        break;
    }
    var fromEnd = from.length;
    var fromLen = fromEnd - fromStart;

    // Trim any leading backslashes
    var toStart = 1;
    for (; toStart < to.length; ++toStart) {
      if (to.charCodeAt(toStart) !== 47 /*/*/)
        break;
    }
    var toEnd = to.length;
    var toLen = toEnd - toStart;

    // Compare paths to find the longest common path from root
    var length = fromLen < toLen ? fromLen : toLen;
    var lastCommonSep = -1;
    var i = 0;
    for (; i <= length; ++i) {
      if (i === length) {
        if (toLen > length) {
          if (to.charCodeAt(toStart + i) === 47 /*/*/) {
            // We get here if `from` is the exact base path for `to`.
            // For example: from='/foo/bar'; to='/foo/bar/baz'
            return to.slice(toStart + i + 1);
          } else if (i === 0) {
            // We get here if `from` is the root
            // For example: from='/'; to='/foo'
            return to.slice(toStart + i);
          }
        } else if (fromLen > length) {
          if (from.charCodeAt(fromStart + i) === 47 /*/*/) {
            // We get here if `to` is the exact base path for `from`.
            // For example: from='/foo/bar/baz'; to='/foo/bar'
            lastCommonSep = i;
          } else if (i === 0) {
            // We get here if `to` is the root.
            // For example: from='/foo'; to='/'
            lastCommonSep = 0;
          }
        }
        break;
      }
      var fromCode = from.charCodeAt(fromStart + i);
      var toCode = to.charCodeAt(toStart + i);
      if (fromCode !== toCode)
        break;
      else if (fromCode === 47 /*/*/)
        lastCommonSep = i;
    }

    var out = '';
    // Generate the relative path based on the path difference between `to`
    // and `from`
    for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
      if (i === fromEnd || from.charCodeAt(i) === 47 /*/*/) {
        if (out.length === 0)
          out += '..';
        else
          out += '/..';
      }
    }

    // Lastly, append the rest of the destination (`to`) path that comes after
    // the common path parts
    if (out.length > 0)
      return out + to.slice(toStart + lastCommonSep);
    else {
      toStart += lastCommonSep;
      if (to.charCodeAt(toStart) === 47 /*/*/)
        ++toStart;
      return to.slice(toStart);
    }
  },

  _makeLong: function _makeLong(path) {
    return path;
  },

  dirname: function dirname(path) {
    assertPath(path);
    if (path.length === 0) return '.';
    var code = path.charCodeAt(0);
    var hasRoot = code === 47 /*/*/;
    var end = -1;
    var matchedSlash = true;
    for (var i = path.length - 1; i >= 1; --i) {
      code = path.charCodeAt(i);
      if (code === 47 /*/*/) {
          if (!matchedSlash) {
            end = i;
            break;
          }
        } else {
        // We saw the first non-path separator
        matchedSlash = false;
      }
    }

    if (end === -1) return hasRoot ? '/' : '.';
    if (hasRoot && end === 1) return '//';
    return path.slice(0, end);
  },

  basename: function basename(path, ext) {
    if (ext !== undefined && typeof ext !== 'string') throw new TypeError('"ext" argument must be a string');
    assertPath(path);

    var start = 0;
    var end = -1;
    var matchedSlash = true;
    var i;

    if (ext !== undefined && ext.length > 0 && ext.length <= path.length) {
      if (ext.length === path.length && ext === path) return '';
      var extIdx = ext.length - 1;
      var firstNonSlashEnd = -1;
      for (i = path.length - 1; i >= 0; --i) {
        var code = path.charCodeAt(i);
        if (code === 47 /*/*/) {
            // If we reached a path separator that was not part of a set of path
            // separators at the end of the string, stop now
            if (!matchedSlash) {
              start = i + 1;
              break;
            }
          } else {
          if (firstNonSlashEnd === -1) {
            // We saw the first non-path separator, remember this index in case
            // we need it if the extension ends up not matching
            matchedSlash = false;
            firstNonSlashEnd = i + 1;
          }
          if (extIdx >= 0) {
            // Try to match the explicit extension
            if (code === ext.charCodeAt(extIdx)) {
              if (--extIdx === -1) {
                // We matched the extension, so mark this as the end of our path
                // component
                end = i;
              }
            } else {
              // Extension does not match, so our result is the entire path
              // component
              extIdx = -1;
              end = firstNonSlashEnd;
            }
          }
        }
      }

      if (start === end) end = firstNonSlashEnd;else if (end === -1) end = path.length;
      return path.slice(start, end);
    } else {
      for (i = path.length - 1; i >= 0; --i) {
        if (path.charCodeAt(i) === 47 /*/*/) {
            // If we reached a path separator that was not part of a set of path
            // separators at the end of the string, stop now
            if (!matchedSlash) {
              start = i + 1;
              break;
            }
          } else if (end === -1) {
          // We saw the first non-path separator, mark this as the end of our
          // path component
          matchedSlash = false;
          end = i + 1;
        }
      }

      if (end === -1) return '';
      return path.slice(start, end);
    }
  },

  extname: function extname(path) {
    assertPath(path);
    var startDot = -1;
    var startPart = 0;
    var end = -1;
    var matchedSlash = true;
    // Track the state of characters (if any) we see before our first dot and
    // after any path separator we find
    var preDotState = 0;
    for (var i = path.length - 1; i >= 0; --i) {
      var code = path.charCodeAt(i);
      if (code === 47 /*/*/) {
          // If we reached a path separator that was not part of a set of path
          // separators at the end of the string, stop now
          if (!matchedSlash) {
            startPart = i + 1;
            break;
          }
          continue;
        }
      if (end === -1) {
        // We saw the first non-path separator, mark this as the end of our
        // extension
        matchedSlash = false;
        end = i + 1;
      }
      if (code === 46 /*.*/) {
          // If this is our first dot, mark it as the start of our extension
          if (startDot === -1)
            startDot = i;
          else if (preDotState !== 1)
            preDotState = 1;
      } else if (startDot !== -1) {
        // We saw a non-dot and non-path separator before our dot, so we should
        // have a good chance at having a non-empty extension
        preDotState = -1;
      }
    }

    if (startDot === -1 || end === -1 ||
        // We saw a non-dot character immediately before the dot
        preDotState === 0 ||
        // The (right-most) trimmed path component is exactly '..'
        preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
      return '';
    }
    return path.slice(startDot, end);
  },

  format: function format(pathObject) {
    if (pathObject === null || typeof pathObject !== 'object') {
      throw new TypeError('The "pathObject" argument must be of type Object. Received type ' + typeof pathObject);
    }
    return _format('/', pathObject);
  },

  parse: function parse(path) {
    assertPath(path);

    var ret = { root: '', dir: '', base: '', ext: '', name: '' };
    if (path.length === 0) return ret;
    var code = path.charCodeAt(0);
    var isAbsolute = code === 47 /*/*/;
    var start;
    if (isAbsolute) {
      ret.root = '/';
      start = 1;
    } else {
      start = 0;
    }
    var startDot = -1;
    var startPart = 0;
    var end = -1;
    var matchedSlash = true;
    var i = path.length - 1;

    // Track the state of characters (if any) we see before our first dot and
    // after any path separator we find
    var preDotState = 0;

    // Get non-dir info
    for (; i >= start; --i) {
      code = path.charCodeAt(i);
      if (code === 47 /*/*/) {
          // If we reached a path separator that was not part of a set of path
          // separators at the end of the string, stop now
          if (!matchedSlash) {
            startPart = i + 1;
            break;
          }
          continue;
        }
      if (end === -1) {
        // We saw the first non-path separator, mark this as the end of our
        // extension
        matchedSlash = false;
        end = i + 1;
      }
      if (code === 46 /*.*/) {
          // If this is our first dot, mark it as the start of our extension
          if (startDot === -1) startDot = i;else if (preDotState !== 1) preDotState = 1;
        } else if (startDot !== -1) {
        // We saw a non-dot and non-path separator before our dot, so we should
        // have a good chance at having a non-empty extension
        preDotState = -1;
      }
    }

    if (startDot === -1 || end === -1 ||
    // We saw a non-dot character immediately before the dot
    preDotState === 0 ||
    // The (right-most) trimmed path component is exactly '..'
    preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
      if (end !== -1) {
        if (startPart === 0 && isAbsolute) ret.base = ret.name = path.slice(1, end);else ret.base = ret.name = path.slice(startPart, end);
      }
    } else {
      if (startPart === 0 && isAbsolute) {
        ret.name = path.slice(1, startDot);
        ret.base = path.slice(1, end);
      } else {
        ret.name = path.slice(startPart, startDot);
        ret.base = path.slice(startPart, end);
      }
      ret.ext = path.slice(startDot, end);
    }

    if (startPart > 0) ret.dir = path.slice(0, startPart - 1);else if (isAbsolute) ret.dir = '/';

    return ret;
  },

  sep: '/',
  delimiter: ':',
  win32: null,
  posix: null
};

posix.posix = posix;

module.exports = posix;

}).call(this)}).call(this,require('_process'))
},{"_process":87}],"rw":[function(require,module,exports){
exports.dash = require("./lib/rw/dash");
exports.readFile = require("./lib/rw/read-file");
exports.readFileSync = require("./lib/rw/read-file-sync");
exports.writeFile = require("./lib/rw/write-file");
exports.writeFileSync = require("./lib/rw/write-file-sync");

},{"./lib/rw/dash":38,"./lib/rw/read-file":42,"./lib/rw/read-file-sync":41,"./lib/rw/write-file":44,"./lib/rw/write-file-sync":43}],"sync-request":[function(require,module,exports){
"use strict";
exports.__esModule = true;
var handle_qs_js_1 = require("then-request/lib/handle-qs.js");
var GenericResponse = require("http-response-object");
var fd = FormData;
exports.FormData = fd;
function doRequest(method, url, options) {
    var xhr = new XMLHttpRequest();
    // check types of arguments
    if (typeof method !== 'string') {
        throw new TypeError('The method must be a string.');
    }
    if (url && typeof url === 'object') {
        url = url.href;
    }
    if (typeof url !== 'string') {
        throw new TypeError('The URL/path must be a string.');
    }
    if (options === null || options === undefined) {
        options = {};
    }
    if (typeof options !== 'object') {
        throw new TypeError('Options must be an object (or null).');
    }
    method = method.toUpperCase();
    options.headers = options.headers || {};
    // handle cross domain
    var match;
    var crossDomain = !!((match = /^([\w-]+:)?\/\/([^\/]+)/.exec(url)) && match[2] != location.host);
    if (!crossDomain)
        options.headers['X-Requested-With'] = 'XMLHttpRequest';
    // handle query string
    if (options.qs) {
        url = handle_qs_js_1["default"](url, options.qs);
    }
    // handle json body
    if (options.json) {
        options.body = JSON.stringify(options.json);
        options.headers['content-type'] = 'application/json';
    }
    if (options.form) {
        options.body = options.form;
    }
    // method, url, async
    xhr.open(method, url, false);
    for (var name in options.headers) {
        xhr.setRequestHeader(name.toLowerCase(), '' + options.headers[name]);
    }
    // avoid sending empty string (#319)
    xhr.send(options.body ? options.body : null);
    var headers = {};
    xhr
        .getAllResponseHeaders()
        .split('\r\n')
        .forEach(function (header) {
        var h = header.split(':');
        if (h.length > 1) {
            headers[h[0].toLowerCase()] = h
                .slice(1)
                .join(':')
                .trim();
        }
    });
    return new GenericResponse(xhr.status, headers, xhr.responseText, url);
}
exports["default"] = doRequest;
module.exports = doRequest;
module.exports["default"] = doRequest;
module.exports.FormData = fd;

},{"http-response-object":10,"then-request/lib/handle-qs.js":47}]},{},[1]);
