/**
 * image-js - Image processing and manipulation in JavaScript
 * @version v0.37.0
 * @link https://github.com/image-js/image-js
 * @license MIT
 */
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  typeof define === 'function' && define.amd ? define(['exports'], factory) :
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.IJS = {}));
})(this, (function (exports) { 'use strict';

  // Those methods can only be called on binary images, but we won't lose time to check.
  const bitMethods = {
    /**
     * Get the bit of a pixel using a pixel index.
     * This method can only be called on binary images.
     * @memberof Image
     * @instance
     * @param {number} pixel - The pixel index which corresponds to `x * image.width + y`
     * @return {number} 0: bit is unset, 1: bit is set
     */
    getBit(pixel) {
      return this.data[getSlot(pixel)] & 1 << getShift(pixel) ? 1 : 0;
    },
    /**
     * Set the bit of a pixel using a pixel index.
     * This method can only be called on binary images.
     * @memberof Image
     * @instance
     * @param {number} pixel - The pixel index which corresponds to `x * image.width + y`
     */
    setBit(pixel) {
      this.data[getSlot(pixel)] |= 1 << getShift(pixel);
    },
    /**
     * Clear the bit of a pixel using a pixel index.
     * This method can only be called on binary images.
     * @memberof Image
     * @instance
     * @param {number} pixel - The pixel index which corresponds to `x * image.width + y`
     */
    clearBit(pixel) {
      this.data[getSlot(pixel)] &= ~(1 << getShift(pixel));
    },
    /**
     * Toggle (invert) the bit of a pixel using a pixel index.
     * This method can only be called on binary images.
     * @memberof Image
     * @instance
     * @param {number} pixel - The pixel index which corresponds to `x * image.width + y`
     */
    toggleBit(pixel) {
      this.data[getSlot(pixel)] ^= 1 << getShift(pixel);
    },
    /**
     * Get the bit of a pixel using coordinates.
     * This method can only be called on binary images.
     * @memberof Image
     * @instance
     * @param {number} x - x coordinate (0 = left)
     * @param {number} y - y coordinate (0 = top)
     * @return {number} 0: bit is unset, 1: bit is set
     */
    getBitXY(x, y) {
      if (x >= this.width || y >= this.height) return 0;
      return this.getBit(y * this.width + x);
    },
    /**
     * Set the bit of a pixel using coordinates.
     * This method can only be called on binary images.
     * @memberof Image
     * @instance
     * @param {number} x - x coordinate (0 = left)
     * @param {number} y - y coordinate (0 = top)
     */
    setBitXY(x, y) {
      this.setBit(y * this.width + x);
    },
    /**
     * Clear the bit of a pixel using coordinates.
     * @memberof Image
     * @instance
     * @param {number} x - x coordinate (0 = left)
     * @param {number} y - y coordinate (0 = top)
     */
    clearBitXY(x, y) {
      this.clearBit(y * this.width + x);
    },
    /**
     * Toggle (invert) the bit of a pixel using coordinates.
     * @memberof Image
     * @instance
     * @param {number} x - x coordinate (0 = left)
     * @param {number} y - y coordinate (0 = top)
     */
    toggleBitXY(x, y) {
      this.toggleBit(y * this.width + x);
    }
  };
  function getSlot(pixel) {
    return pixel >> 3;
  }
  function getShift(pixel) {
    return 7 - (pixel & 0b00000111);
  }
  function setBitMethods(Image) {
    for (const i in bitMethods) {
      Image.prototype[i] = bitMethods[i];
    }
  }

  /**
   * This method checks if a process can be applied on the current image
   * @memberof Image
   * @instance
   * @param {string} processName
   * @param {object} [options]
   */
  function checkProcessable(processName, options = {}) {
    let {
      bitDepth,
      alpha,
      colorModel,
      components,
      channels
    } = options;
    if (typeof processName !== 'string' || processName.length === 0) {
      throw new TypeError('processName must be a string');
    }
    if (bitDepth) {
      if (!Array.isArray(bitDepth)) {
        bitDepth = [bitDepth];
      }
      if (!bitDepth.includes(this.bitDepth)) {
        throw new TypeError(`The process: ${processName} can only be applied if bit depth is in: ${bitDepth}`);
      }
    }
    if (alpha) {
      if (!Array.isArray(alpha)) {
        alpha = [alpha];
      }
      if (!alpha.includes(this.alpha)) {
        throw new TypeError(`The process: ${processName} can only be applied if alpha is in: ${alpha}`);
      }
    }
    if (colorModel) {
      if (!Array.isArray(colorModel)) {
        colorModel = [colorModel];
      }
      if (!colorModel.includes(this.colorModel)) {
        throw new TypeError(`The process: ${processName} can only be applied if color model is in: ${colorModel}`);
      }
    }
    if (components) {
      if (!Array.isArray(components)) {
        components = [components];
      }
      if (!components.includes(this.components)) {
        let errorMessage = `The process: ${processName} can only be applied if the number of components is in: ${components}`;
        if (components.length === 1 && components[0] === 1) {
          throw new TypeError(`${errorMessage}.\rYou should transform your image using "image.grey()" before applying the algorithm.`);
        } else {
          throw new TypeError(errorMessage);
        }
      }
    }
    if (channels) {
      if (!Array.isArray(channels)) {
        channels = [channels];
      }
      if (!channels.includes(this.channels)) {
        throw new TypeError(`The process: ${processName} can only be applied if the number of channels is in: ${channels}`);
      }
    }
  }

  // TODO: including these in blob-util.ts causes typedoc to generate docs for them,
  // even with --excludePrivate ¯\_(ツ)_/¯
  /** @private */

  /* global Promise, Image, Blob, FileReader, atob, btoa,
     BlobBuilder, MSBlobBuilder, MozBlobBuilder, WebKitBlobBuilder, webkitURL */
  /**
   * Shim for
   * [`new Blob()`](https://developer.mozilla.org/en-US/docs/Web/API/Blob.Blob)
   * to support
   * [older browsers that use the deprecated `BlobBuilder` API](http://caniuse.com/blob).
   *
   * Example:
   *
   * ```js
   * var myBlob = blobUtil.createBlob(['hello world'], {type: 'text/plain'});
   * ```
   *
   * @param parts - content of the Blob
   * @param properties - usually `{type: myContentType}`,
   *                           you can also pass a string for the content type
   * @returns Blob
   */
  function createBlob(parts, properties) {
    parts = parts || [];
    properties = properties || {};
    if (typeof properties === 'string') {
      properties = {
        type: properties
      }; // infer content type
    }
    try {
      return new Blob(parts, properties);
    } catch (e) {
      if (e.name !== 'TypeError') {
        throw e;
      }
      var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : WebKitBlobBuilder;
      var builder = new Builder();
      for (var i = 0; i < parts.length; i += 1) {
        builder.append(parts[i]);
      }
      return builder.getBlob(properties.type);
    }
  }
  /**
   * Convert a data URL string
   * (e.g. `'data:image/png;base64,iVBORw0KG...'`)
   * to a `Blob`.
   *
   * Example:
   *
   * ```js
   * var blob = blobUtil.dataURLToBlob(dataURL);
   * ```
   *
   * @param dataURL - dataURL-encoded string
   * @returns Blob
   */
  function dataURLToBlob(dataURL) {
    var type = dataURL.match(/data:([^;]+)/)[1];
    var base64 = dataURL.replace(/^[^,]+,/, '');
    var buff = binaryStringToArrayBuffer(atob(base64));
    return createBlob([buff], {
      type: type
    });
  }
  /**
   * Convert a `canvas` to a `Blob`.
   *
   * Examples:
   *
   * ```js
   * blobUtil.canvasToBlob(canvas).then(function (blob) {
   *   // success
   * }).catch(function (err) {
   *   // error
   * });
   * ```
   *
   * Most browsers support converting a canvas to both `'image/png'` and `'image/jpeg'`. You may
   * also want to try `'image/webp'`, which will work in some browsers like Chrome (and in other browsers, will just fall back to `'image/png'`):
   *
   * ```js
   * blobUtil.canvasToBlob(canvas, 'image/webp').then(function (blob) {
   *   // success
   * }).catch(function (err) {
   *   // error
   * });
   * ```
   *
   * @param canvas - HTMLCanvasElement
   * @param type - the content type (optional, defaults to 'image/png')
   * @param quality - a number between 0 and 1 indicating image quality
   *                                     if the requested type is 'image/jpeg' or 'image/webp'
   * @returns Promise that resolves with the `Blob`
   */
  function canvasToBlob(canvas, type, quality) {
    if (typeof canvas.toBlob === 'function') {
      return new Promise(function (resolve) {
        canvas.toBlob(resolve, type, quality);
      });
    }
    return Promise.resolve(dataURLToBlob(canvas.toDataURL(type, quality)));
  }
  /**
   * Convert a binary string to an `ArrayBuffer`.
   *
   * ```js
   * var myBuffer = blobUtil.binaryStringToArrayBuffer(binaryString)
   * ```
   *
   * @param binary - binary string
   * @returns array buffer
   */
  function binaryStringToArrayBuffer(binary) {
    var length = binary.length;
    var buf = new ArrayBuffer(length);
    var arr = new Uint8Array(buf);
    var i = -1;
    while (++i < length) {
      arr[i] = binary.charCodeAt(i);
    }
    return buf;
  }

  function getDefaultExportFromCjs (x) {
  	return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  }

  function getAugmentedNamespace(n) {
    if (Object.prototype.hasOwnProperty.call(n, '__esModule')) return n;
    var f = n.default;
  	if (typeof f == "function") {
  		var a = function a () {
  			if (this instanceof a) {
          return Reflect.construct(f, arguments, this.constructor);
  			}
  			return f.apply(this, arguments);
  		};
  		a.prototype = f.prototype;
    } else a = {};
    Object.defineProperty(a, '__esModule', {value: true});
  	Object.keys(n).forEach(function (k) {
  		var d = Object.getOwnPropertyDescriptor(n, k);
  		Object.defineProperty(a, k, d.get ? d : {
  			enumerable: true,
  			get: function () {
  				return n[k];
  			}
  		});
  	});
  	return a;
  }

  function decode$5(bytes, encoding = 'utf8') {
    const decoder = new TextDecoder(encoding);
    return decoder.decode(bytes);
  }
  const encoder$1 = new TextEncoder();
  function encode$3(str) {
    return encoder$1.encode(str);
  }

  const defaultByteLength$1 = 1024 * 8;
  const hostBigEndian = (() => {
    const array = new Uint8Array(4);
    const view = new Uint32Array(array.buffer);
    return !((view[0] = 1) & array[0]);
  })();
  const typedArrays = {
    int8: globalThis.Int8Array,
    uint8: globalThis.Uint8Array,
    int16: globalThis.Int16Array,
    uint16: globalThis.Uint16Array,
    int32: globalThis.Int32Array,
    uint32: globalThis.Uint32Array,
    uint64: globalThis.BigUint64Array,
    int64: globalThis.BigInt64Array,
    float32: globalThis.Float32Array,
    float64: globalThis.Float64Array
  };
  let IOBuffer$4 = class IOBuffer {
    /**
     * Reference to the internal ArrayBuffer object.
     */
    buffer;
    /**
     * Byte length of the internal ArrayBuffer.
     */
    byteLength;
    /**
     * Byte offset of the internal ArrayBuffer.
     */
    byteOffset;
    /**
     * Byte length of the internal ArrayBuffer.
     */
    length;
    /**
     * The current offset of the buffer's pointer.
     */
    offset;
    lastWrittenByte;
    littleEndian;
    _data;
    _mark;
    _marks;
    /**
     * Create a new IOBuffer.
     * @param data - The data to construct the IOBuffer with.
     * If data is a number, it will be the new buffer's length<br>
     * If data is `undefined`, the buffer will be initialized with a default length of 8Kb<br>
     * If data is an ArrayBuffer, SharedArrayBuffer, an ArrayBufferView (Typed Array), an IOBuffer instance,
     * or a Node.js Buffer, a view will be created over the underlying ArrayBuffer.
     * @param options - An object for the options.
     * @returns A new IOBuffer instance.
     */
    constructor(data = defaultByteLength$1, options = {}) {
      let dataIsGiven = false;
      if (typeof data === 'number') {
        data = new ArrayBuffer(data);
      } else {
        dataIsGiven = true;
        this.lastWrittenByte = data.byteLength;
      }
      const offset = options.offset ? options.offset >>> 0 : 0;
      const byteLength = data.byteLength - offset;
      let dvOffset = offset;
      if (ArrayBuffer.isView(data) || data instanceof IOBuffer) {
        if (data.byteLength !== data.buffer.byteLength) {
          dvOffset = data.byteOffset + offset;
        }
        data = data.buffer;
      }
      if (dataIsGiven) {
        this.lastWrittenByte = byteLength;
      } else {
        this.lastWrittenByte = 0;
      }
      this.buffer = data;
      this.length = byteLength;
      this.byteLength = byteLength;
      this.byteOffset = dvOffset;
      this.offset = 0;
      this.littleEndian = true;
      this._data = new DataView(this.buffer, dvOffset, byteLength);
      this._mark = 0;
      this._marks = [];
    }
    /**
     * Checks if the memory allocated to the buffer is sufficient to store more
     * bytes after the offset.
     * @param byteLength - The needed memory in bytes.
     * @returns `true` if there is sufficient space and `false` otherwise.
     */
    available(byteLength = 1) {
      return this.offset + byteLength <= this.length;
    }
    /**
     * Check if little-endian mode is used for reading and writing multi-byte
     * values.
     * @returns `true` if little-endian mode is used, `false` otherwise.
     */
    isLittleEndian() {
      return this.littleEndian;
    }
    /**
     * Set little-endian mode for reading and writing multi-byte values.
     * @returns This.
     */
    setLittleEndian() {
      this.littleEndian = true;
      return this;
    }
    /**
     * Check if big-endian mode is used for reading and writing multi-byte values.
     * @returns `true` if big-endian mode is used, `false` otherwise.
     */
    isBigEndian() {
      return !this.littleEndian;
    }
    /**
     * Switches to big-endian mode for reading and writing multi-byte values.
     * @returns This.
     */
    setBigEndian() {
      this.littleEndian = false;
      return this;
    }
    /**
     * Move the pointer n bytes forward.
     * @param n - Number of bytes to skip.
     * @returns This.
     */
    skip(n = 1) {
      this.offset += n;
      return this;
    }
    /**
     * Move the pointer n bytes backward.
     * @param n - Number of bytes to move back.
     * @returns This.
     */
    back(n = 1) {
      this.offset -= n;
      return this;
    }
    /**
     * Move the pointer to the given offset.
     * @param offset - The offset to move to.
     * @returns This.
     */
    seek(offset) {
      this.offset = offset;
      return this;
    }
    /**
     * Store the current pointer offset.
     * @see {@link IOBuffer#reset}
     * @returns This.
     */
    mark() {
      this._mark = this.offset;
      return this;
    }
    /**
     * Move the pointer back to the last pointer offset set by mark.
     * @see {@link IOBuffer#mark}
     * @returns This.
     */
    reset() {
      this.offset = this._mark;
      return this;
    }
    /**
     * Push the current pointer offset to the mark stack.
     * @see {@link IOBuffer#popMark}
     * @returns This.
     */
    pushMark() {
      this._marks.push(this.offset);
      return this;
    }
    /**
     * Pop the last pointer offset from the mark stack, and set the current
     * pointer offset to the popped value.
     * @see {@link IOBuffer#pushMark}
     * @returns This.
     */
    popMark() {
      const offset = this._marks.pop();
      if (offset === undefined) {
        throw new Error('Mark stack empty');
      }
      this.seek(offset);
      return this;
    }
    /**
     * Move the pointer offset back to 0.
     * @returns This.
     */
    rewind() {
      this.offset = 0;
      return this;
    }
    /**
     * Make sure the buffer has sufficient memory to write a given byteLength at
     * the current pointer offset.
     * If the buffer's memory is insufficient, this method will create a new
     * buffer (a copy) with a length that is twice (byteLength + current offset).
     * @param byteLength - The needed memory in bytes.
     * @returns This.
     */
    ensureAvailable(byteLength = 1) {
      if (!this.available(byteLength)) {
        const lengthNeeded = this.offset + byteLength;
        const newLength = lengthNeeded * 2;
        const newArray = new Uint8Array(newLength);
        newArray.set(new Uint8Array(this.buffer));
        this.buffer = newArray.buffer;
        this.length = newLength;
        this.byteLength = newLength;
        this._data = new DataView(this.buffer);
      }
      return this;
    }
    /**
     * Read a byte and return false if the byte's value is 0, or true otherwise.
     * Moves pointer forward by one byte.
     * @returns The read boolean.
     */
    readBoolean() {
      return this.readUint8() !== 0;
    }
    /**
     * Read a signed 8-bit integer and move pointer forward by 1 byte.
     * @returns The read byte.
     */
    readInt8() {
      return this._data.getInt8(this.offset++);
    }
    /**
     * Read an unsigned 8-bit integer and move pointer forward by 1 byte.
     * @returns The read byte.
     */
    readUint8() {
      return this._data.getUint8(this.offset++);
    }
    /**
     * Alias for {@link IOBuffer#readUint8}.
     * @returns The read byte.
     */
    readByte() {
      return this.readUint8();
    }
    /**
     * Read `n` bytes and move pointer forward by `n` bytes.
     * @param n - Number of bytes to read.
     * @returns The read bytes.
     */
    readBytes(n = 1) {
      return this.readArray(n, 'uint8');
    }
    /**
     * Creates an array of corresponding to the type `type` and size `size`.
     * For example type `uint8` will create a `Uint8Array`.
     * @param size - size of the resulting array
     * @param type - number type of elements to read
     * @returns The read array.
     */
    readArray(size, type) {
      const bytes = typedArrays[type].BYTES_PER_ELEMENT * size;
      const offset = this.byteOffset + this.offset;
      const slice = this.buffer.slice(offset, offset + bytes);
      if (this.littleEndian === hostBigEndian && type !== 'uint8' && type !== 'int8') {
        const slice = new Uint8Array(this.buffer.slice(offset, offset + bytes));
        slice.reverse();
        const returnArray = new typedArrays[type](slice.buffer);
        this.offset += bytes;
        returnArray.reverse();
        return returnArray;
      }
      const returnArray = new typedArrays[type](slice);
      this.offset += bytes;
      return returnArray;
    }
    /**
     * Read a 16-bit signed integer and move pointer forward by 2 bytes.
     * @returns The read value.
     */
    readInt16() {
      const value = this._data.getInt16(this.offset, this.littleEndian);
      this.offset += 2;
      return value;
    }
    /**
     * Read a 16-bit unsigned integer and move pointer forward by 2 bytes.
     * @returns The read value.
     */
    readUint16() {
      const value = this._data.getUint16(this.offset, this.littleEndian);
      this.offset += 2;
      return value;
    }
    /**
     * Read a 32-bit signed integer and move pointer forward by 4 bytes.
     * @returns The read value.
     */
    readInt32() {
      const value = this._data.getInt32(this.offset, this.littleEndian);
      this.offset += 4;
      return value;
    }
    /**
     * Read a 32-bit unsigned integer and move pointer forward by 4 bytes.
     * @returns The read value.
     */
    readUint32() {
      const value = this._data.getUint32(this.offset, this.littleEndian);
      this.offset += 4;
      return value;
    }
    /**
     * Read a 32-bit floating number and move pointer forward by 4 bytes.
     * @returns The read value.
     */
    readFloat32() {
      const value = this._data.getFloat32(this.offset, this.littleEndian);
      this.offset += 4;
      return value;
    }
    /**
     * Read a 64-bit floating number and move pointer forward by 8 bytes.
     * @returns The read value.
     */
    readFloat64() {
      const value = this._data.getFloat64(this.offset, this.littleEndian);
      this.offset += 8;
      return value;
    }
    /**
     * Read a 64-bit signed integer number and move pointer forward by 8 bytes.
     * @returns The read value.
     */
    readBigInt64() {
      const value = this._data.getBigInt64(this.offset, this.littleEndian);
      this.offset += 8;
      return value;
    }
    /**
     * Read a 64-bit unsigned integer number and move pointer forward by 8 bytes.
     * @returns The read value.
     */
    readBigUint64() {
      const value = this._data.getBigUint64(this.offset, this.littleEndian);
      this.offset += 8;
      return value;
    }
    /**
     * Read a 1-byte ASCII character and move pointer forward by 1 byte.
     * @returns The read character.
     */
    readChar() {
      // eslint-disable-next-line unicorn/prefer-code-point
      return String.fromCharCode(this.readInt8());
    }
    /**
     * Read `n` 1-byte ASCII characters and move pointer forward by `n` bytes.
     * @param n - Number of characters to read.
     * @returns The read characters.
     */
    readChars(n = 1) {
      let result = '';
      for (let i = 0; i < n; i++) {
        result += this.readChar();
      }
      return result;
    }
    /**
     * Read the next `n` bytes, return a UTF-8 decoded string and move pointer
     * forward by `n` bytes.
     * @param n - Number of bytes to read.
     * @returns The decoded string.
     */
    readUtf8(n = 1) {
      return decode$5(this.readBytes(n));
    }
    /**
     * Read the next `n` bytes, return a string decoded with `encoding` and move pointer
     * forward by `n` bytes.
     * If no encoding is passed, the function is equivalent to @see {@link IOBuffer#readUtf8}
     * @param n - Number of bytes to read.
     * @param encoding - The encoding to use. Default is 'utf8'.
     * @returns The decoded string.
     */
    decodeText(n = 1, encoding = 'utf8') {
      return decode$5(this.readBytes(n), encoding);
    }
    /**
     * Write 0xff if the passed value is truthy, 0x00 otherwise and move pointer
     * forward by 1 byte.
     * @param value - The value to write.
     * @returns This.
     */
    writeBoolean(value) {
      this.writeUint8(value ? 0xff : 0x00);
      return this;
    }
    /**
     * Write `value` as an 8-bit signed integer and move pointer forward by 1 byte.
     * @param value - The value to write.
     * @returns This.
     */
    writeInt8(value) {
      this.ensureAvailable(1);
      this._data.setInt8(this.offset++, value);
      this._updateLastWrittenByte();
      return this;
    }
    /**
     * Write `value` as an 8-bit unsigned integer and move pointer forward by 1
     * byte.
     * @param value - The value to write.
     * @returns This.
     */
    writeUint8(value) {
      this.ensureAvailable(1);
      this._data.setUint8(this.offset++, value);
      this._updateLastWrittenByte();
      return this;
    }
    /**
     * An alias for {@link IOBuffer#writeUint8}.
     * @param value - The value to write.
     * @returns This.
     */
    writeByte(value) {
      return this.writeUint8(value);
    }
    /**
     * Write all elements of `bytes` as uint8 values and move pointer forward by
     * `bytes.length` bytes.
     * @param bytes - The array of bytes to write.
     * @returns This.
     */
    writeBytes(bytes) {
      this.ensureAvailable(bytes.length);
      // eslint-disable-next-line @typescript-eslint/prefer-for-of
      for (let i = 0; i < bytes.length; i++) {
        this._data.setUint8(this.offset++, bytes[i]);
      }
      this._updateLastWrittenByte();
      return this;
    }
    /**
     * Write `value` as a 16-bit signed integer and move pointer forward by 2
     * bytes.
     * @param value - The value to write.
     * @returns This.
     */
    writeInt16(value) {
      this.ensureAvailable(2);
      this._data.setInt16(this.offset, value, this.littleEndian);
      this.offset += 2;
      this._updateLastWrittenByte();
      return this;
    }
    /**
     * Write `value` as a 16-bit unsigned integer and move pointer forward by 2
     * bytes.
     * @param value - The value to write.
     * @returns This.
     */
    writeUint16(value) {
      this.ensureAvailable(2);
      this._data.setUint16(this.offset, value, this.littleEndian);
      this.offset += 2;
      this._updateLastWrittenByte();
      return this;
    }
    /**
     * Write `value` as a 32-bit signed integer and move pointer forward by 4
     * bytes.
     * @param value - The value to write.
     * @returns This.
     */
    writeInt32(value) {
      this.ensureAvailable(4);
      this._data.setInt32(this.offset, value, this.littleEndian);
      this.offset += 4;
      this._updateLastWrittenByte();
      return this;
    }
    /**
     * Write `value` as a 32-bit unsigned integer and move pointer forward by 4
     * bytes.
     * @param value - The value to write.
     * @returns This.
     */
    writeUint32(value) {
      this.ensureAvailable(4);
      this._data.setUint32(this.offset, value, this.littleEndian);
      this.offset += 4;
      this._updateLastWrittenByte();
      return this;
    }
    /**
     * Write `value` as a 32-bit floating number and move pointer forward by 4
     * bytes.
     * @param value - The value to write.
     * @returns This.
     */
    writeFloat32(value) {
      this.ensureAvailable(4);
      this._data.setFloat32(this.offset, value, this.littleEndian);
      this.offset += 4;
      this._updateLastWrittenByte();
      return this;
    }
    /**
     * Write `value` as a 64-bit floating number and move pointer forward by 8
     * bytes.
     * @param value - The value to write.
     * @returns This.
     */
    writeFloat64(value) {
      this.ensureAvailable(8);
      this._data.setFloat64(this.offset, value, this.littleEndian);
      this.offset += 8;
      this._updateLastWrittenByte();
      return this;
    }
    /**
     * Write `value` as a 64-bit signed bigint and move pointer forward by 8
     * bytes.
     * @param value - The value to write.
     * @returns This.
     */
    writeBigInt64(value) {
      this.ensureAvailable(8);
      this._data.setBigInt64(this.offset, value, this.littleEndian);
      this.offset += 8;
      this._updateLastWrittenByte();
      return this;
    }
    /**
     * Write `value` as a 64-bit unsigned bigint and move pointer forward by 8
     * bytes.
     * @param value - The value to write.
     * @returns This.
     */
    writeBigUint64(value) {
      this.ensureAvailable(8);
      this._data.setBigUint64(this.offset, value, this.littleEndian);
      this.offset += 8;
      this._updateLastWrittenByte();
      return this;
    }
    /**
     * Write the charCode of `str`'s first character as an 8-bit unsigned integer
     * and move pointer forward by 1 byte.
     * @param str - The character to write.
     * @returns This.
     */
    writeChar(str) {
      // eslint-disable-next-line unicorn/prefer-code-point
      return this.writeUint8(str.charCodeAt(0));
    }
    /**
     * Write the charCodes of all `str`'s characters as 8-bit unsigned integers
     * and move pointer forward by `str.length` bytes.
     * @param str - The characters to write.
     * @returns This.
     */
    writeChars(str) {
      for (let i = 0; i < str.length; i++) {
        // eslint-disable-next-line unicorn/prefer-code-point
        this.writeUint8(str.charCodeAt(i));
      }
      return this;
    }
    /**
     * UTF-8 encode and write `str` to the current pointer offset and move pointer
     * forward according to the encoded length.
     * @param str - The string to write.
     * @returns This.
     */
    writeUtf8(str) {
      return this.writeBytes(encode$3(str));
    }
    /**
     * Export a Uint8Array view of the internal buffer.
     * The view starts at the byte offset and its length
     * is calculated to stop at the last written byte or the original length.
     * @returns A new Uint8Array view.
     */
    toArray() {
      return new Uint8Array(this.buffer, this.byteOffset, this.lastWrittenByte);
    }
    /**
     *  Get the total number of bytes written so far, regardless of the current offset.
     * @returns - Total number of bytes.
     */
    getWrittenByteLength() {
      return this.lastWrittenByte - this.byteOffset;
    }
    /**
     * Update the last written byte offset
     * @private
     */
    _updateLastWrittenByte() {
      if (this.offset > this.lastWrittenByte) {
        this.lastWrittenByte = this.offset;
      }
    }
  };

  var IOBuffer$5 = /*#__PURE__*/Object.freeze({
    __proto__: null,
    IOBuffer: IOBuffer$4
  });

  var require$$0$3 = /*@__PURE__*/getAugmentedNamespace(IOBuffer$5);

  var constants$1 = {
    BITMAPV5HEADER: {
      LogicalColorSpace: {
        LCS_sRGB: 0x73524742},
      Compression: {
        // https://msdn.microsoft.com/en-us/library/cc250415.aspx
        BI_RGB: 0x0000},
      GamutMappingIntent: {
        LCS_GM_IMAGES: 0x00000004
      }
    }
  };

  const {
    IOBuffer: IOBuffer$3
  } = require$$0$3;
  const constants = constants$1;
  const tableLeft = [];
  for (let i = 0; i <= 8; i++) {
    tableLeft.push(0b11111111 << i);
  }
  class BMPEncoder extends IOBuffer$3 {
    constructor(data) {
      if (data.bitDepth !== 1) {
        throw new Error('Only bitDepth of 1 is supported');
      }
      if (!data.height || !data.width) {
        throw new Error('ImageData width and height are required');
      }
      super(data.data);
      this.width = data.width;
      this.height = data.height;
      this.bitDepth = data.bitDepth;
      this.channels = data.channels;
      this.components = data.components;
    }
    encode() {
      this.encoded = new IOBuffer$3();
      this.encoded.skip(14);
      this.writeBitmapV5Header();
      this.writeColorTable();
      const offset = this.encoded.offset;
      this.writePixelArray();
      this.encoded.rewind();
      this.writeBitmapFileHeader(offset);
      return this.encoded.toArray();
    }
    writePixelArray() {
      let io = this.encoded;
      const rowSize = Math.floor((this.bitDepth * this.width + 31) / 32) * 4;
      const dataRowSize = Math.ceil(this.bitDepth * this.width / 8);
      const skipSize = rowSize - dataRowSize;
      const bitOverflow = this.bitDepth * this.width % 8;
      const bitSkip = bitOverflow === 0 ? 0 : 8 - bitOverflow;
      const totalBytes = rowSize * this.height;
      let byteA, byteB;
      let offset = 0; // Current off set in the ioData
      let relOffset = 0;
      let iOffset = 8;
      io.mark();
      byteB = this.readUint8();
      for (let i = this.height - 1; i >= 0; i--) {
        const lastRow = i === 0;
        io.reset();
        io.skip(i * rowSize);
        for (let j = 0; j < dataRowSize; j++) {
          const lastCol = j === dataRowSize - 1;
          if (relOffset <= bitSkip && lastCol) {
            // no need to read new data
            io.writeByte(byteB << relOffset);
            if ((bitSkip === 0 || bitSkip === relOffset) && !lastRow) {
              byteA = byteB;
              byteB = this.readByte();
            }
          } else if (relOffset === 0) {
            byteA = byteB;
            byteB = this.readUint8();
            io.writeByte(byteA);
          } else {
            byteA = byteB;
            byteB = this.readUint8();
            io.writeByte(byteA << relOffset & tableLeft[relOffset] | byteB >> iOffset);
          }
          if (lastCol) {
            offset += bitOverflow || 0;
            io.skip(skipSize);
            relOffset = offset % 8;
            iOffset = 8 - relOffset;
          }
        }
      }
      if (rowSize > dataRowSize) {
        // make sure last written byte is correct
        io.reset();
        io.skip(totalBytes - 1);
        io.writeUint8(0);
      }
    }
    writeColorTable() {
      // We only handle 1-bit images
      this.encoded.writeUint32(0x00000000) // black
      .writeUint32(0x00ffffff); // white
    }
    writeBitmapFileHeader(imageOffset) {
      this.encoded.writeChars('BM') // 14 bytes bitmap file header
      .writeInt32(this.encoded.lastWrittenByte) // Size of BMP file in bytes
      .writeUint16(0).writeUint16(0).writeUint32(imageOffset);
    }
    writeBitmapV5Header() {
      const rowSize = Math.floor((this.bitDepth * this.width + 31) / 32) * 4;
      const totalBytes = rowSize * this.height;
      // Size of the header
      this.encoded.writeUint32(124) // Header size
      .writeInt32(this.width) // bV5Width
      .writeInt32(this.height) // bV5Height
      .writeUint16(1) // bv5Planes - must be set to 1
      .writeUint16(this.bitDepth) // bV5BitCount
      .writeUint32(constants.BITMAPV5HEADER.Compression.BI_RGB) // bV5Compression - No compression
      .writeUint32(totalBytes) // bv5SizeImage - size of pixel buffer (can be 0 if uncompressed)
      .writeInt32(0) // bV5XPelsPerMeter - resolution
      .writeInt32(0) // bV5YPelsPerMeter - resolution
      .writeUint32(Math.pow(2, this.bitDepth)).writeUint32(Math.pow(2, this.bitDepth)).writeUint32(0xff000000) // bV5RedMask
      .writeUint32(0x00ff0000) // bV5GreenMask
      .writeUint32(0x0000ff00) // bV5BlueMask
      .writeUint32(0x000000ff) // bV5AlphaMask
      .writeUint32(constants.BITMAPV5HEADER.LogicalColorSpace.LCS_sRGB).skip(36) // bV5Endpoints
      .skip(12) // bV5GammaRed, Green, Blue
      .writeUint32(constants.BITMAPV5HEADER.GamutMappingIntent.LCS_GM_IMAGES).skip(12); // ProfileData, ProfileSize, Reserved
    }
  }
  var BMPEncoder_1 = BMPEncoder;

  const Encoder = BMPEncoder_1;
  var encode$2 = function encode(data) {
    const encoder = new Encoder(data);
    return encoder.encode();
  };

  /*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */
  // (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 */

  /* Public constants ==========================================================*/
  /* ===========================================================================*/

  //const Z_FILTERED          = 1;
  //const Z_HUFFMAN_ONLY      = 2;
  //const Z_RLE               = 3;
  const Z_FIXED$1 = 4;
  //const Z_DEFAULT_STRATEGY  = 0;

  /* Possible values of the data_type field (though see inflate()) */
  const Z_BINARY = 0;
  const Z_TEXT = 1;
  //const Z_ASCII             = 1; // = Z_TEXT
  const Z_UNKNOWN$1 = 2;

  /*============================================================================*/

  function zero$1(buf) {
    let len = buf.length;
    while (--len >= 0) {
      buf[len] = 0;
    }
  }

  // From zutil.h

  const STORED_BLOCK = 0;
  const STATIC_TREES = 1;
  const DYN_TREES = 2;
  /* The three kinds of block type */

  const MIN_MATCH$1 = 3;
  const MAX_MATCH$1 = 258;
  /* The minimum and maximum match lengths */

  // From deflate.h
  /* ===========================================================================
   * Internal compression state.
   */

  const LENGTH_CODES$1 = 29;
  /* number of length codes, not counting the special END_BLOCK code */

  const LITERALS$1 = 256;
  /* number of literal bytes 0..255 */

  const L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1;
  /* number of Literal or Length codes, including the END_BLOCK code */

  const D_CODES$1 = 30;
  /* number of distance codes */

  const BL_CODES$1 = 19;
  /* number of codes used to transfer the bit lengths */

  const HEAP_SIZE$1 = 2 * L_CODES$1 + 1;
  /* maximum heap size */

  const MAX_BITS$1 = 15;
  /* All codes must not exceed MAX_BITS bits */

  const Buf_size = 16;
  /* size of bit buffer in bi_buf */

  /* ===========================================================================
   * Constants
   */

  const MAX_BL_BITS = 7;
  /* Bit length codes must not exceed MAX_BL_BITS bits */

  const END_BLOCK = 256;
  /* end of block literal code */

  const REP_3_6 = 16;
  /* repeat previous bit length 3-6 times (2 bits of repeat count) */

  const REPZ_3_10 = 17;
  /* repeat a zero length 3-10 times  (3 bits of repeat count) */

  const REPZ_11_138 = 18;
  /* repeat a zero length 11-138 times  (7 bits of repeat count) */

  /* eslint-disable comma-spacing,array-bracket-spacing */
  const extra_lbits = /* extra bits for each length code */
  new Uint8Array([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]);
  const extra_dbits = /* extra bits for each distance code */
  new Uint8Array([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]);
  const extra_blbits = /* extra bits for each bit length code */
  new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7]);
  const bl_order = new Uint8Array([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

  const DIST_CODE_LEN = 512; /* see definition of array dist_code below */

  // !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
  const static_ltree = new Array((L_CODES$1 + 2) * 2);
  zero$1(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).
   */

  const static_dtree = new Array(D_CODES$1 * 2);
  zero$1(static_dtree);
  /* The static distance tree. (Actually a trivial tree since all codes use
   * 5 bits.)
   */

  const _dist_code = new Array(DIST_CODE_LEN);
  zero$1(_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.
   */

  const _length_code = new Array(MAX_MATCH$1 - MIN_MATCH$1 + 1);
  zero$1(_length_code);
  /* length code for each normalized match length (0 == MIN_MATCH) */

  const base_length = new Array(LENGTH_CODES$1);
  zero$1(base_length);
  /* First normalized length for each code (0 = MIN_MATCH) */

  const base_dist = new Array(D_CODES$1);
  zero$1(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;
  }
  let static_l_desc;
  let static_d_desc;
  let 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 */
  }
  const 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.
   */
  const 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.
   */
  const 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;
    }
  };
  const 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
   */
  const bi_reverse = (code, len) => {
    let 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.
   */
  const 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.
   */
  const gen_bitlen = (s, desc) => {
    //    deflate_state *s;
    //    tree_desc *desc;    /* the tree descriptor */

    const tree = desc.dyn_tree;
    const max_code = desc.max_code;
    const stree = desc.stat_desc.static_tree;
    const has_stree = desc.stat_desc.has_stree;
    const extra = desc.stat_desc.extra_bits;
    const base = desc.stat_desc.extra_base;
    const max_length = desc.stat_desc.max_length;
    let h; /* heap index */
    let n, m; /* iterate over the tree elements */
    let bits; /* bit length */
    let xbits; /* extra bits */
    let f; /* frequency */
    let overflow = 0; /* number of elements with bit length too large */

    for (bits = 0; bits <= MAX_BITS$1; 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$1; 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;
    }

    // Tracev((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) {
          // Tracev((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.
   */
  const 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 */

    const next_code = new Array(MAX_BITS$1 + 1); /* next code value for each bit length */
    let code = 0; /* running code value */
    let bits; /* bit index */
    let n; /* code index */

    /* The distribution counts are first used to generate the code values
     * without bit reversal.
     */
    for (bits = 1; bits <= MAX_BITS$1; bits++) {
      code = code + bl_count[bits - 1] << 1;
      next_code[bits] = code;
    }
    /* 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++) {
      let 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.
   */
  const tr_static_init = () => {
    let n; /* iterates over tree elements */
    let bits; /* bit counter */
    let length; /* length value */
    let code; /* code value */
    let dist; /* distance index */
    const bl_count = new Array(MAX_BITS$1 + 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 - 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$1; 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$1; 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 + 1, bl_count);

    /* The static distance tree is trivial: */
    for (n = 0; n < D_CODES$1; 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 + 1, L_CODES$1, MAX_BITS$1);
    static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES$1, MAX_BITS$1);
    static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES$1, MAX_BL_BITS);

    //static_init_done = true;
  };

  /* ===========================================================================
   * Initialize a new block.
   */
  const init_block = s => {
    let n; /* iterates over tree elements */

    /* Initialize the trees. */
    for (n = 0; n < L_CODES$1; n++) {
      s.dyn_ltree[n * 2] /*.Freq*/ = 0;
    }
    for (n = 0; n < D_CODES$1; n++) {
      s.dyn_dtree[n * 2] /*.Freq*/ = 0;
    }
    for (n = 0; n < BL_CODES$1; n++) {
      s.bl_tree[n * 2] /*.Freq*/ = 0;
    }
    s.dyn_ltree[END_BLOCK * 2] /*.Freq*/ = 1;
    s.opt_len = s.static_len = 0;
    s.sym_next = s.matches = 0;
  };

  /* ===========================================================================
   * Flush the bit buffer and align the output on a byte boundary
   */
  const 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;
  };

  /* ===========================================================================
   * Compares to subtrees, using the tree depth as tie breaker when
   * the subtrees have equal frequency. This minimizes the worst case length.
   */
  const smaller = (tree, n, m, depth) => {
    const _n2 = n * 2;
    const _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).
   */
  const pqdownheap = (s, tree, k) => {
    //    deflate_state *s;
    //    ct_data *tree;  /* the tree to restore */
    //    int k;               /* node to move down */

    const v = s.heap[k];
    let 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
  // const SMALLEST = 1;

  /* ===========================================================================
   * Send the block data compressed using the given Huffman trees
   */
  const compress_block = (s, ltree, dtree) => {
    //    deflate_state *s;
    //    const ct_data *ltree; /* literal tree */
    //    const ct_data *dtree; /* distance tree */

    let dist; /* distance of matched string */
    let lc; /* match length or unmatched char (if dist == 0) */
    let sx = 0; /* running index in sym_buf */
    let code; /* the code to send */
    let extra; /* number of extra bits to send */

    if (s.sym_next !== 0) {
      do {
        dist = s.pending_buf[s.sym_buf + sx++] & 0xff;
        dist += (s.pending_buf[s.sym_buf + sx++] & 0xff) << 8;
        lc = s.pending_buf[s.sym_buf + sx++];
        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 + 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 sym_buf is ok: */
        //Assert(s->pending < s->lit_bufsize + sx, "pendingBuf overflow");
      } while (sx < s.sym_next);
    }
    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.
   */
  const build_tree = (s, desc) => {
    //    deflate_state *s;
    //    tree_desc *desc; /* the tree descriptor */

    const tree = desc.dyn_tree;
    const stree = desc.stat_desc.static_tree;
    const has_stree = desc.stat_desc.has_stree;
    const elems = desc.stat_desc.elems;
    let n, m; /* iterate over heap elements */
    let max_code = -1; /* largest code with non zero frequency */
    let 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$1;
    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.
   */
  const 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 */

    let n; /* iterates over all tree elements */
    let prevlen = -1; /* last emitted length */
    let curlen; /* length of current code */

    let nextlen = tree[0 * 2 + 1] /*.Len*/; /* length of next code */

    let count = 0; /* repeat count of the current code */
    let max_count = 7; /* max repeat count */
    let 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.
   */
  const 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 */

    let n; /* iterates over all tree elements */
    let prevlen = -1; /* last emitted length */
    let curlen; /* length of current code */

    let nextlen = tree[0 * 2 + 1] /*.Len*/; /* length of next code */

    let count = 0; /* repeat count of the current code */
    let max_count = 7; /* max repeat count */
    let 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.
   */
  const build_bl_tree = s => {
    let 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 - 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.
   */
  const send_all_trees = (s, lcodes, dcodes, blcodes) => {
    //    deflate_state *s;
    //    int lcodes, dcodes, blcodes; /* number of codes for each tree */

    let 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
   *       "block list" (0..6, 14..25, 28..31).
   *    b) There is at least one printable character belonging to the
   *       "allow 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.
   */
  const detect_data_type = s => {
    /* block_mask is the bit mask of block-listed bytes
     * set bits 0..6, 14..25, and 28..31
     * 0xf3ffc07f = binary 11110011111111111100000001111111
     */
    let block_mask = 0xf3ffc07f;
    let n;

    /* Check for non-textual ("block-listed") bytes. */
    for (n = 0; n <= 31; n++, block_mask >>>= 1) {
      if (block_mask & 1 && s.dyn_ltree[n * 2] /*.Freq*/ !== 0) {
        return Z_BINARY;
      }
    }

    /* Check for textual ("allow-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$1; n++) {
      if (s.dyn_ltree[n * 2] /*.Freq*/ !== 0) {
        return Z_TEXT;
      }
    }

    /* There are no "block-listed" or "allow-listed" bytes:
     * this stream either is empty or has tolerated ("gray-listed") bytes only.
     */
    return Z_BINARY;
  };
  let static_init_done = false;

  /* ===========================================================================
   * Initialize the tree data structures for a new zlib stream.
   */
  const _tr_init$1 = 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
   */
  const _tr_stored_block$1 = (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 */
    bi_windup(s); /* align on byte boundary */
    put_short(s, stored_len);
    put_short(s, ~stored_len);
    if (stored_len) {
      s.pending_buf.set(s.window.subarray(buf, buf + stored_len), s.pending);
    }
    s.pending += stored_len;
  };

  /* ===========================================================================
   * Send one empty static block to give enough lookahead for inflate.
   * This takes 10 bits, of which 7 may remain in the bit buffer.
   */
  const _tr_align$1 = 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 write out the encoded block.
   */
  const _tr_flush_block$1 = (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 */

    let opt_lenb, static_lenb; /* opt_len and static_len in bytes */
    let 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$1) {
        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->sym_next / 3));

      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$1(s, buf, stored_len, last);
    } else if (s.strategy === Z_FIXED$1 || 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.
   */
  const _tr_tally$1 = (s, dist, lc) => {
    //    deflate_state *s;
    //    unsigned dist;  /* distance of matched string */
    //    unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */

    s.pending_buf[s.sym_buf + s.sym_next++] = dist;
    s.pending_buf[s.sym_buf + s.sym_next++] = dist >> 8;
    s.pending_buf[s.sym_buf + s.sym_next++] = lc;
    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 + 1) * 2] /*.Freq*/++;
      s.dyn_dtree[d_code(dist) * 2] /*.Freq*/++;
    }
    return s.sym_next === s.sym_end;
  };
  var _tr_init_1 = _tr_init$1;
  var _tr_stored_block_1 = _tr_stored_block$1;
  var _tr_flush_block_1 = _tr_flush_block$1;
  var _tr_tally_1 = _tr_tally$1;
  var _tr_align_1 = _tr_align$1;
  var trees = {
    _tr_init: _tr_init_1,
    _tr_stored_block: _tr_stored_block_1,
    _tr_flush_block: _tr_flush_block_1,
    _tr_tally: _tr_tally_1,
    _tr_align: _tr_align_1
  };

  // 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.

  const adler32 = (adler, buf, len, pos) => {
    let 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;
  };
  var adler32_1 = adler32;

  // 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
  const makeTable = () => {
    let 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.
  const crcTable$1 = new Uint32Array(makeTable());
  const crc32 = (crc, buf, len, pos) => {
    const t = crcTable$1;
    const end = pos + len;
    crc ^= -1;
    for (let i = pos; i < end; i++) {
      crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 0xFF];
    }
    return crc ^ -1; // >>> 0;
  };
  var crc32_1 = crc32;

  // (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 messages = {
    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) */
  };

  // (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 constants$2 = {
    /* 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_STREAM_ERROR: -2,
    Z_DATA_ERROR: -3,
    Z_MEM_ERROR: -4,
    Z_BUF_ERROR: -5,
    Z_DEFAULT_COMPRESSION: -1,
    Z_FILTERED: 1,
    Z_HUFFMAN_ONLY: 2,
    Z_RLE: 3,
    Z_FIXED: 4,
    Z_DEFAULT_STRATEGY: 0,
    //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
  };

  // (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.

  const {
    _tr_init,
    _tr_stored_block,
    _tr_flush_block,
    _tr_tally,
    _tr_align
  } = trees;

  /* Public constants ==========================================================*/
  /* ===========================================================================*/

  const {
    Z_NO_FLUSH: Z_NO_FLUSH$2,
    Z_PARTIAL_FLUSH,
    Z_FULL_FLUSH: Z_FULL_FLUSH$1,
    Z_FINISH: Z_FINISH$3,
    Z_BLOCK: Z_BLOCK$1,
    Z_OK: Z_OK$3,
    Z_STREAM_END: Z_STREAM_END$3,
    Z_STREAM_ERROR: Z_STREAM_ERROR$2,
    Z_DATA_ERROR: Z_DATA_ERROR$2,
    Z_BUF_ERROR: Z_BUF_ERROR$1,
    Z_DEFAULT_COMPRESSION: Z_DEFAULT_COMPRESSION$1,
    Z_FILTERED,
    Z_HUFFMAN_ONLY,
    Z_RLE,
    Z_FIXED,
    Z_DEFAULT_STRATEGY: Z_DEFAULT_STRATEGY$1,
    Z_UNKNOWN,
    Z_DEFLATED: Z_DEFLATED$2
  } = constants$2;

  /*============================================================================*/

  const MAX_MEM_LEVEL = 9;
  /* Maximum value for memLevel in deflateInit2 */
  const MAX_WBITS$1 = 15;
  /* 32K LZ77 window */
  const DEF_MEM_LEVEL = 8;
  const LENGTH_CODES = 29;
  /* number of length codes, not counting the special END_BLOCK code */
  const LITERALS = 256;
  /* number of literal bytes 0..255 */
  const L_CODES = LITERALS + 1 + LENGTH_CODES;
  /* number of Literal or Length codes, including the END_BLOCK code */
  const D_CODES = 30;
  /* number of distance codes */
  const BL_CODES = 19;
  /* number of codes used to transfer the bit lengths */
  const HEAP_SIZE = 2 * L_CODES + 1;
  /* maximum heap size */
  const MAX_BITS = 15;
  /* All codes must not exceed MAX_BITS bits */

  const MIN_MATCH = 3;
  const MAX_MATCH = 258;
  const MIN_LOOKAHEAD = MAX_MATCH + MIN_MATCH + 1;
  const PRESET_DICT = 0x20;
  const INIT_STATE = 42; /* zlib header -> BUSY_STATE */
  //#ifdef GZIP
  const GZIP_STATE = 57; /* gzip header -> BUSY_STATE | EXTRA_STATE */
  //#endif
  const EXTRA_STATE = 69; /* gzip extra block -> NAME_STATE */
  const NAME_STATE = 73; /* gzip file name -> COMMENT_STATE */
  const COMMENT_STATE = 91; /* gzip comment -> HCRC_STATE */
  const HCRC_STATE = 103; /* gzip header CRC -> BUSY_STATE */
  const BUSY_STATE = 113; /* deflate -> FINISH_STATE */
  const FINISH_STATE = 666; /* stream complete */

  const BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  const BS_BLOCK_DONE = 2; /* block flush performed */
  const BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  const BS_FINISH_DONE = 4; /* finish done, accept no more input or output */

  const OS_CODE = 0x03; // Unix :) . Don't detect, use this default.

  const err = (strm, errorCode) => {
    strm.msg = messages[errorCode];
    return errorCode;
  };
  const rank = f => {
    return f * 2 - (f > 4 ? 9 : 0);
  };
  const zero = buf => {
    let len = buf.length;
    while (--len >= 0) {
      buf[len] = 0;
    }
  };

  /* ===========================================================================
   * Slide the hash table when sliding the window down (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.
   */
  const slide_hash = s => {
    let n, m;
    let p;
    let wsize = s.w_size;
    n = s.hash_size;
    p = n;
    do {
      m = s.head[--p];
      s.head[p] = m >= wsize ? m - wsize : 0;
    } while (--n);
    n = wsize;
    //#ifndef FASTEST
    p = n;
    do {
      m = s.prev[--p];
      s.prev[p] = m >= wsize ? m - wsize : 0;
      /* If n is not on any hash chain, prev[n] is garbage but
       * its value will never be used.
       */
    } while (--n);
    //#endif
  };

  /* eslint-disable new-cap */
  let HASH_ZLIB = (s, prev, data) => (prev << s.hash_shift ^ data) & s.hash_mask;
  // This hash causes less collisions, https://github.com/nodeca/pako/issues/135
  // But breaks binary compatibility
  //let HASH_FAST = (s, prev, data) => ((prev << 8) + (prev >> 8) + (data << 4)) & s.hash_mask;
  let HASH = HASH_ZLIB;

  /* =========================================================================
   * Flush as much pending output as possible. All deflate() output, except for
   * some deflate_stored() output, goes through this function so some
   * applications may wish to modify it to avoid allocating a large
   * strm->next_out buffer and copying into it. (See also read_buf()).
   */
  const flush_pending = strm => {
    const s = strm.state;

    //_tr_flush_bits(s);
    let len = s.pending;
    if (len > strm.avail_out) {
      len = strm.avail_out;
    }
    if (len === 0) {
      return;
    }
    strm.output.set(s.pending_buf.subarray(s.pending_out, 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;
    }
  };
  const flush_block_only = (s, last) => {
    _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);
  };
  const 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.
   */
  const 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()).
   */
  const read_buf = (strm, buf, start, size) => {
    let len = strm.avail_in;
    if (len > size) {
      len = size;
    }
    if (len === 0) {
      return 0;
    }
    strm.avail_in -= len;

    // zmemcpy(buf, strm->next_in, len);
    buf.set(strm.input.subarray(strm.next_in, strm.next_in + len), start);
    if (strm.state.wrap === 1) {
      strm.adler = adler32_1(strm.adler, buf, len, start);
    } else if (strm.state.wrap === 2) {
      strm.adler = crc32_1(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.
   */
  const longest_match = (s, cur_match) => {
    let chain_length = s.max_chain_length; /* max hash chain length */
    let scan = s.strstart; /* current string */
    let match; /* matched string */
    let len; /* length of current match */
    let best_len = s.prev_length; /* best match length so far */
    let nice_match = s.nice_match; /* stop if match long enough */
    const limit = s.strstart > s.w_size - MIN_LOOKAHEAD ? s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0 /*NIL*/;
    const _win = s.window; // shortcut

    const wmask = s.w_mask;
    const prev = s.prev;

    /* Stop when cur_match becomes <= limit. To simplify the code,
     * we prevent matches with the string of window index 0.
     */

    const strend = s.strstart + MAX_MATCH;
    let scan_end1 = _win[scan + best_len - 1];
    let 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).
   */
  const fill_window = s => {
    const _w_size = s.w_size;
    let n, 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)) {
        s.window.set(s.window.subarray(_w_size, _w_size + _w_size - more), 0);
        s.match_start -= _w_size;
        s.strstart -= _w_size;
        /* we now have strstart >= MAX_DIST */
        s.block_start -= _w_size;
        if (s.insert > s.strstart) {
          s.insert = s.strstart;
        }
        slide_hash(s);
        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 = HASH(s, s.ins_h, s.window[str + 1]);
        //#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 = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]);
          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) {
    //    const curr = s.strstart + s.lookahead;
    //    let 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.
   *
   * In case deflateParams() is used to later switch to a non-zero compression
   * level, s->matches (otherwise unused when storing) keeps track of the number
   * of hash table slides to perform. If s->matches is 1, then one hash table
   * slide will be done when switching. If s->matches is 2, the maximum value
   * allowed here, then the hash table will be cleared, since two or more slides
   * is the same as a clear.
   *
   * deflate_stored() is written to minimize the number of times an input byte is
   * copied. It is most efficient with large input and output buffers, which
   * maximizes the opportunites to have a single copy from next_in to next_out.
   */
  const deflate_stored = (s, flush) => {
    /* Smallest worthy block size when not flushing or finishing. By default
     * this is 32K. This can be as small as 507 bytes for memLevel == 1. For
     * large input and output buffers, the stored block size will be larger.
     */
    let min_block = s.pending_buf_size - 5 > s.w_size ? s.w_size : s.pending_buf_size - 5;

    /* Copy as many min_block or larger stored blocks directly to next_out as
     * possible. If flushing, copy the remaining available input to next_out as
     * stored blocks, if there is enough space.
     */
    let len,
      left,
      have,
      last = 0;
    let used = s.strm.avail_in;
    do {
      /* Set len to the maximum size block that we can copy directly with the
       * available input data and output space. Set left to how much of that
       * would be copied from what's left in the window.
       */
      len = 65535 /* MAX_STORED */; /* maximum deflate stored block length */
      have = s.bi_valid + 42 >> 3; /* number of header bytes */
      if (s.strm.avail_out < have) {
        /* need room for header */
        break;
      }
      /* maximum stored block length that will fit in avail_out: */
      have = s.strm.avail_out - have;
      left = s.strstart - s.block_start; /* bytes left in window */
      if (len > left + s.strm.avail_in) {
        len = left + s.strm.avail_in; /* limit len to the input */
      }
      if (len > have) {
        len = have; /* limit len to the output */
      }

      /* If the stored block would be less than min_block in length, or if
       * unable to copy all of the available input when flushing, then try
       * copying to the window and the pending buffer instead. Also don't
       * write an empty block when flushing -- deflate() does that.
       */
      if (len < min_block && (len === 0 && flush !== Z_FINISH$3 || flush === Z_NO_FLUSH$2 || len !== left + s.strm.avail_in)) {
        break;
      }

      /* Make a dummy stored block in pending to get the header bytes,
       * including any pending bits. This also updates the debugging counts.
       */
      last = flush === Z_FINISH$3 && len === left + s.strm.avail_in ? 1 : 0;
      _tr_stored_block(s, 0, 0, last);

      /* Replace the lengths in the dummy stored block with len. */
      s.pending_buf[s.pending - 4] = len;
      s.pending_buf[s.pending - 3] = len >> 8;
      s.pending_buf[s.pending - 2] = ~len;
      s.pending_buf[s.pending - 1] = ~len >> 8;

      /* Write the stored block header bytes. */
      flush_pending(s.strm);

      //#ifdef ZLIB_DEBUG
      //    /* Update debugging counts for the data about to be copied. */
      //    s->compressed_len += len << 3;
      //    s->bits_sent += len << 3;
      //#endif

      /* Copy uncompressed bytes from the window to next_out. */
      if (left) {
        if (left > len) {
          left = len;
        }
        //zmemcpy(s->strm->next_out, s->window + s->block_start, left);
        s.strm.output.set(s.window.subarray(s.block_start, s.block_start + left), s.strm.next_out);
        s.strm.next_out += left;
        s.strm.avail_out -= left;
        s.strm.total_out += left;
        s.block_start += left;
        len -= left;
      }

      /* Copy uncompressed bytes directly from next_in to next_out, updating
       * the check value.
       */
      if (len) {
        read_buf(s.strm, s.strm.output, s.strm.next_out, len);
        s.strm.next_out += len;
        s.strm.avail_out -= len;
        s.strm.total_out += len;
      }
    } while (last === 0);

    /* Update the sliding window with the last s->w_size bytes of the copied
     * data, or append all of the copied data to the existing window if less
     * than s->w_size bytes were copied. Also update the number of bytes to
     * insert in the hash tables, in the event that deflateParams() switches to
     * a non-zero compression level.
     */
    used -= s.strm.avail_in; /* number of input bytes directly copied */
    if (used) {
      /* If any input was used, then no unused input remains in the window,
       * therefore s->block_start == s->strstart.
       */
      if (used >= s.w_size) {
        /* supplant the previous history */
        s.matches = 2; /* clear hash */
        //zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size);
        s.window.set(s.strm.input.subarray(s.strm.next_in - s.w_size, s.strm.next_in), 0);
        s.strstart = s.w_size;
        s.insert = s.strstart;
      } else {
        if (s.window_size - s.strstart <= used) {
          /* Slide the window down. */
          s.strstart -= s.w_size;
          //zmemcpy(s->window, s->window + s->w_size, s->strstart);
          s.window.set(s.window.subarray(s.w_size, s.w_size + s.strstart), 0);
          if (s.matches < 2) {
            s.matches++; /* add a pending slide_hash() */
          }
          if (s.insert > s.strstart) {
            s.insert = s.strstart;
          }
        }
        //zmemcpy(s->window + s->strstart, s->strm->next_in - used, used);
        s.window.set(s.strm.input.subarray(s.strm.next_in - used, s.strm.next_in), s.strstart);
        s.strstart += used;
        s.insert += used > s.w_size - s.insert ? s.w_size - s.insert : used;
      }
      s.block_start = s.strstart;
    }
    if (s.high_water < s.strstart) {
      s.high_water = s.strstart;
    }

    /* If the last block was written to next_out, then done. */
    if (last) {
      return BS_FINISH_DONE;
    }

    /* If flushing and all input has been consumed, then done. */
    if (flush !== Z_NO_FLUSH$2 && flush !== Z_FINISH$3 && s.strm.avail_in === 0 && s.strstart === s.block_start) {
      return BS_BLOCK_DONE;
    }

    /* Fill the window with any remaining input. */
    have = s.window_size - s.strstart;
    if (s.strm.avail_in > have && s.block_start >= s.w_size) {
      /* Slide the window down. */
      s.block_start -= s.w_size;
      s.strstart -= s.w_size;
      //zmemcpy(s->window, s->window + s->w_size, s->strstart);
      s.window.set(s.window.subarray(s.w_size, s.w_size + s.strstart), 0);
      if (s.matches < 2) {
        s.matches++; /* add a pending slide_hash() */
      }
      have += s.w_size; /* more space now */
      if (s.insert > s.strstart) {
        s.insert = s.strstart;
      }
    }
    if (have > s.strm.avail_in) {
      have = s.strm.avail_in;
    }
    if (have) {
      read_buf(s.strm, s.window, s.strstart, have);
      s.strstart += have;
      s.insert += have > s.w_size - s.insert ? s.w_size - s.insert : have;
    }
    if (s.high_water < s.strstart) {
      s.high_water = s.strstart;
    }

    /* There was not enough avail_out to write a complete worthy or flushed
     * stored block to next_out. Write a stored block to pending instead, if we
     * have enough input for a worthy block, or if flushing and there is enough
     * room for the remaining input as a stored block in the pending buffer.
     */
    have = s.bi_valid + 42 >> 3; /* number of header bytes */
    /* maximum stored block length that will fit in pending: */
    have = s.pending_buf_size - have > 65535 /* MAX_STORED */ ? 65535 /* MAX_STORED */ : s.pending_buf_size - have;
    min_block = have > s.w_size ? s.w_size : have;
    left = s.strstart - s.block_start;
    if (left >= min_block || (left || flush === Z_FINISH$3) && flush !== Z_NO_FLUSH$2 && s.strm.avail_in === 0 && left <= have) {
      len = left > have ? have : left;
      last = flush === Z_FINISH$3 && s.strm.avail_in === 0 && len === left ? 1 : 0;
      _tr_stored_block(s, s.block_start, len, last);
      s.block_start += len;
      flush_pending(s.strm);
    }

    /* We've done all we can with the available input and output. */
    return last ? BS_FINISH_STARTED : 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.
   */
  const deflate_fast = (s, flush) => {
    let hash_head; /* head of the hash chain */
    let 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$2) {
          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 = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);
        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 = _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 = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);
            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 = HASH(s, s.ins_h, s.window[s.strstart + 1]);

          //#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 = _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$3) {
      /*** 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.sym_next) {
      /*** 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.
   */
  const deflate_slow = (s, flush) => {
    let hash_head; /* head of hash chain */
    let bflush; /* set if current block must be flushed */

    let 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$2) {
          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 = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);
        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 = _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 = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);
            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 = _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 = _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$3) {
      /*** 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.sym_next) {
      /*** 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.)
   */
  const deflate_rle = (s, flush) => {
    let bflush; /* set if current block must be flushed */
    let prev; /* byte at distance one to match */
    let scan, strend; /* scan goes up to strend for length of run */

    const _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$2) {
          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 = _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 = _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$3) {
      /*** 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.sym_next) {
      /*** 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.)
   */
  const deflate_huff = (s, flush) => {
    let 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$2) {
            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 = _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$3) {
      /*** 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.sym_next) {
      /*** 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;
  }
  const 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
   */
  const 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$2; /* 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 Uint16Array(HEAP_SIZE * 2);
    this.dyn_dtree = new Uint16Array((2 * D_CODES + 1) * 2);
    this.bl_tree = new Uint16Array((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 Uint16Array(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 Uint16Array(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 Uint16Array(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.sym_buf = 0; /* buffer for distances and literals/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.sym_next = 0; /* running index in sym_buf */
    this.sym_end = 0; /* symbol table full when sym_next reaches this */

    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.
     */
  }

  /* =========================================================================
   * Check for a valid deflate stream state. Return 0 if ok, 1 if not.
   */
  const deflateStateCheck = strm => {
    if (!strm) {
      return 1;
    }
    const s = strm.state;
    if (!s || s.strm !== strm || s.status !== INIT_STATE &&
    //#ifdef GZIP
    s.status !== GZIP_STATE &&
    //#endif
    s.status !== EXTRA_STATE && s.status !== NAME_STATE && s.status !== COMMENT_STATE && s.status !== HCRC_STATE && s.status !== BUSY_STATE && s.status !== FINISH_STATE) {
      return 1;
    }
    return 0;
  };
  const deflateResetKeep = strm => {
    if (deflateStateCheck(strm)) {
      return err(strm, Z_STREAM_ERROR$2);
    }
    strm.total_in = strm.total_out = 0;
    strm.data_type = Z_UNKNOWN;
    const 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 =
    //#ifdef GZIP
    s.wrap === 2 ? GZIP_STATE :
    //#endif
    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 = -2;
    _tr_init(s);
    return Z_OK$3;
  };
  const deflateReset = strm => {
    const ret = deflateResetKeep(strm);
    if (ret === Z_OK$3) {
      lm_init(strm.state);
    }
    return ret;
  };
  const deflateSetHeader = (strm, head) => {
    if (deflateStateCheck(strm) || strm.state.wrap !== 2) {
      return Z_STREAM_ERROR$2;
    }
    strm.state.gzhead = head;
    return Z_OK$3;
  };
  const deflateInit2 = (strm, level, method, windowBits, memLevel, strategy) => {
    if (!strm) {
      // === Z_NULL
      return Z_STREAM_ERROR$2;
    }
    let wrap = 1;
    if (level === Z_DEFAULT_COMPRESSION$1) {
      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$2 || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED || windowBits === 8 && wrap !== 1) {
      return err(strm, Z_STREAM_ERROR$2);
    }
    if (windowBits === 8) {
      windowBits = 9;
    }
    /* until 256-byte window bug fixed */

    const s = new DeflateState();
    strm.state = s;
    s.strm = strm;
    s.status = INIT_STATE; /* to pass state test in deflateReset() */

    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 Uint8Array(s.w_size * 2);
    s.head = new Uint16Array(s.hash_size);
    s.prev = new Uint16Array(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 */

    /* We overlay pending_buf and sym_buf. This works since the average size
     * for length/distance pairs over any compressed block is assured to be 31
     * bits or less.
     *
     * Analysis: The longest fixed codes are a length code of 8 bits plus 5
     * extra bits, for lengths 131 to 257. The longest fixed distance codes are
     * 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest
     * possible fixed-codes length/distance pair is then 31 bits total.
     *
     * sym_buf starts one-fourth of the way into pending_buf. So there are
     * three bytes in sym_buf for every four bytes in pending_buf. Each symbol
     * in sym_buf is three bytes -- two for the distance and one for the
     * literal/length. As each symbol is consumed, the pointer to the next
     * sym_buf value to read moves forward three bytes. From that symbol, up to
     * 31 bits are written to pending_buf. The closest the written pending_buf
     * bits gets to the next sym_buf symbol to read is just before the last
     * code is written. At that time, 31*(n-2) bits have been written, just
     * after 24*(n-2) bits have been consumed from sym_buf. sym_buf starts at
     * 8*n bits into pending_buf. (Note that the symbol buffer fills when n-1
     * symbols are written.) The closest the writing gets to what is unread is
     * then n+14 bits. Here n is lit_bufsize, which is 16384 by default, and
     * can range from 128 to 32768.
     *
     * Therefore, at a minimum, there are 142 bits of space between what is
     * written and what is read in the overlain buffers, so the symbols cannot
     * be overwritten by the compressed data. That space is actually 139 bits,
     * due to the three-bit fixed-code block header.
     *
     * That covers the case where either Z_FIXED is specified, forcing fixed
     * codes, or when the use of fixed codes is chosen, because that choice
     * results in a smaller compressed block than dynamic codes. That latter
     * condition then assures that the above analysis also covers all dynamic
     * blocks. A dynamic-code block will only be chosen to be emitted if it has
     * fewer bits than a fixed-code block would for the same set of symbols.
     * Therefore its average symbol length is assured to be less than 31. So
     * the compressed data for a dynamic block also cannot overwrite the
     * symbols from which it is being constructed.
     */

    s.pending_buf_size = s.lit_bufsize * 4;
    s.pending_buf = new Uint8Array(s.pending_buf_size);

    // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
    //s->sym_buf = s->pending_buf + s->lit_bufsize;
    s.sym_buf = s.lit_bufsize;

    //s->sym_end = (s->lit_bufsize - 1) * 3;
    s.sym_end = (s.lit_bufsize - 1) * 3;
    /* We avoid equality with lit_bufsize*3 because of wraparound at 64K
     * on 16 bit machines and because stored blocks are restricted to
     * 64K-1 bytes.
     */

    s.level = level;
    s.strategy = strategy;
    s.method = method;
    return deflateReset(strm);
  };
  const deflateInit = (strm, level) => {
    return deflateInit2(strm, level, Z_DEFLATED$2, MAX_WBITS$1, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY$1);
  };

  /* ========================================================================= */
  const deflate$2 = (strm, flush) => {
    if (deflateStateCheck(strm) || flush > Z_BLOCK$1 || flush < 0) {
      return strm ? err(strm, Z_STREAM_ERROR$2) : Z_STREAM_ERROR$2;
    }
    const s = strm.state;
    if (!strm.output || strm.avail_in !== 0 && !strm.input || s.status === FINISH_STATE && flush !== Z_FINISH$3) {
      return err(strm, strm.avail_out === 0 ? Z_BUF_ERROR$1 : Z_STREAM_ERROR$2);
    }
    const old_flush = s.last_flush;
    s.last_flush = flush;

    /* 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$3;
      }

      /* 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$3) {
      return err(strm, Z_BUF_ERROR$1);
    }

    /* 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$1);
    }

    /* Write the header */
    if (s.status === INIT_STATE && s.wrap === 0) {
      s.status = BUSY_STATE;
    }
    if (s.status === INIT_STATE) {
      /* zlib header */
      let header = Z_DEFLATED$2 + (s.w_bits - 8 << 4) << 8;
      let 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;
      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);
      s.status = BUSY_STATE;

      /* Compression must start with an empty pending buffer */
      flush_pending(strm);
      if (s.pending !== 0) {
        s.last_flush = -1;
        return Z_OK$3;
      }
    }
    //#ifdef GZIP
    if (s.status === GZIP_STATE) {
      /* 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;

        /* Compression must start with an empty pending buffer */
        flush_pending(strm);
        if (s.pending !== 0) {
          s.last_flush = -1;
          return Z_OK$3;
        }
      } 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_1(strm.adler, s.pending_buf, s.pending, 0);
        }
        s.gzindex = 0;
        s.status = EXTRA_STATE;
      }
    }
    if (s.status === EXTRA_STATE) {
      if (s.gzhead.extra /* != Z_NULL*/) {
        let beg = s.pending; /* start of bytes to update crc */
        let left = (s.gzhead.extra.length & 0xffff) - s.gzindex;
        while (s.pending + left > s.pending_buf_size) {
          let copy = s.pending_buf_size - s.pending;
          // zmemcpy(s.pending_buf + s.pending,
          //    s.gzhead.extra + s.gzindex, copy);
          s.pending_buf.set(s.gzhead.extra.subarray(s.gzindex, s.gzindex + copy), s.pending);
          s.pending = s.pending_buf_size;
          //--- HCRC_UPDATE(beg) ---//
          if (s.gzhead.hcrc && s.pending > beg) {
            strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
          }
          //---//
          s.gzindex += copy;
          flush_pending(strm);
          if (s.pending !== 0) {
            s.last_flush = -1;
            return Z_OK$3;
          }
          beg = 0;
          left -= copy;
        }
        // JS specific: s.gzhead.extra may be TypedArray or Array for backward compatibility
        //              TypedArray.slice and TypedArray.from don't exist in IE10-IE11
        let gzhead_extra = new Uint8Array(s.gzhead.extra);
        // zmemcpy(s->pending_buf + s->pending,
        //     s->gzhead->extra + s->gzindex, left);
        s.pending_buf.set(gzhead_extra.subarray(s.gzindex, s.gzindex + left), s.pending);
        s.pending += left;
        //--- HCRC_UPDATE(beg) ---//
        if (s.gzhead.hcrc && s.pending > beg) {
          strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
        }
        //---//
        s.gzindex = 0;
      }
      s.status = NAME_STATE;
    }
    if (s.status === NAME_STATE) {
      if (s.gzhead.name /* != Z_NULL*/) {
        let beg = s.pending; /* start of bytes to update crc */
        let val;
        do {
          if (s.pending === s.pending_buf_size) {
            //--- HCRC_UPDATE(beg) ---//
            if (s.gzhead.hcrc && s.pending > beg) {
              strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
            }
            //---//
            flush_pending(strm);
            if (s.pending !== 0) {
              s.last_flush = -1;
              return Z_OK$3;
            }
            beg = 0;
          }
          // 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);
        //--- HCRC_UPDATE(beg) ---//
        if (s.gzhead.hcrc && s.pending > beg) {
          strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
        }
        //---//
        s.gzindex = 0;
      }
      s.status = COMMENT_STATE;
    }
    if (s.status === COMMENT_STATE) {
      if (s.gzhead.comment /* != Z_NULL*/) {
        let beg = s.pending; /* start of bytes to update crc */
        let val;
        do {
          if (s.pending === s.pending_buf_size) {
            //--- HCRC_UPDATE(beg) ---//
            if (s.gzhead.hcrc && s.pending > beg) {
              strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
            }
            //---//
            flush_pending(strm);
            if (s.pending !== 0) {
              s.last_flush = -1;
              return Z_OK$3;
            }
            beg = 0;
          }
          // 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);
        //--- HCRC_UPDATE(beg) ---//
        if (s.gzhead.hcrc && s.pending > beg) {
          strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
        }
        //---//
      }
      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 !== 0) {
            s.last_flush = -1;
            return Z_OK$3;
          }
        }
        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;

      /* Compression must start with an empty pending buffer */
      flush_pending(strm);
      if (s.pending !== 0) {
        s.last_flush = -1;
        return Z_OK$3;
      }
    }
    //#endif

    /* Start a new block or continue the current one.
     */
    if (strm.avail_in !== 0 || s.lookahead !== 0 || flush !== Z_NO_FLUSH$2 && s.status !== FINISH_STATE) {
      let bstate = s.level === 0 ? deflate_stored(s, flush) : 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$3;
        /* 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) {
          _tr_align(s);
        } else if (flush !== Z_BLOCK$1) {
          /* FULL_FLUSH or SYNC_FLUSH */

          _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$1) {
            /*** 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$3;
        }
      }
    }
    if (flush !== Z_FINISH$3) {
      return Z_OK$3;
    }
    if (s.wrap <= 0) {
      return Z_STREAM_END$3;
    }

    /* 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$3 : Z_STREAM_END$3;
  };
  const deflateEnd = strm => {
    if (deflateStateCheck(strm)) {
      return Z_STREAM_ERROR$2;
    }
    const status = strm.state.status;
    strm.state = null;
    return status === BUSY_STATE ? err(strm, Z_DATA_ERROR$2) : Z_OK$3;
  };

  /* =========================================================================
   * Initializes the compression dictionary from the given byte
   * sequence without producing any compressed output.
   */
  const deflateSetDictionary = (strm, dictionary) => {
    let dictLength = dictionary.length;
    if (deflateStateCheck(strm)) {
      return Z_STREAM_ERROR$2;
    }
    const s = strm.state;
    const wrap = s.wrap;
    if (wrap === 2 || wrap === 1 && s.status !== INIT_STATE || s.lookahead) {
      return Z_STREAM_ERROR$2;
    }

    /* when using zlib wrappers, compute Adler-32 for provided dictionary */
    if (wrap === 1) {
      /* adler32(strm->adler, dictionary, dictLength); */
      strm.adler = adler32_1(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);
      let tmpDict = new Uint8Array(s.w_size);
      tmpDict.set(dictionary.subarray(dictLength - s.w_size, dictLength), 0);
      dictionary = tmpDict;
      dictLength = s.w_size;
    }
    /* insert dictionary into window and hash */
    const avail = strm.avail_in;
    const next = strm.next_in;
    const input = strm.input;
    strm.avail_in = dictLength;
    strm.next_in = 0;
    strm.input = dictionary;
    fill_window(s);
    while (s.lookahead >= MIN_MATCH) {
      let str = s.strstart;
      let n = s.lookahead - (MIN_MATCH - 1);
      do {
        /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
        s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]);
        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$3;
  };
  var deflateInit_1 = deflateInit;
  var deflateInit2_1 = deflateInit2;
  var deflateReset_1 = deflateReset;
  var deflateResetKeep_1 = deflateResetKeep;
  var deflateSetHeader_1 = deflateSetHeader;
  var deflate_2$1 = deflate$2;
  var deflateEnd_1 = deflateEnd;
  var deflateSetDictionary_1 = deflateSetDictionary;
  var deflateInfo = 'pako deflate (from Nodeca project)';

  /* Not implemented
  module.exports.deflateBound = deflateBound;
  module.exports.deflateCopy = deflateCopy;
  module.exports.deflateGetDictionary = deflateGetDictionary;
  module.exports.deflateParams = deflateParams;
  module.exports.deflatePending = deflatePending;
  module.exports.deflatePrime = deflatePrime;
  module.exports.deflateTune = deflateTune;
  */

  var deflate_1$2 = {
    deflateInit: deflateInit_1,
    deflateInit2: deflateInit2_1,
    deflateReset: deflateReset_1,
    deflateResetKeep: deflateResetKeep_1,
    deflateSetHeader: deflateSetHeader_1,
    deflate: deflate_2$1,
    deflateEnd: deflateEnd_1,
    deflateSetDictionary: deflateSetDictionary_1,
    deflateInfo: deflateInfo
  };
  const _has = (obj, key) => {
    return Object.prototype.hasOwnProperty.call(obj, key);
  };
  var assign = function (obj /*from1, from2, from3, ...*/) {
    const sources = Array.prototype.slice.call(arguments, 1);
    while (sources.length) {
      const source = sources.shift();
      if (!source) {
        continue;
      }
      if (typeof source !== 'object') {
        throw new TypeError(source + 'must be non-object');
      }
      for (const p in source) {
        if (_has(source, p)) {
          obj[p] = source[p];
        }
      }
    }
    return obj;
  };

  // Join array of chunks to single array.
  var flattenChunks = chunks => {
    // calculate data length
    let len = 0;
    for (let i = 0, l = chunks.length; i < l; i++) {
      len += chunks[i].length;
    }

    // join chunks
    const result = new Uint8Array(len);
    for (let i = 0, pos = 0, l = chunks.length; i < l; i++) {
      let chunk = chunks[i];
      result.set(chunk, pos);
      pos += chunk.length;
    }
    return result;
  };
  var common = {
    assign: assign,
    flattenChunks: flattenChunks
  };

  // String encode/decode helpers

  // Quick check if we can use fast array to bin string conversion
  //
  // - apply(Array) can fail on Android 2.2
  // - apply(Uint8Array) can fail on iOS 5.1 Safari
  //
  let STR_APPLY_UIA_OK = true;
  try {
    String.fromCharCode.apply(null, new Uint8Array(1));
  } catch (__) {
    STR_APPLY_UIA_OK = false;
  }

  // Table with utf8 lengths (calculated by first byte of sequence)
  // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  // because max possible codepoint is 0x10ffff
  const _utf8len = new Uint8Array(256);
  for (let q = 0; q < 256; q++) {
    _utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1;
  }
  _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start

  // convert string to array (typed, when possible)
  var string2buf = str => {
    if (typeof TextEncoder === 'function' && TextEncoder.prototype.encode) {
      return new TextEncoder().encode(str);
    }
    let buf,
      c,
      c2,
      m_pos,
      i,
      str_len = str.length,
      buf_len = 0;

    // count binary size
    for (m_pos = 0; m_pos < str_len; m_pos++) {
      c = str.charCodeAt(m_pos);
      if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) {
        c2 = str.charCodeAt(m_pos + 1);
        if ((c2 & 0xfc00) === 0xdc00) {
          c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00);
          m_pos++;
        }
      }
      buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
    }

    // allocate buffer
    buf = new Uint8Array(buf_len);

    // convert
    for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
      c = str.charCodeAt(m_pos);
      if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) {
        c2 = str.charCodeAt(m_pos + 1);
        if ((c2 & 0xfc00) === 0xdc00) {
          c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00);
          m_pos++;
        }
      }
      if (c < 0x80) {
        /* one byte */
        buf[i++] = c;
      } else if (c < 0x800) {
        /* two bytes */
        buf[i++] = 0xC0 | c >>> 6;
        buf[i++] = 0x80 | c & 0x3f;
      } else if (c < 0x10000) {
        /* three bytes */
        buf[i++] = 0xE0 | c >>> 12;
        buf[i++] = 0x80 | c >>> 6 & 0x3f;
        buf[i++] = 0x80 | c & 0x3f;
      } else {
        /* four bytes */
        buf[i++] = 0xf0 | c >>> 18;
        buf[i++] = 0x80 | c >>> 12 & 0x3f;
        buf[i++] = 0x80 | c >>> 6 & 0x3f;
        buf[i++] = 0x80 | c & 0x3f;
      }
    }
    return buf;
  };

  // Helper
  const buf2binstring = (buf, len) => {
    // On Chrome, the arguments in a function call that are allowed is `65534`.
    // If the length of the buffer is smaller than that, we can use this optimization,
    // otherwise we will take a slower path.
    if (len < 65534) {
      if (buf.subarray && STR_APPLY_UIA_OK) {
        return String.fromCharCode.apply(null, buf.length === len ? buf : buf.subarray(0, len));
      }
    }
    let result = '';
    for (let i = 0; i < len; i++) {
      result += String.fromCharCode(buf[i]);
    }
    return result;
  };

  // convert array to string
  var buf2string = (buf, max) => {
    const len = max || buf.length;
    if (typeof TextDecoder === 'function' && TextDecoder.prototype.decode) {
      return new TextDecoder().decode(buf.subarray(0, max));
    }
    let i, out;

    // Reserve max possible length (2 words per char)
    // NB: by unknown reasons, Array is significantly faster for
    //     String.fromCharCode.apply than Uint16Array.
    const utf16buf = new Array(len * 2);
    for (out = 0, i = 0; i < len;) {
      let c = buf[i++];
      // quick process ascii
      if (c < 0x80) {
        utf16buf[out++] = c;
        continue;
      }
      let c_len = _utf8len[c];
      // skip 5 & 6 byte codes
      if (c_len > 4) {
        utf16buf[out++] = 0xfffd;
        i += c_len - 1;
        continue;
      }

      // apply mask on first byte
      c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
      // join the rest
      while (c_len > 1 && i < len) {
        c = c << 6 | buf[i++] & 0x3f;
        c_len--;
      }

      // terminated by end of string?
      if (c_len > 1) {
        utf16buf[out++] = 0xfffd;
        continue;
      }
      if (c < 0x10000) {
        utf16buf[out++] = c;
      } else {
        c -= 0x10000;
        utf16buf[out++] = 0xd800 | c >> 10 & 0x3ff;
        utf16buf[out++] = 0xdc00 | c & 0x3ff;
      }
    }
    return buf2binstring(utf16buf, out);
  };

  // Calculate max possible position in utf8 buffer,
  // that will not break sequence. If that's not possible
  // - (very small limits) return max size as is.
  //
  // buf[] - utf8 bytes array
  // max   - length limit (mandatory);
  var utf8border = (buf, max) => {
    max = max || buf.length;
    if (max > buf.length) {
      max = buf.length;
    }

    // go back from last position, until start of sequence found
    let pos = max - 1;
    while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) {
      pos--;
    }

    // Very small and broken sequence,
    // return max, because we should return something anyway.
    if (pos < 0) {
      return max;
    }

    // If we came to start of buffer - that means buffer is too small,
    // return max too.
    if (pos === 0) {
      return max;
    }
    return pos + _utf8len[buf[pos]] > max ? pos : max;
  };
  var strings = {
    string2buf: string2buf,
    buf2string: buf2string,
    utf8border: utf8border
  };

  // (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;
  }
  var zstream = ZStream;
  const toString$1$1 = Object.prototype.toString;

  /* Public constants ==========================================================*/
  /* ===========================================================================*/

  const {
    Z_NO_FLUSH: Z_NO_FLUSH$1,
    Z_SYNC_FLUSH,
    Z_FULL_FLUSH,
    Z_FINISH: Z_FINISH$2,
    Z_OK: Z_OK$2,
    Z_STREAM_END: Z_STREAM_END$2,
    Z_DEFAULT_COMPRESSION,
    Z_DEFAULT_STRATEGY,
    Z_DEFLATED: Z_DEFLATED$1
  } = constants$2;

  /* ===========================================================================*/

  /**
   * class Deflate
   *
   * Generic JS-style wrapper for zlib calls. If you don't need
   * streaming behaviour - use more simple functions: [[deflate]],
   * [[deflateRaw]] and [[gzip]].
   **/

  /* internal
   * Deflate.chunks -> Array
   *
   * Chunks of output data, if [[Deflate#onData]] not overridden.
   **/

  /**
   * Deflate.result -> Uint8Array
   *
   * Compressed result, generated by default [[Deflate#onData]]
   * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
   * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
   **/

  /**
   * Deflate.err -> Number
   *
   * Error code after deflate finished. 0 (Z_OK) on success.
   * You will not need it in real life, because deflate errors
   * are possible only on wrong options or bad `onData` / `onEnd`
   * custom handlers.
   **/

  /**
   * Deflate.msg -> String
   *
   * Error message, if [[Deflate.err]] != 0
   **/

  /**
   * new Deflate(options)
   * - options (Object): zlib deflate options.
   *
   * Creates new deflator instance with specified params. Throws exception
   * on bad params. Supported options:
   *
   * - `level`
   * - `windowBits`
   * - `memLevel`
   * - `strategy`
   * - `dictionary`
   *
   * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
   * for more information on these.
   *
   * Additional options, for internal needs:
   *
   * - `chunkSize` - size of generated data chunks (16K by default)
   * - `raw` (Boolean) - do raw deflate
   * - `gzip` (Boolean) - create gzip wrapper
   * - `header` (Object) - custom header for gzip
   *   - `text` (Boolean) - true if compressed data believed to be text
   *   - `time` (Number) - modification time, unix timestamp
   *   - `os` (Number) - operation system code
   *   - `extra` (Array) - array of bytes with extra data (max 65536)
   *   - `name` (String) - file name (binary string)
   *   - `comment` (String) - comment (binary string)
   *   - `hcrc` (Boolean) - true if header crc should be added
   *
   * ##### Example:
   *
   * ```javascript
   * const pako = require('pako')
   *   , chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])
   *   , chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);
   *
   * const deflate = new pako.Deflate({ level: 3});
   *
   * deflate.push(chunk1, false);
   * deflate.push(chunk2, true);  // true -> last chunk
   *
   * if (deflate.err) { throw new Error(deflate.err); }
   *
   * console.log(deflate.result);
   * ```
   **/
  function Deflate$1(options) {
    this.options = common.assign({
      level: Z_DEFAULT_COMPRESSION,
      method: Z_DEFLATED$1,
      chunkSize: 16384,
      windowBits: 15,
      memLevel: 8,
      strategy: Z_DEFAULT_STRATEGY
    }, options || {});
    let opt = this.options;
    if (opt.raw && opt.windowBits > 0) {
      opt.windowBits = -opt.windowBits;
    } else if (opt.gzip && opt.windowBits > 0 && opt.windowBits < 16) {
      opt.windowBits += 16;
    }
    this.err = 0; // error code, if happens (0 = Z_OK)
    this.msg = ''; // error message
    this.ended = false; // used to avoid multiple onEnd() calls
    this.chunks = []; // chunks of compressed data

    this.strm = new zstream();
    this.strm.avail_out = 0;
    let status = deflate_1$2.deflateInit2(this.strm, opt.level, opt.method, opt.windowBits, opt.memLevel, opt.strategy);
    if (status !== Z_OK$2) {
      throw new Error(messages[status]);
    }
    if (opt.header) {
      deflate_1$2.deflateSetHeader(this.strm, opt.header);
    }
    if (opt.dictionary) {
      let dict;
      // Convert data if needed
      if (typeof opt.dictionary === 'string') {
        // If we need to compress text, change encoding to utf8.
        dict = strings.string2buf(opt.dictionary);
      } else if (toString$1$1.call(opt.dictionary) === '[object ArrayBuffer]') {
        dict = new Uint8Array(opt.dictionary);
      } else {
        dict = opt.dictionary;
      }
      status = deflate_1$2.deflateSetDictionary(this.strm, dict);
      if (status !== Z_OK$2) {
        throw new Error(messages[status]);
      }
      this._dict_set = true;
    }
  }

  /**
   * Deflate#push(data[, flush_mode]) -> Boolean
   * - data (Uint8Array|ArrayBuffer|String): input data. Strings will be
   *   converted to utf8 byte sequence.
   * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
   *   See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
   *
   * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
   * new compressed chunks. Returns `true` on success. The last data block must
   * have `flush_mode` Z_FINISH (or `true`). That will flush internal pending
   * buffers and call [[Deflate#onEnd]].
   *
   * On fail call [[Deflate#onEnd]] with error code and return false.
   *
   * ##### Example
   *
   * ```javascript
   * push(chunk, false); // push one of data chunks
   * ...
   * push(chunk, true);  // push last chunk
   * ```
   **/
  Deflate$1.prototype.push = function (data, flush_mode) {
    const strm = this.strm;
    const chunkSize = this.options.chunkSize;
    let status, _flush_mode;
    if (this.ended) {
      return false;
    }
    if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;else _flush_mode = flush_mode === true ? Z_FINISH$2 : Z_NO_FLUSH$1;

    // Convert data if needed
    if (typeof data === 'string') {
      // If we need to compress text, change encoding to utf8.
      strm.input = strings.string2buf(data);
    } else if (toString$1$1.call(data) === '[object ArrayBuffer]') {
      strm.input = new Uint8Array(data);
    } else {
      strm.input = data;
    }
    strm.next_in = 0;
    strm.avail_in = strm.input.length;
    for (;;) {
      if (strm.avail_out === 0) {
        strm.output = new Uint8Array(chunkSize);
        strm.next_out = 0;
        strm.avail_out = chunkSize;
      }

      // Make sure avail_out > 6 to avoid repeating markers
      if ((_flush_mode === Z_SYNC_FLUSH || _flush_mode === Z_FULL_FLUSH) && strm.avail_out <= 6) {
        this.onData(strm.output.subarray(0, strm.next_out));
        strm.avail_out = 0;
        continue;
      }
      status = deflate_1$2.deflate(strm, _flush_mode);

      // Ended => flush and finish
      if (status === Z_STREAM_END$2) {
        if (strm.next_out > 0) {
          this.onData(strm.output.subarray(0, strm.next_out));
        }
        status = deflate_1$2.deflateEnd(this.strm);
        this.onEnd(status);
        this.ended = true;
        return status === Z_OK$2;
      }

      // Flush if out buffer full
      if (strm.avail_out === 0) {
        this.onData(strm.output);
        continue;
      }

      // Flush if requested and has data
      if (_flush_mode > 0 && strm.next_out > 0) {
        this.onData(strm.output.subarray(0, strm.next_out));
        strm.avail_out = 0;
        continue;
      }
      if (strm.avail_in === 0) break;
    }
    return true;
  };

  /**
   * Deflate#onData(chunk) -> Void
   * - chunk (Uint8Array): output data.
   *
   * By default, stores data blocks in `chunks[]` property and glue
   * those in `onEnd`. Override this handler, if you need another behaviour.
   **/
  Deflate$1.prototype.onData = function (chunk) {
    this.chunks.push(chunk);
  };

  /**
   * Deflate#onEnd(status) -> Void
   * - status (Number): deflate status. 0 (Z_OK) on success,
   *   other if not.
   *
   * Called once after you tell deflate that the input stream is
   * complete (Z_FINISH). By default - join collected chunks,
   * free memory and fill `results` / `err` properties.
   **/
  Deflate$1.prototype.onEnd = function (status) {
    // On success - join
    if (status === Z_OK$2) {
      this.result = common.flattenChunks(this.chunks);
    }
    this.chunks = [];
    this.err = status;
    this.msg = this.strm.msg;
  };

  /**
   * deflate(data[, options]) -> Uint8Array
   * - data (Uint8Array|ArrayBuffer|String): input data to compress.
   * - options (Object): zlib deflate options.
   *
   * Compress `data` with deflate algorithm and `options`.
   *
   * Supported options are:
   *
   * - level
   * - windowBits
   * - memLevel
   * - strategy
   * - dictionary
   *
   * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
   * for more information on these.
   *
   * Sugar (options):
   *
   * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
   *   negative windowBits implicitly.
   *
   * ##### Example:
   *
   * ```javascript
   * const pako = require('pako')
   * const data = new Uint8Array([1,2,3,4,5,6,7,8,9]);
   *
   * console.log(pako.deflate(data));
   * ```
   **/
  function deflate$1(input, options) {
    const deflator = new Deflate$1(options);
    deflator.push(input, true);

    // That will never happens, if you don't cheat with options :)
    if (deflator.err) {
      throw deflator.msg || messages[deflator.err];
    }
    return deflator.result;
  }
  var deflate_2 = deflate$1;
  var deflate_1$1 = {
    deflate: deflate_2};

  // (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
  const BAD$1 = 16209; /* got a data error -- remain here until reset */
  const TYPE$1 = 16191; /* 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.
   */
  var inffast = function inflate_fast(strm, start) {
    let _in; /* local strm.input */
    let last; /* have enough input while in < last */
    let _out; /* local strm.output */
    let beg; /* inflate()'s initial strm.output */
    let end; /* while out < end, enough space available */
    //#ifdef INFLATE_STRICT
    let dmax; /* maximum distance from zlib header */
    //#endif
    let wsize; /* window size or zero if not using window */
    let whave; /* valid bytes in the window */
    let wnext; /* window write index */
    // Use `s_window` instead `window`, avoid conflict with instrumentation tools
    let s_window; /* allocated sliding window, if wsize != 0 */
    let hold; /* local strm.hold */
    let bits; /* local strm.bits */
    let lcode; /* local strm.lencode */
    let dcode; /* local strm.distcode */
    let lmask; /* mask for first level of length codes */
    let dmask; /* mask for first level of distance codes */
    let here; /* retrieved table entry */
    let op; /* code bits, operation, extra bits, or */
    /*  window position, window bytes to copy */
    let len; /* match length, unused bytes */
    let dist; /* match distance */
    let from; /* where to copy match from */
    let from_source;
    let input, output; // JS specific, because we have no pointers

    /* copy state to local variables */
    const 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$1;
                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$1;
                    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$1;
              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$1;
          break top;
        } else {
          strm.msg = 'invalid literal/length code';
          state.mode = BAD$1;
          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;
  };

  // (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.

  const MAXBITS = 15;
  const ENOUGH_LENS$1 = 852;
  const ENOUGH_DISTS$1 = 592;
  //const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);

  const CODES$1 = 0;
  const LENS$1 = 1;
  const DISTS$1 = 2;
  const lbase = new Uint16Array([/* 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]);
  const lext = new Uint8Array([/* 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]);
  const dbase = new Uint16Array([/* 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]);
  const dext = new Uint8Array([/* 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]);
  const inflate_table = (type, lens, lens_index, codes, table, table_index, work, opts) => {
    const bits = opts.bits;
    //here = opts.here; /* table entry for duplication */

    let len = 0; /* a code's length in bits */
    let sym = 0; /* index of code symbols */
    let min = 0,
      max = 0; /* minimum and maximum code lengths */
    let root = 0; /* number of index bits for root table */
    let curr = 0; /* number of index bits for current table */
    let drop = 0; /* code bits to drop for sub-table */
    let left = 0; /* number of prefix codes available */
    let used = 0; /* code entries in table used */
    let huff = 0; /* Huffman code */
    let incr; /* for incrementing code, index */
    let fill; /* index for replicating entries */
    let low; /* low bits for current root entry */
    let mask; /* mask for low root bits */
    let next; /* next available space in table */
    let base = null; /* base value table to use */
    //  let shoextra;    /* extra bits table to use */
    let match; /* use base and extra for symbol >= match */
    const count = new Uint16Array(MAXBITS + 1); //[MAXBITS+1];    /* number of codes of each length */
    const offs = new Uint16Array(MAXBITS + 1); //[MAXBITS+1];     /* offsets in table for each length */
    let extra = null;
    let 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$1 || 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$1) {
      base = extra = work; /* dummy value--not used */
      match = 20;
    } else if (type === LENS$1) {
      base = lbase;
      extra = lext;
      match = 257;
    } else {
      /* DISTS */
      base = dbase;
      extra = dext;
      match = 0;
    }

    /* 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$1 && used > ENOUGH_LENS$1 || type === DISTS$1 && used > ENOUGH_DISTS$1) {
      return 1;
    }

    /* process all codes and make table entries */
    for (;;) {
      /* create table entry */
      here_bits = len - drop;
      if (work[sym] + 1 < match) {
        here_op = 0;
        here_val = work[sym];
      } else if (work[sym] >= match) {
        here_op = extra[work[sym] - match];
        here_val = base[work[sym] - match];
      } 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$1 && used > ENOUGH_LENS$1 || type === DISTS$1 && used > ENOUGH_DISTS$1) {
          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;
  };
  var inftrees = inflate_table;

  // (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.

  const CODES = 0;
  const LENS = 1;
  const DISTS = 2;

  /* Public constants ==========================================================*/
  /* ===========================================================================*/

  const {
    Z_FINISH: Z_FINISH$1,
    Z_BLOCK,
    Z_TREES,
    Z_OK: Z_OK$1,
    Z_STREAM_END: Z_STREAM_END$1,
    Z_NEED_DICT: Z_NEED_DICT$1,
    Z_STREAM_ERROR: Z_STREAM_ERROR$1,
    Z_DATA_ERROR: Z_DATA_ERROR$1,
    Z_MEM_ERROR: Z_MEM_ERROR$1,
    Z_BUF_ERROR,
    Z_DEFLATED
  } = constants$2;

  /* STATES ====================================================================*/
  /* ===========================================================================*/

  const HEAD = 16180; /* i: waiting for magic header */
  const FLAGS = 16181; /* i: waiting for method and flags (gzip) */
  const TIME = 16182; /* i: waiting for modification time (gzip) */
  const OS = 16183; /* i: waiting for extra flags and operating system (gzip) */
  const EXLEN = 16184; /* i: waiting for extra length (gzip) */
  const EXTRA = 16185; /* i: waiting for extra bytes (gzip) */
  const NAME = 16186; /* i: waiting for end of file name (gzip) */
  const COMMENT = 16187; /* i: waiting for end of comment (gzip) */
  const HCRC = 16188; /* i: waiting for header crc (gzip) */
  const DICTID = 16189; /* i: waiting for dictionary check value */
  const DICT = 16190; /* waiting for inflateSetDictionary() call */
  const TYPE = 16191; /* i: waiting for type bits, including last-flag bit */
  const TYPEDO = 16192; /* i: same, but skip check to exit inflate on new block */
  const STORED = 16193; /* i: waiting for stored size (length and complement) */
  const COPY_ = 16194; /* i/o: same as COPY below, but only first time in */
  const COPY = 16195; /* i/o: waiting for input or output to copy stored block */
  const TABLE = 16196; /* i: waiting for dynamic block table lengths */
  const LENLENS = 16197; /* i: waiting for code length code lengths */
  const CODELENS = 16198; /* i: waiting for length/lit and distance code lengths */
  const LEN_ = 16199; /* i: same as LEN below, but only first time in */
  const LEN = 16200; /* i: waiting for length/lit/eob code */
  const LENEXT = 16201; /* i: waiting for length extra bits */
  const DIST = 16202; /* i: waiting for distance code */
  const DISTEXT = 16203; /* i: waiting for distance extra bits */
  const MATCH = 16204; /* o: waiting for output space to copy string */
  const LIT = 16205; /* o: waiting for output space to write literal */
  const CHECK = 16206; /* i: waiting for 32-bit check value */
  const LENGTH = 16207; /* i: waiting for 32-bit length (gzip) */
  const DONE = 16208; /* finished check, done -- remain here until reset */
  const BAD = 16209; /* got a data error -- remain here until reset */
  const MEM = 16210; /* got an inflate() memory error -- remain here until reset */
  const SYNC = 16211; /* looking for synchronization bytes to restart inflate() */

  /* ===========================================================================*/

  const ENOUGH_LENS = 852;
  const ENOUGH_DISTS = 592;
  //const ENOUGH =  (ENOUGH_LENS+ENOUGH_DISTS);

  const MAX_WBITS = 15;
  /* 32K LZ77 window */
  const DEF_WBITS = MAX_WBITS;
  const zswap32 = q => {
    return (q >>> 24 & 0xff) + (q >>> 8 & 0xff00) + ((q & 0xff00) << 8) + ((q & 0xff) << 24);
  };
  function InflateState() {
    this.strm = null; /* pointer back to this zlib stream */
    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,
                      bit 2 true to validate check value */
    this.havedict = false; /* true if dictionary provided */
    this.flags = 0; /* gzip header method and flags (0 if zlib), or
                       -1 if raw or no header yet */
    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 Uint16Array(320); /* temporary storage for code lengths */
    this.work = new Uint16Array(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 Int32Array(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 */
  }
  const inflateStateCheck = strm => {
    if (!strm) {
      return 1;
    }
    const state = strm.state;
    if (!state || state.strm !== strm || state.mode < HEAD || state.mode > SYNC) {
      return 1;
    }
    return 0;
  };
  const inflateResetKeep = strm => {
    if (inflateStateCheck(strm)) {
      return Z_STREAM_ERROR$1;
    }
    const 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.flags = -1;
    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 Int32Array(ENOUGH_LENS);
    state.distcode = state.distdyn = new Int32Array(ENOUGH_DISTS);
    state.sane = 1;
    state.back = -1;
    //Tracev((stderr, "inflate: reset\n"));
    return Z_OK$1;
  };
  const inflateReset = strm => {
    if (inflateStateCheck(strm)) {
      return Z_STREAM_ERROR$1;
    }
    const state = strm.state;
    state.wsize = 0;
    state.whave = 0;
    state.wnext = 0;
    return inflateResetKeep(strm);
  };
  const inflateReset2 = (strm, windowBits) => {
    let wrap;

    /* get the state */
    if (inflateStateCheck(strm)) {
      return Z_STREAM_ERROR$1;
    }
    const state = strm.state;

    /* extract wrap request from windowBits parameter */
    if (windowBits < 0) {
      wrap = 0;
      windowBits = -windowBits;
    } else {
      wrap = (windowBits >> 4) + 5;
      if (windowBits < 48) {
        windowBits &= 15;
      }
    }

    /* set number of window bits, free window if different */
    if (windowBits && (windowBits < 8 || windowBits > 15)) {
      return Z_STREAM_ERROR$1;
    }
    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);
  };
  const inflateInit2 = (strm, windowBits) => {
    if (!strm) {
      return Z_STREAM_ERROR$1;
    }
    //strm.msg = Z_NULL;                 /* in case we return an error */

    const state = new InflateState();

    //if (state === Z_NULL) return Z_MEM_ERROR;
    //Tracev((stderr, "inflate: allocated\n"));
    strm.state = state;
    state.strm = strm;
    state.window = null /*Z_NULL*/;
    state.mode = HEAD; /* to pass state test in inflateReset2() */
    const ret = inflateReset2(strm, windowBits);
    if (ret !== Z_OK$1) {
      strm.state = null /*Z_NULL*/;
    }
    return ret;
  };
  const 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.
   */
  let virgin = true;
  let lenfix, distfix; // We have no pointers in JS, so keep tables separate

  const fixedtables = state => {
    /* build fixed huffman tables if first call (may not be thread safe) */
    if (virgin) {
      lenfix = new Int32Array(512);
      distfix = new Int32Array(32);

      /* literal/length table */
      let 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;
      }
      inftrees(LENS, state.lens, 0, 288, lenfix, 0, state.work, {
        bits: 9
      });

      /* distance table */
      sym = 0;
      while (sym < 32) {
        state.lens[sym++] = 5;
      }
      inftrees(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.
   */
  const updatewindow = (strm, src, end, copy) => {
    let dist;
    const 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 Uint8Array(state.wsize);
    }

    /* copy state->wsize or less output bytes into the circular window */
    if (copy >= state.wsize) {
      state.window.set(src.subarray(end - state.wsize, end), 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);
      state.window.set(src.subarray(end - copy, end - copy + dist), state.wnext);
      copy -= dist;
      if (copy) {
        //zmemcpy(state->window, end - copy, copy);
        state.window.set(src.subarray(end - copy, end), 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;
  };
  const inflate$2 = (strm, flush) => {
    let state;
    let input, output; // input/output buffers
    let next; /* next input INDEX */
    let put; /* next output INDEX */
    let have, left; /* available input and output */
    let hold; /* bit buffer */
    let bits; /* bits in bit buffer */
    let _in, _out; /* save starting available input and output */
    let copy; /* number of stored or match bytes to copy */
    let from; /* where to copy match bytes from */
    let from_source;
    let here = 0; /* current decoding table entry */
    let here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
    //let last;                   /* parent table entry */
    let last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
    let len; /* length to copy for repeats, bits to drop */
    let ret; /* return code */
    const hbuf = new Uint8Array(4); /* buffer for gzip header crc calculation */
    let opts;
    let n; // temporary variable for NEED_BITS

    const order = /* permutation of code lengths */
    new Uint8Array([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
    if (inflateStateCheck(strm) || !strm.output || !strm.input && strm.avail_in !== 0) {
      return Z_STREAM_ERROR$1;
    }
    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$1;
    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 */
            if (state.wbits === 0) {
              state.wbits = 15;
            }
            state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
            //=== CRC2(state.check, hold);
            hbuf[0] = hold & 0xff;
            hbuf[1] = hold >>> 8 & 0xff;
            state.check = crc32_1(state.check, hbuf, 2, 0);
            //===//

            //=== INITBITS();
            hold = 0;
            bits = 0;
            //===//
            state.mode = FLAGS;
            break;
          }
          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;
          }
          if (len > 15 || len > state.wbits) {
            strm.msg = 'invalid window size';
            state.mode = BAD;
            break;
          }

          // !!! pako patch. Force use `options.windowBits` if passed.
          // Required to always use max window size by default.
          state.dmax = 1 << state.wbits;
          //state.dmax = 1 << len;

          state.flags = 0; /* indicate zlib header */
          //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 && state.wrap & 4) {
            //=== CRC2(state.check, hold);
            hbuf[0] = hold & 0xff;
            hbuf[1] = hold >>> 8 & 0xff;
            state.check = crc32_1(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 && state.wrap & 4) {
            //=== 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_1(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 && state.wrap & 4) {
            //=== CRC2(state.check, hold);
            hbuf[0] = hold & 0xff;
            hbuf[1] = hold >>> 8 & 0xff;
            state.check = crc32_1(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 && state.wrap & 4) {
              //=== CRC2(state.check, hold);
              hbuf[0] = hold & 0xff;
              hbuf[1] = hold >>> 8 & 0xff;
              state.check = crc32_1(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 Uint8Array(state.head.extra_len);
                }
                state.head.extra.set(input.subarray(next,
                // extra field is limited to 65536 bytes
                // - no need for additional size check
                next + 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.wrap & 4) {
                state.check = crc32_1(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.wrap & 4) {
              state.check = crc32_1(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.wrap & 4) {
              state.check = crc32_1(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 (state.wrap & 4 && 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$1;
          }
          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); ---
            output.set(input.subarray(next, 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 = inftrees(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 = inftrees(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 = inftrees(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;
            //---
            inffast(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 (state.wrap & 4 && _out) {
              strm.adler = state.check = /*UPDATE_CHECK(state.check, put - _out, _out);*/
              state.flags ? crc32_1(state.check, output, _out, put - _out) : adler32_1(state.check, output, _out, put - _out);
            }
            _out = left;
            // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
            if (state.wrap & 4 && (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 (state.wrap & 4 && 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$1;
          break inf_leave;
        case BAD:
          ret = Z_DATA_ERROR$1;
          break inf_leave;
        case MEM:
          return Z_MEM_ERROR$1;
        case SYNC:
        /* falls through */
        default:
          return Z_STREAM_ERROR$1;
      }
    }

    // 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$1)) {
      if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ;
    }
    _in -= strm.avail_in;
    _out -= strm.avail_out;
    strm.total_in += _in;
    strm.total_out += _out;
    state.total += _out;
    if (state.wrap & 4 && _out) {
      strm.adler = state.check = /*UPDATE_CHECK(state.check, strm.next_out - _out, _out);*/
      state.flags ? crc32_1(state.check, output, _out, strm.next_out - _out) : adler32_1(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$1) && ret === Z_OK$1) {
      ret = Z_BUF_ERROR;
    }
    return ret;
  };
  const inflateEnd = strm => {
    if (inflateStateCheck(strm)) {
      return Z_STREAM_ERROR$1;
    }
    let state = strm.state;
    if (state.window) {
      state.window = null;
    }
    strm.state = null;
    return Z_OK$1;
  };
  const inflateGetHeader = (strm, head) => {
    /* check state */
    if (inflateStateCheck(strm)) {
      return Z_STREAM_ERROR$1;
    }
    const state = strm.state;
    if ((state.wrap & 2) === 0) {
      return Z_STREAM_ERROR$1;
    }

    /* save header structure */
    state.head = head;
    head.done = false;
    return Z_OK$1;
  };
  const inflateSetDictionary = (strm, dictionary) => {
    const dictLength = dictionary.length;
    let state;
    let dictid;
    let ret;

    /* check state */
    if (inflateStateCheck(strm)) {
      return Z_STREAM_ERROR$1;
    }
    state = strm.state;
    if (state.wrap !== 0 && state.mode !== DICT) {
      return Z_STREAM_ERROR$1;
    }

    /* check for correct dictionary identifier */
    if (state.mode === DICT) {
      dictid = 1; /* adler32(0, null, 0)*/
      /* dictid = adler32(dictid, dictionary, dictLength); */
      dictid = adler32_1(dictid, dictionary, dictLength, 0);
      if (dictid !== state.check) {
        return Z_DATA_ERROR$1;
      }
    }
    /* 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$1;
    }
    state.havedict = 1;
    // Tracev((stderr, "inflate:   dictionary set\n"));
    return Z_OK$1;
  };
  var inflateReset_1 = inflateReset;
  var inflateReset2_1 = inflateReset2;
  var inflateResetKeep_1 = inflateResetKeep;
  var inflateInit_1 = inflateInit;
  var inflateInit2_1 = inflateInit2;
  var inflate_2$1 = inflate$2;
  var inflateEnd_1 = inflateEnd;
  var inflateGetHeader_1 = inflateGetHeader;
  var inflateSetDictionary_1 = inflateSetDictionary;
  var inflateInfo = 'pako inflate (from Nodeca project)';

  /* Not implemented
  module.exports.inflateCodesUsed = inflateCodesUsed;
  module.exports.inflateCopy = inflateCopy;
  module.exports.inflateGetDictionary = inflateGetDictionary;
  module.exports.inflateMark = inflateMark;
  module.exports.inflatePrime = inflatePrime;
  module.exports.inflateSync = inflateSync;
  module.exports.inflateSyncPoint = inflateSyncPoint;
  module.exports.inflateUndermine = inflateUndermine;
  module.exports.inflateValidate = inflateValidate;
  */

  var inflate_1$2 = {
    inflateReset: inflateReset_1,
    inflateReset2: inflateReset2_1,
    inflateResetKeep: inflateResetKeep_1,
    inflateInit: inflateInit_1,
    inflateInit2: inflateInit2_1,
    inflate: inflate_2$1,
    inflateEnd: inflateEnd_1,
    inflateGetHeader: inflateGetHeader_1,
    inflateSetDictionary: inflateSetDictionary_1,
    inflateInfo: inflateInfo
  };

  // (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 GZheader() {
    /* true if compressed data believed to be text */
    this.text = 0;
    /* modification time */
    this.time = 0;
    /* extra flags (not used when writing a gzip file) */
    this.xflags = 0;
    /* operating system */
    this.os = 0;
    /* pointer to extra field or Z_NULL if none */
    this.extra = null;
    /* extra field length (valid if extra != Z_NULL) */
    this.extra_len = 0; // Actually, we don't need it in JS,
    // but leave for few code modifications

    //
    // Setup limits is not necessary because in js we should not preallocate memory
    // for inflate use constant limit in 65536 bytes
    //

    /* space at extra (only when reading header) */
    // this.extra_max  = 0;
    /* pointer to zero-terminated file name or Z_NULL */
    this.name = '';
    /* space at name (only when reading header) */
    // this.name_max   = 0;
    /* pointer to zero-terminated comment or Z_NULL */
    this.comment = '';
    /* space at comment (only when reading header) */
    // this.comm_max   = 0;
    /* true if there was or will be a header crc */
    this.hcrc = 0;
    /* true when done reading gzip header (not used when writing a gzip file) */
    this.done = false;
  }
  var gzheader = GZheader;
  const toString$2 = Object.prototype.toString;

  /* Public constants ==========================================================*/
  /* ===========================================================================*/

  const {
    Z_NO_FLUSH,
    Z_FINISH,
    Z_OK,
    Z_STREAM_END,
    Z_NEED_DICT,
    Z_STREAM_ERROR,
    Z_DATA_ERROR,
    Z_MEM_ERROR
  } = constants$2;

  /* ===========================================================================*/

  /**
   * class Inflate
   *
   * Generic JS-style wrapper for zlib calls. If you don't need
   * streaming behaviour - use more simple functions: [[inflate]]
   * and [[inflateRaw]].
   **/

  /* internal
   * inflate.chunks -> Array
   *
   * Chunks of output data, if [[Inflate#onData]] not overridden.
   **/

  /**
   * Inflate.result -> Uint8Array|String
   *
   * Uncompressed result, generated by default [[Inflate#onData]]
   * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
   * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
   **/

  /**
   * Inflate.err -> Number
   *
   * Error code after inflate finished. 0 (Z_OK) on success.
   * Should be checked if broken data possible.
   **/

  /**
   * Inflate.msg -> String
   *
   * Error message, if [[Inflate.err]] != 0
   **/

  /**
   * new Inflate(options)
   * - options (Object): zlib inflate options.
   *
   * Creates new inflator instance with specified params. Throws exception
   * on bad params. Supported options:
   *
   * - `windowBits`
   * - `dictionary`
   *
   * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
   * for more information on these.
   *
   * Additional options, for internal needs:
   *
   * - `chunkSize` - size of generated data chunks (16K by default)
   * - `raw` (Boolean) - do raw inflate
   * - `to` (String) - if equal to 'string', then result will be converted
   *   from utf8 to utf16 (javascript) string. When string output requested,
   *   chunk length can differ from `chunkSize`, depending on content.
   *
   * By default, when no options set, autodetect deflate/gzip data format via
   * wrapper header.
   *
   * ##### Example:
   *
   * ```javascript
   * const pako = require('pako')
   * const chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])
   * const chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);
   *
   * const inflate = new pako.Inflate({ level: 3});
   *
   * inflate.push(chunk1, false);
   * inflate.push(chunk2, true);  // true -> last chunk
   *
   * if (inflate.err) { throw new Error(inflate.err); }
   *
   * console.log(inflate.result);
   * ```
   **/
  function Inflate$1(options) {
    this.options = common.assign({
      chunkSize: 1024 * 64,
      windowBits: 15,
      to: ''
    }, options || {});
    const opt = this.options;

    // Force window size for `raw` data, if not set directly,
    // because we have no header for autodetect.
    if (opt.raw && opt.windowBits >= 0 && opt.windowBits < 16) {
      opt.windowBits = -opt.windowBits;
      if (opt.windowBits === 0) {
        opt.windowBits = -15;
      }
    }

    // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
    if (opt.windowBits >= 0 && opt.windowBits < 16 && !(options && options.windowBits)) {
      opt.windowBits += 32;
    }

    // Gzip header has no info about windows size, we can do autodetect only
    // for deflate. So, if window size not set, force it to max when gzip possible
    if (opt.windowBits > 15 && opt.windowBits < 48) {
      // bit 3 (16) -> gzipped data
      // bit 4 (32) -> autodetect gzip/deflate
      if ((opt.windowBits & 15) === 0) {
        opt.windowBits |= 15;
      }
    }
    this.err = 0; // error code, if happens (0 = Z_OK)
    this.msg = ''; // error message
    this.ended = false; // used to avoid multiple onEnd() calls
    this.chunks = []; // chunks of compressed data

    this.strm = new zstream();
    this.strm.avail_out = 0;
    let status = inflate_1$2.inflateInit2(this.strm, opt.windowBits);
    if (status !== Z_OK) {
      throw new Error(messages[status]);
    }
    this.header = new gzheader();
    inflate_1$2.inflateGetHeader(this.strm, this.header);

    // Setup dictionary
    if (opt.dictionary) {
      // Convert data if needed
      if (typeof opt.dictionary === 'string') {
        opt.dictionary = strings.string2buf(opt.dictionary);
      } else if (toString$2.call(opt.dictionary) === '[object ArrayBuffer]') {
        opt.dictionary = new Uint8Array(opt.dictionary);
      }
      if (opt.raw) {
        //In raw mode we need to set the dictionary early
        status = inflate_1$2.inflateSetDictionary(this.strm, opt.dictionary);
        if (status !== Z_OK) {
          throw new Error(messages[status]);
        }
      }
    }
  }

  /**
   * Inflate#push(data[, flush_mode]) -> Boolean
   * - data (Uint8Array|ArrayBuffer): input data
   * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE
   *   flush modes. See constants. Skipped or `false` means Z_NO_FLUSH,
   *   `true` means Z_FINISH.
   *
   * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
   * new output chunks. Returns `true` on success. If end of stream detected,
   * [[Inflate#onEnd]] will be called.
   *
   * `flush_mode` is not needed for normal operation, because end of stream
   * detected automatically. You may try to use it for advanced things, but
   * this functionality was not tested.
   *
   * On fail call [[Inflate#onEnd]] with error code and return false.
   *
   * ##### Example
   *
   * ```javascript
   * push(chunk, false); // push one of data chunks
   * ...
   * push(chunk, true);  // push last chunk
   * ```
   **/
  Inflate$1.prototype.push = function (data, flush_mode) {
    const strm = this.strm;
    const chunkSize = this.options.chunkSize;
    const dictionary = this.options.dictionary;
    let status, _flush_mode, last_avail_out;
    if (this.ended) return false;
    if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;else _flush_mode = flush_mode === true ? Z_FINISH : Z_NO_FLUSH;

    // Convert data if needed
    if (toString$2.call(data) === '[object ArrayBuffer]') {
      strm.input = new Uint8Array(data);
    } else {
      strm.input = data;
    }
    strm.next_in = 0;
    strm.avail_in = strm.input.length;
    for (;;) {
      if (strm.avail_out === 0) {
        strm.output = new Uint8Array(chunkSize);
        strm.next_out = 0;
        strm.avail_out = chunkSize;
      }
      status = inflate_1$2.inflate(strm, _flush_mode);
      if (status === Z_NEED_DICT && dictionary) {
        status = inflate_1$2.inflateSetDictionary(strm, dictionary);
        if (status === Z_OK) {
          status = inflate_1$2.inflate(strm, _flush_mode);
        } else if (status === Z_DATA_ERROR) {
          // Replace code with more verbose
          status = Z_NEED_DICT;
        }
      }

      // Skip snyc markers if more data follows and not raw mode
      while (strm.avail_in > 0 && status === Z_STREAM_END && strm.state.wrap > 0 && data[strm.next_in] !== 0) {
        inflate_1$2.inflateReset(strm);
        status = inflate_1$2.inflate(strm, _flush_mode);
      }
      switch (status) {
        case Z_STREAM_ERROR:
        case Z_DATA_ERROR:
        case Z_NEED_DICT:
        case Z_MEM_ERROR:
          this.onEnd(status);
          this.ended = true;
          return false;
      }

      // Remember real `avail_out` value, because we may patch out buffer content
      // to align utf8 strings boundaries.
      last_avail_out = strm.avail_out;
      if (strm.next_out) {
        if (strm.avail_out === 0 || status === Z_STREAM_END) {
          if (this.options.to === 'string') {
            let next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
            let tail = strm.next_out - next_out_utf8;
            let utf8str = strings.buf2string(strm.output, next_out_utf8);

            // move tail & realign counters
            strm.next_out = tail;
            strm.avail_out = chunkSize - tail;
            if (tail) strm.output.set(strm.output.subarray(next_out_utf8, next_out_utf8 + tail), 0);
            this.onData(utf8str);
          } else {
            this.onData(strm.output.length === strm.next_out ? strm.output : strm.output.subarray(0, strm.next_out));
          }
        }
      }

      // Must repeat iteration if out buffer is full
      if (status === Z_OK && last_avail_out === 0) continue;

      // Finalize if end of stream reached.
      if (status === Z_STREAM_END) {
        status = inflate_1$2.inflateEnd(this.strm);
        this.onEnd(status);
        this.ended = true;
        return true;
      }
      if (strm.avail_in === 0) break;
    }
    return true;
  };

  /**
   * Inflate#onData(chunk) -> Void
   * - chunk (Uint8Array|String): output data. When string output requested,
   *   each chunk will be string.
   *
   * By default, stores data blocks in `chunks[]` property and glue
   * those in `onEnd`. Override this handler, if you need another behaviour.
   **/
  Inflate$1.prototype.onData = function (chunk) {
    this.chunks.push(chunk);
  };

  /**
   * Inflate#onEnd(status) -> Void
   * - status (Number): inflate status. 0 (Z_OK) on success,
   *   other if not.
   *
   * Called either after you tell inflate that the input stream is
   * complete (Z_FINISH). By default - join collected chunks,
   * free memory and fill `results` / `err` properties.
   **/
  Inflate$1.prototype.onEnd = function (status) {
    // On success - join
    if (status === Z_OK) {
      if (this.options.to === 'string') {
        this.result = this.chunks.join('');
      } else {
        this.result = common.flattenChunks(this.chunks);
      }
    }
    this.chunks = [];
    this.err = status;
    this.msg = this.strm.msg;
  };

  /**
   * inflate(data[, options]) -> Uint8Array|String
   * - data (Uint8Array|ArrayBuffer): input data to decompress.
   * - options (Object): zlib inflate options.
   *
   * Decompress `data` with inflate/ungzip and `options`. Autodetect
   * format via wrapper header by default. That's why we don't provide
   * separate `ungzip` method.
   *
   * Supported options are:
   *
   * - windowBits
   *
   * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
   * for more information.
   *
   * Sugar (options):
   *
   * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
   *   negative windowBits implicitly.
   * - `to` (String) - if equal to 'string', then result will be converted
   *   from utf8 to utf16 (javascript) string. When string output requested,
   *   chunk length can differ from `chunkSize`, depending on content.
   *
   *
   * ##### Example:
   *
   * ```javascript
   * const pako = require('pako');
   * const input = pako.deflate(new Uint8Array([1,2,3,4,5,6,7,8,9]));
   * let output;
   *
   * try {
   *   output = pako.inflate(input);
   * } catch (err) {
   *   console.log(err);
   * }
   * ```
   **/
  function inflate$1(input, options) {
    const inflator = new Inflate$1(options);
    inflator.push(input);

    // That will never happens, if you don't cheat with options :)
    if (inflator.err) throw inflator.msg || messages[inflator.err];
    return inflator.result;
  }

  /**
   * ungzip(data[, options]) -> Uint8Array|String
   * - data (Uint8Array|ArrayBuffer): input data to decompress.
   * - options (Object): zlib inflate options.
   *
   * Just shortcut to [[inflate]], because it autodetects format
   * by header.content. Done for convenience.
   **/

  var Inflate_1$1 = Inflate$1;
  var inflate_2 = inflate$1;
  var inflate_1$1 = {
    Inflate: Inflate_1$1,
    inflate: inflate_2};
  const {
    deflate} = deflate_1$1;
  const {
    Inflate,
    inflate} = inflate_1$1;
  var deflate_1 = deflate;
  var Inflate_1 = Inflate;
  var inflate_1 = inflate;

  const crcTable = [];
  for (let n = 0; n < 256; n++) {
    let c = n;
    for (let k = 0; k < 8; k++) {
      if (c & 1) {
        c = 0xedb88320 ^ c >>> 1;
      } else {
        c = c >>> 1;
      }
    }
    crcTable[n] = c;
  }
  const initialCrc = 0xffffffff;
  function updateCrc(currentCrc, data, length) {
    let c = currentCrc;
    for (let n = 0; n < length; n++) {
      c = crcTable[(c ^ data[n]) & 0xff] ^ c >>> 8;
    }
    return c;
  }
  function crc(data, length) {
    return (updateCrc(initialCrc, data, length) ^ initialCrc) >>> 0;
  }
  function checkCrc(buffer, crcLength, chunkName) {
    const expectedCrc = buffer.readUint32();
    const actualCrc = crc(new Uint8Array(buffer.buffer, buffer.byteOffset + buffer.offset - crcLength - 4, crcLength), crcLength); // "- 4" because we already advanced by reading the CRC
    if (actualCrc !== expectedCrc) {
      throw new Error(`CRC mismatch for chunk ${chunkName}. Expected ${expectedCrc}, found ${actualCrc}`);
    }
  }
  function writeCrc(buffer, length) {
    buffer.writeUint32(crc(new Uint8Array(buffer.buffer, buffer.byteOffset + buffer.offset - length, length), length));
  }

  function unfilterNone(currentLine, newLine, bytesPerLine) {
    for (let i = 0; i < bytesPerLine; i++) {
      newLine[i] = currentLine[i];
    }
  }
  function unfilterSub(currentLine, newLine, bytesPerLine, bytesPerPixel) {
    let i = 0;
    for (; i < bytesPerPixel; i++) {
      // just copy first bytes
      newLine[i] = currentLine[i];
    }
    for (; i < bytesPerLine; i++) {
      newLine[i] = currentLine[i] + newLine[i - bytesPerPixel] & 0xff;
    }
  }
  function unfilterUp(currentLine, newLine, prevLine, bytesPerLine) {
    let i = 0;
    if (prevLine.length === 0) {
      // just copy bytes for first line
      for (; i < bytesPerLine; i++) {
        newLine[i] = currentLine[i];
      }
    } else {
      for (; i < bytesPerLine; i++) {
        newLine[i] = currentLine[i] + prevLine[i] & 0xff;
      }
    }
  }
  function unfilterAverage(currentLine, newLine, prevLine, bytesPerLine, bytesPerPixel) {
    let i = 0;
    if (prevLine.length === 0) {
      for (; i < bytesPerPixel; i++) {
        newLine[i] = currentLine[i];
      }
      for (; i < bytesPerLine; i++) {
        newLine[i] = currentLine[i] + (newLine[i - bytesPerPixel] >> 1) & 0xff;
      }
    } else {
      for (; i < bytesPerPixel; i++) {
        newLine[i] = currentLine[i] + (prevLine[i] >> 1) & 0xff;
      }
      for (; i < bytesPerLine; i++) {
        newLine[i] = currentLine[i] + (newLine[i - bytesPerPixel] + prevLine[i] >> 1) & 0xff;
      }
    }
  }
  function unfilterPaeth(currentLine, newLine, prevLine, bytesPerLine, bytesPerPixel) {
    let i = 0;
    if (prevLine.length === 0) {
      for (; i < bytesPerPixel; i++) {
        newLine[i] = currentLine[i];
      }
      for (; i < bytesPerLine; i++) {
        newLine[i] = currentLine[i] + newLine[i - bytesPerPixel] & 0xff;
      }
    } else {
      for (; i < bytesPerPixel; i++) {
        newLine[i] = currentLine[i] + prevLine[i] & 0xff;
      }
      for (; i < bytesPerLine; i++) {
        newLine[i] = currentLine[i] + paethPredictor(newLine[i - bytesPerPixel], prevLine[i], prevLine[i - bytesPerPixel]) & 0xff;
      }
    }
  }
  function paethPredictor(a, b, c) {
    const p = a + b - c;
    const pa = Math.abs(p - a);
    const pb = Math.abs(p - b);
    const pc = Math.abs(p - c);
    if (pa <= pb && pa <= pc) return a;else if (pb <= pc) return b;else return c;
  }

  const uint16 = new Uint16Array([0x00ff]);
  const uint8 = new Uint8Array(uint16.buffer);
  const osIsLittleEndian = uint8[0] === 0xff;
  const empty = new Uint8Array(0);
  function decodeInterlaceNull(params) {
    const {
      data,
      width,
      height,
      channels,
      depth
    } = params;
    const bytesPerPixel = channels * depth / 8;
    const bytesPerLine = width * bytesPerPixel;
    const newData = new Uint8Array(height * bytesPerLine);
    let prevLine = empty;
    let offset = 0;
    let currentLine;
    let newLine;
    for (let i = 0; i < height; i++) {
      currentLine = data.subarray(offset + 1, offset + 1 + bytesPerLine);
      newLine = newData.subarray(i * bytesPerLine, (i + 1) * bytesPerLine);
      switch (data[offset]) {
        case 0:
          unfilterNone(currentLine, newLine, bytesPerLine);
          break;
        case 1:
          unfilterSub(currentLine, newLine, bytesPerLine, bytesPerPixel);
          break;
        case 2:
          unfilterUp(currentLine, newLine, prevLine, bytesPerLine);
          break;
        case 3:
          unfilterAverage(currentLine, newLine, prevLine, bytesPerLine, bytesPerPixel);
          break;
        case 4:
          unfilterPaeth(currentLine, newLine, prevLine, bytesPerLine, bytesPerPixel);
          break;
        default:
          throw new Error(`Unsupported filter: ${data[offset]}`);
      }
      prevLine = newLine;
      offset += bytesPerLine + 1;
    }
    if (depth === 16) {
      const uint16Data = new Uint16Array(newData.buffer);
      if (osIsLittleEndian) {
        for (let k = 0; k < uint16Data.length; k++) {
          // PNG is always big endian. Swap the bytes.
          uint16Data[k] = swap16(uint16Data[k]);
        }
      }
      return uint16Data;
    } else {
      return newData;
    }
  }
  function swap16(val) {
    return (val & 0xff) << 8 | val >> 8 & 0xff;
  }

  // https://www.w3.org/TR/PNG/#5PNG-file-signature
  const pngSignature = Uint8Array.of(137, 80, 78, 71, 13, 10, 26, 10);
  function writeSignature(buffer) {
    buffer.writeBytes(pngSignature);
  }
  function checkSignature(buffer) {
    if (!hasPngSignature(buffer.readBytes(pngSignature.length))) {
      throw new Error('wrong PNG signature');
    }
  }
  function hasPngSignature(array) {
    if (array.length < pngSignature.length) {
      return false;
    }
    for (let i = 0; i < pngSignature.length; i++) {
      if (array[i] !== pngSignature[i]) {
        return false;
      }
    }
    return true;
  }

  // https://www.w3.org/TR/png/#11tEXt
  const textChunkName = 'tEXt';
  const NULL = 0;
  const latin1Decoder = new TextDecoder('latin1');
  function validateKeyword(keyword) {
    validateLatin1(keyword);
    if (keyword.length === 0 || keyword.length > 79) {
      throw new Error('keyword length must be between 1 and 79');
    }
  }
  // eslint-disable-next-line no-control-regex
  const latin1Regex = /^[\u0000-\u00FF]*$/;
  function validateLatin1(text) {
    if (!latin1Regex.test(text)) {
      throw new Error('invalid latin1 text');
    }
  }
  function decodetEXt(text, buffer, length) {
    const keyword = readKeyword(buffer);
    text[keyword] = readLatin1(buffer, length - keyword.length - 1);
  }
  function encodetEXt(buffer, keyword, text) {
    validateKeyword(keyword);
    validateLatin1(text);
    const length = keyword.length + 1 /* NULL */ + text.length;
    buffer.writeUint32(length);
    buffer.writeChars(textChunkName);
    buffer.writeChars(keyword);
    buffer.writeByte(NULL);
    buffer.writeChars(text);
    writeCrc(buffer, length + 4);
  }
  // https://www.w3.org/TR/png/#11keywords
  function readKeyword(buffer) {
    buffer.mark();
    while (buffer.readByte() !== NULL) {
      /* advance */
    }
    const end = buffer.offset;
    buffer.reset();
    const keyword = latin1Decoder.decode(buffer.readBytes(end - buffer.offset - 1));
    // NULL
    buffer.skip(1);
    validateKeyword(keyword);
    return keyword;
  }
  function readLatin1(buffer, length) {
    return latin1Decoder.decode(buffer.readBytes(length));
  }

  const ColorType = {
    UNKNOWN: -1,
    GREYSCALE: 0,
    TRUECOLOUR: 2,
    INDEXED_COLOUR: 3,
    GREYSCALE_ALPHA: 4,
    TRUECOLOUR_ALPHA: 6
  };
  const CompressionMethod = {
    UNKNOWN: -1,
    DEFLATE: 0
  };
  const FilterMethod = {
    UNKNOWN: -1,
    ADAPTIVE: 0
  };
  const InterlaceMethod = {
    UNKNOWN: -1,
    NO_INTERLACE: 0};

  class PngDecoder extends IOBuffer$4 {
    _checkCrc;
    _inflator;
    _png;
    _end;
    _hasPalette;
    _palette;
    _hasTransparency;
    _transparency;
    _compressionMethod;
    _filterMethod;
    _interlaceMethod;
    _colorType;
    constructor(data, options = {}) {
      super(data);
      const {
        checkCrc = false
      } = options;
      this._checkCrc = checkCrc;
      this._inflator = new Inflate_1();
      this._png = {
        width: -1,
        height: -1,
        channels: -1,
        data: new Uint8Array(0),
        depth: 1,
        text: {}
      };
      this._end = false;
      this._hasPalette = false;
      this._palette = [];
      this._hasTransparency = false;
      this._transparency = new Uint16Array(0);
      this._compressionMethod = CompressionMethod.UNKNOWN;
      this._filterMethod = FilterMethod.UNKNOWN;
      this._interlaceMethod = InterlaceMethod.UNKNOWN;
      this._colorType = ColorType.UNKNOWN;
      // PNG is always big endian
      // https://www.w3.org/TR/PNG/#7Integers-and-byte-order
      this.setBigEndian();
    }
    decode() {
      checkSignature(this);
      while (!this._end) {
        this.decodeChunk();
      }
      this.decodeImage();
      return this._png;
    }
    // https://www.w3.org/TR/PNG/#5Chunk-layout
    decodeChunk() {
      const length = this.readUint32();
      const type = this.readChars(4);
      const offset = this.offset;
      switch (type) {
        // 11.2 Critical chunks
        case 'IHDR':
          // 11.2.2 IHDR Image header
          this.decodeIHDR();
          break;
        case 'PLTE':
          // 11.2.3 PLTE Palette
          this.decodePLTE(length);
          break;
        case 'IDAT':
          // 11.2.4 IDAT Image data
          this.decodeIDAT(length);
          break;
        case 'IEND':
          // 11.2.5 IEND Image trailer
          this._end = true;
          break;
        // 11.3 Ancillary chunks
        case 'tRNS':
          // 11.3.2.1 tRNS Transparency
          this.decodetRNS(length);
          break;
        case 'iCCP':
          // 11.3.3.3 iCCP Embedded ICC profile
          this.decodeiCCP(length);
          break;
        case textChunkName:
          // 11.3.4.3 tEXt Textual data
          decodetEXt(this._png.text, this, length);
          break;
        case 'pHYs':
          // 11.3.5.3 pHYs Physical pixel dimensions
          this.decodepHYs();
          break;
        default:
          this.skip(length);
          break;
      }
      if (this.offset - offset !== length) {
        throw new Error(`Length mismatch while decoding chunk ${type}`);
      }
      if (this._checkCrc) {
        checkCrc(this, length + 4, type);
      } else {
        this.skip(4);
      }
    }
    // https://www.w3.org/TR/PNG/#11IHDR
    decodeIHDR() {
      const image = this._png;
      image.width = this.readUint32();
      image.height = this.readUint32();
      image.depth = checkBitDepth(this.readUint8());
      const colorType = this.readUint8();
      this._colorType = colorType;
      let channels;
      switch (colorType) {
        case ColorType.GREYSCALE:
          channels = 1;
          break;
        case ColorType.TRUECOLOUR:
          channels = 3;
          break;
        case ColorType.INDEXED_COLOUR:
          channels = 1;
          break;
        case ColorType.GREYSCALE_ALPHA:
          channels = 2;
          break;
        case ColorType.TRUECOLOUR_ALPHA:
          channels = 4;
          break;
        // Kept for exhaustiveness.
        // eslint-disable-next-line unicorn/no-useless-switch-case
        case ColorType.UNKNOWN:
        default:
          throw new Error(`Unknown color type: ${colorType}`);
      }
      this._png.channels = channels;
      this._compressionMethod = this.readUint8();
      if (this._compressionMethod !== CompressionMethod.DEFLATE) {
        throw new Error(`Unsupported compression method: ${this._compressionMethod}`);
      }
      this._filterMethod = this.readUint8();
      this._interlaceMethod = this.readUint8();
    }
    // https://www.w3.org/TR/PNG/#11PLTE
    decodePLTE(length) {
      if (length % 3 !== 0) {
        throw new RangeError(`PLTE field length must be a multiple of 3. Got ${length}`);
      }
      const l = length / 3;
      this._hasPalette = true;
      const palette = [];
      this._palette = palette;
      for (let i = 0; i < l; i++) {
        palette.push([this.readUint8(), this.readUint8(), this.readUint8()]);
      }
    }
    // https://www.w3.org/TR/PNG/#11IDAT
    decodeIDAT(length) {
      this._inflator.push(new Uint8Array(this.buffer, this.offset + this.byteOffset, length));
      this.skip(length);
    }
    // https://www.w3.org/TR/PNG/#11tRNS
    decodetRNS(length) {
      switch (this._colorType) {
        case ColorType.GREYSCALE:
        case ColorType.TRUECOLOUR:
          {
            if (length % 2 !== 0) {
              throw new RangeError(`tRNS chunk length must be a multiple of 2. Got ${length}`);
            }
            if (length / 2 > this._png.width * this._png.height) {
              throw new Error(`tRNS chunk contains more alpha values than there are pixels (${length / 2} vs ${this._png.width * this._png.height})`);
            }
            this._hasTransparency = true;
            this._transparency = new Uint16Array(length / 2);
            for (let i = 0; i < length / 2; i++) {
              this._transparency[i] = this.readUint16();
            }
            break;
          }
        case ColorType.INDEXED_COLOUR:
          {
            if (length > this._palette.length) {
              throw new Error(`tRNS chunk contains more alpha values than there are palette colors (${length} vs ${this._palette.length})`);
            }
            let i = 0;
            for (; i < length; i++) {
              const alpha = this.readByte();
              this._palette[i].push(alpha);
            }
            for (; i < this._palette.length; i++) {
              this._palette[i].push(255);
            }
            break;
          }
        // Kept for exhaustiveness.
        /* eslint-disable unicorn/no-useless-switch-case */
        case ColorType.UNKNOWN:
        case ColorType.GREYSCALE_ALPHA:
        case ColorType.TRUECOLOUR_ALPHA:
        default:
          {
            throw new Error(`tRNS chunk is not supported for color type ${this._colorType}`);
          }
        /* eslint-enable unicorn/no-useless-switch-case */
      }
    }
    // https://www.w3.org/TR/PNG/#11iCCP
    decodeiCCP(length) {
      const name = readKeyword(this);
      const compressionMethod = this.readUint8();
      if (compressionMethod !== CompressionMethod.DEFLATE) {
        throw new Error(`Unsupported iCCP compression method: ${compressionMethod}`);
      }
      const compressedProfile = this.readBytes(length - name.length - 2);
      this._png.iccEmbeddedProfile = {
        name,
        profile: inflate_1(compressedProfile)
      };
    }
    // https://www.w3.org/TR/PNG/#11pHYs
    decodepHYs() {
      const ppuX = this.readUint32();
      const ppuY = this.readUint32();
      const unitSpecifier = this.readByte();
      this._png.resolution = {
        x: ppuX,
        y: ppuY,
        unit: unitSpecifier
      };
    }
    decodeImage() {
      if (this._inflator.err) {
        throw new Error(`Error while decompressing the data: ${this._inflator.err}`);
      }
      const data = this._inflator.result;
      if (this._filterMethod !== FilterMethod.ADAPTIVE) {
        throw new Error(`Filter method ${this._filterMethod} not supported`);
      }
      if (this._interlaceMethod === InterlaceMethod.NO_INTERLACE) {
        this._png.data = decodeInterlaceNull({
          data: data,
          width: this._png.width,
          height: this._png.height,
          channels: this._png.channels,
          depth: this._png.depth
        });
      } else {
        throw new Error(`Interlace method ${this._interlaceMethod} not supported`);
      }
      if (this._hasPalette) {
        this._png.palette = this._palette;
      }
      if (this._hasTransparency) {
        this._png.transparency = this._transparency;
      }
    }
  }
  function checkBitDepth(value) {
    if (value !== 1 && value !== 2 && value !== 4 && value !== 8 && value !== 16) {
      throw new Error(`invalid bit depth: ${value}`);
    }
    return value;
  }

  const defaultZlibOptions = {
    level: 3
  };
  class PngEncoder extends IOBuffer$4 {
    _png;
    _zlibOptions;
    _colorType;
    constructor(data, options = {}) {
      super();
      this._colorType = ColorType.UNKNOWN;
      this._zlibOptions = {
        ...defaultZlibOptions,
        ...options.zlib
      };
      this._png = this._checkData(data);
      this.setBigEndian();
    }
    encode() {
      writeSignature(this);
      this.encodeIHDR();
      this.encodeData();
      if (this._png.text) {
        for (const [keyword, text] of Object.entries(this._png.text)) {
          encodetEXt(this, keyword, text);
        }
      }
      this.encodeIEND();
      return this.toArray();
    }
    // https://www.w3.org/TR/PNG/#11IHDR
    encodeIHDR() {
      this.writeUint32(13);
      this.writeChars('IHDR');
      this.writeUint32(this._png.width);
      this.writeUint32(this._png.height);
      this.writeByte(this._png.depth);
      this.writeByte(this._colorType);
      this.writeByte(CompressionMethod.DEFLATE);
      this.writeByte(FilterMethod.ADAPTIVE);
      this.writeByte(InterlaceMethod.NO_INTERLACE);
      writeCrc(this, 17);
    }
    // https://www.w3.org/TR/PNG/#11IEND
    encodeIEND() {
      this.writeUint32(0);
      this.writeChars('IEND');
      writeCrc(this, 4);
    }
    // https://www.w3.org/TR/PNG/#11IDAT
    encodeIDAT(data) {
      this.writeUint32(data.length);
      this.writeChars('IDAT');
      this.writeBytes(data);
      writeCrc(this, data.length + 4);
    }
    encodeData() {
      const {
        width,
        height,
        channels,
        depth,
        data
      } = this._png;
      const slotsPerLine = channels * width;
      const newData = new IOBuffer$4().setBigEndian();
      let offset = 0;
      for (let i = 0; i < height; i++) {
        newData.writeByte(0); // no filter
        /* istanbul ignore else */
        if (depth === 8) {
          offset = writeDataBytes(data, newData, slotsPerLine, offset);
        } else if (depth === 16) {
          offset = writeDataUint16(data, newData, slotsPerLine, offset);
        } else {
          throw new Error('unreachable');
        }
      }
      const buffer = newData.toArray();
      const compressed = deflate_1(buffer, this._zlibOptions);
      this.encodeIDAT(compressed);
    }
    _checkData(data) {
      const {
        colorType,
        channels,
        depth
      } = getColorType(data);
      const png = {
        width: checkInteger(data.width, 'width'),
        height: checkInteger(data.height, 'height'),
        channels,
        data: data.data,
        depth,
        text: data.text
      };
      this._colorType = colorType;
      const expectedSize = png.width * png.height * channels;
      if (png.data.length !== expectedSize) {
        throw new RangeError(`wrong data size. Found ${png.data.length}, expected ${expectedSize}`);
      }
      return png;
    }
  }
  function checkInteger(value, name) {
    if (Number.isInteger(value) && value > 0) {
      return value;
    }
    throw new TypeError(`${name} must be a positive integer`);
  }
  function getColorType(data) {
    const {
      channels = 4,
      depth = 8
    } = data;
    if (channels !== 4 && channels !== 3 && channels !== 2 && channels !== 1) {
      throw new RangeError(`unsupported number of channels: ${channels}`);
    }
    if (depth !== 8 && depth !== 16) {
      throw new RangeError(`unsupported bit depth: ${depth}`);
    }
    const returnValue = {
      channels,
      depth,
      colorType: ColorType.UNKNOWN
    };
    switch (channels) {
      case 4:
        returnValue.colorType = ColorType.TRUECOLOUR_ALPHA;
        break;
      case 3:
        returnValue.colorType = ColorType.TRUECOLOUR;
        break;
      case 1:
        returnValue.colorType = ColorType.GREYSCALE;
        break;
      case 2:
        returnValue.colorType = ColorType.GREYSCALE_ALPHA;
        break;
      default:
        throw new Error('unsupported number of channels');
    }
    return returnValue;
  }
  function writeDataBytes(data, newData, slotsPerLine, offset) {
    for (let j = 0; j < slotsPerLine; j++) {
      newData.writeByte(data[offset++]);
    }
    return offset;
  }
  function writeDataUint16(data, newData, slotsPerLine, offset) {
    for (let j = 0; j < slotsPerLine; j++) {
      newData.writeUint16(data[offset++]);
    }
    return offset;
  }

  function decodePng(data, options) {
    const decoder = new PngDecoder(data, options);
    return decoder.decode();
  }
  function encodePng$1(png, options) {
    const encoder = new PngEncoder(png, options);
    return encoder.encode();
  }

  var encoder = {exports: {}};

  /*
    Copyright (c) 2008, Adobe Systems Incorporated
    All rights reserved.

    Redistribution and use in source and binary forms, with or without 
    modification, are permitted provided that the following conditions are
    met:

    * Redistributions of source code must retain the above copyright notice, 
      this list of conditions and the following disclaimer.
    
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the 
      documentation and/or other materials provided with the distribution.
    
    * Neither the name of Adobe Systems Incorporated nor the names of its 
      contributors may be used to endorse or promote products derived from 
      this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
    IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
    THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
    CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
  (function (module) {
    function JPEGEncoder(quality) {
      var ffloor = Math.floor;
      var YTable = new Array(64);
      var UVTable = new Array(64);
      var fdtbl_Y = new Array(64);
      var fdtbl_UV = new Array(64);
      var YDC_HT;
      var UVDC_HT;
      var YAC_HT;
      var UVAC_HT;
      var bitcode = new Array(65535);
      var category = new Array(65535);
      var outputfDCTQuant = new Array(64);
      var DU = new Array(64);
      var byteout = [];
      var bytenew = 0;
      var bytepos = 7;
      var YDU = new Array(64);
      var UDU = new Array(64);
      var VDU = new Array(64);
      var clt = new Array(256);
      var RGB_YUV_TABLE = new Array(2048);
      var currentQuality;
      var ZigZag = [0, 1, 5, 6, 14, 15, 27, 28, 2, 4, 7, 13, 16, 26, 29, 42, 3, 8, 12, 17, 25, 30, 41, 43, 9, 11, 18, 24, 31, 40, 44, 53, 10, 19, 23, 32, 39, 45, 52, 54, 20, 22, 33, 38, 46, 51, 55, 60, 21, 34, 37, 47, 50, 56, 59, 61, 35, 36, 48, 49, 57, 58, 62, 63];
      var std_dc_luminance_nrcodes = [0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0];
      var std_dc_luminance_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
      var std_ac_luminance_nrcodes = [0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d];
      var std_ac_luminance_values = [0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa];
      var std_dc_chrominance_nrcodes = [0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0];
      var std_dc_chrominance_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
      var std_ac_chrominance_nrcodes = [0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77];
      var std_ac_chrominance_values = [0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa];
      function initQuantTables(sf) {
        var YQT = [16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, 51, 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, 49, 64, 78, 87, 103, 121, 120, 101, 72, 92, 95, 98, 112, 100, 103, 99];
        for (var i = 0; i < 64; i++) {
          var t = ffloor((YQT[i] * sf + 50) / 100);
          if (t < 1) {
            t = 1;
          } else if (t > 255) {
            t = 255;
          }
          YTable[ZigZag[i]] = t;
        }
        var UVQT = [17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99];
        for (var j = 0; j < 64; j++) {
          var u = ffloor((UVQT[j] * sf + 50) / 100);
          if (u < 1) {
            u = 1;
          } else if (u > 255) {
            u = 255;
          }
          UVTable[ZigZag[j]] = u;
        }
        var aasf = [1.0, 1.387039845, 1.306562965, 1.175875602, 1.0, 0.785694958, 0.541196100, 0.275899379];
        var k = 0;
        for (var row = 0; row < 8; row++) {
          for (var col = 0; col < 8; col++) {
            fdtbl_Y[k] = 1.0 / (YTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0);
            fdtbl_UV[k] = 1.0 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0);
            k++;
          }
        }
      }
      function computeHuffmanTbl(nrcodes, std_table) {
        var codevalue = 0;
        var pos_in_table = 0;
        var HT = new Array();
        for (var k = 1; k <= 16; k++) {
          for (var j = 1; j <= nrcodes[k]; j++) {
            HT[std_table[pos_in_table]] = [];
            HT[std_table[pos_in_table]][0] = codevalue;
            HT[std_table[pos_in_table]][1] = k;
            pos_in_table++;
            codevalue++;
          }
          codevalue *= 2;
        }
        return HT;
      }
      function initHuffmanTbl() {
        YDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes, std_dc_luminance_values);
        UVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes, std_dc_chrominance_values);
        YAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes, std_ac_luminance_values);
        UVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes, std_ac_chrominance_values);
      }
      function initCategoryNumber() {
        var nrlower = 1;
        var nrupper = 2;
        for (var cat = 1; cat <= 15; cat++) {
          //Positive numbers
          for (var nr = nrlower; nr < nrupper; nr++) {
            category[32767 + nr] = cat;
            bitcode[32767 + nr] = [];
            bitcode[32767 + nr][1] = cat;
            bitcode[32767 + nr][0] = nr;
          }
          //Negative numbers
          for (var nrneg = -(nrupper - 1); nrneg <= -nrlower; nrneg++) {
            category[32767 + nrneg] = cat;
            bitcode[32767 + nrneg] = [];
            bitcode[32767 + nrneg][1] = cat;
            bitcode[32767 + nrneg][0] = nrupper - 1 + nrneg;
          }
          nrlower <<= 1;
          nrupper <<= 1;
        }
      }
      function initRGBYUVTable() {
        for (var i = 0; i < 256; i++) {
          RGB_YUV_TABLE[i] = 19595 * i;
          RGB_YUV_TABLE[i + 256 >> 0] = 38470 * i;
          RGB_YUV_TABLE[i + 512 >> 0] = 7471 * i + 0x8000;
          RGB_YUV_TABLE[i + 768 >> 0] = -11059 * i;
          RGB_YUV_TABLE[i + 1024 >> 0] = -21709 * i;
          RGB_YUV_TABLE[i + 1280 >> 0] = 32768 * i + 0x807FFF;
          RGB_YUV_TABLE[i + 1536 >> 0] = -27439 * i;
          RGB_YUV_TABLE[i + 1792 >> 0] = -5329 * i;
        }
      }

      // IO functions
      function writeBits(bs) {
        var value = bs[0];
        var posval = bs[1] - 1;
        while (posval >= 0) {
          if (value & 1 << posval) {
            bytenew |= 1 << bytepos;
          }
          posval--;
          bytepos--;
          if (bytepos < 0) {
            if (bytenew == 0xFF) {
              writeByte(0xFF);
              writeByte(0);
            } else {
              writeByte(bytenew);
            }
            bytepos = 7;
            bytenew = 0;
          }
        }
      }
      function writeByte(value) {
        //byteout.push(clt[value]); // write char directly instead of converting later
        byteout.push(value);
      }
      function writeWord(value) {
        writeByte(value >> 8 & 0xFF);
        writeByte(value & 0xFF);
      }

      // DCT & quantization core
      function fDCTQuant(data, fdtbl) {
        var d0, d1, d2, d3, d4, d5, d6, d7;
        /* Pass 1: process rows. */
        var dataOff = 0;
        var i;
        var I8 = 8;
        var I64 = 64;
        for (i = 0; i < I8; ++i) {
          d0 = data[dataOff];
          d1 = data[dataOff + 1];
          d2 = data[dataOff + 2];
          d3 = data[dataOff + 3];
          d4 = data[dataOff + 4];
          d5 = data[dataOff + 5];
          d6 = data[dataOff + 6];
          d7 = data[dataOff + 7];
          var tmp0 = d0 + d7;
          var tmp7 = d0 - d7;
          var tmp1 = d1 + d6;
          var tmp6 = d1 - d6;
          var tmp2 = d2 + d5;
          var tmp5 = d2 - d5;
          var tmp3 = d3 + d4;
          var tmp4 = d3 - d4;

          /* Even part */
          var tmp10 = tmp0 + tmp3; /* phase 2 */
          var tmp13 = tmp0 - tmp3;
          var tmp11 = tmp1 + tmp2;
          var tmp12 = tmp1 - tmp2;
          data[dataOff] = tmp10 + tmp11; /* phase 3 */
          data[dataOff + 4] = tmp10 - tmp11;
          var z1 = (tmp12 + tmp13) * 0.707106781; /* c4 */
          data[dataOff + 2] = tmp13 + z1; /* phase 5 */
          data[dataOff + 6] = tmp13 - z1;

          /* Odd part */
          tmp10 = tmp4 + tmp5; /* phase 2 */
          tmp11 = tmp5 + tmp6;
          tmp12 = tmp6 + tmp7;

          /* The rotator is modified from fig 4-8 to avoid extra negations. */
          var z5 = (tmp10 - tmp12) * 0.382683433; /* c6 */
          var z2 = 0.541196100 * tmp10 + z5; /* c2-c6 */
          var z4 = 1.306562965 * tmp12 + z5; /* c2+c6 */
          var z3 = tmp11 * 0.707106781; /* c4 */

          var z11 = tmp7 + z3; /* phase 5 */
          var z13 = tmp7 - z3;
          data[dataOff + 5] = z13 + z2; /* phase 6 */
          data[dataOff + 3] = z13 - z2;
          data[dataOff + 1] = z11 + z4;
          data[dataOff + 7] = z11 - z4;
          dataOff += 8; /* advance pointer to next row */
        }

        /* Pass 2: process columns. */
        dataOff = 0;
        for (i = 0; i < I8; ++i) {
          d0 = data[dataOff];
          d1 = data[dataOff + 8];
          d2 = data[dataOff + 16];
          d3 = data[dataOff + 24];
          d4 = data[dataOff + 32];
          d5 = data[dataOff + 40];
          d6 = data[dataOff + 48];
          d7 = data[dataOff + 56];
          var tmp0p2 = d0 + d7;
          var tmp7p2 = d0 - d7;
          var tmp1p2 = d1 + d6;
          var tmp6p2 = d1 - d6;
          var tmp2p2 = d2 + d5;
          var tmp5p2 = d2 - d5;
          var tmp3p2 = d3 + d4;
          var tmp4p2 = d3 - d4;

          /* Even part */
          var tmp10p2 = tmp0p2 + tmp3p2; /* phase 2 */
          var tmp13p2 = tmp0p2 - tmp3p2;
          var tmp11p2 = tmp1p2 + tmp2p2;
          var tmp12p2 = tmp1p2 - tmp2p2;
          data[dataOff] = tmp10p2 + tmp11p2; /* phase 3 */
          data[dataOff + 32] = tmp10p2 - tmp11p2;
          var z1p2 = (tmp12p2 + tmp13p2) * 0.707106781; /* c4 */
          data[dataOff + 16] = tmp13p2 + z1p2; /* phase 5 */
          data[dataOff + 48] = tmp13p2 - z1p2;

          /* Odd part */
          tmp10p2 = tmp4p2 + tmp5p2; /* phase 2 */
          tmp11p2 = tmp5p2 + tmp6p2;
          tmp12p2 = tmp6p2 + tmp7p2;

          /* The rotator is modified from fig 4-8 to avoid extra negations. */
          var z5p2 = (tmp10p2 - tmp12p2) * 0.382683433; /* c6 */
          var z2p2 = 0.541196100 * tmp10p2 + z5p2; /* c2-c6 */
          var z4p2 = 1.306562965 * tmp12p2 + z5p2; /* c2+c6 */
          var z3p2 = tmp11p2 * 0.707106781; /* c4 */

          var z11p2 = tmp7p2 + z3p2; /* phase 5 */
          var z13p2 = tmp7p2 - z3p2;
          data[dataOff + 40] = z13p2 + z2p2; /* phase 6 */
          data[dataOff + 24] = z13p2 - z2p2;
          data[dataOff + 8] = z11p2 + z4p2;
          data[dataOff + 56] = z11p2 - z4p2;
          dataOff++; /* advance pointer to next column */
        }

        // Quantize/descale the coefficients
        var fDCTQuant;
        for (i = 0; i < I64; ++i) {
          // Apply the quantization and scaling factor & Round to nearest integer
          fDCTQuant = data[i] * fdtbl[i];
          outputfDCTQuant[i] = fDCTQuant > 0.0 ? fDCTQuant + 0.5 | 0 : fDCTQuant - 0.5 | 0;
          //outputfDCTQuant[i] = fround(fDCTQuant);
        }
        return outputfDCTQuant;
      }
      function writeAPP0() {
        writeWord(0xFFE0); // marker
        writeWord(16); // length
        writeByte(0x4A); // J
        writeByte(0x46); // F
        writeByte(0x49); // I
        writeByte(0x46); // F
        writeByte(0); // = "JFIF",'\0'
        writeByte(1); // versionhi
        writeByte(1); // versionlo
        writeByte(0); // xyunits
        writeWord(1); // xdensity
        writeWord(1); // ydensity
        writeByte(0); // thumbnwidth
        writeByte(0); // thumbnheight
      }
      function writeAPP1(exifBuffer) {
        if (!exifBuffer) return;
        writeWord(0xFFE1); // APP1 marker

        if (exifBuffer[0] === 0x45 && exifBuffer[1] === 0x78 && exifBuffer[2] === 0x69 && exifBuffer[3] === 0x66) {
          // Buffer already starts with EXIF, just use it directly
          writeWord(exifBuffer.length + 2); // length is buffer + length itself!
        } else {
          // Buffer doesn't start with EXIF, write it for them
          writeWord(exifBuffer.length + 5 + 2); // length is buffer + EXIF\0 + length itself!
          writeByte(0x45); // E
          writeByte(0x78); // X
          writeByte(0x69); // I
          writeByte(0x66); // F
          writeByte(0); // = "EXIF",'\0'
        }
        for (var i = 0; i < exifBuffer.length; i++) {
          writeByte(exifBuffer[i]);
        }
      }
      function writeSOF0(width, height) {
        writeWord(0xFFC0); // marker
        writeWord(17); // length, truecolor YUV JPG
        writeByte(8); // precision
        writeWord(height);
        writeWord(width);
        writeByte(3); // nrofcomponents
        writeByte(1); // IdY
        writeByte(0x11); // HVY
        writeByte(0); // QTY
        writeByte(2); // IdU
        writeByte(0x11); // HVU
        writeByte(1); // QTU
        writeByte(3); // IdV
        writeByte(0x11); // HVV
        writeByte(1); // QTV
      }
      function writeDQT() {
        writeWord(0xFFDB); // marker
        writeWord(132); // length
        writeByte(0);
        for (var i = 0; i < 64; i++) {
          writeByte(YTable[i]);
        }
        writeByte(1);
        for (var j = 0; j < 64; j++) {
          writeByte(UVTable[j]);
        }
      }
      function writeDHT() {
        writeWord(0xFFC4); // marker
        writeWord(0x01A2); // length

        writeByte(0); // HTYDCinfo
        for (var i = 0; i < 16; i++) {
          writeByte(std_dc_luminance_nrcodes[i + 1]);
        }
        for (var j = 0; j <= 11; j++) {
          writeByte(std_dc_luminance_values[j]);
        }
        writeByte(0x10); // HTYACinfo
        for (var k = 0; k < 16; k++) {
          writeByte(std_ac_luminance_nrcodes[k + 1]);
        }
        for (var l = 0; l <= 161; l++) {
          writeByte(std_ac_luminance_values[l]);
        }
        writeByte(1); // HTUDCinfo
        for (var m = 0; m < 16; m++) {
          writeByte(std_dc_chrominance_nrcodes[m + 1]);
        }
        for (var n = 0; n <= 11; n++) {
          writeByte(std_dc_chrominance_values[n]);
        }
        writeByte(0x11); // HTUACinfo
        for (var o = 0; o < 16; o++) {
          writeByte(std_ac_chrominance_nrcodes[o + 1]);
        }
        for (var p = 0; p <= 161; p++) {
          writeByte(std_ac_chrominance_values[p]);
        }
      }
      function writeCOM(comments) {
        if (typeof comments === "undefined" || comments.constructor !== Array) return;
        comments.forEach(e => {
          if (typeof e !== "string") return;
          writeWord(0xFFFE); // marker
          var l = e.length;
          writeWord(l + 2); // length itself as well
          var i;
          for (i = 0; i < l; i++) writeByte(e.charCodeAt(i));
        });
      }
      function writeSOS() {
        writeWord(0xFFDA); // marker
        writeWord(12); // length
        writeByte(3); // nrofcomponents
        writeByte(1); // IdY
        writeByte(0); // HTY
        writeByte(2); // IdU
        writeByte(0x11); // HTU
        writeByte(3); // IdV
        writeByte(0x11); // HTV
        writeByte(0); // Ss
        writeByte(0x3f); // Se
        writeByte(0); // Bf
      }
      function processDU(CDU, fdtbl, DC, HTDC, HTAC) {
        var EOB = HTAC[0x00];
        var M16zeroes = HTAC[0xF0];
        var pos;
        var I16 = 16;
        var I63 = 63;
        var I64 = 64;
        var DU_DCT = fDCTQuant(CDU, fdtbl);
        //ZigZag reorder
        for (var j = 0; j < I64; ++j) {
          DU[ZigZag[j]] = DU_DCT[j];
        }
        var Diff = DU[0] - DC;
        DC = DU[0];
        //Encode DC
        if (Diff == 0) {
          writeBits(HTDC[0]); // Diff might be 0
        } else {
          pos = 32767 + Diff;
          writeBits(HTDC[category[pos]]);
          writeBits(bitcode[pos]);
        }
        //Encode ACs
        var end0pos = 63; // was const... which is crazy
        for (; end0pos > 0 && DU[end0pos] == 0; end0pos--) {}
        //end0pos = first element in reverse order !=0
        if (end0pos == 0) {
          writeBits(EOB);
          return DC;
        }
        var i = 1;
        var lng;
        while (i <= end0pos) {
          var startpos = i;
          for (; DU[i] == 0 && i <= end0pos; ++i) {}
          var nrzeroes = i - startpos;
          if (nrzeroes >= I16) {
            lng = nrzeroes >> 4;
            for (var nrmarker = 1; nrmarker <= lng; ++nrmarker) writeBits(M16zeroes);
            nrzeroes = nrzeroes & 0xF;
          }
          pos = 32767 + DU[i];
          writeBits(HTAC[(nrzeroes << 4) + category[pos]]);
          writeBits(bitcode[pos]);
          i++;
        }
        if (end0pos != I63) {
          writeBits(EOB);
        }
        return DC;
      }
      function initCharLookupTable() {
        var sfcc = String.fromCharCode;
        for (var i = 0; i < 256; i++) {
          ///// ACHTUNG // 255
          clt[i] = sfcc(i);
        }
      }
      this.encode = function (image, quality)
      // image data object
      {
        new Date().getTime();
        if (quality) setQuality(quality);

        // Initialize bit writer
        byteout = new Array();
        bytenew = 0;
        bytepos = 7;

        // Add JPEG headers
        writeWord(0xFFD8); // SOI
        writeAPP0();
        writeCOM(image.comments);
        writeAPP1(image.exifBuffer);
        writeDQT();
        writeSOF0(image.width, image.height);
        writeDHT();
        writeSOS();

        // Encode 8x8 macroblocks
        var DCY = 0;
        var DCU = 0;
        var DCV = 0;
        bytenew = 0;
        bytepos = 7;
        this.encode.displayName = "_encode_";
        var imageData = image.data;
        var width = image.width;
        var height = image.height;
        var quadWidth = width * 4;
        var x,
          y = 0;
        var r, g, b;
        var start, p, col, row, pos;
        while (y < height) {
          x = 0;
          while (x < quadWidth) {
            start = quadWidth * y + x;
            p = start;
            col = -1;
            row = 0;
            for (pos = 0; pos < 64; pos++) {
              row = pos >> 3; // /8
              col = (pos & 7) * 4; // %8
              p = start + row * quadWidth + col;
              if (y + row >= height) {
                // padding bottom
                p -= quadWidth * (y + 1 + row - height);
              }
              if (x + col >= quadWidth) {
                // padding right	
                p -= x + col - quadWidth + 4;
              }
              r = imageData[p++];
              g = imageData[p++];
              b = imageData[p++];

              /* // calculate YUV values dynamically
              YDU[pos]=((( 0.29900)*r+( 0.58700)*g+( 0.11400)*b))-128; //-0x80
              UDU[pos]=(((-0.16874)*r+(-0.33126)*g+( 0.50000)*b));
              VDU[pos]=((( 0.50000)*r+(-0.41869)*g+(-0.08131)*b));
              */

              // use lookup table (slightly faster)
              YDU[pos] = (RGB_YUV_TABLE[r] + RGB_YUV_TABLE[g + 256 >> 0] + RGB_YUV_TABLE[b + 512 >> 0] >> 16) - 128;
              UDU[pos] = (RGB_YUV_TABLE[r + 768 >> 0] + RGB_YUV_TABLE[g + 1024 >> 0] + RGB_YUV_TABLE[b + 1280 >> 0] >> 16) - 128;
              VDU[pos] = (RGB_YUV_TABLE[r + 1280 >> 0] + RGB_YUV_TABLE[g + 1536 >> 0] + RGB_YUV_TABLE[b + 1792 >> 0] >> 16) - 128;
            }
            DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT);
            DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);
            DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);
            x += 32;
          }
          y += 8;
        }

        ////////////////////////////////////////////////////////////////

        // Do the bit alignment of the EOI marker
        if (bytepos >= 0) {
          var fillbits = [];
          fillbits[1] = bytepos + 1;
          fillbits[0] = (1 << bytepos + 1) - 1;
          writeBits(fillbits);
        }
        writeWord(0xFFD9); //EOI
        return Buffer.from(byteout);
      };
      function setQuality(quality) {
        if (quality <= 0) {
          quality = 1;
        }
        if (quality > 100) {
          quality = 100;
        }
        if (currentQuality == quality) return; // don't recalc if unchanged

        var sf = 0;
        if (quality < 50) {
          sf = Math.floor(5000 / quality);
        } else {
          sf = Math.floor(200 - quality * 2);
        }
        initQuantTables(sf);
        currentQuality = quality;
        //console.log('Quality set to: '+quality +'%');
      }
      function init() {
        var time_start = new Date().getTime();
        if (!quality) quality = 50;
        // Create tables
        initCharLookupTable();
        initHuffmanTbl();
        initCategoryNumber();
        initRGBYUVTable();
        setQuality(quality);
        new Date().getTime() - time_start;
        //console.log('Initialization '+ duration + 'ms');
      }
      init();
    }
    {
      module.exports = encode;
    }
    function encode(imgData, qu) {
      if (typeof qu === 'undefined') qu = 50;
      var encoder = new JPEGEncoder(qu);
      var data = encoder.encode(imgData, qu);
      return {
        data: data,
        width: imgData.width,
        height: imgData.height
      };
    }
  })(encoder);
  var encoderExports = encoder.exports;

  var decoder = {exports: {}};

  /* -*- tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /
  /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
  (function (module) {
    /*
       Copyright 2011 notmasteryet
    	   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.
    */

    // - The JPEG specification can be found in the ITU CCITT Recommendation T.81
    //   (www.w3.org/Graphics/JPEG/itu-t81.pdf)
    // - The JFIF specification can be found in the JPEG File Interchange Format
    //   (www.w3.org/Graphics/JPEG/jfif3.pdf)
    // - The Adobe Application-Specific JPEG markers in the Supporting the DCT Filters
    //   in PostScript Level 2, Technical Note #5116
    //   (partners.adobe.com/public/developer/en/ps/sdk/5116.DCT_Filter.pdf)

    var JpegImage = function jpegImage() {

      var dctZigZag = new Int32Array([0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63]);
      var dctCos1 = 4017; // cos(pi/16)
      var dctSin1 = 799; // sin(pi/16)
      var dctCos3 = 3406; // cos(3*pi/16)
      var dctSin3 = 2276; // sin(3*pi/16)
      var dctCos6 = 1567; // cos(6*pi/16)
      var dctSin6 = 3784; // sin(6*pi/16)
      var dctSqrt2 = 5793; // sqrt(2)
      var dctSqrt1d2 = 2896; // sqrt(2) / 2

      function constructor() {}
      function buildHuffmanTable(codeLengths, values) {
        var k = 0,
          code = [],
          i,
          j,
          length = 16;
        while (length > 0 && !codeLengths[length - 1]) length--;
        code.push({
          children: [],
          index: 0
        });
        var p = code[0],
          q;
        for (i = 0; i < length; i++) {
          for (j = 0; j < codeLengths[i]; j++) {
            p = code.pop();
            p.children[p.index] = values[k];
            while (p.index > 0) {
              if (code.length === 0) throw new Error('Could not recreate Huffman Table');
              p = code.pop();
            }
            p.index++;
            code.push(p);
            while (code.length <= i) {
              code.push(q = {
                children: [],
                index: 0
              });
              p.children[p.index] = q.children;
              p = q;
            }
            k++;
          }
          if (i + 1 < length) {
            // p here points to last code
            code.push(q = {
              children: [],
              index: 0
            });
            p.children[p.index] = q.children;
            p = q;
          }
        }
        return code[0].children;
      }
      function decodeScan(data, offset, frame, components, resetInterval, spectralStart, spectralEnd, successivePrev, successive, opts) {
        frame.precision;
        frame.samplesPerLine;
        frame.scanLines;
        var mcusPerLine = frame.mcusPerLine;
        var progressive = frame.progressive;
        frame.maxH;
          frame.maxV;
        var startOffset = offset,
          bitsData = 0,
          bitsCount = 0;
        function readBit() {
          if (bitsCount > 0) {
            bitsCount--;
            return bitsData >> bitsCount & 1;
          }
          bitsData = data[offset++];
          if (bitsData == 0xFF) {
            var nextByte = data[offset++];
            if (nextByte) {
              throw new Error("unexpected marker: " + (bitsData << 8 | nextByte).toString(16));
            }
            // unstuff 0
          }
          bitsCount = 7;
          return bitsData >>> 7;
        }
        function decodeHuffman(tree) {
          var node = tree,
            bit;
          while ((bit = readBit()) !== null) {
            node = node[bit];
            if (typeof node === 'number') return node;
            if (typeof node !== 'object') throw new Error("invalid huffman sequence");
          }
          return null;
        }
        function receive(length) {
          var n = 0;
          while (length > 0) {
            var bit = readBit();
            if (bit === null) return;
            n = n << 1 | bit;
            length--;
          }
          return n;
        }
        function receiveAndExtend(length) {
          var n = receive(length);
          if (n >= 1 << length - 1) return n;
          return n + (-1 << length) + 1;
        }
        function decodeBaseline(component, zz) {
          var t = decodeHuffman(component.huffmanTableDC);
          var diff = t === 0 ? 0 : receiveAndExtend(t);
          zz[0] = component.pred += diff;
          var k = 1;
          while (k < 64) {
            var rs = decodeHuffman(component.huffmanTableAC);
            var s = rs & 15,
              r = rs >> 4;
            if (s === 0) {
              if (r < 15) break;
              k += 16;
              continue;
            }
            k += r;
            var z = dctZigZag[k];
            zz[z] = receiveAndExtend(s);
            k++;
          }
        }
        function decodeDCFirst(component, zz) {
          var t = decodeHuffman(component.huffmanTableDC);
          var diff = t === 0 ? 0 : receiveAndExtend(t) << successive;
          zz[0] = component.pred += diff;
        }
        function decodeDCSuccessive(component, zz) {
          zz[0] |= readBit() << successive;
        }
        var eobrun = 0;
        function decodeACFirst(component, zz) {
          if (eobrun > 0) {
            eobrun--;
            return;
          }
          var k = spectralStart,
            e = spectralEnd;
          while (k <= e) {
            var rs = decodeHuffman(component.huffmanTableAC);
            var s = rs & 15,
              r = rs >> 4;
            if (s === 0) {
              if (r < 15) {
                eobrun = receive(r) + (1 << r) - 1;
                break;
              }
              k += 16;
              continue;
            }
            k += r;
            var z = dctZigZag[k];
            zz[z] = receiveAndExtend(s) * (1 << successive);
            k++;
          }
        }
        var successiveACState = 0,
          successiveACNextValue;
        function decodeACSuccessive(component, zz) {
          var k = spectralStart,
            e = spectralEnd,
            r = 0;
          while (k <= e) {
            var z = dctZigZag[k];
            var direction = zz[z] < 0 ? -1 : 1;
            switch (successiveACState) {
              case 0:
                // initial state
                var rs = decodeHuffman(component.huffmanTableAC);
                var s = rs & 15,
                  r = rs >> 4;
                if (s === 0) {
                  if (r < 15) {
                    eobrun = receive(r) + (1 << r);
                    successiveACState = 4;
                  } else {
                    r = 16;
                    successiveACState = 1;
                  }
                } else {
                  if (s !== 1) throw new Error("invalid ACn encoding");
                  successiveACNextValue = receiveAndExtend(s);
                  successiveACState = r ? 2 : 3;
                }
                continue;
              case 1: // skipping r zero items
              case 2:
                if (zz[z]) zz[z] += (readBit() << successive) * direction;else {
                  r--;
                  if (r === 0) successiveACState = successiveACState == 2 ? 3 : 0;
                }
                break;
              case 3:
                // set value for a zero item
                if (zz[z]) zz[z] += (readBit() << successive) * direction;else {
                  zz[z] = successiveACNextValue << successive;
                  successiveACState = 0;
                }
                break;
              case 4:
                // eob
                if (zz[z]) zz[z] += (readBit() << successive) * direction;
                break;
            }
            k++;
          }
          if (successiveACState === 4) {
            eobrun--;
            if (eobrun === 0) successiveACState = 0;
          }
        }
        function decodeMcu(component, decode, mcu, row, col) {
          var mcuRow = mcu / mcusPerLine | 0;
          var mcuCol = mcu % mcusPerLine;
          var blockRow = mcuRow * component.v + row;
          var blockCol = mcuCol * component.h + col;
          // If the block is missing and we're in tolerant mode, just skip it.
          if (component.blocks[blockRow] === undefined && opts.tolerantDecoding) return;
          decode(component, component.blocks[blockRow][blockCol]);
        }
        function decodeBlock(component, decode, mcu) {
          var blockRow = mcu / component.blocksPerLine | 0;
          var blockCol = mcu % component.blocksPerLine;
          // If the block is missing and we're in tolerant mode, just skip it.
          if (component.blocks[blockRow] === undefined && opts.tolerantDecoding) return;
          decode(component, component.blocks[blockRow][blockCol]);
        }
        var componentsLength = components.length;
        var component, i, j, k, n;
        var decodeFn;
        if (progressive) {
          if (spectralStart === 0) decodeFn = successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive;else decodeFn = successivePrev === 0 ? decodeACFirst : decodeACSuccessive;
        } else {
          decodeFn = decodeBaseline;
        }
        var mcu = 0,
          marker;
        var mcuExpected;
        if (componentsLength == 1) {
          mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn;
        } else {
          mcuExpected = mcusPerLine * frame.mcusPerColumn;
        }
        if (!resetInterval) resetInterval = mcuExpected;
        var h, v;
        while (mcu < mcuExpected) {
          // reset interval stuff
          for (i = 0; i < componentsLength; i++) components[i].pred = 0;
          eobrun = 0;
          if (componentsLength == 1) {
            component = components[0];
            for (n = 0; n < resetInterval; n++) {
              decodeBlock(component, decodeFn, mcu);
              mcu++;
            }
          } else {
            for (n = 0; n < resetInterval; n++) {
              for (i = 0; i < componentsLength; i++) {
                component = components[i];
                h = component.h;
                v = component.v;
                for (j = 0; j < v; j++) {
                  for (k = 0; k < h; k++) {
                    decodeMcu(component, decodeFn, mcu, j, k);
                  }
                }
              }
              mcu++;

              // If we've reached our expected MCU's, stop decoding
              if (mcu === mcuExpected) break;
            }
          }
          if (mcu === mcuExpected) {
            // Skip trailing bytes at the end of the scan - until we reach the next marker
            do {
              if (data[offset] === 0xFF) {
                if (data[offset + 1] !== 0x00) {
                  break;
                }
              }
              offset += 1;
            } while (offset < data.length - 2);
          }

          // find marker
          bitsCount = 0;
          marker = data[offset] << 8 | data[offset + 1];
          if (marker < 0xFF00) {
            throw new Error("marker was not found");
          }
          if (marker >= 0xFFD0 && marker <= 0xFFD7) {
            // RSTx
            offset += 2;
          } else break;
        }
        return offset - startOffset;
      }
      function buildComponentData(frame, component) {
        var lines = [];
        var blocksPerLine = component.blocksPerLine;
        var blocksPerColumn = component.blocksPerColumn;
        var samplesPerLine = blocksPerLine << 3;
        // Only 1 used per invocation of this function and garbage collected after invocation, so no need to account for its memory footprint.
        var R = new Int32Array(64),
          r = new Uint8Array(64);

        // A port of poppler's IDCT method which in turn is taken from:
        //   Christoph Loeffler, Adriaan Ligtenberg, George S. Moschytz,
        //   "Practical Fast 1-D DCT Algorithms with 11 Multiplications",
        //   IEEE Intl. Conf. on Acoustics, Speech & Signal Processing, 1989,
        //   988-991.
        function quantizeAndInverse(zz, dataOut, dataIn) {
          var qt = component.quantizationTable;
          var v0, v1, v2, v3, v4, v5, v6, v7, t;
          var p = dataIn;
          var i;

          // dequant
          for (i = 0; i < 64; i++) p[i] = zz[i] * qt[i];

          // inverse DCT on rows
          for (i = 0; i < 8; ++i) {
            var row = 8 * i;

            // check for all-zero AC coefficients
            if (p[1 + row] == 0 && p[2 + row] == 0 && p[3 + row] == 0 && p[4 + row] == 0 && p[5 + row] == 0 && p[6 + row] == 0 && p[7 + row] == 0) {
              t = dctSqrt2 * p[0 + row] + 512 >> 10;
              p[0 + row] = t;
              p[1 + row] = t;
              p[2 + row] = t;
              p[3 + row] = t;
              p[4 + row] = t;
              p[5 + row] = t;
              p[6 + row] = t;
              p[7 + row] = t;
              continue;
            }

            // stage 4
            v0 = dctSqrt2 * p[0 + row] + 128 >> 8;
            v1 = dctSqrt2 * p[4 + row] + 128 >> 8;
            v2 = p[2 + row];
            v3 = p[6 + row];
            v4 = dctSqrt1d2 * (p[1 + row] - p[7 + row]) + 128 >> 8;
            v7 = dctSqrt1d2 * (p[1 + row] + p[7 + row]) + 128 >> 8;
            v5 = p[3 + row] << 4;
            v6 = p[5 + row] << 4;

            // stage 3
            t = v0 - v1 + 1 >> 1;
            v0 = v0 + v1 + 1 >> 1;
            v1 = t;
            t = v2 * dctSin6 + v3 * dctCos6 + 128 >> 8;
            v2 = v2 * dctCos6 - v3 * dctSin6 + 128 >> 8;
            v3 = t;
            t = v4 - v6 + 1 >> 1;
            v4 = v4 + v6 + 1 >> 1;
            v6 = t;
            t = v7 + v5 + 1 >> 1;
            v5 = v7 - v5 + 1 >> 1;
            v7 = t;

            // stage 2
            t = v0 - v3 + 1 >> 1;
            v0 = v0 + v3 + 1 >> 1;
            v3 = t;
            t = v1 - v2 + 1 >> 1;
            v1 = v1 + v2 + 1 >> 1;
            v2 = t;
            t = v4 * dctSin3 + v7 * dctCos3 + 2048 >> 12;
            v4 = v4 * dctCos3 - v7 * dctSin3 + 2048 >> 12;
            v7 = t;
            t = v5 * dctSin1 + v6 * dctCos1 + 2048 >> 12;
            v5 = v5 * dctCos1 - v6 * dctSin1 + 2048 >> 12;
            v6 = t;

            // stage 1
            p[0 + row] = v0 + v7;
            p[7 + row] = v0 - v7;
            p[1 + row] = v1 + v6;
            p[6 + row] = v1 - v6;
            p[2 + row] = v2 + v5;
            p[5 + row] = v2 - v5;
            p[3 + row] = v3 + v4;
            p[4 + row] = v3 - v4;
          }

          // inverse DCT on columns
          for (i = 0; i < 8; ++i) {
            var col = i;

            // check for all-zero AC coefficients
            if (p[1 * 8 + col] == 0 && p[2 * 8 + col] == 0 && p[3 * 8 + col] == 0 && p[4 * 8 + col] == 0 && p[5 * 8 + col] == 0 && p[6 * 8 + col] == 0 && p[7 * 8 + col] == 0) {
              t = dctSqrt2 * dataIn[i + 0] + 8192 >> 14;
              p[0 * 8 + col] = t;
              p[1 * 8 + col] = t;
              p[2 * 8 + col] = t;
              p[3 * 8 + col] = t;
              p[4 * 8 + col] = t;
              p[5 * 8 + col] = t;
              p[6 * 8 + col] = t;
              p[7 * 8 + col] = t;
              continue;
            }

            // stage 4
            v0 = dctSqrt2 * p[0 * 8 + col] + 2048 >> 12;
            v1 = dctSqrt2 * p[4 * 8 + col] + 2048 >> 12;
            v2 = p[2 * 8 + col];
            v3 = p[6 * 8 + col];
            v4 = dctSqrt1d2 * (p[1 * 8 + col] - p[7 * 8 + col]) + 2048 >> 12;
            v7 = dctSqrt1d2 * (p[1 * 8 + col] + p[7 * 8 + col]) + 2048 >> 12;
            v5 = p[3 * 8 + col];
            v6 = p[5 * 8 + col];

            // stage 3
            t = v0 - v1 + 1 >> 1;
            v0 = v0 + v1 + 1 >> 1;
            v1 = t;
            t = v2 * dctSin6 + v3 * dctCos6 + 2048 >> 12;
            v2 = v2 * dctCos6 - v3 * dctSin6 + 2048 >> 12;
            v3 = t;
            t = v4 - v6 + 1 >> 1;
            v4 = v4 + v6 + 1 >> 1;
            v6 = t;
            t = v7 + v5 + 1 >> 1;
            v5 = v7 - v5 + 1 >> 1;
            v7 = t;

            // stage 2
            t = v0 - v3 + 1 >> 1;
            v0 = v0 + v3 + 1 >> 1;
            v3 = t;
            t = v1 - v2 + 1 >> 1;
            v1 = v1 + v2 + 1 >> 1;
            v2 = t;
            t = v4 * dctSin3 + v7 * dctCos3 + 2048 >> 12;
            v4 = v4 * dctCos3 - v7 * dctSin3 + 2048 >> 12;
            v7 = t;
            t = v5 * dctSin1 + v6 * dctCos1 + 2048 >> 12;
            v5 = v5 * dctCos1 - v6 * dctSin1 + 2048 >> 12;
            v6 = t;

            // stage 1
            p[0 * 8 + col] = v0 + v7;
            p[7 * 8 + col] = v0 - v7;
            p[1 * 8 + col] = v1 + v6;
            p[6 * 8 + col] = v1 - v6;
            p[2 * 8 + col] = v2 + v5;
            p[5 * 8 + col] = v2 - v5;
            p[3 * 8 + col] = v3 + v4;
            p[4 * 8 + col] = v3 - v4;
          }

          // convert to 8-bit integers
          for (i = 0; i < 64; ++i) {
            var sample = 128 + (p[i] + 8 >> 4);
            dataOut[i] = sample < 0 ? 0 : sample > 0xFF ? 0xFF : sample;
          }
        }
        requestMemoryAllocation(samplesPerLine * blocksPerColumn * 8);
        var i, j;
        for (var blockRow = 0; blockRow < blocksPerColumn; blockRow++) {
          var scanLine = blockRow << 3;
          for (i = 0; i < 8; i++) lines.push(new Uint8Array(samplesPerLine));
          for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) {
            quantizeAndInverse(component.blocks[blockRow][blockCol], r, R);
            var offset = 0,
              sample = blockCol << 3;
            for (j = 0; j < 8; j++) {
              var line = lines[scanLine + j];
              for (i = 0; i < 8; i++) line[sample + i] = r[offset++];
            }
          }
        }
        return lines;
      }
      function clampTo8bit(a) {
        return a < 0 ? 0 : a > 255 ? 255 : a;
      }
      constructor.prototype = {
        load: function load(path) {
          var xhr = new XMLHttpRequest();
          xhr.open("GET", path, true);
          xhr.responseType = "arraybuffer";
          xhr.onload = function () {
            // TODO catch parse error
            var data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer);
            this.parse(data);
            if (this.onload) this.onload();
          }.bind(this);
          xhr.send(null);
        },
        parse: function parse(data) {
          var maxResolutionInPixels = this.opts.maxResolutionInMP * 1000 * 1000;
          var offset = 0;
            data.length;
          function readUint16() {
            var value = data[offset] << 8 | data[offset + 1];
            offset += 2;
            return value;
          }
          function readDataBlock() {
            var length = readUint16();
            var array = data.subarray(offset, offset + length - 2);
            offset += array.length;
            return array;
          }
          function prepareComponents(frame) {
            // According to the JPEG standard, the sampling factor must be between 1 and 4
            // See https://github.com/libjpeg-turbo/libjpeg-turbo/blob/9abeff46d87bd201a952e276f3e4339556a403a3/libjpeg.txt#L1138-L1146
            var maxH = 1,
              maxV = 1;
            var component, componentId;
            for (componentId in frame.components) {
              if (frame.components.hasOwnProperty(componentId)) {
                component = frame.components[componentId];
                if (maxH < component.h) maxH = component.h;
                if (maxV < component.v) maxV = component.v;
              }
            }
            var mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / maxH);
            var mcusPerColumn = Math.ceil(frame.scanLines / 8 / maxV);
            for (componentId in frame.components) {
              if (frame.components.hasOwnProperty(componentId)) {
                component = frame.components[componentId];
                var blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) * component.h / maxH);
                var blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) * component.v / maxV);
                var blocksPerLineForMcu = mcusPerLine * component.h;
                var blocksPerColumnForMcu = mcusPerColumn * component.v;
                var blocksToAllocate = blocksPerColumnForMcu * blocksPerLineForMcu;
                var blocks = [];

                // Each block is a Int32Array of length 64 (4 x 64 = 256 bytes)
                requestMemoryAllocation(blocksToAllocate * 256);
                for (var i = 0; i < blocksPerColumnForMcu; i++) {
                  var row = [];
                  for (var j = 0; j < blocksPerLineForMcu; j++) row.push(new Int32Array(64));
                  blocks.push(row);
                }
                component.blocksPerLine = blocksPerLine;
                component.blocksPerColumn = blocksPerColumn;
                component.blocks = blocks;
              }
            }
            frame.maxH = maxH;
            frame.maxV = maxV;
            frame.mcusPerLine = mcusPerLine;
            frame.mcusPerColumn = mcusPerColumn;
          }
          var jfif = null;
          var adobe = null;
          var frame, resetInterval;
          var quantizationTables = [],
            frames = [];
          var huffmanTablesAC = [],
            huffmanTablesDC = [];
          var fileMarker = readUint16();
          var malformedDataOffset = -1;
          this.comments = [];
          if (fileMarker != 0xFFD8) {
            // SOI (Start of Image)
            throw new Error("SOI not found");
          }
          fileMarker = readUint16();
          while (fileMarker != 0xFFD9) {
            // EOI (End of image)
            var i, j;
            switch (fileMarker) {
              case 0xFF00:
                break;
              case 0xFFE0: // APP0 (Application Specific)
              case 0xFFE1: // APP1
              case 0xFFE2: // APP2
              case 0xFFE3: // APP3
              case 0xFFE4: // APP4
              case 0xFFE5: // APP5
              case 0xFFE6: // APP6
              case 0xFFE7: // APP7
              case 0xFFE8: // APP8
              case 0xFFE9: // APP9
              case 0xFFEA: // APP10
              case 0xFFEB: // APP11
              case 0xFFEC: // APP12
              case 0xFFED: // APP13
              case 0xFFEE: // APP14
              case 0xFFEF: // APP15
              case 0xFFFE:
                // COM (Comment)
                var appData = readDataBlock();
                if (fileMarker === 0xFFFE) {
                  var comment = String.fromCharCode.apply(null, appData);
                  this.comments.push(comment);
                }
                if (fileMarker === 0xFFE0) {
                  if (appData[0] === 0x4A && appData[1] === 0x46 && appData[2] === 0x49 && appData[3] === 0x46 && appData[4] === 0) {
                    // 'JFIF\x00'
                    jfif = {
                      version: {
                        major: appData[5],
                        minor: appData[6]
                      },
                      densityUnits: appData[7],
                      xDensity: appData[8] << 8 | appData[9],
                      yDensity: appData[10] << 8 | appData[11],
                      thumbWidth: appData[12],
                      thumbHeight: appData[13],
                      thumbData: appData.subarray(14, 14 + 3 * appData[12] * appData[13])
                    };
                  }
                }
                // TODO APP1 - Exif
                if (fileMarker === 0xFFE1) {
                  if (appData[0] === 0x45 && appData[1] === 0x78 && appData[2] === 0x69 && appData[3] === 0x66 && appData[4] === 0) {
                    // 'EXIF\x00'
                    this.exifBuffer = appData.subarray(5, appData.length);
                  }
                }
                if (fileMarker === 0xFFEE) {
                  if (appData[0] === 0x41 && appData[1] === 0x64 && appData[2] === 0x6F && appData[3] === 0x62 && appData[4] === 0x65 && appData[5] === 0) {
                    // 'Adobe\x00'
                    adobe = {
                      version: appData[6],
                      flags0: appData[7] << 8 | appData[8],
                      flags1: appData[9] << 8 | appData[10],
                      transformCode: appData[11]
                    };
                  }
                }
                break;
              case 0xFFDB:
                // DQT (Define Quantization Tables)
                var quantizationTablesLength = readUint16();
                var quantizationTablesEnd = quantizationTablesLength + offset - 2;
                while (offset < quantizationTablesEnd) {
                  var quantizationTableSpec = data[offset++];
                  requestMemoryAllocation(64 * 4);
                  var tableData = new Int32Array(64);
                  if (quantizationTableSpec >> 4 === 0) {
                    // 8 bit values
                    for (j = 0; j < 64; j++) {
                      var z = dctZigZag[j];
                      tableData[z] = data[offset++];
                    }
                  } else if (quantizationTableSpec >> 4 === 1) {
                    //16 bit
                    for (j = 0; j < 64; j++) {
                      var z = dctZigZag[j];
                      tableData[z] = readUint16();
                    }
                  } else throw new Error("DQT: invalid table spec");
                  quantizationTables[quantizationTableSpec & 15] = tableData;
                }
                break;
              case 0xFFC0: // SOF0 (Start of Frame, Baseline DCT)
              case 0xFFC1: // SOF1 (Start of Frame, Extended DCT)
              case 0xFFC2:
                // SOF2 (Start of Frame, Progressive DCT)
                readUint16(); // skip data length
                frame = {};
                frame.extended = fileMarker === 0xFFC1;
                frame.progressive = fileMarker === 0xFFC2;
                frame.precision = data[offset++];
                frame.scanLines = readUint16();
                frame.samplesPerLine = readUint16();
                frame.components = {};
                frame.componentsOrder = [];
                var pixelsInFrame = frame.scanLines * frame.samplesPerLine;
                if (pixelsInFrame > maxResolutionInPixels) {
                  var exceededAmount = Math.ceil((pixelsInFrame - maxResolutionInPixels) / 1e6);
                  throw new Error(`maxResolutionInMP limit exceeded by ${exceededAmount}MP`);
                }
                var componentsCount = data[offset++],
                  componentId;
                for (i = 0; i < componentsCount; i++) {
                  componentId = data[offset];
                  var h = data[offset + 1] >> 4;
                  var v = data[offset + 1] & 15;
                  var qId = data[offset + 2];
                  if (h <= 0 || v <= 0) {
                    throw new Error('Invalid sampling factor, expected values above 0');
                  }
                  frame.componentsOrder.push(componentId);
                  frame.components[componentId] = {
                    h: h,
                    v: v,
                    quantizationIdx: qId
                  };
                  offset += 3;
                }
                prepareComponents(frame);
                frames.push(frame);
                break;
              case 0xFFC4:
                // DHT (Define Huffman Tables)
                var huffmanLength = readUint16();
                for (i = 2; i < huffmanLength;) {
                  var huffmanTableSpec = data[offset++];
                  var codeLengths = new Uint8Array(16);
                  var codeLengthSum = 0;
                  for (j = 0; j < 16; j++, offset++) {
                    codeLengthSum += codeLengths[j] = data[offset];
                  }
                  requestMemoryAllocation(16 + codeLengthSum);
                  var huffmanValues = new Uint8Array(codeLengthSum);
                  for (j = 0; j < codeLengthSum; j++, offset++) huffmanValues[j] = data[offset];
                  i += 17 + codeLengthSum;
                  (huffmanTableSpec >> 4 === 0 ? huffmanTablesDC : huffmanTablesAC)[huffmanTableSpec & 15] = buildHuffmanTable(codeLengths, huffmanValues);
                }
                break;
              case 0xFFDD:
                // DRI (Define Restart Interval)
                readUint16(); // skip data length
                resetInterval = readUint16();
                break;
              case 0xFFDC:
                // Number of Lines marker
                readUint16(); // skip data length
                readUint16(); // Ignore this data since it represents the image height
                break;
              case 0xFFDA:
                // SOS (Start of Scan)
                readUint16();
                var selectorsCount = data[offset++];
                var components = [],
                  component;
                for (i = 0; i < selectorsCount; i++) {
                  component = frame.components[data[offset++]];
                  var tableSpec = data[offset++];
                  component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4];
                  component.huffmanTableAC = huffmanTablesAC[tableSpec & 15];
                  components.push(component);
                }
                var spectralStart = data[offset++];
                var spectralEnd = data[offset++];
                var successiveApproximation = data[offset++];
                var processed = decodeScan(data, offset, frame, components, resetInterval, spectralStart, spectralEnd, successiveApproximation >> 4, successiveApproximation & 15, this.opts);
                offset += processed;
                break;
              case 0xFFFF:
                // Fill bytes
                if (data[offset] !== 0xFF) {
                  // Avoid skipping a valid marker.
                  offset--;
                }
                break;
              default:
                if (data[offset - 3] == 0xFF && data[offset - 2] >= 0xC0 && data[offset - 2] <= 0xFE) {
                  // could be incorrect encoding -- last 0xFF byte of the previous
                  // block was eaten by the encoder
                  offset -= 3;
                  break;
                } else if (fileMarker === 0xE0 || fileMarker == 0xE1) {
                  // Recover from malformed APP1 markers popular in some phone models.
                  // See https://github.com/eugeneware/jpeg-js/issues/82
                  if (malformedDataOffset !== -1) {
                    throw new Error(`first unknown JPEG marker at offset ${malformedDataOffset.toString(16)}, second unknown JPEG marker ${fileMarker.toString(16)} at offset ${(offset - 1).toString(16)}`);
                  }
                  malformedDataOffset = offset - 1;
                  const nextOffset = readUint16();
                  if (data[offset + nextOffset - 2] === 0xFF) {
                    offset += nextOffset - 2;
                    break;
                  }
                }
                throw new Error("unknown JPEG marker " + fileMarker.toString(16));
            }
            fileMarker = readUint16();
          }
          if (frames.length != 1) throw new Error("only single frame JPEGs supported");

          // set each frame's components quantization table
          for (var i = 0; i < frames.length; i++) {
            var cp = frames[i].components;
            for (var j in cp) {
              cp[j].quantizationTable = quantizationTables[cp[j].quantizationIdx];
              delete cp[j].quantizationIdx;
            }
          }
          this.width = frame.samplesPerLine;
          this.height = frame.scanLines;
          this.jfif = jfif;
          this.adobe = adobe;
          this.components = [];
          for (var i = 0; i < frame.componentsOrder.length; i++) {
            var component = frame.components[frame.componentsOrder[i]];
            this.components.push({
              lines: buildComponentData(frame, component),
              scaleX: component.h / frame.maxH,
              scaleY: component.v / frame.maxV
            });
          }
        },
        getData: function getData(width, height) {
          var scaleX = this.width / width,
            scaleY = this.height / height;
          var component1, component2, component3, component4;
          var component1Line, component2Line, component3Line, component4Line;
          var x, y;
          var offset = 0;
          var Y, Cb, Cr, K, C, M, Ye, R, G, B;
          var colorTransform;
          var dataLength = width * height * this.components.length;
          requestMemoryAllocation(dataLength);
          var data = new Uint8Array(dataLength);
          switch (this.components.length) {
            case 1:
              component1 = this.components[0];
              for (y = 0; y < height; y++) {
                component1Line = component1.lines[0 | y * component1.scaleY * scaleY];
                for (x = 0; x < width; x++) {
                  Y = component1Line[0 | x * component1.scaleX * scaleX];
                  data[offset++] = Y;
                }
              }
              break;
            case 2:
              // PDF might compress two component data in custom colorspace
              component1 = this.components[0];
              component2 = this.components[1];
              for (y = 0; y < height; y++) {
                component1Line = component1.lines[0 | y * component1.scaleY * scaleY];
                component2Line = component2.lines[0 | y * component2.scaleY * scaleY];
                for (x = 0; x < width; x++) {
                  Y = component1Line[0 | x * component1.scaleX * scaleX];
                  data[offset++] = Y;
                  Y = component2Line[0 | x * component2.scaleX * scaleX];
                  data[offset++] = Y;
                }
              }
              break;
            case 3:
              // The default transform for three components is true
              colorTransform = true;
              // The adobe transform marker overrides any previous setting
              if (this.adobe && this.adobe.transformCode) colorTransform = true;else if (typeof this.opts.colorTransform !== 'undefined') colorTransform = !!this.opts.colorTransform;
              component1 = this.components[0];
              component2 = this.components[1];
              component3 = this.components[2];
              for (y = 0; y < height; y++) {
                component1Line = component1.lines[0 | y * component1.scaleY * scaleY];
                component2Line = component2.lines[0 | y * component2.scaleY * scaleY];
                component3Line = component3.lines[0 | y * component3.scaleY * scaleY];
                for (x = 0; x < width; x++) {
                  if (!colorTransform) {
                    R = component1Line[0 | x * component1.scaleX * scaleX];
                    G = component2Line[0 | x * component2.scaleX * scaleX];
                    B = component3Line[0 | x * component3.scaleX * scaleX];
                  } else {
                    Y = component1Line[0 | x * component1.scaleX * scaleX];
                    Cb = component2Line[0 | x * component2.scaleX * scaleX];
                    Cr = component3Line[0 | x * component3.scaleX * scaleX];
                    R = clampTo8bit(Y + 1.402 * (Cr - 128));
                    G = clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128));
                    B = clampTo8bit(Y + 1.772 * (Cb - 128));
                  }
                  data[offset++] = R;
                  data[offset++] = G;
                  data[offset++] = B;
                }
              }
              break;
            case 4:
              if (!this.adobe) throw new Error('Unsupported color mode (4 components)');
              // The default transform for four components is false
              colorTransform = false;
              // The adobe transform marker overrides any previous setting
              if (this.adobe && this.adobe.transformCode) colorTransform = true;else if (typeof this.opts.colorTransform !== 'undefined') colorTransform = !!this.opts.colorTransform;
              component1 = this.components[0];
              component2 = this.components[1];
              component3 = this.components[2];
              component4 = this.components[3];
              for (y = 0; y < height; y++) {
                component1Line = component1.lines[0 | y * component1.scaleY * scaleY];
                component2Line = component2.lines[0 | y * component2.scaleY * scaleY];
                component3Line = component3.lines[0 | y * component3.scaleY * scaleY];
                component4Line = component4.lines[0 | y * component4.scaleY * scaleY];
                for (x = 0; x < width; x++) {
                  if (!colorTransform) {
                    C = component1Line[0 | x * component1.scaleX * scaleX];
                    M = component2Line[0 | x * component2.scaleX * scaleX];
                    Ye = component3Line[0 | x * component3.scaleX * scaleX];
                    K = component4Line[0 | x * component4.scaleX * scaleX];
                  } else {
                    Y = component1Line[0 | x * component1.scaleX * scaleX];
                    Cb = component2Line[0 | x * component2.scaleX * scaleX];
                    Cr = component3Line[0 | x * component3.scaleX * scaleX];
                    K = component4Line[0 | x * component4.scaleX * scaleX];
                    C = 255 - clampTo8bit(Y + 1.402 * (Cr - 128));
                    M = 255 - clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128));
                    Ye = 255 - clampTo8bit(Y + 1.772 * (Cb - 128));
                  }
                  data[offset++] = 255 - C;
                  data[offset++] = 255 - M;
                  data[offset++] = 255 - Ye;
                  data[offset++] = 255 - K;
                }
              }
              break;
            default:
              throw new Error('Unsupported color mode');
          }
          return data;
        },
        copyToImageData: function copyToImageData(imageData, formatAsRGBA) {
          var width = imageData.width,
            height = imageData.height;
          var imageDataArray = imageData.data;
          var data = this.getData(width, height);
          var i = 0,
            j = 0,
            x,
            y;
          var Y, K, C, M, R, G, B;
          switch (this.components.length) {
            case 1:
              for (y = 0; y < height; y++) {
                for (x = 0; x < width; x++) {
                  Y = data[i++];
                  imageDataArray[j++] = Y;
                  imageDataArray[j++] = Y;
                  imageDataArray[j++] = Y;
                  if (formatAsRGBA) {
                    imageDataArray[j++] = 255;
                  }
                }
              }
              break;
            case 3:
              for (y = 0; y < height; y++) {
                for (x = 0; x < width; x++) {
                  R = data[i++];
                  G = data[i++];
                  B = data[i++];
                  imageDataArray[j++] = R;
                  imageDataArray[j++] = G;
                  imageDataArray[j++] = B;
                  if (formatAsRGBA) {
                    imageDataArray[j++] = 255;
                  }
                }
              }
              break;
            case 4:
              for (y = 0; y < height; y++) {
                for (x = 0; x < width; x++) {
                  C = data[i++];
                  M = data[i++];
                  Y = data[i++];
                  K = data[i++];
                  R = 255 - clampTo8bit(C * (1 - K / 255) + K);
                  G = 255 - clampTo8bit(M * (1 - K / 255) + K);
                  B = 255 - clampTo8bit(Y * (1 - K / 255) + K);
                  imageDataArray[j++] = R;
                  imageDataArray[j++] = G;
                  imageDataArray[j++] = B;
                  if (formatAsRGBA) {
                    imageDataArray[j++] = 255;
                  }
                }
              }
              break;
            default:
              throw new Error('Unsupported color mode');
          }
        }
      };

      // We cap the amount of memory used by jpeg-js to avoid unexpected OOMs from untrusted content.
      var totalBytesAllocated = 0;
      var maxMemoryUsageBytes = 0;
      function requestMemoryAllocation(increaseAmount = 0) {
        var totalMemoryImpactBytes = totalBytesAllocated + increaseAmount;
        if (totalMemoryImpactBytes > maxMemoryUsageBytes) {
          var exceededAmount = Math.ceil((totalMemoryImpactBytes - maxMemoryUsageBytes) / 1024 / 1024);
          throw new Error(`maxMemoryUsageInMB limit exceeded by at least ${exceededAmount}MB`);
        }
        totalBytesAllocated = totalMemoryImpactBytes;
      }
      constructor.resetMaxMemoryUsage = function (maxMemoryUsageBytes_) {
        totalBytesAllocated = 0;
        maxMemoryUsageBytes = maxMemoryUsageBytes_;
      };
      constructor.getBytesAllocated = function () {
        return totalBytesAllocated;
      };
      constructor.requestMemoryAllocation = requestMemoryAllocation;
      return constructor;
    }();
    {
      module.exports = decode;
    }
    function decode(jpegData, userOpts = {}) {
      var defaultOpts = {
        // "undefined" means "Choose whether to transform colors based on the image’s color model."
        colorTransform: undefined,
        useTArray: false,
        formatAsRGBA: true,
        tolerantDecoding: true,
        maxResolutionInMP: 100,
        // Don't decode more than 100 megapixels
        maxMemoryUsageInMB: 512 // Don't decode if memory footprint is more than 512MB
      };
      var opts = {
        ...defaultOpts,
        ...userOpts
      };
      var arr = new Uint8Array(jpegData);
      var decoder = new JpegImage();
      decoder.opts = opts;
      // If this constructor ever supports async decoding this will need to be done differently.
      // Until then, treating as singleton limit is fine.
      JpegImage.resetMaxMemoryUsage(opts.maxMemoryUsageInMB * 1024 * 1024);
      decoder.parse(arr);
      var channels = opts.formatAsRGBA ? 4 : 3;
      var bytesNeeded = decoder.width * decoder.height * channels;
      try {
        JpegImage.requestMemoryAllocation(bytesNeeded);
        var image = {
          width: decoder.width,
          height: decoder.height,
          exifBuffer: decoder.exifBuffer,
          data: opts.useTArray ? new Uint8Array(bytesNeeded) : Buffer.alloc(bytesNeeded)
        };
        if (decoder.comments.length > 0) {
          image["comments"] = decoder.comments;
        }
      } catch (err) {
        if (err instanceof RangeError) {
          throw new Error("Could not allocate enough memory for the image. " + "Required: " + bytesNeeded);
        }
        if (err instanceof ReferenceError) {
          if (err.message === "Buffer is not defined") {
            throw new Error("Buffer is not globally defined in this environment. " + "Consider setting useTArray to true");
          }
        }
        throw err;
      }
      decoder.copyToImageData(image, opts.formatAsRGBA);
      return image;
    }
  })(decoder);
  var decoderExports = decoder.exports;

  var encode$1 = encoderExports,
    decode$4 = decoderExports;
  var jpegJs = {
    encode: encode$1,
    decode: decode$4
  };

  /*
   * base64-arraybuffer
   * https://github.com/niklasvh/base64-arraybuffer
   *
   * Copyright (c) 2012 Niklas von Hertzen
   * Licensed under the MIT license.
   */

  let chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';

  // Use a lookup table to find the index.
  let lookup = new Uint8Array(256);
  for (let i = 0; i < chars.length; i++) {
    lookup[chars.charCodeAt(i)] = i;
  }
  function encode(bytes) {
    let i;
    let len = bytes.length;
    let base64 = '';
    for (i = 0; i < len; i += 3) {
      base64 += chars[bytes[i] >> 2];
      base64 += chars[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];
      base64 += chars[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];
      base64 += chars[bytes[i + 2] & 63];
    }
    if (len % 3 === 2) {
      base64 = `${base64.substring(0, base64.length - 1)}=`;
    } else if (len % 3 === 1) {
      base64 = `${base64.substring(0, base64.length - 2)}==`;
    }
    return base64;
  }
  function decode$3(base64) {
    let bufferLength = base64.length * 0.75;
    let len = base64.length;
    let p = 0;
    let encoded1, encoded2, encoded3, encoded4;
    if (base64[base64.length - 1] === '=') {
      bufferLength--;
      if (base64[base64.length - 2] === '=') {
        bufferLength--;
      }
    }
    const bytes = new Uint8Array(bufferLength);
    for (let i = 0; i < len; i += 4) {
      encoded1 = lookup[base64.charCodeAt(i)];
      encoded2 = lookup[base64.charCodeAt(i + 1)];
      encoded3 = lookup[base64.charCodeAt(i + 2)];
      encoded4 = lookup[base64.charCodeAt(i + 3)];
      bytes[p++] = encoded1 << 2 | encoded2 >> 4;
      bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
      bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
    }
    return bytes;
  }
  function toBase64URL(u8, type) {
    const base64 = encode(u8);
    return `data:${type};base64,${base64}`;
  }

  const ImageData = self.ImageData;
  const DOMImage = self.Image;
  function createCanvas(width, height) {
    let canvas = self.document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;
    return canvas;
  }
  function fetchBinary(url, {
    withCredentials = false
  } = {}) {
    return new Promise(function (resolve, reject) {
      let xhr = new self.XMLHttpRequest();
      xhr.open('GET', url, true);
      xhr.responseType = 'arraybuffer';
      xhr.withCredentials = withCredentials;
      xhr.onload = function (e) {
        if (this.status !== 200) reject(e);else resolve(this.response);
      };
      xhr.onerror = reject;
      xhr.send();
    });
  }
  function createWriteStream() {
    throw new Error('createWriteStream does not exist in the browser');
  }
  function writeFile() {
    throw new Error('writeFile does not exist in the browser');
  }

  function getType(type) {
    if (!type.includes('/')) {
      type = `image/${type}`;
    }
    return type;
  }

  function encodeJpeg(image, options = {}) {
    const data = {
      width: image.width,
      height: image.height,
      data: image.getRGBAData()
    };
    return jpegJs.encode(data, options.quality).data;
  }
  function encodePng(image, options) {
    const data = {
      width: image.width,
      height: image.height,
      channels: image.channels,
      depth: image.bitDepth,
      data: image.data
    };
    if (data.depth === 1 || data.depth === 32) {
      data.depth = 8;
      data.channels = 4;
      data.data = image.getRGBAData();
    }
    return encodePng$1(data, options);
  }
  const exportMethods = {
    /**
     * Save the image to disk (Node.js only)
     * @memberof Image
     * @instance
     * @param {string} path
     * @param {object} [options]
     * @param {string} [options.format] - One of: png, jpg, bmp (limited support for bmp). If not specified will try to infer from filename
     * @param {boolean} [options.useCanvas=false] - Force use of the canvas API to save the image instead of a JavaScript implementation
     * @param {object} [options.encoder] - Specify options for the encoder if applicable.
     * @return {Promise} - Resolves when the file is fully written
     */
    save(path, options = {}) {
      const {
        useCanvas = false,
        encoder: encoderOptions = undefined
      } = options;
      let {
        format
      } = options;
      if (!format) {
        // try to infer format from filename
        const m = /\.(?<format>[a-zA-Z]+)$/.exec(path);
        if (m) {
          format = m.groups.format.toLowerCase();
        }
      }
      if (!format) {
        throw new Error('file format not provided');
      }
      return new Promise((resolve, reject) => {
        let stream, buffer;
        switch (format.toLowerCase()) {
          case 'png':
            {
              if (useCanvas) {
                stream = this.getCanvas().pngStream();
              } else {
                buffer = encodePng(this, encoderOptions);
              }
              break;
            }
          case 'jpg':
          case 'jpeg':
            if (useCanvas) {
              stream = this.getCanvas().jpegStream();
            } else {
              buffer = encodeJpeg(this, encoderOptions);
            }
            break;
          case 'bmp':
            buffer = encode$2(this, encoderOptions);
            break;
          default:
            throw new RangeError(`invalid output format: ${format}`);
        }
        if (stream) {
          let out = createWriteStream();
          out.on('finish', resolve);
          out.on('error', reject);
          stream.pipe(out);
        } else if (buffer) {
          writeFile();
        }
      });
    },
    /**
     * Creates a dataURL string from the image.
     * @memberof Image
     * @instance
     * @param {string} [type='image/png']
     * @param {object} [options]
     * @param {boolean} [options.useCanvas=false] - Force use of the canvas API to save the image instead of JavaScript implementation.
     * @param {object} [options.encoder] - Specify options for the encoder if applicable.
     * @return {string|Promise<string>}
     */
    toDataURL(type = 'image/png', options = {}) {
      if (typeof type === 'object') {
        options = type;
        type = 'image/png';
      }
      const {
        useCanvas = false,
        encoder: encoderOptions = undefined
      } = options;
      type = getType(type);
      function dataUrl(encoder, ctx) {
        const u8 = encoder(ctx, encoderOptions);
        return toBase64URL(u8, type);
      }
      if (type === 'image/bmp') {
        return dataUrl(encode$2, this);
      } else if (type === 'image/png' && !useCanvas) {
        return dataUrl(encodePng, this);
      } else if (type === 'image/jpeg' && !useCanvas) {
        return dataUrl(encodeJpeg, this);
      } else {
        return this.getCanvas().toDataURL(type);
      }
    },
    /**
     * Encodes the image and returns a buffer
     * @memberof Image
     * @instance
     * @param {object} [options]
     * @param {string} [options.format='png']
     * @param {object} [options.encoder] - Specify options for the encoder if applicable.
     * @return {Uint8Array}
     */
    toBuffer(options = {}) {
      const {
        format = 'png',
        encoder: encoderOptions = undefined
      } = options;
      switch (format.toLowerCase()) {
        case 'png':
          return encodePng(this, encoderOptions);
        case 'jpeg':
        case 'jpg':
          return encodeJpeg(this, encoderOptions);
        case 'bmp':
          return encode$2(this, encoderOptions);
        default:
          throw new RangeError(`invalid output format: ${format}`);
      }
    },
    /**
     * Creates a base64 string from the image.
     * @memberof Image
     * @instance
     * @param {string} [type='image/png']
     * @param {object} [options] - Same options as toDataURL
     * @return {string|Promise<string>}
     */
    toBase64(type = 'image/png', options = {}) {
      if (options.async) {
        return this.toDataURL(type, options).then(function (dataURL) {
          return dataURL.substring(dataURL.indexOf(',') + 1);
        });
      } else {
        const dataURL = this.toDataURL(type, options);
        return dataURL.substring(dataURL.indexOf(',') + 1);
      }
    },
    /**
     * Creates a blob from the image and return a Promise.
     * This function is only available in the browser.
     * @memberof Image
     * @instance
     * @param {string} [type='image/png'] A String indicating the image format. The default type is image/png.
     * @param {string} [quality=0.8] A Number between 0 and 1 indicating image quality if the requested type is image/jpeg or image/webp. If this argument is anything else, the default value for image quality is used. Other arguments are ignored.
     * @return {Promise}
     */
    toBlob(type = 'image/png', quality = 0.8) {
      return canvasToBlob(this.getCanvas(), type, quality);
    },
    /**
     * Creates a new canvas element and draw the image inside it
     * @memberof Image
     * @instance
     * @return {Canvas}
     */
    getCanvas() {
      const data = new ImageData(this.getRGBAData({
        clamped: true
      }), this.width, this.height);
      let canvas = createCanvas(this.width, this.height);
      let ctx = canvas.getContext('2d');
      ctx.putImageData(data, 0, 0);
      return canvas;
    }
  };
  function setExportMethods(Image) {
    for (const i in exportMethods) {
      Image.prototype[i] = exportMethods[i];
    }
  }

  var hasOwn$1 = {exports: {}};

  var version = "1.0.1";
  var require$$0$2 = {
  	version: version};

  (function (module, exports) {
    var hasOwnProperty = Object.prototype.hasOwnProperty;
    module.exports = exports = function hasOwn(prop, obj) {
      return hasOwnProperty.call(obj, prop);
    };
    exports.version = require$$0$2.version;
  })(hasOwn$1, hasOwn$1.exports);
  var hasOwnExports = hasOwn$1.exports;
  var hasOwn = /*@__PURE__*/getDefaultExportFromCjs(hasOwnExports);

  let computedPropertyDescriptor$1 = {
    configurable: true,
    enumerable: false,
    get: undefined
  };
  function extendMethod(name, method, options = {}) {
    let {
      inPlace = false,
      returnThis = true,
      partialArgs = []
    } = options;
    if (inPlace) {
      Image.prototype[name] = function (...args) {
        // remove computed properties
        this.computed = null;
        let result = method.apply(this, [...partialArgs, ...args]);
        if (returnThis) {
          return this;
        }
        return result;
      };
    } else {
      Image.prototype[name] = function (...args) {
        return method.apply(this, [...partialArgs, ...args]);
      };
    }
    return Image;
  }
  function extendProperty(name, method, options = {}) {
    let {
      partialArgs = []
    } = options;
    computedPropertyDescriptor$1.get = function () {
      if (this.computed === null) {
        this.computed = {};
      } else if (hasOwn(name, this.computed)) {
        return this.computed[name];
      }
      let result = method.apply(this, partialArgs);
      this.computed[name] = result;
      return result;
    };
    Object.defineProperty(Image.prototype, name, computedPropertyDescriptor$1);
    return Image;
  }

  /**
   * Color model of an image
   * @typedef {('GREY'|'RGB'|'HSL'|'HSV'|'CMYK')} ColorModel
   */

  const GREY$1 = 'GREY';
  const RGB$1 = 'RGB';
  const HSL = 'HSL';
  const HSV = 'HSV';
  const CMYK$1 = 'CMYK';

  var ColorModel = /*#__PURE__*/Object.freeze({
    __proto__: null,
    CMYK: CMYK$1,
    GREY: GREY$1,
    HSL: HSL,
    HSV: HSV,
    RGB: RGB$1
  });

  /**
   * Retrieve the data of the current image as RGBA 8 bits
   * The source image may be:
   * * a mask (binary image)
   * * a grey image (8 16 bits) with or without alpha channel
   * * a color image (8 or 16 bits) with or without alpha channel in with RGB model
   * @instance
   * @memberof Image
   * @param {object} [options]
   * @param {boolean} [options.clamped] - If true, the function will return a Uint8ClampedArray
   * @return {Uint8Array|Uint8ClampedArray} - Array with the data
   */
  function getRGBAData(options = {}) {
    const {
      clamped
    } = options;
    this.checkProcessable('getRGBAData', {
      components: [1, 3],
      bitDepth: [1, 8, 16, 32]
    });
    const arrayLength = this.width * this.height * 4;
    let newData = clamped ? new Uint8ClampedArray(arrayLength) : new Uint8Array(arrayLength);
    if (this.bitDepth === 1) {
      fillDataFromBinary(this, newData);
    } else if (this.bitDepth === 32) {
      this.checkProcessable('getRGBAData', {
        alpha: 0
      });
      if (this.components === 1) {
        fillDataFromGrey32(this, newData);
      } else if (this.components === 3) {
        this.checkProcessable('getRGBAData', {
          colorModel: [RGB$1]
        });
        fillDataFromRGB32(this, newData);
      }
    } else {
      if (this.components === 1) {
        fillDataFromGrey(this, newData);
      } else if (this.components === 3) {
        this.checkProcessable('getRGBAData', {
          colorModel: [RGB$1]
        });
        fillDataFromRGB(this, newData);
      }
    }
    if (this.alpha === 1) {
      this.checkProcessable('getRGBAData', {
        bitDepth: [8, 16]
      });
      copyAlpha(this, newData);
    } else {
      fillAlpha(this, newData);
    }
    return newData;
  }
  function fillDataFromBinary(image, newData) {
    for (let i = 0; i < image.size; i++) {
      const value = image.getBit(i);
      newData[i * 4] = value * 255;
      newData[i * 4 + 1] = value * 255;
      newData[i * 4 + 2] = value * 255;
    }
  }
  function fillDataFromGrey32(image, newData) {
    const min = image.min[0];
    const max = image.max[0];
    const range = max - min;
    for (let i = 0; i < image.size; i++) {
      const val = Math.floor(255 * (image.data[i] - min) / range);
      newData[i * 4] = val;
      newData[i * 4 + 1] = val;
      newData[i * 4 + 2] = val;
    }
  }
  function fillDataFromRGB32(image, newData) {
    const min = Math.min(...image.min);
    const max = Math.max(...image.max);
    const range = max - min;
    for (let i = 0; i < image.size; i++) {
      const val1 = Math.floor(255 * (image.data[i * 3] - min) / range);
      const val2 = Math.floor(255 * (image.data[i * 3 + 1] - min) / range);
      const val3 = Math.floor(255 * (image.data[i * 3 + 2] - min) / range);
      newData[i * 4] = val1;
      newData[i * 4 + 1] = val2;
      newData[i * 4 + 2] = val3;
    }
  }
  function fillDataFromGrey(image, newData) {
    for (let i = 0; i < image.size; i++) {
      newData[i * 4] = image.data[i * image.channels] >>> image.bitDepth - 8;
      newData[i * 4 + 1] = image.data[i * image.channels] >>> image.bitDepth - 8;
      newData[i * 4 + 2] = image.data[i * image.channels] >>> image.bitDepth - 8;
    }
  }
  function fillDataFromRGB(image, newData) {
    for (let i = 0; i < image.size; i++) {
      newData[i * 4] = image.data[i * image.channels] >>> image.bitDepth - 8;
      newData[i * 4 + 1] = image.data[i * image.channels + 1] >>> image.bitDepth - 8;
      newData[i * 4 + 2] = image.data[i * image.channels + 2] >>> image.bitDepth - 8;
    }
  }
  function copyAlpha(image, newData) {
    for (let i = 0; i < image.size; i++) {
      newData[i * 4 + 3] = image.data[i * image.channels + image.components] >> image.bitDepth - 8;
    }
  }
  function fillAlpha(image, newData) {
    for (let i = 0; i < image.size; i++) {
      newData[i * 4 + 3] = 255;
    }
  }

  // Shortcuts for common image kinds

  const BINARY = 'BINARY';
  const GREY = 'GREY';
  const GREYA = 'GREYA';
  const RGB = 'RGB';
  const RGBA = 'RGBA';
  const CMYK = 'CMYK';
  const CMYKA = 'CMYKA';

  const kinds = {};
  kinds[BINARY] = {
    components: 1,
    alpha: 0,
    bitDepth: 1,
    colorModel: GREY$1
  };
  kinds[GREYA] = {
    components: 1,
    alpha: 1,
    bitDepth: 8,
    colorModel: GREY$1
  };
  kinds[GREY] = {
    components: 1,
    alpha: 0,
    bitDepth: 8,
    colorModel: GREY$1
  };
  kinds[RGBA] = {
    components: 3,
    alpha: 1,
    bitDepth: 8,
    colorModel: RGB$1
  };
  kinds[RGB] = {
    components: 3,
    alpha: 0,
    bitDepth: 8,
    colorModel: RGB$1
  };
  kinds[CMYK] = {
    components: 4,
    alpha: 0,
    bitDepth: 8,
    colorModel: CMYK$1
  };
  kinds[CMYKA] = {
    components: 4,
    alpha: 1,
    bitDepth: 8,
    colorModel: CMYK$1
  };
  function getKind(kind) {
    const result = kinds[kind];
    if (!result) {
      throw new RangeError(`invalid image kind: ${kind}`);
    }
    return result;
  }
  const validBitDepth = [1, 8, 16, 32];
  function verifyKindDefinition(definition) {
    const {
      components,
      alpha,
      bitDepth,
      colorModel
    } = definition;
    if (!Number.isInteger(components) || components <= 0) {
      throw new RangeError(`invalid components: ${components}. Must be a positive integer`);
    }
    if (alpha !== 0 && alpha !== 1 && typeof alpha !== 'boolean') {
      throw new TypeError(`invalid alpha: ${alpha}: must be a boolean, 0 or 1`);
    }
    if (!validBitDepth.includes(bitDepth)) {
      throw new RangeError(`invalid bitDepth: ${bitDepth}. Must be one of ${validBitDepth.join(', ')}`);
    }
    // eslint-disable-next-line import/namespace
    if (!ColorModel[colorModel]) {
      throw new RangeError(`invalid colorModel: ${colorModel}. Must be one of ${Object.keys(ColorModel).join(', ')}`);
    }
  }
  function getTheoreticalPixelArraySize(size, channels, bitDepth) {
    let length = channels * size;
    if (bitDepth === 1) {
      length = Math.ceil(length / 8);
    }
    return length;
  }
  function createPixelArray(size, components, alpha, channels, bitDepth, maxValue) {
    const length = channels * size;
    let arr;
    switch (bitDepth) {
      case 1:
        arr = new Uint8Array(Math.ceil(length / 8));
        break;
      case 8:
        arr = new Uint8Array(length);
        break;
      case 16:
        arr = new Uint16Array(length);
        break;
      case 32:
        arr = new Float32Array(length);
        break;
      default:
        throw new Error(`Cannot create pixel array for bit depth ${bitDepth}`);
    }

    // alpha channel is 100% by default
    if (alpha) {
      for (let i = components; i < arr.length; i += channels) {
        arr[i] = maxValue;
      }
    }
    return arr;
  }

  const defaultByteLength = 1024 * 8;
  const charArray = [];
  let IOBuffer$2 = class IOBuffer {
    constructor(data, options) {
      options = options || {};
      if (data === undefined) {
        data = defaultByteLength;
      }
      if (typeof data === 'number') {
        data = new ArrayBuffer(data);
      }
      let length = data.byteLength;
      const offset = options.offset ? options.offset >>> 0 : 0;
      if (data.buffer) {
        length = data.byteLength - offset;
        if (data.byteLength !== data.buffer.byteLength) {
          // Node.js buffer from pool
          data = data.buffer.slice(data.byteOffset + offset, data.byteOffset + data.byteLength);
        } else if (offset) {
          data = data.buffer.slice(offset);
        } else {
          data = data.buffer;
        }
      }
      this.buffer = data;
      this.length = length;
      this.byteLength = length;
      this.byteOffset = 0;
      this.offset = 0;
      this.littleEndian = true;
      this._data = new DataView(this.buffer);
      this._increment = length || defaultByteLength;
      this._mark = 0;
    }
    available(byteLength) {
      if (byteLength === undefined) byteLength = 1;
      return this.offset + byteLength <= this.length;
    }
    isLittleEndian() {
      return this.littleEndian;
    }
    setLittleEndian() {
      this.littleEndian = true;
    }
    isBigEndian() {
      return !this.littleEndian;
    }
    setBigEndian() {
      this.littleEndian = false;
    }
    skip(n) {
      if (n === undefined) n = 1;
      this.offset += n;
    }
    seek(offset) {
      this.offset = offset;
    }
    mark() {
      this._mark = this.offset;
    }
    reset() {
      this.offset = this._mark;
    }
    rewind() {
      this.offset = 0;
    }
    ensureAvailable(byteLength) {
      if (byteLength === undefined) byteLength = 1;
      if (!this.available(byteLength)) {
        const newIncrement = this._increment + this._increment;
        this._increment = newIncrement;
        const newLength = this.length + newIncrement;
        const newArray = new Uint8Array(newLength);
        newArray.set(new Uint8Array(this.buffer));
        this.buffer = newArray.buffer;
        this.length = newLength;
        this._data = new DataView(this.buffer);
      }
    }
    readBoolean() {
      return this.readUint8() !== 0;
    }
    readInt8() {
      return this._data.getInt8(this.offset++);
    }
    readUint8() {
      return this._data.getUint8(this.offset++);
    }
    readByte() {
      return this.readUint8();
    }
    readBytes(n) {
      if (n === undefined) n = 1;
      var bytes = new Uint8Array(n);
      for (var i = 0; i < n; i++) {
        bytes[i] = this.readByte();
      }
      return bytes;
    }
    readInt16() {
      var value = this._data.getInt16(this.offset, this.littleEndian);
      this.offset += 2;
      return value;
    }
    readUint16() {
      var value = this._data.getUint16(this.offset, this.littleEndian);
      this.offset += 2;
      return value;
    }
    readInt32() {
      var value = this._data.getInt32(this.offset, this.littleEndian);
      this.offset += 4;
      return value;
    }
    readUint32() {
      var value = this._data.getUint32(this.offset, this.littleEndian);
      this.offset += 4;
      return value;
    }
    readFloat32() {
      var value = this._data.getFloat32(this.offset, this.littleEndian);
      this.offset += 4;
      return value;
    }
    readFloat64() {
      var value = this._data.getFloat64(this.offset, this.littleEndian);
      this.offset += 8;
      return value;
    }
    readChar() {
      return String.fromCharCode(this.readInt8());
    }
    readChars(n) {
      if (n === undefined) n = 1;
      charArray.length = n;
      for (var i = 0; i < n; i++) {
        charArray[i] = this.readChar();
      }
      return charArray.join('');
    }
    writeBoolean(bool) {
      this.writeUint8(bool ? 0xff : 0x00);
    }
    writeInt8(value) {
      this.ensureAvailable(1);
      this._data.setInt8(this.offset++, value);
    }
    writeUint8(value) {
      this.ensureAvailable(1);
      this._data.setUint8(this.offset++, value);
    }
    writeByte(value) {
      this.writeUint8(value);
    }
    writeBytes(bytes) {
      this.ensureAvailable(bytes.length);
      for (var i = 0; i < bytes.length; i++) {
        this._data.setUint8(this.offset++, bytes[i]);
      }
    }
    writeInt16(value) {
      this.ensureAvailable(2);
      this._data.setInt16(this.offset, value, this.littleEndian);
      this.offset += 2;
    }
    writeUint16(value) {
      this.ensureAvailable(2);
      this._data.setUint16(this.offset, value, this.littleEndian);
      this.offset += 2;
    }
    writeInt32(value) {
      this.ensureAvailable(4);
      this._data.setInt32(this.offset, value, this.littleEndian);
      this.offset += 4;
    }
    writeUint32(value) {
      this.ensureAvailable(4);
      this._data.setUint32(this.offset, value, this.littleEndian);
      this.offset += 4;
    }
    writeFloat32(value) {
      this.ensureAvailable(4);
      this._data.setFloat32(this.offset, value, this.littleEndian);
      this.offset += 4;
    }
    writeFloat64(value) {
      this.ensureAvailable(8);
      this._data.setFloat64(this.offset, value, this.littleEndian);
      this.offset += 8;
    }
    writeChar(str) {
      this.writeUint8(str.charCodeAt(0));
    }
    writeChars(str) {
      for (var i = 0; i < str.length; i++) {
        this.writeUint8(str.charCodeAt(i));
      }
    }
    toArray() {
      return new Uint8Array(this.buffer, 0, this.offset);
    }
  };
  var IOBuffer_1 = IOBuffer$2;

  var src$3 = {};

  const tagsById$5 = {
    // Baseline tags
    0x00FE: 'NewSubfileType',
    0x00FF: 'SubfileType',
    0x0100: 'ImageWidth',
    0x0101: 'ImageLength',
    0x0102: 'BitsPerSample',
    0x0103: 'Compression',
    0x0106: 'PhotometricInterpretation',
    0x0107: 'Threshholding',
    0x0108: 'CellWidth',
    0x0109: 'CellLength',
    0x010A: 'FillOrder',
    0x010E: 'ImageDescription',
    0x010F: 'Make',
    0x0110: 'Model',
    0x0111: 'StripOffsets',
    0x0112: 'Orientation',
    0x0115: 'SamplesPerPixel',
    0x0116: 'RowsPerStrip',
    0x0117: 'StripByteCounts',
    0x0118: 'MinSampleValue',
    0x0119: 'MaxSampleValue',
    0x011A: 'XResolution',
    0x011B: 'YResolution',
    0x011C: 'PlanarConfiguration',
    0x0120: 'FreeOffsets',
    0x0121: 'FreeByteCounts',
    0x0122: 'GrayResponseUnit',
    0x0123: 'GrayResponseCurve',
    0x0128: 'ResolutionUnit',
    0x0131: 'Software',
    0x0132: 'DateTime',
    0x013B: 'Artist',
    0x013C: 'HostComputer',
    0x0140: 'ColorMap',
    0x0152: 'ExtraSamples',
    0x8298: 'Copyright',
    // Extension tags
    0x010D: 'DocumentName',
    0x011D: 'PageName',
    0x011E: 'XPosition',
    0x011F: 'YPosition',
    0x0124: 'T4Options',
    0x0125: 'T6Options',
    0x0129: 'PageNumber',
    0x012D: 'TransferFunction',
    0x013D: 'Predictor',
    0x013E: 'WhitePoint',
    0x013F: 'PrimaryChromaticities',
    0x0141: 'HalftoneHints',
    0x0142: 'TileWidth',
    0x0143: 'TileLength',
    0x0144: 'TileOffsets',
    0x0145: 'TileByteCounts',
    0x0146: 'BadFaxLines',
    0x0147: 'CleanFaxData',
    0x0148: 'ConsecutiveBadFaxLines',
    0x014A: 'SubIFDs',
    0x014C: 'InkSet',
    0x014D: 'InkNames',
    0x014E: 'NumberOfInks',
    0x0150: 'DotRange',
    0x0151: 'TargetPrinter',
    0x0153: 'SampleFormat',
    0x0154: 'SMinSampleValue',
    0x0155: 'SMaxSampleValue',
    0x0156: 'TransferRange',
    0x0157: 'ClipPath',
    0x0158: 'XClipPathUnits',
    0x0159: 'YClipPathUnits',
    0x015A: 'Indexed',
    0x015B: 'JPEGTables',
    0x015F: 'OPIProxy',
    0x0190: 'GlobalParametersIFD',
    0x0191: 'ProfileType',
    0x0192: 'FaxProfile',
    0x0193: 'CodingMethods',
    0x0194: 'VersionYear',
    0x0195: 'ModeNumber',
    0x01B1: 'Decode',
    0x01B2: 'DefaultImageColor',
    0x0200: 'JPEGProc',
    0x0201: 'JPEGInterchangeFormat',
    0x0202: 'JPEGInterchangeFormatLength',
    0x0203: 'JPEGRestartInterval',
    0x0205: 'JPEGLosslessPredictors',
    0x0206: 'JPEGPointTransforms',
    0x0207: 'JPEGQTables',
    0x0208: 'JPEGDCTables',
    0x0209: 'JPEGACTables',
    0x0211: 'YCbCrCoefficients',
    0x0212: 'YCbCrSubSampling',
    0x0213: 'YCbCrPositioning',
    0x0214: 'ReferenceBlackWhite',
    0x022F: 'StripRowCounts',
    0x02BC: 'XMP',
    0x800D: 'ImageID',
    0x87AC: 'ImageLayer',
    // Private tags
    0x80A4: 'WangAnnotatio',
    0x82A5: 'MDFileTag',
    0x82A6: 'MDScalePixel',
    0x82A7: 'MDColorTable',
    0x82A8: 'MDLabName',
    0x82A9: 'MDSampleInfo',
    0x82AA: 'MDPrepDate',
    0x82AB: 'MDPrepTime',
    0x82AC: 'MDFileUnits',
    0x830E: 'ModelPixelScaleTag',
    0x83BB: 'IPTC',
    0x847E: 'INGRPacketDataTag',
    0x847F: 'INGRFlagRegisters',
    0x8480: 'IrasBTransformationMatrix',
    0x8482: 'ModelTiepointTag',
    0x85D8: 'ModelTransformationTag',
    0x8649: 'Photoshop',
    0x8769: 'ExifIFD',
    0x8773: 'ICCProfile',
    0x87AF: 'GeoKeyDirectoryTag',
    0x87B0: 'GeoDoubleParamsTag',
    0x87B1: 'GeoAsciiParamsTag',
    0x8825: 'GPSIFD',
    0x885C: 'HylaFAXFaxRecvParams',
    0x885D: 'HylaFAXFaxSubAddress',
    0x885E: 'HylaFAXFaxRecvTime',
    0x935C: 'ImageSourceData',
    0xA005: 'InteroperabilityIFD',
    0xA480: 'GDAL_METADATA',
    0xA481: 'GDAL_NODATA',
    0xC427: 'OceScanjobDescription',
    0xC428: 'OceApplicationSelector',
    0xC429: 'OceIdentificationNumber',
    0xC42A: 'OceImageLogicCharacteristics',
    0xC612: 'DNGVersion',
    0xC613: 'DNGBackwardVersion',
    0xC614: 'UniqueCameraModel',
    0xC615: 'LocalizedCameraModel',
    0xC616: 'CFAPlaneColor',
    0xC617: 'CFALayout',
    0xC618: 'LinearizationTable',
    0xC619: 'BlackLevelRepeatDim',
    0xC61A: 'BlackLevel',
    0xC61B: 'BlackLevelDeltaH',
    0xC61C: 'BlackLevelDeltaV',
    0xC61D: 'WhiteLevel',
    0xC61E: 'DefaultScale',
    0xC61F: 'DefaultCropOrigin',
    0xC620: 'DefaultCropSize',
    0xC621: 'ColorMatrix1',
    0xC622: 'ColorMatrix2',
    0xC623: 'CameraCalibration1',
    0xC624: 'CameraCalibration2',
    0xC625: 'ReductionMatrix1',
    0xC626: 'ReductionMatrix2',
    0xC627: 'AnalogBalance',
    0xC628: 'AsShotNeutral',
    0xC629: 'AsShotWhiteXY',
    0xC62A: 'BaselineExposure',
    0xC62B: 'BaselineNoise',
    0xC62C: 'BaselineSharpness',
    0xC62D: 'BayerGreenSplit',
    0xC62E: 'LinearResponseLimit',
    0xC62F: 'CameraSerialNumber',
    0xC630: 'LensInfo',
    0xC631: 'ChromaBlurRadius',
    0xC632: 'AntiAliasStrength',
    0xC634: 'DNGPrivateData',
    0xC635: 'MakerNoteSafety',
    0xC65A: 'CalibrationIlluminant1',
    0xC65B: 'CalibrationIlluminant2',
    0xC65C: 'BestQualityScale',
    0xC660: 'AliasLayerMetadata'
  };
  const tagsByName$5 = {};
  for (var i$2 in tagsById$5) {
    tagsByName$5[tagsById$5[i$2]] = i$2;
  }
  var standard$1 = {
    tagsById: tagsById$5,
    tagsByName: tagsByName$5
  };

  const tagsById$4 = {
    0x829A: 'ExposureTime',
    0x829D: 'FNumber',
    0x8822: 'ExposureProgram',
    0x8824: 'SpectralSensitivity',
    0x8827: 'ISOSpeedRatings',
    0x8828: 'OECF',
    0x8830: 'SensitivityType',
    0x8831: 'StandardOutputSensitivity',
    0x8832: 'RecommendedExposureIndex',
    0x8833: 'ISOSpeed',
    0x8834: 'ISOSpeedLatitudeyyy',
    0x8835: 'ISOSpeedLatitudezzz',
    0x9000: 'ExifVersion',
    0x9003: 'DateTimeOriginal',
    0x9004: 'DateTimeDigitized',
    0x9101: 'ComponentsConfiguration',
    0x9102: 'CompressedBitsPerPixel',
    0x9201: 'ShutterSpeedValue',
    0x9202: 'ApertureValue',
    0x9203: 'BrightnessValue',
    0x9204: 'ExposureBiasValue',
    0x9205: 'MaxApertureValue',
    0x9206: 'SubjectDistance',
    0x9207: 'MeteringMode',
    0x9208: 'LightSource',
    0x9209: 'Flash',
    0x920A: 'FocalLength',
    0x9214: 'SubjectArea',
    0x927C: 'MakerNote',
    0x9286: 'UserComment',
    0x9290: 'SubsecTime',
    0x9291: 'SubsecTimeOriginal',
    0x9292: 'SubsecTimeDigitized',
    0xA000: 'FlashpixVersion',
    0xA001: 'ColorSpace',
    0xA002: 'PixelXDimension',
    0xA003: 'PixelYDimension',
    0xA004: 'RelatedSoundFile',
    0xA20B: 'FlashEnergy',
    0xA20C: 'SpatialFrequencyResponse',
    0xA20E: 'FocalPlaneXResolution',
    0xA20F: 'FocalPlaneYResolution',
    0xA210: 'FocalPlaneResolutionUnit',
    0xA214: 'SubjectLocation',
    0xA215: 'ExposureIndex',
    0xA217: 'SensingMethod',
    0xA300: 'FileSource',
    0xA301: 'SceneType',
    0xA302: 'CFAPattern',
    0xA401: 'CustomRendered',
    0xA402: 'ExposureMode',
    0xA403: 'WhiteBalance',
    0xA404: 'DigitalZoomRatio',
    0xA405: 'FocalLengthIn35mmFilm',
    0xA406: 'SceneCaptureType',
    0xA407: 'GainControl',
    0xA408: 'Contrast',
    0xA409: 'Saturation',
    0xA40A: 'Sharpness',
    0xA40B: 'DeviceSettingDescription',
    0xA40C: 'SubjectDistanceRange',
    0xA420: 'ImageUniqueID',
    0xA430: 'CameraOwnerName',
    0xA431: 'BodySerialNumber',
    0xA432: 'LensSpecification',
    0xA433: 'LensMake',
    0xA434: 'LensModel',
    0xA435: 'LensSerialNumber',
    0xA500: 'Gamma'
  };
  const tagsByName$4 = {};
  for (var i$1 in tagsById$4) {
    tagsByName$4[tagsById$4[i$1]] = i$1;
  }
  var exif$1 = {
    tagsById: tagsById$4,
    tagsByName: tagsByName$4
  };

  const tagsById$3 = {
    0x0000: 'GPSVersionID',
    0x0001: 'GPSLatitudeRef',
    0x0002: 'GPSLatitude',
    0x0003: 'GPSLongitudeRef',
    0x0004: 'GPSLongitude',
    0x0005: 'GPSAltitudeRef',
    0x0006: 'GPSAltitude',
    0x0007: 'GPSTimeStamp',
    0x0008: 'GPSSatellites',
    0x0009: 'GPSStatus',
    0x000A: 'GPSMeasureMode',
    0x000B: 'GPSDOP',
    0x000C: 'GPSSpeedRef',
    0x000D: 'GPSSpeed',
    0x000E: 'GPSTrackRef',
    0x000F: 'GPSTrack',
    0x0010: 'GPSImgDirectionRef',
    0x0011: 'GPSImgDirection',
    0x0012: 'GPSMapDatum',
    0x0013: 'GPSDestLatitudeRef',
    0x0014: 'GPSDestLatitude',
    0x0015: 'GPSDestLongitudeRef',
    0x0016: 'GPSDestLongitude',
    0x0017: 'GPSDestBearingRef',
    0x0018: 'GPSDestBearing',
    0x0019: 'GPSDestDistanceRef',
    0x001A: 'GPSDestDistance',
    0x001B: 'GPSProcessingMethod',
    0x001C: 'GPSAreaInformation',
    0x001D: 'GPSDateStamp',
    0x001E: 'GPSDifferential',
    0x001F: 'GPSHPositioningError'
  };
  const tagsByName$3 = {};
  for (var i in tagsById$3) {
    tagsByName$3[tagsById$3[i]] = i;
  }
  var gps$1 = {
    tagsById: tagsById$3,
    tagsByName: tagsByName$3
  };

  const tags$1 = {
    standard: standard$1,
    exif: exif$1,
    gps: gps$1
  };
  let IFD$2 = class IFD {
    constructor(kind) {
      if (!kind) {
        throw new Error('missing kind');
      }
      this.data = null;
      this.fields = new Map();
      this.kind = kind;
      this._map = null;
    }
    get(tag) {
      if (typeof tag === 'number') {
        return this.fields.get(tag);
      } else if (typeof tag === 'string') {
        return this.fields.get(tags$1[this.kind].tagsByName[tag]);
      } else {
        throw new Error('expected a number or string');
      }
    }
    get map() {
      if (!this._map) {
        this._map = {};
        const taglist = tags$1[this.kind].tagsById;
        for (var key of this.fields.keys()) {
          if (taglist[key]) {
            this._map[taglist[key]] = this.fields.get(key);
          }
        }
      }
      return this._map;
    }
  };
  var ifd = IFD$2;

  const Ifd = ifd;
  const dateTimeRegex$1 = /^(\d{4}):(\d{2}):(\d{2}) (\d{2}):(\d{2}):(\d{2})$/;
  let TiffIfd$1 = class TiffIfd extends Ifd {
    constructor() {
      super('standard');
    }

    // Custom fields
    get size() {
      return this.width * this.height;
    }
    get width() {
      return this.imageWidth;
    }
    get height() {
      return this.imageLength;
    }
    get components() {
      return this.samplesPerPixel;
    }
    get date() {
      var date = new Date();
      var result = dateTimeRegex$1.exec(this.dateTime);
      date.setFullYear(result[1], result[2] - 1, result[3]);
      date.setHours(result[4], result[5], result[6]);
      return date;
    }

    // IFD fields
    get newSubfileType() {
      return this.get(254);
    }
    get imageWidth() {
      return this.get(256);
    }
    get imageLength() {
      return this.get(257);
    }
    get bitsPerSample() {
      return this.get(258);
    }
    get compression() {
      return this.get(259) || 1;
    }
    get type() {
      return this.get(262);
    }
    get fillOrder() {
      return this.get(266) || 1;
    }
    get documentName() {
      return this.get(269);
    }
    get imageDescription() {
      return this.get(270);
    }
    get stripOffsets() {
      return alwaysArray$1(this.get(273));
    }
    get orientation() {
      return this.get(274);
    }
    get samplesPerPixel() {
      return this.get(277);
    }
    get rowsPerStrip() {
      return this.get(278);
    }
    get stripByteCounts() {
      return alwaysArray$1(this.get(279));
    }
    get minSampleValue() {
      return this.get(280) || 0;
    }
    get maxSampleValue() {
      return this.get(281) || Math.pow(2, this.bitsPerSample) - 1;
    }
    get xResolution() {
      return this.get(282);
    }
    get yResolution() {
      return this.get(283);
    }
    get planarConfiguration() {
      return this.get(284) || 1;
    }
    get resolutionUnit() {
      return this.get(296) || 2;
    }
    get dateTime() {
      return this.get(306);
    }
    get predictor() {
      return this.get(317) || 1;
    }
    get sampleFormat() {
      return this.get(339) || 1;
    }
    get sMinSampleValue() {
      return this.get(340) || this.minSampleValue;
    }
    get sMaxSampleValue() {
      return this.get(341) || this.maxSampleValue;
    }
  };
  function alwaysArray$1(value) {
    if (typeof value === 'number') return [value];
    return value;
  }
  var tiffIfd = TiffIfd$1;

  var ifdValue = {};

  var types$1 = new Map([[1, [1, readByte$1]],
  // BYTE
  [2, [1, readASCII$1]],
  // ASCII
  [3, [2, readShort$1]],
  // SHORT
  [4, [4, readLong$1]],
  // LONG
  [5, [8, readRational$1]],
  // RATIONAL
  [6, [1, readSByte$1]],
  // SBYTE
  [7, [1, readByte$1]],
  // UNDEFINED
  [8, [2, readSShort$1]],
  // SSHORT
  [9, [4, readSLong$1]],
  // SLONG
  [10, [8, readSRational$1]],
  // SRATIONAL
  [11, [4, readFloat$1]],
  // FLOAT
  [12, [8, readDouble$1]] // DOUBLE
  ]);
  ifdValue.getByteLength = function (type, count) {
    return types$1.get(type)[0] * count;
  };
  ifdValue.readData = function (decoder, type, count) {
    return types$1.get(type)[1](decoder, count);
  };
  function readByte$1(decoder, count) {
    if (count === 1) return decoder.readUint8();
    var array = new Uint8Array(count);
    for (var i = 0; i < count; i++) {
      array[i] = decoder.readUint8();
    }
    return array;
  }
  function readASCII$1(decoder, count) {
    var strings = [];
    var currentString = '';
    for (var i = 0; i < count; i++) {
      var char = String.fromCharCode(decoder.readUint8());
      if (char === '\0') {
        strings.push(currentString);
        currentString = '';
      } else {
        currentString += char;
      }
    }
    if (strings.length === 1) {
      return strings[0];
    } else {
      return strings;
    }
  }
  function readShort$1(decoder, count) {
    if (count === 1) return decoder.readUint16();
    var array = new Uint16Array(count);
    for (var i = 0; i < count; i++) {
      array[i] = decoder.readUint16();
    }
    return array;
  }
  function readLong$1(decoder, count) {
    if (count === 1) return decoder.readUint32();
    var array = new Uint32Array(count);
    for (var i = 0; i < count; i++) {
      array[i] = decoder.readUint32();
    }
    return array;
  }
  function readRational$1(decoder, count) {
    if (count === 1) {
      return decoder.readUint32() / decoder.readUint32();
    }
    var rationals = new Array(count);
    for (var i = 0; i < count; i++) {
      rationals[i] = decoder.readUint32() / decoder.readUint32();
    }
    return rationals;
  }
  function readSByte$1(decoder, count) {
    if (count === 1) return decoder.readInt8();
    var array = new Int8Array(count);
    for (var i = 0; i < count; i++) {
      array[i] = decoder.readInt8();
    }
    return array;
  }
  function readSShort$1(decoder, count) {
    if (count === 1) return decoder.readInt16();
    var array = new Int16Array(count);
    for (var i = 0; i < count; i++) {
      array[i] = decoder.readInt16();
    }
    return array;
  }
  function readSLong$1(decoder, count) {
    if (count === 1) return decoder.readInt32();
    var array = new Int32Array(count);
    for (var i = 0; i < count; i++) {
      array[i] = decoder.readInt32();
    }
    return array;
  }
  function readSRational$1(decoder, count) {
    if (count === 1) {
      return decoder.readInt32() / decoder.readInt32();
    }
    var rationals = new Array(count);
    for (var i = 0; i < count; i++) {
      rationals[i] = decoder.readInt32() / decoder.readInt32();
    }
    return rationals;
  }
  function readFloat$1(decoder, count) {
    if (count === 1) return decoder.readFloat32();
    var array = new Float32Array(count);
    for (var i = 0; i < count; i++) {
      array[i] = decoder.readFloat32();
    }
    return array;
  }
  function readDouble$1(decoder, count) {
    if (count === 1) return decoder.readFloat64();
    var array = new Float64Array(count);
    for (var i = 0; i < count; i++) {
      array[i] = decoder.readFloat64();
    }
    return array;
  }

  const IOBuffer$1 = IOBuffer_1;
  const IFD$1 = ifd;
  const TiffIFD = tiffIfd;
  const IFDValue = ifdValue;
  const defaultOptions$d = {
    ignoreImageData: false,
    onlyFirst: false
  };
  let TIFFDecoder$2 = class TIFFDecoder extends IOBuffer$1 {
    constructor(data, options) {
      super(data, options);
      this._nextIFD = 0;
    }
    decode(options) {
      options = Object.assign({}, defaultOptions$d, options);
      const result = [];
      this.decodeHeader();
      while (this._nextIFD) {
        result.push(this.decodeIFD(options));
        if (options.onlyFirst) {
          return result[0];
        }
      }
      return result;
    }
    decodeHeader() {
      // Byte offset
      let value = this.readUint16();
      if (value === 0x4949) {
        this.setLittleEndian();
      } else if (value === 0x4D4D) {
        this.setBigEndian();
      } else {
        throw new Error('invalid byte order: 0x' + value.toString(16));
      }

      // Magic number
      value = this.readUint16();
      if (value !== 42) {
        throw new Error('not a TIFF file');
      }

      // Offset of the first IFD
      this._nextIFD = this.readUint32();
    }
    decodeIFD(options) {
      this.seek(this._nextIFD);
      var ifd;
      if (!options.kind) {
        ifd = new TiffIFD();
      } else {
        ifd = new IFD$1(options.kind);
      }
      const numEntries = this.readUint16();
      for (var i = 0; i < numEntries; i++) {
        this.decodeIFDEntry(ifd);
      }
      if (!options.ignoreImageData) {
        this.decodeImageData(ifd);
      }
      this._nextIFD = this.readUint32();
      return ifd;
    }
    decodeIFDEntry(ifd) {
      const offset = this.offset;
      const tag = this.readUint16();
      const type = this.readUint16();
      const numValues = this.readUint32();
      if (type < 1 || type > 12) {
        this.skip(4); // unknown type, skip this value
        return;
      }
      const valueByteLength = IFDValue.getByteLength(type, numValues);
      if (valueByteLength > 4) {
        this.seek(this.readUint32());
      }
      const value = IFDValue.readData(this, type, numValues);
      ifd.fields.set(tag, value);

      // Read sub-IFDs
      if (tag === 0x8769 || tag === 0x8825) {
        let currentOffset = this.offset;
        let kind;
        if (tag === 0x8769) {
          kind = 'exif';
        } else if (tag === 0x8825) {
          kind = 'gps';
        }
        this._nextIFD = value;
        ifd[kind] = this.decodeIFD({
          kind,
          ignoreImageData: true
        });
        this.offset = currentOffset;
      }

      // go to the next entry
      this.seek(offset);
      this.skip(12);
    }
    decodeImageData(ifd) {
      const orientation = ifd.orientation;
      if (orientation && orientation !== 1) {
        unsupported$1('orientation', orientation);
      }
      switch (ifd.type) {
        case 1: // BlackIsZero
        case 2:
          // RGB
          this.readStripData(ifd);
          break;
        default:
          unsupported$1('image type', ifd.type);
          break;
      }
    }
    readStripData(ifd) {
      const width = ifd.width;
      const height = ifd.height;
      const bitDepth = validateBitDepth(ifd.bitsPerSample);
      const sampleFormat = ifd.sampleFormat;
      let size = width * height;
      const data = getDataArray$1(size, 1, bitDepth, sampleFormat);
      const compression = ifd.compression;
      const rowsPerStrip = ifd.rowsPerStrip;
      const maxPixels = rowsPerStrip * width;
      const stripOffsets = ifd.stripOffsets;
      const stripByteCounts = ifd.stripByteCounts;
      var pixel = 0;
      for (var i = 0; i < stripOffsets.length; i++) {
        var stripData = this.getStripData(compression, stripOffsets[i], stripByteCounts[i]);
        // Last strip can be smaller
        var length = size > maxPixels ? maxPixels : size;
        size -= length;
        if (bitDepth === 8) {
          pixel = fill8bit$1(data, stripData, pixel, length);
        } else if (bitDepth === 16) {
          pixel = fill16bit$1(data, stripData, pixel, length, this.isLittleEndian());
        } else if (bitDepth === 32 && sampleFormat === 3) {
          pixel = fillFloat32$1(data, stripData, pixel, length, this.isLittleEndian());
        } else {
          unsupported$1('bitDepth', bitDepth);
        }
      }
      ifd.data = data;
    }
    getStripData(compression, offset, byteCounts) {
      switch (compression) {
        case 1:
          // No compression
          return new DataView(this.buffer, offset, byteCounts);
        case 2: // CCITT Group 3 1-Dimensional Modified Huffman run length encoding
        case 32773:
          // PackBits compression
          return unsupported$1('Compression', compression);
        default:
          throw new Error('invalid compression: ' + compression);
      }
    }
  };
  var tiffDecoder = TIFFDecoder$2;
  function getDataArray$1(size, channels, bitDepth, sampleFormat) {
    if (bitDepth === 8) {
      return new Uint8Array(size * channels);
    } else if (bitDepth === 16) {
      return new Uint16Array(size * channels);
    } else if (bitDepth === 32 && sampleFormat === 3) {
      return new Float32Array(size * channels);
    } else {
      return unsupported$1('bit depth / sample format', bitDepth + ' / ' + sampleFormat);
    }
  }
  function fill8bit$1(dataTo, dataFrom, index, length) {
    for (var i = 0; i < length; i++) {
      dataTo[index++] = dataFrom.getUint8(i);
    }
    return index;
  }
  function fill16bit$1(dataTo, dataFrom, index, length, littleEndian) {
    for (var i = 0; i < length * 2; i += 2) {
      dataTo[index++] = dataFrom.getUint16(i, littleEndian);
    }
    return index;
  }
  function fillFloat32$1(dataTo, dataFrom, index, length, littleEndian) {
    for (var i = 0; i < length * 4; i += 4) {
      dataTo[index++] = dataFrom.getFloat32(i, littleEndian);
    }
    return index;
  }
  function unsupported$1(type, value) {
    throw new Error('Unsupported ' + type + ': ' + value);
  }
  function validateBitDepth(bitDepth) {
    if (bitDepth.length) {
      const bitDepthArray = bitDepth;
      bitDepth = bitDepthArray[0];
      for (var i = 0; i < bitDepthArray.length; i++) {
        if (bitDepthArray[i] !== bitDepth) {
          unsupported$1('bit depth', bitDepthArray);
        }
      }
    }
    return bitDepth;
  }

  const TIFFDecoder$1 = tiffDecoder;
  var decode$2 = function decodeTIFF(data, options) {
    const decoder = new TIFFDecoder$1(data, options);
    return decoder.decode(options);
  };

  src$3.decode = decode$2;

  const IOBuffer = IOBuffer_1;
  const tiff = src$3;
  function decode$1(data) {
    const buffer = new IOBuffer(data);
    const result = {};
    buffer.setBigEndian();
    const val = buffer.readUint16();
    if (val !== 0xffd8) {
      throw new Error('SOI marker not found. Not a valid JPEG file');
    }
    const next = buffer.readUint16();
    if (next === 0xffe1) {
      buffer.readUint16();
      const header = buffer.readBytes(6);
      if (header[0] === 69 &&
      // E
      header[1] === 120 &&
      // x
      header[2] === 105 &&
      // i
      header[3] === 102 &&
      // f
      header[4] === 0 && header[5] === 0) {
        //     buffer.skip(2);
        const exif = tiff.decode(buffer, {
          onlyFirst: true,
          ignoreImageData: true,
          offset: buffer.offset
        });
        result.exif = exif;
      }
    }
    return result;
  }
  var decode_1 = decode$1;

  var decode = decode_1;

  var imageType$2 = {exports: {}};

  var fileType$1 = {exports: {}};

  (function (module) {

    const toBytes = s => [...s].map(c => c.charCodeAt(0));
    const xpiZipFilename = toBytes('META-INF/mozilla.rsa');
    const oxmlContentTypes = toBytes('[Content_Types].xml');
    const oxmlRels = toBytes('_rels/.rels');
    function readUInt64LE(buf, offset = 0) {
      let n = buf[offset];
      let mul = 1;
      let i = 0;
      while (++i < 8) {
        mul *= 0x100;
        n += buf[offset + i] * mul;
      }
      return n;
    }
    const fileType = input => {
      if (!(input instanceof Uint8Array || input instanceof ArrayBuffer || Buffer.isBuffer(input))) {
        throw new TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`Buffer\` or \`ArrayBuffer\`, got \`${typeof input}\``);
      }
      const buf = input instanceof Uint8Array ? input : new Uint8Array(input);
      if (!(buf && buf.length > 1)) {
        return null;
      }
      const check = (header, options) => {
        options = Object.assign({
          offset: 0
        }, options);
        for (let i = 0; i < header.length; i++) {
          // If a bitmask is set
          if (options.mask) {
            // If header doesn't equal `buf` with bits masked off
            if (header[i] !== (options.mask[i] & buf[i + options.offset])) {
              return false;
            }
          } else if (header[i] !== buf[i + options.offset]) {
            return false;
          }
        }
        return true;
      };
      const checkString = (header, options) => check(toBytes(header), options);
      if (check([0xFF, 0xD8, 0xFF])) {
        return {
          ext: 'jpg',
          mime: 'image/jpeg'
        };
      }
      if (check([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])) {
        return {
          ext: 'png',
          mime: 'image/png'
        };
      }
      if (check([0x47, 0x49, 0x46])) {
        return {
          ext: 'gif',
          mime: 'image/gif'
        };
      }
      if (check([0x57, 0x45, 0x42, 0x50], {
        offset: 8
      })) {
        return {
          ext: 'webp',
          mime: 'image/webp'
        };
      }
      if (check([0x46, 0x4C, 0x49, 0x46])) {
        return {
          ext: 'flif',
          mime: 'image/flif'
        };
      }

      // Needs to be before `tif` check
      if ((check([0x49, 0x49, 0x2A, 0x0]) || check([0x4D, 0x4D, 0x0, 0x2A])) && check([0x43, 0x52], {
        offset: 8
      })) {
        return {
          ext: 'cr2',
          mime: 'image/x-canon-cr2'
        };
      }
      if (check([0x49, 0x49, 0x2A, 0x0]) || check([0x4D, 0x4D, 0x0, 0x2A])) {
        return {
          ext: 'tif',
          mime: 'image/tiff'
        };
      }
      if (check([0x42, 0x4D])) {
        return {
          ext: 'bmp',
          mime: 'image/bmp'
        };
      }
      if (check([0x49, 0x49, 0xBC])) {
        return {
          ext: 'jxr',
          mime: 'image/vnd.ms-photo'
        };
      }
      if (check([0x38, 0x42, 0x50, 0x53])) {
        return {
          ext: 'psd',
          mime: 'image/vnd.adobe.photoshop'
        };
      }

      // Zip-based file formats
      // Need to be before the `zip` check
      if (check([0x50, 0x4B, 0x3, 0x4])) {
        if (check([0x6D, 0x69, 0x6D, 0x65, 0x74, 0x79, 0x70, 0x65, 0x61, 0x70, 0x70, 0x6C, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x2F, 0x65, 0x70, 0x75, 0x62, 0x2B, 0x7A, 0x69, 0x70], {
          offset: 30
        })) {
          return {
            ext: 'epub',
            mime: 'application/epub+zip'
          };
        }

        // Assumes signed `.xpi` from addons.mozilla.org
        if (check(xpiZipFilename, {
          offset: 30
        })) {
          return {
            ext: 'xpi',
            mime: 'application/x-xpinstall'
          };
        }
        if (checkString('mimetypeapplication/vnd.oasis.opendocument.text', {
          offset: 30
        })) {
          return {
            ext: 'odt',
            mime: 'application/vnd.oasis.opendocument.text'
          };
        }
        if (checkString('mimetypeapplication/vnd.oasis.opendocument.spreadsheet', {
          offset: 30
        })) {
          return {
            ext: 'ods',
            mime: 'application/vnd.oasis.opendocument.spreadsheet'
          };
        }
        if (checkString('mimetypeapplication/vnd.oasis.opendocument.presentation', {
          offset: 30
        })) {
          return {
            ext: 'odp',
            mime: 'application/vnd.oasis.opendocument.presentation'
          };
        }

        // The docx, xlsx and pptx file types extend the Office Open XML file format:
        // https://en.wikipedia.org/wiki/Office_Open_XML_file_formats
        // We look for:
        // - one entry named '[Content_Types].xml' or '_rels/.rels',
        // - one entry indicating specific type of file.
        // MS Office, OpenOffice and LibreOffice may put the parts in different order, so the check should not rely on it.
        const findNextZipHeaderIndex = (arr, startAt = 0) => arr.findIndex((el, i, arr) => i >= startAt && arr[i] === 0x50 && arr[i + 1] === 0x4B && arr[i + 2] === 0x3 && arr[i + 3] === 0x4);
        let zipHeaderIndex = 0; // The first zip header was already found at index 0
        let oxmlFound = false;
        let type = null;
        do {
          const offset = zipHeaderIndex + 30;
          if (!oxmlFound) {
            oxmlFound = check(oxmlContentTypes, {
              offset
            }) || check(oxmlRels, {
              offset
            });
          }
          if (!type) {
            if (checkString('word/', {
              offset
            })) {
              type = {
                ext: 'docx',
                mime: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
              };
            } else if (checkString('ppt/', {
              offset
            })) {
              type = {
                ext: 'pptx',
                mime: 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
              };
            } else if (checkString('xl/', {
              offset
            })) {
              type = {
                ext: 'xlsx',
                mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
              };
            }
          }
          if (oxmlFound && type) {
            return type;
          }
          zipHeaderIndex = findNextZipHeaderIndex(buf, offset);
        } while (zipHeaderIndex >= 0);

        // No more zip parts available in the buffer, but maybe we are almost certain about the type?
        if (type) {
          return type;
        }
      }
      if (check([0x50, 0x4B]) && (buf[2] === 0x3 || buf[2] === 0x5 || buf[2] === 0x7) && (buf[3] === 0x4 || buf[3] === 0x6 || buf[3] === 0x8)) {
        return {
          ext: 'zip',
          mime: 'application/zip'
        };
      }
      if (check([0x75, 0x73, 0x74, 0x61, 0x72], {
        offset: 257
      })) {
        return {
          ext: 'tar',
          mime: 'application/x-tar'
        };
      }
      if (check([0x52, 0x61, 0x72, 0x21, 0x1A, 0x7]) && (buf[6] === 0x0 || buf[6] === 0x1)) {
        return {
          ext: 'rar',
          mime: 'application/x-rar-compressed'
        };
      }
      if (check([0x1F, 0x8B, 0x8])) {
        return {
          ext: 'gz',
          mime: 'application/gzip'
        };
      }
      if (check([0x42, 0x5A, 0x68])) {
        return {
          ext: 'bz2',
          mime: 'application/x-bzip2'
        };
      }
      if (check([0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C])) {
        return {
          ext: '7z',
          mime: 'application/x-7z-compressed'
        };
      }
      if (check([0x78, 0x01])) {
        return {
          ext: 'dmg',
          mime: 'application/x-apple-diskimage'
        };
      }
      if (check([0x33, 0x67, 0x70, 0x35]) ||
      // 3gp5

      check([0x0, 0x0, 0x0]) && check([0x66, 0x74, 0x79, 0x70], {
        offset: 4
      }) && (check([0x6D, 0x70, 0x34, 0x31], {
        offset: 8
      }) ||
      // MP41
      check([0x6D, 0x70, 0x34, 0x32], {
        offset: 8
      }) ||
      // MP42
      check([0x69, 0x73, 0x6F, 0x6D], {
        offset: 8
      }) ||
      // ISOM
      check([0x69, 0x73, 0x6F, 0x32], {
        offset: 8
      }) ||
      // ISO2
      check([0x6D, 0x6D, 0x70, 0x34], {
        offset: 8
      }) ||
      // MMP4
      check([0x4D, 0x34, 0x56], {
        offset: 8
      }) ||
      // M4V
      check([0x64, 0x61, 0x73, 0x68], {
        offset: 8
      }) // DASH
      )) {
        return {
          ext: 'mp4',
          mime: 'video/mp4'
        };
      }
      if (check([0x4D, 0x54, 0x68, 0x64])) {
        return {
          ext: 'mid',
          mime: 'audio/midi'
        };
      }

      // https://github.com/threatstack/libmagic/blob/master/magic/Magdir/matroska
      if (check([0x1A, 0x45, 0xDF, 0xA3])) {
        const sliced = buf.subarray(4, 4 + 4096);
        const idPos = sliced.findIndex((el, i, arr) => arr[i] === 0x42 && arr[i + 1] === 0x82);
        if (idPos !== -1) {
          const docTypePos = idPos + 3;
          const findDocType = type => [...type].every((c, i) => sliced[docTypePos + i] === c.charCodeAt(0));
          if (findDocType('matroska')) {
            return {
              ext: 'mkv',
              mime: 'video/x-matroska'
            };
          }
          if (findDocType('webm')) {
            return {
              ext: 'webm',
              mime: 'video/webm'
            };
          }
        }
      }
      if (check([0x0, 0x0, 0x0, 0x14, 0x66, 0x74, 0x79, 0x70, 0x71, 0x74, 0x20, 0x20]) || check([0x66, 0x72, 0x65, 0x65], {
        offset: 4
      }) ||
      // Type: `free`
      check([0x66, 0x74, 0x79, 0x70, 0x71, 0x74, 0x20, 0x20], {
        offset: 4
      }) || check([0x6D, 0x64, 0x61, 0x74], {
        offset: 4
      }) ||
      // MJPEG
      check([0x6D, 0x6F, 0x6F, 0x76], {
        offset: 4
      }) ||
      // Type: `moov`
      check([0x77, 0x69, 0x64, 0x65], {
        offset: 4
      })) {
        return {
          ext: 'mov',
          mime: 'video/quicktime'
        };
      }

      // RIFF file format which might be AVI, WAV, QCP, etc
      if (check([0x52, 0x49, 0x46, 0x46])) {
        if (check([0x41, 0x56, 0x49], {
          offset: 8
        })) {
          return {
            ext: 'avi',
            mime: 'video/vnd.avi'
          };
        }
        if (check([0x57, 0x41, 0x56, 0x45], {
          offset: 8
        })) {
          return {
            ext: 'wav',
            mime: 'audio/vnd.wave'
          };
        }

        // QLCM, QCP file
        if (check([0x51, 0x4C, 0x43, 0x4D], {
          offset: 8
        })) {
          return {
            ext: 'qcp',
            mime: 'audio/qcelp'
          };
        }
      }

      // ASF_Header_Object first 80 bytes
      if (check([0x30, 0x26, 0xB2, 0x75, 0x8E, 0x66, 0xCF, 0x11, 0xA6, 0xD9])) {
        // Search for header should be in first 1KB of file.

        let offset = 30;
        do {
          const objectSize = readUInt64LE(buf, offset + 16);
          if (check([0x91, 0x07, 0xDC, 0xB7, 0xB7, 0xA9, 0xCF, 0x11, 0x8E, 0xE6, 0x00, 0xC0, 0x0C, 0x20, 0x53, 0x65], {
            offset
          })) {
            // Sync on Stream-Properties-Object (B7DC0791-A9B7-11CF-8EE6-00C00C205365)
            if (check([0x40, 0x9E, 0x69, 0xF8, 0x4D, 0x5B, 0xCF, 0x11, 0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B], {
              offset: offset + 24
            })) {
              // Found audio:
              return {
                ext: 'wma',
                mime: 'audio/x-ms-wma'
              };
            }
            if (check([0xC0, 0xEF, 0x19, 0xBC, 0x4D, 0x5B, 0xCF, 0x11, 0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B], {
              offset: offset + 24
            })) {
              // Found video:
              return {
                ext: 'wmv',
                mime: 'video/x-ms-asf'
              };
            }
            break;
          }
          offset += objectSize;
        } while (offset + 24 <= buf.length);

        // Default to ASF generic extension
        return {
          ext: 'asf',
          mime: 'application/vnd.ms-asf'
        };
      }
      if (check([0x0, 0x0, 0x1, 0xBA]) || check([0x0, 0x0, 0x1, 0xB3])) {
        return {
          ext: 'mpg',
          mime: 'video/mpeg'
        };
      }
      if (check([0x66, 0x74, 0x79, 0x70, 0x33, 0x67], {
        offset: 4
      })) {
        return {
          ext: '3gp',
          mime: 'video/3gpp'
        };
      }

      // Check for MPEG header at different starting offsets
      for (let start = 0; start < 2 && start < buf.length - 16; start++) {
        if (check([0x49, 0x44, 0x33], {
          offset: start
        }) ||
        // ID3 header
        check([0xFF, 0xE2], {
          offset: start,
          mask: [0xFF, 0xE2]
        }) // MPEG 1 or 2 Layer 3 header
        ) {
          return {
            ext: 'mp3',
            mime: 'audio/mpeg'
          };
        }
        if (check([0xFF, 0xE4], {
          offset: start,
          mask: [0xFF, 0xE4]
        }) // MPEG 1 or 2 Layer 2 header
        ) {
          return {
            ext: 'mp2',
            mime: 'audio/mpeg'
          };
        }
        if (check([0xFF, 0xF8], {
          offset: start,
          mask: [0xFF, 0xFC]
        }) // MPEG 2 layer 0 using ADTS
        ) {
          return {
            ext: 'mp2',
            mime: 'audio/mpeg'
          };
        }
        if (check([0xFF, 0xF0], {
          offset: start,
          mask: [0xFF, 0xFC]
        }) // MPEG 4 layer 0 using ADTS
        ) {
          return {
            ext: 'mp4',
            mime: 'audio/mpeg'
          };
        }
      }
      if (check([0x66, 0x74, 0x79, 0x70, 0x4D, 0x34, 0x41], {
        offset: 4
      })) {
        return {
          // MPEG-4 layer 3 (audio)
          ext: 'm4a',
          mime: 'audio/mp4' // RFC 4337
        };
      }

      // Needs to be before `ogg` check
      if (check([0x4F, 0x70, 0x75, 0x73, 0x48, 0x65, 0x61, 0x64], {
        offset: 28
      })) {
        return {
          ext: 'opus',
          mime: 'audio/opus'
        };
      }

      // If 'OggS' in first  bytes, then OGG container
      if (check([0x4F, 0x67, 0x67, 0x53])) {
        // This is a OGG container

        // If ' theora' in header.
        if (check([0x80, 0x74, 0x68, 0x65, 0x6F, 0x72, 0x61], {
          offset: 28
        })) {
          return {
            ext: 'ogv',
            mime: 'video/ogg'
          };
        }

        // If '\x01video' in header.
        if (check([0x01, 0x76, 0x69, 0x64, 0x65, 0x6F, 0x00], {
          offset: 28
        })) {
          return {
            ext: 'ogm',
            mime: 'video/ogg'
          };
        }

        // If ' FLAC' in header  https://xiph.org/flac/faq.html
        if (check([0x7F, 0x46, 0x4C, 0x41, 0x43], {
          offset: 28
        })) {
          return {
            ext: 'oga',
            mime: 'audio/ogg'
          };
        }

        // 'Speex  ' in header https://en.wikipedia.org/wiki/Speex
        if (check([0x53, 0x70, 0x65, 0x65, 0x78, 0x20, 0x20], {
          offset: 28
        })) {
          return {
            ext: 'spx',
            mime: 'audio/ogg'
          };
        }

        // If '\x01vorbis' in header
        if (check([0x01, 0x76, 0x6F, 0x72, 0x62, 0x69, 0x73], {
          offset: 28
        })) {
          return {
            ext: 'ogg',
            mime: 'audio/ogg'
          };
        }

        // Default OGG container https://www.iana.org/assignments/media-types/application/ogg
        return {
          ext: 'ogx',
          mime: 'application/ogg'
        };
      }
      if (check([0x66, 0x4C, 0x61, 0x43])) {
        return {
          ext: 'flac',
          mime: 'audio/x-flac'
        };
      }
      if (check([0x4D, 0x41, 0x43, 0x20])) {
        // 'MAC '
        return {
          ext: 'ape',
          mime: 'audio/ape'
        };
      }
      if (check([0x77, 0x76, 0x70, 0x6B])) {
        // 'wvpk'
        return {
          ext: 'wv',
          mime: 'audio/wavpack'
        };
      }
      if (check([0x23, 0x21, 0x41, 0x4D, 0x52, 0x0A])) {
        return {
          ext: 'amr',
          mime: 'audio/amr'
        };
      }
      if (check([0x25, 0x50, 0x44, 0x46])) {
        return {
          ext: 'pdf',
          mime: 'application/pdf'
        };
      }
      if (check([0x4D, 0x5A])) {
        return {
          ext: 'exe',
          mime: 'application/x-msdownload'
        };
      }
      if ((buf[0] === 0x43 || buf[0] === 0x46) && check([0x57, 0x53], {
        offset: 1
      })) {
        return {
          ext: 'swf',
          mime: 'application/x-shockwave-flash'
        };
      }
      if (check([0x7B, 0x5C, 0x72, 0x74, 0x66])) {
        return {
          ext: 'rtf',
          mime: 'application/rtf'
        };
      }
      if (check([0x00, 0x61, 0x73, 0x6D])) {
        return {
          ext: 'wasm',
          mime: 'application/wasm'
        };
      }
      if (check([0x77, 0x4F, 0x46, 0x46]) && (check([0x00, 0x01, 0x00, 0x00], {
        offset: 4
      }) || check([0x4F, 0x54, 0x54, 0x4F], {
        offset: 4
      }))) {
        return {
          ext: 'woff',
          mime: 'font/woff'
        };
      }
      if (check([0x77, 0x4F, 0x46, 0x32]) && (check([0x00, 0x01, 0x00, 0x00], {
        offset: 4
      }) || check([0x4F, 0x54, 0x54, 0x4F], {
        offset: 4
      }))) {
        return {
          ext: 'woff2',
          mime: 'font/woff2'
        };
      }
      if (check([0x4C, 0x50], {
        offset: 34
      }) && (check([0x00, 0x00, 0x01], {
        offset: 8
      }) || check([0x01, 0x00, 0x02], {
        offset: 8
      }) || check([0x02, 0x00, 0x02], {
        offset: 8
      }))) {
        return {
          ext: 'eot',
          mime: 'application/vnd.ms-fontobject'
        };
      }
      if (check([0x00, 0x01, 0x00, 0x00, 0x00])) {
        return {
          ext: 'ttf',
          mime: 'font/ttf'
        };
      }
      if (check([0x4F, 0x54, 0x54, 0x4F, 0x00])) {
        return {
          ext: 'otf',
          mime: 'font/otf'
        };
      }
      if (check([0x00, 0x00, 0x01, 0x00])) {
        return {
          ext: 'ico',
          mime: 'image/x-icon'
        };
      }
      if (check([0x00, 0x00, 0x02, 0x00])) {
        return {
          ext: 'cur',
          mime: 'image/x-icon'
        };
      }
      if (check([0x46, 0x4C, 0x56, 0x01])) {
        return {
          ext: 'flv',
          mime: 'video/x-flv'
        };
      }
      if (check([0x25, 0x21])) {
        return {
          ext: 'ps',
          mime: 'application/postscript'
        };
      }
      if (check([0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00])) {
        return {
          ext: 'xz',
          mime: 'application/x-xz'
        };
      }
      if (check([0x53, 0x51, 0x4C, 0x69])) {
        return {
          ext: 'sqlite',
          mime: 'application/x-sqlite3'
        };
      }
      if (check([0x4E, 0x45, 0x53, 0x1A])) {
        return {
          ext: 'nes',
          mime: 'application/x-nintendo-nes-rom'
        };
      }
      if (check([0x43, 0x72, 0x32, 0x34])) {
        return {
          ext: 'crx',
          mime: 'application/x-google-chrome-extension'
        };
      }
      if (check([0x4D, 0x53, 0x43, 0x46]) || check([0x49, 0x53, 0x63, 0x28])) {
        return {
          ext: 'cab',
          mime: 'application/vnd.ms-cab-compressed'
        };
      }

      // Needs to be before `ar` check
      if (check([0x21, 0x3C, 0x61, 0x72, 0x63, 0x68, 0x3E, 0x0A, 0x64, 0x65, 0x62, 0x69, 0x61, 0x6E, 0x2D, 0x62, 0x69, 0x6E, 0x61, 0x72, 0x79])) {
        return {
          ext: 'deb',
          mime: 'application/x-deb'
        };
      }
      if (check([0x21, 0x3C, 0x61, 0x72, 0x63, 0x68, 0x3E])) {
        return {
          ext: 'ar',
          mime: 'application/x-unix-archive'
        };
      }
      if (check([0xED, 0xAB, 0xEE, 0xDB])) {
        return {
          ext: 'rpm',
          mime: 'application/x-rpm'
        };
      }
      if (check([0x1F, 0xA0]) || check([0x1F, 0x9D])) {
        return {
          ext: 'Z',
          mime: 'application/x-compress'
        };
      }
      if (check([0x4C, 0x5A, 0x49, 0x50])) {
        return {
          ext: 'lz',
          mime: 'application/x-lzip'
        };
      }
      if (check([0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1])) {
        return {
          ext: 'msi',
          mime: 'application/x-msi'
        };
      }
      if (check([0x06, 0x0E, 0x2B, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0D, 0x01, 0x02, 0x01, 0x01, 0x02])) {
        return {
          ext: 'mxf',
          mime: 'application/mxf'
        };
      }
      if (check([0x47], {
        offset: 4
      }) && (check([0x47], {
        offset: 192
      }) || check([0x47], {
        offset: 196
      }))) {
        return {
          ext: 'mts',
          mime: 'video/mp2t'
        };
      }
      if (check([0x42, 0x4C, 0x45, 0x4E, 0x44, 0x45, 0x52])) {
        return {
          ext: 'blend',
          mime: 'application/x-blender'
        };
      }
      if (check([0x42, 0x50, 0x47, 0xFB])) {
        return {
          ext: 'bpg',
          mime: 'image/bpg'
        };
      }
      if (check([0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0x0D, 0x0A, 0x87, 0x0A])) {
        // JPEG-2000 family

        if (check([0x6A, 0x70, 0x32, 0x20], {
          offset: 20
        })) {
          return {
            ext: 'jp2',
            mime: 'image/jp2'
          };
        }
        if (check([0x6A, 0x70, 0x78, 0x20], {
          offset: 20
        })) {
          return {
            ext: 'jpx',
            mime: 'image/jpx'
          };
        }
        if (check([0x6A, 0x70, 0x6D, 0x20], {
          offset: 20
        })) {
          return {
            ext: 'jpm',
            mime: 'image/jpm'
          };
        }
        if (check([0x6D, 0x6A, 0x70, 0x32], {
          offset: 20
        })) {
          return {
            ext: 'mj2',
            mime: 'image/mj2'
          };
        }
      }
      if (check([0x46, 0x4F, 0x52, 0x4D])) {
        return {
          ext: 'aif',
          mime: 'audio/aiff'
        };
      }
      if (checkString('<?xml ')) {
        return {
          ext: 'xml',
          mime: 'application/xml'
        };
      }
      if (check([0x42, 0x4F, 0x4F, 0x4B, 0x4D, 0x4F, 0x42, 0x49], {
        offset: 60
      })) {
        return {
          ext: 'mobi',
          mime: 'application/x-mobipocket-ebook'
        };
      }

      // File Type Box (https://en.wikipedia.org/wiki/ISO_base_media_file_format)
      if (check([0x66, 0x74, 0x79, 0x70], {
        offset: 4
      })) {
        if (check([0x6D, 0x69, 0x66, 0x31], {
          offset: 8
        })) {
          return {
            ext: 'heic',
            mime: 'image/heif'
          };
        }
        if (check([0x6D, 0x73, 0x66, 0x31], {
          offset: 8
        })) {
          return {
            ext: 'heic',
            mime: 'image/heif-sequence'
          };
        }
        if (check([0x68, 0x65, 0x69, 0x63], {
          offset: 8
        }) || check([0x68, 0x65, 0x69, 0x78], {
          offset: 8
        })) {
          return {
            ext: 'heic',
            mime: 'image/heic'
          };
        }
        if (check([0x68, 0x65, 0x76, 0x63], {
          offset: 8
        }) || check([0x68, 0x65, 0x76, 0x78], {
          offset: 8
        })) {
          return {
            ext: 'heic',
            mime: 'image/heic-sequence'
          };
        }
      }
      if (check([0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A])) {
        return {
          ext: 'ktx',
          mime: 'image/ktx'
        };
      }
      if (check([0x44, 0x49, 0x43, 0x4D], {
        offset: 128
      })) {
        return {
          ext: 'dcm',
          mime: 'application/dicom'
        };
      }

      // Musepack, SV7
      if (check([0x4D, 0x50, 0x2B])) {
        return {
          ext: 'mpc',
          mime: 'audio/x-musepack'
        };
      }

      // Musepack, SV8
      if (check([0x4D, 0x50, 0x43, 0x4B])) {
        return {
          ext: 'mpc',
          mime: 'audio/x-musepack'
        };
      }
      if (check([0x42, 0x45, 0x47, 0x49, 0x4E, 0x3A])) {
        return {
          ext: 'ics',
          mime: 'text/calendar'
        };
      }
      if (check([0x67, 0x6C, 0x54, 0x46, 0x02, 0x00, 0x00, 0x00])) {
        return {
          ext: 'glb',
          mime: 'model/gltf-binary'
        };
      }
      if (check([0xD4, 0xC3, 0xB2, 0xA1]) || check([0xA1, 0xB2, 0xC3, 0xD4])) {
        return {
          ext: 'pcap',
          mime: 'application/vnd.tcpdump.pcap'
        };
      }
      return null;
    };
    module.exports = fileType;
    // TODO: Remove this for the next major release
    module.exports.default = fileType;
    Object.defineProperty(fileType, 'minimumBytes', {
      value: 4100
    });
    module.exports.stream = readableStream => new Promise((resolve, reject) => {
      // Using `eval` to work around issues when bundling with Webpack
      const stream = eval('require')('stream'); // eslint-disable-line no-eval

      readableStream.once('readable', () => {
        const pass = new stream.PassThrough();
        const chunk = readableStream.read(module.exports.minimumBytes) || readableStream.read();
        try {
          pass.fileType = fileType(chunk);
        } catch (error) {
          reject(error);
        }
        readableStream.unshift(chunk);
        if (stream.pipeline) {
          resolve(stream.pipeline(readableStream, pass, () => {}));
        } else {
          resolve(readableStream.pipe(pass));
        }
      });
    });
  })(fileType$1);
  var fileTypeExports = fileType$1.exports;

  const fileType = fileTypeExports;
  const imageExts = new Set(['jpg', 'png', 'gif', 'webp', 'flif', 'cr2', 'tif', 'bmp', 'jxr', 'psd', 'ico', 'bpg', 'jp2', 'jpm', 'jpx', 'heic', 'cur', 'dcm']);
  const imageType = input => {
    const ret = fileType(input);
    return imageExts.has(ret && ret.ext) ? ret : null;
  };
  imageType$2.exports = imageType;
  // TODO: Remove this for the next major release
  imageType$2.exports.default = imageType;
  Object.defineProperty(imageType, 'minimumBytes', {
    value: fileType.minimumBytes
  });
  var imageTypeExports = imageType$2.exports;
  var imageType$1 = /*@__PURE__*/getDefaultExportFromCjs(imageTypeExports);

  function guessStripByteCounts(ifd) {
    if (ifd.compression !== 1) {
      throw new Error('missing mandatory StripByteCounts field in compressed image');
    }
    const bytesPerStrip = ifd.rowsPerStrip * ifd.width * ifd.samplesPerPixel * (ifd.bitsPerSample / 8);
    return new Array(ifd.stripOffsets.length).fill(bytesPerStrip);
  }

  // Section 14: Differencing Predictor (p. 64)
  function applyHorizontalDifferencing8Bit(data, width, components) {
    let i = 0;
    while (i < data.length) {
      for (let j = components; j < width * components; j += components) {
        for (let k = 0; k < components; k++) {
          data[i + j + k] = data[i + j + k] + data[i + j - (components - k)] & 255;
        }
      }
      i += width * components;
    }
  }
  function applyHorizontalDifferencing16Bit(data, width, components) {
    let i = 0;
    while (i < data.length) {
      for (let j = components; j < width * components; j += components) {
        for (let k = 0; k < components; k++) {
          data[i + j + k] = data[i + j + k] + data[i + j - (components - k)] & 65535;
        }
      }
      i += width * components;
    }
  }

  const tagsById$2 = {
    0x829a: 'ExposureTime',
    0x829d: 'FNumber',
    0x8822: 'ExposureProgram',
    0x8824: 'SpectralSensitivity',
    0x8827: 'ISOSpeedRatings',
    0x8828: 'OECF',
    0x8830: 'SensitivityType',
    0x8831: 'StandardOutputSensitivity',
    0x8832: 'RecommendedExposureIndex',
    0x8833: 'ISOSpeed',
    0x8834: 'ISOSpeedLatitudeyyy',
    0x8835: 'ISOSpeedLatitudezzz',
    0x9000: 'ExifVersion',
    0x9003: 'DateTimeOriginal',
    0x9004: 'DateTimeDigitized',
    0x9101: 'ComponentsConfiguration',
    0x9102: 'CompressedBitsPerPixel',
    0x9201: 'ShutterSpeedValue',
    0x9202: 'ApertureValue',
    0x9203: 'BrightnessValue',
    0x9204: 'ExposureBiasValue',
    0x9205: 'MaxApertureValue',
    0x9206: 'SubjectDistance',
    0x9207: 'MeteringMode',
    0x9208: 'LightSource',
    0x9209: 'Flash',
    0x920a: 'FocalLength',
    0x9214: 'SubjectArea',
    0x927c: 'MakerNote',
    0x9286: 'UserComment',
    0x9290: 'SubsecTime',
    0x9291: 'SubsecTimeOriginal',
    0x9292: 'SubsecTimeDigitized',
    0xa000: 'FlashpixVersion',
    0xa001: 'ColorSpace',
    0xa002: 'PixelXDimension',
    0xa003: 'PixelYDimension',
    0xa004: 'RelatedSoundFile',
    0xa20b: 'FlashEnergy',
    0xa20c: 'SpatialFrequencyResponse',
    0xa20e: 'FocalPlaneXResolution',
    0xa20f: 'FocalPlaneYResolution',
    0xa210: 'FocalPlaneResolutionUnit',
    0xa214: 'SubjectLocation',
    0xa215: 'ExposureIndex',
    0xa217: 'SensingMethod',
    0xa300: 'FileSource',
    0xa301: 'SceneType',
    0xa302: 'CFAPattern',
    0xa401: 'CustomRendered',
    0xa402: 'ExposureMode',
    0xa403: 'WhiteBalance',
    0xa404: 'DigitalZoomRatio',
    0xa405: 'FocalLengthIn35mmFilm',
    0xa406: 'SceneCaptureType',
    0xa407: 'GainControl',
    0xa408: 'Contrast',
    0xa409: 'Saturation',
    0xa40a: 'Sharpness',
    0xa40b: 'DeviceSettingDescription',
    0xa40c: 'SubjectDistanceRange',
    0xa420: 'ImageUniqueID',
    0xa430: 'CameraOwnerName',
    0xa431: 'BodySerialNumber',
    0xa432: 'LensSpecification',
    0xa433: 'LensMake',
    0xa434: 'LensModel',
    0xa435: 'LensSerialNumber',
    0xa500: 'Gamma'
  };
  const tagsByName$2 = {};
  for (let i in tagsById$2) {
    tagsByName$2[tagsById$2[i]] = Number(i);
  }

  var exif = /*#__PURE__*/Object.freeze({
    __proto__: null,
    tagsById: tagsById$2,
    tagsByName: tagsByName$2
  });

  const tagsById$1 = {
    0x0000: 'GPSVersionID',
    0x0001: 'GPSLatitudeRef',
    0x0002: 'GPSLatitude',
    0x0003: 'GPSLongitudeRef',
    0x0004: 'GPSLongitude',
    0x0005: 'GPSAltitudeRef',
    0x0006: 'GPSAltitude',
    0x0007: 'GPSTimeStamp',
    0x0008: 'GPSSatellites',
    0x0009: 'GPSStatus',
    0x000a: 'GPSMeasureMode',
    0x000b: 'GPSDOP',
    0x000c: 'GPSSpeedRef',
    0x000d: 'GPSSpeed',
    0x000e: 'GPSTrackRef',
    0x000f: 'GPSTrack',
    0x0010: 'GPSImgDirectionRef',
    0x0011: 'GPSImgDirection',
    0x0012: 'GPSMapDatum',
    0x0013: 'GPSDestLatitudeRef',
    0x0014: 'GPSDestLatitude',
    0x0015: 'GPSDestLongitudeRef',
    0x0016: 'GPSDestLongitude',
    0x0017: 'GPSDestBearingRef',
    0x0018: 'GPSDestBearing',
    0x0019: 'GPSDestDistanceRef',
    0x001a: 'GPSDestDistance',
    0x001b: 'GPSProcessingMethod',
    0x001c: 'GPSAreaInformation',
    0x001d: 'GPSDateStamp',
    0x001e: 'GPSDifferential',
    0x001f: 'GPSHPositioningError'
  };
  const tagsByName$1 = {};
  for (let i in tagsById$1) {
    tagsByName$1[tagsById$1[i]] = Number(i);
  }

  var gps = /*#__PURE__*/Object.freeze({
    __proto__: null,
    tagsById: tagsById$1,
    tagsByName: tagsByName$1
  });

  const tagsById = {
    // Baseline tags
    0x00fe: 'NewSubfileType',
    0x00ff: 'SubfileType',
    0x0100: 'ImageWidth',
    0x0101: 'ImageLength',
    0x0102: 'BitsPerSample',
    0x0103: 'Compression',
    0x0106: 'PhotometricInterpretation',
    0x0107: 'Threshholding',
    0x0108: 'CellWidth',
    0x0109: 'CellLength',
    0x010a: 'FillOrder',
    0x010e: 'ImageDescription',
    0x010f: 'Make',
    0x0110: 'Model',
    0x0111: 'StripOffsets',
    0x0112: 'Orientation',
    0x0115: 'SamplesPerPixel',
    0x0116: 'RowsPerStrip',
    0x0117: 'StripByteCounts',
    0x0118: 'MinSampleValue',
    0x0119: 'MaxSampleValue',
    0x011a: 'XResolution',
    0x011b: 'YResolution',
    0x011c: 'PlanarConfiguration',
    0x0120: 'FreeOffsets',
    0x0121: 'FreeByteCounts',
    0x0122: 'GrayResponseUnit',
    0x0123: 'GrayResponseCurve',
    0x0128: 'ResolutionUnit',
    0x0131: 'Software',
    0x0132: 'DateTime',
    0x013b: 'Artist',
    0x013c: 'HostComputer',
    0x0140: 'ColorMap',
    0x0152: 'ExtraSamples',
    0x8298: 'Copyright',
    // Extension tags
    0x010d: 'DocumentName',
    0x011d: 'PageName',
    0x011e: 'XPosition',
    0x011f: 'YPosition',
    0x0124: 'T4Options',
    0x0125: 'T6Options',
    0x0129: 'PageNumber',
    0x012d: 'TransferFunction',
    0x013d: 'Predictor',
    0x013e: 'WhitePoint',
    0x013f: 'PrimaryChromaticities',
    0x0141: 'HalftoneHints',
    0x0142: 'TileWidth',
    0x0143: 'TileLength',
    0x0144: 'TileOffsets',
    0x0145: 'TileByteCounts',
    0x0146: 'BadFaxLines',
    0x0147: 'CleanFaxData',
    0x0148: 'ConsecutiveBadFaxLines',
    0x014a: 'SubIFDs',
    0x014c: 'InkSet',
    0x014d: 'InkNames',
    0x014e: 'NumberOfInks',
    0x0150: 'DotRange',
    0x0151: 'TargetPrinter',
    0x0153: 'SampleFormat',
    0x0154: 'SMinSampleValue',
    0x0155: 'SMaxSampleValue',
    0x0156: 'TransferRange',
    0x0157: 'ClipPath',
    0x0158: 'XClipPathUnits',
    0x0159: 'YClipPathUnits',
    0x015a: 'Indexed',
    0x015b: 'JPEGTables',
    0x015f: 'OPIProxy',
    0x0190: 'GlobalParametersIFD',
    0x0191: 'ProfileType',
    0x0192: 'FaxProfile',
    0x0193: 'CodingMethods',
    0x0194: 'VersionYear',
    0x0195: 'ModeNumber',
    0x01b1: 'Decode',
    0x01b2: 'DefaultImageColor',
    0x0200: 'JPEGProc',
    0x0201: 'JPEGInterchangeFormat',
    0x0202: 'JPEGInterchangeFormatLength',
    0x0203: 'JPEGRestartInterval',
    0x0205: 'JPEGLosslessPredictors',
    0x0206: 'JPEGPointTransforms',
    0x0207: 'JPEGQTables',
    0x0208: 'JPEGDCTables',
    0x0209: 'JPEGACTables',
    0x0211: 'YCbCrCoefficients',
    0x0212: 'YCbCrSubSampling',
    0x0213: 'YCbCrPositioning',
    0x0214: 'ReferenceBlackWhite',
    0x022f: 'StripRowCounts',
    0x02bc: 'XMP',
    0x800d: 'ImageID',
    0x87ac: 'ImageLayer',
    // Private tags
    0x80a4: 'WangAnnotatio',
    0x82a5: 'MDFileTag',
    0x82a6: 'MDScalePixel',
    0x82a7: 'MDColorTable',
    0x82a8: 'MDLabName',
    0x82a9: 'MDSampleInfo',
    0x82aa: 'MDPrepDate',
    0x82ab: 'MDPrepTime',
    0x82ac: 'MDFileUnits',
    0x830e: 'ModelPixelScaleTag',
    0x83bb: 'IPTC',
    0x847e: 'INGRPacketDataTag',
    0x847f: 'INGRFlagRegisters',
    0x8480: 'IrasBTransformationMatrix',
    0x8482: 'ModelTiepointTag',
    0x85d8: 'ModelTransformationTag',
    0x8649: 'Photoshop',
    0x8769: 'ExifIFD',
    0x8773: 'ICCProfile',
    0x87af: 'GeoKeyDirectoryTag',
    0x87b0: 'GeoDoubleParamsTag',
    0x87b1: 'GeoAsciiParamsTag',
    0x8825: 'GPSIFD',
    0x885c: 'HylaFAXFaxRecvParams',
    0x885d: 'HylaFAXFaxSubAddress',
    0x885e: 'HylaFAXFaxRecvTime',
    0x935c: 'ImageSourceData',
    0xa005: 'InteroperabilityIFD',
    0xa480: 'GDAL_METADATA',
    0xa481: 'GDAL_NODATA',
    0xc427: 'OceScanjobDescription',
    0xc428: 'OceApplicationSelector',
    0xc429: 'OceIdentificationNumber',
    0xc42a: 'OceImageLogicCharacteristics',
    0xc612: 'DNGVersion',
    0xc613: 'DNGBackwardVersion',
    0xc614: 'UniqueCameraModel',
    0xc615: 'LocalizedCameraModel',
    0xc616: 'CFAPlaneColor',
    0xc617: 'CFALayout',
    0xc618: 'LinearizationTable',
    0xc619: 'BlackLevelRepeatDim',
    0xc61a: 'BlackLevel',
    0xc61b: 'BlackLevelDeltaH',
    0xc61c: 'BlackLevelDeltaV',
    0xc61d: 'WhiteLevel',
    0xc61e: 'DefaultScale',
    0xc61f: 'DefaultCropOrigin',
    0xc620: 'DefaultCropSize',
    0xc621: 'ColorMatrix1',
    0xc622: 'ColorMatrix2',
    0xc623: 'CameraCalibration1',
    0xc624: 'CameraCalibration2',
    0xc625: 'ReductionMatrix1',
    0xc626: 'ReductionMatrix2',
    0xc627: 'AnalogBalance',
    0xc628: 'AsShotNeutral',
    0xc629: 'AsShotWhiteXY',
    0xc62a: 'BaselineExposure',
    0xc62b: 'BaselineNoise',
    0xc62c: 'BaselineSharpness',
    0xc62d: 'BayerGreenSplit',
    0xc62e: 'LinearResponseLimit',
    0xc62f: 'CameraSerialNumber',
    0xc630: 'LensInfo',
    0xc631: 'ChromaBlurRadius',
    0xc632: 'AntiAliasStrength',
    0xc634: 'DNGPrivateData',
    0xc635: 'MakerNoteSafety',
    0xc65a: 'CalibrationIlluminant1',
    0xc65b: 'CalibrationIlluminant2',
    0xc65c: 'BestQualityScale',
    0xc660: 'AliasLayerMetadata'
  };
  const tagsByName = {};
  for (let i in tagsById) {
    tagsByName[tagsById[i]] = Number(i);
  }

  var standard = /*#__PURE__*/Object.freeze({
    __proto__: null,
    tagsById: tagsById,
    tagsByName: tagsByName
  });

  const tags = {
    standard,
    exif,
    gps
  };
  class IFD {
    constructor(kind) {
      if (!kind) {
        throw new Error('missing kind');
      }
      this.data = new Uint8Array();
      this.fields = new Map();
      this.kind = kind;
      this._hasMap = false;
      this._map = {};
    }
    get(tag) {
      if (typeof tag === 'number') {
        return this.fields.get(tag);
      } else if (typeof tag === 'string') {
        return this.fields.get(tags[this.kind].tagsByName[tag]);
      } else {
        throw new Error('expected a number or string');
      }
    }
    get map() {
      if (!this._hasMap) {
        const taglist = tags[this.kind].tagsById;
        for (let key of this.fields.keys()) {
          if (taglist[key]) {
            this._map[taglist[key]] = this.fields.get(key);
          }
        }
        this._hasMap = true;
      }
      return this._map;
    }
  }

  let types = new Map([[1, [1, readByte]], [2, [1, readASCII]], [3, [2, readShort]], [4, [4, readLong]], [5, [8, readRational]], [6, [1, readSByte]], [7, [1, readByte]], [8, [2, readSShort]], [9, [4, readSLong]], [10, [8, readSRational]], [11, [4, readFloat]], [12, [8, readDouble]] // DOUBLE
  ]);
  function getByteLength(type, count) {
    const val = types.get(type);
    if (!val) throw new Error(`type not found: ${type}`);
    return val[0] * count;
  }
  function readData(decoder, type, count) {
    const val = types.get(type);
    if (!val) throw new Error(`type not found: ${type}`);
    return val[1](decoder, count);
  }
  function readByte(decoder, count) {
    if (count === 1) return decoder.readUint8();
    let array = new Uint8Array(count);
    for (let i = 0; i < count; i++) {
      array[i] = decoder.readUint8();
    }
    return array;
  }
  function readASCII(decoder, count) {
    let strings = [];
    let currentString = '';
    for (let i = 0; i < count; i++) {
      let char = String.fromCharCode(decoder.readUint8());
      if (char === '\0') {
        strings.push(currentString);
        currentString = '';
      } else {
        currentString += char;
      }
    }
    if (strings.length === 1) {
      return strings[0];
    } else {
      return strings;
    }
  }
  function readShort(decoder, count) {
    if (count === 1) return decoder.readUint16();
    let array = new Uint16Array(count);
    for (let i = 0; i < count; i++) {
      array[i] = decoder.readUint16();
    }
    return array;
  }
  function readLong(decoder, count) {
    if (count === 1) return decoder.readUint32();
    let array = new Uint32Array(count);
    for (let i = 0; i < count; i++) {
      array[i] = decoder.readUint32();
    }
    return array;
  }
  function readRational(decoder, count) {
    if (count === 1) {
      return decoder.readUint32() / decoder.readUint32();
    }
    let rationals = new Array(count);
    for (let i = 0; i < count; i++) {
      rationals[i] = decoder.readUint32() / decoder.readUint32();
    }
    return rationals;
  }
  function readSByte(decoder, count) {
    if (count === 1) return decoder.readInt8();
    let array = new Int8Array(count);
    for (let i = 0; i < count; i++) {
      array[i] = decoder.readInt8();
    }
    return array;
  }
  function readSShort(decoder, count) {
    if (count === 1) return decoder.readInt16();
    let array = new Int16Array(count);
    for (let i = 0; i < count; i++) {
      array[i] = decoder.readInt16();
    }
    return array;
  }
  function readSLong(decoder, count) {
    if (count === 1) return decoder.readInt32();
    let array = new Int32Array(count);
    for (let i = 0; i < count; i++) {
      array[i] = decoder.readInt32();
    }
    return array;
  }
  function readSRational(decoder, count) {
    if (count === 1) {
      return decoder.readInt32() / decoder.readInt32();
    }
    let rationals = new Array(count);
    for (let i = 0; i < count; i++) {
      rationals[i] = decoder.readInt32() / decoder.readInt32();
    }
    return rationals;
  }
  function readFloat(decoder, count) {
    if (count === 1) return decoder.readFloat32();
    let array = new Float32Array(count);
    for (let i = 0; i < count; i++) {
      array[i] = decoder.readFloat32();
    }
    return array;
  }
  function readDouble(decoder, count) {
    if (count === 1) return decoder.readFloat64();
    let array = new Float64Array(count);
    for (let i = 0; i < count; i++) {
      array[i] = decoder.readFloat64();
    }
    return array;
  }

  const CLEAR_CODE = 256;
  const EOI_CODE = 257;
  // 0-255 from the table + 256 for clear code + 257 for end of information code.
  const TABLE_START = 258;
  const MIN_BIT_LENGTH = 9;
  let stringTable = [];
  function initializeStringTable() {
    if (stringTable.length === 0) {
      for (let i = 0; i < 256; i++) {
        stringTable.push([i]);
      }
      // Fill the table with dummy data.
      // Elements at indices > 257 will be replaced during decompression.
      const dummyString = [];
      for (let i = 256; i < 4096; i++) {
        stringTable.push(dummyString);
      }
    }
  }
  const andTable = [511, 1023, 2047, 4095];
  const bitJumps = [0, 0, 0, 0, 0, 0, 0, 0, 0, 511, 1023, 2047, 4095];
  class LzwDecoder {
    constructor(data) {
      this.nextData = 0;
      this.nextBits = 0;
      this.bytePointer = 0;
      this.tableLength = TABLE_START;
      this.currentBitLength = MIN_BIT_LENGTH;
      this.stripArray = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
      this.outData = new IOBuffer$4(data.byteLength);
      this.initializeTable();
    }
    decode() {
      let code = 0;
      let oldCode = 0;
      while ((code = this.getNextCode()) !== EOI_CODE) {
        if (code === CLEAR_CODE) {
          this.initializeTable();
          code = this.getNextCode();
          if (code === EOI_CODE) {
            break;
          }
          this.writeString(this.stringFromCode(code));
          oldCode = code;
        } else if (this.isInTable(code)) {
          this.writeString(this.stringFromCode(code));
          this.addStringToTable(this.stringFromCode(oldCode).concat(this.stringFromCode(code)[0]));
          oldCode = code;
        } else {
          const outString = this.stringFromCode(oldCode).concat(this.stringFromCode(oldCode)[0]);
          this.writeString(outString);
          this.addStringToTable(outString);
          oldCode = code;
        }
      }
      const outArray = this.outData.toArray();
      return new DataView(outArray.buffer, outArray.byteOffset, outArray.byteLength);
    }
    initializeTable() {
      initializeStringTable();
      this.tableLength = TABLE_START;
      this.currentBitLength = MIN_BIT_LENGTH;
    }
    writeString(string) {
      this.outData.writeBytes(string);
    }
    stringFromCode(code) {
      // At this point, `code` must be defined in the table.
      return stringTable[code];
    }
    isInTable(code) {
      return code < this.tableLength;
    }
    addStringToTable(string) {
      stringTable[this.tableLength++] = string;
      if (stringTable.length > 4096) {
        stringTable = [];
        throw new Error('LZW decoding error. Please open an issue at https://github.com/image-js/tiff/issues/new/choose (include a test image).');
      }
      if (this.tableLength === bitJumps[this.currentBitLength]) {
        this.currentBitLength++;
      }
    }
    getNextCode() {
      this.nextData = this.nextData << 8 | this.stripArray[this.bytePointer++] & 0xff;
      this.nextBits += 8;
      if (this.nextBits < this.currentBitLength) {
        this.nextData = this.nextData << 8 | this.stripArray[this.bytePointer++] & 0xff;
        this.nextBits += 8;
      }
      const code = this.nextData >> this.nextBits - this.currentBitLength & andTable[this.currentBitLength - 9];
      this.nextBits -= this.currentBitLength;
      // This should not really happen but is present in other codes as well.
      // See: https://github.com/sugark/Tiffus/blob/15a60123813d1612f4ae9e4fab964f9f7d71cf63/src/org/eclipse/swt/internal/image/TIFFLZWDecoder.java
      if (this.bytePointer > this.stripArray.length) {
        return 257;
      }
      return code;
    }
  }
  function decompressLzw(stripData) {
    return new LzwDecoder(stripData).decode();
  }

  // eslint-disable-next-line prefer-named-capture-group
  const dateTimeRegex = /^(\d{4}):(\d{2}):(\d{2}) (\d{2}):(\d{2}):(\d{2})$/;
  class TiffIfd extends IFD {
    constructor() {
      super('standard');
    }
    // Custom fields
    get size() {
      return this.width * this.height;
    }
    get width() {
      return this.imageWidth;
    }
    get height() {
      return this.imageLength;
    }
    get components() {
      return this.samplesPerPixel;
    }
    get date() {
      let date = new Date();
      let result = dateTimeRegex.exec(this.dateTime);
      if (result === null) {
        throw new Error(`invalid dateTime: ${this.dateTime}`);
      }
      date.setFullYear(Number(result[1]), Number(result[2]) - 1, Number(result[3]));
      date.setHours(Number(result[4]), Number(result[5]), Number(result[6]));
      return date;
    }
    // IFD fields
    get newSubfileType() {
      return this.get('NewSubfileType');
    }
    get imageWidth() {
      return this.get('ImageWidth');
    }
    get imageLength() {
      return this.get('ImageLength');
    }
    get bitsPerSample() {
      const data = this.get('BitsPerSample');
      if (data && typeof data !== 'number') {
        return data[0];
      }
      return data;
    }
    get alpha() {
      const extraSamples = this.extraSamples;
      if (!extraSamples) return false;
      return extraSamples[0] !== 0;
    }
    get associatedAlpha() {
      const extraSamples = this.extraSamples;
      if (!extraSamples) return false;
      return extraSamples[0] === 1;
    }
    get extraSamples() {
      return alwaysArray(this.get('ExtraSamples'));
    }
    get compression() {
      return this.get('Compression') || 1;
    }
    get type() {
      return this.get('PhotometricInterpretation');
    }
    get fillOrder() {
      return this.get('FillOrder') || 1;
    }
    get documentName() {
      return this.get('DocumentName');
    }
    get imageDescription() {
      return this.get('ImageDescription');
    }
    get stripOffsets() {
      return alwaysArray(this.get('StripOffsets'));
    }
    get orientation() {
      return this.get('Orientation');
    }
    get samplesPerPixel() {
      return this.get('SamplesPerPixel') || 1;
    }
    get rowsPerStrip() {
      return this.get('RowsPerStrip');
    }
    get stripByteCounts() {
      return alwaysArray(this.get('StripByteCounts'));
    }
    get minSampleValue() {
      return this.get('MinSampleValue') || 0;
    }
    get maxSampleValue() {
      return this.get('MaxSampleValue') || Math.pow(2, this.bitsPerSample) - 1;
    }
    get xResolution() {
      return this.get('XResolution');
    }
    get yResolution() {
      return this.get('YResolution');
    }
    get planarConfiguration() {
      return this.get('PlanarConfiguration') || 1;
    }
    get resolutionUnit() {
      return this.get('ResolutionUnit') || 2;
    }
    get dateTime() {
      return this.get('DateTime');
    }
    get predictor() {
      return this.get('Predictor') || 1;
    }
    get sampleFormat() {
      return this.get('SampleFormat') || 1;
    }
    get sMinSampleValue() {
      return this.get('SMinSampleValue') || this.minSampleValue;
    }
    get sMaxSampleValue() {
      return this.get('SMaxSampleValue') || this.maxSampleValue;
    }
    get palette() {
      const totalColors = 2 ** this.bitsPerSample;
      const colorMap = this.get('ColorMap');
      if (!colorMap) return undefined;
      if (colorMap.length !== 3 * totalColors) {
        throw new Error(`ColorMap size must be ${totalColors}`);
      }
      const palette = [];
      for (let i = 0; i < totalColors; i++) {
        palette.push([colorMap[i], colorMap[i + totalColors], colorMap[i + 2 * totalColors]]);
      }
      return palette;
    }
  }
  function alwaysArray(value) {
    if (typeof value === 'number') return [value];
    return value;
  }

  function decompressZlib(stripData) {
    const stripUint8 = new Uint8Array(stripData.buffer, stripData.byteOffset, stripData.byteLength);
    const inflated = inflate_1(stripUint8);
    return new DataView(inflated.buffer, inflated.byteOffset, inflated.byteLength);
  }

  const defaultOptions$c = {
    ignoreImageData: false,
    onlyFirst: false
  };
  class TIFFDecoder extends IOBuffer$4 {
    constructor(data) {
      super(data);
      this._nextIFD = 0;
    }
    get isMultiPage() {
      let c = 0;
      this.decodeHeader();
      while (this._nextIFD) {
        c++;
        this.decodeIFD({
          ignoreImageData: true
        }, true);
        if (c === 2) {
          return true;
        }
      }
      if (c === 1) {
        return false;
      }
      throw unsupported('ifdCount', c);
    }
    get pageCount() {
      let c = 0;
      this.decodeHeader();
      while (this._nextIFD) {
        c++;
        this.decodeIFD({
          ignoreImageData: true
        }, true);
      }
      if (c > 0) {
        return c;
      }
      throw unsupported('ifdCount', c);
    }
    decode(options = {}) {
      options = Object.assign({}, defaultOptions$c, options);
      const result = [];
      this.decodeHeader();
      while (this._nextIFD) {
        result.push(this.decodeIFD(options, true));
        if (options.onlyFirst) {
          return [result[0]];
        }
      }
      return result;
    }
    decodeHeader() {
      // Byte offset
      const value = this.readUint16();
      if (value === 0x4949) {
        this.setLittleEndian();
      } else if (value === 0x4d4d) {
        this.setBigEndian();
      } else {
        throw new Error(`invalid byte order: 0x${value.toString(16)}`);
      }
      // Magic number
      if (this.readUint16() !== 42) {
        throw new Error('not a TIFF file');
      }
      // Offset of the first IFD
      this._nextIFD = this.readUint32();
    }
    decodeIFD(options, tiff) {
      this.seek(this._nextIFD);
      let ifd;
      if (tiff) {
        ifd = new TiffIfd();
      } else {
        if (!options.kind) {
          throw new Error(`kind is missing`);
        }
        ifd = new IFD(options.kind);
      }
      const numEntries = this.readUint16();
      for (let i = 0; i < numEntries; i++) {
        this.decodeIFDEntry(ifd);
      }
      if (!options.ignoreImageData) {
        if (!(ifd instanceof TiffIfd)) {
          throw new Error('must be a tiff ifd');
        }
        this.decodeImageData(ifd);
      }
      this._nextIFD = this.readUint32();
      return ifd;
    }
    decodeIFDEntry(ifd) {
      const offset = this.offset;
      const tag = this.readUint16();
      const type = this.readUint16();
      const numValues = this.readUint32();
      if (type < 1 || type > 12) {
        this.skip(4); // unknown type, skip this value
        return;
      }
      const valueByteLength = getByteLength(type, numValues);
      if (valueByteLength > 4) {
        this.seek(this.readUint32());
      }
      const value = readData(this, type, numValues);
      ifd.fields.set(tag, value);
      // Read sub-IFDs
      if (tag === 0x8769 || tag === 0x8825) {
        let currentOffset = this.offset;
        let kind = 'exif';
        if (tag === 0x8769) {
          kind = 'exif';
        } else if (tag === 0x8825) {
          kind = 'gps';
        }
        this._nextIFD = value;
        ifd[kind] = this.decodeIFD({
          kind,
          ignoreImageData: true
        }, false);
        this.offset = currentOffset;
      }
      // go to the next entry
      this.seek(offset);
      this.skip(12);
    }
    decodeImageData(ifd) {
      const orientation = ifd.orientation;
      if (orientation && orientation !== 1) {
        throw unsupported('orientation', orientation);
      }
      switch (ifd.type) {
        case 0: // WhiteIsZero
        case 1: // BlackIsZero
        case 2: // RGB
        case 3:
          // Palette color
          this.readStripData(ifd);
          break;
        default:
          throw unsupported('image type', ifd.type);
      }
      this.applyPredictor(ifd);
      this.convertAlpha(ifd);
      if (ifd.type === 0) {
        // WhiteIsZero: we invert the values
        const bitDepth = ifd.bitsPerSample;
        const maxValue = Math.pow(2, bitDepth) - 1;
        for (let i = 0; i < ifd.data.length; i++) {
          ifd.data[i] = maxValue - ifd.data[i];
        }
      }
    }
    readStripData(ifd) {
      const width = ifd.width;
      const height = ifd.height;
      const bitDepth = ifd.bitsPerSample;
      const sampleFormat = ifd.sampleFormat;
      const size = width * height * ifd.samplesPerPixel;
      const data = getDataArray(size, bitDepth, sampleFormat);
      const rowsPerStrip = ifd.rowsPerStrip;
      const maxPixels = rowsPerStrip * width * ifd.samplesPerPixel;
      const stripOffsets = ifd.stripOffsets;
      const stripByteCounts = ifd.stripByteCounts || guessStripByteCounts(ifd);
      let remainingPixels = size;
      let pixel = 0;
      for (let i = 0; i < stripOffsets.length; i++) {
        let stripData = new DataView(this.buffer, this.byteOffset + stripOffsets[i], stripByteCounts[i]);
        // Last strip can be smaller
        let length = remainingPixels > maxPixels ? maxPixels : remainingPixels;
        remainingPixels -= length;
        let dataToFill = stripData;
        switch (ifd.compression) {
          case 1:
            {
              // No compression, nothing to do
              break;
            }
          case 5:
            {
              // LZW compression
              dataToFill = decompressLzw(stripData);
              break;
            }
          case 8:
            {
              // Zlib compression
              dataToFill = decompressZlib(stripData);
              break;
            }
          case 2:
            // CCITT Group 3 1-Dimensional Modified Huffman run length encoding
            throw unsupported('Compression', 'CCITT Group 3');
          case 32773:
            // PackBits compression
            throw unsupported('Compression', 'PackBits');
          default:
            throw unsupported('Compression', ifd.compression);
        }
        pixel = this.fillUncompressed(bitDepth, sampleFormat, data, dataToFill, pixel, length);
      }
      ifd.data = data;
    }
    fillUncompressed(bitDepth, sampleFormat, data, stripData, pixel, length) {
      if (bitDepth === 8) {
        return fill8bit(data, stripData, pixel, length);
      } else if (bitDepth === 16) {
        return fill16bit(data, stripData, pixel, length, this.isLittleEndian());
      } else if (bitDepth === 32 && sampleFormat === 3) {
        return fillFloat32(data, stripData, pixel, length, this.isLittleEndian());
      } else {
        throw unsupported('bitDepth', bitDepth);
      }
    }
    applyPredictor(ifd) {
      const bitDepth = ifd.bitsPerSample;
      switch (ifd.predictor) {
        case 1:
          {
            // No prediction scheme, nothing to do
            break;
          }
        case 2:
          {
            if (bitDepth === 8) {
              applyHorizontalDifferencing8Bit(ifd.data, ifd.width, ifd.components);
            } else if (bitDepth === 16) {
              applyHorizontalDifferencing16Bit(ifd.data, ifd.width, ifd.components);
            } else {
              throw new Error(`Horizontal differencing is only supported for images with a bit depth of ${bitDepth}`);
            }
            break;
          }
        default:
          throw new Error(`invalid predictor: ${ifd.predictor}`);
      }
    }
    convertAlpha(ifd) {
      if (ifd.alpha && ifd.associatedAlpha) {
        const {
          data,
          components,
          maxSampleValue
        } = ifd;
        for (let i = 0; i < data.length; i += components) {
          const alphaValue = data[i + components - 1];
          for (let j = 0; j < components - 1; j++) {
            data[i + j] = Math.round(data[i + j] * maxSampleValue / alphaValue);
          }
        }
      }
    }
  }
  function getDataArray(size, bitDepth, sampleFormat) {
    if (bitDepth === 8) {
      return new Uint8Array(size);
    } else if (bitDepth === 16) {
      return new Uint16Array(size);
    } else if (bitDepth === 32 && sampleFormat === 3) {
      return new Float32Array(size);
    } else {
      throw unsupported('bit depth / sample format', `${bitDepth} / ${sampleFormat}`);
    }
  }
  function fill8bit(dataTo, dataFrom, index, length) {
    for (let i = 0; i < length; i++) {
      dataTo[index++] = dataFrom.getUint8(i);
    }
    return index;
  }
  function fill16bit(dataTo, dataFrom, index, length, littleEndian) {
    for (let i = 0; i < length * 2; i += 2) {
      dataTo[index++] = dataFrom.getUint16(i, littleEndian);
    }
    return index;
  }
  function fillFloat32(dataTo, dataFrom, index, length, littleEndian) {
    for (let i = 0; i < length * 4; i += 4) {
      dataTo[index++] = dataFrom.getFloat32(i, littleEndian);
    }
    return index;
  }
  function unsupported(type, value) {
    return new Error(`Unsupported ${type}: ${value}`);
  }

  function decodeTIFF(data, options) {
    const decoder = new TIFFDecoder(data);
    return decoder.decode(options);
  }

  // TODO this code seems buggy if it is not 0,0
  /**
   * We will try to move a set of images in order to get only the best common part of them.
   * In a stack, we compare 2 consecutive images or directly to a parent.
   * Ignoring border may be dangerous ! If there is a shape on the side of the image there will be a
   * continuous shift if you ignore border. By default it is better to leave it to 0,0
   * Now if the background is not black there will also be no way to shift ...
   * It may therefore be much better to make a background correction before trying to match and crop.
   * @memberof Stack
   * @instance
   * @param {object} [options]
   * @param {string} [options.algorithm='matchToPrevious'] - matchToPrevious or matchToFirst
   * @param {number[]} [options.ignoreBorder=[0, 0]]
   * @return {Stack}
   */
  function matchAndCrop(options = {}) {
    let {
      algorithm = 'matchToPrevious',
      ignoreBorder = [0, 0]
    } = options;
    this.checkProcessable('matchAndCrop', {
      bitDepth: [8, 16]
    });
    let matchToPrevious = algorithm === 'matchToPrevious';
    let parent = this[0];
    let results = [];
    results[0] = {
      position: [0, 0],
      image: this[0]
    };
    let relativePosition = [0, 0];

    // we calculate the best relative position to the parent image
    for (let i = 1; i < this.length; i++) {
      let position = parent.getBestMatch(this[i], {
        border: ignoreBorder
      });
      results[i] = {
        position: [position[0] + relativePosition[0], position[1] + relativePosition[1]],
        image: this[i]
      };
      if (matchToPrevious) {
        relativePosition[0] += position[0];
        relativePosition[1] += position[1];
        parent = this[i];
      }
    }
    // now we can calculate the cropping that we need to do

    let leftShift = 0;
    let rightShift = 0;
    let topShift = 0;
    let bottomShift = 0;
    for (let i = 0; i < results.length; i++) {
      let result = results[i];
      if (result.position[0] > leftShift) {
        leftShift = result.position[0];
      }
      if (result.position[0] < rightShift) {
        rightShift = result.position[0];
      }
      if (result.position[1] > topShift) {
        topShift = result.position[1];
      }
      if (result.position[1] < bottomShift) {
        bottomShift = result.position[1];
      }
    }
    rightShift = 0 - rightShift;
    bottomShift = 0 - bottomShift;
    for (let i = 0; i < results.length; i++) {
      let result = results[i];
      result.crop = result.image.crop({
        x: leftShift - result.position[0],
        y: topShift - result.position[1],
        width: parent.width - rightShift - leftShift,
        height: parent.height - bottomShift - topShift
      });
    }

    // finally we crop and create a new array of images
    let newImages = [];
    for (let i = 0; i < results.length; i++) {
      newImages[i] = results[i].crop;
    }
    return new Stack(newImages);
  }

  /**
   * @memberof Stack
   * @instance
   * @return {number[]}
   */
  function min$2() {
    this.checkProcessable('min', {
      bitDepth: [8, 16]
    });
    let min = this[0].min;
    for (let i = 1; i < this.length; i++) {
      for (let j = 0; j < min.length; j++) {
        min[j] = Math.min(min[j], this[i].min[j]);
      }
    }
    return min;
  }

  /**
   * @memberof Stack
   * @instance
   * @return {number[]}
   */
  function max$2() {
    this.checkProcessable('min', {
      bitDepth: [8, 16]
    });
    let max = this[0].max;
    for (let i = 1; i < this.length; i++) {
      for (let j = 0; j < max.length; j++) {
        max[j] = Math.max(max[j], this[i].max[j]);
      }
    }
    return max;
  }

  /**
   * Returns the median of an histogram
   * @param {number[]} histogram
   * @return {number}
   * @private
   */
  function median$2(histogram) {
    let total = histogram.reduce((sum, x) => sum + x);
    if (total === 0) {
      throw new Error('unreachable');
    }
    let position = 0;
    let currentTotal = 0;
    let middle = total / 2;
    let previous;
    while (true) {
      if (histogram[position] > 0) {
        if (previous !== undefined) {
          return (previous + position) / 2;
        }
        currentTotal += histogram[position];
        if (currentTotal > middle) {
          return position;
        } else if (currentTotal === middle) {
          previous = position;
        }
      }
      position++;
    }
  }

  /**
   * Retuns the mean of an histogram
   * @param {number[]} histogram
   * @return {number}
   * @private
   */
  function mean$2(histogram) {
    let total = 0;
    let sum = 0;
    for (let i = 0; i < histogram.length; i++) {
      total += histogram[i];
      sum += histogram[i] * i;
    }
    if (total === 0) {
      return 0;
    }
    return sum / total;
  }

  /**
   * @memberof Stack
   * @instance
   * @return {number[]}
   */
  function median$1() {
    this.checkProcessable('median', {
      bitDepth: [8, 16]
    });
    let histograms = this.getHistograms({
      maxSlots: this[0].maxValue + 1
    });
    let result = new Array(histograms.length);
    for (let c = 0; c < histograms.length; c++) {
      let histogram = histograms[c];
      result[c] = median$2(histogram);
    }
    return result;
  }

  /**
   * @memberof Stack
   * @instance
   * @param {object} [options]
   * @return {number[]}
   */
  function histogram(options) {
    this.checkProcessable('min', {
      bitDepth: [8, 16]
    });
    let histogram = this[0].getHistogram(options);
    for (let i = 1; i < this.length; i++) {
      let secondHistogram = this[i].getHistogram(options);
      for (let j = 0; j < histogram.length; j++) {
        histogram[j] += secondHistogram[j];
      }
    }
    return histogram;
  }

  /**
   * @memberof Stack
   * @instance
   * @param {object} [options]
   * @return {Array<Array<number>>}
   */
  function histograms(options) {
    this.checkProcessable('min', {
      bitDepth: [8, 16]
    });
    let histograms = this[0].getHistograms(options);
    let histogramLength = histograms[0].length;
    for (let i = 1; i < this.length; i++) {
      let secondHistograms = this[i].getHistograms(options);
      for (let c = 0; c < histograms.length; c++) {
        for (let j = 0; j < histogramLength; j++) {
          histograms[c][j] += secondHistograms[c][j];
        }
      }
    }
    return histograms;
  }

  /**
   * @memberof Stack
   * @instance
   * @return {Image}
   */
  function averageImage() {
    this.checkProcessable('averageImage', {
      bitDepth: [8, 16]
    });
    let data = new Uint32Array(this[0].data.length);
    for (let i = 0; i < this.length; i++) {
      let current = this[i];
      for (let j = 0; j < this[0].data.length; j++) {
        data[j] += current.data[j];
      }
    }
    let image = Image.createFrom(this[0]);
    let newData = image.data;
    for (let i = 0; i < this[0].data.length; i++) {
      newData[i] = data[i] / this.length;
    }
    return image;
  }

  /**
   * @memberof Stack
   * @instance
   * @return {Image}
   */
  function maxImage() {
    this.checkProcessable('max', {
      bitDepth: [8, 16]
    });
    let image = Image.createFrom(this[0]);
    image.data.fill(0);
    for (const current of this) {
      for (let j = 0; j < image.data.length; j++) {
        image.data[j] = Math.max(current.data[j], image.data[j]);
      }
    }
    return image;
  }

  /**
   * @memberof Stack
   * @instance
   * @return {Image}
   */
  function minImage() {
    this.checkProcessable('max', {
      bitDepth: [8, 16]
    });
    let image = Image.createFrom(this[0]);
    image.data.fill(image.maxValue);
    for (const current of this) {
      for (let j = 0; j < image.data.length; j++) {
        image.data[j] = Math.min(current.data[j], image.data[j]);
      }
    }
    return image;
  }

  /* eslint-disable import/order */
  function extend$2(Stack) {
    // let inPlace = {inPlace: true};
    Stack.extendMethod('matchAndCrop', matchAndCrop);
    Stack.extendMethod('getMin', min$2);
    Stack.extendMethod('getMax', max$2);
    Stack.extendMethod('getMedian', median$1);
    Stack.extendMethod('getHistogram', histogram);
    Stack.extendMethod('getHistograms', histograms);
    Stack.extendMethod('getAverage', averageImage); // to be removed but will be a breaking change

    Stack.extendMethod('getAverageImage', averageImage);
    Stack.extendMethod('getMaxImage', maxImage);
    Stack.extendMethod('getMinImage', minImage);
  }

  let computedPropertyDescriptor = {
    configurable: true,
    enumerable: false,
    get: undefined
  };

  /**
   * Class representing stack of images
   * @class Stack
   */
  class Stack extends Array {
    constructor(images) {
      if (Array.isArray(images)) {
        super(images.length);
        for (let i = 0; i < images.length; i++) {
          this[i] = images[i];
        }
      } else if (typeof images === 'number') {
        super(images);
      } else {
        super();
      }
      this.computed = null;
    }
    static load(urls) {
      return Promise.all(urls.map(Image.load)).then(images => new Stack(images));
    }
    static extendMethod(name, method, options = {}) {
      let {
        inPlace = false,
        returnThis = true,
        partialArgs = []
      } = options;
      if (inPlace) {
        Stack.prototype[name] = function (...args) {
          // remove computed properties
          this.computed = null;
          let result = method.apply(this, [...partialArgs, ...args]);
          if (returnThis) {
            return this;
          }
          return result;
        };
      } else {
        Stack.prototype[name] = function (...args) {
          return method.apply(this, [...partialArgs, ...args]);
        };
      }
      return Stack;
    }
    static extendProperty(name, method, options = {}) {
      let {
        partialArgs = []
      } = options;
      computedPropertyDescriptor.get = function () {
        if (this.computed === null) {
          this.computed = {};
        } else if (hasOwn(name, this.computed)) {
          return this.computed[name];
        }
        let result = method.apply(this, partialArgs);
        this.computed[name] = result;
        return result;
      };
      Object.defineProperty(Stack.prototype, name, computedPropertyDescriptor);
      return Stack;
    }

    /**
     * Check if a process can be applied on the stack
     * @param {string} processName
     * @param {object} [options]
     * @private
     */
    checkProcessable(processName, options = {}) {
      if (typeof processName !== 'string') {
        throw new TypeError('checkProcessable requires as first parameter the processName (a string)');
      }
      if (this.size === 0) {
        throw new TypeError(`The process: ${processName} can not be applied on an empty stack`);
      }
      this[0].checkProcessable(processName, options);
      for (let i = 1; i < this.length; i++) {
        if ((options.sameSize === undefined || options.sameSize) && this[0].width !== this[i].width) {
          throw new TypeError(`The process: ${processName} can not be applied if width is not identical in all images`);
        }
        if ((options.sameSize === undefined || options.sameSize) && this[0].height !== this[i].height) {
          throw new TypeError(`The process: ${processName} can not be applied if height is not identical in all images`);
        }
        if ((options.sameAlpha === undefined || options.sameAlpha) && this[0].alpha !== this[i].alpha) {
          throw new TypeError(`The process: ${processName} can not be applied if alpha is not identical in all images`);
        }
        if ((options.sameBitDepth === undefined || options.sameBitDepth) && this[0].bitDepth !== this[i].bitDepth) {
          throw new TypeError(`The process: ${processName} can not be applied if bitDepth is not identical in all images`);
        }
        if ((options.sameColorModel === undefined || options.sameColorModel) && this[0].colorModel !== this[i].colorModel) {
          throw new TypeError(`The process: ${processName} can not be applied if colorModel is not identical in all images`);
        }
        if ((options.sameNumberChannels === undefined || options.sameNumberChannels) && this[0].channels !== this[i].channels) {
          throw new TypeError(`The process: ${processName} can not be applied if channels is not identical in all images`);
        }
      }
    }
  }
  if (!Array[Symbol.species]) {
    // support old engines
    Stack.prototype.map = function (cb, thisArg) {
      if (typeof cb !== 'function') {
        throw new TypeError(`${cb} is not a function`);
      }
      let newStack = new Stack(this.length);
      for (let i = 0; i < this.length; i++) {
        newStack[i] = cb.call(thisArg, this[i], i, this);
      }
      return newStack;
    };
  }
  extend$2(Stack);

  const isDataURL = /^data:[a-z]+\/(?:[a-z]+);base64,/;

  /**
   * Load an image
   * @memberof Image
   * @static
   * @param {string|ArrayBuffer|Buffer|Uint8Array} image - URL of the image (browser, can be a dataURL) or path (Node.js)
   * or buffer containing the binary data
   * @param {object} [options] - In the browser, the options object is passed to the underlying `fetch` call, along with
   * the data URL. For binary data, the option specify decoding options.
   * @param {boolean} [options.ignorePalette] - When set to true and loading a tiff from binary data, if the tiff is of
   * type 3 (palette), load as single channel greyscale rather than as a pseudo-colored RGB.
   * @return {Promise<Image>}
   * @example
   * const image = await Image.load('https://example.com/image.png');
   */
  function load(image, options) {
    if (typeof image === 'string') {
      return loadURL(image, options);
    } else if (image instanceof ArrayBuffer) {
      return Promise.resolve(loadBinary(new Uint8Array(image), undefined, options && options.ignorePalette));
    } else if (image.buffer) {
      return Promise.resolve(loadBinary(image, undefined, options && options.ignorePalette));
    } else {
      throw new Error('argument to "load" must be a string or buffer.');
    }
  }
  function loadBinary(image, base64Url, ignorePalette) {
    const type = imageType$1(image);
    if (type) {
      switch (type.mime) {
        case 'image/png':
          return loadPNG(image);
        case 'image/jpeg':
          return loadJPEG(image);
        case 'image/tiff':
          return loadTIFF(image, ignorePalette);
        default:
          return loadGeneric(getBase64(type.mime));
      }
    }
    return loadGeneric(getBase64('application/octet-stream'));
    function getBase64(type) {
      if (base64Url) {
        return base64Url;
      } else {
        return toBase64URL(image, type);
      }
    }
  }
  function loadURL(url, options) {
    const dataURL = url.slice(0, 64).match(isDataURL);
    let binaryDataP;
    if (dataURL !== null) {
      binaryDataP = Promise.resolve(decode$3(url.slice(dataURL[0].length)));
    } else {
      binaryDataP = fetchBinary(url, options);
    }
    return binaryDataP.then(binaryData => {
      const uint8 = new Uint8Array(binaryData);
      return loadBinary(uint8, dataURL ? url : undefined, options && options.ignorePalette);
    });
  }
  function loadPNG(data) {
    const png = decodePng(data);
    let channels = png.channels;
    let components;
    let alpha = 0;
    if (channels === 2 || channels === 4) {
      components = channels - 1;
      alpha = 1;
    } else {
      components = channels;
    }
    if (png.palette) {
      return loadPNGFromPalette(png);
    }
    return new Image(png.width, png.height, png.data, {
      components,
      alpha,
      bitDepth: png.depth,
      meta: {
        text: png.text
      }
    });
  }
  function loadPNGFromPalette(png) {
    const pixels = png.width * png.height;
    const channels = png.palette[0].length;
    const data = new Uint8Array(pixels * channels);
    const pixelsPerByte = 8 / png.depth;
    const factor = png.depth < 8 ? pixelsPerByte : 1;
    const mask = parseInt('1'.repeat(png.depth), 2);
    const hasAlpha = channels === 4;
    let dataIndex = 0;
    for (let i = 0; i < pixels; i++) {
      const index = Math.floor(i / factor);
      let value = png.data[index];
      if (png.depth < 8) {
        value = value >>> png.depth * (pixelsPerByte - 1 - i % pixelsPerByte) & mask;
      }
      const paletteValue = png.palette[value];
      data[dataIndex++] = paletteValue[0];
      data[dataIndex++] = paletteValue[1];
      data[dataIndex++] = paletteValue[2];
      if (hasAlpha) {
        data[dataIndex++] = paletteValue[3];
      }
    }
    return new Image(png.width, png.height, data, {
      components: 3,
      alpha: hasAlpha,
      bitDepth: 8
    });
  }
  function loadJPEG(data) {
    const decodedExif = decode(data);
    let meta;
    if (decodedExif.exif) {
      meta = getMetadata(decodedExif.exif);
    }
    const jpeg = jpegJs.decode(data, {
      useTArray: true,
      maxMemoryUsageInMB: 1024
    });
    let image = new Image(jpeg.width, jpeg.height, jpeg.data, {
      meta
    });
    if (meta && meta.tiff.tags.Orientation) {
      const orientation = meta.tiff.tags.Orientation;
      if (orientation > 2) {
        image = image.rotate({
          3: 180,
          4: 180,
          5: 90,
          6: 90,
          7: 270,
          8: 270
        }[orientation]);
      }
      if ([2, 4, 5, 7].includes(orientation)) {
        image = image.flipX();
      }
    }
    return image;
  }
  function loadTIFF(data, ignorePalette) {
    let result = decodeTIFF(data);
    if (result.length === 1) {
      return getImageFromIFD(result[0], ignorePalette);
    } else {
      return new Stack(result.map(function (image) {
        return getImageFromIFD(image, ignorePalette);
      }));
    }
  }
  function getMetadata(image) {
    const metadata = {
      tiff: {
        fields: image.fields,
        tags: image.map
      }
    };
    if (image.exif) {
      metadata.exif = image.exif;
    }
    if (image.gps) {
      metadata.gps = image.gps;
    }
    return metadata;
  }
  function getImageFromIFD(image, ignorePalette) {
    if (!ignorePalette && image.type === 3) {
      // Palette
      const data = new Uint16Array(3 * image.width * image.height);
      const palette = image.palette;
      let ptr = 0;
      for (let i = 0; i < image.data.length; i++) {
        const index = image.data[i];
        const color = palette[index];
        data[ptr++] = color[0];
        data[ptr++] = color[1];
        data[ptr++] = color[2];
      }
      return new Image(image.width, image.height, data, {
        components: 3,
        alpha: image.alpha,
        colorModel: RGB$1,
        bitDepth: 16,
        meta: getMetadata(image)
      });
    } else {
      return new Image(image.width, image.height, image.data, {
        components: image.type === 2 ? 3 : 1,
        alpha: image.alpha,
        colorModel: image.type === 2 ? RGB$1 : GREY$1,
        bitDepth: image.bitsPerSample.length ? image.bitsPerSample[0] : image.bitsPerSample,
        meta: getMetadata(image)
      });
    }
  }
  function loadGeneric(url, options) {
    options = options || {};
    return new Promise(function (resolve, reject) {
      let image = new DOMImage();
      image.onload = function () {
        let w = image.width;
        let h = image.height;
        let canvas = createCanvas(w, h);
        let ctx = canvas.getContext('2d');
        ctx.drawImage(image, 0, 0, w, h);
        let data = ctx.getImageData(0, 0, w, h).data;
        resolve(new Image(w, h, data, options));
      };
      image.onerror = function () {
        reject(new Error(`Could not load ${url}`));
      };
      image.src = url;
    });
  }

  const valueMethods = {
    /**
     * Get the value of specific pixel channel
     * @memberof Image
     * @instance
     * @param {number} x - x coordinate (0 = left)
     * @param {number} y - y coordinate (0 = top)
     * @param {number} channel
     * @return {number} - the value of this pixel channel
     */
    getValueXY(x, y, channel) {
      return this.data[(y * this.width + x) * this.channels + channel];
    },
    /**
     * Set the value of specific pixel channel
     * @memberof Image
     * @instance
     * @param {number} x - x coordinate (0 = left)
     * @param {number} y - y coordinate (0 = top)
     * @param {number} channel
     * @param {number} value - the new value of this pixel channel
     * @return {this}
     */
    setValueXY(x, y, channel, value) {
      this.data[(y * this.width + x) * this.channels + channel] = value;
      this.computed = null;
      return this;
    },
    /**
     * Get the value of specific pixel channel
     * @memberof Image
     * @instance
     * @param {number} index - 1D index of the pixel
     * @param {number} channel
     * @return {number} - the value of this pixel channel
     */
    getValue(index, channel) {
      return this.data[index * this.channels + channel];
    },
    /**
     * Set the value of specific pixel channel
     * @memberof Image
     * @instance
     * @param {number} index - 1D index of the pixel
     * @param {number} channel
     * @param {number} value - the new value of this pixel channel
     * @return {this}
     */
    setValue(index, channel, value) {
      this.data[index * this.channels + channel] = value;
      this.computed = null;
      return this;
    },
    /**
     * Get the value of an entire pixel
     * @memberof Image
     * @instance
     * @param {number} x - x coordinate (0 = left)
     * @param {number} y - y coordinate (0 = top)
     * @return {number[]} the value of this pixel
     */
    getPixelXY(x, y) {
      return this.getPixel(y * this.width + x);
    },
    /**
     * Set the value of an entire pixel
     * @memberof Image
     * @instance
     * @param {number} x - x coordinate (0 = left)
     * @param {number} y - y coordinate (0 = top)
     * @param {number[]} value - the new value of this pixel
     * @return {this}
     */
    setPixelXY(x, y, value) {
      return this.setPixel(y * this.width + x, value);
    },
    /**
     * Get the value of an entire pixel
     * @memberof Image
     * @instance
     * @param {number} index - 1D index of the pixel
     * @return {number[]} the value of this pixel
     */
    getPixel(index) {
      const value = new Array(this.channels);
      const target = index * this.channels;
      for (let i = 0; i < this.channels; i++) {
        value[i] = this.data[target + i];
      }
      return value;
    },
    /**
     * Set the value of an entire pixel
     * @memberof Image
     * @instance
     * @param {number} index - 1D index of the pixel
     * @param {number[]} value - the new value of this pixel
     * @return {this}
     */
    setPixel(index, value) {
      const target = index * this.channels;
      for (let i = 0; i < value.length; i++) {
        this.data[target + i] = value[i];
      }
      this.computed = null;
      return this;
    }
  };
  function setValueMethods(Image) {
    for (const i in valueMethods) {
      Image.prototype[i] = valueMethods[i];
    }
  }

  function getImageParameters(image) {
    return {
      width: image.width,
      height: image.height,
      components: image.components,
      alpha: image.alpha,
      colorModel: image.colorModel,
      bitDepth: image.bitDepth
    };
  }

  /**
   * Use this function to support getting the output image of an algorithm from user-supplied
   * options.
   * @private
   * @param {Image} thisImage - Original image on which the algorithm will be applied
   * @param {object} options - Options object received by the algorithm
   * @param {Image} [options.out] - If set, must be an image compatible with the algorithm
   * @param {object} newParameters - Parameters that will be combined with the ones from `thisImage`.
   * @param {object} internalOptions - Some additional options on the way to create the output image
   * @return {Image}
   */
  function getOutputImage(thisImage, options, newParameters, internalOptions = {}) {
    const {
      out
    } = options;
    if (out === undefined) {
      if (internalOptions.copy) {
        return thisImage.clone();
      } else {
        return Image.createFrom(thisImage, newParameters);
      }
    } else {
      if (!Image.isImage(out)) {
        throw new TypeError('out must be an Image object');
      }
      const requirements = Object.assign(getImageParameters(thisImage), newParameters);
      for (const property in requirements) {
        if (out[property] !== requirements[property]) {
          throw new RangeError(`cannot use out. Its ${property} must be "${requirements[property]}" (found "${out[property]}")`);
        }
      }
      return out;
    }
  }

  /**
   * Same as getOutputImage but allows for an `inPlace` option.
   * @private
   * @param {Image} thisImage
   * @param {object} options
   * @param {boolean} [options.inPlace=false] - If true, thisImage is returned
   * @param {Image} [options.out]
   * @param {object} internalOptions - Additional internal options on how to create the output image
   * @param {boolean} [interalOptions.copy] - If true will copy the original image instead of creating a new empty image
   * @return {Image}
   */
  function getOutputImageOrInPlace(thisImage, options, internalOptions) {
    if (options.inPlace !== undefined && typeof options.inPlace !== 'boolean') {
      throw new TypeError('inPlace option must be a boolean');
    }
    if (options.inPlace) {
      if (options.out !== undefined) {
        throw new TypeError('out option must not be set if inPlace option is true');
      }
      return thisImage;
    }
    return getOutputImage(thisImage, options, null, internalOptions);
  }

  /**
   * Calculate the absolute values of an image.
   * Only works on 32-bit images.
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {boolean} [options.inPlace=false]
   * @param {Image} [options.out]
   * @return {Image}
   */
  function abs(options = {}) {
    this.checkProcessable('abs', {
      bitDepth: [32]
    });
    const out = getOutputImageOrInPlace(this, options);
    absolute(this, out);
    return out;
  }
  function absolute(image, out) {
    for (let i = 0; i < image.data.length; i++) {
      out.data[i] = Math.abs(image.data[i]);
    }
  }

  /**
   * Copies the alpha channel from an image to another. no-op if one of the images has no alpha
   * @private
   * @param {Image} from
   * @param {Image} to
   */
  function copyAlphaChannel(from, to) {
    if (from.alpha === 1 && to.alpha === 1) {
      for (let i = 0; i < from.size; i++) {
        to.data[i * to.channels + to.components] = from.data[i * from.channels + from.components];
      }
    }
  }

  /**
   * Invert the colors of an image
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {boolean} [options.inPlace=false]
   * @param {Image} [options.out]
   * @return {Image}
   */
  function invert(options = {}) {
    this.checkProcessable('invert', {
      bitDepth: [1, 8, 16]
    });
    const out = getOutputImageOrInPlace(this, options);
    if (this.bitDepth === 1) {
      invertBinary(this, out);
    } else {
      invertColor(this, out);
      if (this !== out) {
        copyAlphaChannel(this, out);
      }
    }
    return out;
  }
  function invertBinary(image, out) {
    for (let i = 0; i < image.data.length; i++) {
      out.data[i] = ~image.data[i];
    }
  }
  function invertColor(image, out) {
    for (let pixel = 0; pixel < image.data.length; pixel += image.channels) {
      for (let c = 0; c < image.components; c++) {
        out.data[pixel + c] = image.maxValue - image.data[pixel + c];
      }
    }
  }

  /**
   * Flip an image horizontally.
   * @memberof Image
   * @instance
   * @return {this}
   */
  function flipX() {
    this.checkProcessable('flipX', {
      bitDepth: [8, 16]
    });
    for (let i = 0; i < this.height; i++) {
      let offsetY = i * this.width * this.channels;
      for (let j = 0; j < Math.floor(this.width / 2); j++) {
        let posCurrent = j * this.channels + offsetY;
        let posOpposite = (this.width - j - 1) * this.channels + offsetY;
        for (let k = 0; k < this.channels; k++) {
          let tmp = this.data[posCurrent + k];
          this.data[posCurrent + k] = this.data[posOpposite + k];
          this.data[posOpposite + k] = tmp;
        }
      }
    }
    return this;
  }

  /**
   * Flip an image vertically. The image
   * @memberof Image
   * @instance
   * @return {this}
   */
  function flipY() {
    this.checkProcessable('flipY', {
      bitDepth: [8, 16]
    });
    for (let i = 0; i < Math.floor(this.height / 2); i++) {
      for (let j = 0; j < this.width; j++) {
        let posCurrent = j * this.channels + i * this.width * this.channels;
        let posOpposite = j * this.channels + (this.height - 1 - i) * this.channels * this.width;
        for (let k = 0; k < this.channels; k++) {
          let tmp = this.data[posCurrent + k];
          this.data[posCurrent + k] = this.data[posOpposite + k];
          this.data[posOpposite + k] = tmp;
        }
      }
    }
    return this;
  }

  /**
   * Blurs the image by averaging the neighboring pixels.
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {number} [options.radius=1] - Number of pixels around the current pixel to average
   * @return {Image}
   */
  function blurFilter(options = {}) {
    const {
      radius = 1
    } = options;
    if (radius < 1) {
      throw new Error('radius must be greater than 1');
    }
    const n = 2 * radius + 1;
    const kernel = new Array(n);
    for (let i = 0; i < n; i++) {
      kernel[i] = new Array(n);
      for (let j = 0; j < n; j++) {
        kernel[i][j] = 1 / (n * n);
      }
    }
    return this.convolution(kernel);
  }

  var medianQuickselect_min = {exports: {}};

  (function (module) {
    (function () {
      function a(d) {
        for (var e = 0, f = d.length - 1, g = void 0, h = void 0, i = void 0, j = c(e, f); true;) {
          if (f <= e) return d[j];
          if (f == e + 1) return d[e] > d[f] && b(d, e, f), d[j];
          for (g = c(e, f), d[g] > d[f] && b(d, g, f), d[e] > d[f] && b(d, e, f), d[g] > d[e] && b(d, g, e), b(d, g, e + 1), h = e + 1, i = f; true;) {
            do h++; while (d[e] > d[h]);
            do i--; while (d[i] > d[e]);
            if (i < h) break;
            b(d, h, i);
          }
          b(d, e, i), i <= j && (e = h), i >= j && (f = i - 1);
        }
      }
      var b = function b(d, e, f) {
          var _ref;
          return _ref = [d[f], d[e]], d[e] = _ref[0], d[f] = _ref[1], _ref;
        },
        c = function c(d, e) {
          return ~~((d + e) / 2);
        };
      module.exports ? module.exports = a : window.median = a;
    })();
  })(medianQuickselect_min);
  var medianQuickselect_minExports = medianQuickselect_min.exports;
  var quickSelectMedian = /*@__PURE__*/getDefaultExportFromCjs(medianQuickselect_minExports);

  /**
   * Specify which channels should be processed
   * * undefined : we take all the channels but alpha
   * * number : this specific channel
   * * string : converted to a channel based on rgb, cmyk, hsl or hsv (one letter code)
   * * [number] : array of channels as numbers
   * * [string] : array of channels as one letter string
   * @typedef {undefined|number|string|Array<number>|Array<string>} SelectedChannels
   */

  function validateArrayOfChannels(image, options = {}) {
    let {
      channels,
      allowAlpha,
      // are we allowing the selection of an alpha channel ?
      defaultAlpha // if no channels are selected should we take the alpha channel ?
    } = options;
    if (typeof allowAlpha !== 'boolean') {
      allowAlpha = true;
    }
    if (typeof channels === 'undefined') {
      return allChannels(image, defaultAlpha);
    } else {
      return validateChannels(image, channels, allowAlpha);
    }
  }
  function allChannels(image, defaultAlpha) {
    let length = defaultAlpha ? image.channels : image.components;
    let array = new Array(length);
    for (let i = 0; i < length; i++) {
      array[i] = i;
    }
    return array;
  }
  function validateChannels(image, channels, allowAlpha) {
    if (!Array.isArray(channels)) {
      channels = [channels];
    }
    for (let c = 0; c < channels.length; c++) {
      channels[c] = validateChannel(image, channels[c], allowAlpha);
    }
    return channels;
  }
  function validateChannel(image, channel, allowAlpha = true) {
    if (channel === undefined) {
      throw new RangeError(`validateChannel : the channel has to be >=0 and <${image.channels}`);
    }
    if (typeof channel === 'string') {
      switch (image.colorModel) {
        case GREY$1:
          break;
        case RGB$1:
          if ('rgb'.includes(channel)) {
            switch (channel) {
              case 'r':
                channel = 0;
                break;
              case 'g':
                channel = 1;
                break;
              case 'b':
                channel = 2;
                break;
              // no default
            }
          }
          break;
        case HSL:
          if ('hsl'.includes(channel)) {
            switch (channel) {
              case 'h':
                channel = 0;
                break;
              case 's':
                channel = 1;
                break;
              case 'l':
                channel = 2;
                break;
              // no default
            }
          }
          break;
        case HSV:
          if ('hsv'.includes(channel)) {
            switch (channel) {
              case 'h':
                channel = 0;
                break;
              case 's':
                channel = 1;
                break;
              case 'v':
                channel = 2;
                break;
              // no default
            }
          }
          break;
        case CMYK$1:
          if ('cmyk'.includes(channel)) {
            switch (channel) {
              case 'c':
                channel = 0;
                break;
              case 'm':
                channel = 1;
                break;
              case 'y':
                channel = 2;
                break;
              case 'k':
                channel = 3;
                break;
              // no default
            }
          }
          break;
        default:
          throw new Error(`Unexpected color model: ${image.colorModel}`);
      }
      if (channel === 'a') {
        if (!image.alpha) {
          throw new Error('validateChannel : the image does not contain alpha channel');
        }
        channel = image.components;
      }
      if (typeof channel === 'string') {
        throw new Error(`validateChannel : undefined channel: ${channel}`);
      }
    }
    if (channel >= image.channels) {
      throw new RangeError(`validateChannel : the channel has to be >=0 and <${image.channels}`);
    }
    if (!allowAlpha && channel >= image.components) {
      throw new RangeError('validateChannel : alpha channel may not be selected');
    }
    return channel;
  }

  /**
   * Each pixel of the image becomes the median of the neighbor pixels.
   * @memberof Image
   * @instance
   * @param {object} options
   * @param {SelectedChannels} [options.channels] - Specify which channels should be processed.
   * @param {number} [options.radius=1] - Distance of the square to take the mean of.
   * @param {string} [options.border='copy'] - Algorithm that will be applied after to deal with borders.
   * @return {Image}
   */
  function medianFilter(options = {}) {
    let {
      radius = 1,
      border = 'copy',
      channels
    } = options;
    this.checkProcessable('medianFilter', {
      bitDepth: [8, 16]
    });
    if (radius < 1) {
      throw new Error('radius must be greater than 0');
    }
    channels = validateArrayOfChannels(this, channels);
    let kWidth = radius;
    let kHeight = radius;
    let newImage = Image.createFrom(this);
    let size = (kWidth * 2 + 1) * (kHeight * 2 + 1);
    let kernel = new Array(size);
    for (let channel = 0; channel < channels.length; channel++) {
      let c = channels[channel];
      for (let y = kHeight; y < this.height - kHeight; y++) {
        for (let x = kWidth; x < this.width - kWidth; x++) {
          let n = 0;
          for (let j = -kHeight; j <= kHeight; j++) {
            for (let i = -kWidth; i <= kWidth; i++) {
              let index = ((y + j) * this.width + x + i) * this.channels + c;
              kernel[n++] = this.data[index];
            }
          }
          let index = (y * this.width + x) * this.channels + c;
          newImage.data[index] = quickSelectMedian(kernel);
        }
      }
    }
    if (this.alpha && !channels.includes(this.channels)) {
      for (let i = this.components; i < this.data.length; i = i + this.channels) {
        newImage.data[i] = this.data[i];
      }
    }
    newImage.setBorder({
      size: [kWidth, kHeight],
      algorithm: border
    });
    return newImage;
  }

  /**
   * Apply a gaussian filter to the image.
   * @memberof Image
   * @instance
   * @param {object} options
   * @param {number} [options.radius=1] - Number of pixels around the current pixel.
   * @param {number} [options.sigma] - Sigma parameter for the gaussian.
   * @param {number[]|string[]} [options.channels] - To which channel to apply the filter.
   * @param {string} [options.border='copy']
   * @return {Image}
   */
  function gaussianFilter(options = {}) {
    let {
      radius = 1,
      sigma,
      channels,
      border = 'copy'
    } = options;
    this.checkProcessable('gaussian', {
      bitDepth: [8, 16]
    });
    const kernel = getKernel(radius, sigma);
    return this.convolution([kernel, kernel], {
      border,
      channels,
      algorithm: 'separable'
    });
  }
  function getKernel(radius, sigma) {
    const n = radius * 2 + 1;
    const kernel = new Array(n);
    const sigmaX = sigma ? sigma : ((n - 1) * 0.5 - 1) * 0.3 + 0.8;
    const scale2X = -0.5 / (sigmaX * sigmaX);
    let sum = 0;
    for (let i = 0; i < n; i++) {
      const x = i - radius;
      const t = Math.exp(scale2X * x * x);
      kernel[i] = t;
      sum += t;
    }
    for (let i = 0; i < n; i++) {
      kernel[i] /= sum;
    }
    return kernel;
  }

  const DISCRETE_LAPLACE_4 = [[0, 1, 0], [1, -4, 1], [0, 1, 0]];
  const DISCRETE_LAPLACE_8 = [[1, 1, 1], [1, -8, 1], [1, 1, 1]];
  const SOBEL_X = [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]];
  const SOBEL_Y = [[-1, -2, -1], [0, 0, 0], [1, 2, 1]];
  const SCHARR_X = [[3, 0, -3], [10, 0, -10], [3, 0, -3]];
  const SCHARR_Y = [[3, 10, 3], [0, 0, 0], [-3, -10, -3]];
  const SECOND_DERIVATIVE = [[-1, -2, 0, 2, 1], [-2, -4, 0, 4, 2], [0, 0, 0, 0, 0], [1, 2, 0, -2, -1], [2, 4, 0, -4, -2]];
  const SECOND_DERIVATIVE_INV = [[1, 2, 0, -2, -1], [2, 4, 0, -4, -2], [0, 0, 0, 0, 0], [-2, -4, 0, 4, 2], [-1, -2, 0, 2, 1]];

  var src$2 = {};

  var fftlib = {};

  /**
   * Fast Fourier Transform module
   * 1D-FFT/IFFT, 2D-FFT/IFFT (radix-2)
   */
  (function (exports) {
    (function () {
      var FFT;
      {
        FFT = exports; // for CommonJS
      }
      var version = {
        release: '0.3.0',
        date: '2013-03'
      };
      FFT.toString = function () {
        return "version " + version.release + ", released " + version.date;
      };

      // core operations
      var _n = 0,
        // order
        _bitrev = null,
        // bit reversal table
        _cstb = null; // sin/cos table

      var core = {
        init: function (n) {
          if (n !== 0 && (n & n - 1) === 0) {
            _n = n;
            core._initArray();
            core._makeBitReversalTable();
            core._makeCosSinTable();
          } else {
            throw new Error("init: radix-2 required");
          }
        },
        // 1D-FFT
        fft1d: function (re, im) {
          core.fft(re, im, 1);
        },
        // 1D-IFFT
        ifft1d: function (re, im) {
          var n = 1 / _n;
          core.fft(re, im, -1);
          for (var i = 0; i < _n; i++) {
            re[i] *= n;
            im[i] *= n;
          }
        },
        // 1D-IFFT
        bt1d: function (re, im) {
          core.fft(re, im, -1);
        },
        // 2D-FFT Not very useful if the number of rows have to be equal to cols
        fft2d: function (re, im) {
          var tre = [],
            tim = [],
            i = 0;
          // x-axis
          for (var y = 0; y < _n; y++) {
            i = y * _n;
            for (var x1 = 0; x1 < _n; x1++) {
              tre[x1] = re[x1 + i];
              tim[x1] = im[x1 + i];
            }
            core.fft1d(tre, tim);
            for (var x2 = 0; x2 < _n; x2++) {
              re[x2 + i] = tre[x2];
              im[x2 + i] = tim[x2];
            }
          }
          // y-axis
          for (var x = 0; x < _n; x++) {
            for (var y1 = 0; y1 < _n; y1++) {
              i = x + y1 * _n;
              tre[y1] = re[i];
              tim[y1] = im[i];
            }
            core.fft1d(tre, tim);
            for (var y2 = 0; y2 < _n; y2++) {
              i = x + y2 * _n;
              re[i] = tre[y2];
              im[i] = tim[y2];
            }
          }
        },
        // 2D-IFFT
        ifft2d: function (re, im) {
          var tre = [],
            tim = [],
            i = 0;
          // x-axis
          for (var y = 0; y < _n; y++) {
            i = y * _n;
            for (var x1 = 0; x1 < _n; x1++) {
              tre[x1] = re[x1 + i];
              tim[x1] = im[x1 + i];
            }
            core.ifft1d(tre, tim);
            for (var x2 = 0; x2 < _n; x2++) {
              re[x2 + i] = tre[x2];
              im[x2 + i] = tim[x2];
            }
          }
          // y-axis
          for (var x = 0; x < _n; x++) {
            for (var y1 = 0; y1 < _n; y1++) {
              i = x + y1 * _n;
              tre[y1] = re[i];
              tim[y1] = im[i];
            }
            core.ifft1d(tre, tim);
            for (var y2 = 0; y2 < _n; y2++) {
              i = x + y2 * _n;
              re[i] = tre[y2];
              im[i] = tim[y2];
            }
          }
        },
        // core operation of FFT
        fft: function (re, im, inv) {
          var d,
            h,
            ik,
            m,
            tmp,
            wr,
            wi,
            xr,
            xi,
            n4 = _n >> 2;
          // bit reversal
          for (var l = 0; l < _n; l++) {
            m = _bitrev[l];
            if (l < m) {
              tmp = re[l];
              re[l] = re[m];
              re[m] = tmp;
              tmp = im[l];
              im[l] = im[m];
              im[m] = tmp;
            }
          }
          // butterfly operation
          for (var k = 1; k < _n; k <<= 1) {
            h = 0;
            d = _n / (k << 1);
            for (var j = 0; j < k; j++) {
              wr = _cstb[h + n4];
              wi = inv * _cstb[h];
              for (var i = j; i < _n; i += k << 1) {
                ik = i + k;
                xr = wr * re[ik] + wi * im[ik];
                xi = wr * im[ik] - wi * re[ik];
                re[ik] = re[i] - xr;
                re[i] += xr;
                im[ik] = im[i] - xi;
                im[i] += xi;
              }
              h += d;
            }
          }
        },
        // initialize the array (supports TypedArray)
        _initArray: function () {
          if (typeof Uint32Array !== 'undefined') {
            _bitrev = new Uint32Array(_n);
          } else {
            _bitrev = [];
          }
          if (typeof Float64Array !== 'undefined') {
            _cstb = new Float64Array(_n * 1.25);
          } else {
            _cstb = [];
          }
        },
        // zero padding
        _paddingZero: function () {
          // TODO
        },
        // makes bit reversal table
        _makeBitReversalTable: function () {
          var i = 0,
            j = 0,
            k = 0;
          _bitrev[0] = 0;
          while (++i < _n) {
            k = _n >> 1;
            while (k <= j) {
              j -= k;
              k >>= 1;
            }
            j += k;
            _bitrev[i] = j;
          }
        },
        // makes trigonometiric function table
        _makeCosSinTable: function () {
          var n2 = _n >> 1,
            n4 = _n >> 2,
            n8 = _n >> 3,
            n2p4 = n2 + n4,
            t = Math.sin(Math.PI / _n),
            dc = 2 * t * t,
            ds = Math.sqrt(dc * (2 - dc)),
            c = _cstb[n4] = 1,
            s = _cstb[0] = 0;
          t = 2 * dc;
          for (var i = 1; i < n8; i++) {
            c -= dc;
            dc += t * c;
            s += ds;
            ds -= t * s;
            _cstb[i] = s;
            _cstb[n4 - i] = c;
          }
          if (n8 !== 0) {
            _cstb[n8] = Math.sqrt(0.5);
          }
          for (var j = 0; j < n4; j++) {
            _cstb[n2 - j] = _cstb[j];
          }
          for (var k = 0; k < n2p4; k++) {
            _cstb[k + n2] = -_cstb[k];
          }
        }
      };
      // aliases (public APIs)
      var apis = ['init', 'fft1d', 'ifft1d', 'fft2d', 'ifft2d'];
      for (var i = 0; i < apis.length; i++) {
        FFT[apis[i]] = core[apis[i]];
      }
      FFT.bt = core.bt1d;
      FFT.fft = core.fft1d;
      FFT.ifft = core.ifft1d;
      return FFT;
    }).call(fftlib);
  })(fftlib);

  var FFT = fftlib;
  var FFTUtils$1 = {
    DEBUG: false,
    /**
     * Calculates the inverse of a 2D Fourier transform
     *
     * @param ft
     * @param ftRows
     * @param ftCols
     * @return
     */
    ifft2DArray: function (ft, ftRows, ftCols) {
      var tempTransform = new Array(ftRows * ftCols);
      var nRows = ftRows / 2;
      var nCols = (ftCols - 1) * 2;
      // reverse transform columns
      FFT.init(nRows);
      var tmpCols = {
        re: new Array(nRows),
        im: new Array(nRows)
      };
      for (var iCol = 0; iCol < ftCols; iCol++) {
        for (var iRow = nRows - 1; iRow >= 0; iRow--) {
          tmpCols.re[iRow] = ft[iRow * 2 * ftCols + iCol];
          tmpCols.im[iRow] = ft[(iRow * 2 + 1) * ftCols + iCol];
        }
        //Unnormalized inverse transform
        FFT.bt(tmpCols.re, tmpCols.im);
        for (var iRow = nRows - 1; iRow >= 0; iRow--) {
          tempTransform[iRow * 2 * ftCols + iCol] = tmpCols.re[iRow];
          tempTransform[(iRow * 2 + 1) * ftCols + iCol] = tmpCols.im[iRow];
        }
      }

      // reverse row transform
      var finalTransform = new Array(nRows * nCols);
      FFT.init(nCols);
      var tmpRows = {
        re: new Array(nCols),
        im: new Array(nCols)
      };
      var scale = nCols * nRows;
      for (var iRow = 0; iRow < ftRows; iRow += 2) {
        tmpRows.re[0] = tempTransform[iRow * ftCols];
        tmpRows.im[0] = tempTransform[(iRow + 1) * ftCols];
        for (var iCol = 1; iCol < ftCols; iCol++) {
          tmpRows.re[iCol] = tempTransform[iRow * ftCols + iCol];
          tmpRows.im[iCol] = tempTransform[(iRow + 1) * ftCols + iCol];
          tmpRows.re[nCols - iCol] = tempTransform[iRow * ftCols + iCol];
          tmpRows.im[nCols - iCol] = -tempTransform[(iRow + 1) * ftCols + iCol];
        }
        //Unnormalized inverse transform
        FFT.bt(tmpRows.re, tmpRows.im);
        var indexB = iRow / 2 * nCols;
        for (var iCol = nCols - 1; iCol >= 0; iCol--) {
          finalTransform[indexB + iCol] = tmpRows.re[iCol] / scale;
        }
      }
      return finalTransform;
    },
    /**
     * Calculates the fourier transform of a matrix of size (nRows,nCols) It is
     * assumed that both nRows and nCols are a power of two
     *
     * On exit the matrix has dimensions (nRows * 2, nCols / 2 + 1) where the
     * even rows contain the real part and the odd rows the imaginary part of the
     * transform
     * @param data
     * @param nRows
     * @param nCols
     * @return
     */
    fft2DArray: function (data, nRows, nCols, opt) {
      Object.assign({}, {
        inplace: true
      });
      var ftCols = nCols / 2 + 1;
      var ftRows = nRows * 2;
      var tempTransform = new Array(ftRows * ftCols);
      FFT.init(nCols);
      // transform rows
      var tmpRows = {
        re: new Array(nCols),
        im: new Array(nCols)
      };
      var row1 = {
        re: new Array(nCols),
        im: new Array(nCols)
      };
      var row2 = {
        re: new Array(nCols),
        im: new Array(nCols)
      };
      var index, iRow0, iRow1, iRow2, iRow3;
      for (var iRow = 0; iRow < nRows / 2; iRow++) {
        index = iRow * 2 * nCols;
        tmpRows.re = data.slice(index, index + nCols);
        index = (iRow * 2 + 1) * nCols;
        tmpRows.im = data.slice(index, index + nCols);
        FFT.fft1d(tmpRows.re, tmpRows.im);
        this.reconstructTwoRealFFT(tmpRows, row1, row2);
        //Now lets put back the result into the output array
        iRow0 = iRow * 4 * ftCols;
        iRow1 = (iRow * 4 + 1) * ftCols;
        iRow2 = (iRow * 4 + 2) * ftCols;
        iRow3 = (iRow * 4 + 3) * ftCols;
        for (var k = ftCols - 1; k >= 0; k--) {
          tempTransform[iRow0 + k] = row1.re[k];
          tempTransform[iRow1 + k] = row1.im[k];
          tempTransform[iRow2 + k] = row2.re[k];
          tempTransform[iRow3 + k] = row2.im[k];
        }
      }

      //console.log(tempTransform);
      row1 = null;
      row2 = null;
      // transform columns
      var finalTransform = new Array(ftRows * ftCols);
      FFT.init(nRows);
      var tmpCols = {
        re: new Array(nRows),
        im: new Array(nRows)
      };
      for (var iCol = ftCols - 1; iCol >= 0; iCol--) {
        for (var iRow = nRows - 1; iRow >= 0; iRow--) {
          tmpCols.re[iRow] = tempTransform[iRow * 2 * ftCols + iCol];
          tmpCols.im[iRow] = tempTransform[(iRow * 2 + 1) * ftCols + iCol];
          //TODO Chech why this happens
          if (isNaN(tmpCols.re[iRow])) {
            tmpCols.re[iRow] = 0;
          }
          if (isNaN(tmpCols.im[iRow])) {
            tmpCols.im[iRow] = 0;
          }
        }
        FFT.fft1d(tmpCols.re, tmpCols.im);
        for (var iRow = nRows - 1; iRow >= 0; iRow--) {
          finalTransform[iRow * 2 * ftCols + iCol] = tmpCols.re[iRow];
          finalTransform[(iRow * 2 + 1) * ftCols + iCol] = tmpCols.im[iRow];
        }
      }

      //console.log(finalTransform);
      return finalTransform;
    },
    /**
     *
     * @param fourierTransform
     * @param realTransform1
     * @param realTransform2
     *
     * Reconstructs the individual Fourier transforms of two simultaneously
     * transformed series. Based on the Symmetry relationships (the asterisk
     * denotes the complex conjugate)
     *
     * F_{N-n} = F_n^{*} for a purely real f transformed to F
     *
     * G_{N-n} = G_n^{*} for a purely imaginary g transformed to G
     *
     */
    reconstructTwoRealFFT: function (fourierTransform, realTransform1, realTransform2) {
      var length = fourierTransform.re.length;

      // the components n=0 are trivial
      realTransform1.re[0] = fourierTransform.re[0];
      realTransform1.im[0] = 0.0;
      realTransform2.re[0] = fourierTransform.im[0];
      realTransform2.im[0] = 0.0;
      var rm, rp, im, ip, j;
      for (var i = length / 2; i > 0; i--) {
        j = length - i;
        rm = 0.5 * (fourierTransform.re[i] - fourierTransform.re[j]);
        rp = 0.5 * (fourierTransform.re[i] + fourierTransform.re[j]);
        im = 0.5 * (fourierTransform.im[i] - fourierTransform.im[j]);
        ip = 0.5 * (fourierTransform.im[i] + fourierTransform.im[j]);
        realTransform1.re[i] = rp;
        realTransform1.im[i] = im;
        realTransform1.re[j] = rp;
        realTransform1.im[j] = -im;
        realTransform2.re[i] = ip;
        realTransform2.im[i] = -rm;
        realTransform2.re[j] = ip;
        realTransform2.im[j] = rm;
      }
    },
    /**
     * In place version of convolute 2D
     *
     * @param ftSignal
     * @param ftFilter
     * @param ftRows
     * @param ftCols
     * @return
     */
    convolute2DI: function (ftSignal, ftFilter, ftRows, ftCols) {
      var re, im;
      for (var iRow = 0; iRow < ftRows / 2; iRow++) {
        for (var iCol = 0; iCol < ftCols; iCol++) {
          //
          re = ftSignal[iRow * 2 * ftCols + iCol] * ftFilter[iRow * 2 * ftCols + iCol] - ftSignal[(iRow * 2 + 1) * ftCols + iCol] * ftFilter[(iRow * 2 + 1) * ftCols + iCol];
          im = ftSignal[iRow * 2 * ftCols + iCol] * ftFilter[(iRow * 2 + 1) * ftCols + iCol] + ftSignal[(iRow * 2 + 1) * ftCols + iCol] * ftFilter[iRow * 2 * ftCols + iCol];
          //
          ftSignal[iRow * 2 * ftCols + iCol] = re;
          ftSignal[(iRow * 2 + 1) * ftCols + iCol] = im;
        }
      }
    },
    /**
     *
     * @param data
     * @param kernel
     * @param nRows
     * @param nCols
     * @returns {*}
     */
    convolute: function (data, kernel, nRows, nCols, opt) {
      var ftSpectrum = new Array(nCols * nRows);
      for (var i = 0; i < nRows * nCols; i++) {
        ftSpectrum[i] = data[i];
      }
      ftSpectrum = this.fft2DArray(ftSpectrum, nRows, nCols);
      var dimR = kernel.length;
      var dimC = kernel[0].length;
      var ftFilterData = new Array(nCols * nRows);
      for (var i = 0; i < nCols * nRows; i++) {
        ftFilterData[i] = 0;
      }
      var iRow, iCol;
      var shiftR = Math.floor((dimR - 1) / 2);
      var shiftC = Math.floor((dimC - 1) / 2);
      for (var ir = 0; ir < dimR; ir++) {
        iRow = (ir - shiftR + nRows) % nRows;
        for (var ic = 0; ic < dimC; ic++) {
          iCol = (ic - shiftC + nCols) % nCols;
          ftFilterData[iRow * nCols + iCol] = kernel[ir][ic];
        }
      }
      ftFilterData = this.fft2DArray(ftFilterData, nRows, nCols);
      var ftRows = nRows * 2;
      var ftCols = nCols / 2 + 1;
      this.convolute2DI(ftSpectrum, ftFilterData, ftRows, ftCols);
      return this.ifft2DArray(ftSpectrum, ftRows, ftCols);
    },
    toRadix2: function (data, nRows, nCols) {
      var i, j, irow, icol;
      var cols = nCols,
        rows = nRows;
      if (!(nCols !== 0 && (nCols & nCols - 1) === 0)) {
        //Then we have to make a pading to next radix2
        cols = 0;
        while (nCols >> ++cols != 0);
        cols = 1 << cols;
      }
      if (!(nRows !== 0 && (nRows & nRows - 1) === 0)) {
        //Then we have to make a pading to next radix2
        rows = 0;
        while (nRows >> ++rows != 0);
        rows = 1 << rows;
      }
      if (rows == nRows && cols == nCols)
        //Do nothing. Returns the same input!!! Be careful
        return {
          data: data,
          rows: nRows,
          cols: nCols
        };
      var output = new Array(rows * cols);
      var shiftR = Math.floor((rows - nRows) / 2) - nRows;
      var shiftC = Math.floor((cols - nCols) / 2) - nCols;
      for (i = 0; i < rows; i++) {
        irow = i * cols;
        icol = (i - shiftR) % nRows * nCols;
        for (j = 0; j < cols; j++) {
          output[irow + j] = data[icol + (j - shiftC) % nCols];
        }
      }
      return {
        data: output,
        rows: rows,
        cols: cols
      };
    },
    /**
     * Crop the given matrix to fit the corresponding number of rows and columns
     */
    crop: function (data, rows, cols, nRows, nCols, opt) {
      if (rows == nRows && cols == nCols)
        //Do nothing. Returns the same input!!! Be careful
        return data;
      Object.assign({}, opt);
      var output = new Array(nCols * nRows);
      var shiftR = Math.floor((rows - nRows) / 2);
      var shiftC = Math.floor((cols - nCols) / 2);
      var destinyRow, sourceRow, i, j;
      for (i = 0; i < nRows; i++) {
        destinyRow = i * nCols;
        sourceRow = (i + shiftR) * cols;
        for (j = 0; j < nCols; j++) {
          output[destinyRow + j] = data[sourceRow + (j + shiftC)];
        }
      }
      return output;
    }
  };
  var FFTUtils_1 = FFTUtils$1;

  src$2.FFTUtils = FFTUtils_1;
  src$2.FFT = fftlib;

  /**
   * Created by acastillo on 7/7/16.
   */
  var FFTUtils = src$2.FFTUtils;
  function convolutionFFT(input, kernel, opt) {
    var tmp = matrix2Array(input);
    var inputData = tmp.data;
    var options = Object.assign({
      normalize: false,
      divisor: 1,
      rows: tmp.rows,
      cols: tmp.cols
    }, opt);
    var nRows, nCols;
    if (options.rows && options.cols) {
      nRows = options.rows;
      nCols = options.cols;
    } else {
      throw new Error("Invalid number of rows or columns " + nRows + " " + nCols);
    }
    var divisor = options.divisor;
    var i, j;
    var kHeight = kernel.length;
    var kWidth = kernel[0].length;
    if (options.normalize) {
      divisor = 0;
      for (i = 0; i < kHeight; i++) for (j = 0; j < kWidth; j++) divisor += kernel[i][j];
    }
    if (divisor === 0) {
      throw new RangeError('convolution: The divisor is equal to zero');
    }
    var radix2Sized = FFTUtils.toRadix2(inputData, nRows, nCols);
    var conv = FFTUtils.convolute(radix2Sized.data, kernel, radix2Sized.rows, radix2Sized.cols);
    conv = FFTUtils.crop(conv, radix2Sized.rows, radix2Sized.cols, nRows, nCols);
    if (divisor != 0 && divisor != 1) {
      for (i = 0; i < conv.length; i++) {
        conv[i] /= divisor;
      }
    }
    return conv;
  }
  function convolutionDirect(input, kernel, opt) {
    var tmp = matrix2Array(input);
    var inputData = tmp.data;
    var options = Object.assign({
      normalize: false,
      divisor: 1,
      rows: tmp.rows,
      cols: tmp.cols
    }, opt);
    var nRows, nCols;
    if (options.rows && options.cols) {
      nRows = options.rows;
      nCols = options.cols;
    } else {
      throw new Error("Invalid number of rows or columns " + nRows + " " + nCols);
    }
    var divisor = options.divisor;
    var kHeight = kernel.length;
    var kWidth = kernel[0].length;
    var i, j, x, y, index, sum, kVal, row, col;
    if (options.normalize) {
      divisor = 0;
      for (i = 0; i < kHeight; i++) for (j = 0; j < kWidth; j++) divisor += kernel[i][j];
    }
    if (divisor === 0) {
      throw new RangeError('convolution: The divisor is equal to zero');
    }
    var output = new Array(nRows * nCols);
    var hHeight = Math.floor(kHeight / 2);
    var hWidth = Math.floor(kWidth / 2);
    for (y = 0; y < nRows; y++) {
      for (x = 0; x < nCols; x++) {
        sum = 0;
        for (j = 0; j < kHeight; j++) {
          for (i = 0; i < kWidth; i++) {
            kVal = kernel[kHeight - j - 1][kWidth - i - 1];
            row = (y + j - hHeight + nRows) % nRows;
            col = (x + i - hWidth + nCols) % nCols;
            index = row * nCols + col;
            sum += inputData[index] * kVal;
          }
        }
        index = y * nCols + x;
        output[index] = sum / divisor;
      }
    }
    return output;
  }
  function LoG(sigma, nPoints, options) {
    var factor = 1000;
    if (options && options.factor) {
      factor = options.factor;
    }
    var kernel = new Array(nPoints);
    var i, j, tmp, y2;
    factor *= -1; //-1/(Math.PI*Math.pow(sigma,4));
    var center = (nPoints - 1) / 2;
    var sigma2 = 2 * sigma * sigma;
    for (i = 0; i < nPoints; i++) {
      kernel[i] = new Array(nPoints);
      y2 = (i - center) * (i - center);
      for (j = 0; j < nPoints; j++) {
        tmp = -((j - center) * (j - center) + y2) / sigma2;
        kernel[i][j] = Math.round(factor * (1 + tmp) * Math.exp(tmp));
      }
    }
    return kernel;
  }
  function matrix2Array(input) {
    var inputData = input;
    var nRows, nCols;
    if (typeof input[0] != "number") {
      nRows = input.length;
      nCols = input[0].length;
      inputData = new Array(nRows * nCols);
      for (var i = 0; i < nRows; i++) {
        for (var j = 0; j < nCols; j++) {
          inputData[i * nCols + j] = input[i][j];
        }
      }
    } else {
      var tmp = Math.sqrt(input.length);
      if (Number.isInteger(tmp)) {
        nRows = tmp;
        nCols = tmp;
      }
    }
    return {
      data: inputData,
      rows: nRows,
      cols: nCols
    };
  }
  var src$1 = {
    fft: convolutionFFT,
    direct: convolutionDirect,
    kernelFactory: {
      LoG: LoG
    },
    matrix2Array: matrix2Array
  };

  var _isFinite = Number.isFinite || function (value) {
    return !(typeof value !== 'number' || value !== value || value === Infinity || value === -Infinity);
  };

  // https://github.com/paulmillr/es6-shim
  // http://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.isinteger
  var isFinite$1 = _isFinite;
  var isInteger = Number.isInteger || function (val) {
    return typeof val === "number" && isFinite$1(val) && Math.floor(val) === val;
  };
  var isInteger$1 = /*@__PURE__*/getDefaultExportFromCjs(isInteger);

  function validateKernel(kernel) {
    let kHeight, kWidth;
    if (Array.isArray(kernel)) {
      if (Array.isArray(kernel[0])) {
        // 2D array
        if ((kernel.length & 1) === 0 || (kernel[0].length & 1) === 0) {
          throw new RangeError('validateKernel: Kernel rows and columns should be odd numbers');
        } else {
          kHeight = Math.floor(kernel.length / 2);
          kWidth = Math.floor(kernel[0].length / 2);
        }
      } else {
        let kernelWidth = Math.sqrt(kernel.length);
        if (isInteger$1(kernelWidth)) {
          kWidth = kHeight = Math.floor(Math.sqrt(kernel.length) / 2);
        } else {
          throw new RangeError('validateKernel: Kernel array should be a square');
        }
        // we convert the array to a matrix
        let newKernel = new Array(kernelWidth);
        for (let i = 0; i < kernelWidth; i++) {
          newKernel[i] = new Array(kernelWidth);
          for (let j = 0; j < kernelWidth; j++) {
            newKernel[i][j] = kernel[i * kernelWidth + j];
          }
        }
        kernel = newKernel;
      }
    } else {
      throw new Error(`validateKernel: Invalid Kernel: ${kernel}`);
    }
    return {
      kernel,
      kWidth,
      kHeight
    };
  }

  function clamp(value, image) {
    return Math.round(Math.min(Math.max(value, 0), image.maxValue));
  }

  function directConvolution(input, kernel, output) {
    if (output === undefined) {
      const length = input.length + kernel.length - 1;
      output = new Array(length);
    }
    fill(output);
    for (var i = 0; i < input.length; i++) {
      for (var j = 0; j < kernel.length; j++) {
        output[i + j] += input[i] * kernel[j];
      }
    }
    return output;
  }
  function fill(array) {
    for (var i = 0; i < array.length; i++) {
      array[i] = 0;
    }
  }

  function convolutionSeparable(data, separatedKernel, width, height) {
    const result = new Array(data.length);
    let tmp, conv, offset, kernel;
    kernel = separatedKernel[1];
    offset = (kernel.length - 1) / 2;
    conv = new Array(width + kernel.length - 1);
    tmp = new Array(width);
    for (let y = 0; y < height; y++) {
      for (let x = 0; x < width; x++) {
        tmp[x] = data[y * width + x];
      }
      directConvolution(tmp, kernel, conv);
      for (let x = 0; x < width; x++) {
        result[y * width + x] = conv[offset + x];
      }
    }
    kernel = separatedKernel[0];
    offset = (kernel.length - 1) / 2;
    conv = new Array(height + kernel.length - 1);
    tmp = new Array(height);
    for (let x = 0; x < width; x++) {
      for (let y = 0; y < height; y++) {
        tmp[y] = result[y * width + x];
      }
      directConvolution(tmp, kernel, conv);
      for (let y = 0; y < height; y++) {
        result[y * width + x] = conv[offset + y];
      }
    }
    return result;
  }

  var matrix = {};

  // eslint-disable-next-line @typescript-eslint/unbound-method
  const toString$1 = Object.prototype.toString;
  /**
   * Checks if an object is an instance of an Array (array or typed array, except those that contain bigint values).
   *
   * @param value - Object to check.
   * @returns True if the object is an array or a typed array.
   */
  function isAnyArray$1(value) {
    const tag = toString$1.call(value);
    return tag.endsWith('Array]') && !tag.includes('Big');
  }

  var libEsm = /*#__PURE__*/Object.freeze({
    __proto__: null,
    isAnyArray: isAnyArray$1
  });

  var require$$0$1 = /*@__PURE__*/getAugmentedNamespace(libEsm);

  function max$1(input) {
    var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    if (!isAnyArray$1(input)) {
      throw new TypeError('input must be an array');
    }
    if (input.length === 0) {
      throw new TypeError('input must not be empty');
    }
    var _options$fromIndex = options.fromIndex,
      fromIndex = _options$fromIndex === void 0 ? 0 : _options$fromIndex,
      _options$toIndex = options.toIndex,
      toIndex = _options$toIndex === void 0 ? input.length : _options$toIndex;
    if (fromIndex < 0 || fromIndex >= input.length || !Number.isInteger(fromIndex)) {
      throw new Error('fromIndex must be a positive integer smaller than length');
    }
    if (toIndex <= fromIndex || toIndex > input.length || !Number.isInteger(toIndex)) {
      throw new Error('toIndex must be an integer greater than fromIndex and at most equal to length');
    }
    var maxValue = input[fromIndex];
    for (var i = fromIndex + 1; i < toIndex; i++) {
      if (input[i] > maxValue) maxValue = input[i];
    }
    return maxValue;
  }

  function min$1(input) {
    var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    if (!isAnyArray$1(input)) {
      throw new TypeError('input must be an array');
    }
    if (input.length === 0) {
      throw new TypeError('input must not be empty');
    }
    var _options$fromIndex = options.fromIndex,
      fromIndex = _options$fromIndex === void 0 ? 0 : _options$fromIndex,
      _options$toIndex = options.toIndex,
      toIndex = _options$toIndex === void 0 ? input.length : _options$toIndex;
    if (fromIndex < 0 || fromIndex >= input.length || !Number.isInteger(fromIndex)) {
      throw new Error('fromIndex must be a positive integer smaller than length');
    }
    if (toIndex <= fromIndex || toIndex > input.length || !Number.isInteger(toIndex)) {
      throw new Error('toIndex must be an integer greater than fromIndex and at most equal to length');
    }
    var minValue = input[fromIndex];
    for (var i = fromIndex + 1; i < toIndex; i++) {
      if (input[i] < minValue) minValue = input[i];
    }
    return minValue;
  }

  function rescale$1(input) {
    var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    if (!isAnyArray$1(input)) {
      throw new TypeError('input must be an array');
    } else if (input.length === 0) {
      throw new TypeError('input must not be empty');
    }
    var output;
    if (options.output !== undefined) {
      if (!isAnyArray$1(options.output)) {
        throw new TypeError('output option must be an array if specified');
      }
      output = options.output;
    } else {
      output = new Array(input.length);
    }
    var currentMin = min$1(input);
    var currentMax = max$1(input);
    if (currentMin === currentMax) {
      throw new RangeError('minimum and maximum input values are equal. Cannot rescale a constant array');
    }
    var _options$min = options.min,
      minValue = _options$min === void 0 ? options.autoMinMax ? currentMin : 0 : _options$min,
      _options$max = options.max,
      maxValue = _options$max === void 0 ? options.autoMinMax ? currentMax : 1 : _options$max;
    if (minValue >= maxValue) {
      throw new RangeError('min option must be smaller than max option');
    }
    var factor = (maxValue - minValue) / (currentMax - currentMin);
    for (var i = 0; i < input.length; i++) {
      output[i] = (input[i] - currentMin) * factor + minValue;
    }
    return output;
  }

  var libEs6 = /*#__PURE__*/Object.freeze({
    __proto__: null,
    default: rescale$1
  });

  var require$$1 = /*@__PURE__*/getAugmentedNamespace(libEs6);

  Object.defineProperty(matrix, '__esModule', {
    value: true
  });
  var isAnyArray = require$$0$1;
  var rescale = require$$1;
  const indent = ' '.repeat(2);
  const indentData = ' '.repeat(4);

  /**
   * @this {Matrix}
   * @returns {string}
   */
  function inspectMatrix() {
    return inspectMatrixWithOptions(this);
  }
  function inspectMatrixWithOptions(matrix, options = {}) {
    const {
      maxRows = 15,
      maxColumns = 10,
      maxNumSize = 8,
      padMinus = 'auto'
    } = options;
    return `${matrix.constructor.name} {
${indent}[
${indentData}${inspectData(matrix, maxRows, maxColumns, maxNumSize, padMinus)}
${indent}]
${indent}rows: ${matrix.rows}
${indent}columns: ${matrix.columns}
}`;
  }
  function inspectData(matrix, maxRows, maxColumns, maxNumSize, padMinus) {
    const {
      rows,
      columns
    } = matrix;
    const maxI = Math.min(rows, maxRows);
    const maxJ = Math.min(columns, maxColumns);
    const result = [];
    if (padMinus === 'auto') {
      padMinus = false;
      loop: for (let i = 0; i < maxI; i++) {
        for (let j = 0; j < maxJ; j++) {
          if (matrix.get(i, j) < 0) {
            padMinus = true;
            break loop;
          }
        }
      }
    }
    for (let i = 0; i < maxI; i++) {
      let line = [];
      for (let j = 0; j < maxJ; j++) {
        line.push(formatNumber(matrix.get(i, j), maxNumSize, padMinus));
      }
      result.push(`${line.join(' ')}`);
    }
    if (maxJ !== columns) {
      result[result.length - 1] += ` ... ${columns - maxColumns} more columns`;
    }
    if (maxI !== rows) {
      result.push(`... ${rows - maxRows} more rows`);
    }
    return result.join(`\n${indentData}`);
  }
  function formatNumber(num, maxNumSize, padMinus) {
    return (num >= 0 && padMinus ? ` ${formatNumber2(num, maxNumSize - 1)}` : formatNumber2(num, maxNumSize)).padEnd(maxNumSize);
  }
  function formatNumber2(num, len) {
    // small.length numbers should be as is
    let str = num.toString();
    if (str.length <= len) return str;

    // (7)'0.00123' is better then (7)'1.23e-2'
    // (8)'0.000123' is worse then (7)'1.23e-3',
    let fix = num.toFixed(len);
    if (fix.length > len) {
      fix = num.toFixed(Math.max(0, len - (fix.length - len)));
    }
    if (fix.length <= len && !fix.startsWith('0.000') && !fix.startsWith('-0.000')) {
      return fix;
    }

    // well, if it's still too long the user should've used longer numbers
    let exp = num.toExponential(len);
    if (exp.length > len) {
      exp = num.toExponential(Math.max(0, len - (exp.length - len)));
    }
    return exp.slice(0);
  }
  function installMathOperations(AbstractMatrix, Matrix) {
    AbstractMatrix.prototype.add = function add(value) {
      if (typeof value === 'number') return this.addS(value);
      return this.addM(value);
    };
    AbstractMatrix.prototype.addS = function addS(value) {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) + value);
        }
      }
      return this;
    };
    AbstractMatrix.prototype.addM = function addM(matrix) {
      matrix = Matrix.checkMatrix(matrix);
      if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
        throw new RangeError('Matrices dimensions must be equal');
      }
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) + matrix.get(i, j));
        }
      }
      return this;
    };
    AbstractMatrix.add = function add(matrix, value) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.add(value);
    };
    AbstractMatrix.prototype.sub = function sub(value) {
      if (typeof value === 'number') return this.subS(value);
      return this.subM(value);
    };
    AbstractMatrix.prototype.subS = function subS(value) {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) - value);
        }
      }
      return this;
    };
    AbstractMatrix.prototype.subM = function subM(matrix) {
      matrix = Matrix.checkMatrix(matrix);
      if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
        throw new RangeError('Matrices dimensions must be equal');
      }
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) - matrix.get(i, j));
        }
      }
      return this;
    };
    AbstractMatrix.sub = function sub(matrix, value) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.sub(value);
    };
    AbstractMatrix.prototype.subtract = AbstractMatrix.prototype.sub;
    AbstractMatrix.prototype.subtractS = AbstractMatrix.prototype.subS;
    AbstractMatrix.prototype.subtractM = AbstractMatrix.prototype.subM;
    AbstractMatrix.subtract = AbstractMatrix.sub;
    AbstractMatrix.prototype.mul = function mul(value) {
      if (typeof value === 'number') return this.mulS(value);
      return this.mulM(value);
    };
    AbstractMatrix.prototype.mulS = function mulS(value) {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) * value);
        }
      }
      return this;
    };
    AbstractMatrix.prototype.mulM = function mulM(matrix) {
      matrix = Matrix.checkMatrix(matrix);
      if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
        throw new RangeError('Matrices dimensions must be equal');
      }
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) * matrix.get(i, j));
        }
      }
      return this;
    };
    AbstractMatrix.mul = function mul(matrix, value) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.mul(value);
    };
    AbstractMatrix.prototype.multiply = AbstractMatrix.prototype.mul;
    AbstractMatrix.prototype.multiplyS = AbstractMatrix.prototype.mulS;
    AbstractMatrix.prototype.multiplyM = AbstractMatrix.prototype.mulM;
    AbstractMatrix.multiply = AbstractMatrix.mul;
    AbstractMatrix.prototype.div = function div(value) {
      if (typeof value === 'number') return this.divS(value);
      return this.divM(value);
    };
    AbstractMatrix.prototype.divS = function divS(value) {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) / value);
        }
      }
      return this;
    };
    AbstractMatrix.prototype.divM = function divM(matrix) {
      matrix = Matrix.checkMatrix(matrix);
      if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
        throw new RangeError('Matrices dimensions must be equal');
      }
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) / matrix.get(i, j));
        }
      }
      return this;
    };
    AbstractMatrix.div = function div(matrix, value) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.div(value);
    };
    AbstractMatrix.prototype.divide = AbstractMatrix.prototype.div;
    AbstractMatrix.prototype.divideS = AbstractMatrix.prototype.divS;
    AbstractMatrix.prototype.divideM = AbstractMatrix.prototype.divM;
    AbstractMatrix.divide = AbstractMatrix.div;
    AbstractMatrix.prototype.mod = function mod(value) {
      if (typeof value === 'number') return this.modS(value);
      return this.modM(value);
    };
    AbstractMatrix.prototype.modS = function modS(value) {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) % value);
        }
      }
      return this;
    };
    AbstractMatrix.prototype.modM = function modM(matrix) {
      matrix = Matrix.checkMatrix(matrix);
      if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
        throw new RangeError('Matrices dimensions must be equal');
      }
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) % matrix.get(i, j));
        }
      }
      return this;
    };
    AbstractMatrix.mod = function mod(matrix, value) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.mod(value);
    };
    AbstractMatrix.prototype.modulus = AbstractMatrix.prototype.mod;
    AbstractMatrix.prototype.modulusS = AbstractMatrix.prototype.modS;
    AbstractMatrix.prototype.modulusM = AbstractMatrix.prototype.modM;
    AbstractMatrix.modulus = AbstractMatrix.mod;
    AbstractMatrix.prototype.and = function and(value) {
      if (typeof value === 'number') return this.andS(value);
      return this.andM(value);
    };
    AbstractMatrix.prototype.andS = function andS(value) {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) & value);
        }
      }
      return this;
    };
    AbstractMatrix.prototype.andM = function andM(matrix) {
      matrix = Matrix.checkMatrix(matrix);
      if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
        throw new RangeError('Matrices dimensions must be equal');
      }
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) & matrix.get(i, j));
        }
      }
      return this;
    };
    AbstractMatrix.and = function and(matrix, value) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.and(value);
    };
    AbstractMatrix.prototype.or = function or(value) {
      if (typeof value === 'number') return this.orS(value);
      return this.orM(value);
    };
    AbstractMatrix.prototype.orS = function orS(value) {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) | value);
        }
      }
      return this;
    };
    AbstractMatrix.prototype.orM = function orM(matrix) {
      matrix = Matrix.checkMatrix(matrix);
      if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
        throw new RangeError('Matrices dimensions must be equal');
      }
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) | matrix.get(i, j));
        }
      }
      return this;
    };
    AbstractMatrix.or = function or(matrix, value) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.or(value);
    };
    AbstractMatrix.prototype.xor = function xor(value) {
      if (typeof value === 'number') return this.xorS(value);
      return this.xorM(value);
    };
    AbstractMatrix.prototype.xorS = function xorS(value) {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) ^ value);
        }
      }
      return this;
    };
    AbstractMatrix.prototype.xorM = function xorM(matrix) {
      matrix = Matrix.checkMatrix(matrix);
      if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
        throw new RangeError('Matrices dimensions must be equal');
      }
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) ^ matrix.get(i, j));
        }
      }
      return this;
    };
    AbstractMatrix.xor = function xor(matrix, value) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.xor(value);
    };
    AbstractMatrix.prototype.leftShift = function leftShift(value) {
      if (typeof value === 'number') return this.leftShiftS(value);
      return this.leftShiftM(value);
    };
    AbstractMatrix.prototype.leftShiftS = function leftShiftS(value) {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) << value);
        }
      }
      return this;
    };
    AbstractMatrix.prototype.leftShiftM = function leftShiftM(matrix) {
      matrix = Matrix.checkMatrix(matrix);
      if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
        throw new RangeError('Matrices dimensions must be equal');
      }
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) << matrix.get(i, j));
        }
      }
      return this;
    };
    AbstractMatrix.leftShift = function leftShift(matrix, value) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.leftShift(value);
    };
    AbstractMatrix.prototype.signPropagatingRightShift = function signPropagatingRightShift(value) {
      if (typeof value === 'number') return this.signPropagatingRightShiftS(value);
      return this.signPropagatingRightShiftM(value);
    };
    AbstractMatrix.prototype.signPropagatingRightShiftS = function signPropagatingRightShiftS(value) {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) >> value);
        }
      }
      return this;
    };
    AbstractMatrix.prototype.signPropagatingRightShiftM = function signPropagatingRightShiftM(matrix) {
      matrix = Matrix.checkMatrix(matrix);
      if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
        throw new RangeError('Matrices dimensions must be equal');
      }
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) >> matrix.get(i, j));
        }
      }
      return this;
    };
    AbstractMatrix.signPropagatingRightShift = function signPropagatingRightShift(matrix, value) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.signPropagatingRightShift(value);
    };
    AbstractMatrix.prototype.rightShift = function rightShift(value) {
      if (typeof value === 'number') return this.rightShiftS(value);
      return this.rightShiftM(value);
    };
    AbstractMatrix.prototype.rightShiftS = function rightShiftS(value) {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) >>> value);
        }
      }
      return this;
    };
    AbstractMatrix.prototype.rightShiftM = function rightShiftM(matrix) {
      matrix = Matrix.checkMatrix(matrix);
      if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
        throw new RangeError('Matrices dimensions must be equal');
      }
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) >>> matrix.get(i, j));
        }
      }
      return this;
    };
    AbstractMatrix.rightShift = function rightShift(matrix, value) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.rightShift(value);
    };
    AbstractMatrix.prototype.zeroFillRightShift = AbstractMatrix.prototype.rightShift;
    AbstractMatrix.prototype.zeroFillRightShiftS = AbstractMatrix.prototype.rightShiftS;
    AbstractMatrix.prototype.zeroFillRightShiftM = AbstractMatrix.prototype.rightShiftM;
    AbstractMatrix.zeroFillRightShift = AbstractMatrix.rightShift;
    AbstractMatrix.prototype.not = function not() {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, ~this.get(i, j));
        }
      }
      return this;
    };
    AbstractMatrix.not = function not(matrix) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.not();
    };
    AbstractMatrix.prototype.abs = function abs() {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, Math.abs(this.get(i, j)));
        }
      }
      return this;
    };
    AbstractMatrix.abs = function abs(matrix) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.abs();
    };
    AbstractMatrix.prototype.acos = function acos() {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, Math.acos(this.get(i, j)));
        }
      }
      return this;
    };
    AbstractMatrix.acos = function acos(matrix) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.acos();
    };
    AbstractMatrix.prototype.acosh = function acosh() {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, Math.acosh(this.get(i, j)));
        }
      }
      return this;
    };
    AbstractMatrix.acosh = function acosh(matrix) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.acosh();
    };
    AbstractMatrix.prototype.asin = function asin() {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, Math.asin(this.get(i, j)));
        }
      }
      return this;
    };
    AbstractMatrix.asin = function asin(matrix) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.asin();
    };
    AbstractMatrix.prototype.asinh = function asinh() {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, Math.asinh(this.get(i, j)));
        }
      }
      return this;
    };
    AbstractMatrix.asinh = function asinh(matrix) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.asinh();
    };
    AbstractMatrix.prototype.atan = function atan() {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, Math.atan(this.get(i, j)));
        }
      }
      return this;
    };
    AbstractMatrix.atan = function atan(matrix) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.atan();
    };
    AbstractMatrix.prototype.atanh = function atanh() {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, Math.atanh(this.get(i, j)));
        }
      }
      return this;
    };
    AbstractMatrix.atanh = function atanh(matrix) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.atanh();
    };
    AbstractMatrix.prototype.cbrt = function cbrt() {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, Math.cbrt(this.get(i, j)));
        }
      }
      return this;
    };
    AbstractMatrix.cbrt = function cbrt(matrix) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.cbrt();
    };
    AbstractMatrix.prototype.ceil = function ceil() {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, Math.ceil(this.get(i, j)));
        }
      }
      return this;
    };
    AbstractMatrix.ceil = function ceil(matrix) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.ceil();
    };
    AbstractMatrix.prototype.clz32 = function clz32() {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, Math.clz32(this.get(i, j)));
        }
      }
      return this;
    };
    AbstractMatrix.clz32 = function clz32(matrix) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.clz32();
    };
    AbstractMatrix.prototype.cos = function cos() {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, Math.cos(this.get(i, j)));
        }
      }
      return this;
    };
    AbstractMatrix.cos = function cos(matrix) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.cos();
    };
    AbstractMatrix.prototype.cosh = function cosh() {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, Math.cosh(this.get(i, j)));
        }
      }
      return this;
    };
    AbstractMatrix.cosh = function cosh(matrix) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.cosh();
    };
    AbstractMatrix.prototype.exp = function exp() {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, Math.exp(this.get(i, j)));
        }
      }
      return this;
    };
    AbstractMatrix.exp = function exp(matrix) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.exp();
    };
    AbstractMatrix.prototype.expm1 = function expm1() {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, Math.expm1(this.get(i, j)));
        }
      }
      return this;
    };
    AbstractMatrix.expm1 = function expm1(matrix) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.expm1();
    };
    AbstractMatrix.prototype.floor = function floor() {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, Math.floor(this.get(i, j)));
        }
      }
      return this;
    };
    AbstractMatrix.floor = function floor(matrix) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.floor();
    };
    AbstractMatrix.prototype.fround = function fround() {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, Math.fround(this.get(i, j)));
        }
      }
      return this;
    };
    AbstractMatrix.fround = function fround(matrix) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.fround();
    };
    AbstractMatrix.prototype.log = function log() {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, Math.log(this.get(i, j)));
        }
      }
      return this;
    };
    AbstractMatrix.log = function log(matrix) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.log();
    };
    AbstractMatrix.prototype.log1p = function log1p() {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, Math.log1p(this.get(i, j)));
        }
      }
      return this;
    };
    AbstractMatrix.log1p = function log1p(matrix) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.log1p();
    };
    AbstractMatrix.prototype.log10 = function log10() {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, Math.log10(this.get(i, j)));
        }
      }
      return this;
    };
    AbstractMatrix.log10 = function log10(matrix) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.log10();
    };
    AbstractMatrix.prototype.log2 = function log2() {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, Math.log2(this.get(i, j)));
        }
      }
      return this;
    };
    AbstractMatrix.log2 = function log2(matrix) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.log2();
    };
    AbstractMatrix.prototype.round = function round() {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, Math.round(this.get(i, j)));
        }
      }
      return this;
    };
    AbstractMatrix.round = function round(matrix) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.round();
    };
    AbstractMatrix.prototype.sign = function sign() {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, Math.sign(this.get(i, j)));
        }
      }
      return this;
    };
    AbstractMatrix.sign = function sign(matrix) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.sign();
    };
    AbstractMatrix.prototype.sin = function sin() {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, Math.sin(this.get(i, j)));
        }
      }
      return this;
    };
    AbstractMatrix.sin = function sin(matrix) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.sin();
    };
    AbstractMatrix.prototype.sinh = function sinh() {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, Math.sinh(this.get(i, j)));
        }
      }
      return this;
    };
    AbstractMatrix.sinh = function sinh(matrix) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.sinh();
    };
    AbstractMatrix.prototype.sqrt = function sqrt() {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, Math.sqrt(this.get(i, j)));
        }
      }
      return this;
    };
    AbstractMatrix.sqrt = function sqrt(matrix) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.sqrt();
    };
    AbstractMatrix.prototype.tan = function tan() {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, Math.tan(this.get(i, j)));
        }
      }
      return this;
    };
    AbstractMatrix.tan = function tan(matrix) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.tan();
    };
    AbstractMatrix.prototype.tanh = function tanh() {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, Math.tanh(this.get(i, j)));
        }
      }
      return this;
    };
    AbstractMatrix.tanh = function tanh(matrix) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.tanh();
    };
    AbstractMatrix.prototype.trunc = function trunc() {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, Math.trunc(this.get(i, j)));
        }
      }
      return this;
    };
    AbstractMatrix.trunc = function trunc(matrix) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.trunc();
    };
    AbstractMatrix.pow = function pow(matrix, arg0) {
      const newMatrix = new Matrix(matrix);
      return newMatrix.pow(arg0);
    };
    AbstractMatrix.prototype.pow = function pow(value) {
      if (typeof value === 'number') return this.powS(value);
      return this.powM(value);
    };
    AbstractMatrix.prototype.powS = function powS(value) {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) ** value);
        }
      }
      return this;
    };
    AbstractMatrix.prototype.powM = function powM(matrix) {
      matrix = Matrix.checkMatrix(matrix);
      if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
        throw new RangeError('Matrices dimensions must be equal');
      }
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) ** matrix.get(i, j));
        }
      }
      return this;
    };
  }

  /**
   * @private
   * Check that a row index is not out of bounds
   * @param {Matrix} matrix
   * @param {number} index
   * @param {boolean} [outer]
   */
  function checkRowIndex(matrix, index, outer) {
    let max = outer ? matrix.rows : matrix.rows - 1;
    if (index < 0 || index > max) {
      throw new RangeError('Row index out of range');
    }
  }

  /**
   * @private
   * Check that a column index is not out of bounds
   * @param {Matrix} matrix
   * @param {number} index
   * @param {boolean} [outer]
   */
  function checkColumnIndex(matrix, index, outer) {
    let max = outer ? matrix.columns : matrix.columns - 1;
    if (index < 0 || index > max) {
      throw new RangeError('Column index out of range');
    }
  }

  /**
   * @private
   * Check that the provided vector is an array with the right length
   * @param {Matrix} matrix
   * @param {Array|Matrix} vector
   * @return {Array}
   * @throws {RangeError}
   */
  function checkRowVector(matrix, vector) {
    if (vector.to1DArray) {
      vector = vector.to1DArray();
    }
    if (vector.length !== matrix.columns) {
      throw new RangeError('vector size must be the same as the number of columns');
    }
    return vector;
  }

  /**
   * @private
   * Check that the provided vector is an array with the right length
   * @param {Matrix} matrix
   * @param {Array|Matrix} vector
   * @return {Array}
   * @throws {RangeError}
   */
  function checkColumnVector(matrix, vector) {
    if (vector.to1DArray) {
      vector = vector.to1DArray();
    }
    if (vector.length !== matrix.rows) {
      throw new RangeError('vector size must be the same as the number of rows');
    }
    return vector;
  }
  function checkRowIndices(matrix, rowIndices) {
    if (!isAnyArray.isAnyArray(rowIndices)) {
      throw new TypeError('row indices must be an array');
    }
    for (let i = 0; i < rowIndices.length; i++) {
      if (rowIndices[i] < 0 || rowIndices[i] >= matrix.rows) {
        throw new RangeError('row indices are out of range');
      }
    }
  }
  function checkColumnIndices(matrix, columnIndices) {
    if (!isAnyArray.isAnyArray(columnIndices)) {
      throw new TypeError('column indices must be an array');
    }
    for (let i = 0; i < columnIndices.length; i++) {
      if (columnIndices[i] < 0 || columnIndices[i] >= matrix.columns) {
        throw new RangeError('column indices are out of range');
      }
    }
  }
  function checkRange(matrix, startRow, endRow, startColumn, endColumn) {
    if (arguments.length !== 5) {
      throw new RangeError('expected 4 arguments');
    }
    checkNumber('startRow', startRow);
    checkNumber('endRow', endRow);
    checkNumber('startColumn', startColumn);
    checkNumber('endColumn', endColumn);
    if (startRow > endRow || startColumn > endColumn || startRow < 0 || startRow >= matrix.rows || endRow < 0 || endRow >= matrix.rows || startColumn < 0 || startColumn >= matrix.columns || endColumn < 0 || endColumn >= matrix.columns) {
      throw new RangeError('Submatrix indices are out of range');
    }
  }
  function newArray$2(length, value = 0) {
    let array = [];
    for (let i = 0; i < length; i++) {
      array.push(value);
    }
    return array;
  }
  function checkNumber(name, value) {
    if (typeof value !== 'number') {
      throw new TypeError(`${name} must be a number`);
    }
  }
  function checkNonEmpty(matrix) {
    if (matrix.isEmpty()) {
      throw new Error('Empty matrix has no elements to index');
    }
  }
  function sumByRow(matrix) {
    let sum = newArray$2(matrix.rows);
    for (let i = 0; i < matrix.rows; ++i) {
      for (let j = 0; j < matrix.columns; ++j) {
        sum[i] += matrix.get(i, j);
      }
    }
    return sum;
  }
  function sumByColumn(matrix) {
    let sum = newArray$2(matrix.columns);
    for (let i = 0; i < matrix.rows; ++i) {
      for (let j = 0; j < matrix.columns; ++j) {
        sum[j] += matrix.get(i, j);
      }
    }
    return sum;
  }
  function sumAll(matrix) {
    let v = 0;
    for (let i = 0; i < matrix.rows; i++) {
      for (let j = 0; j < matrix.columns; j++) {
        v += matrix.get(i, j);
      }
    }
    return v;
  }
  function productByRow(matrix) {
    let sum = newArray$2(matrix.rows, 1);
    for (let i = 0; i < matrix.rows; ++i) {
      for (let j = 0; j < matrix.columns; ++j) {
        sum[i] *= matrix.get(i, j);
      }
    }
    return sum;
  }
  function productByColumn(matrix) {
    let sum = newArray$2(matrix.columns, 1);
    for (let i = 0; i < matrix.rows; ++i) {
      for (let j = 0; j < matrix.columns; ++j) {
        sum[j] *= matrix.get(i, j);
      }
    }
    return sum;
  }
  function productAll(matrix) {
    let v = 1;
    for (let i = 0; i < matrix.rows; i++) {
      for (let j = 0; j < matrix.columns; j++) {
        v *= matrix.get(i, j);
      }
    }
    return v;
  }
  function varianceByRow(matrix, unbiased, mean) {
    const rows = matrix.rows;
    const cols = matrix.columns;
    const variance = [];
    for (let i = 0; i < rows; i++) {
      let sum1 = 0;
      let sum2 = 0;
      let x = 0;
      for (let j = 0; j < cols; j++) {
        x = matrix.get(i, j) - mean[i];
        sum1 += x;
        sum2 += x * x;
      }
      if (unbiased) {
        variance.push((sum2 - sum1 * sum1 / cols) / (cols - 1));
      } else {
        variance.push((sum2 - sum1 * sum1 / cols) / cols);
      }
    }
    return variance;
  }
  function varianceByColumn(matrix, unbiased, mean) {
    const rows = matrix.rows;
    const cols = matrix.columns;
    const variance = [];
    for (let j = 0; j < cols; j++) {
      let sum1 = 0;
      let sum2 = 0;
      let x = 0;
      for (let i = 0; i < rows; i++) {
        x = matrix.get(i, j) - mean[j];
        sum1 += x;
        sum2 += x * x;
      }
      if (unbiased) {
        variance.push((sum2 - sum1 * sum1 / rows) / (rows - 1));
      } else {
        variance.push((sum2 - sum1 * sum1 / rows) / rows);
      }
    }
    return variance;
  }
  function varianceAll(matrix, unbiased, mean) {
    const rows = matrix.rows;
    const cols = matrix.columns;
    const size = rows * cols;
    let sum1 = 0;
    let sum2 = 0;
    let x = 0;
    for (let i = 0; i < rows; i++) {
      for (let j = 0; j < cols; j++) {
        x = matrix.get(i, j) - mean;
        sum1 += x;
        sum2 += x * x;
      }
    }
    if (unbiased) {
      return (sum2 - sum1 * sum1 / size) / (size - 1);
    } else {
      return (sum2 - sum1 * sum1 / size) / size;
    }
  }
  function centerByRow(matrix, mean) {
    for (let i = 0; i < matrix.rows; i++) {
      for (let j = 0; j < matrix.columns; j++) {
        matrix.set(i, j, matrix.get(i, j) - mean[i]);
      }
    }
  }
  function centerByColumn(matrix, mean) {
    for (let i = 0; i < matrix.rows; i++) {
      for (let j = 0; j < matrix.columns; j++) {
        matrix.set(i, j, matrix.get(i, j) - mean[j]);
      }
    }
  }
  function centerAll(matrix, mean) {
    for (let i = 0; i < matrix.rows; i++) {
      for (let j = 0; j < matrix.columns; j++) {
        matrix.set(i, j, matrix.get(i, j) - mean);
      }
    }
  }
  function getScaleByRow(matrix) {
    const scale = [];
    for (let i = 0; i < matrix.rows; i++) {
      let sum = 0;
      for (let j = 0; j < matrix.columns; j++) {
        sum += matrix.get(i, j) ** 2 / (matrix.columns - 1);
      }
      scale.push(Math.sqrt(sum));
    }
    return scale;
  }
  function scaleByRow(matrix, scale) {
    for (let i = 0; i < matrix.rows; i++) {
      for (let j = 0; j < matrix.columns; j++) {
        matrix.set(i, j, matrix.get(i, j) / scale[i]);
      }
    }
  }
  function getScaleByColumn(matrix) {
    const scale = [];
    for (let j = 0; j < matrix.columns; j++) {
      let sum = 0;
      for (let i = 0; i < matrix.rows; i++) {
        sum += matrix.get(i, j) ** 2 / (matrix.rows - 1);
      }
      scale.push(Math.sqrt(sum));
    }
    return scale;
  }
  function scaleByColumn(matrix, scale) {
    for (let i = 0; i < matrix.rows; i++) {
      for (let j = 0; j < matrix.columns; j++) {
        matrix.set(i, j, matrix.get(i, j) / scale[j]);
      }
    }
  }
  function getScaleAll(matrix) {
    const divider = matrix.size - 1;
    let sum = 0;
    for (let j = 0; j < matrix.columns; j++) {
      for (let i = 0; i < matrix.rows; i++) {
        sum += matrix.get(i, j) ** 2 / divider;
      }
    }
    return Math.sqrt(sum);
  }
  function scaleAll(matrix, scale) {
    for (let i = 0; i < matrix.rows; i++) {
      for (let j = 0; j < matrix.columns; j++) {
        matrix.set(i, j, matrix.get(i, j) / scale);
      }
    }
  }
  class AbstractMatrix {
    static from1DArray(newRows, newColumns, newData) {
      let length = newRows * newColumns;
      if (length !== newData.length) {
        throw new RangeError('data length does not match given dimensions');
      }
      let newMatrix = new Matrix$3(newRows, newColumns);
      for (let row = 0; row < newRows; row++) {
        for (let column = 0; column < newColumns; column++) {
          newMatrix.set(row, column, newData[row * newColumns + column]);
        }
      }
      return newMatrix;
    }
    static rowVector(newData) {
      let vector = new Matrix$3(1, newData.length);
      for (let i = 0; i < newData.length; i++) {
        vector.set(0, i, newData[i]);
      }
      return vector;
    }
    static columnVector(newData) {
      let vector = new Matrix$3(newData.length, 1);
      for (let i = 0; i < newData.length; i++) {
        vector.set(i, 0, newData[i]);
      }
      return vector;
    }
    static zeros(rows, columns) {
      return new Matrix$3(rows, columns);
    }
    static ones(rows, columns) {
      return new Matrix$3(rows, columns).fill(1);
    }
    static rand(rows, columns, options = {}) {
      if (typeof options !== 'object') {
        throw new TypeError('options must be an object');
      }
      const {
        random = Math.random
      } = options;
      let matrix = new Matrix$3(rows, columns);
      for (let i = 0; i < rows; i++) {
        for (let j = 0; j < columns; j++) {
          matrix.set(i, j, random());
        }
      }
      return matrix;
    }
    static randInt(rows, columns, options = {}) {
      if (typeof options !== 'object') {
        throw new TypeError('options must be an object');
      }
      const {
        min = 0,
        max = 1000,
        random = Math.random
      } = options;
      if (!Number.isInteger(min)) throw new TypeError('min must be an integer');
      if (!Number.isInteger(max)) throw new TypeError('max must be an integer');
      if (min >= max) throw new RangeError('min must be smaller than max');
      let interval = max - min;
      let matrix = new Matrix$3(rows, columns);
      for (let i = 0; i < rows; i++) {
        for (let j = 0; j < columns; j++) {
          let value = min + Math.round(random() * interval);
          matrix.set(i, j, value);
        }
      }
      return matrix;
    }
    static eye(rows, columns, value) {
      if (columns === undefined) columns = rows;
      if (value === undefined) value = 1;
      let min = Math.min(rows, columns);
      let matrix = this.zeros(rows, columns);
      for (let i = 0; i < min; i++) {
        matrix.set(i, i, value);
      }
      return matrix;
    }
    static diag(data, rows, columns) {
      let l = data.length;
      if (rows === undefined) rows = l;
      if (columns === undefined) columns = rows;
      let min = Math.min(l, rows, columns);
      let matrix = this.zeros(rows, columns);
      for (let i = 0; i < min; i++) {
        matrix.set(i, i, data[i]);
      }
      return matrix;
    }
    static min(matrix1, matrix2) {
      matrix1 = this.checkMatrix(matrix1);
      matrix2 = this.checkMatrix(matrix2);
      let rows = matrix1.rows;
      let columns = matrix1.columns;
      let result = new Matrix$3(rows, columns);
      for (let i = 0; i < rows; i++) {
        for (let j = 0; j < columns; j++) {
          result.set(i, j, Math.min(matrix1.get(i, j), matrix2.get(i, j)));
        }
      }
      return result;
    }
    static max(matrix1, matrix2) {
      matrix1 = this.checkMatrix(matrix1);
      matrix2 = this.checkMatrix(matrix2);
      let rows = matrix1.rows;
      let columns = matrix1.columns;
      let result = new this(rows, columns);
      for (let i = 0; i < rows; i++) {
        for (let j = 0; j < columns; j++) {
          result.set(i, j, Math.max(matrix1.get(i, j), matrix2.get(i, j)));
        }
      }
      return result;
    }
    static checkMatrix(value) {
      return AbstractMatrix.isMatrix(value) ? value : new Matrix$3(value);
    }
    static isMatrix(value) {
      return value != null && value.klass === 'Matrix';
    }
    get size() {
      return this.rows * this.columns;
    }
    apply(callback) {
      if (typeof callback !== 'function') {
        throw new TypeError('callback must be a function');
      }
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          callback.call(this, i, j);
        }
      }
      return this;
    }
    to1DArray() {
      let array = [];
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          array.push(this.get(i, j));
        }
      }
      return array;
    }
    to2DArray() {
      let copy = [];
      for (let i = 0; i < this.rows; i++) {
        copy.push([]);
        for (let j = 0; j < this.columns; j++) {
          copy[i].push(this.get(i, j));
        }
      }
      return copy;
    }
    toJSON() {
      return this.to2DArray();
    }
    isRowVector() {
      return this.rows === 1;
    }
    isColumnVector() {
      return this.columns === 1;
    }
    isVector() {
      return this.rows === 1 || this.columns === 1;
    }
    isSquare() {
      return this.rows === this.columns;
    }
    isEmpty() {
      return this.rows === 0 || this.columns === 0;
    }
    isSymmetric() {
      if (this.isSquare()) {
        for (let i = 0; i < this.rows; i++) {
          for (let j = 0; j <= i; j++) {
            if (this.get(i, j) !== this.get(j, i)) {
              return false;
            }
          }
        }
        return true;
      }
      return false;
    }
    isDistance() {
      if (!this.isSymmetric()) return false;
      for (let i = 0; i < this.rows; i++) {
        if (this.get(i, i) !== 0) return false;
      }
      return true;
    }
    isEchelonForm() {
      let i = 0;
      let j = 0;
      let previousColumn = -1;
      let isEchelonForm = true;
      let checked = false;
      while (i < this.rows && isEchelonForm) {
        j = 0;
        checked = false;
        while (j < this.columns && checked === false) {
          if (this.get(i, j) === 0) {
            j++;
          } else if (this.get(i, j) === 1 && j > previousColumn) {
            checked = true;
            previousColumn = j;
          } else {
            isEchelonForm = false;
            checked = true;
          }
        }
        i++;
      }
      return isEchelonForm;
    }
    isReducedEchelonForm() {
      let i = 0;
      let j = 0;
      let previousColumn = -1;
      let isReducedEchelonForm = true;
      let checked = false;
      while (i < this.rows && isReducedEchelonForm) {
        j = 0;
        checked = false;
        while (j < this.columns && checked === false) {
          if (this.get(i, j) === 0) {
            j++;
          } else if (this.get(i, j) === 1 && j > previousColumn) {
            checked = true;
            previousColumn = j;
          } else {
            isReducedEchelonForm = false;
            checked = true;
          }
        }
        for (let k = j + 1; k < this.rows; k++) {
          if (this.get(i, k) !== 0) {
            isReducedEchelonForm = false;
          }
        }
        i++;
      }
      return isReducedEchelonForm;
    }
    echelonForm() {
      let result = this.clone();
      let h = 0;
      let k = 0;
      while (h < result.rows && k < result.columns) {
        let iMax = h;
        for (let i = h; i < result.rows; i++) {
          if (result.get(i, k) > result.get(iMax, k)) {
            iMax = i;
          }
        }
        if (result.get(iMax, k) === 0) {
          k++;
        } else {
          result.swapRows(h, iMax);
          let tmp = result.get(h, k);
          for (let j = k; j < result.columns; j++) {
            result.set(h, j, result.get(h, j) / tmp);
          }
          for (let i = h + 1; i < result.rows; i++) {
            let factor = result.get(i, k) / result.get(h, k);
            result.set(i, k, 0);
            for (let j = k + 1; j < result.columns; j++) {
              result.set(i, j, result.get(i, j) - result.get(h, j) * factor);
            }
          }
          h++;
          k++;
        }
      }
      return result;
    }
    reducedEchelonForm() {
      let result = this.echelonForm();
      let m = result.columns;
      let n = result.rows;
      let h = n - 1;
      while (h >= 0) {
        if (result.maxRow(h) === 0) {
          h--;
        } else {
          let p = 0;
          let pivot = false;
          while (p < n && pivot === false) {
            if (result.get(h, p) === 1) {
              pivot = true;
            } else {
              p++;
            }
          }
          for (let i = 0; i < h; i++) {
            let factor = result.get(i, p);
            for (let j = p; j < m; j++) {
              let tmp = result.get(i, j) - factor * result.get(h, j);
              result.set(i, j, tmp);
            }
          }
          h--;
        }
      }
      return result;
    }
    set() {
      throw new Error('set method is unimplemented');
    }
    get() {
      throw new Error('get method is unimplemented');
    }
    repeat(options = {}) {
      if (typeof options !== 'object') {
        throw new TypeError('options must be an object');
      }
      const {
        rows = 1,
        columns = 1
      } = options;
      if (!Number.isInteger(rows) || rows <= 0) {
        throw new TypeError('rows must be a positive integer');
      }
      if (!Number.isInteger(columns) || columns <= 0) {
        throw new TypeError('columns must be a positive integer');
      }
      let matrix = new Matrix$3(this.rows * rows, this.columns * columns);
      for (let i = 0; i < rows; i++) {
        for (let j = 0; j < columns; j++) {
          matrix.setSubMatrix(this, this.rows * i, this.columns * j);
        }
      }
      return matrix;
    }
    fill(value) {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, value);
        }
      }
      return this;
    }
    neg() {
      return this.mulS(-1);
    }
    getRow(index) {
      checkRowIndex(this, index);
      let row = [];
      for (let i = 0; i < this.columns; i++) {
        row.push(this.get(index, i));
      }
      return row;
    }
    getRowVector(index) {
      return Matrix$3.rowVector(this.getRow(index));
    }
    setRow(index, array) {
      checkRowIndex(this, index);
      array = checkRowVector(this, array);
      for (let i = 0; i < this.columns; i++) {
        this.set(index, i, array[i]);
      }
      return this;
    }
    swapRows(row1, row2) {
      checkRowIndex(this, row1);
      checkRowIndex(this, row2);
      for (let i = 0; i < this.columns; i++) {
        let temp = this.get(row1, i);
        this.set(row1, i, this.get(row2, i));
        this.set(row2, i, temp);
      }
      return this;
    }
    getColumn(index) {
      checkColumnIndex(this, index);
      let column = [];
      for (let i = 0; i < this.rows; i++) {
        column.push(this.get(i, index));
      }
      return column;
    }
    getColumnVector(index) {
      return Matrix$3.columnVector(this.getColumn(index));
    }
    setColumn(index, array) {
      checkColumnIndex(this, index);
      array = checkColumnVector(this, array);
      for (let i = 0; i < this.rows; i++) {
        this.set(i, index, array[i]);
      }
      return this;
    }
    swapColumns(column1, column2) {
      checkColumnIndex(this, column1);
      checkColumnIndex(this, column2);
      for (let i = 0; i < this.rows; i++) {
        let temp = this.get(i, column1);
        this.set(i, column1, this.get(i, column2));
        this.set(i, column2, temp);
      }
      return this;
    }
    addRowVector(vector) {
      vector = checkRowVector(this, vector);
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) + vector[j]);
        }
      }
      return this;
    }
    subRowVector(vector) {
      vector = checkRowVector(this, vector);
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) - vector[j]);
        }
      }
      return this;
    }
    mulRowVector(vector) {
      vector = checkRowVector(this, vector);
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) * vector[j]);
        }
      }
      return this;
    }
    divRowVector(vector) {
      vector = checkRowVector(this, vector);
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) / vector[j]);
        }
      }
      return this;
    }
    addColumnVector(vector) {
      vector = checkColumnVector(this, vector);
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) + vector[i]);
        }
      }
      return this;
    }
    subColumnVector(vector) {
      vector = checkColumnVector(this, vector);
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) - vector[i]);
        }
      }
      return this;
    }
    mulColumnVector(vector) {
      vector = checkColumnVector(this, vector);
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) * vector[i]);
        }
      }
      return this;
    }
    divColumnVector(vector) {
      vector = checkColumnVector(this, vector);
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          this.set(i, j, this.get(i, j) / vector[i]);
        }
      }
      return this;
    }
    mulRow(index, value) {
      checkRowIndex(this, index);
      for (let i = 0; i < this.columns; i++) {
        this.set(index, i, this.get(index, i) * value);
      }
      return this;
    }
    mulColumn(index, value) {
      checkColumnIndex(this, index);
      for (let i = 0; i < this.rows; i++) {
        this.set(i, index, this.get(i, index) * value);
      }
      return this;
    }
    max(by) {
      if (this.isEmpty()) {
        return NaN;
      }
      switch (by) {
        case 'row':
          {
            const max = new Array(this.rows).fill(Number.NEGATIVE_INFINITY);
            for (let row = 0; row < this.rows; row++) {
              for (let column = 0; column < this.columns; column++) {
                if (this.get(row, column) > max[row]) {
                  max[row] = this.get(row, column);
                }
              }
            }
            return max;
          }
        case 'column':
          {
            const max = new Array(this.columns).fill(Number.NEGATIVE_INFINITY);
            for (let row = 0; row < this.rows; row++) {
              for (let column = 0; column < this.columns; column++) {
                if (this.get(row, column) > max[column]) {
                  max[column] = this.get(row, column);
                }
              }
            }
            return max;
          }
        case undefined:
          {
            let max = this.get(0, 0);
            for (let row = 0; row < this.rows; row++) {
              for (let column = 0; column < this.columns; column++) {
                if (this.get(row, column) > max) {
                  max = this.get(row, column);
                }
              }
            }
            return max;
          }
        default:
          throw new Error(`invalid option: ${by}`);
      }
    }
    maxIndex() {
      checkNonEmpty(this);
      let v = this.get(0, 0);
      let idx = [0, 0];
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          if (this.get(i, j) > v) {
            v = this.get(i, j);
            idx[0] = i;
            idx[1] = j;
          }
        }
      }
      return idx;
    }
    min(by) {
      if (this.isEmpty()) {
        return NaN;
      }
      switch (by) {
        case 'row':
          {
            const min = new Array(this.rows).fill(Number.POSITIVE_INFINITY);
            for (let row = 0; row < this.rows; row++) {
              for (let column = 0; column < this.columns; column++) {
                if (this.get(row, column) < min[row]) {
                  min[row] = this.get(row, column);
                }
              }
            }
            return min;
          }
        case 'column':
          {
            const min = new Array(this.columns).fill(Number.POSITIVE_INFINITY);
            for (let row = 0; row < this.rows; row++) {
              for (let column = 0; column < this.columns; column++) {
                if (this.get(row, column) < min[column]) {
                  min[column] = this.get(row, column);
                }
              }
            }
            return min;
          }
        case undefined:
          {
            let min = this.get(0, 0);
            for (let row = 0; row < this.rows; row++) {
              for (let column = 0; column < this.columns; column++) {
                if (this.get(row, column) < min) {
                  min = this.get(row, column);
                }
              }
            }
            return min;
          }
        default:
          throw new Error(`invalid option: ${by}`);
      }
    }
    minIndex() {
      checkNonEmpty(this);
      let v = this.get(0, 0);
      let idx = [0, 0];
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          if (this.get(i, j) < v) {
            v = this.get(i, j);
            idx[0] = i;
            idx[1] = j;
          }
        }
      }
      return idx;
    }
    maxRow(row) {
      checkRowIndex(this, row);
      if (this.isEmpty()) {
        return NaN;
      }
      let v = this.get(row, 0);
      for (let i = 1; i < this.columns; i++) {
        if (this.get(row, i) > v) {
          v = this.get(row, i);
        }
      }
      return v;
    }
    maxRowIndex(row) {
      checkRowIndex(this, row);
      checkNonEmpty(this);
      let v = this.get(row, 0);
      let idx = [row, 0];
      for (let i = 1; i < this.columns; i++) {
        if (this.get(row, i) > v) {
          v = this.get(row, i);
          idx[1] = i;
        }
      }
      return idx;
    }
    minRow(row) {
      checkRowIndex(this, row);
      if (this.isEmpty()) {
        return NaN;
      }
      let v = this.get(row, 0);
      for (let i = 1; i < this.columns; i++) {
        if (this.get(row, i) < v) {
          v = this.get(row, i);
        }
      }
      return v;
    }
    minRowIndex(row) {
      checkRowIndex(this, row);
      checkNonEmpty(this);
      let v = this.get(row, 0);
      let idx = [row, 0];
      for (let i = 1; i < this.columns; i++) {
        if (this.get(row, i) < v) {
          v = this.get(row, i);
          idx[1] = i;
        }
      }
      return idx;
    }
    maxColumn(column) {
      checkColumnIndex(this, column);
      if (this.isEmpty()) {
        return NaN;
      }
      let v = this.get(0, column);
      for (let i = 1; i < this.rows; i++) {
        if (this.get(i, column) > v) {
          v = this.get(i, column);
        }
      }
      return v;
    }
    maxColumnIndex(column) {
      checkColumnIndex(this, column);
      checkNonEmpty(this);
      let v = this.get(0, column);
      let idx = [0, column];
      for (let i = 1; i < this.rows; i++) {
        if (this.get(i, column) > v) {
          v = this.get(i, column);
          idx[0] = i;
        }
      }
      return idx;
    }
    minColumn(column) {
      checkColumnIndex(this, column);
      if (this.isEmpty()) {
        return NaN;
      }
      let v = this.get(0, column);
      for (let i = 1; i < this.rows; i++) {
        if (this.get(i, column) < v) {
          v = this.get(i, column);
        }
      }
      return v;
    }
    minColumnIndex(column) {
      checkColumnIndex(this, column);
      checkNonEmpty(this);
      let v = this.get(0, column);
      let idx = [0, column];
      for (let i = 1; i < this.rows; i++) {
        if (this.get(i, column) < v) {
          v = this.get(i, column);
          idx[0] = i;
        }
      }
      return idx;
    }
    diag() {
      let min = Math.min(this.rows, this.columns);
      let diag = [];
      for (let i = 0; i < min; i++) {
        diag.push(this.get(i, i));
      }
      return diag;
    }
    norm(type = 'frobenius') {
      switch (type) {
        case 'max':
          return this.max();
        case 'frobenius':
          return Math.sqrt(this.dot(this));
        default:
          throw new RangeError(`unknown norm type: ${type}`);
      }
    }
    cumulativeSum() {
      let sum = 0;
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          sum += this.get(i, j);
          this.set(i, j, sum);
        }
      }
      return this;
    }
    dot(vector2) {
      if (AbstractMatrix.isMatrix(vector2)) vector2 = vector2.to1DArray();
      let vector1 = this.to1DArray();
      if (vector1.length !== vector2.length) {
        throw new RangeError('vectors do not have the same size');
      }
      let dot = 0;
      for (let i = 0; i < vector1.length; i++) {
        dot += vector1[i] * vector2[i];
      }
      return dot;
    }
    mmul(other) {
      other = Matrix$3.checkMatrix(other);
      let m = this.rows;
      let n = this.columns;
      let p = other.columns;
      let result = new Matrix$3(m, p);
      let Bcolj = new Float64Array(n);
      for (let j = 0; j < p; j++) {
        for (let k = 0; k < n; k++) {
          Bcolj[k] = other.get(k, j);
        }
        for (let i = 0; i < m; i++) {
          let s = 0;
          for (let k = 0; k < n; k++) {
            s += this.get(i, k) * Bcolj[k];
          }
          result.set(i, j, s);
        }
      }
      return result;
    }
    mpow(scalar) {
      if (!this.isSquare()) {
        throw new RangeError('Matrix must be square');
      }
      if (!Number.isInteger(scalar) || scalar < 0) {
        throw new RangeError('Exponent must be a non-negative integer');
      }
      // Russian Peasant exponentiation, i.e. exponentiation by squaring
      let result = Matrix$3.eye(this.rows);
      let bb = this;
      // Note: Don't bit shift. In JS, that would truncate at 32 bits
      for (let e = scalar; e >= 1; e /= 2) {
        if ((e & 1) !== 0) {
          result = result.mmul(bb);
        }
        bb = bb.mmul(bb);
      }
      return result;
    }
    strassen2x2(other) {
      other = Matrix$3.checkMatrix(other);
      let result = new Matrix$3(2, 2);
      const a11 = this.get(0, 0);
      const b11 = other.get(0, 0);
      const a12 = this.get(0, 1);
      const b12 = other.get(0, 1);
      const a21 = this.get(1, 0);
      const b21 = other.get(1, 0);
      const a22 = this.get(1, 1);
      const b22 = other.get(1, 1);

      // Compute intermediate values.
      const m1 = (a11 + a22) * (b11 + b22);
      const m2 = (a21 + a22) * b11;
      const m3 = a11 * (b12 - b22);
      const m4 = a22 * (b21 - b11);
      const m5 = (a11 + a12) * b22;
      const m6 = (a21 - a11) * (b11 + b12);
      const m7 = (a12 - a22) * (b21 + b22);

      // Combine intermediate values into the output.
      const c00 = m1 + m4 - m5 + m7;
      const c01 = m3 + m5;
      const c10 = m2 + m4;
      const c11 = m1 - m2 + m3 + m6;
      result.set(0, 0, c00);
      result.set(0, 1, c01);
      result.set(1, 0, c10);
      result.set(1, 1, c11);
      return result;
    }
    strassen3x3(other) {
      other = Matrix$3.checkMatrix(other);
      let result = new Matrix$3(3, 3);
      const a00 = this.get(0, 0);
      const a01 = this.get(0, 1);
      const a02 = this.get(0, 2);
      const a10 = this.get(1, 0);
      const a11 = this.get(1, 1);
      const a12 = this.get(1, 2);
      const a20 = this.get(2, 0);
      const a21 = this.get(2, 1);
      const a22 = this.get(2, 2);
      const b00 = other.get(0, 0);
      const b01 = other.get(0, 1);
      const b02 = other.get(0, 2);
      const b10 = other.get(1, 0);
      const b11 = other.get(1, 1);
      const b12 = other.get(1, 2);
      const b20 = other.get(2, 0);
      const b21 = other.get(2, 1);
      const b22 = other.get(2, 2);
      const m1 = (a00 + a01 + a02 - a10 - a11 - a21 - a22) * b11;
      const m2 = (a00 - a10) * (-b01 + b11);
      const m3 = a11 * (-b00 + b01 + b10 - b11 - b12 - b20 + b22);
      const m4 = (-a00 + a10 + a11) * (b00 - b01 + b11);
      const m5 = (a10 + a11) * (-b00 + b01);
      const m6 = a00 * b00;
      const m7 = (-a00 + a20 + a21) * (b00 - b02 + b12);
      const m8 = (-a00 + a20) * (b02 - b12);
      const m9 = (a20 + a21) * (-b00 + b02);
      const m10 = (a00 + a01 + a02 - a11 - a12 - a20 - a21) * b12;
      const m11 = a21 * (-b00 + b02 + b10 - b11 - b12 - b20 + b21);
      const m12 = (-a02 + a21 + a22) * (b11 + b20 - b21);
      const m13 = (a02 - a22) * (b11 - b21);
      const m14 = a02 * b20;
      const m15 = (a21 + a22) * (-b20 + b21);
      const m16 = (-a02 + a11 + a12) * (b12 + b20 - b22);
      const m17 = (a02 - a12) * (b12 - b22);
      const m18 = (a11 + a12) * (-b20 + b22);
      const m19 = a01 * b10;
      const m20 = a12 * b21;
      const m21 = a10 * b02;
      const m22 = a20 * b01;
      const m23 = a22 * b22;
      const c00 = m6 + m14 + m19;
      const c01 = m1 + m4 + m5 + m6 + m12 + m14 + m15;
      const c02 = m6 + m7 + m9 + m10 + m14 + m16 + m18;
      const c10 = m2 + m3 + m4 + m6 + m14 + m16 + m17;
      const c11 = m2 + m4 + m5 + m6 + m20;
      const c12 = m14 + m16 + m17 + m18 + m21;
      const c20 = m6 + m7 + m8 + m11 + m12 + m13 + m14;
      const c21 = m12 + m13 + m14 + m15 + m22;
      const c22 = m6 + m7 + m8 + m9 + m23;
      result.set(0, 0, c00);
      result.set(0, 1, c01);
      result.set(0, 2, c02);
      result.set(1, 0, c10);
      result.set(1, 1, c11);
      result.set(1, 2, c12);
      result.set(2, 0, c20);
      result.set(2, 1, c21);
      result.set(2, 2, c22);
      return result;
    }
    mmulStrassen(y) {
      y = Matrix$3.checkMatrix(y);
      let x = this.clone();
      let r1 = x.rows;
      let c1 = x.columns;
      let r2 = y.rows;
      let c2 = y.columns;
      if (c1 !== r2) {
        // eslint-disable-next-line no-console
        console.warn(`Multiplying ${r1} x ${c1} and ${r2} x ${c2} matrix: dimensions do not match.`);
      }

      // Put a matrix into the top left of a matrix of zeros.
      // `rows` and `cols` are the dimensions of the output matrix.
      function embed(mat, rows, cols) {
        let r = mat.rows;
        let c = mat.columns;
        if (r === rows && c === cols) {
          return mat;
        } else {
          let resultat = AbstractMatrix.zeros(rows, cols);
          resultat = resultat.setSubMatrix(mat, 0, 0);
          return resultat;
        }
      }

      // Make sure both matrices are the same size.
      // This is exclusively for simplicity:
      // this algorithm can be implemented with matrices of different sizes.

      let r = Math.max(r1, r2);
      let c = Math.max(c1, c2);
      x = embed(x, r, c);
      y = embed(y, r, c);

      // Our recursive multiplication function.
      function blockMult(a, b, rows, cols) {
        // For small matrices, resort to naive multiplication.
        if (rows <= 512 || cols <= 512) {
          return a.mmul(b); // a is equivalent to this
        }

        // Apply dynamic padding.
        if (rows % 2 === 1 && cols % 2 === 1) {
          a = embed(a, rows + 1, cols + 1);
          b = embed(b, rows + 1, cols + 1);
        } else if (rows % 2 === 1) {
          a = embed(a, rows + 1, cols);
          b = embed(b, rows + 1, cols);
        } else if (cols % 2 === 1) {
          a = embed(a, rows, cols + 1);
          b = embed(b, rows, cols + 1);
        }
        let halfRows = parseInt(a.rows / 2, 10);
        let halfCols = parseInt(a.columns / 2, 10);
        // Subdivide input matrices.
        let a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1);
        let b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 1);
        let a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1);
        let b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1);
        let a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1);
        let b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1);
        let a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1);
        let b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1);

        // Compute intermediate values.
        let m1 = blockMult(AbstractMatrix.add(a11, a22), AbstractMatrix.add(b11, b22), halfRows, halfCols);
        let m2 = blockMult(AbstractMatrix.add(a21, a22), b11, halfRows, halfCols);
        let m3 = blockMult(a11, AbstractMatrix.sub(b12, b22), halfRows, halfCols);
        let m4 = blockMult(a22, AbstractMatrix.sub(b21, b11), halfRows, halfCols);
        let m5 = blockMult(AbstractMatrix.add(a11, a12), b22, halfRows, halfCols);
        let m6 = blockMult(AbstractMatrix.sub(a21, a11), AbstractMatrix.add(b11, b12), halfRows, halfCols);
        let m7 = blockMult(AbstractMatrix.sub(a12, a22), AbstractMatrix.add(b21, b22), halfRows, halfCols);

        // Combine intermediate values into the output.
        let c11 = AbstractMatrix.add(m1, m4);
        c11.sub(m5);
        c11.add(m7);
        let c12 = AbstractMatrix.add(m3, m5);
        let c21 = AbstractMatrix.add(m2, m4);
        let c22 = AbstractMatrix.sub(m1, m2);
        c22.add(m3);
        c22.add(m6);

        // Crop output to the desired size (undo dynamic padding).
        let result = AbstractMatrix.zeros(2 * c11.rows, 2 * c11.columns);
        result = result.setSubMatrix(c11, 0, 0);
        result = result.setSubMatrix(c12, c11.rows, 0);
        result = result.setSubMatrix(c21, 0, c11.columns);
        result = result.setSubMatrix(c22, c11.rows, c11.columns);
        return result.subMatrix(0, rows - 1, 0, cols - 1);
      }
      return blockMult(x, y, r, c);
    }
    scaleRows(options = {}) {
      if (typeof options !== 'object') {
        throw new TypeError('options must be an object');
      }
      const {
        min = 0,
        max = 1
      } = options;
      if (!Number.isFinite(min)) throw new TypeError('min must be a number');
      if (!Number.isFinite(max)) throw new TypeError('max must be a number');
      if (min >= max) throw new RangeError('min must be smaller than max');
      let newMatrix = new Matrix$3(this.rows, this.columns);
      for (let i = 0; i < this.rows; i++) {
        const row = this.getRow(i);
        if (row.length > 0) {
          rescale(row, {
            min,
            max,
            output: row
          });
        }
        newMatrix.setRow(i, row);
      }
      return newMatrix;
    }
    scaleColumns(options = {}) {
      if (typeof options !== 'object') {
        throw new TypeError('options must be an object');
      }
      const {
        min = 0,
        max = 1
      } = options;
      if (!Number.isFinite(min)) throw new TypeError('min must be a number');
      if (!Number.isFinite(max)) throw new TypeError('max must be a number');
      if (min >= max) throw new RangeError('min must be smaller than max');
      let newMatrix = new Matrix$3(this.rows, this.columns);
      for (let i = 0; i < this.columns; i++) {
        const column = this.getColumn(i);
        if (column.length) {
          rescale(column, {
            min,
            max,
            output: column
          });
        }
        newMatrix.setColumn(i, column);
      }
      return newMatrix;
    }
    flipRows() {
      const middle = Math.ceil(this.columns / 2);
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < middle; j++) {
          let first = this.get(i, j);
          let last = this.get(i, this.columns - 1 - j);
          this.set(i, j, last);
          this.set(i, this.columns - 1 - j, first);
        }
      }
      return this;
    }
    flipColumns() {
      const middle = Math.ceil(this.rows / 2);
      for (let j = 0; j < this.columns; j++) {
        for (let i = 0; i < middle; i++) {
          let first = this.get(i, j);
          let last = this.get(this.rows - 1 - i, j);
          this.set(i, j, last);
          this.set(this.rows - 1 - i, j, first);
        }
      }
      return this;
    }
    kroneckerProduct(other) {
      other = Matrix$3.checkMatrix(other);
      let m = this.rows;
      let n = this.columns;
      let p = other.rows;
      let q = other.columns;
      let result = new Matrix$3(m * p, n * q);
      for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
          for (let k = 0; k < p; k++) {
            for (let l = 0; l < q; l++) {
              result.set(p * i + k, q * j + l, this.get(i, j) * other.get(k, l));
            }
          }
        }
      }
      return result;
    }
    kroneckerSum(other) {
      other = Matrix$3.checkMatrix(other);
      if (!this.isSquare() || !other.isSquare()) {
        throw new Error('Kronecker Sum needs two Square Matrices');
      }
      let m = this.rows;
      let n = other.rows;
      let AxI = this.kroneckerProduct(Matrix$3.eye(n, n));
      let IxB = Matrix$3.eye(m, m).kroneckerProduct(other);
      return AxI.add(IxB);
    }
    transpose() {
      let result = new Matrix$3(this.columns, this.rows);
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j < this.columns; j++) {
          result.set(j, i, this.get(i, j));
        }
      }
      return result;
    }
    sortRows(compareFunction = compareNumbers) {
      for (let i = 0; i < this.rows; i++) {
        this.setRow(i, this.getRow(i).sort(compareFunction));
      }
      return this;
    }
    sortColumns(compareFunction = compareNumbers) {
      for (let i = 0; i < this.columns; i++) {
        this.setColumn(i, this.getColumn(i).sort(compareFunction));
      }
      return this;
    }
    subMatrix(startRow, endRow, startColumn, endColumn) {
      checkRange(this, startRow, endRow, startColumn, endColumn);
      let newMatrix = new Matrix$3(endRow - startRow + 1, endColumn - startColumn + 1);
      for (let i = startRow; i <= endRow; i++) {
        for (let j = startColumn; j <= endColumn; j++) {
          newMatrix.set(i - startRow, j - startColumn, this.get(i, j));
        }
      }
      return newMatrix;
    }
    subMatrixRow(indices, startColumn, endColumn) {
      if (startColumn === undefined) startColumn = 0;
      if (endColumn === undefined) endColumn = this.columns - 1;
      if (startColumn > endColumn || startColumn < 0 || startColumn >= this.columns || endColumn < 0 || endColumn >= this.columns) {
        throw new RangeError('Argument out of range');
      }
      let newMatrix = new Matrix$3(indices.length, endColumn - startColumn + 1);
      for (let i = 0; i < indices.length; i++) {
        for (let j = startColumn; j <= endColumn; j++) {
          if (indices[i] < 0 || indices[i] >= this.rows) {
            throw new RangeError(`Row index out of range: ${indices[i]}`);
          }
          newMatrix.set(i, j - startColumn, this.get(indices[i], j));
        }
      }
      return newMatrix;
    }
    subMatrixColumn(indices, startRow, endRow) {
      if (startRow === undefined) startRow = 0;
      if (endRow === undefined) endRow = this.rows - 1;
      if (startRow > endRow || startRow < 0 || startRow >= this.rows || endRow < 0 || endRow >= this.rows) {
        throw new RangeError('Argument out of range');
      }
      let newMatrix = new Matrix$3(endRow - startRow + 1, indices.length);
      for (let i = 0; i < indices.length; i++) {
        for (let j = startRow; j <= endRow; j++) {
          if (indices[i] < 0 || indices[i] >= this.columns) {
            throw new RangeError(`Column index out of range: ${indices[i]}`);
          }
          newMatrix.set(j - startRow, i, this.get(j, indices[i]));
        }
      }
      return newMatrix;
    }
    setSubMatrix(matrix, startRow, startColumn) {
      matrix = Matrix$3.checkMatrix(matrix);
      if (matrix.isEmpty()) {
        return this;
      }
      let endRow = startRow + matrix.rows - 1;
      let endColumn = startColumn + matrix.columns - 1;
      checkRange(this, startRow, endRow, startColumn, endColumn);
      for (let i = 0; i < matrix.rows; i++) {
        for (let j = 0; j < matrix.columns; j++) {
          this.set(startRow + i, startColumn + j, matrix.get(i, j));
        }
      }
      return this;
    }
    selection(rowIndices, columnIndices) {
      checkRowIndices(this, rowIndices);
      checkColumnIndices(this, columnIndices);
      let newMatrix = new Matrix$3(rowIndices.length, columnIndices.length);
      for (let i = 0; i < rowIndices.length; i++) {
        let rowIndex = rowIndices[i];
        for (let j = 0; j < columnIndices.length; j++) {
          let columnIndex = columnIndices[j];
          newMatrix.set(i, j, this.get(rowIndex, columnIndex));
        }
      }
      return newMatrix;
    }
    trace() {
      let min = Math.min(this.rows, this.columns);
      let trace = 0;
      for (let i = 0; i < min; i++) {
        trace += this.get(i, i);
      }
      return trace;
    }
    clone() {
      return this.constructor.copy(this, new Matrix$3(this.rows, this.columns));
    }

    /**
     * @template {AbstractMatrix} M
     * @param {AbstractMatrix} from
     * @param {M} to
     * @return {M}
     */
    static copy(from, to) {
      for (const [row, column, value] of from.entries()) {
        to.set(row, column, value);
      }
      return to;
    }
    sum(by) {
      switch (by) {
        case 'row':
          return sumByRow(this);
        case 'column':
          return sumByColumn(this);
        case undefined:
          return sumAll(this);
        default:
          throw new Error(`invalid option: ${by}`);
      }
    }
    product(by) {
      switch (by) {
        case 'row':
          return productByRow(this);
        case 'column':
          return productByColumn(this);
        case undefined:
          return productAll(this);
        default:
          throw new Error(`invalid option: ${by}`);
      }
    }
    mean(by) {
      const sum = this.sum(by);
      switch (by) {
        case 'row':
          {
            for (let i = 0; i < this.rows; i++) {
              sum[i] /= this.columns;
            }
            return sum;
          }
        case 'column':
          {
            for (let i = 0; i < this.columns; i++) {
              sum[i] /= this.rows;
            }
            return sum;
          }
        case undefined:
          return sum / this.size;
        default:
          throw new Error(`invalid option: ${by}`);
      }
    }
    variance(by, options = {}) {
      if (typeof by === 'object') {
        options = by;
        by = undefined;
      }
      if (typeof options !== 'object') {
        throw new TypeError('options must be an object');
      }
      const {
        unbiased = true,
        mean = this.mean(by)
      } = options;
      if (typeof unbiased !== 'boolean') {
        throw new TypeError('unbiased must be a boolean');
      }
      switch (by) {
        case 'row':
          {
            if (!isAnyArray.isAnyArray(mean)) {
              throw new TypeError('mean must be an array');
            }
            return varianceByRow(this, unbiased, mean);
          }
        case 'column':
          {
            if (!isAnyArray.isAnyArray(mean)) {
              throw new TypeError('mean must be an array');
            }
            return varianceByColumn(this, unbiased, mean);
          }
        case undefined:
          {
            if (typeof mean !== 'number') {
              throw new TypeError('mean must be a number');
            }
            return varianceAll(this, unbiased, mean);
          }
        default:
          throw new Error(`invalid option: ${by}`);
      }
    }
    standardDeviation(by, options) {
      if (typeof by === 'object') {
        options = by;
        by = undefined;
      }
      const variance = this.variance(by, options);
      if (by === undefined) {
        return Math.sqrt(variance);
      } else {
        for (let i = 0; i < variance.length; i++) {
          variance[i] = Math.sqrt(variance[i]);
        }
        return variance;
      }
    }
    center(by, options = {}) {
      if (typeof by === 'object') {
        options = by;
        by = undefined;
      }
      if (typeof options !== 'object') {
        throw new TypeError('options must be an object');
      }
      const {
        center = this.mean(by)
      } = options;
      switch (by) {
        case 'row':
          {
            if (!isAnyArray.isAnyArray(center)) {
              throw new TypeError('center must be an array');
            }
            centerByRow(this, center);
            return this;
          }
        case 'column':
          {
            if (!isAnyArray.isAnyArray(center)) {
              throw new TypeError('center must be an array');
            }
            centerByColumn(this, center);
            return this;
          }
        case undefined:
          {
            if (typeof center !== 'number') {
              throw new TypeError('center must be a number');
            }
            centerAll(this, center);
            return this;
          }
        default:
          throw new Error(`invalid option: ${by}`);
      }
    }
    scale(by, options = {}) {
      if (typeof by === 'object') {
        options = by;
        by = undefined;
      }
      if (typeof options !== 'object') {
        throw new TypeError('options must be an object');
      }
      let scale = options.scale;
      switch (by) {
        case 'row':
          {
            if (scale === undefined) {
              scale = getScaleByRow(this);
            } else if (!isAnyArray.isAnyArray(scale)) {
              throw new TypeError('scale must be an array');
            }
            scaleByRow(this, scale);
            return this;
          }
        case 'column':
          {
            if (scale === undefined) {
              scale = getScaleByColumn(this);
            } else if (!isAnyArray.isAnyArray(scale)) {
              throw new TypeError('scale must be an array');
            }
            scaleByColumn(this, scale);
            return this;
          }
        case undefined:
          {
            if (scale === undefined) {
              scale = getScaleAll(this);
            } else if (typeof scale !== 'number') {
              throw new TypeError('scale must be a number');
            }
            scaleAll(this, scale);
            return this;
          }
        default:
          throw new Error(`invalid option: ${by}`);
      }
    }
    toString(options) {
      return inspectMatrixWithOptions(this, options);
    }
    [Symbol.iterator]() {
      return this.entries();
    }

    /**
     * iterator from left to right, from top to bottom
     * yield [row, column, value]
     * @returns {Generator<[number, number, number], void, void>}
     */
    *entries() {
      for (let row = 0; row < this.rows; row++) {
        for (let col = 0; col < this.columns; col++) {
          yield [row, col, this.get(row, col)];
        }
      }
    }

    /**
     * iterator from left to right, from top to bottom
     * yield value
     * @returns {Generator<number, void, void>}
     */
    *values() {
      for (let row = 0; row < this.rows; row++) {
        for (let col = 0; col < this.columns; col++) {
          yield this.get(row, col);
        }
      }
    }
  }
  AbstractMatrix.prototype.klass = 'Matrix';
  if (typeof Symbol !== 'undefined') {
    AbstractMatrix.prototype[Symbol.for('nodejs.util.inspect.custom')] = inspectMatrix;
  }
  function compareNumbers(a, b) {
    return a - b;
  }
  function isArrayOfNumbers(array) {
    return array.every(element => {
      return typeof element === 'number';
    });
  }

  // Synonyms
  AbstractMatrix.random = AbstractMatrix.rand;
  AbstractMatrix.randomInt = AbstractMatrix.randInt;
  AbstractMatrix.diagonal = AbstractMatrix.diag;
  AbstractMatrix.prototype.diagonal = AbstractMatrix.prototype.diag;
  AbstractMatrix.identity = AbstractMatrix.eye;
  AbstractMatrix.prototype.negate = AbstractMatrix.prototype.neg;
  AbstractMatrix.prototype.tensorProduct = AbstractMatrix.prototype.kroneckerProduct;
  let Matrix$3 = class Matrix extends AbstractMatrix {
    /**
     * @type {Float64Array[]}
     */
    data;

    /**
     * Init an empty matrix
     * @param {number} nRows
     * @param {number} nColumns
     */
    #initData(nRows, nColumns) {
      this.data = [];
      if (Number.isInteger(nColumns) && nColumns >= 0) {
        for (let i = 0; i < nRows; i++) {
          this.data.push(new Float64Array(nColumns));
        }
      } else {
        throw new TypeError('nColumns must be a positive integer');
      }
      this.rows = nRows;
      this.columns = nColumns;
    }
    constructor(nRows, nColumns) {
      super();
      if (Matrix.isMatrix(nRows)) {
        this.#initData(nRows.rows, nRows.columns);
        Matrix.copy(nRows, this);
      } else if (Number.isInteger(nRows) && nRows >= 0) {
        this.#initData(nRows, nColumns);
      } else if (isAnyArray.isAnyArray(nRows)) {
        // Copy the values from the 2D array
        const arrayData = nRows;
        nRows = arrayData.length;
        nColumns = nRows ? arrayData[0].length : 0;
        if (typeof nColumns !== 'number') {
          throw new TypeError('Data must be a 2D array with at least one element');
        }
        this.data = [];
        for (let i = 0; i < nRows; i++) {
          if (arrayData[i].length !== nColumns) {
            throw new RangeError('Inconsistent array dimensions');
          }
          if (!isArrayOfNumbers(arrayData[i])) {
            throw new TypeError('Input data contains non-numeric values');
          }
          this.data.push(Float64Array.from(arrayData[i]));
        }
        this.rows = nRows;
        this.columns = nColumns;
      } else {
        throw new TypeError('First argument must be a positive number or an array');
      }
    }
    set(rowIndex, columnIndex, value) {
      this.data[rowIndex][columnIndex] = value;
      return this;
    }
    get(rowIndex, columnIndex) {
      return this.data[rowIndex][columnIndex];
    }
    removeRow(index) {
      checkRowIndex(this, index);
      this.data.splice(index, 1);
      this.rows -= 1;
      return this;
    }
    addRow(index, array) {
      if (array === undefined) {
        array = index;
        index = this.rows;
      }
      checkRowIndex(this, index, true);
      array = Float64Array.from(checkRowVector(this, array));
      this.data.splice(index, 0, array);
      this.rows += 1;
      return this;
    }
    removeColumn(index) {
      checkColumnIndex(this, index);
      for (let i = 0; i < this.rows; i++) {
        const newRow = new Float64Array(this.columns - 1);
        for (let j = 0; j < index; j++) {
          newRow[j] = this.data[i][j];
        }
        for (let j = index + 1; j < this.columns; j++) {
          newRow[j - 1] = this.data[i][j];
        }
        this.data[i] = newRow;
      }
      this.columns -= 1;
      return this;
    }
    addColumn(index, array) {
      if (typeof array === 'undefined') {
        array = index;
        index = this.columns;
      }
      checkColumnIndex(this, index, true);
      array = checkColumnVector(this, array);
      for (let i = 0; i < this.rows; i++) {
        const newRow = new Float64Array(this.columns + 1);
        let j = 0;
        for (; j < index; j++) {
          newRow[j] = this.data[i][j];
        }
        newRow[j++] = array[i];
        for (; j < this.columns + 1; j++) {
          newRow[j] = this.data[i][j - 1];
        }
        this.data[i] = newRow;
      }
      this.columns += 1;
      return this;
    }
  };
  installMathOperations(AbstractMatrix, Matrix$3);

  /**
   * @typedef {0 | 1 | number | boolean} Mask
   */

  class SymmetricMatrix extends AbstractMatrix {
    /** @type {Matrix} */
    #matrix;
    get size() {
      return this.#matrix.size;
    }
    get rows() {
      return this.#matrix.rows;
    }
    get columns() {
      return this.#matrix.columns;
    }
    get diagonalSize() {
      return this.rows;
    }

    /**
     * not the same as matrix.isSymmetric()
     * Here is to check if it's instanceof SymmetricMatrix without bundling issues
     *
     * @param value
     * @returns {boolean}
     */
    static isSymmetricMatrix(value) {
      return Matrix$3.isMatrix(value) && value.klassType === 'SymmetricMatrix';
    }

    /**
     * @param diagonalSize
     * @return {SymmetricMatrix}
     */
    static zeros(diagonalSize) {
      return new this(diagonalSize);
    }

    /**
     * @param diagonalSize
     * @return {SymmetricMatrix}
     */
    static ones(diagonalSize) {
      return new this(diagonalSize).fill(1);
    }

    /**
     * @param {number | AbstractMatrix | ArrayLike<ArrayLike<number>>} diagonalSize
     * @return {this}
     */
    constructor(diagonalSize) {
      super();
      if (Matrix$3.isMatrix(diagonalSize)) {
        if (!diagonalSize.isSymmetric()) {
          throw new TypeError('not symmetric data');
        }
        this.#matrix = Matrix$3.copy(diagonalSize, new Matrix$3(diagonalSize.rows, diagonalSize.rows));
      } else if (Number.isInteger(diagonalSize) && diagonalSize >= 0) {
        this.#matrix = new Matrix$3(diagonalSize, diagonalSize);
      } else {
        this.#matrix = new Matrix$3(diagonalSize);
        if (!this.isSymmetric()) {
          throw new TypeError('not symmetric data');
        }
      }
    }
    clone() {
      const matrix = new SymmetricMatrix(this.diagonalSize);
      for (const [row, col, value] of this.upperRightEntries()) {
        matrix.set(row, col, value);
      }
      return matrix;
    }
    toMatrix() {
      return new Matrix$3(this);
    }
    get(rowIndex, columnIndex) {
      return this.#matrix.get(rowIndex, columnIndex);
    }
    set(rowIndex, columnIndex, value) {
      // symmetric set
      this.#matrix.set(rowIndex, columnIndex, value);
      this.#matrix.set(columnIndex, rowIndex, value);
      return this;
    }
    removeCross(index) {
      // symmetric remove side
      this.#matrix.removeRow(index);
      this.#matrix.removeColumn(index);
      return this;
    }
    addCross(index, array) {
      if (array === undefined) {
        array = index;
        index = this.diagonalSize;
      }
      const row = array.slice();
      row.splice(index, 1);
      this.#matrix.addRow(index, row);
      this.#matrix.addColumn(index, array);
      return this;
    }

    /**
     * @param {Mask[]} mask
     */
    applyMask(mask) {
      if (mask.length !== this.diagonalSize) {
        throw new RangeError('Mask size do not match with matrix size');
      }

      // prepare sides to remove from matrix from mask
      /** @type {number[]} */
      const sidesToRemove = [];
      for (const [index, passthroughs] of mask.entries()) {
        if (passthroughs) continue;
        sidesToRemove.push(index);
      }
      // to remove from highest to lowest for no mutation shifting
      sidesToRemove.reverse();

      // remove sides
      for (const sideIndex of sidesToRemove) {
        this.removeCross(sideIndex);
      }
      return this;
    }

    /**
     * Compact format upper-right corner of matrix
     * iterate from left to right, from top to bottom.
     *
     * ```
     *   A B C D
     * A 1 2 3 4
     * B 2 5 6 7
     * C 3 6 8 9
     * D 4 7 9 10
     * ```
     *
     * will return compact 1D array `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]`
     *
     * length is S(i=0, n=sideSize) => 10 for a 4 sideSized matrix
     *
     * @returns {number[]}
     */
    toCompact() {
      const {
        diagonalSize
      } = this;

      /** @type {number[]} */
      const compact = new Array(diagonalSize * (diagonalSize + 1) / 2);
      for (let col = 0, row = 0, index = 0; index < compact.length; index++) {
        compact[index] = this.get(row, col);
        if (++col >= diagonalSize) col = ++row;
      }
      return compact;
    }

    /**
     * @param {number[]} compact
     * @return {SymmetricMatrix}
     */
    static fromCompact(compact) {
      const compactSize = compact.length;
      // compactSize = (sideSize * (sideSize + 1)) / 2
      // https://mathsolver.microsoft.com/fr/solve-problem/y%20%3D%20%20x%20%60cdot%20%20%20%60frac%7B%20%20%60left(%20x%2B1%20%20%60right)%20%20%20%20%7D%7B%202%20%20%7D
      // sideSize = (Sqrt(8 × compactSize + 1) - 1) / 2
      const diagonalSize = (Math.sqrt(8 * compactSize + 1) - 1) / 2;
      if (!Number.isInteger(diagonalSize)) {
        throw new TypeError(`This array is not a compact representation of a Symmetric Matrix, ${JSON.stringify(compact)}`);
      }
      const matrix = new SymmetricMatrix(diagonalSize);
      for (let col = 0, row = 0, index = 0; index < compactSize; index++) {
        matrix.set(col, row, compact[index]);
        if (++col >= diagonalSize) col = ++row;
      }
      return matrix;
    }

    /**
     * half iterator upper-right-corner from left to right, from top to bottom
     * yield [row, column, value]
     *
     * @returns {Generator<[number, number, number], void, void>}
     */
    *upperRightEntries() {
      for (let row = 0, col = 0; row < this.diagonalSize; void 0) {
        const value = this.get(row, col);
        yield [row, col, value];

        // at the end of row, move cursor to next row at diagonal position
        if (++col >= this.diagonalSize) col = ++row;
      }
    }

    /**
     * half iterator upper-right-corner from left to right, from top to bottom
     * yield value
     *
     * @returns {Generator<[number, number, number], void, void>}
     */
    *upperRightValues() {
      for (let row = 0, col = 0; row < this.diagonalSize; void 0) {
        const value = this.get(row, col);
        yield value;

        // at the end of row, move cursor to next row at diagonal position
        if (++col >= this.diagonalSize) col = ++row;
      }
    }
  }
  SymmetricMatrix.prototype.klassType = 'SymmetricMatrix';
  class DistanceMatrix extends SymmetricMatrix {
    /**
     * not the same as matrix.isSymmetric()
     * Here is to check if it's instanceof SymmetricMatrix without bundling issues
     *
     * @param value
     * @returns {boolean}
     */
    static isDistanceMatrix(value) {
      return SymmetricMatrix.isSymmetricMatrix(value) && value.klassSubType === 'DistanceMatrix';
    }
    constructor(sideSize) {
      super(sideSize);
      if (!this.isDistance()) {
        throw new TypeError('Provided arguments do no produce a distance matrix');
      }
    }
    set(rowIndex, columnIndex, value) {
      // distance matrix diagonal is 0
      if (rowIndex === columnIndex) value = 0;
      return super.set(rowIndex, columnIndex, value);
    }
    addCross(index, array) {
      if (array === undefined) {
        array = index;
        index = this.diagonalSize;
      }

      // ensure distance
      array = array.slice();
      array[index] = 0;
      return super.addCross(index, array);
    }
    toSymmetricMatrix() {
      return new SymmetricMatrix(this);
    }
    clone() {
      const matrix = new DistanceMatrix(this.diagonalSize);
      for (const [row, col, value] of this.upperRightEntries()) {
        if (row === col) continue;
        matrix.set(row, col, value);
      }
      return matrix;
    }

    /**
     * Compact format upper-right corner of matrix
     * no diagonal (only zeros)
     * iterable from left to right, from top to bottom.
     *
     * ```
     *   A B C D
     * A 0 1 2 3
     * B 1 0 4 5
     * C 2 4 0 6
     * D 3 5 6 0
     * ```
     *
     * will return compact 1D array `[1, 2, 3, 4, 5, 6]`
     *
     * length is S(i=0, n=sideSize-1) => 6 for a 4 side sized matrix
     *
     * @returns {number[]}
     */
    toCompact() {
      const {
        diagonalSize
      } = this;
      const compactLength = (diagonalSize - 1) * diagonalSize / 2;

      /** @type {number[]} */
      const compact = new Array(compactLength);
      for (let col = 1, row = 0, index = 0; index < compact.length; index++) {
        compact[index] = this.get(row, col);
        if (++col >= diagonalSize) col = ++row + 1;
      }
      return compact;
    }

    /**
     * @param {number[]} compact
     */
    static fromCompact(compact) {
      const compactSize = compact.length;
      if (compactSize === 0) {
        return new this(0);
      }

      // compactSize in Natural integer range ]0;∞]
      // compactSize = (sideSize * (sideSize - 1)) / 2
      // sideSize = (Sqrt(8 × compactSize + 1) + 1) / 2
      const diagonalSize = (Math.sqrt(8 * compactSize + 1) + 1) / 2;
      if (!Number.isInteger(diagonalSize)) {
        throw new TypeError(`This array is not a compact representation of a DistanceMatrix, ${JSON.stringify(compact)}`);
      }
      const matrix = new this(diagonalSize);
      for (let col = 1, row = 0, index = 0; index < compactSize; index++) {
        matrix.set(col, row, compact[index]);
        if (++col >= diagonalSize) col = ++row + 1;
      }
      return matrix;
    }
  }
  DistanceMatrix.prototype.klassSubType = 'DistanceMatrix';
  class BaseView extends AbstractMatrix {
    constructor(matrix, rows, columns) {
      super();
      this.matrix = matrix;
      this.rows = rows;
      this.columns = columns;
    }
  }
  class MatrixColumnView extends BaseView {
    constructor(matrix, column) {
      checkColumnIndex(matrix, column);
      super(matrix, matrix.rows, 1);
      this.column = column;
    }
    set(rowIndex, columnIndex, value) {
      this.matrix.set(rowIndex, this.column, value);
      return this;
    }
    get(rowIndex) {
      return this.matrix.get(rowIndex, this.column);
    }
  }
  class MatrixColumnSelectionView extends BaseView {
    constructor(matrix, columnIndices) {
      checkColumnIndices(matrix, columnIndices);
      super(matrix, matrix.rows, columnIndices.length);
      this.columnIndices = columnIndices;
    }
    set(rowIndex, columnIndex, value) {
      this.matrix.set(rowIndex, this.columnIndices[columnIndex], value);
      return this;
    }
    get(rowIndex, columnIndex) {
      return this.matrix.get(rowIndex, this.columnIndices[columnIndex]);
    }
  }
  class MatrixFlipColumnView extends BaseView {
    constructor(matrix) {
      super(matrix, matrix.rows, matrix.columns);
    }
    set(rowIndex, columnIndex, value) {
      this.matrix.set(rowIndex, this.columns - columnIndex - 1, value);
      return this;
    }
    get(rowIndex, columnIndex) {
      return this.matrix.get(rowIndex, this.columns - columnIndex - 1);
    }
  }
  class MatrixFlipRowView extends BaseView {
    constructor(matrix) {
      super(matrix, matrix.rows, matrix.columns);
    }
    set(rowIndex, columnIndex, value) {
      this.matrix.set(this.rows - rowIndex - 1, columnIndex, value);
      return this;
    }
    get(rowIndex, columnIndex) {
      return this.matrix.get(this.rows - rowIndex - 1, columnIndex);
    }
  }
  class MatrixRowView extends BaseView {
    constructor(matrix, row) {
      checkRowIndex(matrix, row);
      super(matrix, 1, matrix.columns);
      this.row = row;
    }
    set(rowIndex, columnIndex, value) {
      this.matrix.set(this.row, columnIndex, value);
      return this;
    }
    get(rowIndex, columnIndex) {
      return this.matrix.get(this.row, columnIndex);
    }
  }
  class MatrixRowSelectionView extends BaseView {
    constructor(matrix, rowIndices) {
      checkRowIndices(matrix, rowIndices);
      super(matrix, rowIndices.length, matrix.columns);
      this.rowIndices = rowIndices;
    }
    set(rowIndex, columnIndex, value) {
      this.matrix.set(this.rowIndices[rowIndex], columnIndex, value);
      return this;
    }
    get(rowIndex, columnIndex) {
      return this.matrix.get(this.rowIndices[rowIndex], columnIndex);
    }
  }
  class MatrixSelectionView extends BaseView {
    constructor(matrix, rowIndices, columnIndices) {
      checkRowIndices(matrix, rowIndices);
      checkColumnIndices(matrix, columnIndices);
      super(matrix, rowIndices.length, columnIndices.length);
      this.rowIndices = rowIndices;
      this.columnIndices = columnIndices;
    }
    set(rowIndex, columnIndex, value) {
      this.matrix.set(this.rowIndices[rowIndex], this.columnIndices[columnIndex], value);
      return this;
    }
    get(rowIndex, columnIndex) {
      return this.matrix.get(this.rowIndices[rowIndex], this.columnIndices[columnIndex]);
    }
  }
  class MatrixSubView extends BaseView {
    constructor(matrix, startRow, endRow, startColumn, endColumn) {
      checkRange(matrix, startRow, endRow, startColumn, endColumn);
      super(matrix, endRow - startRow + 1, endColumn - startColumn + 1);
      this.startRow = startRow;
      this.startColumn = startColumn;
    }
    set(rowIndex, columnIndex, value) {
      this.matrix.set(this.startRow + rowIndex, this.startColumn + columnIndex, value);
      return this;
    }
    get(rowIndex, columnIndex) {
      return this.matrix.get(this.startRow + rowIndex, this.startColumn + columnIndex);
    }
  }
  let MatrixTransposeView$1 = class MatrixTransposeView extends BaseView {
    constructor(matrix) {
      super(matrix, matrix.columns, matrix.rows);
    }
    set(rowIndex, columnIndex, value) {
      this.matrix.set(columnIndex, rowIndex, value);
      return this;
    }
    get(rowIndex, columnIndex) {
      return this.matrix.get(columnIndex, rowIndex);
    }
  };
  class WrapperMatrix1D extends AbstractMatrix {
    constructor(data, options = {}) {
      const {
        rows = 1
      } = options;
      if (data.length % rows !== 0) {
        throw new Error('the data length is not divisible by the number of rows');
      }
      super();
      this.rows = rows;
      this.columns = data.length / rows;
      this.data = data;
    }
    set(rowIndex, columnIndex, value) {
      let index = this._calculateIndex(rowIndex, columnIndex);
      this.data[index] = value;
      return this;
    }
    get(rowIndex, columnIndex) {
      let index = this._calculateIndex(rowIndex, columnIndex);
      return this.data[index];
    }
    _calculateIndex(row, column) {
      return row * this.columns + column;
    }
  }
  class WrapperMatrix2D extends AbstractMatrix {
    constructor(data) {
      super();
      this.data = data;
      this.rows = data.length;
      this.columns = data[0].length;
    }
    set(rowIndex, columnIndex, value) {
      this.data[rowIndex][columnIndex] = value;
      return this;
    }
    get(rowIndex, columnIndex) {
      return this.data[rowIndex][columnIndex];
    }
  }
  function wrap(array, options) {
    if (isAnyArray.isAnyArray(array)) {
      if (array[0] && isAnyArray.isAnyArray(array[0])) {
        return new WrapperMatrix2D(array);
      } else {
        return new WrapperMatrix1D(array, options);
      }
    } else {
      throw new Error('the argument is not an array');
    }
  }
  class LuDecomposition {
    constructor(matrix) {
      matrix = WrapperMatrix2D.checkMatrix(matrix);
      let lu = matrix.clone();
      let rows = lu.rows;
      let columns = lu.columns;
      let pivotVector = new Float64Array(rows);
      let pivotSign = 1;
      let i, j, k, p, s, t, v;
      let LUcolj, kmax;
      for (i = 0; i < rows; i++) {
        pivotVector[i] = i;
      }
      LUcolj = new Float64Array(rows);
      for (j = 0; j < columns; j++) {
        for (i = 0; i < rows; i++) {
          LUcolj[i] = lu.get(i, j);
        }
        for (i = 0; i < rows; i++) {
          kmax = Math.min(i, j);
          s = 0;
          for (k = 0; k < kmax; k++) {
            s += lu.get(i, k) * LUcolj[k];
          }
          LUcolj[i] -= s;
          lu.set(i, j, LUcolj[i]);
        }
        p = j;
        for (i = j + 1; i < rows; i++) {
          if (Math.abs(LUcolj[i]) > Math.abs(LUcolj[p])) {
            p = i;
          }
        }
        if (p !== j) {
          for (k = 0; k < columns; k++) {
            t = lu.get(p, k);
            lu.set(p, k, lu.get(j, k));
            lu.set(j, k, t);
          }
          v = pivotVector[p];
          pivotVector[p] = pivotVector[j];
          pivotVector[j] = v;
          pivotSign = -pivotSign;
        }
        if (j < rows && lu.get(j, j) !== 0) {
          for (i = j + 1; i < rows; i++) {
            lu.set(i, j, lu.get(i, j) / lu.get(j, j));
          }
        }
      }
      this.LU = lu;
      this.pivotVector = pivotVector;
      this.pivotSign = pivotSign;
    }
    isSingular() {
      let data = this.LU;
      let col = data.columns;
      for (let j = 0; j < col; j++) {
        if (data.get(j, j) === 0) {
          return true;
        }
      }
      return false;
    }
    solve(value) {
      value = Matrix$3.checkMatrix(value);
      let lu = this.LU;
      let rows = lu.rows;
      if (rows !== value.rows) {
        throw new Error('Invalid matrix dimensions');
      }
      if (this.isSingular()) {
        throw new Error('LU matrix is singular');
      }
      let count = value.columns;
      let X = value.subMatrixRow(this.pivotVector, 0, count - 1);
      let columns = lu.columns;
      let i, j, k;
      for (k = 0; k < columns; k++) {
        for (i = k + 1; i < columns; i++) {
          for (j = 0; j < count; j++) {
            X.set(i, j, X.get(i, j) - X.get(k, j) * lu.get(i, k));
          }
        }
      }
      for (k = columns - 1; k >= 0; k--) {
        for (j = 0; j < count; j++) {
          X.set(k, j, X.get(k, j) / lu.get(k, k));
        }
        for (i = 0; i < k; i++) {
          for (j = 0; j < count; j++) {
            X.set(i, j, X.get(i, j) - X.get(k, j) * lu.get(i, k));
          }
        }
      }
      return X;
    }
    get determinant() {
      let data = this.LU;
      if (!data.isSquare()) {
        throw new Error('Matrix must be square');
      }
      let determinant = this.pivotSign;
      let col = data.columns;
      for (let j = 0; j < col; j++) {
        determinant *= data.get(j, j);
      }
      return determinant;
    }
    get lowerTriangularMatrix() {
      let data = this.LU;
      let rows = data.rows;
      let columns = data.columns;
      let X = new Matrix$3(rows, columns);
      for (let i = 0; i < rows; i++) {
        for (let j = 0; j < columns; j++) {
          if (i > j) {
            X.set(i, j, data.get(i, j));
          } else if (i === j) {
            X.set(i, j, 1);
          } else {
            X.set(i, j, 0);
          }
        }
      }
      return X;
    }
    get upperTriangularMatrix() {
      let data = this.LU;
      let rows = data.rows;
      let columns = data.columns;
      let X = new Matrix$3(rows, columns);
      for (let i = 0; i < rows; i++) {
        for (let j = 0; j < columns; j++) {
          if (i <= j) {
            X.set(i, j, data.get(i, j));
          } else {
            X.set(i, j, 0);
          }
        }
      }
      return X;
    }
    get pivotPermutationVector() {
      return Array.from(this.pivotVector);
    }
  }
  function hypotenuse$1(a, b) {
    let r = 0;
    if (Math.abs(a) > Math.abs(b)) {
      r = b / a;
      return Math.abs(a) * Math.sqrt(1 + r * r);
    }
    if (b !== 0) {
      r = a / b;
      return Math.abs(b) * Math.sqrt(1 + r * r);
    }
    return 0;
  }
  class QrDecomposition {
    constructor(value) {
      value = WrapperMatrix2D.checkMatrix(value);
      let qr = value.clone();
      let m = value.rows;
      let n = value.columns;
      let rdiag = new Float64Array(n);
      let i, j, k, s;
      for (k = 0; k < n; k++) {
        let nrm = 0;
        for (i = k; i < m; i++) {
          nrm = hypotenuse$1(nrm, qr.get(i, k));
        }
        if (nrm !== 0) {
          if (qr.get(k, k) < 0) {
            nrm = -nrm;
          }
          for (i = k; i < m; i++) {
            qr.set(i, k, qr.get(i, k) / nrm);
          }
          qr.set(k, k, qr.get(k, k) + 1);
          for (j = k + 1; j < n; j++) {
            s = 0;
            for (i = k; i < m; i++) {
              s += qr.get(i, k) * qr.get(i, j);
            }
            s = -s / qr.get(k, k);
            for (i = k; i < m; i++) {
              qr.set(i, j, qr.get(i, j) + s * qr.get(i, k));
            }
          }
        }
        rdiag[k] = -nrm;
      }
      this.QR = qr;
      this.Rdiag = rdiag;
    }
    solve(value) {
      value = Matrix$3.checkMatrix(value);
      let qr = this.QR;
      let m = qr.rows;
      if (value.rows !== m) {
        throw new Error('Matrix row dimensions must agree');
      }
      if (!this.isFullRank()) {
        throw new Error('Matrix is rank deficient');
      }
      let count = value.columns;
      let X = value.clone();
      let n = qr.columns;
      let i, j, k, s;
      for (k = 0; k < n; k++) {
        for (j = 0; j < count; j++) {
          s = 0;
          for (i = k; i < m; i++) {
            s += qr.get(i, k) * X.get(i, j);
          }
          s = -s / qr.get(k, k);
          for (i = k; i < m; i++) {
            X.set(i, j, X.get(i, j) + s * qr.get(i, k));
          }
        }
      }
      for (k = n - 1; k >= 0; k--) {
        for (j = 0; j < count; j++) {
          X.set(k, j, X.get(k, j) / this.Rdiag[k]);
        }
        for (i = 0; i < k; i++) {
          for (j = 0; j < count; j++) {
            X.set(i, j, X.get(i, j) - X.get(k, j) * qr.get(i, k));
          }
        }
      }
      return X.subMatrix(0, n - 1, 0, count - 1);
    }
    isFullRank() {
      let columns = this.QR.columns;
      for (let i = 0; i < columns; i++) {
        if (this.Rdiag[i] === 0) {
          return false;
        }
      }
      return true;
    }
    get upperTriangularMatrix() {
      let qr = this.QR;
      let n = qr.columns;
      let X = new Matrix$3(n, n);
      let i, j;
      for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
          if (i < j) {
            X.set(i, j, qr.get(i, j));
          } else if (i === j) {
            X.set(i, j, this.Rdiag[i]);
          } else {
            X.set(i, j, 0);
          }
        }
      }
      return X;
    }
    get orthogonalMatrix() {
      let qr = this.QR;
      let rows = qr.rows;
      let columns = qr.columns;
      let X = new Matrix$3(rows, columns);
      let i, j, k, s;
      for (k = columns - 1; k >= 0; k--) {
        for (i = 0; i < rows; i++) {
          X.set(i, k, 0);
        }
        X.set(k, k, 1);
        for (j = k; j < columns; j++) {
          if (qr.get(k, k) !== 0) {
            s = 0;
            for (i = k; i < rows; i++) {
              s += qr.get(i, k) * X.get(i, j);
            }
            s = -s / qr.get(k, k);
            for (i = k; i < rows; i++) {
              X.set(i, j, X.get(i, j) + s * qr.get(i, k));
            }
          }
        }
      }
      return X;
    }
  }
  let SingularValueDecomposition$1 = class SingularValueDecomposition {
    constructor(value, options = {}) {
      value = WrapperMatrix2D.checkMatrix(value);
      if (value.isEmpty()) {
        throw new Error('Matrix must be non-empty');
      }
      let m = value.rows;
      let n = value.columns;
      const {
        computeLeftSingularVectors = true,
        computeRightSingularVectors = true,
        autoTranspose = false
      } = options;
      let wantu = Boolean(computeLeftSingularVectors);
      let wantv = Boolean(computeRightSingularVectors);
      let swapped = false;
      let a;
      if (m < n) {
        if (!autoTranspose) {
          a = value.clone();
          // eslint-disable-next-line no-console
          console.warn('Computing SVD on a matrix with more columns than rows. Consider enabling autoTranspose');
        } else {
          a = value.transpose();
          m = a.rows;
          n = a.columns;
          swapped = true;
          let aux = wantu;
          wantu = wantv;
          wantv = aux;
        }
      } else {
        a = value.clone();
      }
      let nu = Math.min(m, n);
      let ni = Math.min(m + 1, n);
      let s = new Float64Array(ni);
      let U = new Matrix$3(m, nu);
      let V = new Matrix$3(n, n);
      let e = new Float64Array(n);
      let work = new Float64Array(m);
      let si = new Float64Array(ni);
      for (let i = 0; i < ni; i++) si[i] = i;
      let nct = Math.min(m - 1, n);
      let nrt = Math.max(0, Math.min(n - 2, m));
      let mrc = Math.max(nct, nrt);
      for (let k = 0; k < mrc; k++) {
        if (k < nct) {
          s[k] = 0;
          for (let i = k; i < m; i++) {
            s[k] = hypotenuse$1(s[k], a.get(i, k));
          }
          if (s[k] !== 0) {
            if (a.get(k, k) < 0) {
              s[k] = -s[k];
            }
            for (let i = k; i < m; i++) {
              a.set(i, k, a.get(i, k) / s[k]);
            }
            a.set(k, k, a.get(k, k) + 1);
          }
          s[k] = -s[k];
        }
        for (let j = k + 1; j < n; j++) {
          if (k < nct && s[k] !== 0) {
            let t = 0;
            for (let i = k; i < m; i++) {
              t += a.get(i, k) * a.get(i, j);
            }
            t = -t / a.get(k, k);
            for (let i = k; i < m; i++) {
              a.set(i, j, a.get(i, j) + t * a.get(i, k));
            }
          }
          e[j] = a.get(k, j);
        }
        if (wantu && k < nct) {
          for (let i = k; i < m; i++) {
            U.set(i, k, a.get(i, k));
          }
        }
        if (k < nrt) {
          e[k] = 0;
          for (let i = k + 1; i < n; i++) {
            e[k] = hypotenuse$1(e[k], e[i]);
          }
          if (e[k] !== 0) {
            if (e[k + 1] < 0) {
              e[k] = 0 - e[k];
            }
            for (let i = k + 1; i < n; i++) {
              e[i] /= e[k];
            }
            e[k + 1] += 1;
          }
          e[k] = -e[k];
          if (k + 1 < m && e[k] !== 0) {
            for (let i = k + 1; i < m; i++) {
              work[i] = 0;
            }
            for (let i = k + 1; i < m; i++) {
              for (let j = k + 1; j < n; j++) {
                work[i] += e[j] * a.get(i, j);
              }
            }
            for (let j = k + 1; j < n; j++) {
              let t = -e[j] / e[k + 1];
              for (let i = k + 1; i < m; i++) {
                a.set(i, j, a.get(i, j) + t * work[i]);
              }
            }
          }
          if (wantv) {
            for (let i = k + 1; i < n; i++) {
              V.set(i, k, e[i]);
            }
          }
        }
      }
      let p = Math.min(n, m + 1);
      if (nct < n) {
        s[nct] = a.get(nct, nct);
      }
      if (m < p) {
        s[p - 1] = 0;
      }
      if (nrt + 1 < p) {
        e[nrt] = a.get(nrt, p - 1);
      }
      e[p - 1] = 0;
      if (wantu) {
        for (let j = nct; j < nu; j++) {
          for (let i = 0; i < m; i++) {
            U.set(i, j, 0);
          }
          U.set(j, j, 1);
        }
        for (let k = nct - 1; k >= 0; k--) {
          if (s[k] !== 0) {
            for (let j = k + 1; j < nu; j++) {
              let t = 0;
              for (let i = k; i < m; i++) {
                t += U.get(i, k) * U.get(i, j);
              }
              t = -t / U.get(k, k);
              for (let i = k; i < m; i++) {
                U.set(i, j, U.get(i, j) + t * U.get(i, k));
              }
            }
            for (let i = k; i < m; i++) {
              U.set(i, k, -U.get(i, k));
            }
            U.set(k, k, 1 + U.get(k, k));
            for (let i = 0; i < k - 1; i++) {
              U.set(i, k, 0);
            }
          } else {
            for (let i = 0; i < m; i++) {
              U.set(i, k, 0);
            }
            U.set(k, k, 1);
          }
        }
      }
      if (wantv) {
        for (let k = n - 1; k >= 0; k--) {
          if (k < nrt && e[k] !== 0) {
            for (let j = k + 1; j < n; j++) {
              let t = 0;
              for (let i = k + 1; i < n; i++) {
                t += V.get(i, k) * V.get(i, j);
              }
              t = -t / V.get(k + 1, k);
              for (let i = k + 1; i < n; i++) {
                V.set(i, j, V.get(i, j) + t * V.get(i, k));
              }
            }
          }
          for (let i = 0; i < n; i++) {
            V.set(i, k, 0);
          }
          V.set(k, k, 1);
        }
      }
      let pp = p - 1;
      let eps = Number.EPSILON;
      while (p > 0) {
        let k, kase;
        for (k = p - 2; k >= -1; k--) {
          if (k === -1) {
            break;
          }
          const alpha = Number.MIN_VALUE + eps * Math.abs(s[k] + Math.abs(s[k + 1]));
          if (Math.abs(e[k]) <= alpha || Number.isNaN(e[k])) {
            e[k] = 0;
            break;
          }
        }
        if (k === p - 2) {
          kase = 4;
        } else {
          let ks;
          for (ks = p - 1; ks >= k; ks--) {
            if (ks === k) {
              break;
            }
            let t = (ks !== p ? Math.abs(e[ks]) : 0) + (ks !== k + 1 ? Math.abs(e[ks - 1]) : 0);
            if (Math.abs(s[ks]) <= eps * t) {
              s[ks] = 0;
              break;
            }
          }
          if (ks === k) {
            kase = 3;
          } else if (ks === p - 1) {
            kase = 1;
          } else {
            kase = 2;
            k = ks;
          }
        }
        k++;
        switch (kase) {
          case 1:
            {
              let f = e[p - 2];
              e[p - 2] = 0;
              for (let j = p - 2; j >= k; j--) {
                let t = hypotenuse$1(s[j], f);
                let cs = s[j] / t;
                let sn = f / t;
                s[j] = t;
                if (j !== k) {
                  f = -sn * e[j - 1];
                  e[j - 1] = cs * e[j - 1];
                }
                if (wantv) {
                  for (let i = 0; i < n; i++) {
                    t = cs * V.get(i, j) + sn * V.get(i, p - 1);
                    V.set(i, p - 1, -sn * V.get(i, j) + cs * V.get(i, p - 1));
                    V.set(i, j, t);
                  }
                }
              }
              break;
            }
          case 2:
            {
              let f = e[k - 1];
              e[k - 1] = 0;
              for (let j = k; j < p; j++) {
                let t = hypotenuse$1(s[j], f);
                let cs = s[j] / t;
                let sn = f / t;
                s[j] = t;
                f = -sn * e[j];
                e[j] = cs * e[j];
                if (wantu) {
                  for (let i = 0; i < m; i++) {
                    t = cs * U.get(i, j) + sn * U.get(i, k - 1);
                    U.set(i, k - 1, -sn * U.get(i, j) + cs * U.get(i, k - 1));
                    U.set(i, j, t);
                  }
                }
              }
              break;
            }
          case 3:
            {
              const scale = Math.max(Math.abs(s[p - 1]), Math.abs(s[p - 2]), Math.abs(e[p - 2]), Math.abs(s[k]), Math.abs(e[k]));
              const sp = s[p - 1] / scale;
              const spm1 = s[p - 2] / scale;
              const epm1 = e[p - 2] / scale;
              const sk = s[k] / scale;
              const ek = e[k] / scale;
              const b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2;
              const c = sp * epm1 * (sp * epm1);
              let shift = 0;
              if (b !== 0 || c !== 0) {
                if (b < 0) {
                  shift = 0 - Math.sqrt(b * b + c);
                } else {
                  shift = Math.sqrt(b * b + c);
                }
                shift = c / (b + shift);
              }
              let f = (sk + sp) * (sk - sp) + shift;
              let g = sk * ek;
              for (let j = k; j < p - 1; j++) {
                let t = hypotenuse$1(f, g);
                if (t === 0) t = Number.MIN_VALUE;
                let cs = f / t;
                let sn = g / t;
                if (j !== k) {
                  e[j - 1] = t;
                }
                f = cs * s[j] + sn * e[j];
                e[j] = cs * e[j] - sn * s[j];
                g = sn * s[j + 1];
                s[j + 1] = cs * s[j + 1];
                if (wantv) {
                  for (let i = 0; i < n; i++) {
                    t = cs * V.get(i, j) + sn * V.get(i, j + 1);
                    V.set(i, j + 1, -sn * V.get(i, j) + cs * V.get(i, j + 1));
                    V.set(i, j, t);
                  }
                }
                t = hypotenuse$1(f, g);
                if (t === 0) t = Number.MIN_VALUE;
                cs = f / t;
                sn = g / t;
                s[j] = t;
                f = cs * e[j] + sn * s[j + 1];
                s[j + 1] = -sn * e[j] + cs * s[j + 1];
                g = sn * e[j + 1];
                e[j + 1] = cs * e[j + 1];
                if (wantu && j < m - 1) {
                  for (let i = 0; i < m; i++) {
                    t = cs * U.get(i, j) + sn * U.get(i, j + 1);
                    U.set(i, j + 1, -sn * U.get(i, j) + cs * U.get(i, j + 1));
                    U.set(i, j, t);
                  }
                }
              }
              e[p - 2] = f;
              break;
            }
          case 4:
            {
              if (s[k] <= 0) {
                s[k] = s[k] < 0 ? -s[k] : 0;
                if (wantv) {
                  for (let i = 0; i <= pp; i++) {
                    V.set(i, k, -V.get(i, k));
                  }
                }
              }
              while (k < pp) {
                if (s[k] >= s[k + 1]) {
                  break;
                }
                let t = s[k];
                s[k] = s[k + 1];
                s[k + 1] = t;
                if (wantv && k < n - 1) {
                  for (let i = 0; i < n; i++) {
                    t = V.get(i, k + 1);
                    V.set(i, k + 1, V.get(i, k));
                    V.set(i, k, t);
                  }
                }
                if (wantu && k < m - 1) {
                  for (let i = 0; i < m; i++) {
                    t = U.get(i, k + 1);
                    U.set(i, k + 1, U.get(i, k));
                    U.set(i, k, t);
                  }
                }
                k++;
              }
              p--;
              break;
            }
          // no default
        }
      }
      if (swapped) {
        let tmp = V;
        V = U;
        U = tmp;
      }
      this.m = m;
      this.n = n;
      this.s = s;
      this.U = U;
      this.V = V;
    }
    solve(value) {
      let Y = value;
      let e = this.threshold;
      let scols = this.s.length;
      let Ls = Matrix$3.zeros(scols, scols);
      for (let i = 0; i < scols; i++) {
        if (Math.abs(this.s[i]) <= e) {
          Ls.set(i, i, 0);
        } else {
          Ls.set(i, i, 1 / this.s[i]);
        }
      }
      let U = this.U;
      let V = this.rightSingularVectors;
      let VL = V.mmul(Ls);
      let vrows = V.rows;
      let urows = U.rows;
      let VLU = Matrix$3.zeros(vrows, urows);
      for (let i = 0; i < vrows; i++) {
        for (let j = 0; j < urows; j++) {
          let sum = 0;
          for (let k = 0; k < scols; k++) {
            sum += VL.get(i, k) * U.get(j, k);
          }
          VLU.set(i, j, sum);
        }
      }
      return VLU.mmul(Y);
    }
    solveForDiagonal(value) {
      return this.solve(Matrix$3.diag(value));
    }
    inverse() {
      let V = this.V;
      let e = this.threshold;
      let vrows = V.rows;
      let vcols = V.columns;
      let X = new Matrix$3(vrows, this.s.length);
      for (let i = 0; i < vrows; i++) {
        for (let j = 0; j < vcols; j++) {
          if (Math.abs(this.s[j]) > e) {
            X.set(i, j, V.get(i, j) / this.s[j]);
          }
        }
      }
      let U = this.U;
      let urows = U.rows;
      let ucols = U.columns;
      let Y = new Matrix$3(vrows, urows);
      for (let i = 0; i < vrows; i++) {
        for (let j = 0; j < urows; j++) {
          let sum = 0;
          for (let k = 0; k < ucols; k++) {
            sum += X.get(i, k) * U.get(j, k);
          }
          Y.set(i, j, sum);
        }
      }
      return Y;
    }
    get condition() {
      return this.s[0] / this.s[Math.min(this.m, this.n) - 1];
    }
    get norm2() {
      return this.s[0];
    }
    get rank() {
      let tol = Math.max(this.m, this.n) * this.s[0] * Number.EPSILON;
      let r = 0;
      let s = this.s;
      for (let i = 0, ii = s.length; i < ii; i++) {
        if (s[i] > tol) {
          r++;
        }
      }
      return r;
    }
    get diagonal() {
      return Array.from(this.s);
    }
    get threshold() {
      return Number.EPSILON / 2 * Math.max(this.m, this.n) * this.s[0];
    }
    get leftSingularVectors() {
      return this.U;
    }
    get rightSingularVectors() {
      return this.V;
    }
    get diagonalMatrix() {
      return Matrix$3.diag(this.s);
    }
  };
  function inverse$1(matrix, useSVD = false) {
    matrix = WrapperMatrix2D.checkMatrix(matrix);
    if (useSVD) {
      return new SingularValueDecomposition$1(matrix).inverse();
    } else {
      return solve$1(matrix, Matrix$3.eye(matrix.rows));
    }
  }
  function solve$1(leftHandSide, rightHandSide, useSVD = false) {
    leftHandSide = WrapperMatrix2D.checkMatrix(leftHandSide);
    rightHandSide = WrapperMatrix2D.checkMatrix(rightHandSide);
    if (useSVD) {
      return new SingularValueDecomposition$1(leftHandSide).solve(rightHandSide);
    } else {
      return leftHandSide.isSquare() ? new LuDecomposition(leftHandSide).solve(rightHandSide) : new QrDecomposition(leftHandSide).solve(rightHandSide);
    }
  }
  function determinant(matrix) {
    matrix = Matrix$3.checkMatrix(matrix);
    if (matrix.isSquare()) {
      if (matrix.columns === 0) {
        return 1;
      }
      let a, b, c, d;
      if (matrix.columns === 2) {
        // 2 x 2 matrix
        a = matrix.get(0, 0);
        b = matrix.get(0, 1);
        c = matrix.get(1, 0);
        d = matrix.get(1, 1);
        return a * d - b * c;
      } else if (matrix.columns === 3) {
        // 3 x 3 matrix
        let subMatrix0, subMatrix1, subMatrix2;
        subMatrix0 = new MatrixSelectionView(matrix, [1, 2], [1, 2]);
        subMatrix1 = new MatrixSelectionView(matrix, [1, 2], [0, 2]);
        subMatrix2 = new MatrixSelectionView(matrix, [1, 2], [0, 1]);
        a = matrix.get(0, 0);
        b = matrix.get(0, 1);
        c = matrix.get(0, 2);
        return a * determinant(subMatrix0) - b * determinant(subMatrix1) + c * determinant(subMatrix2);
      } else {
        // general purpose determinant using the LU decomposition
        return new LuDecomposition(matrix).determinant;
      }
    } else {
      throw Error('determinant can only be calculated for a square matrix');
    }
  }
  function xrange(n, exception) {
    let range = [];
    for (let i = 0; i < n; i++) {
      if (i !== exception) {
        range.push(i);
      }
    }
    return range;
  }
  function dependenciesOneRow(error, matrix, index, thresholdValue = 10e-10, thresholdError = 10e-10) {
    if (error > thresholdError) {
      return new Array(matrix.rows + 1).fill(0);
    } else {
      let returnArray = matrix.addRow(index, [0]);
      for (let i = 0; i < returnArray.rows; i++) {
        if (Math.abs(returnArray.get(i, 0)) < thresholdValue) {
          returnArray.set(i, 0, 0);
        }
      }
      return returnArray.to1DArray();
    }
  }
  function linearDependencies(matrix, options = {}) {
    const {
      thresholdValue = 10e-10,
      thresholdError = 10e-10
    } = options;
    matrix = Matrix$3.checkMatrix(matrix);
    let n = matrix.rows;
    let results = new Matrix$3(n, n);
    for (let i = 0; i < n; i++) {
      let b = Matrix$3.columnVector(matrix.getRow(i));
      let Abis = matrix.subMatrixRow(xrange(n, i)).transpose();
      let svd = new SingularValueDecomposition$1(Abis);
      let x = svd.solve(b);
      let error = Matrix$3.sub(b, Abis.mmul(x)).abs().max();
      results.setRow(i, dependenciesOneRow(error, x, i, thresholdValue, thresholdError));
    }
    return results;
  }
  function pseudoInverse(matrix, threshold = Number.EPSILON) {
    matrix = Matrix$3.checkMatrix(matrix);
    if (matrix.isEmpty()) {
      // with a zero dimension, the pseudo-inverse is the transpose, since all 0xn and nx0 matrices are singular
      // (0xn)*(nx0)*(0xn) = 0xn
      // (nx0)*(0xn)*(nx0) = nx0
      return matrix.transpose();
    }
    let svdSolution = new SingularValueDecomposition$1(matrix, {
      autoTranspose: true
    });
    let U = svdSolution.leftSingularVectors;
    let V = svdSolution.rightSingularVectors;
    let s = svdSolution.diagonal;
    for (let i = 0; i < s.length; i++) {
      if (Math.abs(s[i]) > threshold) {
        s[i] = 1.0 / s[i];
      } else {
        s[i] = 0.0;
      }
    }
    return V.mmul(Matrix$3.diag(s).mmul(U.transpose()));
  }
  function covariance(xMatrix, yMatrix = xMatrix, options = {}) {
    xMatrix = new Matrix$3(xMatrix);
    let yIsSame = false;
    if (typeof yMatrix === 'object' && !Matrix$3.isMatrix(yMatrix) && !isAnyArray.isAnyArray(yMatrix)) {
      options = yMatrix;
      yMatrix = xMatrix;
      yIsSame = true;
    } else {
      yMatrix = new Matrix$3(yMatrix);
    }
    if (xMatrix.rows !== yMatrix.rows) {
      throw new TypeError('Both matrices must have the same number of rows');
    }
    const {
      center = true
    } = options;
    if (center) {
      xMatrix = xMatrix.center('column');
      if (!yIsSame) {
        yMatrix = yMatrix.center('column');
      }
    }
    const cov = xMatrix.transpose().mmul(yMatrix);
    for (let i = 0; i < cov.rows; i++) {
      for (let j = 0; j < cov.columns; j++) {
        cov.set(i, j, cov.get(i, j) * (1 / (xMatrix.rows - 1)));
      }
    }
    return cov;
  }
  function correlation(xMatrix, yMatrix = xMatrix, options = {}) {
    xMatrix = new Matrix$3(xMatrix);
    let yIsSame = false;
    if (typeof yMatrix === 'object' && !Matrix$3.isMatrix(yMatrix) && !isAnyArray.isAnyArray(yMatrix)) {
      options = yMatrix;
      yMatrix = xMatrix;
      yIsSame = true;
    } else {
      yMatrix = new Matrix$3(yMatrix);
    }
    if (xMatrix.rows !== yMatrix.rows) {
      throw new TypeError('Both matrices must have the same number of rows');
    }
    const {
      center = true,
      scale = true
    } = options;
    if (center) {
      xMatrix.center('column');
      if (!yIsSame) {
        yMatrix.center('column');
      }
    }
    if (scale) {
      xMatrix.scale('column');
      if (!yIsSame) {
        yMatrix.scale('column');
      }
    }
    const sdx = xMatrix.standardDeviation('column', {
      unbiased: true
    });
    const sdy = yIsSame ? sdx : yMatrix.standardDeviation('column', {
      unbiased: true
    });
    const corr = xMatrix.transpose().mmul(yMatrix);
    for (let i = 0; i < corr.rows; i++) {
      for (let j = 0; j < corr.columns; j++) {
        corr.set(i, j, corr.get(i, j) * (1 / (sdx[i] * sdy[j])) * (1 / (xMatrix.rows - 1)));
      }
    }
    return corr;
  }
  class EigenvalueDecomposition {
    constructor(matrix, options = {}) {
      const {
        assumeSymmetric = false
      } = options;
      matrix = WrapperMatrix2D.checkMatrix(matrix);
      if (!matrix.isSquare()) {
        throw new Error('Matrix is not a square matrix');
      }
      if (matrix.isEmpty()) {
        throw new Error('Matrix must be non-empty');
      }
      let n = matrix.columns;
      let V = new Matrix$3(n, n);
      let d = new Float64Array(n);
      let e = new Float64Array(n);
      let value = matrix;
      let i, j;
      let isSymmetric = false;
      if (assumeSymmetric) {
        isSymmetric = true;
      } else {
        isSymmetric = matrix.isSymmetric();
      }
      if (isSymmetric) {
        for (i = 0; i < n; i++) {
          for (j = 0; j < n; j++) {
            V.set(i, j, value.get(i, j));
          }
        }
        tred2(n, e, d, V);
        tql2(n, e, d, V);
      } else {
        let H = new Matrix$3(n, n);
        let ort = new Float64Array(n);
        for (j = 0; j < n; j++) {
          for (i = 0; i < n; i++) {
            H.set(i, j, value.get(i, j));
          }
        }
        orthes(n, H, ort, V);
        hqr2(n, e, d, V, H);
      }
      this.n = n;
      this.e = e;
      this.d = d;
      this.V = V;
    }
    get realEigenvalues() {
      return Array.from(this.d);
    }
    get imaginaryEigenvalues() {
      return Array.from(this.e);
    }
    get eigenvectorMatrix() {
      return this.V;
    }
    get diagonalMatrix() {
      let n = this.n;
      let e = this.e;
      let d = this.d;
      let X = new Matrix$3(n, n);
      let i, j;
      for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
          X.set(i, j, 0);
        }
        X.set(i, i, d[i]);
        if (e[i] > 0) {
          X.set(i, i + 1, e[i]);
        } else if (e[i] < 0) {
          X.set(i, i - 1, e[i]);
        }
      }
      return X;
    }
  }
  function tred2(n, e, d, V) {
    let f, g, h, i, j, k, hh, scale;
    for (j = 0; j < n; j++) {
      d[j] = V.get(n - 1, j);
    }
    for (i = n - 1; i > 0; i--) {
      scale = 0;
      h = 0;
      for (k = 0; k < i; k++) {
        scale = scale + Math.abs(d[k]);
      }
      if (scale === 0) {
        e[i] = d[i - 1];
        for (j = 0; j < i; j++) {
          d[j] = V.get(i - 1, j);
          V.set(i, j, 0);
          V.set(j, i, 0);
        }
      } else {
        for (k = 0; k < i; k++) {
          d[k] /= scale;
          h += d[k] * d[k];
        }
        f = d[i - 1];
        g = Math.sqrt(h);
        if (f > 0) {
          g = -g;
        }
        e[i] = scale * g;
        h = h - f * g;
        d[i - 1] = f - g;
        for (j = 0; j < i; j++) {
          e[j] = 0;
        }
        for (j = 0; j < i; j++) {
          f = d[j];
          V.set(j, i, f);
          g = e[j] + V.get(j, j) * f;
          for (k = j + 1; k <= i - 1; k++) {
            g += V.get(k, j) * d[k];
            e[k] += V.get(k, j) * f;
          }
          e[j] = g;
        }
        f = 0;
        for (j = 0; j < i; j++) {
          e[j] /= h;
          f += e[j] * d[j];
        }
        hh = f / (h + h);
        for (j = 0; j < i; j++) {
          e[j] -= hh * d[j];
        }
        for (j = 0; j < i; j++) {
          f = d[j];
          g = e[j];
          for (k = j; k <= i - 1; k++) {
            V.set(k, j, V.get(k, j) - (f * e[k] + g * d[k]));
          }
          d[j] = V.get(i - 1, j);
          V.set(i, j, 0);
        }
      }
      d[i] = h;
    }
    for (i = 0; i < n - 1; i++) {
      V.set(n - 1, i, V.get(i, i));
      V.set(i, i, 1);
      h = d[i + 1];
      if (h !== 0) {
        for (k = 0; k <= i; k++) {
          d[k] = V.get(k, i + 1) / h;
        }
        for (j = 0; j <= i; j++) {
          g = 0;
          for (k = 0; k <= i; k++) {
            g += V.get(k, i + 1) * V.get(k, j);
          }
          for (k = 0; k <= i; k++) {
            V.set(k, j, V.get(k, j) - g * d[k]);
          }
        }
      }
      for (k = 0; k <= i; k++) {
        V.set(k, i + 1, 0);
      }
    }
    for (j = 0; j < n; j++) {
      d[j] = V.get(n - 1, j);
      V.set(n - 1, j, 0);
    }
    V.set(n - 1, n - 1, 1);
    e[0] = 0;
  }
  function tql2(n, e, d, V) {
    let g, h, i, j, k, l, m, p, r, dl1, c, c2, c3, el1, s, s2;
    for (i = 1; i < n; i++) {
      e[i - 1] = e[i];
    }
    e[n - 1] = 0;
    let f = 0;
    let tst1 = 0;
    let eps = Number.EPSILON;
    for (l = 0; l < n; l++) {
      tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l]));
      m = l;
      while (m < n) {
        if (Math.abs(e[m]) <= eps * tst1) {
          break;
        }
        m++;
      }
      if (m > l) {
        do {
          g = d[l];
          p = (d[l + 1] - g) / (2 * e[l]);
          r = hypotenuse$1(p, 1);
          if (p < 0) {
            r = -r;
          }
          d[l] = e[l] / (p + r);
          d[l + 1] = e[l] * (p + r);
          dl1 = d[l + 1];
          h = g - d[l];
          for (i = l + 2; i < n; i++) {
            d[i] -= h;
          }
          f = f + h;
          p = d[m];
          c = 1;
          c2 = c;
          c3 = c;
          el1 = e[l + 1];
          s = 0;
          s2 = 0;
          for (i = m - 1; i >= l; i--) {
            c3 = c2;
            c2 = c;
            s2 = s;
            g = c * e[i];
            h = c * p;
            r = hypotenuse$1(p, e[i]);
            e[i + 1] = s * r;
            s = e[i] / r;
            c = p / r;
            p = c * d[i] - s * g;
            d[i + 1] = h + s * (c * g + s * d[i]);
            for (k = 0; k < n; k++) {
              h = V.get(k, i + 1);
              V.set(k, i + 1, s * V.get(k, i) + c * h);
              V.set(k, i, c * V.get(k, i) - s * h);
            }
          }
          p = -s * s2 * c3 * el1 * e[l] / dl1;
          e[l] = s * p;
          d[l] = c * p;
        } while (Math.abs(e[l]) > eps * tst1);
      }
      d[l] = d[l] + f;
      e[l] = 0;
    }
    for (i = 0; i < n - 1; i++) {
      k = i;
      p = d[i];
      for (j = i + 1; j < n; j++) {
        if (d[j] < p) {
          k = j;
          p = d[j];
        }
      }
      if (k !== i) {
        d[k] = d[i];
        d[i] = p;
        for (j = 0; j < n; j++) {
          p = V.get(j, i);
          V.set(j, i, V.get(j, k));
          V.set(j, k, p);
        }
      }
    }
  }
  function orthes(n, H, ort, V) {
    let low = 0;
    let high = n - 1;
    let f, g, h, i, j, m;
    let scale;
    for (m = low + 1; m <= high - 1; m++) {
      scale = 0;
      for (i = m; i <= high; i++) {
        scale = scale + Math.abs(H.get(i, m - 1));
      }
      if (scale !== 0) {
        h = 0;
        for (i = high; i >= m; i--) {
          ort[i] = H.get(i, m - 1) / scale;
          h += ort[i] * ort[i];
        }
        g = Math.sqrt(h);
        if (ort[m] > 0) {
          g = -g;
        }
        h = h - ort[m] * g;
        ort[m] = ort[m] - g;
        for (j = m; j < n; j++) {
          f = 0;
          for (i = high; i >= m; i--) {
            f += ort[i] * H.get(i, j);
          }
          f = f / h;
          for (i = m; i <= high; i++) {
            H.set(i, j, H.get(i, j) - f * ort[i]);
          }
        }
        for (i = 0; i <= high; i++) {
          f = 0;
          for (j = high; j >= m; j--) {
            f += ort[j] * H.get(i, j);
          }
          f = f / h;
          for (j = m; j <= high; j++) {
            H.set(i, j, H.get(i, j) - f * ort[j]);
          }
        }
        ort[m] = scale * ort[m];
        H.set(m, m - 1, scale * g);
      }
    }
    for (i = 0; i < n; i++) {
      for (j = 0; j < n; j++) {
        V.set(i, j, i === j ? 1 : 0);
      }
    }
    for (m = high - 1; m >= low + 1; m--) {
      if (H.get(m, m - 1) !== 0) {
        for (i = m + 1; i <= high; i++) {
          ort[i] = H.get(i, m - 1);
        }
        for (j = m; j <= high; j++) {
          g = 0;
          for (i = m; i <= high; i++) {
            g += ort[i] * V.get(i, j);
          }
          g = g / ort[m] / H.get(m, m - 1);
          for (i = m; i <= high; i++) {
            V.set(i, j, V.get(i, j) + g * ort[i]);
          }
        }
      }
    }
  }
  function hqr2(nn, e, d, V, H) {
    let n = nn - 1;
    let low = 0;
    let high = nn - 1;
    let eps = Number.EPSILON;
    let exshift = 0;
    let norm = 0;
    let p = 0;
    let q = 0;
    let r = 0;
    let s = 0;
    let z = 0;
    let iter = 0;
    let i, j, k, l, m, t, w, x, y;
    let ra, sa, vr, vi;
    let notlast, cdivres;
    for (i = 0; i < nn; i++) {
      if (i < low || i > high) {
        d[i] = H.get(i, i);
        e[i] = 0;
      }
      for (j = Math.max(i - 1, 0); j < nn; j++) {
        norm = norm + Math.abs(H.get(i, j));
      }
    }
    while (n >= low) {
      l = n;
      while (l > low) {
        s = Math.abs(H.get(l - 1, l - 1)) + Math.abs(H.get(l, l));
        if (s === 0) {
          s = norm;
        }
        if (Math.abs(H.get(l, l - 1)) < eps * s) {
          break;
        }
        l--;
      }
      if (l === n) {
        H.set(n, n, H.get(n, n) + exshift);
        d[n] = H.get(n, n);
        e[n] = 0;
        n--;
        iter = 0;
      } else if (l === n - 1) {
        w = H.get(n, n - 1) * H.get(n - 1, n);
        p = (H.get(n - 1, n - 1) - H.get(n, n)) / 2;
        q = p * p + w;
        z = Math.sqrt(Math.abs(q));
        H.set(n, n, H.get(n, n) + exshift);
        H.set(n - 1, n - 1, H.get(n - 1, n - 1) + exshift);
        x = H.get(n, n);
        if (q >= 0) {
          z = p >= 0 ? p + z : p - z;
          d[n - 1] = x + z;
          d[n] = d[n - 1];
          if (z !== 0) {
            d[n] = x - w / z;
          }
          e[n - 1] = 0;
          e[n] = 0;
          x = H.get(n, n - 1);
          s = Math.abs(x) + Math.abs(z);
          p = x / s;
          q = z / s;
          r = Math.sqrt(p * p + q * q);
          p = p / r;
          q = q / r;
          for (j = n - 1; j < nn; j++) {
            z = H.get(n - 1, j);
            H.set(n - 1, j, q * z + p * H.get(n, j));
            H.set(n, j, q * H.get(n, j) - p * z);
          }
          for (i = 0; i <= n; i++) {
            z = H.get(i, n - 1);
            H.set(i, n - 1, q * z + p * H.get(i, n));
            H.set(i, n, q * H.get(i, n) - p * z);
          }
          for (i = low; i <= high; i++) {
            z = V.get(i, n - 1);
            V.set(i, n - 1, q * z + p * V.get(i, n));
            V.set(i, n, q * V.get(i, n) - p * z);
          }
        } else {
          d[n - 1] = x + p;
          d[n] = x + p;
          e[n - 1] = z;
          e[n] = -z;
        }
        n = n - 2;
        iter = 0;
      } else {
        x = H.get(n, n);
        y = 0;
        w = 0;
        if (l < n) {
          y = H.get(n - 1, n - 1);
          w = H.get(n, n - 1) * H.get(n - 1, n);
        }
        if (iter === 10) {
          exshift += x;
          for (i = low; i <= n; i++) {
            H.set(i, i, H.get(i, i) - x);
          }
          s = Math.abs(H.get(n, n - 1)) + Math.abs(H.get(n - 1, n - 2));
          // eslint-disable-next-line no-multi-assign
          x = y = 0.75 * s;
          w = -0.4375 * s * s;
        }
        if (iter === 30) {
          s = (y - x) / 2;
          s = s * s + w;
          if (s > 0) {
            s = Math.sqrt(s);
            if (y < x) {
              s = -s;
            }
            s = x - w / ((y - x) / 2 + s);
            for (i = low; i <= n; i++) {
              H.set(i, i, H.get(i, i) - s);
            }
            exshift += s;
            // eslint-disable-next-line no-multi-assign
            x = y = w = 0.964;
          }
        }
        iter = iter + 1;
        m = n - 2;
        while (m >= l) {
          z = H.get(m, m);
          r = x - z;
          s = y - z;
          p = (r * s - w) / H.get(m + 1, m) + H.get(m, m + 1);
          q = H.get(m + 1, m + 1) - z - r - s;
          r = H.get(m + 2, m + 1);
          s = Math.abs(p) + Math.abs(q) + Math.abs(r);
          p = p / s;
          q = q / s;
          r = r / s;
          if (m === l) {
            break;
          }
          if (Math.abs(H.get(m, m - 1)) * (Math.abs(q) + Math.abs(r)) < eps * (Math.abs(p) * (Math.abs(H.get(m - 1, m - 1)) + Math.abs(z) + Math.abs(H.get(m + 1, m + 1))))) {
            break;
          }
          m--;
        }
        for (i = m + 2; i <= n; i++) {
          H.set(i, i - 2, 0);
          if (i > m + 2) {
            H.set(i, i - 3, 0);
          }
        }
        for (k = m; k <= n - 1; k++) {
          notlast = k !== n - 1;
          if (k !== m) {
            p = H.get(k, k - 1);
            q = H.get(k + 1, k - 1);
            r = notlast ? H.get(k + 2, k - 1) : 0;
            x = Math.abs(p) + Math.abs(q) + Math.abs(r);
            if (x !== 0) {
              p = p / x;
              q = q / x;
              r = r / x;
            }
          }
          if (x === 0) {
            break;
          }
          s = Math.sqrt(p * p + q * q + r * r);
          if (p < 0) {
            s = -s;
          }
          if (s !== 0) {
            if (k !== m) {
              H.set(k, k - 1, -s * x);
            } else if (l !== m) {
              H.set(k, k - 1, -H.get(k, k - 1));
            }
            p = p + s;
            x = p / s;
            y = q / s;
            z = r / s;
            q = q / p;
            r = r / p;
            for (j = k; j < nn; j++) {
              p = H.get(k, j) + q * H.get(k + 1, j);
              if (notlast) {
                p = p + r * H.get(k + 2, j);
                H.set(k + 2, j, H.get(k + 2, j) - p * z);
              }
              H.set(k, j, H.get(k, j) - p * x);
              H.set(k + 1, j, H.get(k + 1, j) - p * y);
            }
            for (i = 0; i <= Math.min(n, k + 3); i++) {
              p = x * H.get(i, k) + y * H.get(i, k + 1);
              if (notlast) {
                p = p + z * H.get(i, k + 2);
                H.set(i, k + 2, H.get(i, k + 2) - p * r);
              }
              H.set(i, k, H.get(i, k) - p);
              H.set(i, k + 1, H.get(i, k + 1) - p * q);
            }
            for (i = low; i <= high; i++) {
              p = x * V.get(i, k) + y * V.get(i, k + 1);
              if (notlast) {
                p = p + z * V.get(i, k + 2);
                V.set(i, k + 2, V.get(i, k + 2) - p * r);
              }
              V.set(i, k, V.get(i, k) - p);
              V.set(i, k + 1, V.get(i, k + 1) - p * q);
            }
          }
        }
      }
    }
    if (norm === 0) {
      return;
    }
    for (n = nn - 1; n >= 0; n--) {
      p = d[n];
      q = e[n];
      if (q === 0) {
        l = n;
        H.set(n, n, 1);
        for (i = n - 1; i >= 0; i--) {
          w = H.get(i, i) - p;
          r = 0;
          for (j = l; j <= n; j++) {
            r = r + H.get(i, j) * H.get(j, n);
          }
          if (e[i] < 0) {
            z = w;
            s = r;
          } else {
            l = i;
            if (e[i] === 0) {
              H.set(i, n, w !== 0 ? -r / w : -r / (eps * norm));
            } else {
              x = H.get(i, i + 1);
              y = H.get(i + 1, i);
              q = (d[i] - p) * (d[i] - p) + e[i] * e[i];
              t = (x * s - z * r) / q;
              H.set(i, n, t);
              H.set(i + 1, n, Math.abs(x) > Math.abs(z) ? (-r - w * t) / x : (-s - y * t) / z);
            }
            t = Math.abs(H.get(i, n));
            if (eps * t * t > 1) {
              for (j = i; j <= n; j++) {
                H.set(j, n, H.get(j, n) / t);
              }
            }
          }
        }
      } else if (q < 0) {
        l = n - 1;
        if (Math.abs(H.get(n, n - 1)) > Math.abs(H.get(n - 1, n))) {
          H.set(n - 1, n - 1, q / H.get(n, n - 1));
          H.set(n - 1, n, -(H.get(n, n) - p) / H.get(n, n - 1));
        } else {
          cdivres = cdiv(0, -H.get(n - 1, n), H.get(n - 1, n - 1) - p, q);
          H.set(n - 1, n - 1, cdivres[0]);
          H.set(n - 1, n, cdivres[1]);
        }
        H.set(n, n - 1, 0);
        H.set(n, n, 1);
        for (i = n - 2; i >= 0; i--) {
          ra = 0;
          sa = 0;
          for (j = l; j <= n; j++) {
            ra = ra + H.get(i, j) * H.get(j, n - 1);
            sa = sa + H.get(i, j) * H.get(j, n);
          }
          w = H.get(i, i) - p;
          if (e[i] < 0) {
            z = w;
            r = ra;
            s = sa;
          } else {
            l = i;
            if (e[i] === 0) {
              cdivres = cdiv(-ra, -sa, w, q);
              H.set(i, n - 1, cdivres[0]);
              H.set(i, n, cdivres[1]);
            } else {
              x = H.get(i, i + 1);
              y = H.get(i + 1, i);
              vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q;
              vi = (d[i] - p) * 2 * q;
              if (vr === 0 && vi === 0) {
                vr = eps * norm * (Math.abs(w) + Math.abs(q) + Math.abs(x) + Math.abs(y) + Math.abs(z));
              }
              cdivres = cdiv(x * r - z * ra + q * sa, x * s - z * sa - q * ra, vr, vi);
              H.set(i, n - 1, cdivres[0]);
              H.set(i, n, cdivres[1]);
              if (Math.abs(x) > Math.abs(z) + Math.abs(q)) {
                H.set(i + 1, n - 1, (-ra - w * H.get(i, n - 1) + q * H.get(i, n)) / x);
                H.set(i + 1, n, (-sa - w * H.get(i, n) - q * H.get(i, n - 1)) / x);
              } else {
                cdivres = cdiv(-r - y * H.get(i, n - 1), -s - y * H.get(i, n), z, q);
                H.set(i + 1, n - 1, cdivres[0]);
                H.set(i + 1, n, cdivres[1]);
              }
            }
            t = Math.max(Math.abs(H.get(i, n - 1)), Math.abs(H.get(i, n)));
            if (eps * t * t > 1) {
              for (j = i; j <= n; j++) {
                H.set(j, n - 1, H.get(j, n - 1) / t);
                H.set(j, n, H.get(j, n) / t);
              }
            }
          }
        }
      }
    }
    for (i = 0; i < nn; i++) {
      if (i < low || i > high) {
        for (j = i; j < nn; j++) {
          V.set(i, j, H.get(i, j));
        }
      }
    }
    for (j = nn - 1; j >= low; j--) {
      for (i = low; i <= high; i++) {
        z = 0;
        for (k = low; k <= Math.min(j, high); k++) {
          z = z + V.get(i, k) * H.get(k, j);
        }
        V.set(i, j, z);
      }
    }
  }
  function cdiv(xr, xi, yr, yi) {
    let r, d;
    if (Math.abs(yr) > Math.abs(yi)) {
      r = yi / yr;
      d = yr + r * yi;
      return [(xr + r * xi) / d, (xi - r * xr) / d];
    } else {
      r = yr / yi;
      d = yi + r * yr;
      return [(r * xr + xi) / d, (r * xi - xr) / d];
    }
  }
  class CholeskyDecomposition {
    constructor(value) {
      value = WrapperMatrix2D.checkMatrix(value);
      if (!value.isSymmetric()) {
        throw new Error('Matrix is not symmetric');
      }
      let a = value;
      let dimension = a.rows;
      let l = new Matrix$3(dimension, dimension);
      let positiveDefinite = true;
      let i, j, k;
      for (j = 0; j < dimension; j++) {
        let d = 0;
        for (k = 0; k < j; k++) {
          let s = 0;
          for (i = 0; i < k; i++) {
            s += l.get(k, i) * l.get(j, i);
          }
          s = (a.get(j, k) - s) / l.get(k, k);
          l.set(j, k, s);
          d = d + s * s;
        }
        d = a.get(j, j) - d;
        positiveDefinite &&= d > 0;
        l.set(j, j, Math.sqrt(Math.max(d, 0)));
        for (k = j + 1; k < dimension; k++) {
          l.set(j, k, 0);
        }
      }
      this.L = l;
      this.positiveDefinite = positiveDefinite;
    }
    isPositiveDefinite() {
      return this.positiveDefinite;
    }
    solve(value) {
      value = WrapperMatrix2D.checkMatrix(value);
      let l = this.L;
      let dimension = l.rows;
      if (value.rows !== dimension) {
        throw new Error('Matrix dimensions do not match');
      }
      if (this.isPositiveDefinite() === false) {
        throw new Error('Matrix is not positive definite');
      }
      let count = value.columns;
      let B = value.clone();
      let i, j, k;
      for (k = 0; k < dimension; k++) {
        for (j = 0; j < count; j++) {
          for (i = 0; i < k; i++) {
            B.set(k, j, B.get(k, j) - B.get(i, j) * l.get(k, i));
          }
          B.set(k, j, B.get(k, j) / l.get(k, k));
        }
      }
      for (k = dimension - 1; k >= 0; k--) {
        for (j = 0; j < count; j++) {
          for (i = k + 1; i < dimension; i++) {
            B.set(k, j, B.get(k, j) - B.get(i, j) * l.get(i, k));
          }
          B.set(k, j, B.get(k, j) / l.get(k, k));
        }
      }
      return B;
    }
    get lowerTriangularMatrix() {
      return this.L;
    }
  }
  class nipals {
    constructor(X, options = {}) {
      X = WrapperMatrix2D.checkMatrix(X);
      let {
        Y
      } = options;
      const {
        scaleScores = false,
        maxIterations = 1000,
        terminationCriteria = 1e-10
      } = options;
      let u;
      if (Y) {
        if (isAnyArray.isAnyArray(Y) && typeof Y[0] === 'number') {
          Y = Matrix$3.columnVector(Y);
        } else {
          Y = WrapperMatrix2D.checkMatrix(Y);
        }
        if (Y.rows !== X.rows) {
          throw new Error('Y should have the same number of rows as X');
        }
        u = Y.getColumnVector(0);
      } else {
        u = X.getColumnVector(0);
      }
      let diff = 1;
      let t, q, w, tOld;
      for (let counter = 0; counter < maxIterations && diff > terminationCriteria; counter++) {
        w = X.transpose().mmul(u).div(u.transpose().mmul(u).get(0, 0));
        w = w.div(w.norm());
        t = X.mmul(w).div(w.transpose().mmul(w).get(0, 0));
        if (counter > 0) {
          diff = t.clone().sub(tOld).pow(2).sum();
        }
        tOld = t.clone();
        if (Y) {
          q = Y.transpose().mmul(t).div(t.transpose().mmul(t).get(0, 0));
          q = q.div(q.norm());
          u = Y.mmul(q).div(q.transpose().mmul(q).get(0, 0));
        } else {
          u = t;
        }
      }
      if (Y) {
        let p = X.transpose().mmul(t).div(t.transpose().mmul(t).get(0, 0));
        p = p.div(p.norm());
        let xResidual = X.clone().sub(t.clone().mmul(p.transpose()));
        let residual = u.transpose().mmul(t).div(t.transpose().mmul(t).get(0, 0));
        let yResidual = Y.clone().sub(t.clone().mulS(residual.get(0, 0)).mmul(q.transpose()));
        this.t = t;
        this.p = p.transpose();
        this.w = w.transpose();
        this.q = q;
        this.u = u;
        this.s = t.transpose().mmul(t);
        this.xResidual = xResidual;
        this.yResidual = yResidual;
        this.betas = residual;
      } else {
        this.w = w.transpose();
        this.s = t.transpose().mmul(t).sqrt();
        if (scaleScores) {
          this.t = t.clone().div(this.s.get(0, 0));
        } else {
          this.t = t;
        }
        this.xResidual = X.sub(t.mmul(w.transpose()));
      }
    }
  }
  matrix.AbstractMatrix = AbstractMatrix;
  matrix.CHO = CholeskyDecomposition;
  matrix.CholeskyDecomposition = CholeskyDecomposition;
  matrix.DistanceMatrix = DistanceMatrix;
  matrix.EVD = EigenvalueDecomposition;
  matrix.EigenvalueDecomposition = EigenvalueDecomposition;
  matrix.LU = LuDecomposition;
  matrix.LuDecomposition = LuDecomposition;
  var Matrix_1 = matrix.Matrix = Matrix$3;
  matrix.MatrixColumnSelectionView = MatrixColumnSelectionView;
  matrix.MatrixColumnView = MatrixColumnView;
  matrix.MatrixFlipColumnView = MatrixFlipColumnView;
  matrix.MatrixFlipRowView = MatrixFlipRowView;
  matrix.MatrixRowSelectionView = MatrixRowSelectionView;
  matrix.MatrixRowView = MatrixRowView;
  matrix.MatrixSelectionView = MatrixSelectionView;
  matrix.MatrixSubView = MatrixSubView;
  matrix.MatrixTransposeView = MatrixTransposeView$1;
  matrix.NIPALS = nipals;
  matrix.Nipals = nipals;
  matrix.QR = QrDecomposition;
  matrix.QrDecomposition = QrDecomposition;
  var SVD$1 = matrix.SVD = SingularValueDecomposition$1;
  var SingularValueDecomposition_1 = matrix.SingularValueDecomposition = SingularValueDecomposition$1;
  matrix.SymmetricMatrix = SymmetricMatrix;
  matrix.WrapperMatrix1D = WrapperMatrix1D;
  matrix.WrapperMatrix2D = WrapperMatrix2D;
  matrix.correlation = correlation;
  matrix.covariance = covariance;
  var _default = matrix.default = Matrix$3;
  matrix.determinant = determinant;
  var inverse_1 = matrix.inverse = inverse$1;
  matrix.linearDependencies = linearDependencies;
  matrix.pseudoInverse = pseudoInverse;
  var solve_1 = matrix.solve = solve$1;
  matrix.wrap = wrap;

  const Matrix$2 = Matrix_1;
  const SVD = SVD$1;
  const SingularValueDecomposition = SingularValueDecomposition_1;
  _default.Matrix ? _default.Matrix : Matrix_1;
  const inverse = inverse_1;
  const solve = solve_1;

  function getSeparatedKernel(kernel) {
    const svd = new SVD(kernel, {
      autoTranspose: true
    });
    if (svd.rank !== 1) return null;
    const s = Math.sqrt(svd.s[0]);
    const v = svd.U.to2DArray().map(v => v[0] * s);
    const h = svd.V.to2DArray().map(h => h[0] * s);
    return [v, h];
  }

  /**
   * @memberof Image
   * @instance
   * @param {Array<Array<number>>} kernel
   * @param {object} [options] - options
   * @param {Array} [options.channels] - Array of channels to treat. Defaults to all channels
   * @param {number} [options.bitDepth=this.bitDepth] - A new bit depth can be specified. This allows to use 32 bits to avoid clamping of floating-point numbers.
   * @param {boolean} [options.normalize=false]
   * @param {number} [options.divisor=1]
   * @param {string} [options.border='copy']
   * @param {string} [options.algorithm='auto'] - Either 'auto', 'direct', 'fft' or 'separable'. fft is much faster for large kernel.
   * If the separable algorithm is used, one must provide as kernel an array of two 1D kernels.
   * The 'auto' option will try to separate the kernel if that is possible.
   * @return {Image}
   */
  function convolution(kernel, options = {}) {
    let {
      channels,
      bitDepth,
      normalize = false,
      divisor = 1,
      border = 'copy',
      algorithm = 'auto'
    } = options;
    let createOptions = {};
    if (bitDepth) createOptions.bitDepth = bitDepth;
    let newImage = Image.createFrom(this, createOptions);
    channels = validateArrayOfChannels(this, channels);
    if (algorithm !== 'separable') {
      ({
        kernel
      } = validateKernel(kernel));
    } else if (!Array.isArray(kernel) || kernel.length !== 2) {
      throw new RangeError('separable convolution requires two arrays of numbers to represent the kernel');
    }
    if (algorithm === 'auto') {
      let separatedKernel = getSeparatedKernel(kernel);
      if (separatedKernel !== null) {
        algorithm = 'separable';
        kernel = separatedKernel;
      } else if ((kernel.length > 9 || kernel[0].length > 9) && this.width <= 4096 && this.height <= 4096) {
        algorithm = 'fft';
      } else {
        algorithm = 'direct';
      }
    }
    let halfHeight, halfWidth;
    if (algorithm === 'separable') {
      halfHeight = Math.floor(kernel[0].length / 2);
      halfWidth = Math.floor(kernel[1].length / 2);
    } else {
      halfHeight = Math.floor(kernel.length / 2);
      halfWidth = Math.floor(kernel[0].length / 2);
    }
    let clamped = newImage.isClamped;
    let tmpData = new Array(this.height * this.width);
    let index, x, y, channel, c, tmpResult;
    for (channel = 0; channel < channels.length; channel++) {
      c = channels[channel];
      // Copy the channel in a single array
      for (y = 0; y < this.height; y++) {
        for (x = 0; x < this.width; x++) {
          index = y * this.width + x;
          tmpData[index] = this.data[index * this.channels + c];
        }
      }
      if (algorithm === 'direct') {
        tmpResult = src$1.direct(tmpData, kernel, {
          rows: this.height,
          cols: this.width,
          normalize: normalize,
          divisor: divisor
        });
      } else if (algorithm === 'separable') {
        tmpResult = convolutionSeparable(tmpData, kernel, this.width, this.height);
        if (normalize) {
          divisor = 0;
          for (let i = 0; i < kernel[0].length; i++) {
            for (let j = 0; j < kernel[1].length; j++) {
              divisor += kernel[0][i] * kernel[1][j];
            }
          }
        }
        if (divisor !== 1) {
          for (let i = 0; i < tmpResult.length; i++) {
            tmpResult[i] /= divisor;
          }
        }
      } else {
        tmpResult = src$1.fft(tmpData, kernel, {
          rows: this.height,
          cols: this.width,
          normalize: normalize,
          divisor: divisor
        });
      }

      // Copy the result to the output image
      for (y = 0; y < this.height; y++) {
        for (x = 0; x < this.width; x++) {
          index = y * this.width + x;
          if (clamped) {
            newImage.data[index * this.channels + c] = clamp(tmpResult[index], newImage);
          } else {
            newImage.data[index * this.channels + c] = tmpResult[index];
          }
        }
      }
    }
    // if the kernel was not applied on the alpha channel we just copy it
    // TODO: in general we should copy the channels that where not changed
    // TODO: probably we should just copy the image at the beginning ?
    if (this.alpha && !channels.includes(this.channels)) {
      for (x = this.components; x < this.data.length; x = x + this.channels) {
        newImage.data[x] = this.data[x];
      }
    }

    // I only can have 3 types of borders:
    //  1. Considering the image as periodic: periodic
    //  2. Extend the interior borders: copy
    //  3. fill with a color: set
    if (border !== 'periodic') {
      newImage.setBorder({
        size: [halfWidth, halfHeight],
        algorithm: border
      });
    }
    return newImage;
  }

  /**
   * Direction of a gradient filter
   * @typedef {('x'|'y'|'xy')} GradientDirection
   */

  /**
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {GradientDirection} [options.direction]
   * @param {Array<Array<number>>} [options.kernelX]
   * @param {Array<Array<number>>} [options.kernelY]
   * @param {string} [options.border='copy']
   * @param {*} [options.channels]
   * @param {number} [options.bitDepth=this.bitDepth] Specify the bitDepth of the resulting image
   * @return {Image}
   */
  function gradientFilter(options = {}) {
    let {
      direction = 'xy',
      border = 'copy',
      kernelX,
      kernelY,
      channels,
      bitDepth = this.bitDepth
    } = options;
    this.checkProcessable('gradientFilter', {
      bitDepth: [8, 16]
    });
    switch (direction) {
      case 'x':
        if (!kernelX) throw new Error('kernelX option is missing');
        return convolution.call(this, kernelX, {
          channels: channels,
          border: border,
          bitDepth
        });
      case 'y':
        if (!kernelY) throw new Error('kernelY option is missing');
        return convolution.call(this, kernelY, {
          channels: channels,
          border: border,
          bitDepth
        });
      case 'xy':
        {
          if (!kernelX) throw new Error('kernelX option is missing');
          if (!kernelY) throw new Error('kernelY option is missing');
          const gX = convolution.call(this, kernelX, {
            channels: channels,
            border: border,
            bitDepth: 32
          });
          const gY = convolution.call(this, kernelY, {
            channels: channels,
            border: border,
            bitDepth: 32
          });
          return gX.hypotenuse(gY, {
            bitDepth,
            channels: channels
          });
        }
      default:
        throw new Error(`Unknown parameter direction: ${direction}`);
    }
  }

  /**
   * Applies the Sobel operator.
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {GradientDirection} [options.direction]
   * @param {string} [options.border='copy']
   * @param {*} [options.channels]
   * @param {number} [options.bitDepth=this.bitDepth] Specify the bitDepth of the resulting image
   * @return {Image}
   * @see {@link https://en.wikipedia.org/wiki/Sobel_operator}
   */
  function sobelFilter(options) {
    return gradientFilter.call(this, Object.assign({}, options, {
      kernelX: SOBEL_X,
      kernelY: SOBEL_Y
    }));
  }

  /**
   * Applies the Scharr operator.
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {GradientDirection} [options.direction]
   * @param {string} [options.border='copy']
   * @param {*} [options.channels]
   * @param {number} [options.bitDepth=this.bitDepth] Specify the bitDepth of the resulting image
   * @return {Image}
   * @see {@link https://en.wikipedia.org/wiki/Sobel_operator#Alternative_operators}
   */
  function scharrFilter(options) {
    return gradientFilter.call(this, Object.assign({}, options, {
      kernelX: SCHARR_X,
      kernelY: SCHARR_Y
    }));
  }

  var newArray_1 = newArray;
  function newArray(n, value) {
    n = n || 0;
    var array = new Array(n);
    for (var i = 0; i < n; i++) {
      array[i] = value;
    }
    return array;
  }
  var newArray$1 = /*@__PURE__*/getDefaultExportFromCjs(newArray_1);

  /**
   * Level the image for by default have the minimal and maximal values.
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {string} [options.algorithm='range']
   * @param {SelectedChannels} [options.channels] Specify which channels should be processed
   * @param {number} [options.min=this.min] minimal value after levelling
   * @param {number} [options.max=this.max] maximal value after levelling
   * @return {this}
   */
  function level(options = {}) {
    let {
      algorithm = 'range',
      channels,
      min = this.min,
      max = this.max
    } = options;
    this.checkProcessable('level', {
      bitDepth: [8, 16, 32]
    });
    channels = validateArrayOfChannels(this, {
      channels: channels
    });
    if (channels.length !== this.channel) {
      // if we process only part of the channels and the min or max length corresponds to the number of channels
      // we need to take the corresponding values
      if (Array.isArray(min) && min.length === this.channels) {
        min = min.filter((a, index) => channels.includes(index));
      }
      if (Array.isArray(max) && max.length === this.channels) {
        max = max.filter((a, index) => channels.includes(index));
      }
    }
    switch (algorithm) {
      case 'range':
        if (min < 0) {
          min = 0;
        }
        if (max > this.maxValue) {
          max = this.maxValue;
        }
        if (!Array.isArray(min)) {
          min = newArray$1(channels.length, min);
        }
        if (!Array.isArray(max)) {
          max = newArray$1(channels.length, max);
        }
        processImage(this, min, max, channels);
        break;
      default:
        throw new Error(`level: algorithm not implement: ${algorithm}`);
    }
    return this;
  }
  function processImage(image, min, max, channels) {
    let delta = 1e-5; // sorry no better value that this "best guess"
    let factor = new Array(channels.length);
    for (let i = 0; i < channels.length; i++) {
      if (min[i] === 0 && max[i] === image.maxValue) {
        factor[i] = 0;
      } else if (max[i] === min[i]) {
        factor[i] = 0;
      } else {
        factor[i] = (image.maxValue + 1 - delta) / (max[i] - min[i]);
      }
      min[i] += (0.5 - delta / 2) / factor[i];
    }

    /*
       Note on border effect
       For 8 bits images we should calculate for the space between -0.5 and 255.5
       so that after ronding the first and last points still have the same population
       But doing this we need to deal with Math.round that gives 256 if the value is 255.5
       */

    for (let j = 0; j < channels.length; j++) {
      let c = channels[j];
      if (factor[j] !== 0) {
        for (let i = 0; i < image.data.length; i += image.channels) {
          image.data[i + c] = Math.min(Math.max(0, (image.data[i + c] - min[j]) * factor[j] + 0.5 | 0), image.maxValue);
        }
      }
    }
  }

  var toString = Object.prototype.toString;
  var isArrayType = function isArrayType(value) {
    return toString.call(value).substr(-6, 5) === 'Array';
  };
  var isArray = /*@__PURE__*/getDefaultExportFromCjs(isArrayType);

  function checkNumberArray(value) {
    if (!isNaN(value)) {
      if (value <= 0) {
        throw new Error('checkNumberArray: the value must be greater than 0');
      }
      return value;
    } else {
      if (value instanceof Image) {
        return value.data;
      }
      if (!isArray(value)) {
        throw new Error('checkNumberArray: the value should be either a number, array or Image');
      }
      return value;
    }
  }

  /**
   * Add a specific integer on the specified points of the specified channels
   * @memberof Image
   * @instance
   * @param {*} value
   * @param {object} [options]
   * @return {this} Modified current image
   */
  function add(value, options = {}) {
    let {
      channels
    } = options;
    this.checkProcessable('add', {
      bitDepth: [8, 16]
    });
    channels = validateArrayOfChannels(this, {
      channels: channels
    });
    value = checkNumberArray(value);

    // we allow 3 cases, the value may be an array (1D), an image or a single value
    if (!isNaN(value)) {
      for (let j = 0; j < channels.length; j++) {
        let c = channels[j];
        for (let i = 0; i < this.data.length; i += this.channels) {
          this.data[i + c] = Math.min(this.maxValue, this.data[i + c] + value >> 0);
        }
      }
    } else {
      if (this.data.length !== value.length) {
        throw new Error('add: the data size is different');
      }
      for (let j = 0; j < channels.length; j++) {
        let c = channels[j];
        for (let i = 0; i < this.data.length; i += this.channels) {
          this.data[i + c] = Math.max(0, Math.min(this.maxValue, this.data[i + c] + value[i + c] >> 0));
        }
      }
    }
    return this;
  }

  /**
   * @memberof Image
   * @instance
   * @param {*} value
   * @param {object} [options]
   * @return {this}
   */
  function subtract(value, options = {}) {
    let {
      channels
    } = options;
    this.checkProcessable('subtract', {
      bitDepth: [8, 16]
    });
    channels = validateArrayOfChannels(this, {
      channels: channels
    });
    value = checkNumberArray(value);
    if (!isNaN(value)) {
      for (let j = 0; j < channels.length; j++) {
        let c = channels[j];
        for (let i = 0; i < this.data.length; i += this.channels) {
          this.data[i + c] = Math.max(0, this.data[i + c] - value >> 0);
        }
      }
    } else {
      if (this.data.length !== value.length) {
        throw new Error('subtract: the data size is different');
      }
      for (let j = 0; j < channels.length; j++) {
        let c = channels[j];
        for (let i = 0; i < this.data.length; i += this.channels) {
          this.data[i + c] = Math.max(0, Math.min(this.maxValue, this.data[i + c] - value[i + c] >> 0));
        }
      }
    }
    return this;
  }

  /**
   * Calculate a new image that is the subtraction between the current image and the otherImage.
   * @memberof Image
   * @instance
   * @param {Image} otherImage
   * @param {object} [options={}]
   * @param {number[]|string[]} [options.channels] : to which channel to apply the filter. By default all but alpha.
   * @param {number[]|string[]} [options.absolute=false] :.take the absolute value of the difference (default minimum=0)
   * @return {Image}
   */
  function subtractImage(otherImage, options = {}) {
    let {
      channels,
      absolute = false
    } = options;
    this.checkProcessable('subtractImage', {
      bitDepth: [8, 16]
    });
    if (this.width !== otherImage.width || this.height !== otherImage.height) {
      throw new Error('subtractImage: both images must have the same size');
    }
    if (this.alpha !== otherImage.alpha || this.bitDepth !== otherImage.bitDepth) {
      throw new Error('subtractImage: both images must have the same alpha and bitDepth');
    }
    if (this.channels !== otherImage.channels) {
      throw new Error('subtractImage: both images must have the same number of channels');
    }
    let newImage = this.clone();
    channels = validateArrayOfChannels(this, {
      channels: channels
    });
    for (let j = 0; j < channels.length; j++) {
      let c = channels[j];
      for (let i = c; i < this.data.length; i += this.channels) {
        let value = this.data[i] - otherImage.data[i];
        if (absolute) {
          newImage.data[i] = Math.abs(value);
        } else {
          newImage.data[i] = Math.max(value, 0);
        }
      }
    }
    return newImage;
  }

  /**
   * Calculate a new image that is the hypotenuse between the current image and the otherImage.
   * @memberof Image
   * @instance
   * @param {Image} otherImage
   * @param {object} [options={}]
   * @param {number} [options.bitDepth=this.bitDepth]
   * @param {number[]|string[]} [options.channels] : to which channel to apply the filter. By default all but alpha.
   * @return {Image}
   */
  function hypotenuse(otherImage, options = {}) {
    let {
      bitDepth = this.bitDepth,
      channels
    } = options;
    this.checkProcessable('hypotenuse', {
      bitDepth: [8, 16, 32]
    });
    if (this.width !== otherImage.width || this.height !== otherImage.height) {
      throw new Error('hypotenuse: both images must have the same size');
    }
    if (this.alpha !== otherImage.alpha || this.bitDepth !== otherImage.bitDepth) {
      throw new Error('hypotenuse: both images must have the same alpha and bitDepth');
    }
    if (this.channels !== otherImage.channels) {
      throw new Error('hypotenuse: both images must have the same number of channels');
    }
    let newImage = Image.createFrom(this, {
      bitDepth: bitDepth
    });
    channels = validateArrayOfChannels(this, {
      channels: channels
    });
    let clamped = newImage.isClamped;
    for (let j = 0; j < channels.length; j++) {
      let c = channels[j];
      for (let i = c; i < this.data.length; i += this.channels) {
        let value = Math.hypot(this.data[i], otherImage.data[i]);
        if (clamped) {
          // we calculate the clamped result
          newImage.data[i] = Math.min(Math.max(Math.round(value), 0), newImage.maxValue);
        } else {
          newImage.data[i] = value;
        }
      }
    }
    return newImage;
  }

  /**
   * @memberof Image
   * @instance
   * @param {*} value
   * @param {object} [options]
   * @return {this}
   */
  function multiply(value, options = {}) {
    let {
      channels
    } = options;
    this.checkProcessable('multiply', {
      bitDepth: [8, 16]
    });
    if (value <= 0) {
      throw new Error('multiply: the value must be greater than 0');
    }
    channels = validateArrayOfChannels(this, {
      channels: channels
    });
    value = checkNumberArray(value);
    if (!isNaN(value)) {
      for (let j = 0; j < channels.length; j++) {
        let c = channels[j];
        for (let i = 0; i < this.data.length; i += this.channels) {
          this.data[i + c] = Math.min(this.maxValue, this.data[i + c] * value >> 0);
        }
      }
    } else {
      if (this.data.length !== value.length) {
        throw new Error('multiply: the data size is different');
      }
      for (let j = 0; j < channels.length; j++) {
        let c = channels[j];
        for (let i = 0; i < this.data.length; i += this.channels) {
          this.data[i + c] = Math.max(0, Math.min(this.maxValue, this.data[i + c] * value[i + c] >> 0));
        }
      }
    }
    return this;
  }

  /**
   * @memberof Image
   * @instance
   * @param {*} value
   * @param {object} [options]
   * @return {this}
   */
  function divide(value, options = {}) {
    let {
      channels
    } = options;
    this.checkProcessable('divide', {
      bitDepth: [8, 16]
    });
    channels = validateArrayOfChannels(this, {
      channels: channels
    });
    value = checkNumberArray(value);
    if (!isNaN(value)) {
      for (let j = 0; j < channels.length; j++) {
        let c = channels[j];
        for (let i = 0; i < this.data.length; i += this.channels) {
          this.data[i + c] = Math.min(this.maxValue, this.data[i + c] / value >> 0);
        }
      }
    } else {
      if (this.data.length !== value.length) {
        throw new Error('divide: the: the data size is different');
      }
      for (let j = 0; j < channels.length; j++) {
        let c = channels[j];
        for (let i = 0; i < this.data.length; i += this.channels) {
          this.data[i + c] = Math.max(0, Math.min(this.maxValue, this.data[i + c] / value[i + c] >> 0));
        }
      }
    }
    return this;
  }

  class BaseRegression {
    constructor() {
      if (new.target === BaseRegression) {
        throw new Error('BaseRegression must be subclassed');
      }
    }
    predict(x) {
      if (typeof x === 'number') {
        return this._predict(x);
      } else if (isAnyArray$1(x)) {
        const y = [];
        for (let i = 0; i < x.length; i++) {
          y.push(this._predict(x[i]));
        }
        return y;
      } else {
        throw new TypeError('x must be a number or array');
      }
    }
    _predict() {
      throw new Error('_predict must be implemented');
    }
    train() {
      // Do nothing for this package
    }
    toString() {
      return '';
    }
    toLaTeX() {
      return '';
    }

    /**
     * Return the correlation coefficient of determination (r) and chi-square.
     * @param {Array<number>} x
     * @param {Array<number>} y
     * @return {object}
     */
    score(x, y) {
      if (!isAnyArray$1(x) || !isAnyArray$1(y) || x.length !== y.length) {
        throw new Error('x and y must be arrays of the same length');
      }
      const n = x.length;
      const y2 = new Array(n);
      for (let i = 0; i < n; i++) {
        y2[i] = this._predict(x[i]);
      }
      let xSum = 0;
      let ySum = 0;
      let chi2 = 0;
      let rmsd = 0;
      let xSquared = 0;
      let ySquared = 0;
      let xY = 0;
      for (let i = 0; i < n; i++) {
        xSum += y2[i];
        ySum += y[i];
        xSquared += y2[i] * y2[i];
        ySquared += y[i] * y[i];
        xY += y2[i] * y[i];
        if (y[i] !== 0) {
          chi2 += (y[i] - y2[i]) * (y[i] - y2[i]) / y[i];
        }
        rmsd += (y[i] - y2[i]) * (y[i] - y2[i]);
      }
      const r = (n * xY - xSum * ySum) / Math.sqrt((n * xSquared - xSum * xSum) * (n * ySquared - ySum * ySum));
      return {
        r: r,
        r2: r * r,
        chi2: chi2,
        rmsd: Math.sqrt(rmsd / n)
      };
    }
  }

  function squaredEuclidean$4(p, q) {
    let d = 0;
    for (let i = 0; i < p.length; i++) {
      d += (p[i] - q[i]) * (p[i] - q[i]);
    }
    return d;
  }
  function euclidean$2(p, q) {
    return Math.sqrt(squaredEuclidean$4(p, q));
  }

  var euclidean$3 = /*#__PURE__*/Object.freeze({
    __proto__: null,
    euclidean: euclidean$2,
    squaredEuclidean: squaredEuclidean$4
  });

  var require$$0 = /*@__PURE__*/getAugmentedNamespace(euclidean$3);

  const {
    squaredEuclidean: squaredEuclidean$3
  } = require$$0;
  const defaultOptions$b = {
    sigma: 1
  };
  let GaussianKernel$1 = class GaussianKernel {
    constructor(options) {
      options = Object.assign({}, defaultOptions$b, options);
      this.sigma = options.sigma;
      this.divisor = 2 * options.sigma * options.sigma;
    }
    compute(x, y) {
      const distance = squaredEuclidean$3(x, y);
      return Math.exp(-distance / this.divisor);
    }
  };
  var gaussianKernel = GaussianKernel$1;

  const defaultOptions$a = {
    degree: 1,
    constant: 1,
    scale: 1
  };
  let PolynomialKernel$1 = class PolynomialKernel {
    constructor(options) {
      options = Object.assign({}, defaultOptions$a, options);
      this.degree = options.degree;
      this.constant = options.constant;
      this.scale = options.scale;
    }
    compute(x, y) {
      var sum = 0;
      for (var i = 0; i < x.length; i++) {
        sum += x[i] * y[i];
      }
      return Math.pow(this.scale * sum + this.constant, this.degree);
    }
  };
  var polynomialKernel = PolynomialKernel$1;

  const defaultOptions$9 = {
    alpha: 0.01,
    constant: -Math.E
  };
  let SigmoidKernel$1 = class SigmoidKernel {
    constructor(options) {
      options = Object.assign({}, defaultOptions$9, options);
      this.alpha = options.alpha;
      this.constant = options.constant;
    }
    compute(x, y) {
      var sum = 0;
      for (var i = 0; i < x.length; i++) {
        sum += x[i] * y[i];
      }
      return Math.tanh(this.alpha * sum + this.constant);
    }
  };
  var sigmoidKernel = SigmoidKernel$1;

  const defaultOptions$8 = {
    sigma: 1,
    degree: 1
  };
  let ANOVAKernel$1 = class ANOVAKernel {
    constructor(options) {
      options = Object.assign({}, defaultOptions$8, options);
      this.sigma = options.sigma;
      this.degree = options.degree;
    }
    compute(x, y) {
      var sum = 0;
      var len = Math.min(x.length, y.length);
      for (var i = 1; i <= len; ++i) {
        sum += Math.pow(Math.exp(-this.sigma * Math.pow(Math.pow(x[i - 1], i) - Math.pow(y[i - 1], i), 2)), this.degree);
      }
      return sum;
    }
  };
  var anovaKernel = ANOVAKernel$1;

  const {
    squaredEuclidean: squaredEuclidean$2
  } = require$$0;
  const defaultOptions$7 = {
    sigma: 1
  };
  let CauchyKernel$1 = class CauchyKernel {
    constructor(options) {
      options = Object.assign({}, defaultOptions$7, options);
      this.sigma = options.sigma;
    }
    compute(x, y) {
      return 1 / (1 + squaredEuclidean$2(x, y) / (this.sigma * this.sigma));
    }
  };
  var cauchyKernel = CauchyKernel$1;

  const {
    euclidean: euclidean$1
  } = require$$0;
  const defaultOptions$6 = {
    sigma: 1
  };
  let ExponentialKernel$1 = class ExponentialKernel {
    constructor(options) {
      options = Object.assign({}, defaultOptions$6, options);
      this.sigma = options.sigma;
      this.divisor = 2 * options.sigma * options.sigma;
    }
    compute(x, y) {
      const distance = euclidean$1(x, y);
      return Math.exp(-distance / this.divisor);
    }
  };
  var exponentialKernel = ExponentialKernel$1;

  class HistogramIntersectionKernel {
    compute(x, y) {
      var min = Math.min(x.length, y.length);
      var sum = 0;
      for (var i = 0; i < min; ++i) {
        sum += Math.min(x[i], y[i]);
      }
      return sum;
    }
  }
  var histogramIntersectionKernel = HistogramIntersectionKernel;

  const {
    euclidean
  } = require$$0;
  const defaultOptions$5 = {
    sigma: 1
  };
  let LaplacianKernel$1 = class LaplacianKernel {
    constructor(options) {
      options = Object.assign({}, defaultOptions$5, options);
      this.sigma = options.sigma;
    }
    compute(x, y) {
      const distance = euclidean(x, y);
      return Math.exp(-distance / this.sigma);
    }
  };
  var laplacianKernel = LaplacianKernel$1;

  const {
    squaredEuclidean: squaredEuclidean$1
  } = require$$0;
  const defaultOptions$4 = {
    constant: 1
  };
  let MultiquadraticKernel$1 = class MultiquadraticKernel {
    constructor(options) {
      options = Object.assign({}, defaultOptions$4, options);
      this.constant = options.constant;
    }
    compute(x, y) {
      return Math.sqrt(squaredEuclidean$1(x, y) + this.constant * this.constant);
    }
  };
  var multiquadraticKernel = MultiquadraticKernel$1;

  const {
    squaredEuclidean
  } = require$$0;
  const defaultOptions$3 = {
    constant: 1
  };
  class RationalQuadraticKernel {
    constructor(options) {
      options = Object.assign({}, defaultOptions$3, options);
      this.constant = options.constant;
    }
    compute(x, y) {
      const distance = squaredEuclidean(x, y);
      return 1 - distance / (distance + this.constant);
    }
  }
  var rationalQuadraticKernel = RationalQuadraticKernel;

  const {
    Matrix: Matrix$1,
    MatrixTransposeView
  } = matrix;
  const GaussianKernel = gaussianKernel;
  const PolynomialKernel = polynomialKernel;
  const SigmoidKernel = sigmoidKernel;
  const ANOVAKernel = anovaKernel;
  const CauchyKernel = cauchyKernel;
  const ExponentialKernel = exponentialKernel;
  const HistogramKernel = histogramIntersectionKernel;
  const LaplacianKernel = laplacianKernel;
  const MultiquadraticKernel = multiquadraticKernel;
  const RationalKernel = rationalQuadraticKernel;
  const kernelType = {
    gaussian: GaussianKernel,
    rbf: GaussianKernel,
    polynomial: PolynomialKernel,
    poly: PolynomialKernel,
    anova: ANOVAKernel,
    cauchy: CauchyKernel,
    exponential: ExponentialKernel,
    histogram: HistogramKernel,
    min: HistogramKernel,
    laplacian: LaplacianKernel,
    multiquadratic: MultiquadraticKernel,
    rational: RationalKernel,
    sigmoid: SigmoidKernel,
    mlp: SigmoidKernel
  };
  class Kernel {
    constructor(type, options) {
      this.kernelType = type;
      if (type === 'linear') return;
      if (typeof type === 'string') {
        type = type.toLowerCase();
        var KernelConstructor = kernelType[type];
        if (KernelConstructor) {
          this.kernelFunction = new KernelConstructor(options);
        } else {
          throw new Error(`unsupported kernel type: ${type}`);
        }
      } else if (typeof type === 'object' && typeof type.compute === 'function') {
        this.kernelFunction = type;
      } else {
        throw new TypeError('first argument must be a valid kernel type or instance');
      }
    }
    compute(inputs, landmarks) {
      inputs = Matrix$1.checkMatrix(inputs);
      if (landmarks === undefined) {
        landmarks = inputs;
      } else {
        landmarks = Matrix$1.checkMatrix(landmarks);
      }
      if (this.kernelType === 'linear') {
        return inputs.mmul(new MatrixTransposeView(landmarks));
      }
      const kernelMatrix = new Matrix$1(inputs.rows, landmarks.rows);
      if (inputs === landmarks) {
        // fast path, matrix is symmetric
        for (let i = 0; i < inputs.rows; i++) {
          for (let j = i; j < inputs.rows; j++) {
            const value = this.kernelFunction.compute(inputs.getRow(i), inputs.getRow(j));
            kernelMatrix.set(i, j, value);
            kernelMatrix.set(j, i, value);
          }
        }
      } else {
        for (let i = 0; i < inputs.rows; i++) {
          for (let j = 0; j < landmarks.rows; j++) {
            kernelMatrix.set(i, j, this.kernelFunction.compute(inputs.getRow(i), landmarks.getRow(j)));
          }
        }
      }
      return kernelMatrix;
    }
  }
  var kernel$1 = Kernel;
  var Kernel$1 = /*@__PURE__*/getDefaultExportFromCjs(kernel$1);

  const defaultOptions$2 = {
    lambda: 0.1,
    kernelType: 'gaussian',
    kernelOptions: {},
    computeCoefficient: false
  };

  // Implements the Kernel ridge regression algorithm.
  // http://www.ics.uci.edu/~welling/classnotes/papers_class/Kernel-Ridge.pdf
  class KernelRidgeRegression extends BaseRegression {
    constructor(inputs, outputs, options) {
      super();
      if (inputs === true) {
        // reloading model
        this.alpha = outputs.alpha;
        this.inputs = outputs.inputs;
        this.kernelType = outputs.kernelType;
        this.kernelOptions = outputs.kernelOptions;
        this.kernel = new Kernel$1(outputs.kernelType, outputs.kernelOptions);
      } else {
        inputs = Matrix$2.checkMatrix(inputs);
        options = Object.assign({}, defaultOptions$2, options);
        const kernelFunction = new Kernel$1(options.kernelType, options.kernelOptions);
        const K = kernelFunction.compute(inputs);
        const n = inputs.rows;
        K.add(Matrix$2.eye(n, n).mul(options.lambda));
        this.alpha = solve(K, outputs);
        this.inputs = inputs;
        this.kernelType = options.kernelType;
        this.kernelOptions = options.kernelOptions;
        this.kernel = kernelFunction;
      }
    }
    _predict(newInputs) {
      return this.kernel.compute([newInputs], this.inputs).mmul(this.alpha).getRow(0);
    }
    toJSON() {
      return {
        name: 'kernelRidgeRegression',
        alpha: this.alpha,
        inputs: this.inputs,
        kernelType: this.kernelType,
        kernelOptions: this.kernelOptions
      };
    }
    static load(json) {
      if (json.name !== 'kernelRidgeRegression') {
        throw new TypeError('not a KRR model');
      }
      return new KernelRidgeRegression(true, json);
    }
  }

  /**
   * @memberof Image
   * @instance
   * @param {Array<Array<number>>} coordinates
   * @param {Array<Array<number>>} values;
   * @param {object} [options]
   * @return {Image}
   */
  function background$1(coordinates, values, options) {
    const model = new KernelRidgeRegression(coordinates, values, options);
    const allCoordinates = new Array(this.size);
    for (let i = 0; i < this.width; i++) {
      for (let j = 0; j < this.height; j++) {
        allCoordinates[j * this.width + i] = [i, j];
      }
    }
    const result = model.predict(allCoordinates);
    const background = Image.createFrom(this);
    for (let i = 0; i < this.size; i++) {
      background.data[i] = Math.min(this.maxValue, Math.max(0, result[i][0]));
    }
    return background;
  }

  /**
   * Dilatation is one of two fundamental operations (with erosion) in morphological
   * image processing from which all other morphological operations are based (from Wikipedia).
   * Replaces each value with it's local maximum among the pixels with a kernel value of 1.
   * http://docs.opencv.org/2.4/doc/tutorials/imgproc/erosion_dilatation/erosion_dilatation.html
   * https://en.wikipedia.org/wiki/Dilation_(morphology)
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {Array<Array<number>>} [options.kernel] - The kernel can only have ones and zeros. Default: [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
   * @param {number} [options.iterations=1] - The number of successive erosions
   * @return {Image}
   */
  function dilate(options = {}) {
    let {
      kernel = [[1, 1, 1], [1, 1, 1], [1, 1, 1]],
      iterations = 1
    } = options;
    this.checkProcessable('dilate', {
      bitDepth: [1, 8, 16],
      components: 1,
      alpha: 0
    });
    if (kernel.columns % 2 === 0 || kernel.rows % 2 === 0) {
      throw new TypeError('dilate: The number of rows and columns of the kernel must be odd');
    }
    let onlyOnes = true;
    outer: for (const row of kernel) {
      for (const value of row) {
        if (value !== 1) {
          onlyOnes = false;
          break outer;
        }
      }
    }
    let result = this;
    for (let i = 0; i < iterations; i++) {
      if (this.bitDepth === 1) {
        if (onlyOnes) {
          const newImage = result.clone();
          result = dilateOnceBinaryOnlyOnes(result, newImage, kernel.length, kernel[0].length);
        } else {
          const newImage = Image.createFrom(result);
          result = dilateOnceBinary(result, newImage, kernel);
        }
      } else if (onlyOnes) {
        const newImage = Image.createFrom(result);
        result = dilateOnceGreyOnlyOnes(result, newImage, kernel.length, kernel[0].length);
      } else {
        const newImage = Image.createFrom(result);
        result = dilateOnceGrey(result, newImage, kernel);
      }
    }
    return result;
  }
  function dilateOnceGrey(img, newImage, kernel) {
    const kernelWidth = kernel.length;
    const kernelHeight = kernel[0].length;
    let radiusX = (kernelWidth - 1) / 2;
    let radiusY = (kernelHeight - 1) / 2;
    for (let y = 0; y < img.height; y++) {
      for (let x = 0; x < img.width; x++) {
        let max = 0;
        for (let jj = 0; jj < kernelHeight; jj++) {
          for (let ii = 0; ii < kernelWidth; ii++) {
            if (kernel[ii][jj] !== 1) continue;
            let i = ii - radiusX + x;
            let j = jj - radiusY + y;
            if (i < 0 || j < 0 || i >= img.width || j >= img.height) continue;
            const value = img.getValueXY(i, j, 0);
            if (value > max) max = value;
          }
        }
        newImage.setValueXY(x, y, 0, max);
      }
    }
    return newImage;
  }
  function dilateOnceGreyOnlyOnes(img, newImage, kernelWidth, kernelHeight) {
    const radiusX = (kernelWidth - 1) / 2;
    const radiusY = (kernelHeight - 1) / 2;
    const maxList = [];
    for (let x = 0; x < img.width; x++) {
      maxList.push(0);
    }
    for (let y = 0; y < img.height; y++) {
      for (let x = 0; x < img.width; x++) {
        let max = 0;
        for (let h = Math.max(0, y - radiusY); h < Math.min(img.height, y + radiusY + 1); h++) {
          const value = img.getValueXY(x, h, 0);
          if (value > max) {
            max = value;
          }
        }
        maxList[x] = max;
      }
      for (let x = 0; x < img.width; x++) {
        let max = 0;
        for (let i = Math.max(0, x - radiusX); i < Math.min(img.width, x + radiusX + 1); i++) {
          if (maxList[i] > max) {
            max = maxList[i];
          }
        }
        newImage.setValueXY(x, y, 0, max);
      }
    }
    return newImage;
  }
  function dilateOnceBinary(img, newImage, kernel) {
    const kernelWidth = kernel.length;
    const kernelHeight = kernel[0].length;
    let radiusX = (kernelWidth - 1) / 2;
    let radiusY = (kernelHeight - 1) / 2;
    for (let y = 0; y < img.height; y++) {
      for (let x = 0; x < img.width; x++) {
        let max = 0;
        intLoop: for (let jj = 0; jj < kernelHeight; jj++) {
          for (let ii = 0; ii < kernelWidth; ii++) {
            if (kernel[ii][jj] !== 1) continue;
            let i = ii - radiusX + x;
            let j = jj - radiusY + y;
            if (j < 0 || i < 0 || i >= img.width || j >= img.height) continue;
            const value = img.getBitXY(i, j);
            if (value === 1) {
              max = 1;
              break intLoop;
            }
          }
        }
        if (max === 1) {
          newImage.setBitXY(x, y);
        }
      }
    }
    return newImage;
  }
  function dilateOnceBinaryOnlyOnes(img, newImage, kernelWidth, kernelHeight) {
    const radiusX = (kernelWidth - 1) / 2;
    const radiusY = (kernelHeight - 1) / 2;
    const maxList = [];
    for (let x = 0; x < img.width; x++) {
      maxList.push(1);
    }
    for (let y = 0; y < img.height; y++) {
      for (let x = 0; x < img.width; x++) {
        maxList[x] = 0;
        for (let h = Math.max(0, y - radiusY); h < Math.min(img.height, y + radiusY + 1); h++) {
          if (img.getBitXY(x, h) === 1) {
            maxList[x] = 1;
            break;
          }
        }
      }
      for (let x = 0; x < img.width; x++) {
        if (newImage.getBitXY(x, y) === 1) continue;
        for (let i = Math.max(0, x - radiusX); i < Math.min(img.width, x + radiusX + 1); i++) {
          if (maxList[i] === 1) {
            newImage.setBitXY(x, y);
            break;
          }
        }
      }
    }
    return newImage;
  }

  /**
   * Erosion is one of two fundamental operations (with dilatation) in morphological
   * image processing from which all other morphological operations are based (from Wikipedia).
   * Replaces each value with it's local minimum among the pixels with a kernel value of 1.
   * http://docs.opencv.org/2.4/doc/tutorials/imgproc/erosion_dilatation/erosion_dilatation.html
   * https://en.wikipedia.org/wiki/Erosion_(morphology)
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {Array<Array<number>>} [options.kernel] - The kernel can only have ones and zeros. Default: [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
   * @param {number} [options.iterations=1] - The number of successive erosions
   * @return {Image}
   */
  function erode(options = {}) {
    let {
      kernel = [[1, 1, 1], [1, 1, 1], [1, 1, 1]],
      iterations = 1
    } = options;
    this.checkProcessable('erode', {
      bitDepth: [1, 8, 16],
      components: 1,
      alpha: 0
    });
    if (kernel.columns % 2 === 0 || kernel.rows % 2 === 0) {
      throw new TypeError('erode: The number of rows and columns of the kernel must be odd');
    }
    let onlyOnes = true;
    outer: for (const row of kernel) {
      for (const value of row) {
        if (value !== 1) {
          onlyOnes = false;
          break outer;
        }
      }
    }
    let result = this;
    for (let i = 0; i < iterations; i++) {
      if (this.bitDepth === 1) {
        if (onlyOnes) {
          const newImage = result.clone();
          result = erodeOnceBinaryOnlyOnes(result, newImage, kernel.length, kernel[0].length);
        } else {
          const newImage = Image.createFrom(result);
          result = erodeOnceBinary(result, newImage, kernel);
        }
      } else if (onlyOnes) {
        const newImage = Image.createFrom(result);
        result = erodeOnceGreyOnlyOnes(result, newImage, kernel.length, kernel[0].length);
      } else {
        const newImage = Image.createFrom(result);
        result = erodeOnceGrey(result, newImage, kernel);
      }
    }
    return result;
  }
  function erodeOnceGrey(img, newImage, kernel) {
    const kernelWidth = kernel.length;
    const kernelHeight = kernel[0].length;
    let radiusX = (kernelWidth - 1) / 2;
    let radiusY = (kernelHeight - 1) / 2;
    for (let y = 0; y < img.height; y++) {
      for (let x = 0; x < img.width; x++) {
        let min = img.maxValue;
        for (let jj = 0; jj < kernelHeight; jj++) {
          for (let ii = 0; ii < kernelWidth; ii++) {
            if (kernel[ii][jj] !== 1) continue;
            let i = ii - radiusX + x;
            let j = jj - radiusY + y;
            if (i < 0 || j < 0 || i >= img.width || j >= img.height) continue;
            const value = img.getValueXY(i, j, 0);
            if (value < min) min = value;
          }
        }
        newImage.setValueXY(x, y, 0, min);
      }
    }
    return newImage;
  }
  function erodeOnceGreyOnlyOnes(img, newImage, kernelWidth, kernelHeight) {
    const radiusX = (kernelWidth - 1) / 2;
    const radiusY = (kernelHeight - 1) / 2;
    const minList = [];
    for (let x = 0; x < img.width; x++) {
      minList.push(0);
    }
    for (let y = 0; y < img.height; y++) {
      for (let x = 0; x < img.width; x++) {
        let min = img.maxValue;
        for (let h = Math.max(0, y - radiusY); h < Math.min(img.height, y + radiusY + 1); h++) {
          const value = img.getValueXY(x, h, 0);
          if (value < min) {
            min = value;
          }
        }
        minList[x] = min;
      }
      for (let x = 0; x < img.width; x++) {
        let min = img.maxValue;
        for (let i = Math.max(0, x - radiusX); i < Math.min(img.width, x + radiusX + 1); i++) {
          if (minList[i] < min) {
            min = minList[i];
          }
        }
        newImage.setValueXY(x, y, 0, min);
      }
    }
    return newImage;
  }
  function erodeOnceBinary(img, newImage, kernel) {
    const kernelWidth = kernel.length;
    const kernelHeight = kernel[0].length;
    let radiusX = (kernelWidth - 1) / 2;
    let radiusY = (kernelHeight - 1) / 2;
    for (let y = 0; y < img.height; y++) {
      for (let x = 0; x < img.width; x++) {
        let min = 1;
        intLoop: for (let jj = 0; jj < kernelHeight; jj++) {
          for (let ii = 0; ii < kernelWidth; ii++) {
            if (kernel[ii][jj] !== 1) continue;
            let i = ii - radiusX + x;
            let j = jj - radiusY + y;
            if (j < 0 || i < 0 || i >= img.width || j >= img.height) continue;
            const value = img.getBitXY(i, j);
            if (value === 0) {
              min = 0;
              break intLoop;
            }
          }
        }
        if (min === 1) {
          newImage.setBitXY(x, y);
        }
      }
    }
    return newImage;
  }
  function erodeOnceBinaryOnlyOnes(img, newImage, kernelWidth, kernelHeight) {
    const radiusX = (kernelWidth - 1) / 2;
    const radiusY = (kernelHeight - 1) / 2;
    const minList = [];
    for (let x = 0; x < img.width; x++) {
      minList.push(0);
    }
    for (let y = 0; y < img.height; y++) {
      for (let x = 0; x < img.width; x++) {
        minList[x] = 1;
        for (let h = Math.max(0, y - radiusY); h < Math.min(img.height, y + radiusY + 1); h++) {
          if (img.getBitXY(x, h) === 0) {
            minList[x] = 0;
            break;
          }
        }
      }
      for (let x = 0; x < img.width; x++) {
        if (newImage.getBitXY(x, y) === 0) continue;
        for (let i = Math.max(0, x - radiusX); i < Math.min(img.width, x + radiusX + 1); i++) {
          if (minList[i] === 0) {
            newImage.clearBitXY(x, y);
            break;
          }
        }
      }
    }
    return newImage;
  }

  /**
   * In mathematical morphology, opening is the dilation of the erosion of a set A by a structuring element B.
   * Together with closing, the opening serves in computer vision and image processing as a basic workhorse of morphological noise removal.
   * Opening removes small objects from the foreground (usually taken as the bright pixels) of an image,
   * placing them in the background, while closing removes small holes in the foreground, changing small islands of background into foreground. (Wikipedia)
   * http://docs.opencv.org/2.4/doc/tutorials/imgproc/opening_closing_hats/opening_closing_hats.html
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {Array<Array<number>>} [options.kernel] - The kernel can only have ones and zeros. Default: [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
   * @param {number} [options.iterations=1] - Number of iterations of the morphological transform
   * @return {Image}
   */
  function open(options = {}) {
    let {
      kernel = [[1, 1, 1], [1, 1, 1], [1, 1, 1]],
      iterations = 1
    } = options;
    this.checkProcessable('open', {
      bitDepth: [8, 16],
      components: 1,
      alpha: 0
    });
    if (kernel.columns % 2 === 0 || kernel.rows % 2 === 0) {
      throw new TypeError('open: The number of rows and columns of the kernel must be odd');
    }
    let newImage = this;
    for (let i = 0; i < iterations; i++) {
      newImage = newImage.erode({
        kernel
      });
      newImage = newImage.dilate({
        kernel
      });
    }
    return newImage;
  }

  /**
   * In mathematical morphology, the closing of a set A by a structuring element B is the erosion of the dilation of that set (Wikipedia).
   * In image processing, closing is, together with opening, the basic workhorse of morphological noise removal.
   * Opening removes small objects, while closing removes small holes.
   * http://docs.opencv.org/2.4/doc/tutorials/imgproc/opening_closing_hats/opening_closing_hats.html
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {Array<Array<number>>} [options.kernel] - The kernel can only have ones and zeros. Default: [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
   * @param {number} [options.iterations=1] - Number of iterations of the morphological transform
   * @return {Image}
   */
  function close(options = {}) {
    let {
      kernel = [[1, 1, 1], [1, 1, 1], [1, 1, 1]],
      iterations = 1
    } = options;
    this.checkProcessable('close', {
      bitDepth: [1, 8, 16],
      components: 1,
      alpha: 0
    });
    if (kernel.columns % 2 === 0 || kernel.rows % 2 === 0) {
      throw new TypeError('close: The number of rows and columns of the kernel must be odd');
    }
    let newImage = this;
    for (let i = 0; i < iterations; i++) {
      newImage = newImage.dilate({
        kernel
      }).erode({
        kernel
      });
    }
    return newImage;
  }

  /**
   * This function is the white top hat (also called top hat). In mathematical morphology and digital image processing,
   * top-hat transform is an operation that extracts small elements and details from given images.
   * The white top-hat transform is defined as the difference between the input image and its opening by some structuring element.
   * Top-hat transforms are used for various image processing tasks, such as feature extraction, background equalization, image enhancement, and others. (Wikipedia)
   * http://docs.opencv.org/2.4/doc/tutorials/imgproc/opening_closing_hats/opening_closing_hats.html
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {Array<Array<number>>} [options.kernel] - The kernel can only have ones and zeros. Default: [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
   * @param {number} [options.iterations=1] - Number of iterations of the morphological transform
   * @return {Image}
   */
  function topHat(options = {}) {
    let {
      kernel = [[1, 1, 1], [1, 1, 1], [1, 1, 1]],
      iterations = 1
    } = options;
    this.checkProcessable('topHat', {
      bitDepth: [8, 16],
      components: 1,
      alpha: 0
    });
    if (kernel.length % 2 === 0 || kernel[0].length % 2 === 0) {
      throw new TypeError('topHat: The number of rows and columns of the kernel must be odd');
    }
    let newImage = this;
    for (let i = 0; i < iterations; i++) {
      let openImage = newImage.open({
        kernel
      });
      newImage = openImage.subtractImage(newImage, {
        absolute: true
      });
    }
    return newImage;
  }

  /**
   * This function is the black top hat (also called black hat).
   * In mathematical morphology and digital image processing,
   * top-hat transform is an operation that extracts small elements and details from given images.
   * The black top-hat transform is defined dually as the difference between the closed and the input image.
   * Top-hat transforms are used for various image processing tasks, such as feature extraction, background equalization,
   * image enhancement, and others. (Wikipedia)
   * http://docs.opencv.org/2.4/doc/tutorials/imgproc/opening_closing_hats/opening_closing_hats.html
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {Array<Array<number>>} [options.kernel] - The kernel can only have ones and zeros. Default: [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
   * @param {number} [options.iterations=1] - Number of iterations of the morphological transform
   * @return {Image}
   */
  function blackHat(options = {}) {
    let {
      kernel = [[1, 1, 1], [1, 1, 1], [1, 1, 1]],
      iterations = 1
    } = options;
    this.checkProcessable('blackHat', {
      bitDepth: [8, 16],
      components: 1,
      alpha: 0
    });
    if (kernel.columns % 2 === 0 || kernel.rows % 2 === 0) {
      throw new TypeError('blackHat: The number of rows and columns of the kernel must be odd');
    }
    let newImage = this;
    for (let i = 0; i < iterations; i++) {
      const closeImage = newImage.close({
        kernel
      });
      newImage = closeImage.subtractImage(newImage, {
        absolute: true
      });
    }
    return newImage;
  }

  /**
   * In mathematical morphology and digital image processing, a morphological gradient is the difference between the dilation and the erosion of a given image. It is an image where each pixel value (typically non-negative) indicates the contrast intensity in the close neighborhood of that pixel. It is useful for edge detection and segmentation applications.
   * http://docs.opencv.org/2.4/doc/tutorials/imgproc/opening_closing_hats/opening_closing_hats.html
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {Array<Array<number>>} [options.kernel] - The kernel can only have ones and zeros. Default: [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
   * @param {number} [options.iterations=1] - Number of iterations of the morphological transform
   * @return {Image}
   */
  function morphologicalGradient(options = {}) {
    let {
      kernel = [[1, 1, 1], [1, 1, 1], [1, 1, 1]],
      iterations = 1
    } = options;
    this.checkProcessable('morphologicalGradient', {
      bitDepth: [8, 16],
      components: 1,
      alpha: 0
    });
    if (kernel.columns % 2 === 0 || kernel.rows % 2 === 0) {
      throw new TypeError('morphologicalGradient: The number of rows and columns of the kernel must be odd');
    }
    let newImage = this;
    for (let i = 0; i < iterations; i++) {
      let dilatedImage = newImage.dilate({
        kernel
      });
      let erodedImage = newImage.erode({
        kernel
      });
      newImage = dilatedImage.subtractImage(erodedImage, {
        absolute: true
      });
    }
    return newImage;
  }

  // REFERENCES :
  // https://stackoverflow.com/questions/38285229/calculating-aspect-ratio-of-perspective-transform-destination-image/38402378#38402378
  // http://www.corrmap.com/features/homography_transformation.php
  // https://ags.cs.uni-kl.de/fileadmin/inf_ags/3dcv-ws11-12/3DCV_WS11-12_lec04.pdf
  // http://graphics.cs.cmu.edu/courses/15-463/2011_fall/Lectures/morphing.pdf

  function order4Points(pts) {
    let tl = 0;
    let tr = 0;
    let br = 0;
    let bl = 0;
    let minX = pts[0][0];
    let indexMinX = 0;
    for (let i = 1; i < pts.length; i++) {
      if (pts[i][0] < minX) {
        minX = pts[i][0];
        indexMinX = i;
      }
    }
    let minX2 = pts[(indexMinX + 1) % pts.length][0];
    let indexMinX2 = (indexMinX + 1) % pts.length;
    for (let i = 1; i < pts.length; i++) {
      if (pts[i][0] < minX2 && i !== indexMinX) {
        minX2 = pts[i][0];
        indexMinX2 = i;
      }
    }
    if (pts[indexMinX2][1] < pts[indexMinX][1]) {
      tl = pts[indexMinX2];
      bl = pts[indexMinX];
      if (indexMinX !== (indexMinX2 + 1) % 4) {
        tr = pts[(indexMinX2 + 1) % 4];
        br = pts[(indexMinX2 + 2) % 4];
      } else {
        tr = pts[(indexMinX2 + 2) % 4];
        br = pts[(indexMinX2 + 3) % 4];
      }
    } else {
      bl = pts[indexMinX2];
      tl = pts[indexMinX];
      if (indexMinX2 !== (indexMinX + 1) % 4) {
        tr = pts[(indexMinX + 1) % 4];
        br = pts[(indexMinX + 2) % 4];
      } else {
        tr = pts[(indexMinX + 2) % 4];
        br = pts[(indexMinX + 3) % 4];
      }
    }
    return [tl, tr, br, bl];
  }
  function distance2Points(p1, p2) {
    return Math.sqrt(Math.pow(p1[0] - p2[0], 2) + Math.pow(p1[1] - p2[1], 2));
  }
  function crossVect(u, v) {
    let result = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
    return result;
  }
  function dotVect(u, v) {
    let result = u[0] * v[0] + u[1] * v[1] + u[2] * v[2];
    return result;
  }
  function computeWidthAndHeigth(tl, tr, br, bl, widthImage, heightImage) {
    let w = Math.max(distance2Points(tl, tr), distance2Points(bl, br));
    let h = Math.max(distance2Points(tl, bl), distance2Points(tr, br));
    let finalW = 0;
    let finalH = 0;
    let u0 = Math.ceil(widthImage / 2);
    let v0 = Math.ceil(heightImage / 2);
    let arVis = w / h;
    let m1 = [tl[0], tl[1], 1];
    let m2 = [tr[0], tr[1], 1];
    let m3 = [bl[0], bl[1], 1];
    let m4 = [br[0], br[1], 1];
    let k2 = dotVect(crossVect(m1, m4), m3) / dotVect(crossVect(m2, m4), m3);
    let k3 = dotVect(crossVect(m1, m4), m2) / dotVect(crossVect(m3, m4), m2);
    let n2 = [k2 * m2[0] - m1[0], k2 * m2[1] - m1[1], k2 * m2[2] - m1[2]];
    let n3 = [k3 * m3[0] - m1[0], k3 * m3[1] - m1[1], k3 * m3[2] - m1[2]];
    let n21 = n2[0];
    let n22 = n2[1];
    let n23 = n2[2];
    let n31 = n3[0];
    let n32 = n3[1];
    let n33 = n3[2];
    let f = 1.0 / (n23 * n33) * (n21 * n31 - (n21 * n33 + n23 * n31) * u0 + n23 * n33 * u0 * u0 + (n22 * n32 - (n22 * n33 + n23 * n32) * v0 + n23 * n33 * v0 * v0));
    if (f >= 0) {
      f = Math.sqrt(f);
    } else {
      f = Math.sqrt(-f);
    }
    let A = new Matrix$2([[f, 0, u0], [0, f, v0], [0, 0, 1]]);
    let At = A.transpose();
    let Ati = inverse(At);
    let Ai = inverse(A);
    let n2R = Matrix$2.rowVector(n2);
    let n3R = Matrix$2.rowVector(n3);
    let arReal = Math.sqrt(dotVect(n2R.mmul(Ati).mmul(Ai).to1DArray(), n2) / dotVect(n3R.mmul(Ati).mmul(Ai).to1DArray(), n3));
    if (arReal === 0 || arVis === 0) {
      finalW = Math.ceil(w);
      finalH = Math.ceil(h);
    } else if (arReal < arVis) {
      finalW = Math.ceil(w);
      finalH = Math.ceil(finalW / arReal);
    } else {
      finalH = Math.ceil(h);
      finalW = Math.ceil(arReal * finalH);
    }
    return [finalW, finalH];
  }
  function projectionPoint(x, y, a, b, c, d, e, f, g, h, image, channel) {
    let [newX, newY] = [(a * x + b * y + c) / (g * x + h * y + 1), (d * x + e * y + f) / (g * x + h * y + 1)];
    return image.getValueXY(Math.floor(newX), Math.floor(newY), channel);
  }

  /**
   * Transform a quadrilateral into a rectangle
   * @memberof Image
   * @instance
   * @param {Array<Array<number>>} [pts] - Array of the four corners.
   * @param {object} [options]
   * @param {boolean} [options.calculateRatio=true] - true if you want to calculate the aspect ratio "width x height" by taking the perspectiv into consideration.
   * @return {Image} The new image, which is a rectangle
   * @example
   * var cropped = image.warpingFourPoints({
   *   pts: [[0,0], [100, 0], [80, 50], [10, 50]]
   * });
   */

  function warpingFourPoints(pts, options = {}) {
    let {
      calculateRatio = true
    } = options;
    if (pts.length !== 4) {
      throw new Error(`The array pts must have four elements, which are the four corners. Currently, pts have ${pts.length} elements`);
    }
    let [pt1, pt2, pt3, pt4] = pts;
    let quadrilaterial = [pt1, pt2, pt3, pt4];
    let [tl, tr, br, bl] = order4Points(quadrilaterial);
    let widthRect;
    let heightRect;
    if (calculateRatio) {
      [widthRect, heightRect] = computeWidthAndHeigth(tl, tr, br, bl, this.width, this.height);
    } else {
      widthRect = Math.ceil(Math.max(distance2Points(tl, tr), distance2Points(bl, br)));
      heightRect = Math.ceil(Math.max(distance2Points(tl, bl), distance2Points(tr, br)));
    }
    let newImage = Image.createFrom(this, {
      width: widthRect,
      height: heightRect
    });
    let [X1, Y1] = tl;
    let [X2, Y2] = tr;
    let [X3, Y3] = br;
    let [X4, Y4] = bl;
    let [x1, y1] = [0, 0];
    let [x2, y2] = [0, widthRect - 1];
    let [x3, y3] = [heightRect - 1, widthRect - 1];
    let [x4, y4] = [heightRect - 1, 0];
    let S = new Matrix$2([[x1, y1, 1, 0, 0, 0, -x1 * X1, -y1 * X1], [x2, y2, 1, 0, 0, 0, -x2 * X2, -y2 * X2], [x3, y3, 1, 0, 0, 0, -x3 * X3, -y1 * X3], [x4, y4, 1, 0, 0, 0, -x4 * X4, -y4 * X4], [0, 0, 0, x1, y1, 1, -x1 * Y1, -y1 * Y1], [0, 0, 0, x2, y2, 1, -x2 * Y2, -y2 * Y2], [0, 0, 0, x3, y3, 1, -x3 * Y3, -y3 * Y3], [0, 0, 0, x4, y4, 1, -x4 * Y4, -y4 * Y4]]);
    let D = Matrix$2.columnVector([X1, X2, X3, X4, Y1, Y2, Y3, Y4]);
    let svd = new SingularValueDecomposition(S);
    let T = svd.solve(D); // solve S*T = D
    let [a, b, c, d, e, f, g, h] = T.to1DArray();
    let Xt = new Matrix$2(heightRect, widthRect);
    for (let channel = 0; channel < this.channels; channel++) {
      for (let i = 0; i < heightRect; i++) {
        for (let j = 0; j < widthRect; j++) {
          Xt.set(i, j, projectionPoint(i, j, a, b, c, d, e, f, g, h, this, channel));
        }
      }
      newImage.setMatrix(Xt, {
        channel: channel
      });
    }
    return newImage;
  }

  /**
   * Crops the image
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {number} [options.x=0] - x coordinate to place the zero of the new image
   * @param {number} [options.y=0] - y coordinate to place the zero of the new image
   * @param {number} [options.width=this.width-x] - width of the new image
   * @param {number} [options.height=this.height-y] - height of the new image
   * @return {Image} The new cropped image
   * @example
   * var cropped = image.crop({
   *   x:0,
   *   y:0
   * });
   */
  function crop(options = {}) {
    let {
      x = 0,
      y = 0,
      width = this.width - x,
      height = this.height - y
    } = options;
    this.checkProcessable('crop', {
      bitDepth: [1, 8, 16]
    });
    x = Math.round(x);
    y = Math.round(y);
    width = Math.round(width);
    height = Math.round(height);
    if (x > this.width - 1 || y > this.height - 1) {
      throw new RangeError(`crop: origin (x:${x}, y:${y}) out of range (${this.width - 1}; ${this.height - 1})`);
    }
    if (width <= 0 || height <= 0) {
      throw new RangeError(`crop: width and height (width:${width}; height:${height}) must be positive numbers`);
    }
    if (x < 0 || y < 0) {
      throw new RangeError(`crop: x and y (x:${x}, y:${y}) must be positive numbers`);
    }
    if (width > this.width - x || height > this.height - y) {
      throw new RangeError(`crop: (x: ${x}, y:${y}, width:${width}, height:${height}) size is out of range`);
    }
    let result = this;
    if (this.bitDepth === 1) {
      const newImage = new Image(width, height, {
        kind: 'BINARY',
        parent: this
      });
      result = cropBinary(this, newImage, x, y, width, height);
    } else {
      const newImage = Image.createFrom(this, {
        width,
        height,
        position: [x, y]
      });
      result = cropDefault(this, newImage, x, y, width, height);
    }
    return result;
  }
  function cropDefault(img, newImage, x, y, width, height) {
    let xWidth = width * img.channels;
    let y1 = y + height;
    let ptr = 0; // pointer for new array

    let jLeft = x * img.channels;
    for (let i = y; i < y1; i++) {
      let j = i * img.width * img.channels + jLeft;
      let jL = j + xWidth;
      for (; j < jL; j++) {
        newImage.data[ptr++] = img.data[j];
      }
    }
    return newImage;
  }
  function cropBinary(img, newImage, x, y, width, height) {
    let xWidth = width * img.channels;
    let y1 = y + height;
    let ptr = 0; // pointer for new array

    let jLeft = x * img.channels;
    for (let i = y; i < y1; i++) {
      let j = i * img.width * img.channels + jLeft;
      let jL = j + xWidth;
      for (; j < jL; j++) {
        if (img.getBit(j)) {
          newImage.setBit(ptr);
        }
        ++ptr;
      }
    }
    return newImage;
  }

  /**
   * Crops the image based on the alpha channel
   * This removes lines and columns where the alpha channel is lower than a threshold value.
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {number} [options.threshold=this.maxValue]
   * @return {Image}
   */
  function cropAlpha(options = {}) {
    this.checkProcessable('cropAlpha', {
      alpha: 1
    });
    const {
      threshold = this.maxValue
    } = options;
    let left = findLeft(this, threshold, this.components);
    if (left === -1) {
      throw new Error('Could not find new dimensions. Threshold may be too high.');
    }
    let top = findTop(this, threshold, this.components, left);
    let bottom = findBottom(this, threshold, this.components, left);
    let right = findRight(this, threshold, this.components, left, top, bottom);
    return this.crop({
      x: left,
      y: top,
      width: right - left + 1,
      height: bottom - top + 1
    });
  }
  function findLeft(image, threshold, channel) {
    for (let x = 0; x < image.width; x++) {
      for (let y = 0; y < image.height; y++) {
        if (image.getValueXY(x, y, channel) >= threshold) {
          return x;
        }
      }
    }
    return -1;
  }
  function findTop(image, threshold, channel, left) {
    for (let y = 0; y < image.height; y++) {
      for (let x = left; x < image.width; x++) {
        if (image.getValueXY(x, y, channel) >= threshold) {
          return y;
        }
      }
    }
    return -1;
  }
  function findBottom(image, threshold, channel, left) {
    for (let y = image.height - 1; y >= 0; y--) {
      for (let x = left; x < image.width; x++) {
        if (image.getValueXY(x, y, channel) >= threshold) {
          return y;
        }
      }
    }
    return -1;
  }
  function findRight(image, threshold, channel, left, top, bottom) {
    for (let x = image.width - 1; x >= left; x--) {
      for (let y = top; y <= bottom; y++) {
        if (image.getValueXY(x, y, channel) >= threshold) {
          return x;
        }
      }
    }
    return -1;
  }

  /**
   * Converts a factor value to a number between 0 and 1
   * @private
   * @param {string|number} value
   * @return {number}
   */
  function getFactor(value) {
    if (typeof value === 'string') {
      const last = value[value.length - 1];
      value = parseFloat(value);
      if (last === '%') {
        value /= 100;
      }
    }
    return value;
  }

  /**
   * We can specify a threshold as "0.4", "40%" or 123
   * @private
   * @param {string|number} value
   * @param {number} maxValue
   * @return {number}
   */
  function getThreshold$1(value, maxValue) {
    if (!maxValue) {
      throw Error('getThreshold : the maxValue should be specified');
    }
    if (typeof value === 'string') {
      let last = value[value.length - 1];
      if (last !== '%') {
        throw Error('getThreshold : if the value is a string it must finish by %');
      }
      return parseFloat(value) / 100 * maxValue;
    } else if (typeof value === 'number') {
      if (value < 1) {
        return value * maxValue;
      }
      return value;
    } else {
      throw Error('getThreshold : the value is not valid');
    }
  }
  function factorDimensions(factor, width, height) {
    factor = getFactor(factor);
    let newWidth = Math.round(factor * width);
    let newHeight = Math.round(factor * height);
    if (newWidth <= 0) {
      newWidth = 1;
    }
    if (newHeight <= 0) {
      newHeight = 1;
    }
    return {
      width: newWidth,
      height: newHeight
    };
  }

  function checkRow(image, row) {
    if (row < 0 || row >= image.height) {
      throw new RangeError(`row must be included between 0 and ${image.height - 1}. Current value: ${row}`);
    }
  }
  function checkColumn(image, column) {
    if (column < 0 || column >= image.width) {
      throw new RangeError(`column must be included between 0 and ${image.width - 1}. Current value: ${column}`);
    }
  }
  function checkChannel(image, channel) {
    if (channel < 0 || channel >= image.channels) {
      throw new RangeError(`channel must be included between 0 and ${image.channels - 1}. Current value: ${channel}`);
    }
  }

  /**
   * @typedef {('nearestNeighbor'|'bilinear')} InterpolationAlgorithm
   */
  const validInterpolations = {
    nearestneighbor: 'nearestNeighbor',
    nearestneighbour: 'nearestNeighbor',
    bilinear: 'bilinear'
  };
  function checkInterpolation(interpolation) {
    if (typeof interpolation !== 'string') {
      throw new TypeError('interpolation must be a string');
    }
    interpolation = interpolation.toLowerCase();
    if (!validInterpolations[interpolation]) {
      throw new RangeError(`invalid interpolation algorithm: ${interpolation}`);
    }
    return validInterpolations[interpolation];
  }

  /**
   * Nearest neighbor resizing algorithm
   * @private
   * @param {Image} newImage
   * @param {number} newWidth
   * @param {number} newHeight
   */
  function nearestNeighbor(newImage, newWidth, newHeight) {
    const wRatio = this.width / newWidth;
    const hRatio = this.height / newHeight;
    if (this.bitDepth > 1) {
      for (let i = 0; i < newWidth; i++) {
        const w = Math.floor((i + 0.5) * wRatio);
        for (let j = 0; j < newHeight; j++) {
          const h = Math.floor((j + 0.5) * hRatio);
          for (let c = 0; c < this.channels; c++) {
            newImage.setValueXY(i, j, c, this.getValueXY(w, h, c));
          }
        }
      }
    } else {
      for (let i = 0; i < newWidth; i++) {
        const w = Math.floor((i + 0.5) * wRatio);
        for (let j = 0; j < newHeight; j++) {
          const h = Math.floor((j + 0.5) * hRatio);
          if (this.getBitXY(w, h)) {
            newImage.setBitXY(i, j);
          }
        }
      }
    }
  }

  /**
   * Resize an image
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {number} [options.width=this.width] - new width
   * @param {number} [options.height=this.height] - new height
   * @param {number} [options.factor=1] - scaling factor (applied to the new width and height values)
   * @param {InterpolationAlgorithm} [options.interpolation='nearestNeighbor']
   * @param {boolean} [options.preserveAspectRatio=true] - preserve width/height ratio if only one of them is defined
   * @return {Image}
   */
  function resize(options = {}) {
    const {
      factor = 1,
      interpolation = validInterpolations.nearestneighbor,
      preserveAspectRatio = true
    } = options;
    const interpolationToUse = checkInterpolation(interpolation);
    let width = options.width;
    let height = options.height;
    if (!width) {
      if (height && preserveAspectRatio) {
        width = Math.round(height * (this.width / this.height));
      } else {
        width = this.width;
      }
    }
    if (!height) {
      if (preserveAspectRatio) {
        height = Math.round(width * (this.height / this.width));
      } else {
        height = this.height;
      }
    }
    ({
      width,
      height
    } = factorDimensions(factor, width, height));
    if (width === this.width && height === this.height) {
      const newImage = this.clone();
      newImage.position = [0, 0];
      return newImage;
    }
    let shiftX = Math.round((this.width - width) / 2);
    let shiftY = Math.round((this.height - height) / 2);
    const newImage = Image.createFrom(this, {
      width,
      height,
      position: [shiftX, shiftY]
    });
    switch (interpolationToUse) {
      case validInterpolations.nearestneighbor:
        nearestNeighbor.call(this, newImage, width, height);
        break;
      default:
        throw new Error(`unsupported resize interpolation: ${interpolationToUse}`);
    }
    return newImage;
  }

  // based on https://bgrins.github.io/TinyColor/docs/tinycolor.html


  /**
   * Make a copy of the current image and convert the color model to HSV
   * The source image has to be RGB !
   * @memberof Image
   * @instance
   * @return {Image} - New image in HSV color model
   * @example
   * var hsvImage = image.hsv();
   * // we can create one image per channel
   * var channels = hsvImage.split();
   */
  function hsv() {
    this.checkProcessable('hsv', {
      bitDepth: [8, 16],
      alpha: [0, 1],
      colorModel: [RGB$1]
    });
    let newImage = Image.createFrom(this, {
      colorModel: HSV
    });
    let ptr = 0;
    let data = this.data;
    for (let i = 0; i < data.length; i += this.channels) {
      let red = data[i];
      let green = data[i + 1];
      let blue = data[i + 2];
      let min = Math.min(red, green, blue);
      let max = Math.max(red, green, blue);
      let delta = max - min;
      let hue = 0;
      let saturation = max === 0 ? 0 : delta / max;
      let value = max;
      if (max !== min) {
        switch (max) {
          case red:
            hue = (green - blue) / delta + (green < blue ? 6 : 0);
            break;
          case green:
            hue = (blue - red) / delta + 2;
            break;
          case blue:
            hue = (red - green) / delta + 4;
            break;
          default:
            throw new Error('unreachable');
        }
        hue /= 6;
      }
      newImage.data[ptr++] = hue * this.maxValue;
      newImage.data[ptr++] = saturation * this.maxValue;
      newImage.data[ptr++] = value;
      if (this.alpha) {
        newImage.data[ptr++] = data[i + 3];
      }
    }
    return newImage;
  }

  // http://www.easyrgb.com/index.php?X=MATH&H=18#text18
  // check rgbToHsl : https://bgrins.github.io/TinyColor/docs/tinycolor.html


  /**
   * Make a copy of the current image and convert the color model to HSL
   * The source image has to be RGB !
   * @memberof Image
   * @instance
   * @return {Image} - New image in HSL color model
   * @example
   * var hslImage = image.hsl();
   * // we can create one image per channel
   * var channels = hslImage.split();
   */
  function hsl$1() {
    this.checkProcessable('hsl', {
      bitDepth: [8, 16],
      alpha: [0, 1],
      colorModel: [RGB$1]
    });
    let newImage = Image.createFrom(this, {
      colorModel: HSL
    });
    let threshold = Math.floor(this.maxValue / 2);
    let ptr = 0;
    let data = this.data;
    for (let i = 0; i < data.length; i += this.channels) {
      let red = data[i];
      let green = data[i + 1];
      let blue = data[i + 2];
      let max = Math.max(red, green, blue);
      let min = Math.min(red, green, blue);
      let hue = 0;
      let saturation = 0;
      let luminance = (max + min) / 2;
      if (max !== min) {
        let delta = max - min;
        saturation = luminance > threshold ? delta / (2 - max - min) : delta / (max + min);
        switch (max) {
          case red:
            hue = (green - blue) / delta + (green < blue ? 6 : 0);
            break;
          case green:
            hue = (blue - red) / delta + 2;
            break;
          case blue:
            hue = (red - green) / delta + 4;
            break;
          default:
            throw new Error('unreachable');
        }
        hue /= 6;
      }
      newImage.data[ptr++] = hue * this.maxValue;
      newImage.data[ptr++] = saturation * this.maxValue;
      newImage.data[ptr++] = luminance;
      if (this.alpha) {
        newImage.data[ptr++] = data[i + 3];
      }
    }
    return newImage;
  }

  // http://www.easyrgb.com/index.php?X=MATH&H=18#text18
  // check rgbToHsl : https://bgrins.github.io/TinyColor/docs/tinycolor.html


  /**
   * Make a copy of the current image and convert the color model to CMYK
   * The source image has to be RGB !
   * @memberof Image
   * @instance
   * @return {Image} - New image in CMYK color model
   * @example
   * var cmykImage = image.cmyk();
   * // we can create one image per channel
   * var channels = cmykImage.split();
   */
  function cmyk() {
    this.checkProcessable('cmyk', {
      bitDepth: [8, 16],
      alpha: [0, 1],
      colorModel: [RGB$1]
    });
    let newImage = Image.createFrom(this, {
      components: 4,
      colorModel: CMYK$1
    });
    let ptr = 0;
    let data = this.data;
    for (let i = 0; i < data.length; i += this.channels) {
      let red = data[i];
      let green = data[i + 1];
      let blue = data[i + 2];
      let black = Math.min(this.maxValue - red, this.maxValue - green, this.maxValue - blue);
      let cyan = (this.maxValue - red - black) / (1 - black / this.maxValue);
      let magenta = (this.maxValue - green - black) / (1 - black / this.maxValue);
      let yellow = (this.maxValue - blue - black) / (1 - black / this.maxValue);
      newImage.data[ptr++] = Math.round(cyan);
      newImage.data[ptr++] = Math.round(magenta);
      newImage.data[ptr++] = Math.round(yellow);
      newImage.data[ptr++] = Math.round(black);
      if (this.alpha) {
        newImage.data[ptr++] = data[i + 3];
      }
    }
    return newImage;
  }

  /**
   * Make a copy of the current image and convert to RGBA 8 bits
   * Those images are the one that are displayed in a canvas.
   * RGB model in 8 bits per channel and containing as well an alpha channel.
   * The source image may be:
   * * a mask (binary image)
   * * a grey image (8, 16 or 32 bits) with or without alpha channel
   * * a color image (8, 16 or 32 bits) with or without alpha channel in with RGB model
   * * when the image is 32 bits, a rescaling is performed from the min and max values
   * * to map values from 0 to 255
   * The conversion is based on {@link Image#getRGBAData}.
   * @memberof Image
   * @instance
   * @return {Image} - New image in RGB color model with alpha channel
   * @example
   * var rgbaImage = image.rgba8();
   */
  function rgba8() {
    return new Image(this.width, this.height, this.getRGBAData(), {
      kind: 'RGBA',
      parent: this
    });
  }

  /**
   * @typedef {('luma709'|'luma601'|'maximum'|'minimum'|'average'|'minmax'|'red'|'green'|'blue'|'cyan'|'magenta'|'yellow'|'black'|'hue'|'saturation'|'lightness')} GreyAlgorithm
   */

  const methods$1 = {
    luma709(red, green, blue) {
      // sRGB
      // return red * 0.2126 + green * 0.7152 + blue * 0.0722;
      // Let's do a little trick ... in order not convert the integer to a double we do
      // the multiplication with integer to reach a total of 32768 and then shift the bits
      // of 15 to the right
      // This does a Math.floor and may lead to small (max 1) difference
      // Same result, > 10% faster on the full grey conversion
      return red * 6966 + green * 23436 + blue * 2366 >> 15;
    },
    luma601(red, green, blue) {
      // NTSC
      // return this.red * 0.299 + green * 0.587 + blue * 0.114;
      return red * 9798 + green * 19235 + blue * 3735 >> 15;
    },
    maximum(red, green, blue) {
      return Math.max(red, green, blue);
    },
    minimum(red, green, blue) {
      return Math.min(red, green, blue);
    },
    average(red, green, blue) {
      return (red + green + blue) / 3 >> 0;
    },
    minmax(red, green, blue) {
      return (Math.max(red, green, blue) + Math.min(red, green, blue)) / 2;
    },
    red(red) {
      return red;
    },
    green(red, green) {
      return green;
    },
    blue(red, green, blue) {
      return blue;
    },
    cyan(red, green, blue, image) {
      let black = methods$1.black(red, green, blue, image);
      return (image.maxValue - red - black) / (1 - black / image.maxValue) >> 0;
    },
    magenta(red, green, blue, image) {
      let black = methods$1.black(red, green, blue, image);
      return (image.maxValue - green - black) / (1 - black / image.maxValue) >> 0;
    },
    yellow(red, green, blue, image) {
      let black = methods$1.black(red, green, blue, image);
      return (image.maxValue - blue - black) / (1 - black / image.maxValue) >> 0;
    },
    black(red, green, blue, image) {
      return Math.min(image.maxValue - red, image.maxValue - green, image.maxValue - blue);
    },
    hue(red, green, blue, image) {
      let min = methods$1.min(red, green, blue);
      let max = methods$1.max(red, green, blue);
      if (max === min) {
        return 0;
      }
      let hue = 0;
      let delta = max - min;
      switch (max) {
        case red:
          hue = (green - blue) / delta + (green < blue ? 6 : 0);
          break;
        case green:
          hue = (blue - red) / delta + 2;
          break;
        case blue:
          hue = (red - green) / delta + 4;
          break;
        default:
          throw new Error('unreachable');
      }
      return hue / 6 * image.maxValue >> 0;
    },
    saturation(red, green, blue, image) {
      // from HSV model
      let min = methods$1.min(red, green, blue);
      let max = methods$1.max(red, green, blue);
      let delta = max - min;
      return max === 0 ? 0 : delta / max * image.maxValue;
    },
    lightness(red, green, blue) {
      let min = methods$1.min(red, green, blue);
      let max = methods$1.max(red, green, blue);
      return (max + min) / 2;
    }
  };
  Object.defineProperty(methods$1, 'luminosity', {
    enumerable: false,
    value: methods$1.lightness
  });
  Object.defineProperty(methods$1, 'luminance', {
    enumerable: false,
    value: methods$1.lightness
  });
  Object.defineProperty(methods$1, 'min', {
    enumerable: false,
    value: methods$1.minimum
  });
  Object.defineProperty(methods$1, 'max', {
    enumerable: false,
    value: methods$1.maximum
  });
  Object.defineProperty(methods$1, 'brightness', {
    enumerable: false,
    value: methods$1.maximum
  });
  const names$1 = {};
  Object.keys(methods$1).forEach(name => {
    names$1[name] = name;
  });

  /**
   * Call back that converts the RGB channels to grey. It will be clamped after.
   * @callback GreyAlgorithmCallback
   * @param {number} red - value of the red channel
   * @param {number} green - value of the green channel
   * @param {number} blue - value of the blue channel
   * @return {number} value of the grey channel
   */

  /**
   * Converts the current image to greyscale.
   * The source image has to be RGB.
   * If there is an alpha channel we need to decide what to do:
   * * keepAlpha : we will keep the alpha channel and you will get a GREY / A image
   * * mergeAlpha : we will multiply each pixel of the image by the alpha
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {GreyAlgorithm|GreyAlgorithmCallback} [options.algorithm='luma709'] - Algorithm to get the grey value from RGB values
   * @param {boolean} [options.keepAlpha=false] - If true, the RGB values are treated
   *          separately from the alpha channel and the method returns a GREYA image.
   * @param {boolean} [options.mergeAlpha=true] - If true, the alpha channel will be used to scale the grey pixel.
   * @param {Image} [options.out]
   * @return {Image}
   */
  function grey(options = {}) {
    let {
      algorithm = 'luma709',
      keepAlpha = false,
      mergeAlpha = true
    } = options;
    if (typeof algorithm !== 'string' && typeof algorithm !== 'function') {
      throw new TypeError('algorithm must be a string or a function');
    }
    this.checkProcessable('grey', {
      bitDepth: [8, 16],
      alpha: [0, 1]
    });
    if (this.components === 1) {
      algorithm = 'red'; // actually we just take the first channel if it is a grey image
    }
    keepAlpha &= this.alpha;
    mergeAlpha &= this.alpha;
    if (keepAlpha) {
      mergeAlpha = false;
    }
    let newImage = getOutputImage(this, options, {
      components: 1,
      alpha: keepAlpha,
      colorModel: GREY$1
    });
    let method;
    if (typeof algorithm === 'function') {
      method = algorithm;
    } else {
      method = methods$1[algorithm.toLowerCase()];
      if (!method) {
        throw new Error(`unsupported grey algorithm: ${algorithm}`);
      }
    }
    let ptr = 0;
    for (let i = 0; i < this.data.length; i += this.channels) {
      if (mergeAlpha) {
        newImage.data[ptr++] = clamp(method(this.data[i], this.data[i + 1], this.data[i + 2], this) * this.data[i + this.components] / this.maxValue, this);
      } else {
        newImage.data[ptr++] = clamp(method(this.data[i], this.data[i + 1], this.data[i + 2], this), this);
        if (newImage.alpha) {
          newImage.data[ptr++] = this.data[i + this.components];
        }
      }
    }
    return newImage;
  }

  /*
   *
   * see http://rsb.info.nih.gov/ij/developer/source/ij/process/AutoThresholder.java.html.
   * Huang: Implements Huang's fuzzy thresholding method: Huang, L-K & Wang, M-J J (1995),
   * "Image thresholding by minimizing the measure of fuzziness", Pattern Recognition 28(1): 41-51
   *
   */

  function huang(histogram) {
    /* Determine the first non-zero bin */
    let firstBin = 0;
    for (let ih = 0; ih < histogram.length; ih++) {
      if (histogram[ih] !== 0) {
        firstBin = ih;
        break;
      }
    }

    /* Determine the last non-zero bin */
    let lastBin = histogram.length - 1;
    for (let ih = histogram.length - 1; ih >= firstBin; ih--) {
      if (histogram[ih] !== 0) {
        lastBin = ih;
        break;
      }
    }
    let term = 1.0 / (lastBin - firstBin);
    let mu0 = new Array(histogram.length);
    let sumPix = 0;
    let numPix = 0;
    for (let ih = firstBin; ih < histogram.length; ih++) {
      sumPix += ih * histogram[ih];
      numPix += histogram[ih];
      mu0[ih] = sumPix / numPix;
    }
    let mu1 = new Array(histogram.length);
    sumPix = numPix = 0;
    for (let ih = lastBin; ih > 0; ih--) {
      sumPix += ih * histogram[ih];
      numPix += histogram[ih];
      mu1[ih - 1] = sumPix / numPix;
    }

    /* Determine the threshold that minimizes the fuzzy entropy*/
    let threshold = -1;
    let minEnt = Number.MAX_VALUE;
    for (let it = 0; it < histogram.length; it++) {
      let ent = 0;
      let muX;
      for (let ih = 0; ih <= it; ih++) {
        /* Equation (4) in Ref. 1 */
        muX = 1 / (1 + term * Math.abs(ih - mu0[it]));
        if (!(muX < 1e-6 || muX > 0.999999)) {
          /* Equation (6) & (8) in Ref. 1 */
          ent += histogram[ih] * (-muX * Math.log(muX) - (1 - muX) * Math.log(1 - muX));
        }
      }
      for (let ih = it + 1; ih < histogram.length; ih++) {
        /* Equation (4) in Ref. 1 */
        muX = 1 / (1 + term * Math.abs(ih - mu1[it]));
        if (!(muX < 1e-6 || muX > 0.999999)) {
          /* Equation (6) & (8) in Ref. 1 */
          ent += histogram[ih] * (-muX * Math.log(muX) - (1 - muX) * Math.log(1 - muX));
        }
      }
      if (ent < minEnt) {
        minEnt = ent;
        threshold = it;
      }
    }
    return threshold;
  }

  /*
   *
   * see https://github.com/fiji/Auto_Threshold/blob/master/src/main/java/fiji/threshold/Auto_Threshold.java
   * Intermodes: This assumes a bimodal histogram. Implements the thresholding Prewitt, JMS & Mendelsohn, ML (1966),
   * "The analysis of cell images", Annals of the NewYork Academy of Sciences 128: 1035-1053
   *
   */

  function intermodes(histogram) {
    let iHisto = histogram.slice();
    let iter = 0;
    while (!bimodalTest$1(iHisto)) {
      // smooth with a 3 point running mean filter
      let previous = 0;
      let current = 0;
      let next = iHisto[0];
      for (let i = 0; i < histogram.length - 1; i++) {
        previous = current;
        current = next;
        next = iHisto[i + 1];
        iHisto[i] = (previous + current + next) / 3;
      }
      iHisto[histogram.length - 1] = (current + next) / 3;
      iter++;
      if (iter > 10000) {
        throw new Error('Intermodes Threshold not found after 10000 iterations');
      }
    }

    // The threshold is the mean between the two peaks.
    let tt = 0;
    for (let i = 1; i < histogram.length - 1; i++) {
      if (iHisto[i - 1] < iHisto[i] && iHisto[i + 1] < iHisto[i]) {
        tt += i;
      }
    }
    return Math.floor(tt / 2.0);
  }
  function bimodalTest$1(iHisto) {
    let b = false;
    let modes = 0;
    for (let k = 1; k < iHisto.length - 1; k++) {
      if (iHisto[k - 1] < iHisto[k] && iHisto[k + 1] < iHisto[k]) {
        modes++;
        if (modes > 2) {
          return false;
        }
      }
    }
    if (modes === 2) {
      b = true;
    }
    return b;
  }

  /*
   * see https://github.com/fiji/Auto_Threshold/blob/master/src/main/java/fiji/threshold/Auto_Threshold.java
   * Isodata: Ridler, TW & Calvard, S (1978), "Picture thresholding using an iterative selection method"
   * IEEE Transactions on Systems, Man and Cybernetics 8: 630-632.
   *
   */
  function isodata(histogram) {
    let l; // the average grey value of pixels with intensities < g
    let toth; // the the average grey value of pixels with intensities > g
    let totl; // the total the average grey value of pixels with intensities < g
    let h; // the average grey value of pixels with intensities > g
    let g = 0; // threshold value

    for (let i = 1; i < histogram.length; i++) {
      if (histogram[i] > 0) {
        g = i + 1;
        break;
      }
    }
    while (true) {
      l = 0;
      totl = 0;
      for (let i = 0; i < g; i++) {
        totl = totl + histogram[i];
        l = l + histogram[i] * i;
      }
      h = 0;
      toth = 0;
      for (let i = g + 1; i < histogram.length; i++) {
        toth += histogram[i];
        h += histogram[i] * i;
      }
      if (totl > 0 && toth > 0) {
        l /= totl;
        h /= toth;
        if (g === Math.round((l + h) / 2.0)) {
          break;
        }
      }
      g++;
      if (g > histogram.length - 2) {
        throw new Error('Threshold not found');
      }
    }
    return g;
  }

  /*
   * see http://rsb.info.nih.gov/ij/developer/source/ij/process/AutoThresholder.java.html
   * The method is present in: Implements Li's Minimum Cross Entropy thresholding method
   * This implementation is based on the iterative version (Ref. 2nd reference below) of the algorithm.
   *  1) Li, CH & Lee, CK (1993), "Minimum Cross Entropy Thresholding", Pattern Recognition 26(4): 61 625
   *  2) Li, CH & Tam, PKS (1998), "An Iterative Algorithm for Minimum Cross Entropy Thresholding",
   *     Pattern Recognition Letters 18(8): 771-776
   *  3) Sezgin, M & Sankur, B (2004), "Survey over Image Thresholding Techniques and Quantitative Performance
   *     Evaluation",Journal of Electronic Imaging 13(1): 146-165
   * @param histogram - the histogram of the image
   * @param total - the number of pixels in the image
   * @returns {number} - the threshold
   */

  function li(histogram, total) {
    let threshold;
    let sumBack; /* sum of the background pixels at a given threshold */
    let sumObj; /* sum of the object pixels at a given threshold */
    let numBack; /* number of background pixels at a given threshold */
    let numObj; /* number of object pixels at a given threshold */
    let oldThresh;
    let newThresh;
    let meanBack; /* mean of the background pixels at a given threshold */
    let meanObj; /* mean of the object pixels at a given threshold */
    let mean; /* mean gray-level in the image */
    let tolerance; /* threshold tolerance */
    let temp;
    tolerance = 0.5;

    /* Calculate the mean gray-level */
    mean = 0.0;
    for (let ih = 0; ih < histogram.length; ih++) {
      mean += ih * histogram[ih];
    }
    mean /= total;
    /* Initial estimate */
    newThresh = mean;
    do {
      oldThresh = newThresh;
      threshold = oldThresh + 0.5 | 0; /* range */

      /* Calculate the means of background and object pixels */
      /* Background */
      sumBack = 0;
      numBack = 0;
      for (let ih = 0; ih <= threshold; ih++) {
        sumBack += ih * histogram[ih];
        numBack += histogram[ih];
      }
      meanBack = numBack === 0 ? 0.0 : sumBack / numBack;

      /* Object */
      sumObj = 0;
      numObj = 0;
      for (let ih = threshold + 1; ih < histogram.length; ih++) {
        sumObj += ih * histogram[ih];
        numObj += histogram[ih];
      }
      meanObj = numObj === 0 ? 0.0 : sumObj / numObj;
      temp = (meanBack - meanObj) / (Math.log(meanBack) - Math.log(meanObj));
      if (temp < -Number.EPSILON) {
        newThresh = temp - 0.5 | 0;
      } else {
        newThresh = temp + 0.5 | 0;
      }
      /*  Stop the iterations when the difference between the
           new and old threshold values is less than the tolerance */
    } while (Math.abs(newThresh - oldThresh) > tolerance);
    return threshold;
  }

  /*
   * see http://rsb.info.nih.gov/ij/developer/source/ij/process/AutoThresholder.java.html
   * The method is present in: Implements Kapur-Sahoo-Wong (Maximum Entropy) thresholding method:
   * Kapur, JN; Sahoo, PK & Wong, ACK (1985), "A New Method for Gray-Level Picture Thresholding Using the Entropy of the Histogram",
   * Graphical Models and Image Processing 29(3): 273-285
   * @param histogram - the histogram of the image
   *        total - the number of pixels in the image
   * @returns {number} - the threshold
   */

  function maxEntropy(histogram, total) {
    let normHisto = new Array(histogram.length); // normalized histogram
    for (let ih = 0; ih < histogram.length; ih++) {
      normHisto[ih] = histogram[ih] / total;
    }
    let P1 = new Array(histogram.length); // cumulative normalized histogram
    let P2 = new Array(histogram.length);
    P1[0] = normHisto[0];
    P2[0] = 1.0 - P1[0];
    for (let ih = 1; ih < histogram.length; ih++) {
      P1[ih] = P1[ih - 1] + normHisto[ih];
      P2[ih] = 1.0 - P1[ih];
    }

    /* Determine the first non-zero bin */
    let firstBin = 0;
    for (let ih = 0; ih < histogram.length; ih++) {
      if (Math.abs(P1[ih]) >= Number.EPSILON) {
        firstBin = ih;
        break;
      }
    }

    /* Determine the last non-zero bin */
    let lastBin = histogram.length - 1;
    for (let ih = histogram.length - 1; ih >= firstBin; ih--) {
      if (Math.abs(P2[ih]) >= Number.EPSILON) {
        lastBin = ih;
        break;
      }
    }

    // Calculate the total entropy each gray-level
    // and find the threshold that maximizes it
    let threshold = -1;
    let totEnt; // total entropy
    let maxEnt = Number.MIN_VALUE; // max entropy
    let entBack; // entropy of the background pixels at a given threshold
    let entObj; // entropy of the object pixels at a given threshold

    for (let it = firstBin; it <= lastBin; it++) {
      /* Entropy of the background pixels */
      entBack = 0.0;
      for (let ih = 0; ih <= it; ih++) {
        if (histogram[ih] !== 0) {
          entBack -= normHisto[ih] / P1[it] * Math.log(normHisto[ih] / P1[it]);
        }
      }

      /* Entropy of the object pixels */
      entObj = 0.0;
      for (let ih = it + 1; ih < histogram.length; ih++) {
        if (histogram[ih] !== 0) {
          entObj -= normHisto[ih] / P2[it] * Math.log(normHisto[ih] / P2[it]);
        }
      }

      /* Total entropy */
      totEnt = entBack + entObj;
      if (maxEnt < totEnt) {
        maxEnt = totEnt;
        threshold = it;
      }
    }
    return threshold;
  }

  /*
   * The method is present in: Uses the mean of grey levels as the threshold. It is described in:
   * Glasbey, CA (1993), "An analysis of histogram-based thresholding algorithms",
   * CVGIP: Graphical Models and Image Processing 55: 532-537
   * @param histogram - the histogram of the image
   * @param total - the number of pixels in the image
   * @returns {number} - the threshold
   */

  function mean$1(histogram, total) {
    let sum = 0;
    for (let i = 0; i < histogram.length; i++) {
      sum += i * histogram[i];
    }
    return Math.floor(sum / total);
  }

  /*
   * see http://rsb.info.nih.gov/ij/developer/source/ij/process/AutoThresholder.java.html
   * The method is present in: An iterative implementation of Kittler and Illingworth's Minimum Error
   * thresholding:Kittler, J & Illingworth, J (1986), "Minimum error thresholding", Pattern Recognition 19: 41-47
   * @param histogram - the histogram of the image
   * @param total - the number of pixels in the image
   * @returns {number} - the threshold
   */

  function minError(histogram, total) {
    let threshold;
    let Tprev = -2;
    let mu, nu, p, q, sigma2, tau2, w0, w1, w2, sqterm, temp;

    /* Calculate the mean gray-level */
    let mean = 0.0;
    for (let ih = 0; ih < histogram.length; ih++) {
      mean += ih * histogram[ih];
    }
    mean /= total;
    threshold = mean;
    while (threshold !== Tprev) {
      // Calculate some statistics.
      let sumA1 = sumA(histogram, threshold);
      let sumA2 = sumA(histogram, histogram.length - 1);
      let sumB1 = sumB(histogram, threshold);
      let sumB2 = sumB(histogram, histogram.length - 1);
      let sumC1 = sumC(histogram, threshold);
      let sumC2 = sumC(histogram, histogram.length - 1);
      mu = sumB1 / sumA1;
      nu = (sumB2 - sumB1) / (sumA2 - sumA1);
      p = sumA1 / sumA2;
      q = (sumA2 - sumA1) / sumA2;
      sigma2 = sumC1 / sumA1 - mu * mu;
      tau2 = (sumC2 - sumC1) / (sumA2 - sumA1) - nu * nu;

      // The terms of the quadratic equation to be solved.
      w0 = 1.0 / sigma2 - 1.0 / tau2;
      w1 = mu / sigma2 - nu / tau2;
      w2 = mu * mu / sigma2 - nu * nu / tau2 + Math.log10(sigma2 * (q * q) / (tau2 * (p * p)));

      // If the next threshold would be imaginary, return with the current one.
      sqterm = w1 * w1 - w0 * w2;
      if (sqterm < 0) {
        return threshold;
      }

      // The updated threshold is the integer part of the solution of the quadratic equation.
      Tprev = threshold;
      temp = (w1 + Math.sqrt(sqterm)) / w0;
      if (isNaN(temp)) {
        threshold = Tprev;
      } else {
        threshold = Math.floor(temp);
      }
    }
    return threshold;
  }

  // aux func

  function sumA(y, j) {
    let x = 0;
    for (let i = 0; i <= j; i++) {
      x += y[i];
    }
    return x;
  }
  function sumB(y, j) {
    let x = 0;
    for (let i = 0; i <= j; i++) {
      x += i * y[i];
    }
    return x;
  }
  function sumC(y, j) {
    let x = 0;
    for (let i = 0; i <= j; i++) {
      x += i * i * y[i];
    }
    return x;
  }

  // see https://github.com/fiji/Auto_Threshold/blob/master/src/main/java/fiji/threshold/Auto_Threshold.java
  // J. M. S. Prewitt and M. L. Mendelsohn, "The analysis of cell images," in
  // Annals of the New York Academy of Sciences, vol. 128, pp. 1035-1053, 1966.
  // ported to ImageJ plugin by G.Landini from Antti Niemisto's Matlab code (GPL)
  // Original Matlab code Copyright (C) 2004 Antti Niemisto
  // See http://www.cs.tut.fi/~ant/histthresh/ for an excellent slide presentation
  // and the original Matlab code
  function minimum(histogram) {
    if (histogram.length < 2) {
      // validate that the histogram has at least two color values
      return 0;
    }
    let iterations = 0; // number of iterations of the smoothing process
    let threshold = -1;
    let max = -1; // maximum color value with a greater number of pixels to 0
    let histogramCopy = new Array(histogram.length); // a copy of the histogram
    for (let i = 0; i < histogram.length; i++) {
      histogramCopy[i] = histogram[i];
      if (histogram[i] > 0) {
        max = i;
      }
    }
    while (!bimodalTest(histogramCopy)) {
      histogramCopy = smoothed(histogramCopy);
      iterations++;
      if (iterations > 10000) {
        // if they occur more than 10000 iterations it returns -1
        return threshold;
      }
    }
    threshold = minimumBetweenPeeks(histogramCopy, max);
    return threshold;
  }
  function smoothed(histogram) {
    // Smooth with a 3 point running mean filter
    let auHistogram = new Array(histogram.length); // a copy of the histograma for the smoothing process
    for (let i = 1; i < histogram.length - 1; i++) {
      auHistogram[i] = (histogram[i - 1] + histogram[i] + histogram[i + 1]) / 3;
    }
    auHistogram[0] = (histogram[0] + histogram[1]) / 3;
    auHistogram[histogram.length - 1] = (histogram[histogram.length - 2] + histogram[histogram.length - 1]) / 3;
    return auHistogram;
  }
  function minimumBetweenPeeks(histogramBimodal, max) {
    let threshold;
    for (let i = 1; i < max; i++) {
      if (histogramBimodal[i - 1] > histogramBimodal[i] && histogramBimodal[i + 1] >= histogramBimodal[i]) {
        threshold = i;
        break;
      }
    }
    return threshold;
  }
  function bimodalTest(histogram) {
    // It is responsible for determining if a histogram is bimodal
    let len = histogram.length;
    let isBimodal = false;
    let peaks = 0;
    for (let k = 1; k < len - 1; k++) {
      if (histogram[k - 1] < histogram[k] && histogram[k + 1] < histogram[k]) {
        peaks++;
        if (peaks > 2) {
          return false;
        }
      }
    }
    if (peaks === 2) {
      isBimodal = true;
    }
    return isBimodal;
  }

  // see https://github.com/fiji/Auto_Threshold/blob/master/src/main/java/fiji/threshold/Auto_Threshold.java
  // W. Tsai, "Moment-preserving thresholding: a new approach," Computer Vision,
  // Graphics, and Image Processing, vol. 29, pp. 377-393, 1985.
  // Ported to ImageJ plugin by G.Landini from the the open source project FOURIER 0.8
  // by M. Emre Celebi , Department of Computer Science, Louisiana State University in Shreveport
  // Shreveport, LA 71115, USA
  // http://sourceforge.net/projects/fourier-ipal
  // http://www.lsus.edu/faculty/~ecelebi/fourier.htm
  function moments(histogram, total) {
    // moments
    let m0 = 1.0;
    let m1 = 0.0;
    let m2 = 0.0;
    let m3 = 0.0;
    let sum = 0.0;
    let p0;
    let cd, c0, c1, z0, z1; /* auxiliary variables */
    let threshold = -1;
    let histogramLength = histogram.length;
    let normalizedHistogram = new Array(histogramLength);
    for (let i = 0; i < histogramLength; i++) {
      normalizedHistogram[i] = histogram[i] / total;
    }
    /* Calculate the first, second, and third order moments */
    for (let i = 0; i < histogramLength; i++) {
      m1 += i * normalizedHistogram[i];
      m2 += i * i * normalizedHistogram[i];
      m3 += i * i * i * normalizedHistogram[i];
    }
    /*
       First 4 moments of the gray-level image should match the first 4 moments
       of the target binary image. This leads to 4 equalities whose solutions
       are given in the Appendix of Ref. 1
       */
    cd = m0 * m2 - m1 * m1; // determinant of the matriz of hankel for moments 2x2
    c0 = (-m2 * m2 + m1 * m3) / cd;
    c1 = (m0 * -m3 + m2 * m1) / cd;
    // new two gray values where z0<z1
    z0 = 0.5 * (-c1 - Math.sqrt(c1 * c1 - 4.0 * c0));
    z1 = 0.5 * (-c1 + Math.sqrt(c1 * c1 - 4.0 * c0));
    p0 = (z1 - m1) / (z1 - z0); /* Fraction of the object pixels in the target binary image (p0z0+p1z1=m1) */
    // The threshold is the gray-level closest to the p0-tile of the normalized histogram
    for (let i = 0; i < histogramLength; i++) {
      sum += normalizedHistogram[i];
      if (sum > p0) {
        threshold = i;
        break;
      }
    }
    return threshold;
  }

  /*
   * The method is present in: Otsu, N (1979), "A threshold selection method from gray-level histograms", IEEE Trans. Sys., Man., Cyber. 9: 62-66
   * The Otsu implementation is based on: https://en.wikipedia.org/wiki/Otsu's_method
   * @param histogram - the histogram of the image
   * @returns {number} - the threshold
   */

  function otsu(histogramCounts, total) {
    let sumB = 0;
    let wB = 0;
    let maximum = 0;
    let level = 0;
    let sum1 = 0;
    for (let i = 0; i < histogramCounts.length; i++) {
      sum1 += i * histogramCounts[i];
    }
    for (let ii = 0; ii < histogramCounts.length; ii++) {
      wB = wB + histogramCounts[ii];
      const wF = total - wB;
      if (wB === 0 || wF === 0) {
        continue;
      }
      sumB = sumB + ii * histogramCounts[ii];
      const mF = (sum1 - sumB) / wF;
      const between = wB * wF * (sumB / wB - mF) * (sumB / wB - mF);
      if (between >= maximum) {
        level = ii;
        maximum = between;
      }
    }
    return level;
  }

  // See http://imagej.nih.gov/ij/download/tools/source/ij/process/AutoThresholder.java
  // W. Doyle, "Operation useful for similarity-invariant pattern recognition,"
  // Journal of the Association for Computing Machinery, vol. 9,pp. 259-267, 1962.
  // ported to ImageJ plugin by G.Landini from Antti Niemisto's Matlab code (GPL)
  // Original Matlab code Copyright (C) 2004 Antti Niemisto
  // See http://www.cs.tut.fi/~ant/histthresh/ for an excellent slide presentation
  // and the original Matlab code.
  function percentile(histogram) {
    let threshold = -1;
    let percentile = 0.5; // default fraction of foreground pixels
    let avec = new Array(histogram.length);
    let total = partialSum(histogram, histogram.length - 1);
    let temp = 1.0;
    for (let i = 0; i < histogram.length; i++) {
      avec[i] = Math.abs(partialSum(histogram, i) / total - percentile);
      if (avec[i] < temp) {
        temp = avec[i];
        threshold = i;
      }
    }
    return threshold;
  }
  function partialSum(histogram, endIndex) {
    let x = 0;
    for (let i = 0; i <= endIndex; i++) {
      x += histogram[i];
    }
    return x;
  }

  // see https://github.com/fiji/Auto_Threshold/blob/master/src/main/java/fiji/threshold/Auto_Threshold.java
  // Kapur J.N., Sahoo P.K., and Wong A.K.C. (1985) "A New Method for
  // Gray-Level Picture Thresholding Using the Entropy of the Histogram"
  // Graphical Models and Image Processing, 29(3): 273-285
  // M. Emre Celebi
  // 06.15.2007
  // Ported to ImageJ plugin by G.Landini from E Celebi's fourier_0.8 routines
  function renyiEntropy(histogram, total) {
    let optThreshold; // Optimal threshold
    let firstBin; // First non-zero bin
    let lastBin; // last non-zero bin

    let normHisto = new Array(histogram.length); // normalized histogram
    let P1 = new Array(histogram.length); // acumulative normalized histogram
    let P2 = new Array(histogram.length); // acumulative normalized histogram

    // Entropy Variables
    let threshold1 = 0;
    let threshold2 = 0;
    let threshold3 = 0;
    let maxEnt1 = 0.0;
    let maxEnt2 = 0.0;
    let maxEnt3 = 0.0;
    let alpha2 = 0.5;
    let term2 = 1.0 / (1.0 - alpha2);
    let alpha3 = 2.0;
    let term3 = 1.0 / (1.0 - alpha3);
    for (let ih = 0; ih < histogram.length; ih++) {
      normHisto[ih] = histogram[ih] / total;
    }
    P1[0] = normHisto[0];
    P2[0] = 1.0 - P1[0];
    for (let ih = 1; ih < histogram.length; ih++) {
      P1[ih] = P1[ih - 1] + normHisto[ih];
      P2[ih] = 1.0 - P1[ih];
    }

    /* Determine the first non-zero bin */
    firstBin = 0;
    for (let ih = 0; ih < histogram.length; ih++) {
      if (Math.abs(P1[ih]) >= Number.EPSILON) {
        firstBin = ih;
        break;
      }
    }

    /* Determine the last non-zero bin */
    lastBin = histogram.length - 1;
    for (let ih = histogram.length - 1; ih >= firstBin; ih--) {
      if (Math.abs(P2[ih]) >= Number.EPSILON) {
        lastBin = ih;
        break;
      }
    }

    /* Maximum Entropy Thresholding - BEGIN */
    /* ALPHA = 1.0 */
    /* Calculate the total entropy each gray-level
       and find the threshold that maximizes it
       */
    for (let it = firstBin; it <= lastBin; it++) {
      /* Entropy of the background pixels */
      let entBack1 = 0.0;
      let entBack2 = 0.0;
      let entBack3 = 0.0;
      for (let ih = 0; ih <= it; ih++) {
        if (histogram[ih] !== 0) {
          entBack1 -= normHisto[ih] / P1[it] * Math.log(normHisto[ih] / P1[it]);
        }
        entBack2 += Math.sqrt(normHisto[ih] / P1[it]);
        entBack3 += normHisto[ih] * normHisto[ih] / (P1[it] * P1[it]);
      }

      /* Entropy of the object pixels */
      let entObj1 = 0.0;
      let entObj2 = 0.0;
      let entObj3 = 0.0;
      for (let ih = it + 1; ih < histogram.length; ih++) {
        if (histogram[ih] !== 0) {
          entObj1 -= normHisto[ih] / P2[it] * Math.log(normHisto[ih] / P2[it]);
        }
        entObj2 += Math.sqrt(normHisto[ih] / P2[it]);
        entObj3 += normHisto[ih] * normHisto[ih] / (P2[it] * P2[it]);
      }

      /* Total entropy */
      let totEnt1 = entBack1 + entObj1;
      let totEnt2 = term2 * (entBack2 * entObj2 > 0.0 ? Math.log(entBack2 * entObj2) : 0.0);
      let totEnt3 = term3 * (entBack3 * entObj3 > 0.0 ? Math.log(entBack3 * entObj3) : 0.0);
      if (totEnt1 > maxEnt1) {
        maxEnt1 = totEnt1;
        threshold1 = it;
      }
      if (totEnt2 > maxEnt2) {
        maxEnt2 = totEnt2;
        threshold2 = it;
      }
      if (totEnt3 > maxEnt3) {
        maxEnt3 = totEnt3;
        threshold3 = it;
      }
    }
    /* End Maximum Entropy Thresholding */

    let tStars = [threshold1, threshold2, threshold3];
    tStars.sort((a, b) => a - b);
    let betas;

    /* Adjust beta values */
    if (Math.abs(tStars[0] - tStars[1]) <= 5) {
      if (Math.abs(tStars[1] - tStars[2]) <= 5) {
        betas = [1, 2, 1];
      } else {
        betas = [0, 1, 3];
      }
    } else {
      if (Math.abs(tStars[1] - tStars[2]) <= 5) {
        betas = [3, 1, 0];
      } else {
        betas = [1, 2, 1];
      }
    }

    /* Determine the optimal threshold value */
    let omega = P1[tStars[2]] - P1[tStars[0]];
    optThreshold = Math.round(tStars[0] * (P1[tStars[0]] + 0.25 * omega * betas[0]) + 0.25 * tStars[1] * omega * betas[1] + tStars[2] * (P2[tStars[2]] + 0.25 * omega * betas[2]));
    return optThreshold;
  }

  // see https://github.com/fiji/Auto_Threshold/blob/master/src/main/java/fiji/threshold/Auto_Threshold.java
  // Shanhbag A.G. (1994) "Utilization of Information Measure as a Means of
  // Image Thresholding" Graphical Models and Image Processing, 56(5): 414-419
  // Ported to ImageJ plugin by G.Landini from E Celebi's fourier_0.8 routines

  function shanbhag(histogram, total) {
    let normHisto = new Array(histogram.length); // normalized histogram
    for (let ih = 0; ih < histogram.length; ih++) {
      normHisto[ih] = histogram[ih] / total;
    }
    let P1 = new Array(histogram.length); // cumulative normalized histogram
    let P2 = new Array(histogram.length);
    P1[0] = normHisto[0];
    P2[0] = 1.0 - P1[0];
    for (let ih = 1; ih < histogram.length; ih++) {
      P1[ih] = P1[ih - 1] + normHisto[ih];
      P2[ih] = 1.0 - P1[ih];
    }

    /* Determine the first non-zero bin */
    let firstBin = 0;
    for (let ih = 0; ih < histogram.length; ih++) {
      if (Math.abs(P1[ih]) >= Number.EPSILON) {
        firstBin = ih;
        break;
      }
    }

    /* Determine the last non-zero bin */
    let lastBin = histogram.length - 1;
    for (let ih = histogram.length - 1; ih >= firstBin; ih--) {
      if (Math.abs(P2[ih]) >= Number.EPSILON) {
        lastBin = ih;
        break;
      }
    }

    // Calculate the total entropy each gray-level
    // and find the threshold that maximizes it
    let threshold = -1;
    let minEnt = Number.MAX_VALUE; // min entropy

    let term;
    let totEnt; // total entropy
    let entBack; // entropy of the background pixels at a given threshold
    let entObj; // entropy of the object pixels at a given threshold
    for (let it = firstBin; it <= lastBin; it++) {
      /* Entropy of the background pixels */
      entBack = 0.0;
      term = 0.5 / P1[it];
      for (let ih = 1; ih <= it; ih++) {
        entBack -= normHisto[ih] * Math.log(1.0 - term * P1[ih - 1]);
      }
      entBack *= term;

      /* Entropy of the object pixels */
      entObj = 0.0;
      term = 0.5 / P2[it];
      for (let ih = it + 1; ih < histogram.length; ih++) {
        entObj -= normHisto[ih] * Math.log(1.0 - term * P2[ih]);
      }
      entObj *= term;

      /* Total entropy */
      totEnt = Math.abs(entBack - entObj);
      if (totEnt < minEnt) {
        minEnt = totEnt;
        threshold = it;
      }
    }
    return threshold;
  }

  // see https://github.com/fiji/Auto_Threshold/blob/master/src/main/java/fiji/threshold/Auto_Threshold.java
  // Zack, G. W., Rogers, W. E. and Latt, S. A., 1977,
  // Automatic Measurement of Sister Chromatid Exchange Frequency,
  // Journal of Histochemistry and Cytochemistry 25 (7), pp. 741-753
  //
  //  modified from Johannes Schindelin plugin
  function triangle$1(histogram) {
    // find min and max
    let min = 0;
    let dmax = 0;
    let max = 0;
    let min2 = 0;
    for (let i = 0; i < histogram.length; i++) {
      if (histogram[i] > 0) {
        min = i;
        break;
      }
    }
    if (min > 0) {
      // line to the (p==0) point, not to histogram[min]
      min--;
    }

    // The Triangle algorithm cannot tell whether the data is skewed to one side or another.
    // This causes a problem as there are 2 possible thresholds between the max and the 2 extremes
    // of the histogram.
    // Here I propose to find out to which side of the max point the data is furthest, and use that as
    //  the other extreme.
    for (let i = histogram.length - 1; i > 0; i--) {
      if (histogram[i] > 0) {
        min2 = i;
        break;
      }
    }
    if (min2 < histogram.length - 1) {
      // line to the (p==0) point, not to data[min]
      min2++;
    }
    for (let i = 0; i < histogram.length; i++) {
      if (histogram[i] > dmax) {
        max = i;
        dmax = histogram[i];
      }
    }

    // find which is the furthest side
    let inverted = false;
    if (max - min < min2 - max) {
      // reverse the histogram
      inverted = true;
      let left = 0; // index of leftmost element
      let right = histogram.length - 1; // index of rightmost element
      while (left < right) {
        // exchange the left and right elements
        let temp = histogram[left];
        histogram[left] = histogram[right];
        histogram[right] = temp;
        // move the bounds toward the center
        left++;
        right--;
      }
      min = histogram.length - 1 - min2;
      max = histogram.length - 1 - max;
    }
    if (min === max) {
      return min;
    }

    // describe line by nx * x + ny * y - d = 0
    let nx, ny, d;
    // nx is just the max frequency as the other point has freq=0
    nx = histogram[max]; // -min; // data[min]; //  lowest value bmin = (p=0)% in the image
    ny = min - max;
    d = Math.sqrt(nx * nx + ny * ny);
    nx /= d;
    ny /= d;
    d = nx * min + ny * histogram[min];

    // find split point
    let split = min;
    let splitDistance = 0;
    for (let i = min + 1; i <= max; i++) {
      let newDistance = nx * i + ny * histogram[i] - d;
      if (newDistance > splitDistance) {
        split = i;
        splitDistance = newDistance;
      }
    }
    split--;
    if (inverted) {
      // The histogram might be used for something else, so let's reverse it back
      let left = 0;
      let right = histogram.length - 1;
      while (left < right) {
        let temp = histogram[left];
        histogram[left] = histogram[right];
        histogram[right] = temp;
        left++;
        right--;
      }
      return histogram.length - 1 - split;
    } else {
      return split;
    }
  }

  // see https://github.com/fiji/Auto_Threshold/blob/master/src/main/java/fiji/threshold/Auto_Threshold.java
  // Implements Yen  thresholding method
  // 1) Yen J.C., Chang F.J., and Chang S. (1995) "A New Criterion
  //    for Automatic Multilevel Thresholding" IEEE Trans. on Image
  //    Processing, 4(3): 370-378
  // 2) Sezgin M. and Sankur B. (2004) "Survey over Image Thresholding
  //    Techniques and Quantitative Performance Evaluation" Journal of
  //    Electronic Imaging, 13(1): 146-165
  //    http://citeseer.ist.psu.edu/sezgin04survey.html
  //
  // M. Emre Celebi
  // 06.15.2007
  // Ported to ImageJ plugin by G.Landini from E Celebi's fourier_0.8 routines

  function yen(histogram, total) {
    let normHisto = new Array(histogram.length); // normalized histogram
    for (let ih = 0; ih < histogram.length; ih++) {
      normHisto[ih] = histogram[ih] / total;
    }
    let P1 = new Array(histogram.length); // cumulative normalized histogram
    P1[0] = normHisto[0];
    for (let ih = 1; ih < histogram.length; ih++) {
      P1[ih] = P1[ih - 1] + normHisto[ih];
    }
    let P1Sq = new Array(histogram.length);
    P1Sq[0] = normHisto[0] * normHisto[0];
    for (let ih = 1; ih < histogram.length; ih++) {
      P1Sq[ih] = P1Sq[ih - 1] + normHisto[ih] * normHisto[ih];
    }
    let P2Sq = new Array(histogram.length);
    P2Sq[histogram.length - 1] = 0.0;
    for (let ih = histogram.length - 2; ih >= 0; ih--) {
      P2Sq[ih] = P2Sq[ih + 1] + normHisto[ih + 1] * normHisto[ih + 1];
    }

    /* Find the threshold that maximizes the criterion */
    let threshold = -1;
    let maxCrit = Number.MIN_VALUE;
    let crit;
    for (let it = 0; it < histogram.length; it++) {
      crit = -1 * (P1Sq[it] * P2Sq[it] > 0.0 ? Math.log(P1Sq[it] * P2Sq[it]) : 0.0) + 2 * (P1[it] * (1.0 - P1[it]) > 0.0 ? Math.log(P1[it] * (1.0 - P1[it])) : 0.0);
      if (crit > maxCrit) {
        maxCrit = crit;
        threshold = it;
      }
    }
    return threshold;
  }

  /**
   * @typedef {('huang'|'intermodes'|'isodata'|'li'|'maxentropy'|'mean'|'minerror'|'minimum'|'moments'|'otsu'|'percentile'|'renyientropy'|'shanbhag'|'triangle'|'yen')} ThresholdAlgorithm
   */

  const methods = {
    huang,
    intermodes,
    isodata,
    li,
    maxentropy: maxEntropy,
    mean: mean$1,
    minerror: minError,
    minimum,
    moments,
    otsu,
    percentile,
    renyientropy: renyiEntropy,
    shanbhag,
    triangle: triangle$1,
    yen
  };
  const names = {};
  Object.keys(methods).forEach(name => {
    names[name] = name;
  });

  /**
   * Returns a threshold for the creation of a binary mask with the `mask()` method.
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {ThresholdAlgorithm} [options.algorithm='otsu']
   * @return {number}
   */
  function getThreshold(options = {}) {
    let {
      algorithm = names.otsu
    } = options;
    this.checkProcessable('getThreshold', {
      components: 1,
      bitDepth: [8, 16]
    });
    let method = methods[algorithm.toLowerCase()];
    if (method) {
      let histogram = this.getHistogram();
      return method(histogram, this.size);
    } else {
      throw new Error(`unknown thresholding algorithm: ${algorithm}`);
    }
  }

  const THRESHOLD = 'threshold';

  /**
   * Creation of binary mask is based on the determination of a threshold
   * You may either choose among the provided algorithm or just specify a threshold value
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {ThresholdAlgorithm|'threshold'} [options.algorithm='threshold']
   * @param {number} [options.threshold=0.5] - If the algorithm is 'threshold' specify here the value (0 to 1).
   * @param {boolean} [options.useAlpha=true] - Apply the alpha channel to determine the intensity of the pixel.
   * @param {boolean} [options.invert=false] - Invert the resulting image
   * @return {Image} - Binary image containing the mask
   */
  function mask(options = {}) {
    let {
      algorithm = THRESHOLD,
      threshold = 0.5,
      useAlpha = true,
      invert = false
    } = options;
    this.checkProcessable('mask', {
      components: 1,
      bitDepth: [8, 16]
    });
    if (algorithm === THRESHOLD) {
      threshold = getThreshold$1(threshold, this.maxValue);
    } else {
      threshold = getThreshold.call(this, options);
    }
    let newImage = new Image(this.width, this.height, {
      kind: 'BINARY',
      parent: this
    });
    let ptr = 0;
    if (this.alpha && useAlpha) {
      for (let i = 0; i < this.data.length; i += this.channels) {
        let value = this.data[i] + (this.maxValue - this.data[i]) * (this.maxValue - this.data[i + 1]) / this.maxValue;
        if (invert && value <= threshold || !invert && value >= threshold) {
          newImage.setBit(ptr);
        }
        ptr++;
      }
    } else {
      for (let i = 0; i < this.data.length; i += this.channels) {
        if (invert && this.data[i] <= threshold || !invert && this.data[i] >= threshold) {
          newImage.setBit(ptr);
        }
        ptr++;
      }
    }
    return newImage;
  }

  /**
   * Make a copy of the current image
   * @memberof Image
   * @instance
   * @param {Image} fromImage
   * @param {Image} toImage
   * @param {number} x
   * @param {number} y
   */
  function copyImage(fromImage, toImage, x, y) {
    let fromWidth = fromImage.width;
    let fromHeight = fromImage.height;
    let toWidth = toImage.width;
    let channels = fromImage.channels;
    for (let i = 0; i < fromWidth; i++) {
      for (let j = 0; j < fromHeight; j++) {
        for (let k = 0; k < channels; k++) {
          let source = (j * fromWidth + i) * channels + k;
          let target = ((y + j) * toWidth + x + i) * channels + k;
          toImage.data[target] = fromImage.data[source];
        }
      }
    }
  }

  /**
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {number} [options.size=0]
   * @param {string} [options.algorithm='copy']
   * @param {array<number>} [options.color]
   * @return {Image}
   */
  function pad(options = {}) {
    let {
      size = 0,
      algorithm = 'copy',
      color
    } = options;
    this.checkProcessable('pad', {
      bitDepth: [8, 16]
    });
    if (algorithm === 'set') {
      if (color.length !== this.channels) {
        throw new Error(`pad: the color array must have the same length as the number of channels. Here: ${this.channels}`);
      }
      for (let i = 0; i < color.length; i++) {
        if (color[i] === 0) {
          color[i] = 0.001;
        }
      }
    } else {
      color = newArray$1(this.channels, null);
    }
    if (!Array.isArray(size)) {
      size = [size, size];
    }
    let newWidth = this.width + size[0] * 2;
    let newHeight = this.height + size[1] * 2;
    let channels = this.channels;
    let newImage = Image.createFrom(this, {
      width: newWidth,
      height: newHeight
    });
    copyImage(this, newImage, size[0], size[1]);
    for (let i = size[0]; i < newWidth - size[0]; i++) {
      for (let k = 0; k < channels; k++) {
        let value = color[k] || newImage.data[(size[1] * newWidth + i) * channels + k];
        for (let j = 0; j < size[1]; j++) {
          newImage.data[(j * newWidth + i) * channels + k] = value;
        }
        value = color[k] || newImage.data[((newHeight - size[1] - 1) * newWidth + i) * channels + k];
        for (let j = newHeight - size[1]; j < newHeight; j++) {
          newImage.data[(j * newWidth + i) * channels + k] = value;
        }
      }
    }
    for (let j = 0; j < newHeight; j++) {
      for (let k = 0; k < channels; k++) {
        let value = color[k] || newImage.data[(j * newWidth + size[0]) * channels + k];
        for (let i = 0; i < size[0]; i++) {
          newImage.data[(j * newWidth + i) * channels + k] = value;
        }
        value = color[k] || newImage.data[(j * newWidth + newWidth - size[0] - 1) * channels + k];
        for (let i = newWidth - size[0]; i < newWidth; i++) {
          newImage.data[(j * newWidth + i) * channels + k] = value;
        }
      }
    }
    return newImage;
  }

  /**
   * Change the image color depth.
   * The color depth is the number of bits that is assigned to each point of a channel.
   * For normal images it is 8 bits meaning the value is between 0 and 255.
   * Currently only conversion from 1, 8 or 16 bits towards 8 or 16 bits are allowed.
   * @memberof Image
   * @instance
   * @param {number} [newColorDepth=8]
   * @return {Image} The new image
   * @example
   * var newImage = image.colorDepth(8);
   */
  function colorDepth(newColorDepth = 8) {
    this.checkProcessable('colorDepth', {
      bitDepth: [1, 8, 16]
    });
    if (![8, 16].includes(newColorDepth)) {
      throw Error('You need to specify the new colorDepth as 8 or 16');
    }
    if (this.bitDepth === newColorDepth) {
      return this.clone();
    }
    let newImage = Image.createFrom(this, {
      bitDepth: newColorDepth
    });
    switch (newColorDepth) {
      case 8:
        if (this.bitDepth === 1) {
          for (let i = 0; i < this.size; i++) {
            if (this.getBit(i)) {
              newImage.data[i] = 255;
            }
          }
        } else {
          for (let i = 0; i < this.data.length; i++) {
            newImage.data[i] = this.data[i] >> 8;
          }
        }
        break;
      case 16:
        if (this.bitDepth === 1) {
          for (let i = 0; i < this.size; i++) {
            if (this.getBit(i)) {
              newImage.data[i] = 65535;
            }
          }
        } else {
          for (let i = 0; i < this.data.length; i++) {
            newImage.data[i] = this.data[i] << 8 | this.data[i];
          }
        }
        break;
      default:
        throw new Error('colorDepth conversion unexpected case');
    }
    return newImage;
  }

  function rotateFree(degrees, options = {}) {
    const {
      interpolation = validInterpolations.nearestneighbor,
      width = this.width,
      height = this.height
    } = options;
    if (typeof degrees !== 'number') {
      throw new TypeError('degrees must be a number');
    }
    const interpolationToUse = (checkInterpolation)(interpolation);
    const radians = degrees * Math.PI / 180;
    const newWidth = Math.floor(Math.abs(width * Math.cos(radians)) + Math.abs(height * Math.sin(radians)));
    const newHeight = Math.floor(Math.abs(height * Math.cos(radians)) + Math.abs(width * Math.sin(radians)));
    const cos = Math.cos(-radians);
    const sin = Math.sin(-radians);
    let x0 = newWidth / 2;
    let y0 = newHeight / 2;
    if (newWidth % 2 === 0) {
      x0 = x0 - 0.5;
      if (newHeight % 2 === 0) {
        y0 = y0 - 0.5;
      } else {
        y0 = Math.floor(y0);
      }
    } else {
      x0 = Math.floor(x0);
      if (newHeight % 2 === 0) {
        y0 = y0 - 0.5;
      } else {
        y0 = Math.floor(y0);
      }
    }
    const incrementX = Math.floor(width / 2 - x0);
    const incrementY = Math.floor(height / 2 - y0);
    if (this.bitDepth === 1) {
      const newImage = new Image(newWidth, newHeight, {
        kind: 'BINARY',
        parent: this
      });
      switch (interpolationToUse) {
        case validInterpolations.nearestneighbor:
          return rotateBinaryNearestNeighbor(this, newImage, incrementX, incrementY, x0, y0, cos, sin);
        case validInterpolations.bilinear:
          return rotateBinaryBilinear(this, newImage, incrementX, incrementY, x0, y0, cos, sin);
        default:
          throw new Error(`unsupported rotate interpolation: ${interpolationToUse}`);
      }
    } else {
      const newImage = Image.createFrom(this, {
        width: newWidth,
        height: newHeight
      });
      switch (interpolationToUse) {
        case validInterpolations.nearestneighbor:
          return rotateNearestNeighbor(this, newImage, incrementX, incrementY, x0, y0, cos, sin);
        case validInterpolations.bilinear:
          return rotateBilinear(this, newImage, incrementX, incrementY, x0, y0, cos, sin);
        default:
          throw new Error(`unsupported rotate interpolation: ${interpolationToUse}`);
      }
    }
  }
  function rotateNearestNeighbor(thisImage, newImage, incrementX, incrementY, x0, y0, cos, sin) {
    for (let i = 0; i < newImage.width; i += 1) {
      for (let j = 0; j < newImage.height; j += 1) {
        for (let c = 0; c < thisImage.channels; c++) {
          let x = Math.round((i - x0) * cos - (j - y0) * sin + x0) + incrementX;
          let y = Math.round((j - y0) * cos + (i - x0) * sin + y0) + incrementY;
          if (x < 0 || x >= thisImage.width || y < 0 || y >= thisImage.height) {
            if (thisImage.alpha === 1 && c === thisImage.channels - 1) {
              newImage.setValueXY(i, j, c, 0);
            } else {
              newImage.setValueXY(i, j, c, thisImage.maxValue);
            }
          } else {
            newImage.setValueXY(i, j, c, thisImage.getValueXY(x, y, c));
          }
        }
      }
    }
    return newImage;
  }
  function rotateBinaryNearestNeighbor(thisImage, newImage, incrementX, incrementY, x0, y0, cos, sin) {
    for (let i = 0; i < newImage.width; i += 1) {
      for (let j = 0; j < newImage.height; j += 1) {
        let x = Math.round((i - x0) * cos - (j - y0) * sin + x0) + incrementX;
        let y = Math.round((j - y0) * cos + (i - x0) * sin + y0) + incrementY;
        if (x < 0 || x >= thisImage.width || y < 0 || y >= thisImage.height || thisImage.getBitXY(x, y)) {
          newImage.setBitXY(i, j);
        }
      }
    }
    return newImage;
  }
  function rotateBilinear(thisImage, newImage, incrementX, incrementY, x0, y0, cos, sin) {
    let stride = thisImage.width * thisImage.channels;
    for (let j = 0; j < newImage.height; j++) {
      for (let i = 0; i < newImage.width; i++) {
        let x = (i - x0) * cos - (j - y0) * sin + x0 + incrementX;
        let y = (j - y0) * cos + (i - x0) * sin + y0 + incrementY;
        let x1 = x | 0;
        let y1 = y | 0;
        let xDiff = x - x1;
        let yDiff = y - y1;
        for (let c = 0; c < thisImage.channels; c++) {
          if (x < 0 || x >= thisImage.width || y < 0 || y >= thisImage.height) {
            if (thisImage.alpha === 1 && c === thisImage.channels - 1) {
              newImage.setValueXY(i, j, c, 0);
            } else {
              newImage.setValueXY(i, j, c, thisImage.maxValue);
            }
          } else {
            let index = (y1 * thisImage.width + x1) * thisImage.channels + c;
            let A = thisImage.data[index];
            let B = thisImage.data[index + thisImage.channels];
            let C = thisImage.data[index + stride];
            let D = thisImage.data[index + stride + thisImage.channels];
            let result = A + xDiff * (B - A) + yDiff * (C - A) + xDiff * yDiff * (A - B - C + D) | 0;
            newImage.setValueXY(i, j, c, result);
          }
        }
      }
    }
    return newImage;
  }
  function rotateBinaryBilinear(thisImage, newImage, incrementX, incrementY, x0, y0, cos, sin) {
    let stride = thisImage.width;
    for (let j = 0; j < newImage.height; j++) {
      for (let i = 0; i < newImage.width; i++) {
        let x = (i - x0) * cos - (j - y0) * sin + x0 + incrementX;
        let y = (j - y0) * cos + (i - x0) * sin + y0 + incrementY;
        let x1 = x | 0;
        let y1 = y | 0;
        let xDiff = x - x1;
        let yDiff = y - y1;
        if (x < 0 || x >= thisImage.width || y < 0 || y >= thisImage.height) {
          newImage.setBitXY(i, j);
        } else {
          let index = y1 * thisImage.width + x1;
          let A = thisImage.getBit(index);
          let B = thisImage.getBit(index + 1);
          let C = thisImage.getBit(index + stride);
          let D = thisImage.getBit(index + 1 + stride);
          let result = A | xDiff & B - A | yDiff & C - A | xDiff & yDiff & A - B - C + D;
          if (result > 0) newImage.setBitXY(i, j);
        }
      }
    }
    return newImage;
  }

  /**
   * Rotates an image.
   * @memberof Image
   * @instance
   * @param {number} angle - Angle of the rotation in degrees
   * @param {object} [options]
   * @param {InterpolationAlgorithm} [options.interpolation='nearestNeighbor'] - Interpolation algorithm to use if `angle` is not a multiple of 90
   * @return {Image} The new rotated image
   */
  function rotate$1(angle, options) {
    this.checkProcessable('rotate', {
      bitDepth: [1, 8, 16]
    });
    if (typeof angle !== 'number') {
      throw new TypeError('angle must be a number');
    }
    if (angle < 0) {
      angle = Math.ceil(-angle / 360) * 360 + angle;
    }
    switch (angle % 360) {
      case 0:
        return this.clone();
      case 90:
        return rotateRight.call(this);
      case 180:
        return rotate180.call(this);
      case 270:
        return rotateLeft.call(this);
      default:
        return rotateFree.call(this, angle, options);
    }
  }
  /**
   * Rotates an image counter-clockwise
   * @memberof Image
   * @instance
   * @return {Image} The new rotated image
   */

  function rotateLeft() {
    if (this.bitDepth === 1) {
      const newImage = new Image(this.height, this.width, {
        kind: 'BINARY',
        parent: this
      });
      const newMaxHeight = newImage.height - 1;
      for (let i = 0; i < this.height; i++) {
        for (let j = 0; j < this.width; j++) {
          if (this.getBitXY(j, i)) {
            newImage.setBitXY(i, newMaxHeight - j);
          }
        }
      }
      return newImage;
    } else {
      const newImage = Image.createFrom(this, {
        width: this.height,
        height: this.width
      });
      const newMaxHeight = newImage.height - 1;
      for (let i = 0; i < this.height; i++) {
        for (let j = 0; j < this.width; j++) {
          for (let k = 0; k < this.channels; k++) {
            newImage.setValueXY(i, newMaxHeight - j, k, this.getValueXY(j, i, k));
          }
        }
      }
      return newImage;
    }
  }
  /**
   * Rotates an image clockwise
   * @memberof Image
   * @instance
   * @return {Image} The new rotated image
   */

  function rotateRight() {
    if (this.bitDepth === 1) {
      const newImage = new Image(this.height, this.width, {
        kind: 'BINARY',
        parent: this
      });
      const newMaxWidth = newImage.width - 1;
      for (let i = 0; i < this.height; i++) {
        for (let j = 0; j < this.width; j++) {
          if (this.getBitXY(j, i)) {
            newImage.setBitXY(newMaxWidth - i, j);
          }
        }
      }
      return newImage;
    } else {
      const newImage = Image.createFrom(this, {
        width: this.height,
        height: this.width
      });
      const newMaxWidth = newImage.width - 1;
      for (let i = 0; i < this.height; i++) {
        for (let j = 0; j < this.width; j++) {
          for (let k = 0; k < this.channels; k++) {
            newImage.setValueXY(newMaxWidth - i, j, k, this.getValueXY(j, i, k));
          }
        }
      }
      return newImage;
    }
  }
  function rotate180() {
    if (this.bitDepth === 1) {
      const newImage = new Image(this.width, this.height, {
        kind: 'BINARY',
        parent: this
      });
      const newMaxWidth = newImage.width - 1;
      const newMaxHeight = newImage.height - 1;
      for (let i = 0; i < this.height; i++) {
        for (let j = 0; j < this.width; j++) {
          if (this.getBitXY(j, i)) {
            newImage.setBitXY(newMaxWidth - j, newMaxHeight - i);
          }
        }
      }
      return newImage;
    } else {
      const newImage = Image.createFrom(this);
      const newMaxWidth = newImage.width - 1;
      const newMaxHeight = newImage.height - 1;
      for (let i = 0; i < this.height; i++) {
        for (let j = 0; j < this.width; j++) {
          for (let k = 0; k < this.channels; k++) {
            newImage.setValueXY(newMaxWidth - j, newMaxHeight - i, k, this.getValueXY(j, i, k));
          }
        }
      }
      return newImage;
    }
  }

  /**
   * Inserts an image within another image.
   * @memberof Image
   * @instance
   * @param {Image} toInsert The image to insert. Out of boundary pixel will be ignored.
   * @param {object} [options]
   * @param {number} [options.x=0] x offset
   * @param {number} [options.y=0] y offset
   * @param {boolean} [options.inPlace=false] - If true modifies the image. If false the insertion is performed on a copy of the image.
   * @return {Image} The modified image or the new image.
   */
  function insert(toInsert, options = {}) {
    const parameters = getImageParameters(toInsert);
    this.checkProcessable('insert', parameters);
    let {
      x = 0,
      y = 0
    } = options;
    const out = getOutputImageOrInPlace(this, options, {
      copy: true
    });
    const maxY = Math.min(out.height, y + toInsert.height);
    const maxX = Math.min(out.width, x + toInsert.width);
    if (out.bitDepth === 1) {
      for (let j = y; j < maxY; j++) {
        for (let i = x; i < maxX; i++) {
          const val = toInsert.getBitXY(i - x, j - y);
          if (val) out.setBitXY(i, j);else out.clearBitXY(i, j);
        }
      }
    } else {
      for (let j = y; j < maxY; j++) {
        for (let i = x; i < maxX; i++) {
          out.setPixelXY(i, j, toInsert.getPixelXY(i - x, j - y));
        }
      }
    }
    return out;
  }

  /**
   * This method will change the border
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {number} [options.size=0]
   * @param {string} [options.algorithm='copy']
   * @param {number[]} [options.color]
   * @return {this}
   */
  function setBorder(options = {}) {
    let {
      size = 0,
      algorithm = 'copy',
      color
    } = options;
    this.checkProcessable('setBorder', {
      bitDepth: [8, 16, 32, 64]
    });
    if (algorithm === 'set') {
      if (color.length !== this.channels) {
        throw new Error(`setBorder: the color array must have the same length as the number of channels. Here: ${this.channels}`);
      }
      for (let i = 0; i < color.length; i++) {
        if (color[i] === 0) {
          color[i] = 0.001;
        }
      }
    } else {
      color = newArray$1(this.channels, null);
    }
    if (!Array.isArray(size)) {
      size = [size, size];
    }
    let leftRightSize = size[0];
    let topBottomSize = size[1];
    let channels = this.channels;
    for (let i = leftRightSize; i < this.width - leftRightSize; i++) {
      for (let k = 0; k < channels; k++) {
        let value = color[k] || this.data[(i + this.width * topBottomSize) * channels + k];
        for (let j = 0; j < topBottomSize; j++) {
          this.data[(j * this.width + i) * channels + k] = value;
        }
        value = color[k] || this.data[(i + this.width * (this.height - topBottomSize - 1)) * channels + k];
        for (let j = this.height - topBottomSize; j < this.height; j++) {
          this.data[(j * this.width + i) * channels + k] = value;
        }
      }
    }
    for (let j = 0; j < this.height; j++) {
      for (let k = 0; k < channels; k++) {
        let value = color[k] || this.data[(j * this.width + leftRightSize) * channels + k];
        for (let i = 0; i < leftRightSize; i++) {
          this.data[(j * this.width + i) * channels + k] = value;
        }
        value = color[k] || this.data[(j * this.width + this.width - leftRightSize - 1) * channels + k];
        for (let i = this.width - leftRightSize; i < this.width; i++) {
          this.data[(j * this.width + i) * channels + k] = value;
        }
      }
    }
    return this;
  }

  /**
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {boolean} [options.preserveAlpha=true]
   * @return {Stack}
   */
  function split(options = {}) {
    let {
      preserveAlpha = true
    } = options;
    this.checkProcessable('split', {
      bitDepth: [8, 16]
    });

    // split will always return a stack of images
    if (this.components === 1) {
      return new Stack([this.clone()]);
    }
    let images = new Stack();
    let data = this.data;
    if (this.alpha && preserveAlpha) {
      for (let i = 0; i < this.components; i++) {
        let newImage = Image.createFrom(this, {
          components: 1,
          alpha: true,
          colorModel: GREY$1
        });
        let ptr = 0;
        for (let j = 0; j < data.length; j += this.channels) {
          newImage.data[ptr++] = data[j + i];
          newImage.data[ptr++] = data[j + this.components];
        }
        images.push(newImage);
      }
    } else {
      for (let i = 0; i < this.channels; i++) {
        let newImage = Image.createFrom(this, {
          components: 1,
          alpha: false,
          colorModel: GREY$1
        });
        let ptr = 0;
        for (let j = 0; j < data.length; j += this.channels) {
          newImage.data[ptr++] = data[j + i];
        }
        images.push(newImage);
      }
    }
    return images;
  }

  /**
   * Create a grey image based on the selected channel
   * @memberof Image
   * @instance
   * @param {number|string} channel
   * @param {object} [options]
   * @param {boolean} [options.keepAlpha]
   * @param {boolean} [options.mergeAlpha]
   * @return {Image} A grey image with the extracted channel
   */
  function getChannel(channel, options = {}) {
    let {
      keepAlpha = false,
      mergeAlpha = false
    } = options;
    keepAlpha &= this.alpha;
    mergeAlpha &= this.alpha;
    this.checkProcessable('getChannel', {
      bitDepth: [8, 16]
    });
    channel = validateChannel(this, channel);
    let newImage = Image.createFrom(this, {
      components: 1,
      alpha: keepAlpha,
      colorModel: GREY$1
    });
    let ptr = 0;
    for (let j = 0; j < this.data.length; j += this.channels) {
      if (mergeAlpha) {
        newImage.data[ptr++] = this.data[j + channel] * this.data[j + this.components] / this.maxValue;
      } else {
        newImage.data[ptr++] = this.data[j + channel];
        if (keepAlpha) {
          newImage.data[ptr++] = this.data[j + this.components];
        }
      }
    }
    return newImage;
  }

  /**
   * Create a new grey Image by combining the channels of the current image.
   * @memberof Image
   * @instance
   * @param {function} method
   * @param {object} [options]
   * @param {boolean} [options.mergeAlpha=false]
   * @param {boolean} [options.keepAlpha=false]
   * @return {Image}
   */
  function combineChannels(method = defaultCombineMethod, options = {}) {
    let {
      mergeAlpha = false,
      keepAlpha = false
    } = options;
    mergeAlpha &= this.alpha;
    keepAlpha &= this.alpha;
    this.checkProcessable('combineChannels', {
      bitDepth: [8, 16]
    });
    let newImage = Image.createFrom(this, {
      components: 1,
      alpha: keepAlpha,
      colorModel: GREY$1
    });
    let ptr = 0;
    for (let i = 0; i < this.size; i++) {
      // TODO quite slow because we create a new pixel each time
      let value = method(this.getPixel(i));
      if (mergeAlpha) {
        newImage.data[ptr++] = value * this.data[i * this.channels + this.components] / this.maxValue;
      } else {
        newImage.data[ptr++] = value;
        if (keepAlpha) {
          newImage.data[ptr++] = this.data[i * this.channels + this.components];
        }
      }
    }
    return newImage;
  }
  function defaultCombineMethod(pixel) {
    return (pixel[0] + pixel[1] + pixel[2]) / 3;
  }

  /**
   * @memberof Image
   * @instance
   * @param {*} channel
   * @param {Image} image
   *
   * @return {this}
   */
  function setChannel(channel, image) {
    this.checkProcessable('setChannel', {
      bitDepth: [8, 16]
    });
    image.checkProcessable('setChannel (image parameter check)', {
      bitDepth: [this.bitDepth],
      alpha: [0],
      components: [1]
    });
    if (image.width !== this.width || image.height !== this.height) {
      throw new Error('Images must have exactly the same width and height');
    }
    channel = validateChannel(this, channel);
    let ptr = channel;
    for (let i = 0; i < image.data.length; i++) {
      this.data[ptr] = image.data[i];
      ptr += this.channels;
    }
    return this;
  }

  /**
   * Try to match the current pictures with another one. If normalize we normalize separately the 2 images.
   * @memberof Image
   * @instance
   * @param {Image} image - Other image
   * @param {object} [options]
   * @return {number[]|number}
   */
  function getSimilarity(image, options = {}) {
    let {
      shift = [0, 0],
      average,
      channels,
      defaultAlpha,
      normalize,
      border = [0, 0]
    } = options;
    this.checkProcessable('getSimilarity', {
      bitDepth: [8, 16]
    });
    if (!Array.isArray(border)) {
      border = [border, border];
    }
    channels = validateArrayOfChannels(this, {
      channels: channels,
      defaultAlpha: defaultAlpha
    });
    if (this.bitDepth !== image.bitDepth) {
      throw new Error('Both images must have the same bitDepth');
    }
    if (this.channels !== image.channels) {
      throw new Error('Both images must have the same number of channels');
    }
    if (this.colorModel !== image.colorModel) {
      throw new Error('Both images must have the same colorModel');
    }
    if (typeof average === 'undefined') {
      average = true;
    }

    // we allow a shift
    // we need to find the minX, maxX, minY, maxY
    let minX = Math.max(border[0], -shift[0]);
    let maxX = Math.min(this.width - border[0], this.width - shift[0]);
    let minY = Math.max(border[1], -shift[1]);
    let maxY = Math.min(this.height - border[1], this.height - shift[1]);
    let results = newArray$1(channels.length, 0);
    for (let i = 0; i < channels.length; i++) {
      let c = channels[i];
      let sumThis = normalize ? this.sum[c] : Math.max(this.sum[c], image.sum[c]);
      let sumImage = normalize ? image.sum[c] : Math.max(this.sum[c], image.sum[c]);
      if (sumThis !== 0 && sumImage !== 0) {
        for (let x = minX; x < maxX; x++) {
          for (let y = minY; y < maxY; y++) {
            let indexThis = x * this.multiplierX + y * this.multiplierY + c;
            let indexImage = indexThis + shift[0] * this.multiplierX + shift[1] * this.multiplierY;
            results[i] += Math.min(this.data[indexThis] / sumThis, image.data[indexImage] / sumImage);
          }
        }
      }
    }
    if (average) {
      return results.reduce((sum, x) => sum + x) / results.length;
    }
    return results;
  }

  /**
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {number[]} [options.sampling=[10, 10]]
   * @param {boolean} [options.painted=false]
   * @param {Image} [options.mask]
   * @return {object}
   */
  function getPixelsGrid(options = {}) {
    let {
      sampling = [10, 10],
      painted = false,
      mask
    } = options;
    this.checkProcessable('getPixelsGrid', {
      bitDepth: [8, 16],
      channels: 1
    });
    if (!Array.isArray(sampling)) {
      sampling = [sampling, sampling];
    }
    const xSampling = sampling[0];
    const ySampling = sampling[1];
    const xyS = [];
    const zS = [];
    const xStep = this.width / xSampling;
    const yStep = this.height / ySampling;
    let currentX = Math.floor(xStep / 2);
    for (let i = 0; i < xSampling; i++) {
      let currentY = Math.floor(yStep / 2);
      for (let j = 0; j < ySampling; j++) {
        let x = Math.round(currentX);
        let y = Math.round(currentY);
        if (!mask || mask.getBitXY(x, y)) {
          xyS.push([x, y]);
          zS.push(this.getPixelXY(x, y));
        }
        currentY += yStep;
      }
      currentX += xStep;
    }
    const toReturn = {
      xyS,
      zS
    };
    if (painted) {
      toReturn.painted = this.rgba8().paintPoints(xyS);
    }
    return toReturn;
  }

  function Matrix(width, height, defaultValue) {
    const matrix = new Array(width);
    for (let x = 0; x < width; x++) {
      matrix[x] = new Array(height);
    }
    if (defaultValue) {
      for (let x = 0; x < width; x++) {
        for (let y = 0; y < height; y++) {
          matrix[x][y] = defaultValue;
        }
      }
    }
    matrix.width = width;
    matrix.height = height;
    Object.setPrototypeOf(matrix, Matrix.prototype);
    return matrix;
  }
  Matrix.prototype.localMin = function (x, y) {
    let min = this[x][y];
    let position = [x, y];
    for (let i = Math.max(0, x - 1); i < Math.min(this.length, x + 2); i++) {
      for (let j = Math.max(0, y - 1); j < Math.min(this[0].length, y + 2); j++) {
        if (this[i][j] < min) {
          min = this[i][j];
          position = [i, j];
        }
      }
    }
    return {
      position: position,
      value: min
    };
  };
  Matrix.prototype.localMax = function (x, y) {
    let max = this[x][y];
    let position = [x, y];
    for (let i = Math.max(0, x - 1); i < Math.min(this.length, x + 2); i++) {
      for (let j = Math.max(0, y - 1); j < Math.min(this[0].length, y + 2); j++) {
        if (this[i][j] > max) {
          max = this[i][j];
          position = [i, j];
        }
      }
    }
    return {
      position: position,
      value: max
    };
  };
  Matrix.prototype.localSearch = function (x, y, value) {
    let results = [];
    for (let i = Math.max(0, x - 1); i < Math.min(this.length, x + 2); i++) {
      for (let j = Math.max(0, y - 1); j < Math.min(this[0].length, y + 2); j++) {
        if (this[i][j] === value) {
          results.push([i, j]);
        }
      }
    }
    return results;
  };

  /**
   * Try to match the current pictures with another one
   * @memberof Image
   * @instance
   * @param {Image} image - Other image to match
   * @param {object} [options]
   * @return {number[]}
   */
  function getBestMatch(image, options = {}) {
    let {
      border
    } = options;
    this.checkProcessable('getChannel', {
      bitDepth: [8, 16]
    });
    if (this.bitDepth !== image.bitDepth) {
      throw new Error('Both images must have the same bitDepth');
    }
    if (this.channels !== image.channels) {
      throw new Error('Both images must have the same number of channels');
    }
    if (this.colorModel !== image.colorModel) {
      throw new Error('Both images must have the same colorModel');
    }

    // there could be many names
    let similarityMatrix = new Matrix(image.width, image.height, -Infinity);
    let currentX = Math.floor(image.width / 2);
    let currentY = Math.floor(image.height / 2);
    let middleX = currentX;
    let middleY = currentY;
    let theEnd = false;
    while (!theEnd) {
      let toCalculatePositions = similarityMatrix.localSearch(currentX, currentY, -Infinity);
      for (let i = 0; i < toCalculatePositions.length; i++) {
        let position = toCalculatePositions[i];
        let similarity = this.getSimilarity(image, {
          border: border,
          shift: [middleX - position[0], middleY - position[1]]
        });
        similarityMatrix[position[0]][position[1]] = similarity;
      }
      let max = similarityMatrix.localMax(currentX, currentY);
      if (max.position[0] !== currentX || max.position[1] !== currentY) {
        currentX = max.position[0];
        currentY = max.position[1];
      } else {
        theEnd = true;
      }
    }
    return [currentX - middleX, currentY - middleY];
  }

  /**
   * @memberof Image
   * @instance
   * @param {number} row
   * @param {number} [channel=0]
   * @return {number[]}
   */
  function getRow(row, channel = 0) {
    this.checkProcessable('getRow', {
      bitDepth: [8, 16]
    });
    checkRow(this, row);
    checkChannel(this, channel);
    let array = new Array(this.width);
    let ptr = 0;
    let begin = row * this.width * this.channels + channel;
    let end = begin + this.width * this.channels;
    for (let j = begin; j < end; j += this.channels) {
      array[ptr++] = this.data[j];
    }
    return array;
  }

  /**
   * @memberof Image
   * @instance
   * @param {number} column
   * @param {number} [channel=0]
   * @return {number[]}
   */
  function getColumn(column, channel = 0) {
    this.checkProcessable('getColumn', {
      bitDepth: [8, 16]
    });
    checkColumn(this, column);
    checkChannel(this, channel);
    let array = new Array(this.height);
    let ptr = 0;
    let step = this.width * this.channels;
    for (let j = channel + column * this.channels; j < this.data.length; j += step) {
      array[ptr++] = this.data[j];
    }
    return array;
  }

  /**
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {number} [options.channel]
   * @return {Matrix}
   */
  function getMatrix(options = {}) {
    let {
      channel
    } = options;
    this.checkProcessable('getMatrix', {
      bitDepth: [8, 16]
    });
    if (channel === undefined) {
      if (this.components > 1) {
        throw new RangeError('You need to define the channel for an image that contains more than one channel');
      }
      channel = 0;
    }
    let matrix = new Matrix$2(this.height, this.width);
    for (let x = 0; x < this.height; x++) {
      for (let y = 0; y < this.width; y++) {
        matrix.set(x, y, this.getValueXY(y, x, channel));
      }
    }
    return matrix;
  }

  /**
   * We set the data of the image from a matrix. The size of the matrix and the data have to be the same.
   * @memberof Image
   * @instance
   * @param {Matrix} matrix
   * @param {object} [options]
   * @param {number} [options.channel]
   *
   * @return {this}
   */
  function setMatrix(matrix, options = {}) {
    matrix = new Matrix$2(matrix);
    let {
      channel
    } = options;
    this.checkProcessable('getMatrix', {
      bitDepth: [8, 16]
    });
    if (channel === undefined) {
      if (this.components > 1) {
        throw new RangeError('You need to define the channel for an image that contains more than one channel');
      }
      channel = 0;
    }
    if (this.width !== matrix.columns || this.height !== matrix.rows) {
      throw new RangeError('The size of the matrix must be equal to the size of the image');
    }
    for (let x = 0; x < this.height; x++) {
      for (let y = 0; y < this.width; y++) {
        this.setValueXY(y, x, channel, matrix.get(x, y));
      }
    }
    return this;
  }

  /**
   * Returns an array of arrays containing the pixel values in the form
   * [[R1, G1, B1], [R2, G2, B2], ...]
   * @memberof Image
   * @instance
   * @return {Array<Array<number>>}
   */
  function getPixelsArray() {
    this.checkProcessable('getPixelsArray', {
      bitDepth: [8, 16, 32]
    });
    let array = new Array(this.size);
    let ptr = 0;
    for (let i = 0; i < this.data.length; i += this.channels) {
      let pixel = new Array(this.components);
      for (let j = 0; j < this.components; j++) {
        pixel[j] = this.data[i + j];
      }
      array[ptr++] = pixel;
    }
    return array;
  }

  /**
   * Find intersection of points between two different masks
   * @memberof Image
   * @instance
   * @param {Image} mask2 - a mask (1 bit image)
   * @return {object} - object containing number of white pixels for mask1, for mask 2 and for them both
   */
  function getIntersection(mask2) {
    let mask1 = this;
    let closestParent = mask1.getClosestCommonParent(mask2);
    let startPos1 = mask1.getRelativePosition(closestParent, {
      defaultFurther: true
    });
    let allRelPos1 = getRelativePositionForAllPixels(mask1, startPos1);
    let startPos2 = mask2.getRelativePosition(closestParent, {
      defaultFurther: true
    });
    let allRelPos2 = getRelativePositionForAllPixels(mask2, startPos2);
    let commonSurface = getCommonSurface(allRelPos1, allRelPos2);
    let intersection = {
      whitePixelsMask1: [],
      whitePixelsMask2: [],
      commonWhitePixels: []
    };
    for (let i = 0; i < commonSurface.length; i++) {
      let currentRelativePos = commonSurface[i];
      let realPos1 = [currentRelativePos[0] - startPos1[0], currentRelativePos[1] - startPos1[1]];
      let realPos2 = [currentRelativePos[0] - startPos2[0], currentRelativePos[1] - startPos2[1]];
      let valueBitMask1 = mask1.getBitXY(realPos1[0], realPos1[1]);
      let valueBitMask2 = mask2.getBitXY(realPos2[0], realPos2[1]);
      if (valueBitMask1 === 1 && valueBitMask2 === 1) {
        intersection.commonWhitePixels.push(currentRelativePos);
      }
    }
    for (let i = 0; i < allRelPos1.length; i++) {
      let posX;
      let posY;
      if (i !== 0) {
        posX = Math.floor(i / mask1.width);
        posY = i % mask1.width;
      }
      if (mask1.getBitXY(posX, posY) === 1) {
        intersection.whitePixelsMask1.push(allRelPos1[i]);
      }
    }
    for (let i = 0; i < allRelPos2.length; i++) {
      let posX = 0;
      let posY = 0;
      if (i !== 0) {
        posX = Math.floor(i / mask2.width);
        posY = i % mask2.width;
      }
      if (mask2.getBitXY(posX, posY) === 1) {
        intersection.whitePixelsMask2.push(allRelPos2[i]);
      }
    }
    return intersection;
  }

  /**
   * Get relative position array for all pixels in masks
   * @param {Image} mask - a mask (1 bit image)
   * @param {Array<number>} startPosition - start position of mask relative to parent
   * @return {Array} - relative position of all pixels
   * @private
   */
  function getRelativePositionForAllPixels(mask, startPosition) {
    let relativePositions = [];
    for (let i = 0; i < mask.height; i++) {
      for (let j = 0; j < mask.width; j++) {
        let originalPos = [i, j];
        relativePositions.push([originalPos[0] + startPosition[0], originalPos[1] + startPosition[1]]);
      }
    }
    return relativePositions;
  }

  /**
   * Finds common surface for two arrays containing the positions of the pixels relative to parent image
   * @param {Array<number>} positionArray1 - positions of pixels relative to parent
   * @param {Array<number>} positionArray2 - positions of pixels relative to parent
   * @return {Array<number>} - positions of common pixels for both arrays
   * @private
   */
  function getCommonSurface(positionArray1, positionArray2) {
    let i = 0;
    let j = 0;
    let commonSurface = [];
    while (i < positionArray1.length && j < positionArray2.length) {
      if (positionArray1[i][0] === positionArray2[j][0] && positionArray1[i][1] === positionArray2[j][1]) {
        commonSurface.push(positionArray1[i]);
        i++;
        j++;
      } else if (positionArray1[i][0] < positionArray2[j][0] || positionArray1[i][0] === positionArray2[j][0] && positionArray1[i][1] < positionArray2[j][1]) {
        i++;
      } else {
        j++;
      }
    }
    return commonSurface;
  }

  /**
   * Finds common parent between two different masks
   * @memberof Image
   * @instance
   * @param {Image} mask - a mask (1 bit image)
   * @return {Image} - the lowest common parent of both masks
   */
  function getClosestCommonParent(mask) {
    let depthMask1 = getDepth(this);
    let depthMask2 = getDepth(mask);
    let furthestParent;
    if (depthMask1 >= depthMask2) {
      furthestParent = getFurthestParent(this, depthMask1);
    } else {
      furthestParent = getFurthestParent(mask, depthMask2);
    }
    if (depthMask1 === 0 || depthMask2 === 0) {
      // comparing with at least one original image -> no common parent
      return furthestParent;
    }
    let m1 = this;
    let m2 = mask;
    while (depthMask1 !== depthMask2) {
      if (depthMask1 > depthMask2) {
        m1 = m1.parent;
        if (m1 === null) {
          return furthestParent;
        }
        depthMask1 = depthMask1 - 1;
      } else {
        m2 = m2.parent;
        if (m2 === null) {
          return furthestParent;
        }
        depthMask2 = depthMask2 - 1;
      }
    }
    while (m1 !== m2 && m1 !== null && m2 !== null) {
      m1 = m1.parent;
      m2 = m2.parent;
      if (m1 === null || m2 === null) {
        return furthestParent;
      }
    }

    // TODO
    // no common parent, use parent at top of hierarchy of m1
    // we assume it works for now
    if (m1 !== m2) {
      return furthestParent;
    }
    return m1;
  }

  /**
   * Find the depth of the mask with respect to its arborescence.
   * Helper function to find the common parent between two masks.
   * @param {Image} mask - a mask (1 bit Image)
   * @return {number} - depth of mask
   * @private
   */
  function getDepth(mask) {
    let d = 0;
    let m = mask;
    // a null parent means it's the original image
    while (m.parent != null) {
      m = m.parent;
      d++;
    }
    return d;
  }
  function getFurthestParent(mask, depth) {
    let m = mask;
    while (depth > 0) {
      m = m.parent;
      depth = depth - 1;
    }
    return m;
  }

  const defaultOptions$1 = {
    lowThreshold: 10,
    highThreshold: 30,
    gaussianBlur: 1.1
  };
  const Gx = [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]];
  const Gy = [[-1, -2, -1], [0, 0, 0], [1, 2, 1]];
  const convOptions = {
    bitDepth: 32,
    mode: 'periodic'
  };
  function cannyEdgeDetector(image, options) {
    image.checkProcessable('Canny edge detector', {
      bitDepth: 8,
      channels: 1,
      components: 1
    });
    options = Object.assign({}, defaultOptions$1, options);
    const width = image.width;
    const height = image.height;
    const brightness = image.maxValue;
    const gfOptions = {
      sigma: options.gaussianBlur,
      radius: 3
    };
    const gf = image.gaussianFilter(gfOptions);
    const gradientX = gf.convolution(Gy, convOptions);
    const gradientY = gf.convolution(Gx, convOptions);
    const G = gradientY.hypotenuse(gradientX);
    const Image = image.constructor;
    const nms = new Image(width, height, {
      kind: 'GREY',
      bitDepth: 32
    });
    const edges = new Image(width, height, {
      kind: 'GREY',
      bitDepth: 32
    });
    const finalImage = new Image(width, height, {
      kind: 'GREY'
    });

    // Non-Maximum supression
    for (var i = 1; i < width - 1; i++) {
      for (var j = 1; j < height - 1; j++) {
        var dir = (Math.round(Math.atan2(gradientY.getValueXY(i, j, 0), gradientX.getValueXY(i, j, 0)) * (5.0 / Math.PI)) + 5) % 5;
        if (!(dir === 0 && (G.getValueXY(i, j, 0) <= G.getValueXY(i, j - 1, 0) || G.getValueXY(i, j, 0) <= G.getValueXY(i, j + 1, 0)) || dir === 1 && (G.getValueXY(i, j, 0) <= G.getValueXY(i - 1, j + 1, 0) || G.getValueXY(i, j, 0) <= G.getValueXY(i + 1, j - 1, 0)) || dir === 2 && (G.getValueXY(i, j, 0) <= G.getValueXY(i - 1, j, 0) || G.getValueXY(i, j, 0) <= G.getValueXY(i + 1, j, 0)) || dir === 3 && (G.getValueXY(i, j, 0) <= G.getValueXY(i - 1, j - 1, 0) || G.getValueXY(i, j, 0) <= G.getValueXY(i + 1, j + 1, 0)))) {
          nms.setValueXY(i, j, 0, G.getValueXY(i, j, 0));
        }
      }
    }
    for (i = 0; i < width * height; ++i) {
      var currentNms = nms.data[i];
      var currentEdge = 0;
      if (currentNms > options.highThreshold) {
        currentEdge++;
        finalImage.data[i] = brightness;
      }
      if (currentNms > options.lowThreshold) {
        currentEdge++;
      }
      edges.data[i] = currentEdge;
    }

    // Hysteresis: first pass
    var currentPixels = [];
    for (i = 1; i < width - 1; ++i) {
      for (j = 1; j < height - 1; ++j) {
        if (edges.getValueXY(i, j, 0) !== 1) {
          continue;
        }
        outer: for (var k = i - 1; k < i + 2; ++k) {
          for (var l = j - 1; l < j + 2; ++l) {
            if (edges.getValueXY(k, l, 0) === 2) {
              currentPixels.push([i, j]);
              finalImage.setValueXY(i, j, 0, brightness);
              break outer;
            }
          }
        }
      }
    }

    // Hysteresis: second pass
    while (currentPixels.length > 0) {
      var newPixels = [];
      for (i = 0; i < currentPixels.length; ++i) {
        for (j = -1; j < 2; ++j) {
          for (k = -1; k < 2; ++k) {
            if (j === 0 && k === 0) {
              continue;
            }
            var row = currentPixels[i][0] + j;
            var col = currentPixels[i][1] + k;
            if (edges.getValueXY(row, col, 0) === 1 && finalImage.getValueXY(row, col, 0) === 0) {
              newPixels.push([row, col]);
              finalImage.setValueXY(row, col, 0, brightness);
            }
          }
        }
      }
      currentPixels = newPixels;
    }
    return finalImage;
  }

  /**
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {number} [options.gaussianBlur=1.1] - Sigma parameter for the gaussian filter step
   * @param {number} [options.lowThreshold=10] - Low threshold for the hysteresis procedure
   * @param {number} [options.highThreshold=30] - High threshold for the hysteresis procedure
   * @return {Image}
   */
  function cannyEdge(options) {
    return cannyEdgeDetector(this, options);
  }

  /**
   * Extracts a part of an original image based on a mask. By default the mask may contain
   * a relative position and this part of the original image will be extracted.
   * @memberof Image
   * @instance
   * @param {Image} mask - Image containing a binary mask
   * @param {object} [options]
   * @param {number[]} [options.position] - Array of 2 elements to force the x,y coordinates
   * @return {Image} A new image
   */
  function extract(mask, options = {}) {
    let {
      position
    } = options;
    this.checkProcessable('extract', {
      bitDepth: [1, 8, 16]
    });

    // we need to find the relative position to the parent
    if (!position) {
      position = mask.getRelativePosition(this);
      if (!position) {
        throw new Error('extract : can not extract an image because the relative position can not be ' + 'determined, try to specify manually the position as an array of 2 elements [x,y].');
      }
    }
    if (this.bitDepth > 1) {
      let extract = Image.createFrom(this, {
        width: mask.width,
        height: mask.height,
        alpha: 1,
        // we force the alpha, otherwise difficult to extract a mask ...
        position: position,
        parent: this
      });
      for (let x = 0; x < mask.width; x++) {
        for (let y = 0; y < mask.height; y++) {
          // we copy the point
          for (let channel = 0; channel < this.channels; channel++) {
            let value = this.getValueXY(x + position[0], y + position[1], channel);
            extract.setValueXY(x, y, channel, value);
          }
          // we make it transparent in case it is not in the mask
          if (!mask.getBitXY(x, y)) {
            extract.setValueXY(x, y, this.components, 0);
          }
        }
      }
      return extract;
    } else {
      let extract = Image.createFrom(this, {
        width: mask.width,
        height: mask.height,
        position: position,
        parent: this
      });
      for (let y = 0; y < mask.height; y++) {
        for (let x = 0; x < mask.width; x++) {
          if (mask.getBitXY(x, y)) {
            if (this.getBitXY(x + position[0], y + position[1])) {
              extract.setBitXY(x, y);
            }
          }
        }
      }
      return extract;
    }
  }

  var fastList = {exports: {}};

  (function (module, exports) {
    (function () {
      // closure for web browsers

      function Item(data, prev, next) {
        this.next = next;
        if (next) next.prev = this;
        this.prev = prev;
        if (prev) prev.next = this;
        this.data = data;
      }
      function FastList() {
        if (!(this instanceof FastList)) return new FastList();
        this._head = null;
        this._tail = null;
        this.length = 0;
      }
      FastList.prototype = {
        push: function (data) {
          this._tail = new Item(data, this._tail, null);
          if (!this._head) this._head = this._tail;
          this.length++;
        },
        pop: function () {
          if (this.length === 0) return undefined;
          var t = this._tail;
          this._tail = t.prev;
          if (t.prev) {
            t.prev = this._tail.next = null;
          }
          this.length--;
          if (this.length === 1) this._head = this._tail;else if (this.length === 0) this._head = this._tail = null;
          return t.data;
        },
        unshift: function (data) {
          this._head = new Item(data, null, this._head);
          if (!this._tail) this._tail = this._head;
          this.length++;
        },
        shift: function () {
          if (this.length === 0) return undefined;
          var h = this._head;
          this._head = h.next;
          if (h.next) {
            h.next = this._head.prev = null;
          }
          this.length--;
          if (this.length === 1) this._tail = this._head;else if (this.length === 0) this._head = this._tail = null;
          return h.data;
        },
        item: function (n) {
          if (n < 0) n = this.length + n;
          var h = this._head;
          while (n-- > 0 && h) h = h.next;
          return h ? h.data : undefined;
        },
        slice: function (n, m) {
          if (!n) n = 0;
          if (!m) m = this.length;
          if (m < 0) m = this.length + m;
          if (n < 0) n = this.length + n;
          if (m === n) {
            return [];
          }
          if (m < n) {
            throw new Error("invalid offset: " + n + "," + m + " (length=" + this.length + ")");
          }
          var len = m - n,
            ret = new Array(len),
            i = 0,
            h = this._head;
          while (n-- > 0 && h) h = h.next;
          while (i < len && h) {
            ret[i++] = h.data;
            h = h.next;
          }
          return ret;
        },
        drop: function () {
          FastList.call(this);
        },
        forEach: function (fn, thisp) {
          var p = this._head,
            i = 0,
            len = this.length;
          while (i < len && p) {
            fn.call(thisp || this, p.data, i, this);
            p = p.next;
            i++;
          }
        },
        map: function (fn, thisp) {
          var n = new FastList();
          this.forEach(function (v, i, me) {
            n.push(fn.call(thisp || me, v, i, me));
          });
          return n;
        },
        filter: function (fn, thisp) {
          var n = new FastList();
          this.forEach(function (v, i, me) {
            if (fn.call(thisp || me, v, i, me)) n.push(v);
          });
          return n;
        },
        reduce: function (fn, val, thisp) {
          var i = 0,
            p = this._head,
            len = this.length;
          if (!val) {
            i = 1;
            val = p && p.data;
            p = p && p.next;
          }
          while (i < len && p) {
            val = fn.call(thisp || this, val, p.data, this);
            i++;
            p = p.next;
          }
          return val;
        }
      };
      module.exports = FastList;
    })();
  })(fastList);
  var fastListExports = fastList.exports;
  var LinkedList = /*@__PURE__*/getDefaultExportFromCjs(fastListExports);

  function floodFill(options = {}) {
    const {
      x = 0,
      y = 0,
      inPlace = true
    } = options;
    const destination = inPlace ? this : Image.createFrom(this);
    this.checkProcessable('floodFill', {
      bitDepth: 1
    });
    const bit = this.getBitXY(x, y);
    if (bit) return destination;
    const queue = new LinkedList();
    queue.push(new Node(x, y));
    while (queue.length > 0) {
      const node = queue.shift();
      destination.setBitXY(node.x, node.y);
      for (let i = node.x + 1; i < this.width; i++) {
        if (!destination.getBitXY(i, node.y) && !this.getBitXY(i, node.y)) {
          destination.setBitXY(i, node.y);
          if (node.y + 1 < this.height && !this.getBitXY(i, node.y + 1)) {
            queue.push(new Node(i, node.y + 1));
          }
          if (node.y - 1 >= 0 && !this.getBitXY(i, node.y - 1)) {
            queue.push(new Node(i, node.y - 1));
          }
        } else {
          break;
        }
      }
      // eslint-disable-next-line for-direction
      for (let i = node.x - 1; i >= 0; i++) {
        if (!destination.getBitXY(i, node.y) && !this.getBitXY(i, node.y)) {
          destination.setBitXY(i, node.y);
          if (node.y + 1 < this.height && !this.getBitXY(i, node.y + 1)) {
            queue.push(new Node(i, node.y + 1));
          }
          if (node.y - 1 >= 0 && !this.getBitXY(i, node.y - 1)) {
            queue.push(new Node(i, node.y - 1));
          }
        } else {
          break;
        }
      }
    }
    return destination;
  }
  function Node(x, y) {
    this.x = x;
    this.y = y;
  }

  function _extends() {
    return _extends = Object.assign ? Object.assign.bind() : function (n) {
      for (var e = 1; e < arguments.length; e++) {
        var t = arguments[e];
        for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
      }
      return n;
    }, _extends.apply(null, arguments);
  }

  function hsv2rgb(h, s, v) {
    s = s / 100;
    v = v / 100;
    var rgb = [];
    var c = v * s;
    var hh = h / 60;
    var x = c * (1 - Math.abs(hh % 2 - 1));
    var m = v - c;
    if (hh >= 0 && hh < 1) {
      rgb = [c, x, 0];
    } else if (hh >= 1 && hh < 2) {
      rgb = [x, c, 0];
    } else if (hh >= 2 && hh < 3) {
      rgb = [0, c, x];
    } else if (h >= 3 && hh < 4) {
      rgb = [0, x, c];
    } else if (h >= 4 && hh < 5) {
      rgb = [x, 0, c];
    } else if (h >= 5 && hh <= 6) {
      rgb = [c, 0, x];
    } else {
      rgb = [0, 0, 0];
    }
    return {
      r: Math.round(255 * (rgb[0] + m)),
      g: Math.round(255 * (rgb[1] + m)),
      b: Math.round(255 * (rgb[2] + m))
    };
  }
  function hsl2hsv(h, s, l) {
    s *= (l < 50 ? l : 100 - l) / 100;
    return {
      h: h,
      s: 2 * s / (l + s) * 100,
      v: l + s
    };
  }
  function hsl2rgb$1(h, s, l) {
    var hsv = hsl2hsv(h, s, l);
    return hsv2rgb(hsv.h, hsv.s, hsv.v);
  }
  var colors = {
    aliceblue: [240, 248, 255],
    antiquewhite: [250, 235, 215],
    aqua: [0, 255, 255],
    aquamarine: [127, 255, 212],
    azure: [240, 255, 255],
    beige: [245, 245, 220],
    bisque: [255, 228, 196],
    black: [0, 0, 0],
    blanchedalmond: [255, 235, 205],
    blue: [0, 0, 255],
    blueviolet: [138, 43, 226],
    brown: [165, 42, 42],
    burlywood: [222, 184, 135],
    cadetblue: [95, 158, 160],
    chartreuse: [127, 255, 0],
    chocolate: [210, 105, 30],
    coral: [255, 127, 80],
    cornflowerblue: [100, 149, 237],
    cornsilk: [255, 248, 220],
    crimson: [220, 20, 60],
    cyan: [0, 255, 255],
    darkblue: [0, 0, 139],
    darkcyan: [0, 139, 139],
    darkgoldenrod: [184, 132, 11],
    darkgray: [169, 169, 169],
    darkgreen: [0, 100, 0],
    darkgrey: [169, 169, 169],
    darkkhaki: [189, 183, 107],
    darkmagenta: [139, 0, 139],
    darkolivegreen: [85, 107, 47],
    darkorange: [255, 140, 0],
    darkorchid: [153, 50, 204],
    darkred: [139, 0, 0],
    darksalmon: [233, 150, 122],
    darkseagreen: [143, 188, 143],
    darkslateblue: [72, 61, 139],
    darkslategray: [47, 79, 79],
    darkslategrey: [47, 79, 79],
    darkturquoise: [0, 206, 209],
    darkviolet: [148, 0, 211],
    deeppink: [255, 20, 147],
    deepskyblue: [0, 191, 255],
    dimgray: [105, 105, 105],
    dimgrey: [105, 105, 105],
    dodgerblue: [30, 144, 255],
    firebrick: [178, 34, 34],
    floralwhite: [255, 255, 240],
    forestgreen: [34, 139, 34],
    fuchsia: [255, 0, 255],
    gainsboro: [220, 220, 220],
    ghostwhite: [248, 248, 255],
    gold: [255, 215, 0],
    goldenrod: [218, 165, 32],
    gray: [128, 128, 128],
    green: [0, 128, 0],
    greenyellow: [173, 255, 47],
    grey: [128, 128, 128],
    honeydew: [240, 255, 240],
    hotpink: [255, 105, 180],
    indianred: [205, 92, 92],
    indigo: [75, 0, 130],
    ivory: [255, 255, 240],
    khaki: [240, 230, 140],
    lavender: [230, 230, 250],
    lavenderblush: [255, 240, 245],
    lawngreen: [124, 252, 0],
    lemonchiffon: [255, 250, 205],
    lightblue: [173, 216, 230],
    lightcoral: [240, 128, 128],
    lightcyan: [224, 255, 255],
    lightgoldenrodyellow: [250, 250, 210],
    lightgray: [211, 211, 211],
    lightgreen: [144, 238, 144],
    lightgrey: [211, 211, 211],
    lightpink: [255, 182, 193],
    lightsalmon: [255, 160, 122],
    lightseagreen: [32, 178, 170],
    lightskyblue: [135, 206, 250],
    lightslategray: [119, 136, 153],
    lightslategrey: [119, 136, 153],
    lightsteelblue: [176, 196, 222],
    lightyellow: [255, 255, 224],
    lime: [0, 255, 0],
    limegreen: [50, 205, 50],
    linen: [250, 240, 230],
    magenta: [255, 0, 255],
    maroon: [128, 0, 0],
    mediumaquamarine: [102, 205, 170],
    mediumblue: [0, 0, 205],
    mediumorchid: [186, 85, 211],
    mediumpurple: [147, 112, 219],
    mediumseagreen: [60, 179, 113],
    mediumslateblue: [123, 104, 238],
    mediumspringgreen: [0, 250, 154],
    mediumturquoise: [72, 209, 204],
    mediumvioletred: [199, 21, 133],
    midnightblue: [25, 25, 112],
    mintcream: [245, 255, 250],
    mistyrose: [255, 228, 225],
    moccasin: [255, 228, 181],
    navajowhite: [255, 222, 173],
    navy: [0, 0, 128],
    oldlace: [253, 245, 230],
    olive: [128, 128, 0],
    olivedrab: [107, 142, 35],
    orange: [255, 165, 0],
    orangered: [255, 69, 0],
    orchid: [218, 112, 214],
    palegoldenrod: [238, 232, 170],
    palegreen: [152, 251, 152],
    paleturquoise: [175, 238, 238],
    palevioletred: [219, 112, 147],
    papayawhip: [255, 239, 213],
    peachpuff: [255, 218, 185],
    peru: [205, 133, 63],
    pink: [255, 192, 203],
    plum: [221, 160, 203],
    powderblue: [176, 224, 230],
    purple: [128, 0, 128],
    rebeccapurple: [102, 51, 153],
    red: [255, 0, 0],
    rosybrown: [188, 143, 143],
    royalblue: [65, 105, 225],
    saddlebrown: [139, 69, 19],
    salmon: [250, 128, 114],
    sandybrown: [244, 164, 96],
    seagreen: [46, 139, 87],
    seashell: [255, 245, 238],
    sienna: [160, 82, 45],
    silver: [192, 192, 192],
    skyblue: [135, 206, 235],
    slateblue: [106, 90, 205],
    slategray: [119, 128, 144],
    slategrey: [119, 128, 144],
    snow: [255, 255, 250],
    springgreen: [0, 255, 127],
    steelblue: [70, 130, 180],
    tan: [210, 180, 140],
    teal: [0, 128, 128],
    thistle: [216, 191, 216],
    tomato: [255, 99, 71],
    turquoise: [64, 224, 208],
    violet: [238, 130, 238],
    wheat: [245, 222, 179],
    white: [255, 255, 255],
    whitesmoke: [245, 245, 245],
    yellow: [255, 255, 0],
    yellowgreen: [154, 205, 5]
  };
  function parse(str) {
    return named(str) || hex3(str) || hex6(str) || rgb(str) || rgba$1(str) || hsl(str) || hsla(str);
  }
  function named(str) {
    var c = colors[str.toLowerCase()];
    if (!c) return;
    return {
      r: c[0],
      g: c[1],
      b: c[2],
      a: 100
    };
  }
  function rgb(str) {
    var m = str.match(/rgb\(([^)]+)\)/);
    if (m) {
      var parts = m[1].split(/ *, */).map(Number);
      return {
        r: parts[0],
        g: parts[1],
        b: parts[2],
        a: 100
      };
    }
  }
  function rgba$1(str) {
    var m = str.match(/rgba\(([^)]+)\)/);
    if (m) {
      var parts = m[1].split(/ *, */).map(Number);
      return {
        r: parts[0],
        g: parts[1],
        b: parts[2],
        a: parts[3] * 100
      };
    }
  }
  function hex6(str) {
    if ('#' === str[0] && 7 === str.length) {
      return {
        r: parseInt(str.slice(1, 3), 16),
        g: parseInt(str.slice(3, 5), 16),
        b: parseInt(str.slice(5, 7), 16),
        a: 100
      };
    }
  }
  function hex3(str) {
    if ('#' === str[0] && 4 === str.length) {
      return {
        r: parseInt(str[1] + str[1], 16),
        g: parseInt(str[2] + str[2], 16),
        b: parseInt(str[3] + str[3], 16),
        a: 100
      };
    }
  }
  function hsl(str) {
    var m = str.match(/hsl\(([^)]+)\)/);
    if (m) {
      var parts = m[1].split(/ *, */);
      var h = parseInt(parts[0], 10);
      var s = parseInt(parts[1], 10);
      var l = parseInt(parts[2], 10);
      var _rgb = hsl2rgb$1(h, s, l);
      return _extends({}, _rgb, {
        a: 100
      });
    }
  }
  function hsla(str) {
    var m = str.match(/hsla\(([^)]+)\)/);
    if (m) {
      var parts = m[1].split(/ *, */);
      var h = parseInt(parts[0], 10);
      var s = parseInt(parts[1], 10);
      var l = parseInt(parts[2], 10);
      var a = parseInt(parseFloat(parts[3]) * 100, 10);
      var _rgb2 = hsl2rgb$1(h, s, l);
      return _extends({}, _rgb2, {
        a: a
      });
    }
  }

  function css2array(string) {
    let color = parse(string);
    return [color.r, color.g, color.b, Math.round(color.a * 255 / 100)];
  }
  function hue2rgb(p, q, t) {
    if (t < 0) {
      t += 1;
    }
    if (t > 1) {
      t -= 1;
    }
    if (t < 1 / 6) {
      return p + (q - p) * 6 * t;
    }
    if (t < 1 / 2) {
      return q;
    }
    if (t < 2 / 3) {
      return p + (q - p) * (2 / 3 - t) * 6;
    }
    return p;
  }
  function hsl2rgb(h, s, l) {
    let m1, m2, hue, r, g, b;
    s /= 100;
    l /= 100;
    if (s === 0) {
      r = g = b = l * 255;
    } else {
      if (l <= 0.5) {
        m2 = l * (s + 1);
      } else {
        m2 = l + s - l * s;
      }
      m1 = l * 2 - m2;
      hue = h / 360;
      r = hue2rgb(m1, m2, hue + 1 / 3);
      g = hue2rgb(m1, m2, hue);
      b = hue2rgb(m1, m2, hue - 1 / 3);
    }
    return {
      r: r,
      g: g,
      b: b
    };
  }
  function getDistinctColors(numColors) {
    let colors = new Array(numColors);
    let j = 0;
    for (let i = 0; i < 360; i += 360 / numColors) {
      j++;
      let color = hsl2rgb(i, 100, 30 + j % 4 * 15);
      colors[j - 1] = [Math.round(color.r * 255), Math.round(color.g * 255), Math.round(color.b * 255)];
    }
    return colors;
  }
  function getRandomColor() {
    return [Math.floor(Math.random() * 256), Math.floor(Math.random() * 256), Math.floor(Math.random() * 256)];
  }

  /**
   * returns an array of colors based on various options
   * by default this methods return 50 distinct colors
   * @param {object} [options]
   * @param {Array<number>|string}     [options.color] - Array of 3 elements (R, G, B) or a valid css color.
   * @param {Array<Array<number>>|Array<string>} [options.colors] - Array of Array of 3 elements (R, G, B) for each color of each mask
   * @param {boolean}             [options.randomColors=true] - To paint each mask with a random color if color and colors are undefined
   * @param {boolean}             [options.distinctColors=false] - To paint each mask with a different color if color and colors are undefined
   * @param {boolean}             [options.numberColors=50] - number of colors to generate by default
   * @return {Array} Array of colors
   * @private
   */
  function getColors(options) {
    let {
      color,
      colors,
      randomColors,
      // true / false
      numberColors = 50
    } = options;
    if (color && !Array.isArray(color)) {
      color = css2array(color);
    }
    if (color) {
      return [color];
    }
    if (colors) {
      colors = colors.map(function (color) {
        if (!Array.isArray(color)) {
          return css2array(color);
        }
        return color;
      });
      return colors;
    }
    if (randomColors) {
      colors = new Array(numberColors);
      for (let i = 0; i < numberColors; i++) {
        colors[i] = getRandomColor();
      }
    }
    return getDistinctColors(numberColors);
  }

  /**
   * Paint a label or labels on the current image.
   * @memberof Image
   * @instance
   *
   * @param {Array<string>}           [labels] - Array of labels to display.
   * @param {Array<Array<number>>}    [positions] - Array of points [x,y] where the labels should be displayed.
   * @param {object}                  [options]
   * @param {Array<number>|string}    [options.color='red'] - Array of 3 elements (R, G, B) or a valid css color.
   * @param {Array<Array<number>>|Array<string>} [options.colors] - Array of Array of 3 elements (R, G, B) for each color of each label.
   * @param {string|Array<string>} [options.font='12px Helvetica'] - Paint the labels in a different CSS style
   * @param {number|Array<number>} [options.rotate=0] - Rotate each label of a define angle
   * @return {this} The original painted image
   */
  function paintLabels(labels, positions, options = {}) {
    let {
      color = 'blue',
      colors,
      font = '12px Helvetica',
      rotate = 0
    } = options;
    this.checkProcessable('paintMasks', {
      channels: [3, 4],
      bitDepth: [8, 16],
      colorModel: RGB$1
    });
    if (!Array.isArray(labels)) {
      throw Error('paintLabels: labels must be an array');
    }
    if (!Array.isArray(positions)) {
      throw Error('paintLabels: positions must be an array');
    }
    if (color && !Array.isArray(color)) {
      color = css2array(color);
    }
    if (colors) {
      colors = colors.map(function (color) {
        if (!Array.isArray(color)) {
          return css2array(color);
        }
        return color;
      });
    } else {
      colors = [color];
    }
    if (labels.length !== positions.length) {
      throw Error('paintLabels: positions and labels must be arrays from the same size');
    }

    // We convert everything to array so that we can simply loop thourgh all the labels
    if (!Array.isArray(font)) font = [font];
    if (!Array.isArray(rotate)) rotate = [rotate];
    let canvas = this.getCanvas();
    let ctx = canvas.getContext('2d');
    for (let i = 0; i < labels.length; i++) {
      ctx.save();
      let color = colors[i % colors.length];
      ctx.fillStyle = `rgba(${color[0]},${color[1]},${color[2]},${color[3] / this.maxValue})`;
      ctx.font = font[i % font.length];
      let position = positions[i];
      ctx.translate(position[0], position[1]);
      ctx.rotate(rotate[i % rotate.length] / 180 * Math.PI);
      ctx.fillText(labels[i], 0, 0);
      ctx.restore();
    }
    this.data = Uint8Array.from(ctx.getImageData(0, 0, this.width, this.height).data);
    return this;
  }

  /**
   * Paint a mask or masks on the current image.
   * @memberof Image
   * @instance
   * @param {(Image|Array<Image>)}     masks - Image containing a binary mask
   * @param {object}              [options]
   * @param {Array<number>|string}     [options.color] - Array of 3 elements (R, G, B) or a valid css color.
   * @param {Array<Array<number>>|Array<string>} [options.colors] - Array of Array of 3 elements (R, G, B) for each color of each mask
   * @param {boolean}             [options.randomColors=true] - To paint each mask with a random color if color and colors are undefined
   * @param {boolean}             [options.distinctColors=false] - To paint each mask with a different color if color and colors are undefined
   * @param {number}              [options.alpha=255] - Value from 0 to 255 to specify the alpha.
   * @param {Array<string>}       [options.labels] - Array of labels to display. Should the the same size as masks.
   * @param {Array<Array<number>>} [options.labelsPosition] - Array of points [x,y] where the labels should be displayed.
   *                                      By default it is the 0,0 position of the correesponding mask.
   * @param {string}              [options.labelColor='blue'] - Define the color to paint the labels
   * @param {string}              [options.labelFont='12px Helvetica'] - Paint the labels in a different CSS style
   * @return {this} The original painted image
   */
  function paintMasks(masks, options = {}) {
    let {
      alpha = 255,
      labels = [],
      labelsPosition = [],
      labelColor = 'blue',
      labelFont = '12px Helvetica'
    } = options;
    this.checkProcessable('paintMasks', {
      channels: [3, 4],
      bitDepth: [8, 16],
      colorModel: RGB$1
    });
    let colors = getColors(Object.assign({}, options, {
      numberColors: masks.length
    }));
    if (!Array.isArray(masks)) {
      masks = [masks];
    }
    for (let i = 0; i < masks.length; i++) {
      let mask = masks[i];
      // we need to find the parent image to calculate the relative position
      let color = colors[i % colors.length];
      for (let x = 0; x < mask.width; x++) {
        for (let y = 0; y < mask.height; y++) {
          if (mask.getBitXY(x, y)) {
            for (let component = 0; component < Math.min(this.components, color.length); component++) {
              if (alpha === 255) {
                this.setValueXY(x + mask.position[0], y + mask.position[1], component, color[component]);
              } else {
                let value = this.getValueXY(x + mask.position[0], y + mask.position[1], component);
                value = Math.round((value * (255 - alpha) + color[component] * alpha) / 255);
                this.setValueXY(x + mask.position[0], y + mask.position[1], component, value);
              }
            }
          }
        }
      }
    }
    if (Array.isArray(labels) && labels.length > 0) {
      let canvas = this.getCanvas();
      let ctx = canvas.getContext('2d');
      ctx.fillStyle = labelColor;
      ctx.font = labelFont;
      for (let i = 0; i < Math.min(masks.length, labels.length); i++) {
        let position = labelsPosition[i] ? labelsPosition[i] : masks[i].position;
        ctx.fillText(labels[i], position[0], position[1]);
      }
      this.data = Uint8Array.from(ctx.getImageData(0, 0, this.width, this.height).data);
    }
    return this;
  }

  function zerosMatrix(height, width) {
    let matrix = new Array(height);
    for (let i = 0; i < height; i++) {
      matrix[i] = new Array(width).fill(0);
    }
    return matrix;
  }

  const cross = [[0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [1, 1, 1, 1, 1], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0]];
  const smallCross = [[0, 1, 0], [1, 1, 1], [0, 1, 0]];

  /**
   * Class representing a shape
   * @class Shape
   * @param {object} [options]
   * @param {string} [options.kind='cross'] - Predefined matrix shape, 'cross' or 'smallCross'
   * @param {string} [options.shape] - Value may be 'square', 'rectangle', 'circle', 'ellipse' or 'triangle'
   *                                  The size of the shape will be determined by the size, width and height.
   *                                  A Shape is by default filled.
   * @param {number} [options.size]
   * @param {number} [options.width=options.size] - width of the shape. Must be odd.
   * @param {number} [options.height=options.size] - width of the shape. Must be odd.
   * @param {boolean} [options.filled=true] - If false only the border ot the shape is taken into account.
   */
  class Shape {
    constructor(options = {}) {
      let {
        kind = 'cross',
        shape,
        size,
        width,
        height,
        filled = true
      } = options;
      if (size) {
        width = size;
        height = size;
      }
      if (shape) {
        switch (shape.toLowerCase()) {
          case 'square':
          case 'rectangle':
            this.matrix = rectangle(width, height, {
              filled
            });
            break;
          case 'circle':
          case 'ellipse':
            this.matrix = ellipse(width, height, {
              filled
            });
            break;
          case 'triangle':
            this.matrix = triangle(width, height, {
              filled
            });
            break;
          default:
            throw new Error(`Shape: unexpected shape: ${shape}`);
        }
      } else if (kind) {
        switch (kind.toLowerCase()) {
          case 'cross':
            this.matrix = cross;
            break;
          case 'smallcross':
            this.matrix = smallCross;
            break;
          default:
            throw new Error(`Shape: unexpected kind: ${kind}`);
        }
      } else {
        throw new Error('Shape: expected a kind or a shape option');
      }
      this.height = this.matrix.length;
      this.width = this.matrix[0].length;
      this.halfHeight = this.height / 2 >> 0;
      this.halfWidth = this.width / 2 >> 0;
    }

    /**
     * Returns an array of [x,y] points
     * @return {Array<Array<number>>} - Array of [x,y] points
     */
    getPoints() {
      let matrix = this.matrix;
      let points = [];
      for (let y = 0; y < matrix.length; y++) {
        for (let x = 0; x < matrix[0].length; x++) {
          if (matrix[y][x]) {
            points.push([x - this.halfWidth, y - this.halfHeight]);
          }
        }
      }
      return points;
    }

    /**
     * Returns a Mask (1 bit Image) corresponding to this shape.
     * @return {Image}
     */
    getMask() {
      let img = new Image(this.width, this.height, {
        kind: BINARY
      });
      for (let y = 0; y < this.matrix.length; y++) {
        for (let x = 0; x < this.matrix[0].length; x++) {
          if (this.matrix[y][x]) {
            img.setBitXY(x, y);
          }
        }
      }
      return img;
    }
  }
  function rectangle(width, height, options) {
    const matrix = zerosMatrix(height, width);
    if (options.filled) {
      for (let y = 0; y < height; y++) {
        for (let x = 0; x < width; x++) {
          matrix[y][x] = 1;
        }
      }
    } else {
      for (let y of [0, height - 1]) {
        for (let x = 0; x < width; x++) {
          matrix[y][x] = 1;
        }
      }
      for (let y = 0; y < height; y++) {
        for (let x of [0, width - 1]) {
          matrix[y][x] = 1;
        }
      }
    }
    return matrix;
  }
  function ellipse(width, height, options) {
    const matrix = zerosMatrix(height, width);
    let yEven = 1 - height % 2;
    let xEven = 1 - width % 2;
    let a = Math.floor((width - 1) / 2); // horizontal ellipse axe
    let b = Math.floor((height - 1) / 2); // vertical ellipse axe
    let a2 = a * a;
    let b2 = b * b;
    if (options.filled) {
      for (let y = 0; y <= b; y++) {
        let shift = Math.floor(Math.sqrt(a2 - a2 * y * y / b2));
        for (let x = a - shift; x <= a; x++) {
          matrix[b - y][x] = 1;
          matrix[b + y + yEven][x] = 1;
          matrix[b - y][width - x - 1] = 1;
          matrix[b + y + yEven][width - x - 1] = 1;
        }
      }
    } else {
      for (let y = 0; y <= b; y++) {
        let shift = Math.floor(Math.sqrt(a2 - a2 * y * y / b2));
        let x = a - shift;
        matrix[b - y][x] = 1;
        matrix[b + y + yEven][x] = 1;
        matrix[b - y][width - x - 1] = 1;
        matrix[b + y + yEven][width - x - 1] = 1;
      }
      for (let x = 0; x <= a; x++) {
        let shift = Math.floor(Math.sqrt(b2 - b2 * x * x / a2));
        let y = b - shift;
        matrix[y][a - x] = 1;
        matrix[y][a + x + xEven] = 1;
        matrix[height - y - 1][a - x] = 1;
        matrix[height - y - 1][a + x + xEven] = 1;
      }
    }
    return matrix;
  }
  function triangle(width, height, options) {
    if (!options.filled) {
      throw new Error('Non filled triangle is not implemented');
    }
    const matrix = zerosMatrix(height, width);
    for (let y = 0; y < height; y++) {
      let shift = Math.floor((1 - y / height) * width / 2);
      for (let x = shift; x < width - shift; x++) {
        matrix[y][x] = 1;
      }
    }
    return matrix;
  }

  /**
   * Paint pixels on the current image.
   * @memberof Image
   * @instance
   * @param {Array<Array<number>>} points - Array of [x,y] points
   * @param {object} [options]
   * @param {Array<number>|string}     [options.color] - Array of 3 elements (R, G, B) or a valid css color.
   * @param {Array<Array<number>>|Array<string>} [options.colors] - Array of Array of 3 elements (R, G, B) for each color of each mask
   * @param {boolean}             [options.randomColors=true] - To paint each mask with a random color if color and colors are undefined
   * @param {boolean}             [options.distinctColors=false] - To paint each mask with a different color if color and colors are undefined
   * @param {object} [options.shape] - Definition of the shape, see Shape contructor.
   * @return {this} The original painted image
   */
  function paintPoints(points, options = {}) {
    let {
      shape
    } = options;
    this.checkProcessable('paintPoints', {
      bitDepth: [8, 16]
    });
    let colors = getColors(Object.assign({}, options, {
      numberColors: points.length
    }));
    let shapePixels = new Shape(shape).getPoints();
    let numberChannels = Math.min(this.channels, colors[0].length);
    for (let i = 0; i < points.length; i++) {
      let color = colors[i % colors.length];
      let xP = points[i][0];
      let yP = points[i][1];
      for (let j = 0; j < shapePixels.length; j++) {
        let xS = shapePixels[j][0];
        let yS = shapePixels[j][1];
        if (xP + xS >= 0 && yP + yS >= 0 && xP + xS < this.width && yP + yS < this.height) {
          let position = (xP + xS + (yP + yS) * this.width) * this.channels;
          for (let channel = 0; channel < numberChannels; channel++) {
            this.data[position + channel] = color[channel];
          }
        }
      }
    }
    return this;
  }

  /**
   * Paint a polyline defined by an array of points.
   * @memberof Image
   * @instance
   * @param {Array<Array<number>>} points - Array of [x,y] points
   * @param {object} [options]
   * @param {Array<number>} [options.color=[max,0,0]] - Array of 3 elements (R, G, B), default is red.
   * @param {boolean} [options.closed=false] - Close the polyline.
   * @return {this} The original painted image
   */
  function paintPolyline(points, options = {}) {
    let {
      color = [this.maxValue, 0, 0],
      closed = false
    } = options;
    this.checkProcessable('paintPoints', {
      bitDepth: [1, 8, 16]
    });
    let numberChannels = Math.min(this.channels, color.length);
    for (let i = 0; i < points.length - 1 + closed; i++) {
      let from = points[i];
      let to = points[(i + 1) % points.length];
      let dx = to[0] - from[0];
      let dy = to[1] - from[1];
      let steps = Math.max(Math.abs(dx), Math.abs(dy));
      let xIncrement = dx / steps;
      let yIncrement = dy / steps;
      let x = from[0];
      let y = from[1];
      for (let j = 0; j <= steps; j++) {
        let xPoint = Math.round(x);
        let yPoint = Math.round(y);
        if (xPoint >= 0 && yPoint >= 0 && xPoint < this.width && yPoint < this.height) {
          if (this.bitDepth === 1) {
            this.setBitXY(xPoint, yPoint);
          } else {
            let position = (xPoint + yPoint * this.width) * this.channels;
            for (let channel = 0; channel < numberChannels; channel++) {
              this.data[position + channel] = color[channel];
            }
          }
        }
        x = x + xIncrement;
        y = y + yIncrement;
      }
    }
    return this;
  }

  /**
   * Paint polylines on the current image.
   * @memberof Image
   * @instance
   * @param {Array<Array<Array<number>>>} polylines - Array of array of [x,y] points
   * @param {object} [options]
   * @param {Array<number>|string}     [options.color] - Array of 3 elements (R, G, B) or a valid css color.
   * @param {Array<Array<number>>|Array<string>} [options.colors] - Array of Array of 3 elements (R, G, B) for each color of each mask
   * @param {boolean}             [options.randomColors=true] - To paint each mask with a random color if color and colors are undefined
   * @param {boolean}             [options.distinctColors=false] - To paint each mask with a different color if color and colors are undefined
   * @param {object} [options.shape] - Definition of the shape, see Shape contructor.
   * @return {this} The original painted image
   */
  function paintPolylines(polylines, options = {}) {
    let optionsCopy = Object.assign({}, options);
    this.checkProcessable('paintPolylines', {
      bitDepth: [8, 16]
    });
    let colors = getColors(Object.assign({}, options, {
      numberColors: polylines.length
    }));
    for (let i = 0; i < polylines.length; i++) {
      optionsCopy.color = colors[i % colors.length];
      this.paintPolyline(polylines[i], optionsCopy);
    }
    return this;
  }

  /**
   * Paint a polygon defined by an array of points.
   * @memberof Image
   * @instance
   * @param {Array<Array<number>>} points - Array of [x,y] points
   * @param {object} [options]
   * @param {Array<number>} [options.color=[max,0,0]] - Array of 3 elements (R, G, B), default is red.
   * @param {boolean} [options.filled=false] - If you want the polygon to be filled or not.
   * @return {this} The original painted image
   */
  function paintPolygon(points, options = {}) {
    let {
      color = [this.maxValue, 0, 0],
      filled = false
    } = options;
    this.checkProcessable('paintPoints', {
      bitDepth: [1, 8, 16]
    });
    options.closed = true;
    let filteredPoints = deleteDouble(points);
    if (filled === false) {
      return this.paintPolyline(points, options);
    } else {
      let matrixBinary = Array(this.height);
      for (let i = 0; i < this.height; i++) {
        matrixBinary[i] = [];
        for (let j = 0; j < this.width; j++) {
          matrixBinary[i].push(0);
        }
      }
      for (let p = 0; p < filteredPoints.length; p++) {
        const line = lineBetweenTwoPoints(filteredPoints[p], filteredPoints[(p + 1) % filteredPoints.length]);
        for (let y = 0; y < this.height; y++) {
          for (let x = 0; x < this.width; x++) {
            if (isAtTheRightOfTheLine(x, y, line, this.height)) {
              matrixBinary[y][x] = matrixBinary[y][x] === 0 ? 1 : 0;
            }
          }
        }
      }
      for (let y = 0; y < this.height; y++) {
        for (let x = 0; x < this.width; x++) {
          if (matrixBinary[y][x] === 1) {
            if (this.bitDepth === 1) {
              this.setBitXY(x, y);
            } else {
              let numberChannels = Math.min(this.channels, color.length);
              let position = (x + y * this.width) * this.channels;
              for (let channel = 0; channel < numberChannels; channel++) {
                this.data[position + channel] = color[channel];
              }
            }
          }
        }
      }
      return this.paintPolyline(points, options);
    }
  }
  function deleteDouble(points) {
    let finalPoints = [];
    for (let i = 0; i < points.length; i++) {
      if (points[i][0] === points[(i + 1) % points.length][0] && points[i][1] === points[(i + 1) % points.length][1]) {
        continue;
      } else if (points[i][0] === points[(i - 1 + points.length) % points.length][0] && points[i][1] === points[(i - 1 + points.length) % points.length][1]) {
        continue;
      } else if (points[(i + 1) % points.length][0] === points[(i - 1 + points.length) % points.length][0] && points[(i - 1 + points.length) % points.length][1] === points[(i + 1) % points.length][1]) {
        continue; // we don't consider this point only
      } else {
        finalPoints.push(points[i]);
      }
    }
    return finalPoints;
  }
  function lineBetweenTwoPoints(p1, p2) {
    if (p1[0] === p2[0]) {
      return {
        a: 0,
        b: p1[0],
        vertical: true
      }; // we store the x of the vertical line into b
    } else {
      const coeffA = (p2[1] - p1[1]) / (p2[0] - p1[0]);
      const coeffB = p1[1] - coeffA * p1[0];
      return {
        a: coeffA,
        b: coeffB,
        vertical: false
      };
    }
  }
  function isAtTheRightOfTheLine(x, y, line, height) {
    if (line.vertical === true) {
      return line.b <= x;
    } else {
      if (line.a === 0) {
        return false;
      } else {
        const xline = (y - line.b) / line.a;
        return xline < x && xline >= 0 && xline <= height;
      }
    }
  }

  /**
   * Paint an array of polygons on the current image.
   * @memberof Image
   * @instance
   * @param {Array<Array<Array<number>>>} polygons - Array of array of [x,y] points
   * @param {object} [options]
   * @param {Array<number>|string}     [options.color] - Array of 3 elements (R, G, B) or a valid css color.
   * @param {Array<Array<number>>|Array<string>} [options.colors] - Array of Array of 3 elements (R, G, B) for each color of each mask
   * @param {boolean}             [options.randomColors=true] - To paint each mask with a random color if color and colors are undefined
   * @param {boolean}             [options.distinctColors=false] - To paint each mask with a different color if color and colors are undefined
   * @param {object} [options.shape] - Definition of the shape, see Shape contructor.
   * @return {this} The original painted image
   */
  function paintPolygons(polygons, options = {}) {
    let optionsCopy = Object.assign({}, options);
    this.checkProcessable('paintPolygons', {
      bitDepth: [8, 16]
    });
    let colors = getColors(Object.assign({}, options, {
      numberColors: polygons.length
    }));
    for (let i = 0; i < polygons.length; i++) {
      optionsCopy.color = colors[i % colors.length];
      this.paintPolygon(polygons[i], optionsCopy);
    }
    return this;
  }

  /**
   * Returns a histogram for the specified channel
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {number} [options.maxSlots=256]
   * @param {number} [options.channel]
   * @param {boolean} [options.useAlpha=true]
   * @return {number[]}
   */
  function getHistogram(options = {}) {
    let {
      maxSlots = 256,
      channel,
      useAlpha = true
    } = options;
    this.checkProcessable('getHistogram', {
      bitDepth: [1, 8, 16]
    });
    if (channel === undefined) {
      if (this.components > 1) {
        throw new RangeError('You need to define the channel for an image that contains more than one channel');
      }
      channel = 0;
    }
    return getChannelHistogram.call(this, channel, {
      useAlpha,
      maxSlots
    });
  }

  /**
   * Returns an array (number of channels) of array (number of slots) containing
   * the number of data of a specific intensity.
   * Intensity may be grouped by the maxSlots parameter.
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {number} [options.maxSlots] - Number of slots in the resulting
   *      array. The intensity will be evently distributed between 0 and
   *      the maxValue allowed for this image (255 for usual images).
   *      If maxSlots = 8, all the intensities between 0 and 31 will be
   *      placed in the slot 0, 32 to 63 in slot 1, ...
   * @return {Array<Array<number>>}
   * @example
   *      image.getHistograms({
   *          maxSlots: 8,
   *          useAlpha: false
   *      });
   */
  function getHistograms(options = {}) {
    const {
      maxSlots = 256,
      useAlpha = true
    } = options;
    this.checkProcessable('getHistograms', {
      bitDepth: [8, 16]
    });
    let results = new Array(useAlpha ? this.components : this.channels);
    for (let i = 0; i < results.length; i++) {
      results[i] = getChannelHistogram.call(this, i, {
        useAlpha,
        maxSlots
      });
    }
    return results;
  }
  function getChannelHistogram(channel, options) {
    let {
      useAlpha,
      maxSlots
    } = options;

    // for a mask, return a number array containing count of black and white points (black = array[0], white = array[1])

    if (this.bitDepth === 1) {
      let blackWhiteCount = [0, 0];
      for (let i = 0; i < this.height; i++) {
        for (let j = 0; j < this.width; j++) {
          let value = this.getBitXY(i, j);
          if (value === 0) {
            blackWhiteCount[0] += 1;
          } else if (value === 1) {
            blackWhiteCount[1] += 1;
          }
        }
      }
      return blackWhiteCount;
    }
    let bitSlots = Math.log2(maxSlots);
    if (!isInteger$1(bitSlots)) {
      throw new RangeError('maxSlots must be a power of 2, for example: 64, 256, 1024');
    }
    // we will compare the bitSlots to the bitDepth of the image
    // based on this we will shift the values. This allows to generate a histogram
    // of 16 grey even if the images has 256 shade of grey

    let bitShift = 0;
    if (this.bitDepth > bitSlots) {
      bitShift = this.bitDepth - bitSlots;
    }
    let data = this.data;
    let result = newArray$1(Math.pow(2, Math.min(this.bitDepth, bitSlots)), 0);
    if (useAlpha && this.alpha) {
      let alphaChannelDiff = this.channels - channel - 1;
      for (let i = channel; i < data.length; i += this.channels) {
        result[data[i] >> bitShift] += data[i + alphaChannelDiff] / this.maxValue;
      }
    } else {
      for (let i = channel; i < data.length; i += this.channels) {
        result[data[i] >> bitShift]++;
      }
    }
    return result;
  }

  /**
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {boolean} [options.useAlpha=true]
   * @param {number} [options.nbSlots=512]
   * @return {number[]}
   */
  function getColorHistogram(options = {}) {
    let {
      useAlpha = true,
      nbSlots = 512
    } = options;
    this.checkProcessable('getColorHistogram', {
      bitDepth: [8, 16],
      components: [3]
    });
    let nbSlotsCheck = Math.log(nbSlots) / Math.log(8);
    if (nbSlotsCheck !== Math.floor(nbSlotsCheck)) {
      throw new RangeError('nbSlots must be a power of 8. Usually 8, 64, 512 or 4096');
    }
    let bitShift = this.bitDepth - nbSlotsCheck;
    let data = this.data;
    let result = newArray$1(Math.pow(8, nbSlotsCheck), 0);
    let factor2 = Math.pow(2, nbSlotsCheck * 2);
    let factor1 = Math.pow(2, nbSlotsCheck);
    for (let i = 0; i < data.length; i += this.channels) {
      let slot = (data[i] >> bitShift) * factor2 + (data[i + 1] >> bitShift) * factor1 + (data[i + 2] >> bitShift);
      if (useAlpha && this.alpha) {
        result[slot] += data[i + this.channels - 1] / this.maxValue;
      } else {
        result[slot]++;
      }
    }
    return result;
  }

  /**
   * Returns an array with the minimal value of each channel
   * @memberof Image
   * @instance
   * @return {number[]} Array having has size the number of channels
   */
  function min() {
    this.checkProcessable('min', {
      bitDepth: [8, 16, 32]
    });
    let result = newArray$1(this.channels, +Infinity);
    for (let i = 0; i < this.data.length; i += this.channels) {
      for (let c = 0; c < this.channels; c++) {
        if (this.data[i + c] < result[c]) {
          result[c] = this.data[i + c];
        }
      }
    }
    return result;
  }

  /**
   * Returns an array with the maximal value of each channel
   * @memberof Image
   * @instance
   * @return {number[]} Array having has size the number of channels
   */
  function max() {
    this.checkProcessable('max', {
      bitDepth: [8, 16, 32]
    });
    let result = newArray$1(this.channels, -Infinity);
    for (let i = 0; i < this.data.length; i += this.channels) {
      for (let c = 0; c < this.channels; c++) {
        if (this.data[i + c] > result[c]) {
          result[c] = this.data[i + c];
        }
      }
    }
    return result;
  }

  /**
   * Returns an array with the sum of the values of each channel
   * @memberof Image
   * @instance
   * @return {number[]} Array having has size the number of channels
   */
  function sum() {
    this.checkProcessable('sum', {
      bitDepth: [8, 16]
    });
    let result = newArray$1(this.channels, 0);
    for (let i = 0; i < this.data.length; i += this.channels) {
      for (let c = 0; c < this.channels; c++) {
        result[c] += this.data[i + c];
      }
    }
    return result;
  }

  /**
   * Returns the moment of an image (https://en.wikipedia.org/wiki/Image_moment)
   * @memberof Image
   * @instance
   * @param {number} [xPower=0]
   * @param {number} [yPower=0]
   * @return {number}
   */
  function getMoment(xPower = 0, yPower = 0) {
    this.checkProcessable('getMoment', {
      bitDepth: [1]
    });
    let m = 0;
    for (let x = 0; x < this.width; x++) {
      for (let y = 0; y < this.height; y++) {
        if (this.getBitXY(x, y) === 1) {
          m += x ** xPower * y ** yPower;
        }
      }
    }
    return m;
  }

  /**
   * Returns an array of object with position.
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {Image} [options.mask] - Region of the image that is analyzed. The rest is omitted.
   * @param {number} [options.region=3] -  1, 2 or 3. Define the region around each points that is analyzed. 1 corresponds to 4 cross points, 2 to
   *        the 8 points around and 3 to the 12 points around the central pixel.
   * @param {number} [options.removeClosePoints=0] - Remove pts which have a distance between them smaller than this param.
   * @param {boolean} [options.invert=false] - Search for minima instead of maxima
   * @param {number} [options.maxEquals=2] - Maximal number of values that may be equal to the maximum
   * @return {number[]} Array whose size is the number of channels
   */
  function localMaxima(options = {}) {
    let {
      mask,
      region = 3,
      removeClosePoints = 0,
      invert = false,
      maxEquals = 2
    } = options;
    let image = this;
    this.checkProcessable('localMaxima', {
      bitDepth: [8, 16],
      components: 1
    });
    region *= 4;
    let maskExpectedValue = invert ? 0 : 1;
    let dx = [1, 0, -1, 0, 1, 1, -1, -1, 2, 0, -2, 0, 2, 2, -2, -2];
    let dy = [0, 1, 0, -1, 1, -1, 1, -1, 0, 2, 0, -2, 2, -2, 2, -2];
    let shift = region <= 8 ? 1 : 2;
    let points = [];
    for (let currentY = shift; currentY < image.height - shift; currentY++) {
      for (let currentX = shift; currentX < image.width - shift; currentX++) {
        if (mask && mask.getBitXY(currentX, currentY) !== maskExpectedValue) {
          continue;
        }
        let counter = 0;
        let nbEquals = 0;
        let currentValue = image.data[currentX + currentY * image.width];
        for (let dir = 0; dir < region; dir++) {
          if (invert) {
            // we search for minima
            if (image.data[currentX + dx[dir] + (currentY + dy[dir]) * image.width] > currentValue) {
              counter++;
            }
          } else {
            if (image.data[currentX + dx[dir] + (currentY + dy[dir]) * image.width] < currentValue) {
              counter++;
            }
          }
          if (image.data[currentX + dx[dir] + (currentY + dy[dir]) * image.width] === currentValue) {
            nbEquals++;
          }
        }
        if (counter + nbEquals === region && nbEquals <= maxEquals) {
          points.push([currentX, currentY]);
        }
      }
    }
    // TODO How to make a more performant and general way
    // we don't deal correctly here with groups of points that should be grouped if at the
    // beginning one of them is closer to another
    // Seems that we would ened to calculate a matrix and then split this matrix in 'independant matrices'
    // Or to assign a cluster to each point and regroup them if 2 clusters are close to each other
    // later approach seems much better
    if (removeClosePoints > 0) {
      for (let i = 0; i < points.length; i++) {
        for (let j = i + 1; j < points.length; j++) {
          if (Math.sqrt(Math.pow(points[i][0] - points[j][0], 2) + Math.pow(points[i][1] - points[j][1], 2)) < removeClosePoints) {
            points[i][0] = points[i][0] + points[j][0] >> 1;
            points[i][1] = points[i][1] + points[j][1] >> 1;
            points.splice(j, 1);
            j--;
          }
        }
      }
    }
    return points;
  }

  /**
   * Returns an array with the average value of each channel
   * @memberof Image
   * @instance
   * @return {number[]} Array having has size the number of channels
   */
  function mean() {
    let histograms = this.getHistograms({
      maxSlots: this.maxValue + 1
    });
    let result = new Array(histograms.length);
    for (let c = 0; c < histograms.length; c++) {
      let histogram = histograms[c];
      result[c] = mean$2(histogram);
    }
    return result;
  }

  /**
   * Returns an array with the median value of each channel
   * @memberof Image
   * @instance
   * @return {number[]} Array having has size the number of channels
   */
  function median() {
    let histograms = this.getHistograms({
      maxSlots: this.maxValue + 1
    });
    let result = new Array(histograms.length);
    for (let c = 0; c < histograms.length; c++) {
      let histogram = histograms[c];
      result[c] = median$2(histogram);
    }
    return result;
  }

  /**
   * Allows to generate an array of points for a binary image (bit depth = 1)
   * @memberof Image
   * @instance
   * @return {Array<Array<number>>} - an array of [x,y] corresponding to the set pixels in the binary image
   */
  function points() {
    this.checkProcessable('points', {
      bitDepth: [1]
    });
    const pixels = [];
    for (let x = 0; x < this.width; x++) {
      for (let y = 0; y < this.height; y++) {
        if (this.getBitXY(x, y) === 1) {
          pixels.push([x, y]);
        }
      }
    }
    return pixels;
  }

  /**
   * Allows to generate an array of points for a binary image (bit depth = 1)
   * The points consider the beginning and the end of each pixel
   * This method is only used to calculate minimalBoundRectangle
   * @memberof Image
   * @instance
   * @return {Array<Array<number>>} - an array of [x,y] corresponding to the set pixels in the binary image
   */
  function extendedPoints() {
    this.checkProcessable('extendedPoints', {
      bitDepth: [1]
    });
    const pixels = [];
    for (let y = 0; y < this.height; y++) {
      for (let x = 0; x < this.width; x++) {
        if (this.getBitXY(x, y) === 1) {
          pixels.push([x, y]);
          if (this.getBitXY(x + 1, y) !== 1) {
            pixels.push([x + 1, y]);
            pixels.push([x + 1, y + 1]);
            if (this.getBitXY(x, y + 1) !== 1) {
              pixels.push([x, y + 1]);
            }
          } else {
            if (this.getBitXY(x, y + 1) !== 1) {
              pixels.push([x, y + 1]);
              pixels.push([x + 1, y + 1]);
            }
          }

          // this small optimization allows to reduce dramatically the number of points for MBR calculation
          while (x < this.width - 2 && this.getBitXY(x + 1, y) === 1 && this.getBitXY(x + 2, y) === 1) {
            x++;
          }
        }
      }
    }
    return pixels;
  }

  /**
   * An image may be derived from another image either by a crop
   * or because it is a ROI (region of interest)
   * Also a region of interest can be reprocessed to generated another
   * set of region of interests.
   * It is therefore important to keep the hierarchy of images to know
   * which image is derived from which one and be able to get the
   * relative position of one image in another
   * This methods takes care of this.
   * @memberof Image
   * @instance
   * @param {Image} targetImage
   * @param {object} [options={}]
   * @param {boolean} [options.defaultFurther=false] If set to true and no parent found returns the relative position
   *      to the further parent
   * @return {number[]|boolean}
   */
  function getRelativePosition(targetImage, options = {}) {
    if (this === targetImage) {
      return [0, 0];
    }
    let position = [0, 0];
    let currentImage = this;
    while (currentImage) {
      if (currentImage === targetImage) {
        return position;
      }
      if (currentImage.position) {
        position[0] += currentImage.position[0];
        position[1] += currentImage.position[1];
      }
      currentImage = currentImage.parent;
    }
    // we should never reach this place, this means we could not find the parent
    // throw Error('Parent image was not found, can not get relative position.')
    if (options.defaultFurther) return position;
    return false;
  }

  /**
   * Returns the number of transparent pixels
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {number} [options.alpha=1] - Value of the alpha value to count.
   * @return {number} Number of transparent pixels
   */
  function countAlphaPixels(options = {}) {
    let {
      alpha = 1
    } = options;
    this.checkProcessable('countAlphaPixels', {
      bitDepth: [8, 16],
      alpha: 1
    });
    let count = 0;
    if (alpha !== undefined) {
      for (let i = this.components; i < this.data.length; i += this.channels) {
        if (this.data[i] === alpha) {
          count++;
        }
      }
      return count;
    } else {
      // because there is an alpha channel all the pixels have an alpha
      return this.size;
    }
  }

  /**
   * Computes the convex hull of a binary image using Andrew's Monotone Chain Algorithm
   * http://www.algorithmist.com/index.php/Monotone_Chain_Convex_Hull
   *
   * @param points - An array of points.
   * @param options - MCCH Algorithm options.
   * @return Coordinates of the convex hull in clockwise order
   */
  function monotoneChainConvexHull$1(points, options = {}) {
    const {
      sorted
    } = options;
    if (!sorted) {
      points = points.slice().sort(byXThenY);
    }
    const n = points.length;
    const result = new Array(n * 2);
    let k = 0;
    for (let i = 0; i < n; i++) {
      const point = points[i];
      while (k >= 2 && cw(result[k - 2], result[k - 1], point) <= 0) {
        k--;
      }
      result[k++] = point;
    }
    const t = k + 1;
    for (let i = n - 2; i >= 0; i--) {
      const point = points[i];
      while (k >= t && cw(result[k - 2], result[k - 1], point) <= 0) {
        k--;
      }
      result[k++] = point;
    }
    return result.slice(0, k - 1);
  }
  function cw(p1, p2, p3) {
    return (p2[1] - p1[1]) * (p3[0] - p1[0]) - (p2[0] - p1[0]) * (p3[1] - p1[1]);
  }
  function byXThenY(point1, point2) {
    if (point1[0] === point2[0]) {
      return point1[1] - point2[1];
    }
    return point1[0] - point2[0];
  }

  /**
   * Returns the convex hull of a binary image
   * @memberof Image
   * @instance
   * @return {Array<Array<number>>}
   */
  function monotoneChainConvexHull() {
    return monotoneChainConvexHull$1(this.extendedPoints, {
      sorted: false
    });
  }

  /**
   * Rounds all the x and y values of an array of points
   * @param {Array<Array<number>>} points
   * @return {Array<Array<number>>} modified input value
   * @private
   */
  function round(points) {
    for (let i = 0; i < points.length; i++) {
      points[i][0] = Math.round(points[i][0]);
      points[i][1] = Math.round(points[i][1]);
    }
    return points;
  }

  /**
   * Calculates a new point that is the difference p1 - p2
   * @param {Array<number>} p1
   * @param {Array<number>} p2
   * @return {Array<number>}
   * @private
   */
  function difference(p1, p2) {
    return [p1[0] - p2[0], p1[1] - p2[1]];
  }

  /**
   * Normalize a point
   * @param {Array<number>} p
   * @return {Array<number>}
   * @private
   */
  function normalize(p) {
    let length = Math.sqrt(p[0] ** 2 + p[1] ** 2);
    return [p[0] / length, p[1] / length];
  }

  /**
   * We rotate an array of points
   * @param {number} radians
   * @param {Array<Array<number>>} srcPoints
   * @param {Array<Array<number>>} destPoints
   * @return {Array<Array<number>>}
   * @private
   */
  function rotate(radians, srcPoints, destPoints) {
    if (destPoints === undefined) destPoints = new Array(srcPoints.length);
    let cos = Math.cos(radians);
    let sin = Math.sin(radians);
    for (let i = 0; i < destPoints.length; ++i) {
      destPoints[i] = [cos * srcPoints[i][0] - sin * srcPoints[i][1], sin * srcPoints[i][0] + cos * srcPoints[i][1]];
    }
    return destPoints;
  }

  /**
   * Returns the perimeter represented by the points (a polygon)
   * @param {Array<Array<number>>} points
   */
  function perimeter(vertices) {
    let total = 0;
    for (let i = 0; i < vertices.length; i++) {
      let fromX = vertices[i][0];
      let fromY = vertices[i][1];
      let toX = vertices[i === vertices.length - 1 ? 0 : i + 1][0];
      let toY = vertices[i === vertices.length - 1 ? 0 : i + 1][1];
      total += Math.sqrt((toX - fromX) ** 2 + (toY - fromY) ** 2);
    }
    return total;
  }

  /**
   * Returns the surface represented by the points (a polygon)
   * @param {Array<Array<number>>} points
   */
  function surface(vertices) {
    let total = 0;
    for (let i = 0; i < vertices.length; i++) {
      let addX = vertices[i][0];
      let addY = vertices[i === vertices.length - 1 ? 0 : i + 1][1];
      let subX = vertices[i === vertices.length - 1 ? 0 : i + 1][0];
      let subY = vertices[i][1];
      total += addX * addY * 0.5;
      total -= subX * subY * 0.5;
    }
    return Math.abs(total);
  }

  /**
   * Returns 2 points with minimal and maximal XY
   * @param {Array<Array<number>>} points
   * @return {Array<Array<number>>}
   * @private
   */
  function minMax(points) {
    let xMin = +Infinity;
    let yMin = +Infinity;
    let xMax = -Infinity;
    let yMax = -Infinity;
    for (let i = 0; i < points.length; i++) {
      if (points[i][0] < xMin) xMin = points[i][0];
      if (points[i][0] > xMax) xMax = points[i][0];
      if (points[i][1] < yMin) yMin = points[i][1];
      if (points[i][1] > yMax) yMax = points[i][1];
    }
    return [[xMin, yMin], [xMax, yMax]];
  }

  /**
   * Moves the minX, minY to 0,0
   * All the points will be positive after this move
   * @param {Array<Array<number>>} srcPoints
   * @param {Array<Array<number>>} destPoints
   * @return {Array<Array<number>>}
   * @private
   */
  function moveToZeroZero(srcPoints, destPoints) {
    if (destPoints === undefined) {
      destPoints = new Array(srcPoints.length).fill(0).map(() => []);
    }
    let minMaxValues = minMax(srcPoints);
    let xMin = minMaxValues[0][0];
    let yMin = minMaxValues[0][1];
    for (let i = 0; i < srcPoints.length; i++) {
      destPoints[i][0] = srcPoints[i][0] - xMin;
      destPoints[i][1] = srcPoints[i][1] - yMin;
    }
    return destPoints;
  }

  /**
   * Computes the minimum bounding box around a binary image
   * https://www.researchgate.net/profile/Lennert_Den_Boer2/publication/303783472_A_Fast_Algorithm_for_Generating_a_Minimal_Bounding_Rectangle/links/5751a14108ae6807fafb2aa5.pdf
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {Array<Array<number>>} [options.originalPoints]
   * @return {Array<Array<number>>}
   */
  function minimalBoundingRectangle(options = {}) {
    const {
      originalPoints = monotoneChainConvexHull.call(this)
    } = options;
    if (originalPoints.length === 0) {
      return [];
    }
    if (originalPoints.length === 1) {
      return [originalPoints[0], originalPoints[0], originalPoints[0], originalPoints[0]];
    }
    const p = new Array(originalPoints.length);
    let minSurface = +Infinity;
    let minSurfaceAngle = 0;
    let mbr;
    for (let i = 0; i < p.length; i++) {
      let angle = getAngle$1(originalPoints[i], originalPoints[(i + 1) % p.length]);
      rotate(-angle, originalPoints, p);

      // we rotate and translate so that this axe is in the bottom
      let aX = p[i][0];
      let aY = p[i][1];
      let bX = p[(i + 1) % p.length][0];
      let bY = p[(i + 1) % p.length][1];
      let tUndefined = true;
      let tMin = 0;
      let tMax = 0;
      let maxWidth = 0;
      for (let j = 0; j < p.length; j++) {
        let cX = p[j][0];
        let cY = p[j][1];
        let t = (cX - aX) / (bX - aX);
        if (tUndefined === true) {
          tUndefined = false;
          tMin = t;
          tMax = t;
        } else {
          if (t < tMin) tMin = t;
          if (t > tMax) tMax = t;
        }
        let width = (-(bX - aX) * cY + bX * aY - bY * aX) / (bX - aX);
        if (Math.abs(width) > Math.abs(maxWidth)) maxWidth = width;
      }
      let pMin = [aX + tMin * (bX - aX), aY];
      let pMax = [aX + tMax * (bX - aX), aY];
      let currentSurface = Math.abs(maxWidth * (tMin - tMax) * (bX - aX));
      if (currentSurface < minSurface) {
        minSurfaceAngle = angle;
        minSurface = currentSurface;
        mbr = [pMin, pMax, [pMax[0], pMax[1] - maxWidth], [pMin[0], pMin[1] - maxWidth]];
      }
    }
    rotate(minSurfaceAngle, mbr, mbr);
    return mbr;
  }

  // the angle that allows to make the line going through p1 and p2 horizontal
  // this is an optimized version because it assume one vector is horizontal
  function getAngle$1(p1, p2) {
    let diff = difference(p2, p1);
    let vector = normalize(diff);
    let angle = Math.acos(vector[0]);
    if (vector[1] < 0) return -angle;
    return angle;
  }

  /* eslint-disable import/order */

  function extend$1(Image) {
    let inPlace = {
      inPlace: true
    };
    Image.extendMethod('invert', invert);
    Image.extendMethod('abs', abs);
    Image.extendMethod('level', level, inPlace);
    Image.extendMethod('add', add, inPlace);
    Image.extendMethod('subtract', subtract, inPlace);
    Image.extendMethod('subtractImage', subtractImage);
    Image.extendMethod('multiply', multiply, inPlace);
    Image.extendMethod('divide', divide, inPlace);
    Image.extendMethod('hypotenuse', hypotenuse);
    Image.extendMethod('background', background$1);
    Image.extendMethod('flipX', flipX);
    Image.extendMethod('flipY', flipY);
    Image.extendMethod('blurFilter', blurFilter);
    Image.extendMethod('medianFilter', medianFilter);
    Image.extendMethod('gaussianFilter', gaussianFilter);
    Image.extendMethod('sobelFilter', sobelFilter);
    Image.extendMethod('gradientFilter', gradientFilter);
    Image.extendMethod('scharrFilter', scharrFilter);
    Image.extendMethod('dilate', dilate);
    Image.extendMethod('erode', erode);
    Image.extendMethod('open', open);
    Image.extendMethod('close', close);
    Image.extendMethod('topHat', topHat);
    Image.extendMethod('blackHat', blackHat);
    Image.extendMethod('morphologicalGradient', morphologicalGradient);
    Image.extendMethod('warpingFourPoints', warpingFourPoints);
    Image.extendMethod('crop', crop);
    Image.extendMethod('cropAlpha', cropAlpha);
    Image.extendMethod('resize', resize).extendMethod('scale', resize);
    Image.extendMethod('hsv', hsv);
    Image.extendMethod('hsl', hsl$1);
    Image.extendMethod('cmyk', cmyk);
    Image.extendMethod('rgba8', rgba8);
    Image.extendMethod('grey', grey).extendMethod('gray', grey);
    Image.extendMethod('mask', mask);
    Image.extendMethod('pad', pad);
    Image.extendMethod('colorDepth', colorDepth);
    Image.extendMethod('setBorder', setBorder, inPlace);
    Image.extendMethod('rotate', rotate$1);
    Image.extendMethod('rotateLeft', rotateLeft);
    Image.extendMethod('rotateRight', rotateRight);
    Image.extendMethod('insert', insert);
    Image.extendMethod('getRow', getRow);
    Image.extendMethod('getColumn', getColumn);
    Image.extendMethod('getMatrix', getMatrix);
    Image.extendMethod('setMatrix', setMatrix);
    Image.extendMethod('getPixelsArray', getPixelsArray);
    Image.extendMethod('getIntersection', getIntersection);
    Image.extendMethod('getClosestCommonParent', getClosestCommonParent);
    Image.extendMethod('getThreshold', getThreshold);
    Image.extendMethod('split', split);
    Image.extendMethod('getChannel', getChannel);
    Image.extendMethod('combineChannels', combineChannels);
    Image.extendMethod('setChannel', setChannel);
    Image.extendMethod('getSimilarity', getSimilarity);
    Image.extendMethod('getPixelsGrid', getPixelsGrid);
    Image.extendMethod('getBestMatch', getBestMatch);
    Image.extendMethod('cannyEdge', cannyEdge);
    Image.extendMethod('convolution', convolution);
    Image.extendMethod('extract', extract);
    Image.extendMethod('floodFill', floodFill);
    Image.extendMethod('paintLabels', paintLabels, inPlace);
    Image.extendMethod('paintMasks', paintMasks, inPlace);
    Image.extendMethod('paintPoints', paintPoints, inPlace);
    Image.extendMethod('paintPolyline', paintPolyline, inPlace);
    Image.extendMethod('paintPolylines', paintPolylines, inPlace);
    Image.extendMethod('paintPolygon', paintPolygon, inPlace);
    Image.extendMethod('paintPolygons', paintPolygons, inPlace);
    Image.extendMethod('countAlphaPixels', countAlphaPixels);
    Image.extendMethod('monotoneChainConvexHull', monotoneChainConvexHull);
    Image.extendMethod('minimalBoundingRectangle', minimalBoundingRectangle);
    Image.extendMethod('getHistogram', getHistogram).extendProperty('histogram', getHistogram);
    Image.extendMethod('getHistograms', getHistograms).extendProperty('histograms', getHistograms);
    Image.extendMethod('getColorHistogram', getColorHistogram).extendProperty('colorHistogram', getColorHistogram);
    Image.extendMethod('getMin', min).extendProperty('min', min);
    Image.extendMethod('getMax', max).extendProperty('max', max);
    Image.extendMethod('getSum', sum).extendProperty('sum', sum);
    Image.extendMethod('getMoment', getMoment).extendProperty('moment', getMoment);
    Image.extendMethod('getLocalMaxima', localMaxima);
    Image.extendMethod('getMedian', median).extendProperty('median', median);
    Image.extendMethod('getMean', mean).extendProperty('mean', mean);
    Image.extendMethod('getPoints', points).extendProperty('points', points);
    Image.extendMethod('getExtendedPoints', extendedPoints).extendProperty('extendedPoints', extendedPoints);
    Image.extendMethod('getRelativePosition', getRelativePosition);
  }

  var quantities$1 = {exports: {}};

  /*
  The MIT License (MIT)
  Copyright © 2006-2007 Kevin C. Olbrich
  Copyright © 2010-2016 LIM SAS (http://lim.eu) - Julien Sanchez

  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 quantities = quantities$1.exports;
  (function (module, exports) {
    (function (global, factory) {
      module.exports = factory() ;
    })(quantities, function () {

      /**
       * Tests if a value is a string
       *
       * @param {*} value - Value to test
       *
       * @returns {boolean} true if value is a string, false otherwise
       */
      function isString(value) {
        return typeof value === "string" || value instanceof String;
      }

      /*
       * Prefer stricter Number.isFinite if currently supported.
       * To be dropped when ES6 is finalized. Obsolete browsers will
       * have to use ES6 polyfills.
       */
      var isFiniteImpl = Number.isFinite || window.isFinite;
      /**
       * Tests if a value is a number
       *
       * @param {*} value - Value to test
       *
       * @returns {boolean} true if value is a number, false otherwise
       */
      function isNumber(value) {
        // Number.isFinite allows not to consider NaN or '1' as numbers
        return isFiniteImpl(value);
      }

      /*
       * Identity function
       */
      function identity(value) {
        return value;
      }

      /**
       * Returns unique strings from list
       *
       * @param {string[]} strings - array of strings
       *
       *
       * @returns {string[]} a new array of strings without duplicates
       */
      function uniq(strings) {
        var seen = {};
        return strings.filter(function (item) {
          return seen.hasOwnProperty(item) ? false : seen[item] = true;
        });
      }
      function compareArray(array1, array2) {
        if (array2.length !== array1.length) {
          return false;
        }
        for (var i = 0; i < array1.length; i++) {
          if (array2[i].compareArray) {
            if (!array2[i].compareArray(array1[i])) {
              return false;
            }
          }
          if (array2[i] !== array1[i]) {
            return false;
          }
        }
        return true;
      }
      function assign(target, properties) {
        Object.keys(properties).forEach(function (key) {
          target[key] = properties[key];
        });
      }

      /**
       * Safely multiplies numbers while avoiding floating errors
       * like 0.1 * 0.1 => 0.010000000000000002
       *
       * @param {...number} numbers - numbers to multiply
       *
       * @returns {number} result
       */
      function mulSafe() {
        var result = 1,
          decimals = 0;
        for (var i = 0; i < arguments.length; i++) {
          var arg = arguments[i];
          decimals = decimals + getFractional(arg);
          result *= arg;
        }
        return decimals !== 0 ? round(result, decimals) : result;
      }

      /**
       * Safely divides two numbers while avoiding floating errors
       * like 0.3 / 0.05 => 5.999999999999999
       *
       * @returns {number} result
       * @param {number} num Numerator
       * @param {number} den Denominator
       */
      function divSafe(num, den) {
        if (den === 0) {
          throw new Error("Divide by zero");
        }
        var factor = Math.pow(10, getFractional(den));
        var invDen = factor / (factor * den);
        return mulSafe(num, invDen);
      }

      /**
       * Rounds value at the specified number of decimals
       *
       * @param {number} val - value to round
       * @param {number} decimals - number of decimals
       *
       * @returns {number} rounded number
       */
      function round(val, decimals) {
        return Math.round(val * Math.pow(10, decimals)) / Math.pow(10, decimals);
      }
      function getFractional(num) {
        // Check for NaNs or Infinities
        if (!isFinite(num)) {
          return 0;
        }

        // Faster than parsing strings
        // http://jsperf.com/count-decimals/2
        var count = 0;
        while (num % 1 !== 0) {
          num *= 10;
          count++;
        }
        return count;
      }

      /**
       * Custom error type definition
       * @constructor
       */
      function QtyError() {
        var err;
        if (!this) {
          // Allows to instantiate QtyError without new()
          err = Object.create(QtyError.prototype);
          QtyError.apply(err, arguments);
          return err;
        }
        err = Error.apply(this, arguments);
        this.name = "QtyError";
        this.message = err.message;
        this.stack = err.stack;
      }
      QtyError.prototype = Object.create(Error.prototype, {
        constructor: {
          value: QtyError
        }
      });

      /*
       * Throws incompatible units error
       * @param {string} left - units
       * @param {string} right - units incompatible with first argument
       * @throws "Incompatible units" error
       */
      function throwIncompatibleUnits(left, right) {
        throw new QtyError("Incompatible units: " + left + " and " + right);
      }
      var UNITS = {
        /* prefixes */
        "<googol>": [["googol"], 1e100, "prefix"],
        "<kibi>": [["Ki", "Kibi", "kibi"], Math.pow(2, 10), "prefix"],
        "<mebi>": [["Mi", "Mebi", "mebi"], Math.pow(2, 20), "prefix"],
        "<gibi>": [["Gi", "Gibi", "gibi"], Math.pow(2, 30), "prefix"],
        "<tebi>": [["Ti", "Tebi", "tebi"], Math.pow(2, 40), "prefix"],
        "<pebi>": [["Pi", "Pebi", "pebi"], Math.pow(2, 50), "prefix"],
        "<exi>": [["Ei", "Exi", "exi"], Math.pow(2, 60), "prefix"],
        "<zebi>": [["Zi", "Zebi", "zebi"], Math.pow(2, 70), "prefix"],
        "<yebi>": [["Yi", "Yebi", "yebi"], Math.pow(2, 80), "prefix"],
        "<yotta>": [["Y", "Yotta", "yotta"], 1e24, "prefix"],
        "<zetta>": [["Z", "Zetta", "zetta"], 1e21, "prefix"],
        "<exa>": [["E", "Exa", "exa"], 1e18, "prefix"],
        "<peta>": [["P", "Peta", "peta"], 1e15, "prefix"],
        "<tera>": [["T", "Tera", "tera"], 1e12, "prefix"],
        "<giga>": [["G", "Giga", "giga"], 1e9, "prefix"],
        "<mega>": [["M", "Mega", "mega"], 1e6, "prefix"],
        "<kilo>": [["k", "kilo"], 1e3, "prefix"],
        "<hecto>": [["h", "Hecto", "hecto"], 1e2, "prefix"],
        "<deca>": [["da", "Deca", "deca", "deka"], 1e1, "prefix"],
        "<deci>": [["d", "Deci", "deci"], 1e-1, "prefix"],
        "<centi>": [["c", "Centi", "centi"], 1e-2, "prefix"],
        "<milli>": [["m", "Milli", "milli"], 1e-3, "prefix"],
        "<micro>": [["u", "\u03BC" /*µ as greek letter*/, "\u00B5" /*µ as micro sign*/, "Micro", "mc", "micro"], 1e-6, "prefix"],
        "<nano>": [["n", "Nano", "nano"], 1e-9, "prefix"],
        "<pico>": [["p", "Pico", "pico"], 1e-12, "prefix"],
        "<femto>": [["f", "Femto", "femto"], 1e-15, "prefix"],
        "<atto>": [["a", "Atto", "atto"], 1e-18, "prefix"],
        "<zepto>": [["z", "Zepto", "zepto"], 1e-21, "prefix"],
        "<yocto>": [["y", "Yocto", "yocto"], 1e-24, "prefix"],
        "<1>": [["1", "<1>"], 1, ""],
        /* length units */
        "<meter>": [["m", "meter", "meters", "metre", "metres"], 1.0, "length", ["<meter>"]],
        "<inch>": [["in", "inch", "inches", "\""], 0.0254, "length", ["<meter>"]],
        "<foot>": [["ft", "foot", "feet", "'"], 0.3048, "length", ["<meter>"]],
        "<yard>": [["yd", "yard", "yards"], 0.9144, "length", ["<meter>"]],
        "<mile>": [["mi", "mile", "miles"], 1609.344, "length", ["<meter>"]],
        "<naut-mile>": [["nmi", "naut-mile"], 1852, "length", ["<meter>"]],
        "<league>": [["league", "leagues"], 4828, "length", ["<meter>"]],
        "<furlong>": [["furlong", "furlongs"], 201.2, "length", ["<meter>"]],
        "<rod>": [["rd", "rod", "rods"], 5.029, "length", ["<meter>"]],
        "<mil>": [["mil", "mils"], 0.0000254, "length", ["<meter>"]],
        "<angstrom>": [["ang", "angstrom", "angstroms"], 1e-10, "length", ["<meter>"]],
        "<fathom>": [["fathom", "fathoms"], 1.829, "length", ["<meter>"]],
        "<pica>": [["pica", "picas"], 0.00423333333, "length", ["<meter>"]],
        "<point>": [["pt", "point", "points"], 0.000352777778, "length", ["<meter>"]],
        "<redshift>": [["z", "red-shift", "redshift"], 1.302773e26, "length", ["<meter>"]],
        "<AU>": [["AU", "astronomical-unit"], 149597900000, "length", ["<meter>"]],
        "<light-second>": [["ls", "light-second"], 299792500, "length", ["<meter>"]],
        "<light-minute>": [["lmin", "light-minute"], 17987550000, "length", ["<meter>"]],
        "<light-year>": [["ly", "light-year"], 9460528000000000, "length", ["<meter>"]],
        "<parsec>": [["pc", "parsec", "parsecs"], 30856780000000000, "length", ["<meter>"]],
        "<datamile>": [["DM", "datamile"], 1828.8, "length", ["<meter>"]],
        /* mass */
        "<kilogram>": [["kg", "kilogram", "kilograms"], 1.0, "mass", ["<kilogram>"]],
        "<AMU>": [["u", "AMU", "amu"], 1.660538921e-27, "mass", ["<kilogram>"]],
        "<dalton>": [["Da", "Dalton", "Daltons", "dalton", "daltons"], 1.660538921e-27, "mass", ["<kilogram>"]],
        "<slug>": [["slug", "slugs"], 14.5939029, "mass", ["<kilogram>"]],
        "<short-ton>": [["tn", "ton", "short-ton"], 907.18474, "mass", ["<kilogram>"]],
        "<metric-ton>": [["t", "tonne", "metric-ton"], 1000, "mass", ["<kilogram>"]],
        "<carat>": [["ct", "carat", "carats"], 0.0002, "mass", ["<kilogram>"]],
        "<pound>": [["lbs", "lb", "pound", "pounds", "#"], 0.45359237, "mass", ["<kilogram>"]],
        "<ounce>": [["oz", "ounce", "ounces"], 0.0283495231, "mass", ["<kilogram>"]],
        "<gram>": [["g", "gram", "grams", "gramme", "grammes"], 1e-3, "mass", ["<kilogram>"]],
        "<grain>": [["grain", "grains", "gr"], 6.479891e-5, "mass", ["<kilogram>"]],
        "<dram>": [["dram", "drams", "dr"], 0.0017718452, "mass", ["<kilogram>"]],
        "<stone>": [["stone", "stones", "st"], 6.35029318, "mass", ["<kilogram>"]],
        /* area */
        "<hectare>": [["hectare"], 10000, "area", ["<meter>", "<meter>"]],
        "<acre>": [["acre", "acres"], 4046.85642, "area", ["<meter>", "<meter>"]],
        "<sqft>": [["sqft"], 1, "area", ["<foot>", "<foot>"]],
        /* volume */
        "<liter>": [["l", "L", "liter", "liters", "litre", "litres"], 0.001, "volume", ["<meter>", "<meter>", "<meter>"]],
        "<gallon>": [["gal", "gallon", "gallons"], 0.0037854118, "volume", ["<meter>", "<meter>", "<meter>"]],
        "<gallon-imp>": [["galimp", "gallon-imp", "gallons-imp"], 0.0045460900, "volume", ["<meter>", "<meter>", "<meter>"]],
        "<quart>": [["qt", "quart", "quarts"], 0.00094635295, "volume", ["<meter>", "<meter>", "<meter>"]],
        "<pint>": [["pt", "pint", "pints"], 0.000473176475, "volume", ["<meter>", "<meter>", "<meter>"]],
        "<pint-imp>": [["ptimp", "pint-imp", "pints-imp"], 5.6826125e-4, "volume", ["<meter>", "<meter>", "<meter>"]],
        "<cup>": [["cu", "cup", "cups"], 0.000236588238, "volume", ["<meter>", "<meter>", "<meter>"]],
        "<fluid-ounce>": [["floz", "fluid-ounce", "fluid-ounces"], 2.95735297e-5, "volume", ["<meter>", "<meter>", "<meter>"]],
        "<fluid-ounce-imp>": [["flozimp", "floz-imp", "fluid-ounce-imp", "fluid-ounces-imp"], 2.84130625e-5, "volume", ["<meter>", "<meter>", "<meter>"]],
        "<tablespoon>": [["tb", "tbsp", "tbs", "tablespoon", "tablespoons"], 1.47867648e-5, "volume", ["<meter>", "<meter>", "<meter>"]],
        "<teaspoon>": [["tsp", "teaspoon", "teaspoons"], 4.92892161e-6, "volume", ["<meter>", "<meter>", "<meter>"]],
        "<bushel>": [["bu", "bsh", "bushel", "bushels"], 0.035239072, "volume", ["<meter>", "<meter>", "<meter>"]],
        "<oilbarrel>": [["bbl", "oilbarrel", "oilbarrels", "oil-barrel", "oil-barrels"], 0.158987294928, "volume", ["<meter>", "<meter>", "<meter>"]],
        "<beerbarrel>": [["bl", "bl-us", "beerbarrel", "beerbarrels", "beer-barrel", "beer-barrels"], 0.1173477658, "volume", ["<meter>", "<meter>", "<meter>"]],
        "<beerbarrel-imp>": [["blimp", "bl-imp", "beerbarrel-imp", "beerbarrels-imp", "beer-barrel-imp", "beer-barrels-imp"], 0.16365924, "volume", ["<meter>", "<meter>", "<meter>"]],
        /* speed */
        "<kph>": [["kph"], 0.277777778, "speed", ["<meter>"], ["<second>"]],
        "<mph>": [["mph"], 0.44704, "speed", ["<meter>"], ["<second>"]],
        "<knot>": [["kt", "kn", "kts", "knot", "knots"], 0.514444444, "speed", ["<meter>"], ["<second>"]],
        "<fps>": [["fps"], 0.3048, "speed", ["<meter>"], ["<second>"]],
        /* acceleration */
        "<gee>": [["gee"], 9.80665, "acceleration", ["<meter>"], ["<second>", "<second>"]],
        "<Gal>": [["Gal"], 1e-2, "acceleration", ["<meter>"], ["<second>", "<second>"]],
        /* temperature_difference */
        "<kelvin>": [["degK", "kelvin"], 1.0, "temperature", ["<kelvin>"]],
        "<celsius>": [["degC", "celsius", "celsius", "centigrade"], 1.0, "temperature", ["<kelvin>"]],
        "<fahrenheit>": [["degF", "fahrenheit"], 5 / 9, "temperature", ["<kelvin>"]],
        "<rankine>": [["degR", "rankine"], 5 / 9, "temperature", ["<kelvin>"]],
        "<temp-K>": [["tempK", "temp-K"], 1.0, "temperature", ["<temp-K>"]],
        "<temp-C>": [["tempC", "temp-C"], 1.0, "temperature", ["<temp-K>"]],
        "<temp-F>": [["tempF", "temp-F"], 5 / 9, "temperature", ["<temp-K>"]],
        "<temp-R>": [["tempR", "temp-R"], 5 / 9, "temperature", ["<temp-K>"]],
        /* time */
        "<second>": [["s", "sec", "secs", "second", "seconds"], 1.0, "time", ["<second>"]],
        "<minute>": [["min", "mins", "minute", "minutes"], 60.0, "time", ["<second>"]],
        "<hour>": [["h", "hr", "hrs", "hour", "hours"], 3600.0, "time", ["<second>"]],
        "<day>": [["d", "day", "days"], 3600 * 24, "time", ["<second>"]],
        "<week>": [["wk", "week", "weeks"], 7 * 3600 * 24, "time", ["<second>"]],
        "<fortnight>": [["fortnight", "fortnights"], 1209600, "time", ["<second>"]],
        "<year>": [["y", "yr", "year", "years", "annum"], 31556926, "time", ["<second>"]],
        "<decade>": [["decade", "decades"], 315569260, "time", ["<second>"]],
        "<century>": [["century", "centuries"], 3155692600, "time", ["<second>"]],
        /* pressure */
        "<pascal>": [["Pa", "pascal", "Pascal"], 1.0, "pressure", ["<kilogram>"], ["<meter>", "<second>", "<second>"]],
        "<bar>": [["bar", "bars"], 100000, "pressure", ["<kilogram>"], ["<meter>", "<second>", "<second>"]],
        "<mmHg>": [["mmHg"], 133.322368, "pressure", ["<kilogram>"], ["<meter>", "<second>", "<second>"]],
        "<inHg>": [["inHg"], 3386.3881472, "pressure", ["<kilogram>"], ["<meter>", "<second>", "<second>"]],
        "<torr>": [["torr"], 133.322368, "pressure", ["<kilogram>"], ["<meter>", "<second>", "<second>"]],
        "<atm>": [["atm", "ATM", "atmosphere", "atmospheres"], 101325, "pressure", ["<kilogram>"], ["<meter>", "<second>", "<second>"]],
        "<psi>": [["psi"], 6894.76, "pressure", ["<kilogram>"], ["<meter>", "<second>", "<second>"]],
        "<cmh2o>": [["cmH2O", "cmh2o"], 98.0638, "pressure", ["<kilogram>"], ["<meter>", "<second>", "<second>"]],
        "<inh2o>": [["inH2O", "inh2o"], 249.082052, "pressure", ["<kilogram>"], ["<meter>", "<second>", "<second>"]],
        /* viscosity */
        "<poise>": [["P", "poise"], 0.1, "viscosity", ["<kilogram>"], ["<meter>", "<second>"]],
        "<stokes>": [["St", "stokes"], 1e-4, "viscosity", ["<meter>", "<meter>"], ["<second>"]],
        /* substance */
        "<mole>": [["mol", "mole"], 1.0, "substance", ["<mole>"]],
        /* molar_concentration */
        "<molar>": [["M", "molar"], 1000, "molar_concentration", ["<mole>"], ["<meter>", "<meter>", "<meter>"]],
        "<wtpercent>": [["wt%", "wtpercent"], 10, "molar_concentration", ["<kilogram>"], ["<meter>", "<meter>", "<meter>"]],
        /* activity */
        "<katal>": [["kat", "katal", "Katal"], 1.0, "activity", ["<mole>"], ["<second>"]],
        "<unit>": [["U", "enzUnit", "unit"], 16.667e-16, "activity", ["<mole>"], ["<second>"]],
        /* capacitance */
        "<farad>": [["F", "farad", "Farad"], 1.0, "capacitance", ["<second>", "<second>", "<second>", "<second>", "<ampere>", "<ampere>"], ["<meter>", "<meter>", "<kilogram>"]],
        /* charge */
        "<coulomb>": [["C", "coulomb", "Coulomb"], 1.0, "charge", ["<ampere>", "<second>"]],
        "<Ah>": [["Ah"], 3600, "charge", ["<ampere>", "<second>"]],
        /* current */
        "<ampere>": [["A", "Ampere", "ampere", "amp", "amps"], 1.0, "current", ["<ampere>"]],
        /* conductance */
        "<siemens>": [["S", "Siemens", "siemens"], 1.0, "conductance", ["<second>", "<second>", "<second>", "<ampere>", "<ampere>"], ["<kilogram>", "<meter>", "<meter>"]],
        /* inductance */
        "<henry>": [["H", "Henry", "henry"], 1.0, "inductance", ["<meter>", "<meter>", "<kilogram>"], ["<second>", "<second>", "<ampere>", "<ampere>"]],
        /* potential */
        "<volt>": [["V", "Volt", "volt", "volts"], 1.0, "potential", ["<meter>", "<meter>", "<kilogram>"], ["<second>", "<second>", "<second>", "<ampere>"]],
        /* resistance */
        "<ohm>": [["Ohm", "ohm", "\u03A9" /*Ω as greek letter*/, "\u2126" /*Ω as ohm sign*/], 1.0, "resistance", ["<meter>", "<meter>", "<kilogram>"], ["<second>", "<second>", "<second>", "<ampere>", "<ampere>"]],
        /* magnetism */
        "<weber>": [["Wb", "weber", "webers"], 1.0, "magnetism", ["<meter>", "<meter>", "<kilogram>"], ["<second>", "<second>", "<ampere>"]],
        "<tesla>": [["T", "tesla", "teslas"], 1.0, "magnetism", ["<kilogram>"], ["<second>", "<second>", "<ampere>"]],
        "<gauss>": [["G", "gauss"], 1e-4, "magnetism", ["<kilogram>"], ["<second>", "<second>", "<ampere>"]],
        "<maxwell>": [["Mx", "maxwell", "maxwells"], 1e-8, "magnetism", ["<meter>", "<meter>", "<kilogram>"], ["<second>", "<second>", "<ampere>"]],
        "<oersted>": [["Oe", "oersted", "oersteds"], 250.0 / Math.PI, "magnetism", ["<ampere>"], ["<meter>"]],
        /* energy */
        "<joule>": [["J", "joule", "Joule", "joules", "Joules"], 1.0, "energy", ["<meter>", "<meter>", "<kilogram>"], ["<second>", "<second>"]],
        "<erg>": [["erg", "ergs"], 1e-7, "energy", ["<meter>", "<meter>", "<kilogram>"], ["<second>", "<second>"]],
        "<btu>": [["BTU", "btu", "BTUs"], 1055.056, "energy", ["<meter>", "<meter>", "<kilogram>"], ["<second>", "<second>"]],
        "<calorie>": [["cal", "calorie", "calories"], 4.18400, "energy", ["<meter>", "<meter>", "<kilogram>"], ["<second>", "<second>"]],
        "<Calorie>": [["Cal", "Calorie", "Calories"], 4184.00, "energy", ["<meter>", "<meter>", "<kilogram>"], ["<second>", "<second>"]],
        "<therm-US>": [["th", "therm", "therms", "Therm", "therm-US"], 105480400, "energy", ["<meter>", "<meter>", "<kilogram>"], ["<second>", "<second>"]],
        "<Wh>": [["Wh"], 3600, "energy", ["<meter>", "<meter>", "<kilogram>"], ["<second>", "<second>"]],
        "<electronvolt>": [["eV", "electronvolt", "electronvolts"], 1.602176634E-19, "energy", ["<meter>", "<meter>", "<kilogram>"], ["<second>", "<second>"]],
        /* force */
        "<newton>": [["N", "Newton", "newton"], 1.0, "force", ["<kilogram>", "<meter>"], ["<second>", "<second>"]],
        "<dyne>": [["dyn", "dyne"], 1e-5, "force", ["<kilogram>", "<meter>"], ["<second>", "<second>"]],
        "<pound-force>": [["lbf", "pound-force"], 4.448222, "force", ["<kilogram>", "<meter>"], ["<second>", "<second>"]],
        /* frequency */
        "<hertz>": [["Hz", "hertz", "Hertz"], 1.0, "frequency", ["<1>"], ["<second>"]],
        /* angle */
        "<radian>": [["rad", "radian", "radians"], 1.0, "angle", ["<radian>"]],
        "<degree>": [["deg", "degree", "degrees"], Math.PI / 180.0, "angle", ["<radian>"]],
        "<arcminute>": [["arcmin", "arcminute", "arcminutes"], Math.PI / 10800.0, "angle", ["<radian>"]],
        "<arcsecond>": [["arcsec", "arcsecond", "arcseconds"], Math.PI / 648000.0, "angle", ["<radian>"]],
        "<gradian>": [["gon", "grad", "gradian", "grads"], Math.PI / 200.0, "angle", ["<radian>"]],
        "<steradian>": [["sr", "steradian", "steradians"], 1.0, "solid_angle", ["<steradian>"]],
        /* rotation */
        "<rotation>": [["rotation"], 2.0 * Math.PI, "angle", ["<radian>"]],
        "<rpm>": [["rpm"], 2.0 * Math.PI / 60.0, "angular_velocity", ["<radian>"], ["<second>"]],
        /* information */
        "<byte>": [["B", "byte", "bytes"], 1.0, "information", ["<byte>"]],
        "<bit>": [["b", "bit", "bits"], 0.125, "information", ["<byte>"]],
        /* information rate */
        "<Bps>": [["Bps"], 1.0, "information_rate", ["<byte>"], ["<second>"]],
        "<bps>": [["bps"], 0.125, "information_rate", ["<byte>"], ["<second>"]],
        /* currency */
        "<dollar>": [["USD", "dollar"], 1.0, "currency", ["<dollar>"]],
        "<cents>": [["cents"], 0.01, "currency", ["<dollar>"]],
        /* luminosity */
        "<candela>": [["cd", "candela"], 1.0, "luminosity", ["<candela>"]],
        "<lumen>": [["lm", "lumen"], 1.0, "luminous_power", ["<candela>", "<steradian>"]],
        "<lux>": [["lux"], 1.0, "illuminance", ["<candela>", "<steradian>"], ["<meter>", "<meter>"]],
        /* power */
        "<watt>": [["W", "watt", "watts"], 1.0, "power", ["<kilogram>", "<meter>", "<meter>"], ["<second>", "<second>", "<second>"]],
        "<volt-ampere>": [["VA", "volt-ampere"], 1.0, "power", ["<kilogram>", "<meter>", "<meter>"], ["<second>", "<second>", "<second>"]],
        "<volt-ampere-reactive>": [["var", "Var", "VAr", "VAR", "volt-ampere-reactive"], 1.0, "power", ["<kilogram>", "<meter>", "<meter>"], ["<second>", "<second>", "<second>"]],
        "<horsepower>": [["hp", "horsepower"], 745.699872, "power", ["<kilogram>", "<meter>", "<meter>"], ["<second>", "<second>", "<second>"]],
        /* radiation */
        "<gray>": [["Gy", "gray", "grays"], 1.0, "radiation", ["<meter>", "<meter>"], ["<second>", "<second>"]],
        "<roentgen>": [["R", "roentgen"], 0.009330, "radiation", ["<meter>", "<meter>"], ["<second>", "<second>"]],
        "<sievert>": [["Sv", "sievert", "sieverts"], 1.0, "radiation", ["<meter>", "<meter>"], ["<second>", "<second>"]],
        "<becquerel>": [["Bq", "becquerel", "becquerels"], 1.0, "radiation", ["<1>"], ["<second>"]],
        "<curie>": [["Ci", "curie", "curies"], 3.7e10, "radiation", ["<1>"], ["<second>"]],
        /* rate */
        "<cpm>": [["cpm"], 1.0 / 60.0, "rate", ["<count>"], ["<second>"]],
        "<dpm>": [["dpm"], 1.0 / 60.0, "rate", ["<count>"], ["<second>"]],
        "<bpm>": [["bpm"], 1.0 / 60.0, "rate", ["<count>"], ["<second>"]],
        /* resolution / typography */
        "<dot>": [["dot", "dots"], 1, "resolution", ["<each>"]],
        "<pixel>": [["pixel", "px"], 1, "resolution", ["<each>"]],
        "<ppi>": [["ppi"], 1, "resolution", ["<pixel>"], ["<inch>"]],
        "<dpi>": [["dpi"], 1, "typography", ["<dot>"], ["<inch>"]],
        /* other */
        "<cell>": [["cells", "cell"], 1, "counting", ["<each>"]],
        "<each>": [["each"], 1.0, "counting", ["<each>"]],
        "<count>": [["count"], 1.0, "counting", ["<each>"]],
        "<base-pair>": [["bp", "base-pair"], 1.0, "counting", ["<each>"]],
        "<nucleotide>": [["nt", "nucleotide"], 1.0, "counting", ["<each>"]],
        "<molecule>": [["molecule", "molecules"], 1.0, "counting", ["<1>"]],
        "<dozen>": [["doz", "dz", "dozen"], 12.0, "prefix_only", ["<each>"]],
        "<percent>": [["%", "percent"], 0.01, "prefix_only", ["<1>"]],
        "<ppm>": [["ppm"], 1e-6, "prefix_only", ["<1>"]],
        "<ppb>": [["ppb"], 1e-9, "prefix_only", ["<1>"]],
        "<ppt>": [["ppt"], 1e-12, "prefix_only", ["<1>"]],
        "<ppq>": [["ppq"], 1e-15, "prefix_only", ["<1>"]],
        "<gross>": [["gr", "gross"], 144.0, "prefix_only", ["<dozen>", "<dozen>"]],
        "<decibel>": [["dB", "decibel", "decibels"], 1.0, "logarithmic", ["<decibel>"]]
      };
      var BASE_UNITS = ["<meter>", "<kilogram>", "<second>", "<mole>", "<ampere>", "<radian>", "<kelvin>", "<temp-K>", "<byte>", "<dollar>", "<candela>", "<each>", "<steradian>", "<decibel>"];
      var UNITY = "<1>";
      var UNITY_ARRAY = [UNITY];

      // Setup

      /**
       * Asserts unit definition is valid
       *
       * @param {string} unitDef - Name of unit to test
       * @param {Object} definition - Definition of unit to test
       *
       * @returns {void}
       * @throws {QtyError} if unit definition is not valid
       */
      function validateUnitDefinition(unitDef, definition) {
        var scalar = definition[1];
        var numerator = definition[3] || [];
        var denominator = definition[4] || [];
        if (!isNumber(scalar)) {
          throw new QtyError(unitDef + ": Invalid unit definition. " + "'scalar' must be a number");
        }
        numerator.forEach(function (unit) {
          if (UNITS[unit] === undefined) {
            throw new QtyError(unitDef + ": Invalid unit definition. " + "Unit " + unit + " in 'numerator' is not recognized");
          }
        });
        denominator.forEach(function (unit) {
          if (UNITS[unit] === undefined) {
            throw new QtyError(unitDef + ": Invalid unit definition. " + "Unit " + unit + " in 'denominator' is not recognized");
          }
        });
      }
      var PREFIX_VALUES = {};
      var PREFIX_MAP = {};
      var UNIT_VALUES = {};
      var UNIT_MAP = {};
      var OUTPUT_MAP = {};
      for (var unitDef in UNITS) {
        if (UNITS.hasOwnProperty(unitDef)) {
          var definition = UNITS[unitDef];
          if (definition[2] === "prefix") {
            PREFIX_VALUES[unitDef] = definition[1];
            for (var i = 0; i < definition[0].length; i++) {
              PREFIX_MAP[definition[0][i]] = unitDef;
            }
          } else {
            validateUnitDefinition(unitDef, definition);
            UNIT_VALUES[unitDef] = {
              scalar: definition[1],
              numerator: definition[3],
              denominator: definition[4]
            };
            for (var j = 0; j < definition[0].length; j++) {
              UNIT_MAP[definition[0][j]] = unitDef;
            }
          }
          OUTPUT_MAP[unitDef] = definition[0][0];
        }
      }

      /**
       * Returns a list of available units of kind
       *
       * @param {string} [kind] - kind of units
       * @returns {array} names of units
       * @throws {QtyError} if kind is unknown
       */
      function getUnits(kind) {
        var i;
        var units = [];
        var unitKeys = Object.keys(UNITS);
        if (typeof kind === "undefined") {
          for (i = 0; i < unitKeys.length; i++) {
            if (["", "prefix"].indexOf(UNITS[unitKeys[i]][2]) === -1) {
              units.push(unitKeys[i].substr(1, unitKeys[i].length - 2));
            }
          }
        } else if (this.getKinds().indexOf(kind) === -1) {
          throw new QtyError("Kind not recognized");
        } else {
          for (i = 0; i < unitKeys.length; i++) {
            if (UNITS[unitKeys[i]][2] === kind) {
              units.push(unitKeys[i].substr(1, unitKeys[i].length - 2));
            }
          }
        }
        return units.sort(function (a, b) {
          if (a.toLowerCase() < b.toLowerCase()) {
            return -1;
          }
          if (a.toLowerCase() > b.toLowerCase()) {
            return 1;
          }
          return 0;
        });
      }

      /**
       * Returns a list of alternative names for a unit
       *
       * @param {string} unitName - name of unit
       * @returns {string[]} aliases for unit
       * @throws {QtyError} if unit is unknown
       */
      function getAliases(unitName) {
        if (!UNIT_MAP[unitName]) {
          throw new QtyError("Unit not recognized");
        }
        return UNITS[UNIT_MAP[unitName]][0];
      }
      var SIGNATURE_VECTOR = ["length", "time", "temperature", "mass", "current", "substance", "luminosity", "currency", "information", "angle"];

      /*
      calculates the unit signature id for use in comparing compatible units and simplification
      the signature is based on a simple classification of units and is based on the following publication
       Novak, G.S., Jr. "Conversion of units of measurement", IEEE Transactions on Software Engineering,
      21(8), Aug 1995, pp.651-661
      doi://10.1109/32.403789
      http://ieeexplore.ieee.org/Xplore/login.jsp?url=/iel1/32/9079/00403789.pdf?isnumber=9079&prod=JNL&arnumber=403789&arSt=651&ared=661&arAuthor=Novak%2C+G.S.%2C+Jr.
      */
      function unitSignature() {
        if (this.signature) {
          return this.signature;
        }
        var vector = unitSignatureVector.call(this);
        for (var i = 0; i < vector.length; i++) {
          vector[i] *= Math.pow(20, i);
        }
        return vector.reduce(function (previous, current) {
          return previous + current;
        }, 0);
      }

      // calculates the unit signature vector used by unit_signature
      function unitSignatureVector() {
        if (!this.isBase()) {
          return unitSignatureVector.call(this.toBase());
        }
        var vector = new Array(SIGNATURE_VECTOR.length);
        for (var i = 0; i < vector.length; i++) {
          vector[i] = 0;
        }
        var r, n;
        for (var j = 0; j < this.numerator.length; j++) {
          if (r = UNITS[this.numerator[j]]) {
            n = SIGNATURE_VECTOR.indexOf(r[2]);
            if (n >= 0) {
              vector[n] = vector[n] + 1;
            }
          }
        }
        for (var k = 0; k < this.denominator.length; k++) {
          if (r = UNITS[this.denominator[k]]) {
            n = SIGNATURE_VECTOR.indexOf(r[2]);
            if (n >= 0) {
              vector[n] = vector[n] - 1;
            }
          }
        }
        return vector;
      }
      var SIGN = "[+-]";
      var INTEGER = "\\d+";
      var SIGNED_INTEGER = SIGN + "?" + INTEGER;
      var FRACTION = "\\." + INTEGER;
      var FLOAT = "(?:" + INTEGER + "(?:" + FRACTION + ")?" + ")" + "|" + "(?:" + FRACTION + ")";
      var EXPONENT = "[Ee]" + SIGNED_INTEGER;
      var SCI_NUMBER = "(?:" + FLOAT + ")(?:" + EXPONENT + ")?";
      var SIGNED_NUMBER = SIGN + "?\\s*" + SCI_NUMBER;
      var QTY_STRING = "(" + SIGNED_NUMBER + ")?" + "\\s*([^/]*)(?:\/(.+))?";
      var QTY_STRING_REGEX = new RegExp("^" + QTY_STRING + "$");
      var POWER_OP = "\\^|\\*{2}";
      // Allow unit powers representing scalar, length, area, volume; 4 is for some
      // special case representations in SI base units.
      var SAFE_POWER = "[01234]";
      var TOP_REGEX = new RegExp("([^ \\*\\d]+?)(?:" + POWER_OP + ")?(-?" + SAFE_POWER + "(?![a-zA-Z]))");
      var BOTTOM_REGEX = new RegExp("([^ \\*\\d]+?)(?:" + POWER_OP + ")?(" + SAFE_POWER + "(?![a-zA-Z]))");

      /* parse a string into a unit object.
       * Typical formats like :
       * "5.6 kg*m/s^2"
       * "5.6 kg*m*s^-2"
       * "5.6 kilogram*meter*second^-2"
       * "2.2 kPa"
       * "37 degC"
       * "1"  -- creates a unitless constant with value 1
       * "GPa"  -- creates a unit with scalar 1 with units 'GPa'
       * 6'4"  -- recognized as 6 feet + 4 inches
       * 8 lbs 8 oz -- recognized as 8 lbs + 8 ounces
       */
      function parse(val) {
        if (!isString(val)) {
          val = val.toString();
        }
        val = val.trim();
        var result = QTY_STRING_REGEX.exec(val);
        if (!result) {
          throw new QtyError(val + ": Quantity not recognized");
        }
        var scalarMatch = result[1];
        if (scalarMatch) {
          // Allow whitespaces between sign and scalar for loose parsing
          scalarMatch = scalarMatch.replace(/\s/g, "");
          this.scalar = parseFloat(scalarMatch);
        } else {
          this.scalar = 1;
        }
        var top = result[2];
        var bottom = result[3];
        var n, x, nx;
        // TODO DRY me
        while (result = TOP_REGEX.exec(top)) {
          n = parseFloat(result[2]);
          if (isNaN(n)) {
            // Prevents infinite loops
            throw new QtyError("Unit exponent is not a number");
          }
          // Disallow unrecognized unit even if exponent is 0
          if (n === 0 && !UNIT_TEST_REGEX.test(result[1])) {
            throw new QtyError("Unit not recognized");
          }
          x = result[1] + " ";
          nx = "";
          for (var i = 0; i < Math.abs(n); i++) {
            nx += x;
          }
          if (n >= 0) {
            top = top.replace(result[0], nx);
          } else {
            bottom = bottom ? bottom + nx : nx;
            top = top.replace(result[0], "");
          }
        }
        while (result = BOTTOM_REGEX.exec(bottom)) {
          n = parseFloat(result[2]);
          if (isNaN(n)) {
            // Prevents infinite loops
            throw new QtyError("Unit exponent is not a number");
          }
          // Disallow unrecognized unit even if exponent is 0
          if (n === 0 && !UNIT_TEST_REGEX.test(result[1])) {
            throw new QtyError("Unit not recognized");
          }
          x = result[1] + " ";
          nx = "";
          for (var j = 0; j < n; j++) {
            nx += x;
          }
          bottom = bottom.replace(result[0], nx);
        }
        if (top) {
          this.numerator = parseUnits(top.trim());
        }
        if (bottom) {
          this.denominator = parseUnits(bottom.trim());
        }
      }
      var PREFIX_REGEX = Object.keys(PREFIX_MAP).sort(function (a, b) {
        return b.length - a.length;
      }).join("|");
      var UNIT_REGEX = Object.keys(UNIT_MAP).sort(function (a, b) {
        return b.length - a.length;
      }).join("|");
      /*
       * Minimal boundary regex to support units with Unicode characters
       * \b only works for ASCII
       */
      var BOUNDARY_REGEX = "\\b|$";
      var UNIT_MATCH = "(" + PREFIX_REGEX + ")??(" + UNIT_REGEX + ")(?:" + BOUNDARY_REGEX + ")";
      var UNIT_TEST_REGEX = new RegExp("^\\s*(" + UNIT_MATCH + "[\\s\\*]*)+$");
      var UNIT_MATCH_REGEX = new RegExp(UNIT_MATCH, "g"); // g flag for multiple occurences
      var parsedUnitsCache = {};
      /**
       * Parses and converts units string to normalized unit array.
       * Result is cached to speed up next calls.
       *
       * @param {string} units Units string
       * @returns {string[]} Array of normalized units
       *
       * @example
       * // Returns ["<second>", "<meter>", "<second>"]
       * parseUnits("s m s");
       *
       */
      function parseUnits(units) {
        var cached = parsedUnitsCache[units];
        if (cached) {
          return cached;
        }
        var unitMatch,
          normalizedUnits = [];

        // Scan
        if (!UNIT_TEST_REGEX.test(units)) {
          throw new QtyError("Unit not recognized");
        }
        while (unitMatch = UNIT_MATCH_REGEX.exec(units)) {
          normalizedUnits.push(unitMatch.slice(1));
        }
        normalizedUnits = normalizedUnits.map(function (item) {
          return PREFIX_MAP[item[0]] ? [PREFIX_MAP[item[0]], UNIT_MAP[item[1]]] : [UNIT_MAP[item[1]]];
        });

        // Flatten and remove null elements
        normalizedUnits = normalizedUnits.reduce(function (a, b) {
          return a.concat(b);
        }, []);
        normalizedUnits = normalizedUnits.filter(function (item) {
          return item;
        });
        parsedUnitsCache[units] = normalizedUnits;
        return normalizedUnits;
      }

      /**
       * Parses a string as a quantity
       * @param {string} value - quantity as text
       * @throws if value is not a string
       * @returns {Qty|null} Parsed quantity or null if unrecognized
       */
      function globalParse(value) {
        if (!isString(value)) {
          throw new QtyError("Argument should be a string");
        }
        try {
          return this(value);
        } catch (e) {
          return null;
        }
      }

      /**
       * Tests if a value is a Qty instance
       *
       * @param {*} value - Value to test
       *
       * @returns {boolean} true if value is a Qty instance, false otherwise
       */
      function isQty(value) {
        return value instanceof Qty;
      }
      function Qty(initValue, initUnits) {
        assertValidConstructorArgs.apply(null, arguments);
        if (!isQty(this)) {
          return new Qty(initValue, initUnits);
        }
        this.scalar = null;
        this.baseScalar = null;
        this.signature = null;
        this._conversionCache = {};
        this.numerator = UNITY_ARRAY;
        this.denominator = UNITY_ARRAY;
        if (isDefinitionObject(initValue)) {
          this.scalar = initValue.scalar;
          this.numerator = initValue.numerator && initValue.numerator.length !== 0 ? initValue.numerator : UNITY_ARRAY;
          this.denominator = initValue.denominator && initValue.denominator.length !== 0 ? initValue.denominator : UNITY_ARRAY;
        } else if (initUnits) {
          parse.call(this, initUnits);
          this.scalar = initValue;
        } else {
          parse.call(this, initValue);
        }

        // math with temperatures is very limited
        if (this.denominator.join("*").indexOf("temp") >= 0) {
          throw new QtyError("Cannot divide with temperatures");
        }
        if (this.numerator.join("*").indexOf("temp") >= 0) {
          if (this.numerator.length > 1) {
            throw new QtyError("Cannot multiply by temperatures");
          }
          if (!compareArray(this.denominator, UNITY_ARRAY)) {
            throw new QtyError("Cannot divide with temperatures");
          }
        }
        this.initValue = initValue;
        updateBaseScalar.call(this);
        if (this.isTemperature() && this.baseScalar < 0) {
          throw new QtyError("Temperatures must not be less than absolute zero");
        }
      }
      Qty.prototype = {
        // Properly set up constructor
        constructor: Qty
      };

      /**
       * Asserts constructor arguments are valid
       *
       * @param {*} value - Value to test
       * @param {string} [units] - Optional units when value is passed as a number
       *
       * @returns {void}
       * @throws {QtyError} if constructor arguments are invalid
       */
      function assertValidConstructorArgs(value, units) {
        if (units) {
          if (!(isNumber(value) && isString(units))) {
            throw new QtyError("Only number accepted as initialization value " + "when units are explicitly provided");
          }
        } else {
          if (!(isString(value) || isNumber(value) || isQty(value) || isDefinitionObject(value))) {
            throw new QtyError("Only string, number or quantity accepted as " + "single initialization value");
          }
        }
      }

      /**
       * Tests if a value is a Qty definition object
       *
       * @param {*} value - Value to test
       *
       * @returns {boolean} true if value is a definition object, false otherwise
       */
      function isDefinitionObject(value) {
        return value && typeof value === "object" && value.hasOwnProperty("scalar");
      }
      function updateBaseScalar() {
        if (this.baseScalar) {
          return this.baseScalar;
        }
        if (this.isBase()) {
          this.baseScalar = this.scalar;
          this.signature = unitSignature.call(this);
        } else {
          var base = this.toBase();
          this.baseScalar = base.scalar;
          this.signature = base.signature;
        }
      }
      var KINDS = {
        "-312078": "elastance",
        "-312058": "resistance",
        "-312038": "inductance",
        "-152058": "potential",
        "-152040": "magnetism",
        "-152038": "magnetism",
        "-7997": "specific_volume",
        "-79": "snap",
        "-59": "jolt",
        "-39": "acceleration",
        "-38": "radiation",
        "-20": "frequency",
        "-19": "speed",
        "-18": "viscosity",
        "-17": "volumetric_flow",
        "-1": "wavenumber",
        "0": "unitless",
        "1": "length",
        "2": "area",
        "3": "volume",
        "20": "time",
        "400": "temperature",
        "7941": "yank",
        "7942": "power",
        "7959": "pressure",
        "7961": "force",
        "7962": "energy",
        "7979": "viscosity",
        "7981": "momentum",
        "7982": "angular_momentum",
        "7997": "density",
        "7998": "area_density",
        "8000": "mass",
        "152020": "radiation_exposure",
        "159999": "magnetism",
        "160000": "current",
        "160020": "charge",
        "312058": "conductance",
        "312078": "capacitance",
        "3199980": "activity",
        "3199997": "molar_concentration",
        "3200000": "substance",
        "63999998": "illuminance",
        "64000000": "luminous_power",
        "1280000000": "currency",
        "25599999980": "information_rate",
        "25600000000": "information",
        "511999999980": "angular_velocity",
        "512000000000": "angle"
      };

      /**
       * Returns the list of available well-known kinds of units, e.g.
       * "radiation" or "length".
       *
       * @returns {string[]} names of kinds of units
       */
      function getKinds() {
        return uniq(Object.keys(KINDS).map(function (knownSignature) {
          return KINDS[knownSignature];
        }));
      }
      Qty.prototype.kind = function () {
        return KINDS[this.signature.toString()];
      };
      assign(Qty.prototype, {
        isDegrees: function () {
          // signature may not have been calculated yet
          return (this.signature === null || this.signature === 400) && this.numerator.length === 1 && compareArray(this.denominator, UNITY_ARRAY) && (this.numerator[0].match(/<temp-[CFRK]>/) || this.numerator[0].match(/<(kelvin|celsius|rankine|fahrenheit)>/));
        },
        isTemperature: function () {
          return this.isDegrees() && this.numerator[0].match(/<temp-[CFRK]>/);
        }
      });
      function subtractTemperatures(lhs, rhs) {
        var lhsUnits = lhs.units();
        var rhsConverted = rhs.to(lhsUnits);
        var dstDegrees = Qty(getDegreeUnits(lhsUnits));
        return Qty({
          "scalar": lhs.scalar - rhsConverted.scalar,
          "numerator": dstDegrees.numerator,
          "denominator": dstDegrees.denominator
        });
      }
      function subtractTempDegrees(temp, deg) {
        var tempDegrees = deg.to(getDegreeUnits(temp.units()));
        return Qty({
          "scalar": temp.scalar - tempDegrees.scalar,
          "numerator": temp.numerator,
          "denominator": temp.denominator
        });
      }
      function addTempDegrees(temp, deg) {
        var tempDegrees = deg.to(getDegreeUnits(temp.units()));
        return Qty({
          "scalar": temp.scalar + tempDegrees.scalar,
          "numerator": temp.numerator,
          "denominator": temp.denominator
        });
      }
      function getDegreeUnits(units) {
        if (units === "tempK") {
          return "degK";
        } else if (units === "tempC") {
          return "degC";
        } else if (units === "tempF") {
          return "degF";
        } else if (units === "tempR") {
          return "degR";
        } else {
          throw new QtyError("Unknown type for temp conversion from: " + units);
        }
      }
      function toDegrees(src, dst) {
        var srcDegK = toDegK(src);
        var dstUnits = dst.units();
        var dstScalar;
        if (dstUnits === "degK") {
          dstScalar = srcDegK.scalar;
        } else if (dstUnits === "degC") {
          dstScalar = srcDegK.scalar;
        } else if (dstUnits === "degF") {
          dstScalar = srcDegK.scalar * 9 / 5;
        } else if (dstUnits === "degR") {
          dstScalar = srcDegK.scalar * 9 / 5;
        } else {
          throw new QtyError("Unknown type for degree conversion to: " + dstUnits);
        }
        return Qty({
          "scalar": dstScalar,
          "numerator": dst.numerator,
          "denominator": dst.denominator
        });
      }
      function toDegK(qty) {
        var units = qty.units();
        var q;
        if (units.match(/(deg)[CFRK]/)) {
          q = qty.baseScalar;
        } else if (units === "tempK") {
          q = qty.scalar;
        } else if (units === "tempC") {
          q = qty.scalar;
        } else if (units === "tempF") {
          q = qty.scalar * 5 / 9;
        } else if (units === "tempR") {
          q = qty.scalar * 5 / 9;
        } else {
          throw new QtyError("Unknown type for temp conversion from: " + units);
        }
        return Qty({
          "scalar": q,
          "numerator": ["<kelvin>"],
          "denominator": UNITY_ARRAY
        });
      }
      function toTemp(src, dst) {
        var dstUnits = dst.units();
        var dstScalar;
        if (dstUnits === "tempK") {
          dstScalar = src.baseScalar;
        } else if (dstUnits === "tempC") {
          dstScalar = src.baseScalar - 273.15;
        } else if (dstUnits === "tempF") {
          dstScalar = src.baseScalar * 9 / 5 - 459.67;
        } else if (dstUnits === "tempR") {
          dstScalar = src.baseScalar * 9 / 5;
        } else {
          throw new QtyError("Unknown type for temp conversion to: " + dstUnits);
        }
        return Qty({
          "scalar": dstScalar,
          "numerator": dst.numerator,
          "denominator": dst.denominator
        });
      }
      function toTempK(qty) {
        var units = qty.units();
        var q;
        if (units.match(/(deg)[CFRK]/)) {
          q = qty.baseScalar;
        } else if (units === "tempK") {
          q = qty.scalar;
        } else if (units === "tempC") {
          q = qty.scalar + 273.15;
        } else if (units === "tempF") {
          q = (qty.scalar + 459.67) * 5 / 9;
        } else if (units === "tempR") {
          q = qty.scalar * 5 / 9;
        } else {
          throw new QtyError("Unknown type for temp conversion from: " + units);
        }
        return Qty({
          "scalar": q,
          "numerator": ["<temp-K>"],
          "denominator": UNITY_ARRAY
        });
      }
      assign(Qty.prototype, {
        /**
         * Converts to other compatible units.
         * Instance's converted quantities are cached for faster subsequent calls.
         *
         * @param {(string|Qty)} other - Target units as string or retrieved from
         *                               other Qty instance (scalar is ignored)
         *
         * @returns {Qty} New converted Qty instance with target units
         *
         * @throws {QtyError} if target units are incompatible
         *
         * @example
         * var weight = Qty("25 kg");
         * weight.to("lb"); // => Qty("55.11556554621939 lbs");
         * weight.to(Qty("3 g")); // => Qty("25000 g"); // scalar of passed Qty is ignored
         */
        to: function (other) {
          var cached, target;
          if (other === undefined || other === null) {
            return this;
          }
          if (!isString(other)) {
            return this.to(other.units());
          }
          cached = this._conversionCache[other];
          if (cached) {
            return cached;
          }

          // Instantiating target to normalize units
          target = Qty(other);
          if (target.units() === this.units()) {
            return this;
          }
          if (!this.isCompatible(target)) {
            if (this.isInverse(target)) {
              target = this.inverse().to(other);
            } else {
              throwIncompatibleUnits(this.units(), target.units());
            }
          } else {
            if (target.isTemperature()) {
              target = toTemp(this, target);
            } else if (target.isDegrees()) {
              target = toDegrees(this, target);
            } else {
              var q = divSafe(this.baseScalar, target.baseScalar);
              target = Qty({
                "scalar": q,
                "numerator": target.numerator,
                "denominator": target.denominator
              });
            }
          }
          this._conversionCache[other] = target;
          return target;
        },
        // convert to base SI units
        // results of the conversion are cached so subsequent calls to this will be fast
        toBase: function () {
          if (this.isBase()) {
            return this;
          }
          if (this.isTemperature()) {
            return toTempK(this);
          }
          var cached = baseUnitCache[this.units()];
          if (!cached) {
            cached = toBaseUnits(this.numerator, this.denominator);
            baseUnitCache[this.units()] = cached;
          }
          return cached.mul(this.scalar);
        },
        // Converts the unit back to a float if it is unitless.  Otherwise raises an exception
        toFloat: function () {
          if (this.isUnitless()) {
            return this.scalar;
          }
          throw new QtyError("Can't convert to Float unless unitless.  Use Unit#scalar");
        },
        /**
         * Returns the nearest multiple of quantity passed as
         * precision
         *
         * @param {(Qty|string|number)} precQuantity - Quantity, string formated
         *   quantity or number as expected precision
         *
         * @returns {Qty} Nearest multiple of precQuantity
         *
         * @example
         * Qty('5.5 ft').toPrec('2 ft'); // returns 6 ft
         * Qty('0.8 cu').toPrec('0.25 cu'); // returns 0.75 cu
         * Qty('6.3782 m').toPrec('cm'); // returns 6.38 m
         * Qty('1.146 MPa').toPrec('0.1 bar'); // returns 1.15 MPa
         *
         */
        toPrec: function (precQuantity) {
          if (isString(precQuantity)) {
            precQuantity = Qty(precQuantity);
          }
          if (isNumber(precQuantity)) {
            precQuantity = Qty(precQuantity + " " + this.units());
          }
          if (!this.isUnitless()) {
            precQuantity = precQuantity.to(this.units());
          } else if (!precQuantity.isUnitless()) {
            throwIncompatibleUnits(this.units(), precQuantity.units());
          }
          if (precQuantity.scalar === 0) {
            throw new QtyError("Divide by zero");
          }
          var precRoundedResult = mulSafe(Math.round(this.scalar / precQuantity.scalar), precQuantity.scalar);
          return Qty(precRoundedResult + this.units());
        }
      });

      /**
       * Configures and returns a fast function to convert
       * Number values from units to others.
       * Useful to efficiently convert large array of values
       * with same units into others with iterative methods.
       * Does not take care of rounding issues.
       *
       * @param {string} srcUnits Units of values to convert
       * @param {string} dstUnits Units to convert to
       *
       * @returns {Function} Converting function accepting Number value
       *   and returning converted value
       *
       * @throws "Incompatible units" if units are incompatible
       *
       * @example
       * // Converting large array of numbers with the same units
       * // into other units
       * var converter = Qty.swiftConverter("m/h", "ft/s");
       * var convertedSerie = largeSerie.map(converter);
       *
       */
      function swiftConverter(srcUnits, dstUnits) {
        var srcQty = Qty(srcUnits);
        var dstQty = Qty(dstUnits);
        if (srcQty.eq(dstQty)) {
          return identity;
        }
        var convert;
        if (!srcQty.isTemperature()) {
          convert = function (value) {
            return value * srcQty.baseScalar / dstQty.baseScalar;
          };
        } else {
          convert = function (value) {
            // TODO Not optimized
            return srcQty.mul(value).to(dstQty).scalar;
          };
        }
        return function converter(value) {
          var i, length, result;
          if (!Array.isArray(value)) {
            return convert(value);
          } else {
            length = value.length;
            result = [];
            for (i = 0; i < length; i++) {
              result.push(convert(value[i]));
            }
            return result;
          }
        };
      }
      var baseUnitCache = {};
      function toBaseUnits(numerator, denominator) {
        var num = [];
        var den = [];
        var q = 1;
        var unit;
        for (var i = 0; i < numerator.length; i++) {
          unit = numerator[i];
          if (PREFIX_VALUES[unit]) {
            // workaround to fix
            // 0.1 * 0.1 => 0.010000000000000002
            q = mulSafe(q, PREFIX_VALUES[unit]);
          } else {
            if (UNIT_VALUES[unit]) {
              q *= UNIT_VALUES[unit].scalar;
              if (UNIT_VALUES[unit].numerator) {
                num.push(UNIT_VALUES[unit].numerator);
              }
              if (UNIT_VALUES[unit].denominator) {
                den.push(UNIT_VALUES[unit].denominator);
              }
            }
          }
        }
        for (var j = 0; j < denominator.length; j++) {
          unit = denominator[j];
          if (PREFIX_VALUES[unit]) {
            q /= PREFIX_VALUES[unit];
          } else {
            if (UNIT_VALUES[unit]) {
              q /= UNIT_VALUES[unit].scalar;
              if (UNIT_VALUES[unit].numerator) {
                den.push(UNIT_VALUES[unit].numerator);
              }
              if (UNIT_VALUES[unit].denominator) {
                num.push(UNIT_VALUES[unit].denominator);
              }
            }
          }
        }

        // Flatten
        num = num.reduce(function (a, b) {
          return a.concat(b);
        }, []);
        den = den.reduce(function (a, b) {
          return a.concat(b);
        }, []);
        return Qty({
          "scalar": q,
          "numerator": num,
          "denominator": den
        });
      }
      Qty.parse = globalParse;
      Qty.getUnits = getUnits;
      Qty.getAliases = getAliases;
      Qty.mulSafe = mulSafe;
      Qty.divSafe = divSafe;
      Qty.getKinds = getKinds;
      Qty.swiftConverter = swiftConverter;
      Qty.Error = QtyError;
      assign(Qty.prototype, {
        // Returns new instance with units of this
        add: function (other) {
          if (isString(other)) {
            other = Qty(other);
          }
          if (!this.isCompatible(other)) {
            throwIncompatibleUnits(this.units(), other.units());
          }
          if (this.isTemperature() && other.isTemperature()) {
            throw new QtyError("Cannot add two temperatures");
          } else if (this.isTemperature()) {
            return addTempDegrees(this, other);
          } else if (other.isTemperature()) {
            return addTempDegrees(other, this);
          }
          return Qty({
            "scalar": this.scalar + other.to(this).scalar,
            "numerator": this.numerator,
            "denominator": this.denominator
          });
        },
        sub: function (other) {
          if (isString(other)) {
            other = Qty(other);
          }
          if (!this.isCompatible(other)) {
            throwIncompatibleUnits(this.units(), other.units());
          }
          if (this.isTemperature() && other.isTemperature()) {
            return subtractTemperatures(this, other);
          } else if (this.isTemperature()) {
            return subtractTempDegrees(this, other);
          } else if (other.isTemperature()) {
            throw new QtyError("Cannot subtract a temperature from a differential degree unit");
          }
          return Qty({
            "scalar": this.scalar - other.to(this).scalar,
            "numerator": this.numerator,
            "denominator": this.denominator
          });
        },
        mul: function (other) {
          if (isNumber(other)) {
            return Qty({
              "scalar": mulSafe(this.scalar, other),
              "numerator": this.numerator,
              "denominator": this.denominator
            });
          } else if (isString(other)) {
            other = Qty(other);
          }
          if ((this.isTemperature() || other.isTemperature()) && !(this.isUnitless() || other.isUnitless())) {
            throw new QtyError("Cannot multiply by temperatures");
          }

          // Quantities should be multiplied with same units if compatible, with base units else
          var op1 = this;
          var op2 = other;

          // so as not to confuse results, multiplication and division between temperature degrees will maintain original unit info in num/den
          // multiplication and division between deg[CFRK] can never factor each other out, only themselves: "degK*degC/degC^2" == "degK/degC"
          if (op1.isCompatible(op2) && op1.signature !== 400) {
            op2 = op2.to(op1);
          }
          var numdenscale = cleanTerms(op1.numerator, op1.denominator, op2.numerator, op2.denominator);
          return Qty({
            "scalar": mulSafe(op1.scalar, op2.scalar, numdenscale[2]),
            "numerator": numdenscale[0],
            "denominator": numdenscale[1]
          });
        },
        div: function (other) {
          if (isNumber(other)) {
            if (other === 0) {
              throw new QtyError("Divide by zero");
            }
            return Qty({
              "scalar": this.scalar / other,
              "numerator": this.numerator,
              "denominator": this.denominator
            });
          } else if (isString(other)) {
            other = Qty(other);
          }
          if (other.scalar === 0) {
            throw new QtyError("Divide by zero");
          }
          if (other.isTemperature()) {
            throw new QtyError("Cannot divide with temperatures");
          } else if (this.isTemperature() && !other.isUnitless()) {
            throw new QtyError("Cannot divide with temperatures");
          }

          // Quantities should be multiplied with same units if compatible, with base units else
          var op1 = this;
          var op2 = other;

          // so as not to confuse results, multiplication and division between temperature degrees will maintain original unit info in num/den
          // multiplication and division between deg[CFRK] can never factor each other out, only themselves: "degK*degC/degC^2" == "degK/degC"
          if (op1.isCompatible(op2) && op1.signature !== 400) {
            op2 = op2.to(op1);
          }
          var numdenscale = cleanTerms(op1.numerator, op1.denominator, op2.denominator, op2.numerator);
          return Qty({
            "scalar": mulSafe(op1.scalar, numdenscale[2]) / op2.scalar,
            "numerator": numdenscale[0],
            "denominator": numdenscale[1]
          });
        },
        // Returns a Qty that is the inverse of this Qty,
        inverse: function () {
          if (this.isTemperature()) {
            throw new QtyError("Cannot divide with temperatures");
          }
          if (this.scalar === 0) {
            throw new QtyError("Divide by zero");
          }
          return Qty({
            "scalar": 1 / this.scalar,
            "numerator": this.denominator,
            "denominator": this.numerator
          });
        }
      });
      function cleanTerms(num1, den1, num2, den2) {
        function notUnity(val) {
          return val !== UNITY;
        }
        num1 = num1.filter(notUnity);
        num2 = num2.filter(notUnity);
        den1 = den1.filter(notUnity);
        den2 = den2.filter(notUnity);
        var combined = {};
        function combineTerms(terms, direction) {
          var k;
          var prefix;
          var prefixValue;
          for (var i = 0; i < terms.length; i++) {
            if (PREFIX_VALUES[terms[i]]) {
              k = terms[i + 1];
              prefix = terms[i];
              prefixValue = PREFIX_VALUES[prefix];
              i++;
            } else {
              k = terms[i];
              prefix = null;
              prefixValue = 1;
            }
            if (k && k !== UNITY) {
              if (combined[k]) {
                combined[k][0] += direction;
                var combinedPrefixValue = combined[k][2] ? PREFIX_VALUES[combined[k][2]] : 1;
                combined[k][direction === 1 ? 3 : 4] *= divSafe(prefixValue, combinedPrefixValue);
              } else {
                combined[k] = [direction, k, prefix, 1, 1];
              }
            }
          }
        }
        combineTerms(num1, 1);
        combineTerms(den1, -1);
        combineTerms(num2, 1);
        combineTerms(den2, -1);
        var num = [];
        var den = [];
        var scale = 1;
        for (var prop in combined) {
          if (combined.hasOwnProperty(prop)) {
            var item = combined[prop];
            var n;
            if (item[0] > 0) {
              for (n = 0; n < item[0]; n++) {
                num.push(item[2] === null ? item[1] : [item[2], item[1]]);
              }
            } else if (item[0] < 0) {
              for (n = 0; n < -item[0]; n++) {
                den.push(item[2] === null ? item[1] : [item[2], item[1]]);
              }
            }
            scale *= divSafe(item[3], item[4]);
          }
        }
        if (num.length === 0) {
          num = UNITY_ARRAY;
        }
        if (den.length === 0) {
          den = UNITY_ARRAY;
        }

        // Flatten
        num = num.reduce(function (a, b) {
          return a.concat(b);
        }, []);
        den = den.reduce(function (a, b) {
          return a.concat(b);
        }, []);
        return [num, den, scale];
      }
      assign(Qty.prototype, {
        eq: function (other) {
          return this.compareTo(other) === 0;
        },
        lt: function (other) {
          return this.compareTo(other) === -1;
        },
        lte: function (other) {
          return this.eq(other) || this.lt(other);
        },
        gt: function (other) {
          return this.compareTo(other) === 1;
        },
        gte: function (other) {
          return this.eq(other) || this.gt(other);
        },
        // Compare two Qty objects. Throws an exception if they are not of compatible types.
        // Comparisons are done based on the value of the quantity in base SI units.
        //
        // NOTE: We cannot compare inverses as that breaks the general compareTo contract:
        //   if a.compareTo(b) < 0 then b.compareTo(a) > 0
        //   if a.compareTo(b) == 0 then b.compareTo(a) == 0
        //
        //   Since "10S" == ".1ohm" (10 > .1) and "10ohm" == ".1S" (10 > .1)
        //     Qty("10S").inverse().compareTo("10ohm") == -1
        //     Qty("10ohm").inverse().compareTo("10S") == -1
        //
        //   If including inverses in the sort is needed, I suggest writing: Qty.sort(qtyArray,units)
        compareTo: function (other) {
          if (isString(other)) {
            return this.compareTo(Qty(other));
          }
          if (!this.isCompatible(other)) {
            throwIncompatibleUnits(this.units(), other.units());
          }
          if (this.baseScalar < other.baseScalar) {
            return -1;
          } else if (this.baseScalar === other.baseScalar) {
            return 0;
          } else if (this.baseScalar > other.baseScalar) {
            return 1;
          }
        },
        // Return true if quantities and units match
        // Unit("100 cm").same(Unit("100 cm"))  # => true
        // Unit("100 cm").same(Unit("1 m"))     # => false
        same: function (other) {
          return this.scalar === other.scalar && this.units() === other.units();
        }
      });
      assign(Qty.prototype, {
        // returns true if no associated units
        // false, even if the units are "unitless" like 'radians, each, etc'
        isUnitless: function () {
          return [this.numerator, this.denominator].every(function (item) {
            return compareArray(item, UNITY_ARRAY);
          });
        },
        /*
        check to see if units are compatible, but not the scalar part
        this check is done by comparing signatures for performance reasons
        if passed a string, it will create a unit object with the string and then do the comparison
        this permits a syntax like:
        unit =~ "mm"
        if you want to do a regexp on the unit string do this ...
        unit.units =~ /regexp/
        */
        isCompatible: function (other) {
          if (isString(other)) {
            return this.isCompatible(Qty(other));
          }
          if (!isQty(other)) {
            return false;
          }
          if (other.signature !== undefined) {
            return this.signature === other.signature;
          } else {
            return false;
          }
        },
        /*
        check to see if units are inverse of each other, but not the scalar part
        this check is done by comparing signatures for performance reasons
        if passed a string, it will create a unit object with the string and then do the comparison
        this permits a syntax like:
        unit =~ "mm"
        if you want to do a regexp on the unit string do this ...
        unit.units =~ /regexp/
        */
        isInverse: function (other) {
          return this.inverse().isCompatible(other);
        },
        // Returns 'true' if the Unit is represented in base units
        isBase: function () {
          if (this._isBase !== undefined) {
            return this._isBase;
          }
          if (this.isDegrees() && this.numerator[0].match(/<(kelvin|temp-K)>/)) {
            this._isBase = true;
            return this._isBase;
          }
          this.numerator.concat(this.denominator).forEach(function (item) {
            if (item !== UNITY && BASE_UNITS.indexOf(item) === -1) {
              this._isBase = false;
            }
          }, this);
          if (this._isBase === false) {
            return this._isBase;
          }
          this._isBase = true;
          return this._isBase;
        }
      });
      function NestedMap() {}
      NestedMap.prototype.get = function (keys) {
        // Allows to pass key1, key2, ... instead of [key1, key2, ...]
        if (arguments.length > 1) {
          // Slower with Firefox but faster with Chrome than
          // Array.prototype.slice.call(arguments)
          // See http://jsperf.com/array-apply-versus-array-prototype-slice-call
          keys = Array.apply(null, arguments);
        }
        return keys.reduce(function (map, key, index) {
          if (map) {
            var childMap = map[key];
            if (index === keys.length - 1) {
              return childMap ? childMap.data : undefined;
            } else {
              return childMap;
            }
          }
        }, this);
      };
      NestedMap.prototype.set = function (keys, value) {
        if (arguments.length > 2) {
          keys = Array.prototype.slice.call(arguments, 0, -1);
          value = arguments[arguments.length - 1];
        }
        return keys.reduce(function (map, key, index) {
          var childMap = map[key];
          if (childMap === undefined) {
            childMap = map[key] = {};
          }
          if (index === keys.length - 1) {
            childMap.data = value;
            return value;
          } else {
            return childMap;
          }
        }, this);
      };

      /**
       * Default formatter
       *
       * @param {number} scalar - scalar value
       * @param {string} units - units as string
       *
       * @returns {string} formatted result
       */
      function defaultFormatter(scalar, units) {
        return (scalar + " " + units).trim();
      }

      /**
       *
       * Configurable Qty default formatter
       *
       * @type {function}
       *
       * @param {number} scalar
       * @param {string} units
       *
       * @returns {string} formatted result
       */
      Qty.formatter = defaultFormatter;
      assign(Qty.prototype, {
        // returns the 'unit' part of the Unit object without the scalar
        units: function () {
          if (this._units !== undefined) {
            return this._units;
          }
          var numIsUnity = compareArray(this.numerator, UNITY_ARRAY);
          var denIsUnity = compareArray(this.denominator, UNITY_ARRAY);
          if (numIsUnity && denIsUnity) {
            this._units = "";
            return this._units;
          }
          var numUnits = stringifyUnits(this.numerator);
          var denUnits = stringifyUnits(this.denominator);
          this._units = numUnits + (denIsUnity ? "" : "/" + denUnits);
          return this._units;
        },
        /**
         * Stringifies the quantity
         * Deprecation notice: only units parameter is supported.
         *
         * @param {(number|string|Qty)} targetUnitsOrMaxDecimalsOrPrec -
         *                              target units if string,
         *                              max number of decimals if number,
         *                              passed to #toPrec before converting if Qty
         *
         * @param {number=} maxDecimals - Maximum number of decimals of
         *                                formatted output
         *
         * @returns {string} reparseable quantity as string
         */
        toString: function (targetUnitsOrMaxDecimalsOrPrec, maxDecimals) {
          var targetUnits;
          if (isNumber(targetUnitsOrMaxDecimalsOrPrec)) {
            targetUnits = this.units();
            maxDecimals = targetUnitsOrMaxDecimalsOrPrec;
          } else if (isString(targetUnitsOrMaxDecimalsOrPrec)) {
            targetUnits = targetUnitsOrMaxDecimalsOrPrec;
          } else if (isQty(targetUnitsOrMaxDecimalsOrPrec)) {
            return this.toPrec(targetUnitsOrMaxDecimalsOrPrec).toString(maxDecimals);
          }
          var out = this.to(targetUnits);
          var outScalar = maxDecimals !== undefined ? round(out.scalar, maxDecimals) : out.scalar;
          out = (outScalar + " " + out.units()).trim();
          return out;
        },
        /**
         * Format the quantity according to optional passed target units
         * and formatter
         *
         * @param {string} [targetUnits=current units] -
         *                 optional units to convert to before formatting
         *
         * @param {function} [formatter=Qty.formatter] -
         *                   delegates formatting to formatter callback.
         *                   formatter is called back with two parameters (scalar, units)
         *                   and should return formatted result.
         *                   If unspecified, formatting is delegated to default formatter
         *                   set to Qty.formatter
         *
         * @example
         * var roundingAndLocalizingFormatter = function(scalar, units) {
         *   // localize or limit scalar to n max decimals for instance
         *   // return formatted result
         * };
         * var qty = Qty('1.1234 m');
         * qty.format(); // same units, default formatter => "1.234 m"
         * qty.format("cm"); // converted to "cm", default formatter => "123.45 cm"
         * qty.format(roundingAndLocalizingFormatter); // same units, custom formatter => "1,2 m"
         * qty.format("cm", roundingAndLocalizingFormatter); // convert to "cm", custom formatter => "123,4 cm"
         *
         * @returns {string} quantity as string
         */
        format: function (targetUnits, formatter) {
          if (arguments.length === 1) {
            if (typeof targetUnits === "function") {
              formatter = targetUnits;
              targetUnits = undefined;
            }
          }
          formatter = formatter || Qty.formatter;
          var targetQty = this.to(targetUnits);
          return formatter.call(this, targetQty.scalar, targetQty.units());
        }
      });
      var stringifiedUnitsCache = new NestedMap();
      /**
       * Returns a string representing a normalized unit array
       *
       * @param {string[]} units Normalized unit array
       * @returns {string} String representing passed normalized unit array and
       *   suitable for output
       *
       */
      function stringifyUnits(units) {
        var stringified = stringifiedUnitsCache.get(units);
        if (stringified) {
          return stringified;
        }
        var isUnity = compareArray(units, UNITY_ARRAY);
        if (isUnity) {
          stringified = "1";
        } else {
          stringified = simplify(getOutputNames(units)).join("*");
        }

        // Cache result
        stringifiedUnitsCache.set(units, stringified);
        return stringified;
      }
      function getOutputNames(units) {
        var unitNames = [],
          token,
          tokenNext;
        for (var i = 0; i < units.length; i++) {
          token = units[i];
          tokenNext = units[i + 1];
          if (PREFIX_VALUES[token]) {
            unitNames.push(OUTPUT_MAP[token] + OUTPUT_MAP[tokenNext]);
            i++;
          } else {
            unitNames.push(OUTPUT_MAP[token]);
          }
        }
        return unitNames;
      }
      function simplify(units) {
        // this turns ['s','m','s'] into ['s2','m']

        var unitCounts = units.reduce(function (acc, unit) {
          var unitCounter = acc[unit];
          if (!unitCounter) {
            acc.push(unitCounter = acc[unit] = [unit, 0]);
          }
          unitCounter[1]++;
          return acc;
        }, []);
        return unitCounts.map(function (unitCount) {
          return unitCount[0] + (unitCount[1] > 1 ? unitCount[1] : "");
        });
      }
      Qty.version = "1.8.0";
      return Qty;
    });
  })(quantities$1);
  var quantitiesExports = quantities$1.exports;
  var Qty = /*@__PURE__*/getDefaultExportFromCjs(quantitiesExports);

  function deepValue(object, path = '') {
    let parts = path.split('.');
    for (let part of parts) {
      if (object[part] === undefined) return undefined;
      object = object[part];
    }
    return object;
  }

  var orientation = {exports: {}};

  var twoProduct_1 = twoProduct$1;
  var SPLITTER = +(Math.pow(2, 27) + 1.0);
  function twoProduct$1(a, b, result) {
    var x = a * b;
    var c = SPLITTER * a;
    var abig = c - a;
    var ahi = c - abig;
    var alo = a - ahi;
    var d = SPLITTER * b;
    var bbig = d - b;
    var bhi = d - bbig;
    var blo = b - bhi;
    var err1 = x - ahi * bhi;
    var err2 = err1 - alo * bhi;
    var err3 = err2 - ahi * blo;
    var y = alo * blo - err3;
    if (result) {
      result[0] = y;
      result[1] = x;
      return result;
    }
    return [y, x];
  }

  var robustSum = linearExpansionSum;

  //Easy case: Add two scalars
  function scalarScalar$1(a, b) {
    var x = a + b;
    var bv = x - a;
    var av = x - bv;
    var br = b - bv;
    var ar = a - av;
    var y = ar + br;
    if (y) {
      return [y, x];
    }
    return [x];
  }
  function linearExpansionSum(e, f) {
    var ne = e.length | 0;
    var nf = f.length | 0;
    if (ne === 1 && nf === 1) {
      return scalarScalar$1(e[0], f[0]);
    }
    var n = ne + nf;
    var g = new Array(n);
    var count = 0;
    var eptr = 0;
    var fptr = 0;
    var abs = Math.abs;
    var ei = e[eptr];
    var ea = abs(ei);
    var fi = f[fptr];
    var fa = abs(fi);
    var a, b;
    if (ea < fa) {
      b = ei;
      eptr += 1;
      if (eptr < ne) {
        ei = e[eptr];
        ea = abs(ei);
      }
    } else {
      b = fi;
      fptr += 1;
      if (fptr < nf) {
        fi = f[fptr];
        fa = abs(fi);
      }
    }
    if (eptr < ne && ea < fa || fptr >= nf) {
      a = ei;
      eptr += 1;
      if (eptr < ne) {
        ei = e[eptr];
        ea = abs(ei);
      }
    } else {
      a = fi;
      fptr += 1;
      if (fptr < nf) {
        fi = f[fptr];
        fa = abs(fi);
      }
    }
    var x = a + b;
    var bv = x - a;
    var y = b - bv;
    var q0 = y;
    var q1 = x;
    var _x, _bv, _av, _br, _ar;
    while (eptr < ne && fptr < nf) {
      if (ea < fa) {
        a = ei;
        eptr += 1;
        if (eptr < ne) {
          ei = e[eptr];
          ea = abs(ei);
        }
      } else {
        a = fi;
        fptr += 1;
        if (fptr < nf) {
          fi = f[fptr];
          fa = abs(fi);
        }
      }
      b = q0;
      x = a + b;
      bv = x - a;
      y = b - bv;
      if (y) {
        g[count++] = y;
      }
      _x = q1 + x;
      _bv = _x - q1;
      _av = _x - _bv;
      _br = x - _bv;
      _ar = q1 - _av;
      q0 = _ar + _br;
      q1 = _x;
    }
    while (eptr < ne) {
      a = ei;
      b = q0;
      x = a + b;
      bv = x - a;
      y = b - bv;
      if (y) {
        g[count++] = y;
      }
      _x = q1 + x;
      _bv = _x - q1;
      _av = _x - _bv;
      _br = x - _bv;
      _ar = q1 - _av;
      q0 = _ar + _br;
      q1 = _x;
      eptr += 1;
      if (eptr < ne) {
        ei = e[eptr];
      }
    }
    while (fptr < nf) {
      a = fi;
      b = q0;
      x = a + b;
      bv = x - a;
      y = b - bv;
      if (y) {
        g[count++] = y;
      }
      _x = q1 + x;
      _bv = _x - q1;
      _av = _x - _bv;
      _br = x - _bv;
      _ar = q1 - _av;
      q0 = _ar + _br;
      q1 = _x;
      fptr += 1;
      if (fptr < nf) {
        fi = f[fptr];
      }
    }
    if (q0) {
      g[count++] = q0;
    }
    if (q1) {
      g[count++] = q1;
    }
    if (!count) {
      g[count++] = 0.0;
    }
    g.length = count;
    return g;
  }

  var twoSum$1 = fastTwoSum;
  function fastTwoSum(a, b, result) {
    var x = a + b;
    var bv = x - a;
    var av = x - bv;
    var br = b - bv;
    var ar = a - av;
    if (result) {
      result[0] = ar + br;
      result[1] = x;
      return result;
    }
    return [ar + br, x];
  }

  var twoProduct = twoProduct_1;
  var twoSum = twoSum$1;
  var robustScale = scaleLinearExpansion;
  function scaleLinearExpansion(e, scale) {
    var n = e.length;
    if (n === 1) {
      var ts = twoProduct(e[0], scale);
      if (ts[0]) {
        return ts;
      }
      return [ts[1]];
    }
    var g = new Array(2 * n);
    var q = [0.1, 0.1];
    var t = [0.1, 0.1];
    var count = 0;
    twoProduct(e[0], scale, q);
    if (q[0]) {
      g[count++] = q[0];
    }
    for (var i = 1; i < n; ++i) {
      twoProduct(e[i], scale, t);
      var pq = q[1];
      twoSum(pq, t[0], q);
      if (q[0]) {
        g[count++] = q[0];
      }
      var a = t[1];
      var b = q[1];
      var x = a + b;
      var bv = x - a;
      var y = b - bv;
      q[1] = x;
      if (y) {
        g[count++] = y;
      }
    }
    if (q[1]) {
      g[count++] = q[1];
    }
    if (count === 0) {
      g[count++] = 0.0;
    }
    g.length = count;
    return g;
  }

  var robustDiff = robustSubtract;

  //Easy case: Add two scalars
  function scalarScalar(a, b) {
    var x = a + b;
    var bv = x - a;
    var av = x - bv;
    var br = b - bv;
    var ar = a - av;
    var y = ar + br;
    if (y) {
      return [y, x];
    }
    return [x];
  }
  function robustSubtract(e, f) {
    var ne = e.length | 0;
    var nf = f.length | 0;
    if (ne === 1 && nf === 1) {
      return scalarScalar(e[0], -f[0]);
    }
    var n = ne + nf;
    var g = new Array(n);
    var count = 0;
    var eptr = 0;
    var fptr = 0;
    var abs = Math.abs;
    var ei = e[eptr];
    var ea = abs(ei);
    var fi = -f[fptr];
    var fa = abs(fi);
    var a, b;
    if (ea < fa) {
      b = ei;
      eptr += 1;
      if (eptr < ne) {
        ei = e[eptr];
        ea = abs(ei);
      }
    } else {
      b = fi;
      fptr += 1;
      if (fptr < nf) {
        fi = -f[fptr];
        fa = abs(fi);
      }
    }
    if (eptr < ne && ea < fa || fptr >= nf) {
      a = ei;
      eptr += 1;
      if (eptr < ne) {
        ei = e[eptr];
        ea = abs(ei);
      }
    } else {
      a = fi;
      fptr += 1;
      if (fptr < nf) {
        fi = -f[fptr];
        fa = abs(fi);
      }
    }
    var x = a + b;
    var bv = x - a;
    var y = b - bv;
    var q0 = y;
    var q1 = x;
    var _x, _bv, _av, _br, _ar;
    while (eptr < ne && fptr < nf) {
      if (ea < fa) {
        a = ei;
        eptr += 1;
        if (eptr < ne) {
          ei = e[eptr];
          ea = abs(ei);
        }
      } else {
        a = fi;
        fptr += 1;
        if (fptr < nf) {
          fi = -f[fptr];
          fa = abs(fi);
        }
      }
      b = q0;
      x = a + b;
      bv = x - a;
      y = b - bv;
      if (y) {
        g[count++] = y;
      }
      _x = q1 + x;
      _bv = _x - q1;
      _av = _x - _bv;
      _br = x - _bv;
      _ar = q1 - _av;
      q0 = _ar + _br;
      q1 = _x;
    }
    while (eptr < ne) {
      a = ei;
      b = q0;
      x = a + b;
      bv = x - a;
      y = b - bv;
      if (y) {
        g[count++] = y;
      }
      _x = q1 + x;
      _bv = _x - q1;
      _av = _x - _bv;
      _br = x - _bv;
      _ar = q1 - _av;
      q0 = _ar + _br;
      q1 = _x;
      eptr += 1;
      if (eptr < ne) {
        ei = e[eptr];
      }
    }
    while (fptr < nf) {
      a = fi;
      b = q0;
      x = a + b;
      bv = x - a;
      y = b - bv;
      if (y) {
        g[count++] = y;
      }
      _x = q1 + x;
      _bv = _x - q1;
      _av = _x - _bv;
      _br = x - _bv;
      _ar = q1 - _av;
      q0 = _ar + _br;
      q1 = _x;
      fptr += 1;
      if (fptr < nf) {
        fi = -f[fptr];
      }
    }
    if (q0) {
      g[count++] = q0;
    }
    if (q1) {
      g[count++] = q1;
    }
    if (!count) {
      g[count++] = 0.0;
    }
    g.length = count;
    return g;
  }

  (function (module) {

    var twoProduct = twoProduct_1;
    var robustSum$1 = robustSum;
    var robustScale$1 = robustScale;
    var robustSubtract = robustDiff;
    var NUM_EXPAND = 5;
    var EPSILON = 1.1102230246251565e-16;
    var ERRBOUND3 = (3.0 + 16.0 * EPSILON) * EPSILON;
    var ERRBOUND4 = (7.0 + 56.0 * EPSILON) * EPSILON;
    function orientation_3(sum, prod, scale, sub) {
      return function orientation3Exact(m0, m1, m2) {
        var p = sum(sum(prod(m1[1], m2[0]), prod(-m2[1], m1[0])), sum(prod(m0[1], m1[0]), prod(-m1[1], m0[0])));
        var n = sum(prod(m0[1], m2[0]), prod(-m2[1], m0[0]));
        var d = sub(p, n);
        return d[d.length - 1];
      };
    }
    function orientation_4(sum, prod, scale, sub) {
      return function orientation4Exact(m0, m1, m2, m3) {
        var p = sum(sum(scale(sum(prod(m2[1], m3[0]), prod(-m3[1], m2[0])), m1[2]), sum(scale(sum(prod(m1[1], m3[0]), prod(-m3[1], m1[0])), -m2[2]), scale(sum(prod(m1[1], m2[0]), prod(-m2[1], m1[0])), m3[2]))), sum(scale(sum(prod(m1[1], m3[0]), prod(-m3[1], m1[0])), m0[2]), sum(scale(sum(prod(m0[1], m3[0]), prod(-m3[1], m0[0])), -m1[2]), scale(sum(prod(m0[1], m1[0]), prod(-m1[1], m0[0])), m3[2]))));
        var n = sum(sum(scale(sum(prod(m2[1], m3[0]), prod(-m3[1], m2[0])), m0[2]), sum(scale(sum(prod(m0[1], m3[0]), prod(-m3[1], m0[0])), -m2[2]), scale(sum(prod(m0[1], m2[0]), prod(-m2[1], m0[0])), m3[2]))), sum(scale(sum(prod(m1[1], m2[0]), prod(-m2[1], m1[0])), m0[2]), sum(scale(sum(prod(m0[1], m2[0]), prod(-m2[1], m0[0])), -m1[2]), scale(sum(prod(m0[1], m1[0]), prod(-m1[1], m0[0])), m2[2]))));
        var d = sub(p, n);
        return d[d.length - 1];
      };
    }
    function orientation_5(sum, prod, scale, sub) {
      return function orientation5Exact(m0, m1, m2, m3, m4) {
        var p = sum(sum(sum(scale(sum(scale(sum(prod(m3[1], m4[0]), prod(-m4[1], m3[0])), m2[2]), sum(scale(sum(prod(m2[1], m4[0]), prod(-m4[1], m2[0])), -m3[2]), scale(sum(prod(m2[1], m3[0]), prod(-m3[1], m2[0])), m4[2]))), m1[3]), sum(scale(sum(scale(sum(prod(m3[1], m4[0]), prod(-m4[1], m3[0])), m1[2]), sum(scale(sum(prod(m1[1], m4[0]), prod(-m4[1], m1[0])), -m3[2]), scale(sum(prod(m1[1], m3[0]), prod(-m3[1], m1[0])), m4[2]))), -m2[3]), scale(sum(scale(sum(prod(m2[1], m4[0]), prod(-m4[1], m2[0])), m1[2]), sum(scale(sum(prod(m1[1], m4[0]), prod(-m4[1], m1[0])), -m2[2]), scale(sum(prod(m1[1], m2[0]), prod(-m2[1], m1[0])), m4[2]))), m3[3]))), sum(scale(sum(scale(sum(prod(m2[1], m3[0]), prod(-m3[1], m2[0])), m1[2]), sum(scale(sum(prod(m1[1], m3[0]), prod(-m3[1], m1[0])), -m2[2]), scale(sum(prod(m1[1], m2[0]), prod(-m2[1], m1[0])), m3[2]))), -m4[3]), sum(scale(sum(scale(sum(prod(m3[1], m4[0]), prod(-m4[1], m3[0])), m1[2]), sum(scale(sum(prod(m1[1], m4[0]), prod(-m4[1], m1[0])), -m3[2]), scale(sum(prod(m1[1], m3[0]), prod(-m3[1], m1[0])), m4[2]))), m0[3]), scale(sum(scale(sum(prod(m3[1], m4[0]), prod(-m4[1], m3[0])), m0[2]), sum(scale(sum(prod(m0[1], m4[0]), prod(-m4[1], m0[0])), -m3[2]), scale(sum(prod(m0[1], m3[0]), prod(-m3[1], m0[0])), m4[2]))), -m1[3])))), sum(sum(scale(sum(scale(sum(prod(m1[1], m4[0]), prod(-m4[1], m1[0])), m0[2]), sum(scale(sum(prod(m0[1], m4[0]), prod(-m4[1], m0[0])), -m1[2]), scale(sum(prod(m0[1], m1[0]), prod(-m1[1], m0[0])), m4[2]))), m3[3]), sum(scale(sum(scale(sum(prod(m1[1], m3[0]), prod(-m3[1], m1[0])), m0[2]), sum(scale(sum(prod(m0[1], m3[0]), prod(-m3[1], m0[0])), -m1[2]), scale(sum(prod(m0[1], m1[0]), prod(-m1[1], m0[0])), m3[2]))), -m4[3]), scale(sum(scale(sum(prod(m2[1], m3[0]), prod(-m3[1], m2[0])), m1[2]), sum(scale(sum(prod(m1[1], m3[0]), prod(-m3[1], m1[0])), -m2[2]), scale(sum(prod(m1[1], m2[0]), prod(-m2[1], m1[0])), m3[2]))), m0[3]))), sum(scale(sum(scale(sum(prod(m2[1], m3[0]), prod(-m3[1], m2[0])), m0[2]), sum(scale(sum(prod(m0[1], m3[0]), prod(-m3[1], m0[0])), -m2[2]), scale(sum(prod(m0[1], m2[0]), prod(-m2[1], m0[0])), m3[2]))), -m1[3]), sum(scale(sum(scale(sum(prod(m1[1], m3[0]), prod(-m3[1], m1[0])), m0[2]), sum(scale(sum(prod(m0[1], m3[0]), prod(-m3[1], m0[0])), -m1[2]), scale(sum(prod(m0[1], m1[0]), prod(-m1[1], m0[0])), m3[2]))), m2[3]), scale(sum(scale(sum(prod(m1[1], m2[0]), prod(-m2[1], m1[0])), m0[2]), sum(scale(sum(prod(m0[1], m2[0]), prod(-m2[1], m0[0])), -m1[2]), scale(sum(prod(m0[1], m1[0]), prod(-m1[1], m0[0])), m2[2]))), -m3[3])))));
        var n = sum(sum(sum(scale(sum(scale(sum(prod(m3[1], m4[0]), prod(-m4[1], m3[0])), m2[2]), sum(scale(sum(prod(m2[1], m4[0]), prod(-m4[1], m2[0])), -m3[2]), scale(sum(prod(m2[1], m3[0]), prod(-m3[1], m2[0])), m4[2]))), m0[3]), scale(sum(scale(sum(prod(m3[1], m4[0]), prod(-m4[1], m3[0])), m0[2]), sum(scale(sum(prod(m0[1], m4[0]), prod(-m4[1], m0[0])), -m3[2]), scale(sum(prod(m0[1], m3[0]), prod(-m3[1], m0[0])), m4[2]))), -m2[3])), sum(scale(sum(scale(sum(prod(m2[1], m4[0]), prod(-m4[1], m2[0])), m0[2]), sum(scale(sum(prod(m0[1], m4[0]), prod(-m4[1], m0[0])), -m2[2]), scale(sum(prod(m0[1], m2[0]), prod(-m2[1], m0[0])), m4[2]))), m3[3]), scale(sum(scale(sum(prod(m2[1], m3[0]), prod(-m3[1], m2[0])), m0[2]), sum(scale(sum(prod(m0[1], m3[0]), prod(-m3[1], m0[0])), -m2[2]), scale(sum(prod(m0[1], m2[0]), prod(-m2[1], m0[0])), m3[2]))), -m4[3]))), sum(sum(scale(sum(scale(sum(prod(m2[1], m4[0]), prod(-m4[1], m2[0])), m1[2]), sum(scale(sum(prod(m1[1], m4[0]), prod(-m4[1], m1[0])), -m2[2]), scale(sum(prod(m1[1], m2[0]), prod(-m2[1], m1[0])), m4[2]))), m0[3]), scale(sum(scale(sum(prod(m2[1], m4[0]), prod(-m4[1], m2[0])), m0[2]), sum(scale(sum(prod(m0[1], m4[0]), prod(-m4[1], m0[0])), -m2[2]), scale(sum(prod(m0[1], m2[0]), prod(-m2[1], m0[0])), m4[2]))), -m1[3])), sum(scale(sum(scale(sum(prod(m1[1], m4[0]), prod(-m4[1], m1[0])), m0[2]), sum(scale(sum(prod(m0[1], m4[0]), prod(-m4[1], m0[0])), -m1[2]), scale(sum(prod(m0[1], m1[0]), prod(-m1[1], m0[0])), m4[2]))), m2[3]), scale(sum(scale(sum(prod(m1[1], m2[0]), prod(-m2[1], m1[0])), m0[2]), sum(scale(sum(prod(m0[1], m2[0]), prod(-m2[1], m0[0])), -m1[2]), scale(sum(prod(m0[1], m1[0]), prod(-m1[1], m0[0])), m2[2]))), -m4[3]))));
        var d = sub(p, n);
        return d[d.length - 1];
      };
    }
    function orientation(n) {
      var fn = n === 3 ? orientation_3 : n === 4 ? orientation_4 : orientation_5;
      return fn(robustSum$1, twoProduct, robustScale$1, robustSubtract);
    }
    var orientation3Exact = orientation(3);
    var orientation4Exact = orientation(4);
    var CACHED = [function orientation0() {
      return 0;
    }, function orientation1() {
      return 0;
    }, function orientation2(a, b) {
      return b[0] - a[0];
    }, function orientation3(a, b, c) {
      var l = (a[1] - c[1]) * (b[0] - c[0]);
      var r = (a[0] - c[0]) * (b[1] - c[1]);
      var det = l - r;
      var s;
      if (l > 0) {
        if (r <= 0) {
          return det;
        } else {
          s = l + r;
        }
      } else if (l < 0) {
        if (r >= 0) {
          return det;
        } else {
          s = -(l + r);
        }
      } else {
        return det;
      }
      var tol = ERRBOUND3 * s;
      if (det >= tol || det <= -tol) {
        return det;
      }
      return orientation3Exact(a, b, c);
    }, function orientation4(a, b, c, d) {
      var adx = a[0] - d[0];
      var bdx = b[0] - d[0];
      var cdx = c[0] - d[0];
      var ady = a[1] - d[1];
      var bdy = b[1] - d[1];
      var cdy = c[1] - d[1];
      var adz = a[2] - d[2];
      var bdz = b[2] - d[2];
      var cdz = c[2] - d[2];
      var bdxcdy = bdx * cdy;
      var cdxbdy = cdx * bdy;
      var cdxady = cdx * ady;
      var adxcdy = adx * cdy;
      var adxbdy = adx * bdy;
      var bdxady = bdx * ady;
      var det = adz * (bdxcdy - cdxbdy) + bdz * (cdxady - adxcdy) + cdz * (adxbdy - bdxady);
      var permanent = (Math.abs(bdxcdy) + Math.abs(cdxbdy)) * Math.abs(adz) + (Math.abs(cdxady) + Math.abs(adxcdy)) * Math.abs(bdz) + (Math.abs(adxbdy) + Math.abs(bdxady)) * Math.abs(cdz);
      var tol = ERRBOUND4 * permanent;
      if (det > tol || -det > tol) {
        return det;
      }
      return orientation4Exact(a, b, c, d);
    }];
    function slowOrient(args) {
      var proc = CACHED[args.length];
      if (!proc) {
        proc = CACHED[args.length] = orientation(args.length);
      }
      return proc.apply(undefined, args);
    }
    function proc(slow, o0, o1, o2, o3, o4, o5) {
      return function getOrientation(a0, a1, a2, a3, a4) {
        switch (arguments.length) {
          case 0:
          case 1:
            return 0;
          case 2:
            return o2(a0, a1);
          case 3:
            return o3(a0, a1, a2);
          case 4:
            return o4(a0, a1, a2, a3);
          case 5:
            return o5(a0, a1, a2, a3, a4);
        }
        var s = new Array(arguments.length);
        for (var i = 0; i < arguments.length; ++i) {
          s[i] = arguments[i];
        }
        return slow(s);
      };
    }
    function generateOrientationProc() {
      while (CACHED.length <= NUM_EXPAND) {
        CACHED.push(orientation(CACHED.length));
      }
      module.exports = proc.apply(undefined, [slowOrient].concat(CACHED));
      for (var i = 0; i <= NUM_EXPAND; ++i) {
        module.exports[i] = CACHED[i];
      }
    }
    generateOrientationProc();
  })(orientation);
  var orientationExports = orientation.exports;

  var robustPnp = robustPointInPolygon;
  var orient = orientationExports;
  function robustPointInPolygon(vs, point) {
    var x = point[0];
    var y = point[1];
    var n = vs.length;
    var inside = 1;
    var lim = n;
    for (var i = 0, j = n - 1; i < lim; j = i++) {
      var a = vs[i];
      var b = vs[j];
      var yi = a[1];
      var yj = b[1];
      if (yj < yi) {
        if (yj < y && y < yi) {
          var s = orient(a, b, point);
          if (s === 0) {
            return 0;
          } else {
            inside ^= 0 < s | 0;
          }
        } else if (y === yi) {
          var c = vs[(i + 1) % n];
          var yk = c[1];
          if (yi < yk) {
            var s = orient(a, b, point);
            if (s === 0) {
              return 0;
            } else {
              inside ^= 0 < s | 0;
            }
          }
        }
      } else if (yi < yj) {
        if (yi < y && y < yj) {
          var s = orient(a, b, point);
          if (s === 0) {
            return 0;
          } else {
            inside ^= s < 0 | 0;
          }
        } else if (y === yi) {
          var c = vs[(i + 1) % n];
          var yk = c[1];
          if (yk < yi) {
            var s = orient(a, b, point);
            if (s === 0) {
              return 0;
            } else {
              inside ^= s < 0 | 0;
            }
          }
        }
      } else if (y === yi) {
        var x0 = Math.min(a[0], b[0]);
        var x1 = Math.max(a[0], b[0]);
        if (i === 0) {
          while (j > 0) {
            var k = (j + n - 1) % n;
            var p = vs[k];
            if (p[1] !== y) {
              break;
            }
            var px = p[0];
            x0 = Math.min(x0, px);
            x1 = Math.max(x1, px);
            j = k;
          }
          if (j === 0) {
            if (x0 <= x && x <= x1) {
              return 0;
            }
            return 1;
          }
          lim = j + 1;
        }
        var y0 = vs[(j + n - 1) % n][1];
        while (i + 1 < lim) {
          var p = vs[i + 1];
          if (p[1] !== y) {
            break;
          }
          var px = p[0];
          x0 = Math.min(x0, px);
          x1 = Math.max(x1, px);
          i += 1;
        }
        if (x0 <= x && x <= x1) {
          return 0;
        }
        var y1 = vs[(i + 1) % n][1];
        if (x < x0 && y0 < y !== y1 < y) {
          inside ^= 1;
        }
      }
    }
    return 2 * inside - 1;
  }
  var robustPointInPolygon$1 = /*@__PURE__*/getDefaultExportFromCjs(robustPnp);

  /**
   * Computes the Feret diameters
   * https://www.sympatec.com/en/particle-measurement/glossary/particle-shape/#
   * http://portal.s2nano.org:8282/files/TEM_protocol_NANoREG.pdf
   * @memberof Image
   * @instance
   * @param {object} [options]
   * @param {Array<Array<number>>} [options.originalPoints]
   * @return {object} Object with {min, max, minLine: {Array<Array<number>>}, maxLine: {Array<Array<number>>}}
   */
  function feretDiameters(options = {}) {
    const {
      originalPoints = monotoneChainConvexHull.call(this)
    } = options;
    if (originalPoints.length === 0) {
      return {
        min: 0,
        max: 0,
        minLine: [],
        maxLine: [],
        aspectRatio: 1
      };
    }
    if (originalPoints.length === 1) {
      return {
        min: 1,
        max: 1,
        minLine: [originalPoints[0], originalPoints[0]],
        maxLine: [originalPoints[0], originalPoints[0]],
        aspectRatio: 1
      };
    }
    const temporaryPoints = new Array(originalPoints.length);

    // CALCULATE MIN VALUE
    let minWidth = +Infinity;
    let minWidthAngle = 0;
    let minLine = [];
    for (let i = 0; i < originalPoints.length; i++) {
      let angle = getAngle(originalPoints[i], originalPoints[(i + 1) % originalPoints.length]);

      // we rotate so that it is parallel to X axis
      rotate(-angle, originalPoints, temporaryPoints);
      let currentWidth = 0;
      let currentMinLine = [];
      for (let j = 0; j < originalPoints.length; j++) {
        let absWidth = Math.abs(temporaryPoints[i][1] - temporaryPoints[j][1]);
        if (absWidth > currentWidth) {
          currentWidth = absWidth;
          currentMinLine = [];
          currentMinLine.push([temporaryPoints[j][0], temporaryPoints[i][1]], [temporaryPoints[j][0], temporaryPoints[j][1]]);
        }
      }
      if (currentWidth < minWidth) {
        minWidth = currentWidth;
        minWidthAngle = angle;
        minLine = currentMinLine;
      }
    }
    rotate(minWidthAngle, minLine, minLine);

    // CALCULATE MAX VALUE
    let maxWidth = 0;
    let maxLine = [];
    let maxSquaredWidth = 0;
    for (let i = 0; i < originalPoints.length - 1; i++) {
      for (let j = i + 1; j < originalPoints.length; j++) {
        let currentSquaredWidth = (originalPoints[i][0] - originalPoints[j][0]) ** 2 + (originalPoints[i][1] - originalPoints[j][1]) ** 2;
        if (currentSquaredWidth > maxSquaredWidth) {
          maxSquaredWidth = currentSquaredWidth;
          maxWidth = Math.sqrt(currentSquaredWidth);
          maxLine = [originalPoints[i], originalPoints[j]];
        }
      }
    }
    return {
      min: minWidth,
      minLine,
      max: maxWidth,
      maxLine,
      aspectRatio: minWidth / maxWidth
    };
  }

  // the angle that allows to make the line going through p1 and p2 horizontal
  // this is an optimized version because it assume one vector is horizontal
  function getAngle(p1, p2) {
    let diff = difference(p2, p1);
    let vector = normalize(diff);
    let angle = Math.acos(vector[0]);
    if (vector[1] < 0) return -angle;
    return angle;
  }

  // Many measurements:
  // https://www.sympatec.com/en/particle-measurement/glossary/particle-shape/#

  /**
   * Class to manage Region Of Interests
   * @class Roi
   */
  class Roi {
    constructor(map, id) {
      this.map = map;
      this.id = id;
      this.minX = Number.POSITIVE_INFINITY;
      this.maxX = Number.NEGATIVE_INFINITY;
      this.minY = Number.POSITIVE_INFINITY;
      this.maxY = Number.NEGATIVE_INFINITY;
      this.meanX = 0;
      this.meanY = 0;
      this.surface = 0;
      this.computed = {};
    }

    /**
     * Returns a binary image (mask) for the corresponding ROI
     * @param {object} [options]
     * @param {number} [options.scale=1] - Scaling factor to apply to the mask
     * @param {string} [options.kind='normal'] - 'contour', 'box', 'filled', 'center', 'hull' or 'normal'
     * @return {Image} - Returns a mask (1 bit Image)
     */
    getMask(options = {}) {
      const {
        scale = 1,
        kind = ''
      } = options;
      let mask;
      switch (kind) {
        case 'contour':
          mask = this.contourMask;
          break;
        case 'box':
          mask = this.boxMask;
          break;
        case 'filled':
          mask = this.filledMask;
          break;
        case 'center':
          mask = this.centerMask;
          break;
        case 'mbr':
          mask = this.mbrFilledMask;
          break;
        case 'hull':
          mask = this.convexHullFilledMask;
          break;
        case 'hullContour':
          mask = this.convexHullMask;
          break;
        case 'mbrContour':
          mask = this.mbrMask;
          break;
        case 'feret':
          mask = this.feretMask;
          break;
        default:
          mask = this.mask;
      }
      if (scale < 1) {
        // by reassigning the mask we loose the parent and therefore the position
        // we will have to force it back
        mask = mask.resize({
          factor: scale
        });
        mask.parent = this.mask.parent;
        mask.position[0] += this.minX;
        mask.position[1] += this.minY;
      }
      return mask;
    }
    get mean() {
      throw new Error('Roi mean not implemented yet');
      // return [this.meanX,this.meanY];
    }
    get center() {
      if (!this.computed.center) {
        this.computed.center = [this.width / 2 >> 0, this.height / 2 >> 0];
      }
      return this.computed.center;
    }
    get ratio() {
      return this.width / this.height;
    }
    get width() {
      return this.maxX - this.minX + 1;
    }
    get height() {
      return this.maxY - this.minY + 1;
    }
    _computExternalIDs() {
      // take all the borders and remove the internal one ...
      let borders = this.borderIDs;
      let lengths = this.borderLengths;
      this.computed.externalIDs = [];
      this.computed.externalLengths = [];
      let internals = this.internalIDs;
      for (let i = 0; i < borders.length; i++) {
        if (!internals.includes(borders[i])) {
          this.computed.externalIDs.push(borders[i]);
          this.computed.externalLengths.push(lengths[i]);
        }
      }
    }
    get externalIDs() {
      if (this.computed.externalIDs) {
        return this.computed.externalIDs;
      }
      this._computExternalIDs();
      return this.computed.externalIDs;
    }
    get externalLengths() {
      if (this.computed.externalLengths) {
        return this.computed.externalLengths;
      }
      this._computExternalIDs();
      return this.computed.externalLengths;
    }
    _computeBorderIDs() {
      let borders = getBorders(this);
      this.computed.borderIDs = borders.ids;
      this.computed.borderLengths = borders.lengths;
    }

    /**
       Retrieve all the IDs (array of number) of the regions that are in contact with this
       specific region. It may be external or internal
       */
    get borderIDs() {
      if (this.computed.borderIDs) {
        return this.computed.borderIDs;
      }
      this._computeBorderIDs();
      return this.computed.borderIDs;
    }

    /**
       Retrieve all the length (array of number) of the contacts with this
       specific region. It may be external or internal
       */
    get borderLengths() {
      if (this.computed.borderLengths) {
        return this.computed.borderLengths;
      }
      this._computeBorderIDs();
      return this.computed.borderLengths;
    }

    /**
       Retrieve all the IDs or the Roi touching the box surrouding the region
        It should really be an array to solve complex cases related to border effect
        Like the image
       <pre>
       0000
       1111
       0000
       1111
       </pre>
        The first row of 1 will be surrouned by 2 differents zones
        Or even worse
       <pre>
       010
       111
       010
       </pre>
       The cross will be surrouned by 4 differents zones
        However in most of the cases it will be an array of one element
       */
    get boxIDs() {
      if (!this.computed.boxIDs) {
        this.computed.boxIDs = getBoxIDs(this);
      }
      return this.computed.boxIDs;
    }
    get internalIDs() {
      if (!this.computed.internalIDs) {
        this.computed.internalIDs = getInternalIDs(this);
      }
      return this.computed.internalIDs;
    }

    /**
       Number of pixels of the Roi that touch the rectangle
       This is useful for the calculation of the border
       because we will ignore those special pixels of the rectangle
       border that don't have neighbours all around them.
       */
    get box() {
      // points of the Roi that touch the rectangular shape
      if (!this.computed.box) {
        this.computed.box = getBox(this);
      }
      return this.computed.box;
    }

    /**
       Calculates the number of pixels that are in the external border of the Roi
       Contour are all the pixels that touch an external "zone".
       All the pixels that touch the box are part of the border and
       are calculated in the getBoxPixels procedure
       */
    get external() {
      if (!this.computed.external) {
        this.computed.external = getExternal(this);
      }
      return this.computed.external;
    }

    /**
       Calculates information about holes
       */
    get holesInfo() {
      if (!this.computed.holesInfo) {
        this.computed.holesInfo = getHolesInfo(this);
      }
      return this.computed.holesInfo;
    }

    /**
       Calculates the number of pixels that are involved in border
       Border are all the pixels that touch another "zone". It could be external
       or internal. If there is a hole in the zone it will be counted as a border.
       All the pixels that touch the box are part of the border and
       are calculated in the getBoxPixels procedure
       */
    get border() {
      if (!this.computed.border) {
        this.computed.border = getBorder(this);
      }
      return this.computed.border;
    }

    /**
      Returns a binary image (mask) containing only the border of the mask
    */
    get contourMask() {
      if (!this.computed.contourMask) {
        let img = new Image(this.width, this.height, {
          kind: BINARY,
          position: [this.minX, this.minY],
          parent: this.map.parent
        });
        for (let x = 0; x < this.width; x++) {
          for (let y = 0; y < this.height; y++) {
            if (this.map.data[x + this.minX + (y + this.minY) * this.map.width] === this.id) {
              // it also has to be on a border ...
              if (x > 0 && x < this.width - 1 && y > 0 && y < this.height - 1) {
                if (this.map.data[x - 1 + this.minX + (y + this.minY) * this.map.width] !== this.id || this.map.data[x + 1 + this.minX + (y + this.minY) * this.map.width] !== this.id || this.map.data[x + this.minX + (y - 1 + this.minY) * this.map.width] !== this.id || this.map.data[x + this.minX + (y + 1 + this.minY) * this.map.width] !== this.id) {
                  img.setBitXY(x, y);
                }
              } else {
                img.setBitXY(x, y);
              }
            }
          }
        }
        this.computed.contourMask = img;
      }
      return this.computed.contourMask;
    }
    get boxMask() {
      if (!this.computed.boxMask) {
        let img = new Image(this.width, this.height, {
          kind: BINARY,
          position: [this.minX, this.minY],
          parent: this.map.parent
        });
        for (let x = 0; x < this.width; x++) {
          img.setBitXY(x, 0);
          img.setBitXY(x, this.height - 1);
        }
        for (let y = 0; y < this.height; y++) {
          img.setBitXY(0, y);
          img.setBitXY(this.width - 1, y);
        }
        this.computed.boxMask = img;
      }
      return this.computed.boxMask;
    }

    /**
       Returns a binary image containing the mask
       */
    get mask() {
      if (!this.computed.mask) {
        let img = new Image(this.width, this.height, {
          kind: BINARY,
          position: [this.minX, this.minY],
          parent: this.map.parent
        });
        for (let x = 0; x < this.width; x++) {
          for (let y = 0; y < this.height; y++) {
            if (this.map.data[x + this.minX + (y + this.minY) * this.map.width] === this.id) {
              img.setBitXY(x, y);
            }
          }
        }
        this.computed.mask = img;
      }
      return this.computed.mask;
    }
    get filledMask() {
      if (!this.computed.filledMask) {
        let img = new Image(this.width, this.height, {
          kind: BINARY,
          position: [this.minX, this.minY],
          parent: this.map.parent
        });
        for (let x = 0; x < this.width; x++) {
          for (let y = 0; y < this.height; y++) {
            let target = x + this.minX + (y + this.minY) * this.map.width;
            if (this.internalIDs.includes(this.map.data[target])) {
              img.setBitXY(x, y);
            } // by default a pixel is to 0 so no problems, it will be transparent
          }
        }
        this.computed.filledMask = img;
      }
      return this.computed.filledMask;
    }
    get centerMask() {
      if (!this.computed.centerMask) {
        let img = new Shape({
          kind: 'smallCross'
        }).getMask();
        img.parent = this.map.parent;
        img.position = [this.minX + this.center[0] - 1, this.minY + this.center[1] - 1];
        this.computed.centerMask = img;
      }
      return this.computed.centerMask;
    }
    get convexHull() {
      if (!this.computed.convexHull) {
        const calculationPoints = [];
        // slow approach, we check all the points
        // for each point we take the 4 corners !!!!

        for (let x = 0; x < this.width; x++) {
          for (let y = 0; y < this.height; y++) {
            if (this.map.data[x + this.minX + (y + this.minY) * this.map.width] === this.id) {
              // it also has to be on a border ...
              if (x > 0 && x < this.width - 1 && y > 0 && y < this.height - 1) {
                if (this.map.data[x - 1 + this.minX + (y + this.minY) * this.map.width] !== this.id || this.map.data[x + 1 + this.minX + (y + this.minY) * this.map.width] !== this.id || this.map.data[x + this.minX + (y - 1 + this.minY) * this.map.width] !== this.id || this.map.data[x + this.minX + (y + 1 + this.minY) * this.map.width] !== this.id) {
                  calculationPoints.push([x, y]);
                  calculationPoints.push([x + 1, y]);
                  calculationPoints.push([x, y + 1]);
                  calculationPoints.push([x + 1, y + 1]);
                }
              } else {
                calculationPoints.push([x, y]);
                calculationPoints.push([x + 1, y]);
                calculationPoints.push([x, y + 1]);
                calculationPoints.push([x + 1, y + 1]);
              }
            }
          }
        }
        const convexHull = monotoneChainConvexHull$1(calculationPoints);
        this.computed.convexHull = {
          polyline: convexHull,
          surface: surface(convexHull),
          perimeter: perimeter(convexHull)
        };
      }
      return this.computed.convexHull;
    }
    get convexHullMask() {
      if (!this.computed.convexHullMask) {
        const convexHull = this.convexHull;
        const img = new Image(this.width + 1, this.height + 1, {
          kind: BINARY,
          position: [this.minX, this.minY],
          parent: this.map.parent
        });
        img.paintPolyline(convexHull.polyline, {
          closed: true
        });
        this.computed.convexHullMask = img;
      }
      return this.computed.convexHullMask;
    }
    get convexHullFilledMask() {
      if (!this.computed.convexHullFilledMask) {
        const convexHull = this.convexHull;
        const img = new Image(this.width, this.height, {
          kind: BINARY,
          position: [this.minX, this.minY],
          parent: this.map.parent
        });
        for (let x = 0; x < this.width; x++) {
          for (let y = 0; y < this.height; y++) {
            if (robustPointInPolygon$1(convexHull.polyline, [x, y]) !== 1) {
              img.setBitXY(x, y);
            }
          }
        }
        this.computed.convexHullFilledMask = img;
      }
      return this.computed.convexHullFilledMask;
    }
    get mbr() {
      if (!this.computed.mbr) {
        let mbr = minimalBoundingRectangle({
          originalPoints: this.convexHull.polyline
        });
        if (mbr.length === 0) {
          this.computed.mbr = {
            width: 0,
            height: 0,
            surface: 0,
            perimeter: 0,
            rectangle: mbr
          };
        } else {
          let first = mbr[0];
          let second = mbr[1];
          let third = mbr[2];
          let width = Math.sqrt((first[0] - second[0]) ** 2 + (first[1] - second[1]) ** 2);
          let height = Math.sqrt((third[0] - second[0]) ** 2 + (third[1] - second[1]) ** 2);
          this.computed.mbr = {
            width,
            height,
            elongation: 1 - width / height,
            aspectRatio: width / height,
            surface: width * height,
            perimeter: (width + height) * 2,
            rectangle: mbr
          };
        }
      }
      return this.computed.mbr;
    }
    get filledSurface() {
      return this.surface + this.holesInfo.surface;
    }
    get fillRatio() {
      return this.surface / (this.surface + this.holesInfo.surface);
    }
    get feretDiameters() {
      if (!this.computed.feretDiameters) {
        this.computed.feretDiameters = feretDiameters({
          originalPoints: this.convexHull.polyline
        });
      }
      return this.computed.feretDiameters;
    }

    /**
     * Diameter of a circle of equal projection area
     */
    get eqpc() {
      if (!this.computed.eqpc) {
        this.computed.eqpc = 2 * Math.sqrt(this.surface / Math.PI);
      }
      return this.computed.eqpc;
    }

    /**
     * Get the category in which each external pixel belongs
     */
    get perimeterInfo() {
      if (!this.computed.perimeterInfo) {
        this.computed.perimeterInfo = getPerimeterInfo(this);
      }
      return this.computed.perimeterInfo;
    }

    /**
     * Return the perimeter of the ROI
     */
    get perimeter() {
      let info = this.perimeterInfo;
      let delta = 2 - Math.sqrt(2);
      return info.one + info.two * 2 + info.three * 3 + info.four * 4 - delta * (info.two + info.three * 2 + info.four);
    }

    /**
     * Diameter of a circle of equal perimeter
     */
    get ped() {
      if (!this.computed.ped) {
        this.computed.ped = this.perimeter / Math.PI;
      }
      return this.computed.ped;
    }
    get feretMask() {
      if (!this.computed.feretMask) {
        const image = new Image(this.width + 1, this.height + 1, {
          kind: BINARY,
          position: [this.minX, this.minY],
          parent: this.map.parent
        });
        image.paintPolyline(this.feretDiameters.minLine);
        image.paintPolyline(this.feretDiameters.maxLine);
        this.computed.feretMask = image;
      }
      return this.computed.feretMask;
    }
    get mbrMask() {
      if (!this.computed.mbrMask) {
        let rectangle = round(this.mbr.rectangle);
        if (rectangle.length > 0) {
          // the problem is that the rectangle may be outside the roi
          const minMax$1 = minMax(rectangle);
          const img = new Image(minMax$1[1][0] - minMax$1[0][0] + 1, minMax$1[1][1] - minMax$1[0][1] + 1, {
            kind: BINARY,
            position: [this.minX + minMax$1[0][0], this.minY + minMax$1[0][1]],
            parent: this.map.parent
          });
          rectangle = moveToZeroZero(rectangle);
          img.paintPolyline(rectangle, {
            closed: true
          });
          this.computed.mbrMask = img;
        } else {
          this.computed.mbrMask = new Image(1, 1, {
            kind: BINARY,
            position: [this.minX, this.minY],
            parent: this.map.parent
          });
        }
      }
      return this.computed.mbrMask;
    }
    get mbrFilledMask() {
      if (!this.computed.mbrFilledMask) {
        const img = new Image(this.width, this.height, {
          kind: BINARY,
          position: [this.minX, this.minY],
          parent: this.map.parent
        });
        const mbr = this.mask.minimalBoundingRectangle();
        for (let x = 0; x < this.width; x++) {
          for (let y = 0; y < this.height; y++) {
            if (robustPointInPolygon$1(mbr, [x, y]) !== 1) {
              img.setBitXY(x, y);
            }
          }
        }
        this.computed.mbrFilledMask = img;
      }
      return this.computed.mbrFilledMask;
    }
    get points() {
      if (!this.computed.points) {
        let points = [];
        for (let y = 0; y < this.height; y++) {
          for (let x = 0; x < this.width; x++) {
            let target = (y + this.minY) * this.map.width + x + this.minX;
            if (this.map.data[target] === this.id) {
              points.push([x, y]);
            }
          }
        }
        this.computed.points = points;
      }
      return this.computed.points;
    }
    get maxLengthPoints() {
      if (!this.computed.maxLengthPoints) {
        let maxLength = 0;
        let maxLengthPoints;
        const points = this.points;
        for (let i = 0; i < points.length; i++) {
          for (let j = i + 1; j < points.length; j++) {
            let currentML = Math.pow(points[i][0] - points[j][0], 2) + Math.pow(points[i][1] - points[j][1], 2);
            if (currentML >= maxLength) {
              maxLength = currentML;
              maxLengthPoints = [points[i], points[j]];
            }
          }
        }
        this.computed.maxLengthPoints = maxLengthPoints;
      }
      return this.computed.maxLengthPoints;
    }

    /**
          Calculates the maximum length between two pixels of the Roi.
       */
    get maxLength() {
      if (!this.computed.maxLength) {
        let maxLength = Math.sqrt(Math.pow(this.maxLengthPoints[0][0] - this.maxLengthPoints[1][0], 2) + Math.pow(this.maxLengthPoints[0][1] - this.maxLengthPoints[1][1], 2));
        this.computed.maxLength = maxLength;
      }
      return this.computed.maxLength;
    }
    get roundness() {
      /*Slide 24 https://static.horiba.com/fileadmin/Horiba/Products/Scientific/Particle_Characterization/Webinars/Slides/TE011.pdf */
      return 4 * this.surface / (Math.PI * this.feretDiameters.max ** 2);
    }
    get sphericity() {
      return 2 * Math.sqrt(this.surface * Math.PI) / this.perimeter;
    }
    get solidity() {
      return this.surface / this.convexHull.surface;
    }
    get angle() {
      if (!this.computed.angle) {
        let points = this.maxLengthPoints;
        let angle = -Math.atan2(points[0][1] - points[1][1], points[0][0] - points[1][0]) * 180 / Math.PI;
        this.computed.angle = angle;
      }
      return this.computed.angle;
    }
    toJSON() {
      return {
        id: this.id,
        minX: this.minX,
        maxX: this.maxX,
        minY: this.minY,
        maxY: this.maxY,
        meanX: this.meanX,
        meanY: this.meanY,
        height: this.height,
        width: this.width,
        filledSurface: this.filledSurface,
        surface: this.surface,
        hullSurface: this.convexHull.surface,
        hullPerimeter: this.convexHull.perimeter,
        mbrWidth: this.mbr.width,
        mbrHeight: this.mbr.height,
        mbrSurface: this.mbr.surface,
        eqpc: this.eqpc,
        ped: this.ped,
        feretDiameterMin: this.feretDiameters.min,
        feretDiameterMax: this.feretDiameters.max,
        aspectRatio: this.feretDiameters.aspectRatio,
        fillRatio: this.fillRatio,
        sphericity: this.sphericity,
        roundness: this.roundness,
        solidity: this.solidity,
        perimeter: this.perimeter
      };
    }
  }

  // TODO we should follow the region in order to increase the speed

  function getBorders(roi) {
    let roiMap = roi.map;
    let data = roiMap.data;
    let surroudingIDs = new Set(); // allows to get a unique list without indexOf
    let surroundingBorders = new Map();
    let visitedData = new Set();
    let dx = [1, 0, -1, 0];
    let dy = [0, 1, 0, -1];
    for (let x = roi.minX; x <= roi.maxX; x++) {
      for (let y = roi.minY; y <= roi.maxY; y++) {
        let target = x + y * roiMap.width;
        if (data[target] === roi.id) {
          for (let dir = 0; dir < 4; dir++) {
            let newX = x + dx[dir];
            let newY = y + dy[dir];
            if (newX >= 0 && newY >= 0 && newX < roiMap.width && newY < roiMap.height) {
              let neighbour = newX + newY * roiMap.width;
              if (data[neighbour] !== roi.id && !visitedData.has(neighbour)) {
                visitedData.add(neighbour);
                surroudingIDs.add(data[neighbour]);
                let surroundingBorder = surroundingBorders.get(data[neighbour]);
                if (!surroundingBorder) {
                  surroundingBorders.set(data[neighbour], 1);
                } else {
                  surroundingBorders.set(data[neighbour], ++surroundingBorder);
                }
              }
            }
          }
        }
      }
    }
    let ids = Array.from(surroudingIDs);
    let borderLengths = ids.map(function (id) {
      return surroundingBorders.get(id);
    });
    return {
      ids: ids,
      lengths: borderLengths
    };
  }
  function getBoxIDs(roi) {
    let surroundingIDs = new Set(); // allows to get a unique list without indexOf

    let roiMap = roi.map;
    let data = roiMap.data;

    // we check the first line and the last line
    for (let y of [0, roi.height - 1]) {
      for (let x = 0; x < roi.width; x++) {
        let target = (y + roi.minY) * roiMap.width + x + roi.minX;
        if (x - roi.minX > 0 && data[target] === roi.id && data[target - 1] !== roi.id) {
          let value = data[target - 1];
          surroundingIDs.add(value);
        }
        if (roiMap.width - x - roi.minX > 1 && data[target] === roi.id && data[target + 1] !== roi.id) {
          let value = data[target + 1];
          surroundingIDs.add(value);
        }
      }
    }

    // we check the first column and the last column
    for (let x of [0, roi.width - 1]) {
      for (let y = 0; y < roi.height; y++) {
        let target = (y + roi.minY) * roiMap.width + x + roi.minX;
        if (y - roi.minY > 0 && data[target] === roi.id && data[target - roiMap.width] !== roi.id) {
          let value = data[target - roiMap.width];
          surroundingIDs.add(value);
        }
        if (roiMap.height - y - roi.minY > 1 && data[target] === roi.id && data[target + roiMap.width] !== roi.id) {
          let value = data[target + roiMap.width];
          surroundingIDs.add(value);
        }
      }
    }
    return Array.from(surroundingIDs); // the selection takes the whole rectangle
  }
  function getBox(roi) {
    let total = 0;
    let roiMap = roi.map;
    let data = roiMap.data;
    let topBottom = [0];
    if (roi.height > 1) {
      topBottom[1] = roi.height - 1;
    }
    for (let y of topBottom) {
      for (let x = 1; x < roi.width - 1; x++) {
        let target = (y + roi.minY) * roiMap.width + x + roi.minX;
        if (data[target] === roi.id) {
          total++;
        }
      }
    }
    let leftRight = [0];
    if (roi.width > 1) {
      leftRight[1] = roi.width - 1;
    }
    for (let x of leftRight) {
      for (let y = 0; y < roi.height; y++) {
        let target = (y + roi.minY) * roiMap.width + x + roi.minX;
        if (data[target] === roi.id) {
          total++;
        }
      }
    }
    return total;
  }
  function getBorder(roi) {
    let total = 0;
    let roiMap = roi.map;
    let data = roiMap.data;
    for (let x = 1; x < roi.width - 1; x++) {
      for (let y = 1; y < roi.height - 1; y++) {
        let target = (y + roi.minY) * roiMap.width + x + roi.minX;
        if (data[target] === roi.id) {
          // if a point around is not roi.id it is a border
          if (data[target - 1] !== roi.id || data[target + 1] !== roi.id || data[target - roiMap.width] !== roi.id || data[target + roiMap.width] !== roi.id) {
            total++;
          }
        }
      }
    }
    return total + roi.box;
  }
  function getPerimeterInfo(roi) {
    let roiMap = roi.map;
    let data = roiMap.data;
    let one = 0;
    let two = 0;
    let three = 0;
    let four = 0;
    for (let x = 0; x < roi.width; x++) {
      for (let y = 0; y < roi.height; y++) {
        let target = (y + roi.minY) * roiMap.width + x + roi.minX;
        if (data[target] === roi.id) {
          let nbAround = 0;
          if (x === 0) {
            nbAround++;
          } else if (roi.externalIDs.includes(data[target - 1])) {
            nbAround++;
          }
          if (x === roi.width - 1) {
            nbAround++;
          } else if (roi.externalIDs.includes(data[target + 1])) {
            nbAround++;
          }
          if (y === 0) {
            nbAround++;
          } else if (roi.externalIDs.includes(data[target - roiMap.width])) {
            nbAround++;
          }
          if (y === roi.height - 1) {
            nbAround++;
          } else if (roi.externalIDs.includes(data[target + roiMap.width])) {
            nbAround++;
          }
          switch (nbAround) {
            case 1:
              one++;
              break;
            case 2:
              two++;
              break;
            case 3:
              three++;
              break;
            case 4:
              four++;
              break;
          }
        }
      }
    }
    return {
      one,
      two,
      three,
      four
    };
  }
  function getExternal(roi) {
    let total = 0;
    let roiMap = roi.map;
    let data = roiMap.data;
    for (let x = 1; x < roi.width - 1; x++) {
      for (let y = 1; y < roi.height - 1; y++) {
        let target = (y + roi.minY) * roiMap.width + x + roi.minX;
        if (data[target] === roi.id) {
          // if a point around is not roi.id it is a border
          if (roi.externalIDs.includes(data[target - 1]) || roi.externalIDs.includes(data[target + 1]) || roi.externalIDs.includes(data[target - roiMap.width]) || roi.externalIDs.includes(data[target + roiMap.width])) {
            total++;
          }
        }
      }
    }
    return total + roi.box;
  }
  function getHolesInfo(roi) {
    let surface = 0;
    let width = roi.map.width;
    let data = roi.map.data;
    for (let x = 1; x < roi.width - 1; x++) {
      for (let y = 1; y < roi.height - 1; y++) {
        let target = (y + roi.minY) * width + x + roi.minX;
        if (roi.internalIDs.includes(data[target]) && data[target] !== roi.id) {
          surface++;
        }
      }
    }
    return {
      number: roi.internalIDs.length - 1,
      surface
    };
  }

  /*
  We will calculate all the ids of the map that are "internal"
  This will allow to extract the 'plain' image
   */
  function getInternalIDs(roi) {
    let internal = [roi.id];
    let roiMap = roi.map;
    let data = roiMap.data;
    if (roi.height > 2) {
      for (let x = 0; x < roi.width; x++) {
        let target = roi.minY * roiMap.width + x + roi.minX;
        if (internal.includes(data[target])) {
          let id = data[target + roiMap.width];
          if (!internal.includes(id) && !roi.boxIDs.includes(id)) {
            internal.push(id);
          }
        }
      }
    }
    let array = new Array(4);
    for (let x = 1; x < roi.width - 1; x++) {
      for (let y = 1; y < roi.height - 1; y++) {
        let target = (y + roi.minY) * roiMap.width + x + roi.minX;
        if (internal.includes(data[target])) {
          // we check if one of the neighbour is not yet in

          array[0] = data[target - 1];
          array[1] = data[target + 1];
          array[2] = data[target - roiMap.width];
          array[3] = data[target + roiMap.width];
          for (let i = 0; i < 4; i++) {
            let id = array[i];
            if (!internal.includes(id) && !roi.boxIDs.includes(id)) {
              internal.push(id);
            }
          }
        }
      }
    }
    return internal;
  }

  /**
   * A layer that is caracterised by a {@link RoiMap} and that will
   * generated automatically the corresponding ROI.
   * ROI should be a continuous
   * surface (it is not tested when it is not continous ...)
   * From the roiMap, the RoiLayer will create the corresponding
   * {@link ROI}.
   *
   * @class RoiLayer
   * @private
   * @param {Image} image
   * @param {object} [options]
   */
  class RoiLayer {
    constructor(roiMap, options) {
      this.roiMap = roiMap;
      this.options = options;
      this.roi = this.createRoi();
    }

    /**
     * Roi are created from a roiMap
     * The roiMap contains mainty an array of identifiers that define
     * for each data to which Roi it belongs
     * @memberof RoiManager
     * @instance
     * @return {Roi[]}
     */
    createRoi() {
      // we need to find all all the different IDs there is in the data
      let data = this.roiMap.data;
      let mapIDs = {};
      this.roiMap.positive = 0;
      this.roiMap.negative = 0;
      for (let i = 0; i < data.length; i++) {
        if (data[i] && !mapIDs[data[i]]) {
          mapIDs[data[i]] = true;
          if (data[i] > 0) {
            this.roiMap.positive++;
          } else {
            this.roiMap.negative++;
          }
        }
      }
      let rois = {};
      for (let mapID in mapIDs) {
        rois[mapID] = new Roi(this.roiMap, mapID * 1);
      }
      let width = this.roiMap.width;
      let height = this.roiMap.height;
      for (let y = 0; y < height; y++) {
        for (let x = 0; x < width; x++) {
          let target = y * width + x;
          if (data[target] !== 0) {
            const mapID = data[target];
            const roi = rois[mapID];
            if (x < roi.minX) {
              roi.minX = x;
            }
            if (x > roi.maxX) {
              roi.maxX = x;
            }
            if (y < roi.minY) {
              roi.minY = y;
            }
            if (y > roi.maxY) {
              roi.maxY = y;
            }
            roi.meanX += x;
            roi.meanY += y;
            roi.surface++;
          }
        }
      }
      let roiArray = [];
      for (let mapID in mapIDs) {
        rois[mapID].meanX /= rois[mapID].surface;
        rois[mapID].meanY /= rois[mapID].surface;
        roiArray.push(rois[mapID]);
      }
      return roiArray;
    }
  }

  // We calculate all the border length with the neighbours

  function commonBorderLength(roiMap) {
    let data = roiMap.data;
    let dx = [1, 0, -1, 0];
    let dy = [0, 1, 0, -1];
    let minMax = roiMap.minMax;
    let shift = -minMax.min;
    let max = minMax.max + shift;
    let borderInfo = [];
    for (let i = 0; i <= max; i++) {
      borderInfo.push(Object.create(null));
    }
    for (let x = 0; x < roiMap.width; x++) {
      for (let y = 0; y < roiMap.height; y++) {
        let target = x + y * roiMap.width;
        let currentRoiID = data[target];
        if (currentRoiID !== 0) {
          // each pixel may only contribute one time to a border
          let used = Object.create(null);
          let isBorder = false;
          for (let dir = 0; dir < 4; dir++) {
            let newX = x + dx[dir];
            let newY = y + dy[dir];
            if (newX >= 0 && newY >= 0 && newX < roiMap.width && newY < roiMap.height) {
              let neighbourRoiID = data[newX + newY * roiMap.width];
              if (currentRoiID !== neighbourRoiID) {
                isBorder = true;
                if (neighbourRoiID !== 0 && used[neighbourRoiID] === undefined) {
                  used[neighbourRoiID] = true;
                  if (!borderInfo[neighbourRoiID + shift][currentRoiID]) {
                    borderInfo[neighbourRoiID + shift][currentRoiID] = 1;
                  } else {
                    borderInfo[neighbourRoiID + shift][currentRoiID]++;
                  }
                }
              }
            } else {
              isBorder = true;
            }
          }
          // we will also add an information to specify the border length
          if (isBorder) {
            if (!borderInfo[currentRoiID + shift][currentRoiID]) {
              borderInfo[currentRoiID + shift][currentRoiID] = 1;
            } else {
              borderInfo[currentRoiID + shift][currentRoiID]++;
            }
          }
        }
      }
    }

    // we convert now the result to an object for fast lookup and we will reshift the result
    let result = {};
    for (let i = 0; i < borderInfo.length; i++) {
      if (Object.keys(borderInfo[i]).length > 0) {
        result[i - shift] = borderInfo[i];
      }
    }
    return result;
  }

  /**
   * In place modification of the roiMap that joins regions of interest
   * @param {object} [options]
   * @param {string|function(object,number,number)} [options.algorithm='commonBorderLength'] algorithm used to decide which ROIs are merged.
   *      Current implemented algorithms are 'commonBorderLength' that use the parameters
   *      'minCommonBorderLength' and 'maxCommonBorderLength' as well as 'commonBorderRatio' that uses
   *      the parameters 'minCommonBorderRatio' and 'maxCommonBorderRatio'.
   * @param {number} [options.minCommonBorderLength=5] minimal common number of pixels for merging
   * @param {number} [options.maxCommonBorderLength=100] maximal common number of pixels for merging
   * @param {number} [options.minCommonBorderRatio=0.3] minimal common border ratio for merging
   * @param {number} [options.maxCommonBorderRatio=1] maximal common border ratio for merging
   * @return {this}
   * @private
   */
  function mergeRoi(options = {}) {
    const {
      algorithm = 'commonBorderLength',
      minCommonBorderLength = 5,
      maxCommonBorderLength = 100,
      minCommonBorderRatio = 0.3,
      maxCommonBorderRatio = 1
    } = options;
    let checkFunction = function (currentInfo, currentID, neighbourID) {
      return currentInfo[neighbourID] >= minCommonBorderLength && currentInfo[neighbourID] <= maxCommonBorderLength;
    };
    if (typeof algorithm === 'function') {
      checkFunction = algorithm;
    }
    if (algorithm.toLowerCase() === 'commonborderratio') {
      checkFunction = function (currentInfo, currentID, neighbourID) {
        let ratio = Math.min(currentInfo[neighbourID] / currentInfo[currentID], 1);
        return ratio >= minCommonBorderRatio && ratio <= maxCommonBorderRatio;
      };
    }
    const roiMap = this;
    const borderLengths = roiMap.commonBorderLength;
    let newMap = {};
    let oldToNew = {};
    for (let currentID of Object.keys(borderLengths)) {
      let currentInfo = borderLengths[currentID];
      let neighbourIDs = Object.keys(currentInfo);
      for (let neighbourID of neighbourIDs) {
        if (neighbourID !== currentID) {
          // it is not myself ...
          if (checkFunction(currentInfo, currentID, neighbourID)) {
            // the common border are in the range. We should merge
            let newNeighbourID = neighbourID;
            if (oldToNew[neighbourID]) newNeighbourID = oldToNew[neighbourID];
            let newCurrentID = currentID;
            if (oldToNew[currentID]) newCurrentID = oldToNew[currentID];
            if (Number(newNeighbourID) !== newCurrentID) {
              let smallerID = Math.min(newNeighbourID, newCurrentID);
              let largerID = Math.max(newNeighbourID, newCurrentID);
              if (!newMap[smallerID]) {
                newMap[smallerID] = {};
              }
              newMap[smallerID][largerID] = true;
              oldToNew[largerID] = smallerID;
              if (newMap[largerID]) {
                // need to put everything to smallerID and remove property
                for (let id of Object.keys(newMap[largerID])) {
                  newMap[smallerID][id] = true;
                  oldToNew[id] = smallerID;
                }
                delete newMap[largerID];
              }
            }
          }
        }
      }
    }
    let minMax = roiMap.minMax;
    let shift = -minMax.min;
    let max = minMax.max + shift;
    let oldToNewArray = new Array(max + 1).fill(0);
    for (let key of Object.keys(oldToNew)) {
      oldToNewArray[Number(key) + shift] = oldToNew[key];
    }
    // time to change the roiMap
    let data = roiMap.data;
    for (let i = 0; i < data.length; i++) {
      let currentValue = data[i];
      if (currentValue !== 0) {
        let newValue = oldToNewArray[currentValue + shift];
        if (newValue !== 0) {
          data[i] = newValue;
        }
      }
    }
    roiMap.computed = {};
    return roiMap;
  }

  /**
   * The roiMap is an array of the size of the original image data that contains
   * positive and negative numbers. When the number is common, it corresponds
   * to one region of interest (ROI)
   *
   * @class RoiMap
   * @private
   */
  class RoiMap {
    constructor(parent, data) {
      this.parent = parent;
      this.width = parent.width;
      this.height = parent.height;
      this.data = data;
      this.negative = 0;
      this.positive = 0;
    }
    get total() {
      return this.negative + this.positive;
    }
    get minMax() {
      let min = Number.MAX_SAFE_INTEGER;
      let max = Number.MIN_SAFE_INTEGER;
      for (let i = 0; i < this.data.length; i++) {
        if (this.data[i] < min) min = this.data[i];
        if (this.data[i] > max) max = this.data[i];
      }
      return {
        min,
        max
      };
    }
    get commonBorderLength() {
      return commonBorderLength(this);
    }
    mergeRoi(options = {}) {
      return mergeRoi.call(this, options);
    }
    mergeRois(rois) {
      const first = rois[0];
      const others = rois.slice(1);
      for (let i = 0; i < this.data.length; i++) {
        if (others.includes(this.data[i])) {
          this.data[i] = first;
        }
      }
    }
    rowsInfo() {
      let rowsInfo = new Array(this.height);
      let currentRow = 0;
      for (let i = 0; i < this.data.length; i += this.width) {
        let info = {
          row: currentRow,
          positivePixel: 0,
          negativePixel: 0,
          zeroPixel: 0,
          positiveRoi: 0,
          negativeRoi: 0,
          medianChange: 0
        };
        rowsInfo[currentRow++] = info;
        let positives = {};
        let negatives = {};
        let changes = [];
        let previous = this.data[i];
        let current = 0;
        for (let j = i; j < i + this.width; j++) {
          let value = this.data[j];
          if (previous !== value) {
            previous = value;
            changes.push(current);
            current = 0;
          }
          current++;
          if (value > 0) {
            info.positivePixel++;
            if (!positives[value]) {
              positives[value] = true;
            }
          } else if (value < 0) {
            info.negativePixel++;
            if (!negatives[value]) {
              negatives[value] = true;
            }
          } else {
            info.zeroPixel++;
          }
        }
        changes.push(current);
        // TODO use median package
        info.medianChange = changes.sort((a, b) => a - b)[Math.floor(changes.length / 2)];
        info.positiveRoiIDs = Object.keys(positives);
        info.negativeRoiIDs = Object.keys(negatives);
        info.positiveRoi = info.positiveRoiIDs.length;
        info.negativeRoi = info.negativeRoiIDs.length;
      }
      return rowsInfo;
    }
    colsInfo() {
      let colsInfo = new Array(this.width);
      let currentCol = 0;
      for (let i = 0; i < this.width; i++) {
        let info = {
          col: currentCol,
          positivePixel: 0,
          negativePixel: 0,
          zeroPixel: 0,
          positiveRoi: 0,
          negativeRoi: 0,
          medianChange: 0
        };
        colsInfo[currentCol++] = info;
        let positives = {};
        let negatives = {};
        let changes = [];
        let previous = this.data[i];
        let current = 0;
        for (let j = i; j < i + this.data.length; j += this.width) {
          let value = this.data[j];
          if (previous !== value) {
            previous = value;
            changes.push(current);
            current = 0;
          }
          current++;
          if (value > 0) {
            info.positivePixel++;
            if (!positives[value]) {
              positives[value] = true;
            }
          } else if (value < 0) {
            info.negativePixel++;
            if (!negatives[value]) {
              negatives[value] = true;
            }
          } else {
            info.zeroPixel++;
          }
        }
        changes.push(current);
        // TODO use median package
        info.medianChange = changes.sort((a, b) => a - b)[Math.floor(changes.length / 2)];
        info.positiveRoiIDs = Object.keys(positives);
        info.negativeRoiIDs = Object.keys(negatives);
        info.positiveRoi = info.positiveRoiIDs.length;
        info.negativeRoi = info.negativeRoiIDs.length;
      }
      return colsInfo;
    }
  }

  /**
   * @memberof RoiManager
   * @instance
   * @param {Image} mask
   * @param {object} [options]
   * @return {RoiMap}
   */
  function fromMask(mask, options = {}) {
    const {
      allowCorners = false
    } = options;
    const MAX_ARRAY = 0x00ffff; // 65535 should be enough for most of the cases

    // based on a binary image we will create plenty of small images
    let data = new Int16Array(mask.size); // maxValue: 32767, minValue: -32768

    // split will always return an array of images
    let positiveID = 0;
    let negativeID = 0;
    let xToProcess = new Uint16Array(MAX_ARRAY + 1); // assign dynamically ????
    let yToProcess = new Uint16Array(MAX_ARRAY + 1); // mask +1 is of course mandatory !!!

    for (let x = 0; x < mask.width; x++) {
      for (let y = 0; y < mask.height; y++) {
        if (data[y * mask.width + x] === 0) {
          // need to process the whole surface
          analyseSurface(x, y);
        }
      }
    }
    function analyseSurface(x, y) {
      let from = 0;
      let to = 0;
      let targetState = mask.getBitXY(x, y);
      let id = targetState ? ++positiveID : --negativeID;
      if (positiveID > 32767 || negativeID < -32768) {
        throw new Error('Too many regions of interest');
      }
      xToProcess[0] = x;
      yToProcess[0] = y;
      while (from <= to) {
        let currentX = xToProcess[from & MAX_ARRAY];
        let currentY = yToProcess[from & MAX_ARRAY];
        data[currentY * mask.width + currentX] = id;
        // need to check all around mask pixel
        if (currentX > 0 && data[currentY * mask.width + currentX - 1] === 0 && mask.getBitXY(currentX - 1, currentY) === targetState) {
          // LEFT
          to++;
          xToProcess[to & MAX_ARRAY] = currentX - 1;
          yToProcess[to & MAX_ARRAY] = currentY;
          data[currentY * mask.width + currentX - 1] = -32768;
        }
        if (currentY > 0 && data[(currentY - 1) * mask.width + currentX] === 0 && mask.getBitXY(currentX, currentY - 1) === targetState) {
          // TOP
          to++;
          xToProcess[to & MAX_ARRAY] = currentX;
          yToProcess[to & MAX_ARRAY] = currentY - 1;
          data[(currentY - 1) * mask.width + currentX] = -32768;
        }
        if (currentX < mask.width - 1 && data[currentY * mask.width + currentX + 1] === 0 && mask.getBitXY(currentX + 1, currentY) === targetState) {
          // RIGHT
          to++;
          xToProcess[to & MAX_ARRAY] = currentX + 1;
          yToProcess[to & MAX_ARRAY] = currentY;
          data[currentY * mask.width + currentX + 1] = -32768;
        }
        if (currentY < mask.height - 1 && data[(currentY + 1) * mask.width + currentX] === 0 && mask.getBitXY(currentX, currentY + 1) === targetState) {
          // BOTTOM
          to++;
          xToProcess[to & MAX_ARRAY] = currentX;
          yToProcess[to & MAX_ARRAY] = currentY + 1;
          data[(currentY + 1) * mask.width + currentX] = -32768;
        }
        if (allowCorners) {
          if (currentX > 0 && currentY > 0 && data[(currentY - 1) * mask.width + currentX - 1] === 0 && mask.getBitXY(currentX - 1, currentY - 1) === targetState) {
            // TOP LEFT
            to++;
            xToProcess[to & MAX_ARRAY] = currentX - 1;
            yToProcess[to & MAX_ARRAY] = currentY - 1;
            data[(currentY - 1) * mask.width + currentX - 1] = -32768;
          }
          if (currentX < mask.width - 1 && currentY > 0 && data[(currentY - 1) * mask.width + currentX + 1] === 0 && mask.getBitXY(currentX + 1, currentY - 1) === targetState) {
            // TOP RIGHT
            to++;
            xToProcess[to & MAX_ARRAY] = currentX + 1;
            yToProcess[to & MAX_ARRAY] = currentY - 1;
            data[(currentY - 1) * mask.width + currentX + 1] = -32768;
          }
          if (currentX > 0 && currentY < mask.height - 1 && data[(currentY + 1) * mask.width + currentX - 1] === 0 && mask.getBitXY(currentX - 1, currentY + 1) === targetState) {
            // BOTTOM LEFT
            to++;
            xToProcess[to & MAX_ARRAY] = currentX - 1;
            yToProcess[to & MAX_ARRAY] = currentY + 1;
            data[(currentY + 1) * mask.width + currentX - 1] = -32768;
          }
          if (currentX < mask.width - 1 && currentY < mask.height - 1 && data[(currentY + 1) * mask.width + currentX + 1] === 0 && mask.getBitXY(currentX + 1, currentY + 1) === targetState) {
            // BOTTOM RIGHT
            to++;
            xToProcess[to & MAX_ARRAY] = currentX + 1;
            yToProcess[to & MAX_ARRAY] = currentY + 1;
            data[(currentY + 1) * mask.width + currentX + 1] = -32768;
          }
        }
        from++;
        if (to - from > MAX_ARRAY) {
          throw new Error('analyseMask can not finish, the array to manage internal data is not big enough.' + 'You could improve mask by changing MAX_ARRAY');
        }
      }
    }
    return new RoiMap(mask, data);
  }

  /**
   * @class DisjointSet
   */
  class DisjointSet {
    constructor() {
      this.nodes = new Map();
    }

    /**
     * Adds an element as a new set
     * @param {*} value
     * @return {DisjointSetNode} Object holding the element
     */
    add(value) {
      var node = this.nodes.get(value);
      if (!node) {
        node = new DisjointSetNode(value);
        this.nodes.set(value, node);
      }
      return node;
    }

    /**
     * Merges the sets that contain x and y
     * @param {DisjointSetNode} x
     * @param {DisjointSetNode} y
     */
    union(x, y) {
      const rootX = this.find(x);
      const rootY = this.find(y);
      if (rootX === rootY) {
        return;
      }
      if (rootX.rank < rootY.rank) {
        rootX.parent = rootY;
      } else if (rootX.rank > rootY.rank) {
        rootY.parent = rootX;
      } else {
        rootY.parent = rootX;
        rootX.rank++;
      }
    }

    /**
     * Finds and returns the root node of the set that contains node
     * @param {DisjointSetNode} node
     * @return {DisjointSetNode}
     */
    find(node) {
      var rootX = node;
      while (rootX.parent !== null) {
        rootX = rootX.parent;
      }
      var toUpdateX = node;
      while (toUpdateX.parent !== null) {
        var toUpdateParent = toUpdateX;
        toUpdateX = toUpdateX.parent;
        toUpdateParent.parent = rootX;
      }
      return rootX;
    }

    /**
     * Returns true if x and y belong to the same set
     * @param {DisjointSetNode} x
     * @param {DisjointSetNode} y
     */
    connected(x, y) {
      return this.find(x) === this.find(y);
    }
  }
  var DisjointSet_1 = DisjointSet;
  function DisjointSetNode(value) {
    this.value = value;
    this.parent = null;
    this.rank = 0;
  }
  var DisjointSet$1 = /*@__PURE__*/getDefaultExportFromCjs(DisjointSet_1);

  /*
  This algorithm is nice and is therefore kept here
  However it seems to be slower than the get mask and
  also provides only the positive ROI
  We therefore don't expose it in the roiManager
   */

  const direction4X = [-1, 0];
  const direction4Y = [0, -1];
  const neighbours4 = [null, null];
  const direction8X = [-1, -1, 0, 1];
  const direction8Y = [0, -1, -1, -1];
  const neighbours8 = [null, null, null, null];

  /*
  Implementation of the connected-component labeling algorithm
   */
  function fromMaskConnectedComponentLabelingAlgorithm(mask, options = {}) {
    const {
      allowCorners = false
    } = options;
    let neighbours = 4;
    if (allowCorners) {
      neighbours = 8;
    }
    let directionX;
    let directionY;
    let neighboursList;
    if (neighbours === 8) {
      directionX = direction8X;
      directionY = direction8Y;
      neighboursList = neighbours8;
    } else if (neighbours === 4) {
      directionX = direction4X;
      directionY = direction4Y;
      neighboursList = neighbours4;
    } else {
      throw new RangeError(`unsupported neighbours count: ${neighbours}`);
    }
    const size = mask.size;
    const width = mask.width;
    const height = mask.height;
    const labels = new Array(size);
    const data = new Uint32Array(size);
    const linked = new DisjointSet$1();
    let currentLabel = 1;
    for (let j = 0; j < height; j++) {
      for (let i = 0; i < width; i++) {
        // true means out of background
        const index = i + j * width;
        if (mask.getBit(index)) {
          let smallestNeighbour = null;
          for (let k = 0; k < neighboursList.length; k++) {
            const ii = i + directionX[k];
            const jj = j + directionY[k];
            if (ii >= 0 && jj >= 0 && ii < width && jj < height) {
              const index = ii + jj * width;
              let neighbour = labels[index];
              if (!neighbour) {
                neighboursList[k] = null;
              } else {
                neighboursList[k] = neighbour;
                if (!smallestNeighbour || neighboursList[k].value < smallestNeighbour.value) {
                  smallestNeighbour = neighboursList[k];
                }
              }
            }
          }
          if (!smallestNeighbour) {
            labels[index] = linked.add(currentLabel++);
          } else {
            labels[index] = smallestNeighbour;
            for (let k = 0; k < neighboursList.length; k++) {
              if (neighboursList[k] && neighboursList[k] !== smallestNeighbour) {
                linked.union(smallestNeighbour, neighboursList[k]);
              }
            }
          }
        }
      }
    }
    for (let j = 0; j < height; j++) {
      for (let i = 0; i < width; i++) {
        const index = i + j * width;
        if (mask.getBit(index)) {
          data[index] = linked.find(labels[index]).value;
        }
      }
    }
    return new RoiMap(mask, data);
  }

  /**
   * @memberof RoiManager
   * @instance
   * @param {object} [options]
   * @param {boolean} [options.allowCorner=true]
   * @param {boolean} [options.onlyTop=false]
   * @param {boolean} [options.invert=false]
   * @return {RoiMap}
   */
  function fromMaxima(options = {}) {
    let {
      allowCorner = true,
      onlyTop = false,
      invert = false
    } = options;
    let image = this;
    image.checkProcessable('fromMaxima', {
      components: [1]
    });
    const PROCESS_TOP = 1;
    const PROCESS_NORMAL = 2;

    // split will always return an array of images
    let positiveID = 0;
    let negativeID = 0;
    let data = new Int16Array(image.size); // maxValue: 32767, minValue: -32768
    let processed = new Int8Array(image.size);
    let variations = new Float32Array(image.size);
    let MAX_ARRAY = 0x0fffff; // should be enough for most of the cases
    let xToProcess = new Uint16Array(MAX_ARRAY + 1); // assign dynamically ????
    let yToProcess = new Uint16Array(MAX_ARRAY + 1); // mask +1 is of course mandatory !!!

    let from = 0;
    let to = 0;
    let xToProcessTop = new Uint16Array(MAX_ARRAY + 1); // assign dynamically ????
    let yToProcessTop = new Uint16Array(MAX_ARRAY + 1); // mask +1 is of course mandatory !!!

    let fromTop = 0;
    let toTop = 0;
    appendMaxima(image);
    while (from < to) {
      let currentX = xToProcess[from & MAX_ARRAY];
      let currentY = yToProcess[from & MAX_ARRAY];
      process(currentX, currentY, PROCESS_NORMAL);
      from++;
    }
    return new RoiMap(image, data);

    // we will look for the maxima (or minima) that is present in the picture
    // a maxima is a point that is surrounded by lower values
    // should deal with allowCorner and invert
    function appendMaxima({
      maxima = true
    }) {
      for (let y = 1; y < image.height - 1; y++) {
        for (let x = 1; x < image.width - 1; x++) {
          let index = x + y * image.width;
          if (processed[index] === 0) {
            let currentValue = maxima ? image.data[index] : -image.data[x + y * image.width];
            if (image.data[y * image.width + x - 1] > currentValue) {
              // LEFT
              continue;
            }
            if (image.data[y * image.width + x + 1] > currentValue) {
              // RIGHT
              continue;
            }
            if (image.data[(y - 1) * image.width + x] > currentValue) {
              // TOP
              continue;
            }
            if (image.data[(y + 1) * image.width + x] > currentValue) {
              // BOTTOM
              continue;
            }
            if (allowCorner) {
              if (image.data[(y - 1) * image.width + x - 1] > currentValue) {
                // LEFT TOP
                continue;
              }
              if (image.data[(y - 1) * image.width + x + 1] > currentValue) {
                // RIGHT TOP
                continue;
              }
              if (image.data[(y + 1) * image.width + x - 1] > currentValue) {
                // LEFT BOTTOM
                continue;
              }
              if (image.data[(y + 1) * image.width + x + 1] > currentValue) {
                // RIGHT BOTTOM
                continue;
              }
            }
            data[index] = maxima ? ++positiveID : --negativeID;
            let valid = processTop(x, y);
            if (!valid) {
              if (maxima) {
                --positiveID;
              } else {
                ++negativeID;
              }
            }
          }
        }
      }
    }

    // we will try to get all the points of the top (same value)
    // and to check if the whole group is surrounded by lower value
    // as soon as one of them if not part we need to reverse the process
    // and just for get those points
    function processTop(xToProcess, yToProcess) {
      let currentTo = to; // in case if fails we come back
      fromTop = 0;
      toTop = 1;
      xToProcessTop[0] = xToProcess;
      yToProcessTop[0] = yToProcess;
      let valid = true;
      while (fromTop < toTop) {
        let currentX = xToProcessTop[fromTop & MAX_ARRAY];
        let currentY = yToProcessTop[fromTop & MAX_ARRAY];
        valid &= process(currentX, currentY, PROCESS_TOP);
        fromTop++;
      }
      if (!valid) {
        // need to clear all the calculated data because the top is not surrounded by negative values
        for (let i = 0; i < toTop; i++) {
          let currentX = xToProcessTop[i & MAX_ARRAY];
          let currentY = yToProcessTop[i & MAX_ARRAY];
          let index = currentY * image.width + currentX;
          data[index] = 0;
        }
        to = currentTo;
      }
      return valid;
    }

    /*
       For a specific point we will check the points around, increase the area of interests and add
       them to the processing list
       type=0 : top
       type=1 : normal
       */
    function process(xCenter, yCenter, type) {
      let currentID = data[yCenter * image.width + xCenter];
      let currentValue = image.data[yCenter * image.width + xCenter];
      for (let y = yCenter - 1; y <= yCenter + 1; y++) {
        for (let x = xCenter - 1; x <= xCenter + 1; x++) {
          let index = y * image.width + x;
          if (processed[index] === 0) {
            processed[index] = 1;
            // we store the variation compare to the parent pixel
            variations[index] = image.data[index] - currentValue;
            switch (type) {
              case PROCESS_TOP:
                if (variations[index] === 0) {
                  // we look for maxima
                  // if we are next to a border ... it is not surrounded !
                  if (x === 0 || y === 0 || x === image.width - 1 || y === image.height - 1) {
                    return false;
                  }
                  data[index] = currentID;
                  xToProcessTop[toTop & MAX_ARRAY] = x;
                  yToProcessTop[toTop & MAX_ARRAY] = y;
                  toTop++;
                } else if (variations[index] > 0) {
                  // not a global maximum
                  return false;
                } else {
                  // a point we will have to process
                  if (!onlyTop) {
                    data[index] = currentID;
                    xToProcess[to & MAX_ARRAY] = x;
                    yToProcess[to & MAX_ARRAY] = y;
                    to++;
                  }
                }
                break;
              case PROCESS_NORMAL:
                if (variations[index] <= 0) {
                  // we look for maxima
                  data[index] = currentID;
                  xToProcess[to & MAX_ARRAY] = x;
                  yToProcess[to & MAX_ARRAY] = y;
                  to++;
                }
                break;
              default:
                throw new Error('unreachable');
            }
          }
        }
      }
      return true;
    }
  }

  /**
   * @memberof RoiManager
   * @instance
   * @param {Array<Array<number>>} pointsToPaint - an array of points
   * @param {object} [options]
   * @return {RoiMap}
   */
  function fromPoints(pointsToPaint, options = {}) {
    let shape = new Shape(options);

    // based on a binary image we will create plenty of small images
    let data = new Int16Array(this.size); // maxValue: 32767, minValue: -32768
    let positiveID = 0;
    let shapePoints = shape.getPoints();
    for (let i = 0; i < pointsToPaint.length; i++) {
      positiveID++;
      let xP = pointsToPaint[i][0];
      let yP = pointsToPaint[i][1];
      for (let j = 0; j < shapePoints.length; j++) {
        let xS = shapePoints[j][0];
        let yS = shapePoints[j][1];
        if (xP + xS >= 0 && yP + yS >= 0 && xP + xS < this.width && yP + yS < this.height) {
          data[xP + xS + (yP + yS) * this.width] = positiveID;
        }
      }
    }
    return new RoiMap(this, data);
  }

  function commonjsRequire(path) {
  	throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
  }

  var priorityQueue = {exports: {}};

  (function (module, exports) {
    (function (f) {
      {
        module.exports = f();
      }
    })(function () {
      return function e(t, n, r) {
        function s(o, u) {
          if (!n[o]) {
            if (!t[o]) {
              var a = typeof commonjsRequire == "function" && commonjsRequire;
              if (!u && a) return a(o, true);
              if (i) return i(o, true);
              var f = new Error("Cannot find module '" + o + "'");
              throw f.code = "MODULE_NOT_FOUND", f;
            }
            var l = n[o] = {
              exports: {}
            };
            t[o][0].call(l.exports, function (e) {
              var n = t[o][1][e];
              return s(n ? n : e);
            }, l, l.exports, e, t, n, r);
          }
          return n[o].exports;
        }
        var i = typeof commonjsRequire == "function" && commonjsRequire;
        for (var o = 0; o < r.length; o++) s(r[o]);
        return s;
      }({
        1: [function (_dereq_, module, exports) {
          var AbstractPriorityQueue,
            ArrayStrategy,
            BHeapStrategy,
            BinaryHeapStrategy,
            PriorityQueue,
            extend = function (child, parent) {
              for (var key in parent) {
                if (hasProp.call(parent, key)) child[key] = parent[key];
              }
              function ctor() {
                this.constructor = child;
              }
              ctor.prototype = parent.prototype;
              child.prototype = new ctor();
              child.__super__ = parent.prototype;
              return child;
            },
            hasProp = {}.hasOwnProperty;
          AbstractPriorityQueue = _dereq_('./PriorityQueue/AbstractPriorityQueue');
          ArrayStrategy = _dereq_('./PriorityQueue/ArrayStrategy');
          BinaryHeapStrategy = _dereq_('./PriorityQueue/BinaryHeapStrategy');
          BHeapStrategy = _dereq_('./PriorityQueue/BHeapStrategy');
          PriorityQueue = function (superClass) {
            extend(PriorityQueue, superClass);
            function PriorityQueue(options) {
              options || (options = {});
              options.strategy || (options.strategy = BinaryHeapStrategy);
              options.comparator || (options.comparator = function (a, b) {
                return (a || 0) - (b || 0);
              });
              PriorityQueue.__super__.constructor.call(this, options);
            }
            return PriorityQueue;
          }(AbstractPriorityQueue);
          PriorityQueue.ArrayStrategy = ArrayStrategy;
          PriorityQueue.BinaryHeapStrategy = BinaryHeapStrategy;
          PriorityQueue.BHeapStrategy = BHeapStrategy;
          module.exports = PriorityQueue;
        }, {
          "./PriorityQueue/AbstractPriorityQueue": 2,
          "./PriorityQueue/ArrayStrategy": 3,
          "./PriorityQueue/BHeapStrategy": 4,
          "./PriorityQueue/BinaryHeapStrategy": 5
        }],
        2: [function (_dereq_, module, exports) {
          module.exports = function () {
            function AbstractPriorityQueue(options) {
              var ref;
              if ((options != null ? options.strategy : void 0) == null) {
                throw 'Must pass options.strategy, a strategy';
              }
              if ((options != null ? options.comparator : void 0) == null) {
                throw 'Must pass options.comparator, a comparator';
              }
              this.priv = new options.strategy(options);
              this.length = (options != null ? (ref = options.initialValues) != null ? ref.length : void 0 : void 0) || 0;
            }
            AbstractPriorityQueue.prototype.queue = function (value) {
              this.length++;
              this.priv.queue(value);
              return void 0;
            };
            AbstractPriorityQueue.prototype.dequeue = function (value) {
              if (!this.length) {
                throw 'Empty queue';
              }
              this.length--;
              return this.priv.dequeue();
            };
            AbstractPriorityQueue.prototype.peek = function (value) {
              if (!this.length) {
                throw 'Empty queue';
              }
              return this.priv.peek();
            };
            AbstractPriorityQueue.prototype.clear = function () {
              this.length = 0;
              return this.priv.clear();
            };
            return AbstractPriorityQueue;
          }();
        }, {}],
        3: [function (_dereq_, module, exports) {
          var binarySearchForIndexReversed;
          binarySearchForIndexReversed = function (array, value, comparator) {
            var high, low, mid;
            low = 0;
            high = array.length;
            while (low < high) {
              mid = low + high >>> 1;
              if (comparator(array[mid], value) >= 0) {
                low = mid + 1;
              } else {
                high = mid;
              }
            }
            return low;
          };
          module.exports = function () {
            function ArrayStrategy(options) {
              var ref;
              this.options = options;
              this.comparator = this.options.comparator;
              this.data = ((ref = this.options.initialValues) != null ? ref.slice(0) : void 0) || [];
              this.data.sort(this.comparator).reverse();
            }
            ArrayStrategy.prototype.queue = function (value) {
              var pos;
              pos = binarySearchForIndexReversed(this.data, value, this.comparator);
              this.data.splice(pos, 0, value);
              return void 0;
            };
            ArrayStrategy.prototype.dequeue = function () {
              return this.data.pop();
            };
            ArrayStrategy.prototype.peek = function () {
              return this.data[this.data.length - 1];
            };
            ArrayStrategy.prototype.clear = function () {
              this.data.length = 0;
              return void 0;
            };
            return ArrayStrategy;
          }();
        }, {}],
        4: [function (_dereq_, module, exports) {
          module.exports = function () {
            function BHeapStrategy(options) {
              var arr, j, k, len, ref, ref1, shift, value;
              this.comparator = (options != null ? options.comparator : void 0) || function (a, b) {
                return a - b;
              };
              this.pageSize = (options != null ? options.pageSize : void 0) || 512;
              this.length = 0;
              shift = 0;
              while (1 << shift < this.pageSize) {
                shift += 1;
              }
              if (1 << shift !== this.pageSize) {
                throw 'pageSize must be a power of two';
              }
              this._shift = shift;
              this._emptyMemoryPageTemplate = arr = [];
              for (j = 0, ref = this.pageSize; 0 <= ref ? j < ref : j > ref; 0 <= ref ? ++j : --j) {
                arr.push(null);
              }
              this._memory = [];
              this._mask = this.pageSize - 1;
              if (options.initialValues) {
                ref1 = options.initialValues;
                for (k = 0, len = ref1.length; k < len; k++) {
                  value = ref1[k];
                  this.queue(value);
                }
              }
            }
            BHeapStrategy.prototype.queue = function (value) {
              this.length += 1;
              this._write(this.length, value);
              this._bubbleUp(this.length, value);
              return void 0;
            };
            BHeapStrategy.prototype.dequeue = function () {
              var ret, val;
              ret = this._read(1);
              val = this._read(this.length);
              this.length -= 1;
              if (this.length > 0) {
                this._write(1, val);
                this._bubbleDown(1, val);
              }
              return ret;
            };
            BHeapStrategy.prototype.peek = function () {
              return this._read(1);
            };
            BHeapStrategy.prototype.clear = function () {
              this.length = 0;
              this._memory.length = 0;
              return void 0;
            };
            BHeapStrategy.prototype._write = function (index, value) {
              var page;
              page = index >> this._shift;
              while (page >= this._memory.length) {
                this._memory.push(this._emptyMemoryPageTemplate.slice(0));
              }
              return this._memory[page][index & this._mask] = value;
            };
            BHeapStrategy.prototype._read = function (index) {
              return this._memory[index >> this._shift][index & this._mask];
            };
            BHeapStrategy.prototype._bubbleUp = function (index, value) {
              var compare, indexInPage, parentIndex, parentValue;
              compare = this.comparator;
              while (index > 1) {
                indexInPage = index & this._mask;
                if (index < this.pageSize || indexInPage > 3) {
                  parentIndex = index & ~this._mask | indexInPage >> 1;
                } else if (indexInPage < 2) {
                  parentIndex = index - this.pageSize >> this._shift;
                  parentIndex += parentIndex & ~(this._mask >> 1);
                  parentIndex |= this.pageSize >> 1;
                } else {
                  parentIndex = index - 2;
                }
                parentValue = this._read(parentIndex);
                if (compare(parentValue, value) < 0) {
                  break;
                }
                this._write(parentIndex, value);
                this._write(index, parentValue);
                index = parentIndex;
              }
              return void 0;
            };
            BHeapStrategy.prototype._bubbleDown = function (index, value) {
              var childIndex1, childIndex2, childValue1, childValue2, compare;
              compare = this.comparator;
              while (index < this.length) {
                if (index > this._mask && !(index & this._mask - 1)) {
                  childIndex1 = childIndex2 = index + 2;
                } else if (index & this.pageSize >> 1) {
                  childIndex1 = (index & ~this._mask) >> 1;
                  childIndex1 |= index & this._mask >> 1;
                  childIndex1 = childIndex1 + 1 << this._shift;
                  childIndex2 = childIndex1 + 1;
                } else {
                  childIndex1 = index + (index & this._mask);
                  childIndex2 = childIndex1 + 1;
                }
                if (childIndex1 !== childIndex2 && childIndex2 <= this.length) {
                  childValue1 = this._read(childIndex1);
                  childValue2 = this._read(childIndex2);
                  if (compare(childValue1, value) < 0 && compare(childValue1, childValue2) <= 0) {
                    this._write(childIndex1, value);
                    this._write(index, childValue1);
                    index = childIndex1;
                  } else if (compare(childValue2, value) < 0) {
                    this._write(childIndex2, value);
                    this._write(index, childValue2);
                    index = childIndex2;
                  } else {
                    break;
                  }
                } else if (childIndex1 <= this.length) {
                  childValue1 = this._read(childIndex1);
                  if (compare(childValue1, value) < 0) {
                    this._write(childIndex1, value);
                    this._write(index, childValue1);
                    index = childIndex1;
                  } else {
                    break;
                  }
                } else {
                  break;
                }
              }
              return void 0;
            };
            return BHeapStrategy;
          }();
        }, {}],
        5: [function (_dereq_, module, exports) {
          module.exports = function () {
            function BinaryHeapStrategy(options) {
              var ref;
              this.comparator = (options != null ? options.comparator : void 0) || function (a, b) {
                return a - b;
              };
              this.length = 0;
              this.data = ((ref = options.initialValues) != null ? ref.slice(0) : void 0) || [];
              this._heapify();
            }
            BinaryHeapStrategy.prototype._heapify = function () {
              var i, j, ref;
              if (this.data.length > 0) {
                for (i = j = 1, ref = this.data.length; 1 <= ref ? j < ref : j > ref; i = 1 <= ref ? ++j : --j) {
                  this._bubbleUp(i);
                }
              }
              return void 0;
            };
            BinaryHeapStrategy.prototype.queue = function (value) {
              this.data.push(value);
              this._bubbleUp(this.data.length - 1);
              return void 0;
            };
            BinaryHeapStrategy.prototype.dequeue = function () {
              var last, ret;
              ret = this.data[0];
              last = this.data.pop();
              if (this.data.length > 0) {
                this.data[0] = last;
                this._bubbleDown(0);
              }
              return ret;
            };
            BinaryHeapStrategy.prototype.peek = function () {
              return this.data[0];
            };
            BinaryHeapStrategy.prototype.clear = function () {
              this.length = 0;
              this.data.length = 0;
              return void 0;
            };
            BinaryHeapStrategy.prototype._bubbleUp = function (pos) {
              var parent, x;
              while (pos > 0) {
                parent = pos - 1 >>> 1;
                if (this.comparator(this.data[pos], this.data[parent]) < 0) {
                  x = this.data[parent];
                  this.data[parent] = this.data[pos];
                  this.data[pos] = x;
                  pos = parent;
                } else {
                  break;
                }
              }
              return void 0;
            };
            BinaryHeapStrategy.prototype._bubbleDown = function (pos) {
              var last, left, minIndex, right, x;
              last = this.data.length - 1;
              while (true) {
                left = (pos << 1) + 1;
                right = left + 1;
                minIndex = pos;
                if (left <= last && this.comparator(this.data[left], this.data[minIndex]) < 0) {
                  minIndex = left;
                }
                if (right <= last && this.comparator(this.data[right], this.data[minIndex]) < 0) {
                  minIndex = right;
                }
                if (minIndex !== pos) {
                  x = this.data[minIndex];
                  this.data[minIndex] = this.data[pos];
                  this.data[pos] = x;
                  pos = minIndex;
                } else {
                  break;
                }
              }
              return void 0;
            };
            return BinaryHeapStrategy;
          }();
        }, {}]
      }, {}, [1])(1);
    });
  })(priorityQueue);
  var priorityQueueExports = priorityQueue.exports;
  var PriorityQueue = /*@__PURE__*/getDefaultExportFromCjs(priorityQueueExports);

  const dxs = [1, 0, -1, 0, 1, 1, -1, -1];
  const dys = [0, 1, 0, -1, 1, -1, 1, -1];

  /**
   * This method allows to create a ROIMap using the water shed algorithm. By default this algorithm
   * will fill the holes and therefore the lowest value of the image (black zones).
   * If no points are given, the function will look for all the minimal points.
   * If no mask is given the algorithm will completely fill the image.
   * Please take care about the value that has be in the mask ! In order to be coherent with the expected mask,
   * meaning that if it is a dark zone, the mask will be dark the normal behaviour to fill a zone
   * is that the mask pixel is clear (value of 0) !
   * However if you work in the 'invert' mode, the mask value has to be 'set' and the method will look for
   * maxima.
   * @memberof RoiManager
   * @instance
   * @param {object} [options={}]
   * @param {Array<Array<number>>} [options.points] - Array of points [[x1,y1], [x2,y2], ...].
   * @param {number} [options.fillMaxValue] - Limit of filling. By example, we can fill to a maximum value 32000 of a 16 bitDepth image.
   *          If invert this will corresponds to the minimal value
   * @param {Image} [options.image=this] - By default the waterShed will be applied on the current image. However waterShed can only be applied
   *                              on 1 component image. This allows to specify a grey scale image on which to apply waterShed..
   * @param {Image} [options.mask] - A binary image, the same size as the image. The algorithm will fill only if the current pixel in the binary mask is true.
   * @param {boolean} [options.invert=false] - By default we fill the minima
   * @return {RoiMap}
   */
  function fromWaterShed(options = {}) {
    let {
      points,
      mask,
      image,
      fillMaxValue = this.maxValue,
      invert = false
    } = options;
    let currentImage = image || this;
    currentImage.checkProcessable('fromWaterShed', {
      bitDepth: [8, 16],
      components: 1
    });

    /*
       We need to invert the logic because we are always using method to look for maxima and not minima and
       here water is expected to fill the minima first ...
      */

    invert = !invert;

    // WaterShed is done from points in the image. We can either specify those points in options,
    // or it is gonna take the minimum locals of the image by default.
    if (!points) {
      points = currentImage.getLocalMaxima({
        invert,
        mask
      });
    }
    let maskExpectedValue = invert ? 0 : 1;
    let data = new Int16Array(currentImage.size);
    let width = currentImage.width;
    let height = currentImage.height;
    let toProcess = new PriorityQueue({
      comparator: (a, b) => a[2] - b[2],
      strategy: PriorityQueue.BinaryHeapStrategy
    });
    for (let i = 0; i < points.length; i++) {
      let index = points[i][0] + points[i][1] * width;
      data[index] = i + 1;
      let intensity = currentImage.data[index];
      if (invert && intensity <= fillMaxValue || !invert && intensity >= fillMaxValue) {
        toProcess.queue([points[i][0], points[i][1], intensity]);
      }
    }

    // Then we iterate through each points
    while (toProcess.length > 0) {
      let currentPoint = toProcess.dequeue();
      let currentValueIndex = currentPoint[0] + currentPoint[1] * width;
      for (let dir = 0; dir < 4; dir++) {
        let newX = currentPoint[0] + dxs[dir];
        let newY = currentPoint[1] + dys[dir];
        if (newX >= 0 && newY >= 0 && newX < width && newY < height) {
          let currentNeighbourIndex = newX + newY * width;
          if (!mask || mask.getBit(currentNeighbourIndex) === maskExpectedValue) {
            let intensity = currentImage.data[currentNeighbourIndex];
            if (invert && intensity <= fillMaxValue || !invert && intensity >= fillMaxValue) {
              if (data[currentNeighbourIndex] === 0) {
                data[currentNeighbourIndex] = data[currentValueIndex];
                toProcess.queue([currentPoint[0] + dxs[dir], currentPoint[1] + dys[dir], intensity]);
              }
            }
          }
        }
      }
    }
    return new RoiMap(currentImage, data);
  }

  /**
   * A manager of Regions of Interest. A RoiManager is related to a specific Image
   * and may contain multiple layers. Each layer is characterized by a label whose is
   * name by default 'default'
   * @class RoiManager
   * @param {Image} image
   * @param {object} [options]
   */
  class RoiManager {
    constructor(image, options = {}) {
      this._image = image;
      this._options = options;
      if (!this._options.label) {
        this._options.label = 'default';
      }
      this._layers = {};
      this._painted = null;
    }

    // docs is in the corresponding file
    fromMaxima(options = {}) {
      let opt = Object.assign({}, this._options, options);
      let roiMap = fromMaxima.call(this._image, options);
      this._layers[opt.label] = new RoiLayer(roiMap, opt);
    }

    // docs is in the corresponding file
    fromPoints(points, options = {}) {
      let opt = Object.assign({}, this._options, options);
      let roiMap = fromPoints.call(this._image, points, options);
      this._layers[opt.label] = new RoiLayer(roiMap, opt);
      return this;
    }

    /**
     * @param {number[]} map
     * @param {object} [options]
     * @return {this}
     */
    putMap(map, options = {}) {
      let roiMap = new RoiMap(this._image, map);
      let opt = Object.assign({}, this._options, options);
      this._layers[opt.label] = new RoiLayer(roiMap, opt);
      return this;
    }

    // docs is in the corresponding file
    fromWaterShed(options = {}) {
      let opt = Object.assign({}, this._options, options);
      let roiMap = fromWaterShed.call(this._image, options);
      this._layers[opt.label] = new RoiLayer(roiMap, opt);
    }

    // docs is in the corresponding file
    fromMask(mask, options = {}) {
      let opt = Object.assign({}, this._options, options);
      let roiMap = fromMask.call(this._image, mask, options);
      this._layers[opt.label] = new RoiLayer(roiMap, opt);
      return this;
    }
    fromMaskConnectedComponentLabelingAlgorithm(mask, options = {}) {
      let opt = Object.assign({}, this._options, options);
      let roiMap = fromMaskConnectedComponentLabelingAlgorithm.call(this._image, mask, options);
      this._layers[opt.label] = new RoiLayer(roiMap, opt);
      return this;
    }

    /**
     *
     * @param {object} [options]
     * @return {RoiMap}
     */
    getMap(options = {}) {
      let opt = Object.assign({}, this._options, options);
      this._assertLayerWithLabel(opt.label);
      return this._layers[opt.label].roiMap;
    }

    /**
     * Return statistics about rows
     * @param {object} [options]
     * @return {object[]}
     */
    rowsInfo(options = {}) {
      return this.getMap(options).rowsInfo();
    }

    /**
     * Return statistics about columns
     * @param {object} [options]
     * @return {object[]}
     */
    colsInfo(options = {}) {
      return this.getMap(options).rowsInfo();
    }

    /**
     * Return the IDs of the Regions Of Interest (Roi) as an array of number
     * @param {object} [options]
     * @return {number[]}
     */
    getRoiIds(options = {}) {
      let rois = this.getRois(options);
      if (rois) {
        let ids = new Array(rois.length);
        for (let i = 0; i < rois.length; i++) {
          ids[i] = rois[i].id;
        }
        return ids;
      }
      throw new Error('ROIs not found');
    }

    /**
     * Allows to select ROI based on size, label and sign.
     * @param {object} [options={}]
     * @param {string} [options.label='default'] Label of the layer containing the ROI
     * @param {boolean} [options.positive=true] Select the positive region of interest
     * @param {boolean} [options.negative=true] Select he negative region of interest
     * @param {number} [options.minSurface=0]
     * @param {number} [options.maxSurface=Number.POSITIVE_INFINITY]
     * @param {number} [options.minWidth=0]
     * @param {number} [options.minHeight=Number.POSITIVE_INFINITY]
     * @param {number} [options.maxWidth=0]
     * @param {number} [options.maxHeight=Number.POSITIVE_INFINITY]
     * @param {number} [options.minRatio=0] Ratio width / height
     * @param {number} [options.maxRatio=Number.POSITIVE_INFINITY]
     * @return {Roi[]}
     */
    getRois(options = {}) {
      let {
        label = this._options.label,
        positive = true,
        negative = true,
        minSurface = 0,
        maxSurface = Number.POSITIVE_INFINITY,
        minWidth = 0,
        maxWidth = Number.POSITIVE_INFINITY,
        minHeight = 0,
        maxHeight = Number.POSITIVE_INFINITY,
        minRatio = 0,
        maxRatio = Number.POSITIVE_INFINITY
      } = options;
      if (!this._layers[label]) {
        throw new Error(`this Roi layer (${label}) does not exist`);
      }
      const allRois = this._layers[label].roi;
      const rois = [];
      for (const roi of allRois) {
        if ((roi.id < 0 && negative || roi.id > 0 && positive) && roi.surface >= minSurface && roi.surface <= maxSurface && roi.width >= minWidth && roi.width <= maxWidth && roi.height >= minHeight && roi.height <= maxHeight && roi.ratio >= minRatio && roi.ratio <= maxRatio) {
          rois.push(roi);
        }
      }
      return rois;
    }

    /**
     * Get an ROI by its id.
     * @param {number} roiId
     * @param {object} [options={}]
     * @param {string} [options.label='default'] Label of the layer containing the ROI
     * @return {Roi}
     */
    getRoi(roiId, options = {}) {
      const {
        label = this._options.label
      } = options;
      if (!this._layers[label]) {
        throw new Error(`this Roi layer (${label}) does not exist`);
      }
      const roi = this._layers[label].roi.find(roi => roi.id === roiId);
      if (!roi) {
        throw new Error(`found no Roi with id ${roiId}`);
      }
      return roi;
    }

    /**
     * Returns an array of masks
     * See {@link Roi.getMask} for the options
     * @param {object} [options]
     * @return {Image[]} Retuns an array of masks (1 bit Image)
     */
    getMasks(options = {}) {
      let rois = this.getRois(options);
      let masks = new Array(rois.length);
      for (let i = 0; i < rois.length; i++) {
        masks[i] = rois[i].getMask(options);
      }
      return masks;
    }

    /**
     * Returns an array of masks
     * See {@link Roi.getAnalysisMasks} for the options
     * @param {object} [options]
     * @return {Image[]} Retuns an array of masks (1 bit Image)
     */
    getAnalysisMasks(options = {}) {
      const {
        analysisProperty
      } = options;
      let maskProperty = `${analysisProperty}Mask`;
      let rois = this.getRois(options);
      if (rois.length === 0 || !rois[0][maskProperty]) return [];
      return rois.map(roi => roi[maskProperty]);
    }

    /**
     *
     * @param {object} [options]
     * @return {number[]}
     */
    getData(options = {}) {
      let opt = Object.assign({}, this._options, options);
      this._assertLayerWithLabel(opt.label);
      return this._layers[opt.label].roiMap.data;
    }

    /**
     * Paint the ROI on a copy of the image and return this image.
     * For painting options {@link Image.paintMasks}
     * For ROI selection options, see {@link RoiManager.getMasks}
     * @param {object} [options] - all the options to select ROIs
     * @param {string} [options.labelProperty] - Paint a mask property on the image.
     *                                  May be any property of the ROI like
     *                                  for example id, surface, width, height, meanX, meanY.
     * @param {number} [options.pixelSize] Size of a pixel in SI
     * @param {string} [options.unit="pixel"] Unit in which to display the values
     * @return {Image} - The painted RGBA 8 bits image
     */
    paint(options = {}) {
      let {
        labelProperty,
        analysisProperty
      } = options;
      if (!this._painted) {
        this._painted = this._image.rgba8();
      }
      let masks = this.getMasks(options);
      if (labelProperty) {
        const rois = this.getRois(options);
        options.labels = rois.map(roi => deepValue(roi, labelProperty));
        const max = Math.max(...options.labels);
        let isSurface = false;
        let isDistance = false;
        if (labelProperty.includes('surface')) {
          isSurface = true;
        } else if (/(?:perimeter|min|max|external|width|height|length)/.test(labelProperty)) {
          isDistance = true;
        }
        if (isFinite(max)) {
          let unitLabel = '';
          if (options.unit !== 'pixel' && options.pixelSize && (isDistance || isSurface)) {
            unitLabel = isSurface ? `${options.unit}^2` : options.unit;
            let siLabel = isSurface ? 'm^2' : 'm';
            let factor = isSurface ? options.pixelSize ** 2 : options.pixelSize;
            const convert = Qty.swiftConverter(siLabel, unitLabel);
            options.labels = options.labels.map(value => {
              return convert(factor * value);
            });
          }
          if (max > 50) {
            options.labels = options.labels.map(number => Math.round(number) + unitLabel);
          } else if (max > 10) {
            options.labels = options.labels.map(number => number.toFixed(1) + unitLabel);
          } else {
            options.labels = options.labels.map(number => number.toFixed(2) + unitLabel);
          }
        }
        options.labelsPosition = rois.map(roi => [roi.meanX, roi.meanY]);
      }
      this._painted.paintMasks(masks, options);
      if (analysisProperty) {
        let analysisMasks = this.getAnalysisMasks(options);
        this._painted.paintMasks(analysisMasks, {
          color: options.analysisColor,
          alpha: options.analysisAlpha
        });
      }
      return this._painted;
    }

    // return a mask corresponding to all the selected masks
    getMask(options = {}) {
      let mask = new Image(this._image.width, this._image.height, {
        kind: 'BINARY'
      });
      let masks = this.getMasks(options);
      for (let i = 0; i < masks.length; i++) {
        let roi = masks[i];
        // we need to find the parent image to calculate the relative position

        for (let x = 0; x < roi.width; x++) {
          for (let y = 0; y < roi.height; y++) {
            if (roi.getBitXY(x, y)) {
              mask.setBitXY(x + roi.position[0], y + roi.position[1]);
            }
          }
        }
      }
      return mask;
    }

    /**
     * Reset the changes to the current painted iamge to the image that was
     * used during the creation of the RoiManager except if a new image is
     * specified as parameter;
     * @param {object} [options]
     * @param {Image} [options.image] A new iamge that you would like to sue for painting over
     */
    resetPainted(options = {}) {
      const {
        image
      } = options;
      if (image) {
        this._painted = this.image.rgba8();
      } else {
        this._painted = this._image.rgba8();
      }
    }

    /**
     * In place modification of the roiMap that joins regions of interest
     * @param {object} [options]
     * @param {string|function(object,number,number)} [options.algorithm='commonBorderLength'] algorithm used to decide which ROIs are merged.
     *      Current implemented algorithms are 'commonBorderLength' that use the parameters
     *      'minCommonBorderLength' and 'maxCommonBorderLength' as well as 'commonBorderRatio' that uses
     *      the parameters 'minCommonBorderRatio' and 'maxCommonBorderRatio'.
     * @param {number} [options.minCommonBorderLength=5] minimal common number of pixels for merging
     * @param {number} [options.maxCommonBorderLength=100] maximal common number of pixels for merging
     * @param {number} [options.minCommonBorderRatio=0.3] minimal common border ratio for merging
     * @param {number} [options.maxCommonBorderRatio=1] maximal common border ratio for merging
     * @return {this}
     */
    mergeRoi(options = {}) {
      const roiMap = this.getMap(options);
      roiMap.mergeRoi(options);
      this.putMap(roiMap.data, options);
      return this;
    }

    /**
     * Merge multiple rois into one.
     * All rois in the provided array will be merged into the first one.
     * @param {Array<number>} roiIds - A list of Roi ids to merge
     * @param {object} [options]
     */
    mergeRois(roiIds, options = {}) {
      if (!Array.isArray(roiIds) || roiIds.some(id => !Number.isInteger(id))) {
        throw new Error('Roi ids must be an array of integers');
      }
      if (roiIds.length < 2) {
        throw new Error('Roi ids must have at least two elements');
      }
      if (new Set(roiIds).size !== roiIds.length) {
        throw new Error('Roi ids must be all different');
      }
      // Throws if one of the ids is wrong
      roiIds.forEach(roiId => this.getRoi(roiId));
      const roiMap = this.getMap(options);
      roiMap.mergeRois(roiIds);
      this.putMap(roiMap.data, options);
      return this;
    }

    /**
     * Finds all corresponding ROIs for all ROIs in the manager
     * @param {number[]} roiMap
     * @param {object} [options]
     * @return {Array} array of objects returned in correspondingRoisInformation
     */
    findCorrespondingRoi(roiMap, options = {}) {
      let allRois = this.getRois(options);
      let allRelated = [];
      for (let i = 0; i < allRois.length; i++) {
        let currentRoi = allRois[i];
        let x = currentRoi.minX;
        let y = currentRoi.minY;
        let allPoints = currentRoi.points;
        let roiSign = Math.sign(currentRoi.id);
        let currentRelated = correspondingRoisInformation(x, y, allPoints, roiMap, roiSign);
        allRelated.push(currentRelated);
      }
      return allRelated;
    }
    _assertLayerWithLabel(label) {
      if (!this._layers[label]) {
        throw new Error(`no layer with label ${label}`);
      }
    }
  }

  /**
   * For a given ROI, find corresponding ROIs and properties in given ROIMap.
   * Returns an object containing the ID of ROIs, the surface shared by given and corresponding ROIs,
   * the percentage of given ROI surface covered by the corresponding ROI, the number of points with same and opposite signs,
   * the total number of points (same and opposite).
   * @param {number} x - minX value of ROI
   * @param {number} y - minY value of ROI
   * @param {Array<Array<number>>} points - points of ROI
   * @param {Array<number>} roiMap - roiMap from which we get the corresponding ROI
   * @param {number} roiSign - sign of ROI
   * @return {object} {{id: Array, surface: Array, roiSurfaceCovered: Array, same: number, opposite: number, total: number}}
   * @private
   */
  function correspondingRoisInformation(x, y, points, roiMap, roiSign) {
    let correspondingRois = {
      id: [],
      surface: [],
      roiSurfaceCovered: [],
      same: 0,
      opposite: 0,
      total: 0
    };
    for (let i = 0; i < points.length; i++) {
      let currentPoint = points[i];
      let currentX = currentPoint[0];
      let currentY = currentPoint[1];
      let correspondingRoiMapIndex = currentX + x + (currentY + y) * roiMap.width;
      let value = roiMap.data[correspondingRoiMapIndex];
      if (value > 0 || value < 0) {
        if (correspondingRois.id.includes(value)) {
          correspondingRois.surface[correspondingRois.id.indexOf(value)] += 1;
        } else {
          correspondingRois.id.push(value);
          correspondingRois.surface.push(1);
        }
      }
    }
    for (let i = 0; i < correspondingRois.id.length; i++) {
      let currentSign = Math.sign(correspondingRois.id[i]);
      if (currentSign === roiSign) {
        correspondingRois.same += correspondingRois.surface[i];
      } else {
        correspondingRois.opposite += correspondingRois.surface[i];
      }
      correspondingRois.roiSurfaceCovered[i] = correspondingRois.surface[i] / points.length;
    }
    correspondingRois.total = correspondingRois.opposite + correspondingRois.same;
    return correspondingRois;
  }

  const objectToString = Object.prototype.toString;

  /**
   * Class representing an image.
   * This class allows to manipulate easily images directly in the browser or in node.
   *
   * This library is designed to deal with scientific images (8 or 16 bit depth) and will be able to open
   * and process jpeg, png and uncompressed tiff images. It is designed to work in the browser
   * as on the server side in node.
   *
   * An image is characterized by:
   * * width and height
   * * colorModel (RGB, HSL, CMYK, GREY, ...)
   * * components: number of components, Grey scale images will have 1 component while RGB will have 3 and CMYK 4.
   * * alpha: 0 or 1 depending if there is an alpha channel. The
   *      alpha channel define the opacity of each pixel
   * * channels: number of channels (components + alpha)
   * * bitDepth : number of bits to define the intensity of a point.
   *      The values may be 1 for a binary image (mask), 8 for a normal image (each
   *      channel contains values between 0 and 255) and 16 for scientific images
   *      (each channel contains values between 0 and 65535).
   *      The png library and tiff library included in image-js allow to deal correctly with
   *      8 and 16 bit depth images.
   * * position : an array of 2 elements that allows to define a relative position
   *      to a parent image. This will be used in a crop or in the management
   *      of Region Of Interests (Roi) for example
   * * data : an array that contains all the points of the image.
   *      Depending the bitDepth Uint8Array (1 bit), Uint8Array (8 bits),
   *      Uint16Array (16 bits), Float32Array (32 bits)
   *
   * In an image there are pixels and points:
   * * A pixel is an array that has as size the number of channels
   * and that contains all the values that define a particular pixel of the image.
   * * A point is an array of 2 elements that contains the x / y coordinate
   * of a specific pixel of the image
   *
   *
   * @class Image
   * @param {number} [width=1]
   * @param {number} [height=1]
   * @param {Array} [data] - Image data to load
   * @param {object} [options]
   *
   *
   * @example
   * // JavaScript code using Node.js to get some info about the image.
   * // We load the library that was installed using 'npm install image-js'
   * const { Image } = require('image-js');
   *
   * // Loading an image is asynchronous and will return a Promise.
   * Image.load('cat.jpg').then(function (image) {
   *   console.log('Width', image.width);
   *   console.log('Height', image.height);
   *   console.log('colorModel', image.colorModel);
   *   console.log('components', image.components);
   *   console.log('alpha', image.alpha);
   *   console.log('channels', image.channels);
   *   console.log('bitDepth', image.bitDepth);
   * });
   *
   * @example
   * // Convert an image to greyscale
   * const { Image } = require('image-js');
   *
   * Image.load('cat.jpg').then(function (image) {
   *   var grey = image.grey();
   *   grey.save('cat-grey.jpg');
   * });
   *
   * @example
   * // Split an RGB image in its components
   * const { Image } = require('image-js');
   *
   * Image.load('cat.jpg').then(function (image) {
   *   var components = image.split();
   *   components[0].save('cat-red.jpg');
   *   components[1].save('cat-green.jpg');
   *   components[2].save('cat-blur.jpg');
   * });
   *
   *
   * @example
   * // For this example you will need the picture of an ecstasy pill that is available on
   * // wget https://raw.githubusercontent.com/image-js/core/854e70f50d63cc73d2dde1d2020fe61ba1b5ec05/test/img/xtc.png // the goal is to isolate the picture and to get a RGB histogram of the pill.
   * // Practically this allows to classify pills based on the histogram similarity
   * // This work was published at: http://dx.doi.org/10.1016/j.forsciint.2012.10.004
   *
   * const { Image } = require('image-js');
   *
   * const image = await Image.load('xtc.png');
   *
   * const grey = image.grey({
   *   algorithm:'lightness'
   * });
   * // we create a mask, which is basically a binary image
   * // a mask has as source a grey image and we will decide how to determine
   * // the threshold to define what is white and what is black
   * var mask = grey.mask({
   *   algorithm: 'li'
   * });
   *
   * // it is possible to create an array of Region Of Interest (Roi) using
   * // the RoiManager. A RoiManager will be applied on the original image
   * // in order to be able to extract from the original image the regions
   *
   * // the result of this console.log result can directly be pasted
   * // in the browser
   * // console.log(mask.toDataURL());
   *
   *
   * var manager = image.getRoiManager();
   * manager.fromMask(mask);
   * var rois = manager.getRoi({
   *   positive: true,
   *   negative: false,
   *   minSurface: 100
   * });
   *
   * // console.log(rois);
   *
   * // we can sort teh rois by surface
   * // for demonstration we use an arrow function
   * rois.sort((a, b) => b.surface - a.surface);
   *
   * // the first Roi (the biggest is expected to be the pill)
   *
   * var pillMask = rois[0].getMask({
   *   scale: 0.7   // we will scale down the mask to take just the center of the pill and avoid border effects
   * });
   *
   * // image-js remembers the parent of the image and the relative
   * // position of a derived image. This is the case for a crop as
   * // well as for Roi
   *
   * var pill = image.extract(pillMask);
   * pill.save('pill.jpg');
   *
   * var histogram = pill.getHistograms({ maxSlots: 16 });
   *
   * console.log(histogram);
   *
   * @example
   * // Example of use of IJS in the browser
   *
   * <script>
   *  var canvas = document.getElementById('myCanvasID');
   *  var image = IJS.fromCanvas(canvas);
   * </script>
   *
   * @example
   * // Image from matrix of values
   * const [min, max] = d3.extent(temperatures)
   * const colorScaler = d3.scaleSequential([min, max], d3.interpolateRdYlBu);
   *
   * // size = rows * columns * channels
   * const data = new Uint8Array(2*3*3);
   * for (let i = 0; i < temperatures.length; i++) {
   *   const {r, g, b} = d3.rgb(colorScaler(temperatures[i]));
   *   data[i*3] = r;
   *   data[i*3 + 1] = g;
   *   data[i*3 + 2] = b;
   * }
   *
   * const image = new Image(2, 3, data, { kind: 'RGB' });
   * // or
   * const image = new Image({ width: 2, height: 3, data, kind: 'RGB'});
   */
  class Image {
    constructor(width, height, data, options) {
      if (arguments.length === 1) {
        options = width;
        ({
          width,
          height,
          data
        } = options);
      } else if (data && !data.length) {
        options = data;
        ({
          data
        } = options);
      }
      if (width === undefined) width = 1;
      if (height === undefined) height = 1;
      if (options === undefined) options = {};
      if (typeof options !== 'object' || options === null) {
        throw new TypeError('options must be an object');
      }
      if (!Number.isInteger(width) || width <= 0) {
        throw new RangeError('width must be a positive integer');
      }
      if (!Number.isInteger(height) || height <= 0) {
        throw new RangeError('height must be a positive integer');
      }
      const {
        kind = RGBA
      } = options;
      if (typeof kind !== 'string') {
        throw new TypeError('kind must be a string');
      }
      const theKind = getKind(kind);
      const kindDefinition = Object.assign({}, options);
      for (const prop in theKind) {
        if (kindDefinition[prop] === undefined) {
          kindDefinition[prop] = theKind[prop];
        }
      }
      verifyKindDefinition(kindDefinition);
      const {
        components,
        bitDepth,
        colorModel
      } = kindDefinition;
      const alpha = kindDefinition.alpha + 0;
      const size = width * height;
      const channels = components + alpha;
      const maxValue = bitDepth === 32 ? Number.MAX_VALUE : 2 ** bitDepth - 1;
      if (data === undefined) {
        data = createPixelArray(size, components, alpha, channels, bitDepth, maxValue);
      } else {
        const expectedLength = getTheoreticalPixelArraySize(size, channels, bitDepth);
        if (data.length !== expectedLength) {
          throw new RangeError(`incorrect data size: ${data.length}. Should be ${expectedLength}`);
        }
      }

      /**
       * Width of the image.
       * @member {number}
       */
      this.width = width;

      /**
       * Height of the image.
       * @member {number}
       */
      this.height = height;

      /**
       * Typed array holding the image data.
       * @member {TypedArray}
       */
      this.data = data;

      /**
       * Total number of pixels (width * height).
       * @member {number}
       */
      this.size = size;

      /**
       * Number of color channels in the image.
       * A grey image has 1 component. An RGB image has 3 components.
       * @member {number}
       */
      this.components = components;

      /**
       * Alpha is 1 if there is an alpha channel, 0 otherwise.
       * @member {number}
       */
      this.alpha = alpha;

      /**
       * Number of bits per value in each channel.
       * @member {number}
       */
      this.bitDepth = bitDepth;

      /**
       * Maximum value that a pixel can have.
       * @member {number}
       */
      this.maxValue = maxValue;

      /**
       * Color model of the image.
       * @member {ColorModel}
       */
      this.colorModel = colorModel;

      /**
       * Total number of channels. Is equal to `image.components + image.alpha`.
       * @member {number}
       */
      this.channels = channels;

      /**
       * Metadata associated with the image.
       * @member {object}
       */
      this.meta = options.meta || {};

      // TODO review those props
      Object.defineProperty(this, 'parent', {
        enumerable: false,
        writable: true,
        configurable: true,
        value: options.parent || null
      });
      this.position = options.position || [0, 0];
      this.computed = null;
      this.sizes = [this.width, this.height];
      this.multiplierX = this.channels;
      this.multiplierY = this.channels * this.width;
      this.isClamped = this.bitDepth < 32;
      this.borderSizes = [0, 0]; // when a filter creates a border, it may have impact on future processing like Roi
    }
    get [Symbol.toStringTag]() {
      return 'IJSImage';
    }
    static isImage(object) {
      return objectToString.call(object) === '[object IJSImage]';
    }

    /**
     * Creates an image from an HTML Canvas object
     * @param {Canvas} canvas
     * @return {Image}
     */
    static fromCanvas(canvas) {
      const ctx = canvas.getContext('2d');
      const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
      return new Image(imageData.width, imageData.height, imageData.data);
    }

    /**
     * Create a new Image based on the characteristics of another one.
     * @param {Image} other
     * @param {object} [options] - Override options to change some parameters
     * @return {Image}
     * @example
     * const newImage = Image.createFrom(image, { width: 100 });
     */
    static createFrom(other, options) {
      const newOptions = getImageParameters(other);
      Object.assign(newOptions, {
        parent: other,
        position: [0, 0]
      }, options);
      return new Image(newOptions);
    }

    /**
     * Create a new manager for regions of interest based on the current image.
     * @param {object} [options]
     * @return {RoiManager}
     */
    getRoiManager(options) {
      return new RoiManager(this, options);
    }

    /**
     * Create a copy a the current image, including its data.
     * @instance
     * @return {Image}
     */
    clone() {
      const newData = this.data.slice();
      return new Image(this.width, this.height, newData, this);
    }
    apply(filter) {
      for (let y = 0; y < this.height; y++) {
        for (let x = 0; x < this.width; x++) {
          let index = (y * this.width + x) * this.channels;
          filter.call(this, index);
        }
      }
    }
  }
  setValueMethods(Image);
  setBitMethods(Image);
  setExportMethods(Image);
  Image.prototype.checkProcessable = checkProcessable;
  Image.prototype.getRGBAData = getRGBAData;
  Image.load = load;
  Image.extendMethod = extendMethod;
  Image.extendProperty = extendProperty;
  extend$1(Image);

  // http://homepages.inf.ed.ac.uk/rbf/HIPR2/log.htm

  function laplacianOfGaussian(sigma, nPoints, factor) {
    let kernel = new Array(nPoints);
    let i, j, x2, y2;
    if (!factor) {
      factor = 100;
    }
    factor *= -1; // -480/(Math.PI*Math.pow(sigma,4));
    let center = (nPoints - 1) / 2;
    let sigma2 = 2 * sigma * sigma;
    for (i = 0; i < nPoints; i++) {
      kernel[i] = new Array(nPoints);
      y2 = (i - center) * (i - center);
      for (j = 0; j < nPoints; j++) {
        x2 = (j - center) * (j - center);
        kernel[i][j] = Math.round(factor * (1 - (x2 + y2) / sigma2) * Math.exp(-(x2 + y2) / sigma2));
      }
    }
    return kernel;
  }

  var kernel = /*#__PURE__*/Object.freeze({
    __proto__: null,
    DISCRETE_LAPLACE_4: DISCRETE_LAPLACE_4,
    DISCRETE_LAPLACE_8: DISCRETE_LAPLACE_8,
    SCHARR_X: SCHARR_X,
    SCHARR_Y: SCHARR_Y,
    SECOND_DERIVATIVE: SECOND_DERIVATIVE,
    SECOND_DERIVATIVE_INV: SECOND_DERIVATIVE_INV,
    SOBEL_X: SOBEL_X,
    SOBEL_Y: SOBEL_Y,
    laplacianOfGaussian: laplacianOfGaussian
  });

  var workerTemplate$1 = {};

  var worker$2 = function () {
    self.window = self;
    function ManagedWorker() {
      this._listeners = {};
    }
    ManagedWorker.prototype.on = function (event, callback) {
      if (this._listeners[event]) throw new RangeError('there is already a listener for ' + event);
      if (typeof callback !== 'function') throw new TypeError('callback argument must be a function');
      this._listeners[event] = callback;
    };
    ManagedWorker.prototype._send = function (id, data, transferable) {
      if (transferable === undefined) {
        transferable = [];
      } else if (!Array.isArray(transferable)) {
        transferable = [transferable];
      }
      self.postMessage({
        id: id,
        data: data
      }, transferable);
    };
    ManagedWorker.prototype._trigger = function (event, args) {
      if (!this._listeners[event]) throw new Error('event ' + event + ' is not defined');
      this._listeners[event].apply(null, args);
    };
    var worker = new ManagedWorker();
    self.onmessage = function (event) {
      switch (event.data.action) {
        case 'exec':
          event.data.args.unshift(function (data, transferable) {
            worker._send(event.data.id, data, transferable);
          });
          worker._trigger(event.data.event, event.data.args);
          break;
        case 'ping':
          worker._send(event.data.id, 'pong');
          break;
        default:
          throw new Error('unexpected action: ' + event.data.action);
      }
    };
  };
  var workerStr = worker$2.toString().split('"CODE";');
  workerTemplate$1.newWorkerURL = function newWorkerURL(code, deps) {
    var blob = new Blob(['(', workerStr[0], 'importScripts.apply(self, ' + JSON.stringify(deps) + ');\n', '(', code, ')();', workerStr[1], ')();'], {
      type: 'application/javascript'
    });
    return URL.createObjectURL(blob);
  };

  var workerTemplate = workerTemplate$1;
  var CORES = navigator.hardwareConcurrency || 1;
  function WorkerManager(func, options) {
    // Check arguments
    if (typeof func !== 'string' && typeof func !== 'function') throw new TypeError('func argument must be a function');
    if (options === undefined) options = {};
    if (typeof options !== 'object' || options === null) throw new TypeError('options argument must be an object');
    this._workerCode = func.toString();

    // Parse options
    if (options.maxWorkers === undefined || options.maxWorkers === 'auto') {
      this._numWorkers = Math.min(CORES - 1, 1);
    } else if (options.maxWorkers > 0) {
      this._numWorkers = Math.min(options.maxWorkers, CORES);
    } else {
      this._numWorkers = CORES;
    }
    this._workers = new Map();
    this._timeout = options.timeout || 0;
    this._terminateOnError = !!options.terminateOnError;
    var deps = options.deps;
    if (typeof deps === 'string') deps = [deps];
    if (!Array.isArray(deps)) deps = undefined;
    this._id = 0;
    this._terminated = false;
    this._working = 0;
    this._waiting = [];
    this._init(deps);
  }
  WorkerManager.prototype._init = function (deps) {
    var workerURL = workerTemplate.newWorkerURL(this._workerCode, deps);
    for (var i = 0; i < this._numWorkers; i++) {
      var worker = new Worker(workerURL);
      worker.onmessage = this._onmessage.bind(this, worker);
      worker.onerror = this._onerror.bind(this, worker);
      worker.running = false;
      worker.id = i;
      this._workers.set(worker, null);
    }
    URL.revokeObjectURL(workerURL);
  };
  WorkerManager.prototype._onerror = function (worker, error) {
    if (this._terminated) return;
    this._working--;
    worker.running = false;
    var callback = this._workers.get(worker);
    if (callback) {
      callback[1](error.message);
    }
    this._workers.set(worker, null);
    if (this._terminateOnError) {
      this.terminate();
    } else {
      this._exec();
    }
  };
  WorkerManager.prototype._onmessage = function (worker, event) {
    if (this._terminated) return;
    this._working--;
    worker.running = false;
    var callback = this._workers.get(worker);
    if (callback) {
      callback[0](event.data.data);
    }
    this._workers.set(worker, null);
    this._exec();
  };
  WorkerManager.prototype._exec = function () {
    for (var worker of this._workers.keys()) {
      if (this._working === this._numWorkers || this._waiting.length === 0) {
        return;
      }
      if (!worker.running) {
        for (var i = 0; i < this._waiting.length; i++) {
          var execInfo = this._waiting[i];
          if (typeof execInfo[4] === 'number' && execInfo[4] !== worker.id) {
            // this message is intended to another worker, let's ignore it
            continue;
          }
          this._waiting.splice(i, 1);
          worker.postMessage({
            action: 'exec',
            event: execInfo[0],
            args: execInfo[1]
          }, execInfo[2]);
          worker.running = true;
          worker.time = Date.now();
          this._workers.set(worker, execInfo[3]);
          this._working++;
          break;
        }
      }
    }
  };
  WorkerManager.prototype.terminate = function () {
    if (this._terminated) return;
    for (var entry of this._workers) {
      entry[0].terminate();
      if (entry[1]) {
        entry[1][1](new Error('Terminated'));
      }
    }
    this._workers.clear();
    this._waiting = [];
    this._working = 0;
    this._terminated = true;
  };
  WorkerManager.prototype.postAll = function (event, args) {
    if (this._terminated) throw new Error('Cannot post (terminated)');
    var promises = [];
    for (var worker of this._workers.keys()) {
      promises.push(this.post(event, args, [], worker.id));
    }
    return Promise.all(promises);
  };
  WorkerManager.prototype.post = function (event, args, transferable, id) {
    if (args === undefined) args = [];
    if (transferable === undefined) transferable = [];
    if (!Array.isArray(args)) {
      args = [args];
    }
    if (!Array.isArray(transferable)) {
      transferable = [transferable];
    }
    var self = this;
    return new Promise(function (resolve, reject) {
      if (self._terminated) throw new Error('Cannot post (terminated)');
      self._waiting.push([event, args, transferable, [resolve, reject], id]);
      self._exec();
    });
  };
  var src = WorkerManager;
  var WorkerManager$1 = /*@__PURE__*/getDefaultExportFromCjs(src);

  const defaultOptions = {
    regression: {
      kernelType: 'polynomial',
      kernelOptions: {
        degree: 2,
        constant: 1
      }
    },
    threshold: 0.02,
    roi: {
      minSurface: 100,
      positive: false
    },
    sampling: 20,
    include: []
  };
  function run(image, options, onStep) {
    options = Object.assign({}, defaultOptions, options);
    const manager = this.manager;
    if (Array.isArray(image)) {
      return Promise.all(image.map(function (img) {
        const run = runOnce(manager, img, options);
        if (typeof onStep === 'function') {
          run.then(onStep);
        }
        return run;
      }));
    } else {
      return runOnce(manager, image, options);
    }
  }
  function runOnce(manager, image, options) {
    return manager.post('data', [image, options]).then(function (response) {
      for (let i in response) {
        response[i] = new Image(response[i]);
      }
      return response;
    });
  }
  function work() {
    worker.on('data', function (send, image, options) {
      image = new IJS(image);
      const result = {};
      const toTransfer = [];
      const grey = image.grey();
      const sobel = grey.sobelFilter();
      maybeInclude('sobel', sobel);
      const mask = sobel.level().mask({
        threshold: options.threshold
      });
      maybeInclude('mask', mask);
      const roiManager = sobel.getRoiManager();
      roiManager.fromMask(mask);
      const realMask = roiManager.getMask(options.roi);
      maybeInclude('realMask', realMask);
      const pixels = grey.getPixelsGrid({
        sampling: options.sampling,
        mask: realMask
      });
      const background = image.getBackground(pixels.xyS, pixels.zS, options.regression);
      maybeInclude('background', background);
      const corrected = image.subtract(background);
      result.result = corrected;
      toTransfer.push(corrected.data.buffer);
      send(result, toTransfer);
      function maybeInclude(name, image) {
        if (options.include.includes(name)) {
          result[name] = image;
          toTransfer.push(image.data.buffer);
        }
      }
    });
  }
  const background = {
    run,
    work
  };

  function extend(Worker) {
    Worker.extendMethod('background', background);
  }

  let Worker$1 = class Worker {
    constructor() {
      this._url = null;
      this._deps = [null];
    }
    checkUrl() {
      if (this._url === null) {
        throw new Error('image worker must be initialized with an URL');
      }
    }
    get url() {
      return this._url;
    }
    set url(value) {
      if (typeof value !== 'string') {
        throw new TypeError('worker URL must be a string');
      }
      this._url = value;
      this._deps[0] = value;
    }
    static extendMethod(name, method) {
      let manager;
      let url;
      let runner = {};
      function run(...args) {
        if (!manager) {
          this.checkUrl();
          url = this.url;
          manager = new WorkerManager$1(method.work, {
            deps: url
          });
          runner.manager = manager;
        }
        return method.run.call(runner, ...args);
      }
      run.reset = function () {
        if (manager) {
          manager.terminate();
          manager = new WorkerManager$1(method.work, {
            deps: url
          });
          runner.manager = manager;
        }
      };
      Worker.prototype[name] = run;
    }
  };
  extend(Worker$1);
  var worker$1 = new Worker$1();

  const Static = {
    grey: names$1,
    threshold: names
  };

  exports.Image = Image;
  exports.Kernel = kernel;
  exports.Shape = Shape;
  exports.Stack = Stack;
  exports.Static = Static;
  exports.Worker = worker$1;
  exports.default = Image;

  Object.defineProperty(exports, '__esModule', { value: true });

}));
//# sourceMappingURL=image-js.js.map
