text: (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.WalletAccounts = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);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 require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  (function (global,Buffer){
  /**
  ethereumjs-accounts - A suite for managing Ethereum accounts in browser.
  
  Welcome to ethereumjs-accounts. Generate, encrypt, manage, export and remove Ethereum accounts and store them in your browsers local storage. You may also choose to extendWeb3 so that transactions made from accounts stored in browser, can be signed with the private key provided. EthereumJs-WalletAccounts also supports account encryption using the AES encryption protocol. You may choose to optionally encrypt your Ethereum account data with a passphrase to prevent others from using or accessing your account.
  
  Requires:
   - cryptojs v0.3.1  <https://github.com/fahad19/crypto-js>
   - localstorejs *  <https://github.com/SilentCicero/localstore>
   - ethereumjs-tx v0.4.0  <https://www.npmjs.com/package/ethereumjs-tx>
   - ethereumjs-tx v1.2.0  <https://www.npmjs.com/package/ethereumjs-util>
   - Underscore.js v1.8.3+  <http://underscorejs.org/>
   - Web3.js v0.4.2+ <https://github.com/ethereum/web3.js>
  
  Commands:
      (Browserify)
      browserify --s WalletAccounts index.js -o dist/ethereumjs-accounts.js
  
      (Run)
      node index.js
  
      (NPM)
      npm install ethereumjs-accounts
  
      (Meteor)
      meteor install silentcicero:ethereumjs-accounts
  **/
  var _ = require('underscore');
  var Tx = require('ethereumjs-tx');
  var LocalStore = require('localstorejs');
  var BigNumber = require('bignumber.js');
  var JSZip = require("jszip");
  var FileSaver = require("node-safe-filesaver");
  global.CryptoJS = require('browserify-cryptojs');
  require('browserify-cryptojs/components/enc-base64');
  require('browserify-cryptojs/components/md5');
  require('browserify-cryptojs/components/evpkdf');
  require('browserify-cryptojs/components/cipher-core');
  require('browserify-cryptojs/components/aes');
  /**
  The WalletAccounts constructor method. This method will construct the in browser Ethereum accounts manager.
  
  @class WalletAccounts
  @constructor
  @method (WalletAccounts)
  @param {Object} options       The accounts object options.
  **/
  var WalletAccounts = module.exports = function(options) {
      if (_.isUndefined(options)) options = {};
      // setup default options
      var defaultOptions = {
          varName: 'ethereumAccounts',
          minPassphraseLength: 6,
          requirePassphrase: false,
          selectNew: true,
          defaultGasPrice: 'useWeb3',
          request: function(accountObject) {
              var passphrase = prompt("Please enter your account passphrase for address " + accountObject.address.substr(0, 8) + '...', "passphrase");
              if (passphrase == null) passphrase = '';
              return String(passphrase);
          }
      };
      // build options
      this.options = _.extend(defaultOptions, options);
      // define WalletAccounts object properties
      defineProperties(this);
      // get accounts object, if any
      var accounts = LocalStore.get(this.options.varName);
      // if no accounts object exists, create one
      if (_.isUndefined(accounts) || !_.isObject(accounts)) LocalStore.set(this.options.varName, {});
  };
  /**
  Pad the given string with a prefix zero, if length is uneven.
  
  @method (formatHex)
  @param {String} str    The string to pad for use as hex
  @return {String} The padded or formatted string for use as a hex string
  **/
  var formatHex = function(str) {
      if (_.isUndefined(str)) str = '00';
      return String(str).length % 2 ? '0' + String(str) : String(str);
  };
  /**
  Prepair numbers for raw transactions.
  
  @method (formatNumber)
  @param {Number|String|BigNumber} The object to be used as a number
  @return {String} The padded, toString hex value of the number
  **/
  var formatNumber = function(num) {
      if (_.isUndefined(num) || num == 0) num = '00';
      if (_.isString(num) || _.isNumber(num)) num = new BigNumber(String(num));
      if (isBigNumber(num)) num = num.toString(16);
      return formatHex(num);
  };
  /**
  Prepair Ethereum address for either raw transactions or browser storage.
  
  @method (formatAddress)
  @param {String} addr    An ethereum address to prep
  @param {String} format          The format type (i.e. 'raw' or 'hex')
  @return {String} The prepaired ethereum address
  **/
  var formatAddress = function(addr, format) {
      if (_.isUndefined(format) || !_.isString(format)) format = 'hex';
      if (_.isUndefined(addr) || !_.isString(addr)) addr = '0000000000000000000000000000000000000000';
      if (addr.substr(0, 2) == '0x' && format == 'raw') addr = addr.substr(2);
      if (addr.substr(0, 2) != '0x' && format == 'hex') addr = '0x' + addr;
      return addr;
  };
  /**
  Generate 16 random alpha numeric bytes.
  
  @method (randomBytes)
  @param {Number} length      The string length that should be generated
  @return {String} A 16 char/UTF-8 byte string of random alpha-numeric characters
  **/
  var randomBytes = function(length) {
          var charset = "abcdef0123456789";
          var i;
          var result = "";
          var isOpera = Object.prototype.toString.call(window.opera) == '[object Opera]';
          if (window.crypto && window.crypto.getRandomValues) {
              values = new Uint32Array(length);
              window.crypto.getRandomValues(values);
              for (i = 0; i < length; i++) {
                  result += charset[values[i] % charset.length];
              }
              return result;
          } else if (isOpera) { //Opera's Math.random is secure, see http://lists.w3.org/Archives/Public/public-webcrypto/2013Jan/0063.html
              for (i = 0; i < length; i++) {
                  result += charset[Math.floor(Math.random() * charset.length)];
              }
              return result;
          } else throw new Error("Your browser sucks and can't generate secure random numbers");
      }
      /**
      Is the object provided a Bignumber object.
  
      @method (isBigNumber)
      **/
  var isBigNumber = function(value) {
      if (_.isUndefined(value) || !_.isObject(value)) return false;
      return (value instanceof BigNumber) ? true : false;
  };
  /**
   * Checks if the given string is an address
   *
   * @method isAddress
   * @param {String} address the given HEX adress
   * @return {Boolean}
   **/
  var isAddress = function(address) {
      return /^(0x)?[0-9a-f]{40}$/.test(address);
  };
  /**
  Define object properties such as 'length'.
  
  @method (defineProperties)
  @param {Object} context     The WalletAccounts object context
  **/
  var defineProperties = function(context) {
      Object.defineProperty(context, 'length', {
          get: function() {
              var count = 0;
              // count valid accounts in browser storage
              _.each(this.get(), function(account, accountIndex) {
                  if (_.isUndefined(account) || !_.isObject(account) || _.isString(account)) return;
                  if (!_.has(account, 'encrypted') || !_.has(account, 'private')) return;
                  count += 1;
              });
              return count;
          }
      });
  };
  /**
  Returns true when a valid passphrase is provided.
  
  @method (isPassphrase)
  @param {String} passphrase    A valid ethereum passphrase
  @return {Boolean} Whether the passphrase is valid or invalid.
  **/
  WalletAccounts.prototype.isPassphrase = function(passphrase) {
      if (!_.isUndefined(passphrase) && _.isString(passphrase) && !_.isEmpty(passphrase) && String(passphrase).length > this.options.minPassphraseLength) return true;
  };
  /**
  This will set in browser accounts data at a specified address with the specified accountObject data.
  
  @method (set)
  @param {String} address          The address of the account
  @param {Object} accountObject    The account object data.
  **/
  WalletAccounts.prototype.set = function(address, accountObject) {
      var accounts = LocalStore.get(this.options.varName);
      // if object, store; if null, delete
      if (_.isObject(accountObject)) accounts[formatAddress(address)] = accountObject;
      else delete accounts[formatAddress(address)];
      this.log('Setting account object at address: ' + address + ' to account object ' + String(accountObject));
      LocalStore.set(this.options.varName, accounts);
  };
  /**
  Remove an account from the Ethereum accounts stored in browser
  
  @method (remove)
  @param {String} address          The address of the account stored in browser
  **/
  WalletAccounts.prototype.remove = function(address) {
      this.set(address, null);
  };
  /**
  Generate a new Ethereum account in browser with a passphrase that will encrypt the public and private keys with AES for storage.
  
  @method (new)
  @param {String} passphrase          The passphrase to encrypt the public and private keys.
  @return {Object} an account object with the public and private keys included.
  **/
  WalletAccounts.prototype.new = function(passphrase) {
      var private = new Buffer(randomBytes(64), 'hex');
      var public = ethUtil.privateToPublic(private);
      var address = formatAddress(ethUtil.publicToAddress(public).toString('hex'));
      var accountObject = {
          address: address,
          encrypted: false,
          locked: false,
          hash: ethUtil.sha3(public.toString('hex') + private.toString('hex')).toString('hex')
      };
      // if passphrrase provided or required, attempt account encryption
      if ((!_.isUndefined(passphrase) && !_.isEmpty(passphrase)) || this.options.requirePassphrase) {
          if (this.isPassphrase(passphrase)) {
              private = CryptoJS.AES.encrypt(private.toString('hex'), passphrase).toString();
              public = CryptoJS.AES.encrypt(public.toString('hex'), passphrase).toString();
              accountObject.encrypted = true;
              accountObject.locked = true;
          } else {
              this.log('The passphrase you tried to use was invalid.');
              private = private.toString('hex')
              public = public.toString('hex')
          }
      } else {
          private = private.toString('hex')
          public = public.toString('hex')
      }
      // Set account object private and public keys
      accountObject.private = private;
      accountObject.public = public;
      this.set(address, accountObject);
      this.log('New address created');
      // If option select new is true
      if (this.options.selectNew) this.select(accountObject.address);
      return accountObject;
  };
  /**
  Select the account that will be used when transactions are made.
  
  @method (select)
  @param {String} address          The address of the account to select
  **/
  WalletAccounts.prototype.select = function(address) {
      var accounts = LocalStore.get(this.options.varName);
      //if(!this.contains(address))
      //    return;
      accounts['selected'] = address;
      LocalStore.set(this.options.varName, accounts);
  };
  /**
  Get an account object that is stored in local browser storage. If encrypted, decrypt it with the passphrase.
  
  @method (new)
  @param {String} passphrase          The passphrase to encrypt the public and private keys.
  @return {Object} an account object with the public and private keys included.
  **/
  WalletAccounts.prototype.get = function(address, passphrase) {
      var accounts = LocalStore.get(this.options.varName);
      if (_.isUndefined(address) || _.isEmpty(address)) return accounts;
      if (address == 'selected') address = accounts.selected;
      address = formatAddress(address);
      var accountObject = {
          address: address
      };
      if (!this.contains(address)) return accountObject;
      accountObject = accounts[address];
      if (_.isEmpty(accountObject)) return accountObject;
      // If a passphrase is provided, decrypt private and public key
      if (this.isPassphrase(passphrase) && accountObject.encrypted) {
          try {
              accountObject.private = CryptoJS.AES.decrypt(accountObject.private, passphrase).toString(CryptoJS.enc.Utf8);
              accountObject.public = CryptoJS.AES.decrypt(accountObject.public, passphrase).toString(CryptoJS.enc.Utf8);
              if (ethUtil.sha3(accountObject.public + accountObject.private).toString('hex') == accountObject.hash) accountObject.locked = false;
          } catch (e) {
              this.log('Error while decrypting public/private keys: ' + String(e));
          }
      }
      return accountObject;
  };
  WalletAccounts.prototype.getAddresses = function() {
      this.log('Retrieving all addresses');
      var accounts = LocalStore.get(this.options.varName),
          return_array = [];
      _.each(_.keys(accounts), function(accountKey, accountIndex) {
          if (accountKey != "selected") return_array.push(accounts[accountKey].address);
      });
      return return_array;
  };
  /**
  Clear all stored Ethereum accounts in browser.
  
  @method (clear)
  **/
  WalletAccounts.prototype.clear = function() {
      this.log('Clearing all accounts');
      LocalStore.set(this.options.varName, {});
  };
  /**
  Does the account exist in browser storage, given the specified account address.
  
  @method (contains)
  @param {String} address          The account address
  @return {Boolean} Does the account exists or not given the specified address
  **/
  WalletAccounts.prototype.contains = function(address) {
      var accounts = LocalStore.get(this.options.varName);
      if (_.isUndefined(address) || _.isEmpty(address)) return false;
      // Add '0x' prefix if not available
      address = formatAddress(address);
      // If account with address exists.
      if (_.has(accounts, address)) return (!_.isUndefined(accounts[address]) && !_.isEmpty(accounts[address]));
      return false;
  };
  /**
  Export the accounts to a JSON ready string.
  
  @method (export)
  @return {String} A JSON ready string
  **/
  WalletAccounts.prototype.export = function() {
      this.log('Exported accounts');
      return JSON.stringify(this.get());
  };
  /**
  Import a JSON ready string. This will import JSON data, parse it, and attempt to use it as accounts data.
  
  @method (import)
  @param {String} A JSON ready string
  @return {String} How many accountObject's were added
  **/
  WalletAccounts.prototype.import = function(JSON_data) {
      var JSON_data = JSON_data.trim();
      var parsed = JSON.parse(JSON_data);
      var count = 0;
      var _this = this;
      _.each(parsed, function(accountObject, accountIndex) {
          if (!_.has(accountObject, 'private') || !_.has(accountObject, 'hash') || !_.has(accountObject, 'address') || !_.has(accountObject, 'encrypted') || !_.has(accountObject, 'locked')) return;
          count += 1;
          _this.set(accountObject.address, accountObject);
      });
      this.log('Imported ' + String(count) + ' accounts');
      return count;
  };
  /**
  Backup your accounts in a zip file.
  
  @method (backup)
  **/
  WalletAccounts.prototype.backup = function() {
      var zip = new JSZip();
      zip.file("wallet", this.export());
      var content = zip.generate({
          type: "blob"
      });
      var dateString = new Date();
      this.log('Saving wallet as: ' + "wallet-" + dateString.toISOString() + ".zip");
      FileSaver.saveAs(content, "wallet-" + dateString.toISOString() + ".zip");
  };
  /**
  A log function that will log all actions that occur with ethereumjs-accounts.
  
  @method (log)
  **/
  WalletAccounts.prototype.log = function() {};
  /**
  Return all accounts as a list array.
  
  @method (list)
  @return {Array} a list array of all accounts
  **/
  WalletAccounts.prototype.list = function() {
      var accounts = LocalStore.get(this.options.varName),
          return_array = [];
      _.each(_.keys(accounts), function(accountKey, accountIndex) {
          if (accountKey != "selected") return_array.push(accounts[accountKey]);
      });
      return return_array;
  };
  /**
  Alias for contains(), but asynchronous.
  
  This method is required to be a part of the transaction_signer specification for
  the HookedWeb3Provider.
  
  @method (hasAddress)
  **/
  WalletAccounts.prototype.hasAddress = function(address, callback) {
          callback(null, this.contains(address));
      }
      /**
      This will sign a transaction based on transaction parameters passed to it.
      If the from address is not registered as an in-browser account, signTransaction
      will respond with an error.
  
      This method is required to be a part of the transaction_signer specification for
      the HookedWeb3Provider.
  
      tx_params should be an object passed directly from web3. All data should be hex
      and start with the prefix "0x". nonce is required.
  
      @method (signTransaction)
      **/
  WalletAccounts.prototype.signTransaction = function(tx_params, callback) {
      // WalletAccounts instance
      var accounts = this;
      // if from is an account is not stored in browser, error because we can't
      // sign the transaction.
      if (!accounts.contains(tx_params.from)) {
          callback(new Error("Cannot sign transaction; from address not found in accounts list."));
      }
      // Get the account of address set in sendTransaction options, from the accounts stored in browser
      var account = accounts.get(tx_params.from);
      // if the account is encrypted, try to decrypt it
      if (account.encrypted) {
          account = accounts.get(tx_params.from, accounts.options.request(account));
      }
      // if account is still locked, quit
      if (account.locked) {
          callback(new Error("Cannot sign transaction. Account locked!"));
          return;
      }
      var rawTx = {
          nonce: formatHex(ethUtil.stripHexPrefix(tx_params.nonce)),
          gasPrice: formatHex(ethUtil.stripHexPrefix(tx_params.gasPrice)),
          gasLimit: formatHex(new BigNumber('3141592').toString(16)),
          value: '00',
          data: ''
      };
      if (tx_params.gasPrice != null) rawTx.gasPrice = formatHex(ethUtil.stripHexPrefix(tx_params.gasPrice));
      if (tx_params.gas != null) rawTx.gasLimit = formatHex(ethUtil.stripHexPrefix(tx_params.gas));
      if (tx_params.to != null) rawTx.to = formatHex(ethUtil.stripHexPrefix(tx_params.to));
      if (tx_params.value != null) rawTx.value = formatHex(ethUtil.stripHexPrefix(tx_params.value));
      if (tx_params.data != null) rawTx.data = formatHex(ethUtil.stripHexPrefix(tx_params.data));
      // convert string private key to a Buffer Object
      var privateKey = new Buffer(account.private, 'hex');
  
      function signTx(err) {
          // init new transaction object, and sign the transaction
          var tx = new Tx(rawTx);
          tx.sign(privateKey);
          // Build a serialized hex version of the Tx
          var serializedTx = '0x' + tx.serialize().toString('hex');
          // fire callback
          callback(err, serializedTx);
      };
      // If the gas price is zero or null, get the gas price async
      if (rawTx.gasPrice == '00') web3.eth.getGasPrice(function(err, result) {
          if (err) return signTx(err);
          else rawTx.gasPrice = formatHex(ethUtil.stripHexPrefix(result));
          signTx(null);
      });
      else signTx(null);
  };
  }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
  },{"bignumber.js":2,"browserify-cryptojs":10,"browserify-cryptojs/components/aes":5,"browserify-cryptojs/components/cipher-core":6,"browserify-cryptojs/components/enc-base64":7,"browserify-cryptojs/components/evpkdf":8,"browserify-cryptojs/components/md5":9,"buffer":88,"ethereumjs-tx":31,"jszip":50,"localstorejs":65,"node-safe-filesaver":66,"underscore":85}],2:[function(require,module,exports){
  /*! bignumber.js v2.3.0 https://github.com/MikeMcl/bignumber.js/LICENCE */
  
  ;(function (globalObj) {
      'use strict';
  
      /*
        bignumber.js v2.3.0
        A JavaScript library for arbitrary-precision arithmetic.
        https://github.com/MikeMcl/bignumber.js
        Copyright (c) 2016 Michael Mclaughlin <M8ch88l@gmail.com>
        MIT Expat Licence
      */
  
  
      var cryptoObj, parseNumeric,
          isNumeric = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
          mathceil = Math.ceil,
          mathfloor = Math.floor,
          notBool = ' not a boolean or binary digit',
          roundingMode = 'rounding mode',
          tooManyDigits = 'number type has more than 15 significant digits',
          ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_',
          BASE = 1e14,
          LOG_BASE = 14,
          MAX_SAFE_INTEGER = 0x1fffffffffffff,         // 2^53 - 1
          // MAX_INT32 = 0x7fffffff,                   // 2^31 - 1
          POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13],
          SQRT_BASE = 1e7,
  
          /*
           * The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and
           * the arguments to toExponential, toFixed, toFormat, and toPrecision, beyond which an
           * exception is thrown (if ERRORS is true).
           */
          MAX = 1E9;                                   // 0 to MAX_INT32
  
      if ( typeof crypto != 'undefined' ) cryptoObj = crypto;
  
  
      /*
       * Create and return a BigNumber constructor.
       */
      function constructorFactory(configObj) {
          var div,
  
              // id tracks the caller function, so its name can be included in error messages.
              id = 0,
              P = BigNumber.prototype,
              ONE = new BigNumber(1),
  
  
              /********************************* EDITABLE DEFAULTS **********************************/
  
  
              /*
               * The default values below must be integers within the inclusive ranges stated.
               * The values can also be changed at run-time using BigNumber.config.
               */
  
              // The maximum number of decimal places for operations involving division.
              DECIMAL_PLACES = 20,                     // 0 to MAX
  
              /*
               * The rounding mode used when rounding to the above decimal places, and when using
               * toExponential, toFixed, toFormat and toPrecision, and round (default value).
               * UP         0 Away from zero.
               * DOWN       1 Towards zero.
               * CEIL       2 Towards +Infinity.
               * FLOOR      3 Towards -Infinity.
               * HALF_UP    4 Towards nearest neighbour. If equidistant, up.
               * HALF_DOWN  5 Towards nearest neighbour. If equidistant, down.
               * HALF_EVEN  6 Towards nearest neighbour. If equidistant, towards even neighbour.
               * HALF_CEIL  7 Towards nearest neighbour. If equidistant, towards +Infinity.
               * HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
               */
              ROUNDING_MODE = 4,                       // 0 to 8
  
              // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]
  
              // The exponent value at and beneath which toString returns exponential notation.
              // Number type: -7
              TO_EXP_NEG = -7,                         // 0 to -MAX
  
              // The exponent value at and above which toString returns exponential notation.
              // Number type: 21
              TO_EXP_POS = 21,                         // 0 to MAX
  
              // RANGE : [MIN_EXP, MAX_EXP]
  
              // The minimum exponent value, beneath which underflow to zero occurs.
              // Number type: -324  (5e-324)
              MIN_EXP = -1e7,                          // -1 to -MAX
  
              // The maximum exponent value, above which overflow to Infinity occurs.
              // Number type:  308  (1.7976931348623157e+308)
              // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.
              MAX_EXP = 1e7,                           // 1 to MAX
  
              // Whether BigNumber Errors are ever thrown.
              ERRORS = true,                           // true or false
  
              // Change to intValidatorNoErrors if ERRORS is false.
              isValidInt = intValidatorWithErrors,     // intValidatorWithErrors/intValidatorNoErrors
  
              // Whether to use cryptographically-secure random number generation, if available.
              CRYPTO = false,                          // true or false
  
              /*
               * The modulo mode used when calculating the modulus: a mod n.
               * The quotient (q = a / n) is calculated according to the corresponding rounding mode.
               * The remainder (r) is calculated as: r = a - n * q.
               *
               * UP        0 The remainder is positive if the dividend is negative, else is negative.
               * DOWN      1 The remainder has the same sign as the dividend.
               *             This modulo mode is commonly known as 'truncated division' and is
               *             equivalent to (a % n) in JavaScript.
               * FLOOR     3 The remainder has the same sign as the divisor (Python %).
               * HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.
               * EUCLID    9 Euclidian division. q = sign(n) * floor(a / abs(n)).
               *             The remainder is always positive.
               *
               * The truncated division, floored division, Euclidian division and IEEE 754 remainder
               * modes are commonly used for the modulus operation.
               * Although the other rounding modes can also be used, they may not give useful results.
               */
              MODULO_MODE = 1,                         // 0 to 9
  
              // The maximum number of significant digits of the result of the toPower operation.
              // If POW_PRECISION is 0, there will be unlimited significant digits.
              POW_PRECISION = 100,                     // 0 to MAX
  
              // The format specification used by the BigNumber.prototype.toFormat method.
              FORMAT = {
                  decimalSeparator: '.',
                  groupSeparator: ',',
                  groupSize: 3,
                  secondaryGroupSize: 0,
                  fractionGroupSeparator: '\xA0',      // non-breaking space
                  fractionGroupSize: 0
              };
  
  
          /******************************************************************************************/
  
  
          // CONSTRUCTOR
  
  
          /*
           * The BigNumber constructor and exported function.
           * Create and return a new instance of a BigNumber object.
           *
           * n {number|string|BigNumber} A numeric value.
           * [b] {number} The base of n. Integer, 2 to 64 inclusive.
           */
          function BigNumber( n, b ) {
              var c, e, i, num, len, str,
                  x = this;
  
              // Enable constructor usage without new.
              if ( !( x instanceof BigNumber ) ) {
  
                  // 'BigNumber() constructor call without new: {n}'
                  if (ERRORS) raise( 26, 'constructor call without new', n );
                  return new BigNumber( n, b );
              }
  
              // 'new BigNumber() base not an integer: {b}'
              // 'new BigNumber() base out of range: {b}'
              if ( b == null || !isValidInt( b, 2, 64, id, 'base' ) ) {
  
                  // Duplicate.
                  if ( n instanceof BigNumber ) {
                      x.s = n.s;
                      x.e = n.e;
                      x.c = ( n = n.c ) ? n.slice() : n;
                      id = 0;
                      return;
                  }
  
                  if ( ( num = typeof n == 'number' ) && n * 0 == 0 ) {
                      x.s = 1 / n < 0 ? ( n = -n, -1 ) : 1;
  
                      // Fast path for integers.
                      if ( n === ~~n ) {
                          for ( e = 0, i = n; i >= 10; i /= 10, e++ );
                          x.e = e;
                          x.c = [n];
                          id = 0;
                          return;
                      }
  
                      str = n + '';
                  } else {
                      if ( !isNumeric.test( str = n + '' ) ) return parseNumeric( x, str, num );
                      x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;
                  }
              } else {
                  b = b | 0;
                  str = n + '';
  
                  // Ensure return value is rounded to DECIMAL_PLACES as with other bases.
                  // Allow exponential notation to be used with base 10 argument.
                  if ( b == 10 ) {
                      x = new BigNumber( n instanceof BigNumber ? n : str );
                      return round( x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE );
                  }
  
                  // Avoid potential interpretation of Infinity and NaN as base 44+ values.
                  // Any number in exponential form will fail due to the [Ee][+-].
                  if ( ( num = typeof n == 'number' ) && n * 0 != 0 ||
                    !( new RegExp( '^-?' + ( c = '[' + ALPHABET.slice( 0, b ) + ']+' ) +
                      '(?:\\.' + c + ')?$',b < 37 ? 'i' : '' ) ).test(str) ) {
                      return parseNumeric( x, str, num, b );
                  }
  
                  if (num) {
                      x.s = 1 / n < 0 ? ( str = str.slice(1), -1 ) : 1;
  
                      if ( ERRORS && str.replace( /^0\.0*|\./, '' ).length > 15 ) {
  
                          // 'new BigNumber() number type has more than 15 significant digits: {n}'
                          raise( id, tooManyDigits, n );
                      }
  
                      // Prevent later check for length on converted number.
                      num = false;
                  } else {
                      x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;
                  }
  
                  str = convertBase( str, 10, b, x.s );
              }
  
              // Decimal point?
              if ( ( e = str.indexOf('.') ) > -1 ) str = str.replace( '.', '' );
  
              // Exponential form?
              if ( ( i = str.search( /e/i ) ) > 0 ) {
  
                  // Determine exponent.
                  if ( e < 0 ) e = i;
                  e += +str.slice( i + 1 );
                  str = str.substring( 0, i );
              } else if ( e < 0 ) {
  
                  // Integer.
                  e = str.length;
              }
  
              // Determine leading zeros.
              for ( i = 0; str.charCodeAt(i) === 48; i++ );
  
              // Determine trailing zeros.
              for ( len = str.length; str.charCodeAt(--len) === 48; );
              str = str.slice( i, len + 1 );
  
              if (str) {
                  len = str.length;
  
                  // Disallow numbers with over 15 significant digits if number type.
                  // 'new BigNumber() number type has more than 15 significant digits: {n}'
                  if ( num && ERRORS && len > 15 && ( n > MAX_SAFE_INTEGER || n !== mathfloor(n) ) ) {
                      raise( id, tooManyDigits, x.s * n );
                  }
  
                  e = e - i - 1;
  
                   // Overflow?
                  if ( e > MAX_EXP ) {
  
                      // Infinity.
                      x.c = x.e = null;
  
                  // Underflow?
                  } else if ( e < MIN_EXP ) {
  
                      // Zero.
                      x.c = [ x.e = 0 ];
                  } else {
                      x.e = e;
                      x.c = [];
  
                      // Transform base
  
                      // e is the base 10 exponent.
                      // i is where to slice str to get the first element of the coefficient array.
                      i = ( e + 1 ) % LOG_BASE;
                      if ( e < 0 ) i += LOG_BASE;
  
                      if ( i < len ) {
                          if (i) x.c.push( +str.slice( 0, i ) );
  
                          for ( len -= LOG_BASE; i < len; ) {
                              x.c.push( +str.slice( i, i += LOG_BASE ) );
                          }
  
                          str = str.slice(i);
                          i = LOG_BASE - str.length;
                      } else {
                          i -= len;
                      }
  
                      for ( ; i--; str += '0' );
                      x.c.push( +str );
                  }
              } else {
  
                  // Zero.
                  x.c = [ x.e = 0 ];
              }
  
              id = 0;
          }
  
  
          // CONSTRUCTOR PROPERTIES
  
  
          BigNumber.another = constructorFactory;
  
          BigNumber.ROUND_UP = 0;
          BigNumber.ROUND_DOWN = 1;
          BigNumber.ROUND_CEIL = 2;
          BigNumber.ROUND_FLOOR = 3;
          BigNumber.ROUND_HALF_UP = 4;
          BigNumber.ROUND_HALF_DOWN = 5;
          BigNumber.ROUND_HALF_EVEN = 6;
          BigNumber.ROUND_HALF_CEIL = 7;
          BigNumber.ROUND_HALF_FLOOR = 8;
          BigNumber.EUCLID = 9;
  
  
          /*
           * Configure infrequently-changing library-wide settings.
           *
           * Accept an object or an argument list, with one or many of the following properties or
           * parameters respectively:
           *
           *   DECIMAL_PLACES  {number}  Integer, 0 to MAX inclusive
           *   ROUNDING_MODE   {number}  Integer, 0 to 8 inclusive
           *   EXPONENTIAL_AT  {number|number[]}  Integer, -MAX to MAX inclusive or
           *                                      [integer -MAX to 0 incl., 0 to MAX incl.]
           *   RANGE           {number|number[]}  Non-zero integer, -MAX to MAX inclusive or
           *                                      [integer -MAX to -1 incl., integer 1 to MAX incl.]
           *   ERRORS          {boolean|number}   true, false, 1 or 0
           *   CRYPTO          {boolean|number}   true, false, 1 or 0
           *   MODULO_MODE     {number}           0 to 9 inclusive
           *   POW_PRECISION   {number}           0 to MAX inclusive
           *   FORMAT          {object}           See BigNumber.prototype.toFormat
           *      decimalSeparator       {string}
           *      groupSeparator         {string}
           *      groupSize              {number}
           *      secondaryGroupSize     {number}
           *      fractionGroupSeparator {string}
           *      fractionGroupSize      {number}
           *
           * (The values assigned to the above FORMAT object properties are not checked for validity.)
           *
           * E.g.
           * BigNumber.config(20, 4) is equivalent to
           * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })
           *
           * Ignore properties/parameters set to null or undefined.
           * Return an object with the properties current values.
           */
          BigNumber.config = function () {
              var v, p,
                  i = 0,
                  r = {},
                  a = arguments,
                  o = a[0],
                  has = o && typeof o == 'object'
                    ? function () { if ( o.hasOwnProperty(p) ) return ( v = o[p] ) != null; }
                    : function () { if ( a.length > i ) return ( v = a[i++] ) != null; };
  
              // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.
              // 'config() DECIMAL_PLACES not an integer: {v}'
              // 'config() DECIMAL_PLACES out of range: {v}'
              if ( has( p = 'DECIMAL_PLACES' ) && isValidInt( v, 0, MAX, 2, p ) ) {
                  DECIMAL_PLACES = v | 0;
              }
              r[p] = DECIMAL_PLACES;
  
              // ROUNDING_MODE {number} Integer, 0 to 8 inclusive.
              // 'config() ROUNDING_MODE not an integer: {v}'
              // 'config() ROUNDING_MODE out of range: {v}'
              if ( has( p = 'ROUNDING_MODE' ) && isValidInt( v, 0, 8, 2, p ) ) {
                  ROUNDING_MODE = v | 0;
              }
              r[p] = ROUNDING_MODE;
  
              // EXPONENTIAL_AT {number|number[]}
              // Integer, -MAX to MAX inclusive or [integer -MAX to 0 inclusive, 0 to MAX inclusive].
              // 'config() EXPONENTIAL_AT not an integer: {v}'
              // 'config() EXPONENTIAL_AT out of range: {v}'
              if ( has( p = 'EXPONENTIAL_AT' ) ) {
  
                  if ( isArray(v) ) {
                      if ( isValidInt( v[0], -MAX, 0, 2, p ) && isValidInt( v[1], 0, MAX, 2, p ) ) {
                          TO_EXP_NEG = v[0] | 0;
                          TO_EXP_POS = v[1] | 0;
                      }
                  } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) {
                      TO_EXP_NEG = -( TO_EXP_POS = ( v < 0 ? -v : v ) | 0 );
                  }
              }
              r[p] = [ TO_EXP_NEG, TO_EXP_POS ];
  
              // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
              // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].
              // 'config() RANGE not an integer: {v}'
              // 'config() RANGE cannot be zero: {v}'
              // 'config() RANGE out of range: {v}'
              if ( has( p = 'RANGE' ) ) {
  
                  if ( isArray(v) ) {
                      if ( isValidInt( v[0], -MAX, -1, 2, p ) && isValidInt( v[1], 1, MAX, 2, p ) ) {
                          MIN_EXP = v[0] | 0;
                          MAX_EXP = v[1] | 0;
                      }
                  } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) {
                      if ( v | 0 ) MIN_EXP = -( MAX_EXP = ( v < 0 ? -v : v ) | 0 );
                      else if (ERRORS) raise( 2, p + ' cannot be zero', v );
                  }
              }
              r[p] = [ MIN_EXP, MAX_EXP ];
  
              // ERRORS {boolean|number} true, false, 1 or 0.
              // 'config() ERRORS not a boolean or binary digit: {v}'
              if ( has( p = 'ERRORS' ) ) {
  
                  if ( v === !!v || v === 1 || v === 0 ) {
                      id = 0;
                      isValidInt = ( ERRORS = !!v ) ? intValidatorWithErrors : intValidatorNoErrors;
                  } else if (ERRORS) {
                      raise( 2, p + notBool, v );
                  }
              }
              r[p] = ERRORS;
  
              // CRYPTO {boolean|number} true, false, 1 or 0.
              // 'config() CRYPTO not a boolean or binary digit: {v}'
              // 'config() crypto unavailable: {crypto}'
              if ( has( p = 'CRYPTO' ) ) {
  
                  if ( v === !!v || v === 1 || v === 0 ) {
                      CRYPTO = !!( v && cryptoObj );
                      if ( v && !CRYPTO && ERRORS ) raise( 2, 'crypto unavailable', cryptoObj );
                  } else if (ERRORS) {
                      raise( 2, p + notBool, v );
                  }
              }
              r[p] = CRYPTO;
  
              // MODULO_MODE {number} Integer, 0 to 9 inclusive.
              // 'config() MODULO_MODE not an integer: {v}'
              // 'config() MODULO_MODE out of range: {v}'
              if ( has( p = 'MODULO_MODE' ) && isValidInt( v, 0, 9, 2, p ) ) {
                  MODULO_MODE = v | 0;
              }
              r[p] = MODULO_MODE;
  
              // POW_PRECISION {number} Integer, 0 to MAX inclusive.
              // 'config() POW_PRECISION not an integer: {v}'
              // 'config() POW_PRECISION out of range: {v}'
              if ( has( p = 'POW_PRECISION' ) && isValidInt( v, 0, MAX, 2, p ) ) {
                  POW_PRECISION = v | 0;
              }
              r[p] = POW_PRECISION;
  
              // FORMAT {object}
              // 'config() FORMAT not an object: {v}'
              if ( has( p = 'FORMAT' ) ) {
  
                  if ( typeof v == 'object' ) {
                      FORMAT = v;
                  } else if (ERRORS) {
                      raise( 2, p + ' not an object', v );
                  }
              }
              r[p] = FORMAT;
  
              return r;
          };
  
  
          /*
           * Return a new BigNumber whose value is the maximum of the arguments.
           *
           * arguments {number|string|BigNumber}
           */
          BigNumber.max = function () { return maxOrMin( arguments, P.lt ); };
  
  
          /*
           * Return a new BigNumber whose value is the minimum of the arguments.
           *
           * arguments {number|string|BigNumber}
           */
          BigNumber.min = function () { return maxOrMin( arguments, P.gt ); };
  
  
          /*
           * Return a new BigNumber with a random value equal to or greater than 0 and less than 1,
           * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing
           * zeros are produced).
           *
           * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
           *
           * 'random() decimal places not an integer: {dp}'
           * 'random() decimal places out of range: {dp}'
           * 'random() crypto unavailable: {crypto}'
           */
          BigNumber.random = (function () {
              var pow2_53 = 0x20000000000000;
  
              // Return a 53 bit integer n, where 0 <= n < 9007199254740992.
              // Check if Math.random() produces more than 32 bits of randomness.
              // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.
              // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.
              var random53bitInt = (Math.random() * pow2_53) & 0x1fffff
                ? function () { return mathfloor( Math.random() * pow2_53 ); }
                : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +
                    (Math.random() * 0x800000 | 0); };
  
              return function (dp) {
                  var a, b, e, k, v,
                      i = 0,
                      c = [],
                      rand = new BigNumber(ONE);
  
                  dp = dp == null || !isValidInt( dp, 0, MAX, 14 ) ? DECIMAL_PLACES : dp | 0;
                  k = mathceil( dp / LOG_BASE );
  
                  if (CRYPTO) {
  
                      // Browsers supporting crypto.getRandomValues.
                      if ( cryptoObj && cryptoObj.getRandomValues ) {
  
                          a = cryptoObj.getRandomValues( new Uint32Array( k *= 2 ) );
  
                          for ( ; i < k; ) {
  
                              // 53 bits:
                              // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)
                              // 11111 11111111 11111111 11111111 11100000 00000000 00000000
                              // ((Math.pow(2, 32) - 1) >>> 11).toString(2)
                              //                                     11111 11111111 11111111
                              // 0x20000 is 2^21.
                              v = a[i] * 0x20000 + (a[i + 1] >>> 11);
  
                              // Rejection sampling:
                              // 0 <= v < 9007199254740992
                              // Probability that v >= 9e15, is
                              // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251
                              if ( v >= 9e15 ) {
                                  b = cryptoObj.getRandomValues( new Uint32Array(2) );
                                  a[i] = b[0];
                                  a[i + 1] = b[1];
                              } else {
  
                                  // 0 <= v <= 8999999999999999
                                  // 0 <= (v % 1e14) <= 99999999999999
                                  c.push( v % 1e14 );
                                  i += 2;
                              }
                          }
                          i = k / 2;
  
                      // Node.js supporting crypto.randomBytes.
                      } else if ( cryptoObj && cryptoObj.randomBytes ) {
  
                          // buffer
                          a = cryptoObj.randomBytes( k *= 7 );
  
                          for ( ; i < k; ) {
  
                              // 0x1000000000000 is 2^48, 0x10000000000 is 2^40
                              // 0x100000000 is 2^32, 0x1000000 is 2^24
                              // 11111 11111111 11111111 11111111 11111111 11111111 11111111
                              // 0 <= v < 9007199254740992
                              v = ( ( a[i] & 31 ) * 0x1000000000000 ) + ( a[i + 1] * 0x10000000000 ) +
                                    ( a[i + 2] * 0x100000000 ) + ( a[i + 3] * 0x1000000 ) +
                                    ( a[i + 4] << 16 ) + ( a[i + 5] << 8 ) + a[i + 6];
  
                              if ( v >= 9e15 ) {
                                  cryptoObj.randomBytes(7).copy( a, i );
                              } else {
  
                                  // 0 <= (v % 1e14) <= 99999999999999
                                  c.push( v % 1e14 );
                                  i += 7;
                              }
                          }
                          i = k / 7;
                      } else if (ERRORS) {
                          raise( 14, 'crypto unavailable', cryptoObj );
                      }
                  }
  
                  // Use Math.random: CRYPTO is false or crypto is unavailable and ERRORS is false.
                  if (!i) {
  
                      for ( ; i < k; ) {
                          v = random53bitInt();
                          if ( v < 9e15 ) c[i++] = v % 1e14;
                      }
                  }
  
                  k = c[--i];
                  dp %= LOG_BASE;
  
                  // Convert trailing digits to zeros according to dp.
                  if ( k && dp ) {
                      v = POWS_TEN[LOG_BASE - dp];
                      c[i] = mathfloor( k / v ) * v;
                  }
  
                  // Remove trailing elements which are zero.
                  for ( ; c[i] === 0; c.pop(), i-- );
  
                  // Zero?
                  if ( i < 0 ) {
                      c = [ e = 0 ];
                  } else {
  
                      // Remove leading elements which are zero and adjust exponent accordingly.
                      for ( e = -1 ; c[0] === 0; c.shift(), e -= LOG_BASE);
  
                      // Count the digits of the first element of c to determine leading zeros, and...
                      for ( i = 1, v = c[0]; v >= 10; v /= 10, i++);
  
                      // adjust the exponent accordingly.
                      if ( i < LOG_BASE ) e -= LOG_BASE - i;
                  }
  
                  rand.e = e;
                  rand.c = c;
                  return rand;
              };
          })();
  
  
          // PRIVATE FUNCTIONS
  
  
          // Convert a numeric string of baseIn to a numeric string of baseOut.
          function convertBase( str, baseOut, baseIn, sign ) {
              var d, e, k, r, x, xc, y,
                  i = str.indexOf( '.' ),
                  dp = DECIMAL_PLACES,
                  rm = ROUNDING_MODE;
  
              if ( baseIn < 37 ) str = str.toLowerCase();
  
              // Non-integer.
              if ( i >= 0 ) {
                  k = POW_PRECISION;
  
                  // Unlimited precision.
                  POW_PRECISION = 0;
                  str = str.replace( '.', '' );
                  y = new BigNumber(baseIn);
                  x = y.pow( str.length - i );
                  POW_PRECISION = k;
  
                  // Convert str as if an integer, then restore the fraction part by dividing the
                  // result by its base raised to a power.
                  y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e ), 10, baseOut );
                  y.e = y.c.length;
              }
  
              // Convert the number as integer.
              xc = toBaseOut( str, baseIn, baseOut );
              e = k = xc.length;
  
              // Remove trailing zeros.
              for ( ; xc[--k] == 0; xc.pop() );
              if ( !xc[0] ) return '0';
  
              if ( i < 0 ) {
                  --e;
              } else {
                  x.c = xc;
                  x.e = e;
  
                  // sign is needed for correct rounding.
                  x.s = sign;
                  x = div( x, y, dp, rm, baseOut );
                  xc = x.c;
                  r = x.r;
                  e = x.e;
              }
  
              d = e + dp + 1;
  
              // The rounding digit, i.e. the digit to the right of the digit that may be rounded up.
              i = xc[d];
              k = baseOut / 2;
              r = r || d < 0 || xc[d + 1] != null;
  
              r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )
                         : i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||
                           rm == ( x.s < 0 ? 8 : 7 ) );
  
              if ( d < 1 || !xc[0] ) {
  
                  // 1^-dp or 0.
                  str = r ? toFixedPoint( '1', -dp ) : '0';
              } else {
                  xc.length = d;
  
                  if (r) {
  
                      // Rounding up may mean the previous digit has to be rounded up and so on.
                      for ( --baseOut; ++xc[--d] > baseOut; ) {
                          xc[d] = 0;
  
                          if ( !d ) {
                              ++e;
                              xc.unshift(1);
                          }
                      }
                  }
  
                  // Determine trailing zeros.
                  for ( k = xc.length; !xc[--k]; );
  
                  // E.g. [4, 11, 15] becomes 4bf.
                  for ( i = 0, str = ''; i <= k; str += ALPHABET.charAt( xc[i++] ) );
                  str = toFixedPoint( str, e );
              }
  
              // The caller will add the sign.
              return str;
          }
  
  
          // Perform division in the specified base. Called by div and convertBase.
          div = (function () {
  
              // Assume non-zero x and k.
              function multiply( x, k, base ) {
                  var m, temp, xlo, xhi,
                      carry = 0,
                      i = x.length,
                      klo = k % SQRT_BASE,
                      khi = k / SQRT_BASE | 0;
  
                  for ( x = x.slice(); i--; ) {
                      xlo = x[i] % SQRT_BASE;
                      xhi = x[i] / SQRT_BASE | 0;
                      m = khi * xlo + xhi * klo;
                      temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;
                      carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;
                      x[i] = temp % base;
                  }
  
                  if (carry) x.unshift(carry);
  
                  return x;
              }
  
              function compare( a, b, aL, bL ) {
                  var i, cmp;
  
                  if ( aL != bL ) {
                      cmp = aL > bL ? 1 : -1;
                  } else {
  
                      for ( i = cmp = 0; i < aL; i++ ) {
  
                          if ( a[i] != b[i] ) {
                              cmp = a[i] > b[i] ? 1 : -1;
                              break;
                          }
                      }
                  }
                  return cmp;
              }
  
              function subtract( a, b, aL, base ) {
                  var i = 0;
  
                  // Subtract b from a.
                  for ( ; aL--; ) {
                      a[aL] -= i;
                      i = a[aL] < b[aL] ? 1 : 0;
                      a[aL] = i * base + a[aL] - b[aL];
                  }
  
                  // Remove leading zeros.
                  for ( ; !a[0] && a.length > 1; a.shift() );
              }
  
              // x: dividend, y: divisor.
              return function ( x, y, dp, rm, base ) {
                  var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0,
                      yL, yz,
                      s = x.s == y.s ? 1 : -1,
                      xc = x.c,
                      yc = y.c;
  
                  // Either NaN, Infinity or 0?
                  if ( !xc || !xc[0] || !yc || !yc[0] ) {
  
                      return new BigNumber(
  
                        // Return NaN if either NaN, or both Infinity or 0.
                        !x.s || !y.s || ( xc ? yc && xc[0] == yc[0] : !yc ) ? NaN :
  
                          // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.
                          xc && xc[0] == 0 || !yc ? s * 0 : s / 0
                      );
                  }
  
                  q = new BigNumber(s);
                  qc = q.c = [];
                  e = x.e - y.e;
                  s = dp + e + 1;
  
                  if ( !base ) {
                      base = BASE;
                      e = bitFloor( x.e / LOG_BASE ) - bitFloor( y.e / LOG_BASE );
                      s = s / LOG_BASE | 0;
                  }
  
                  // Result exponent may be one less then the current value of e.
                  // The coefficients of the BigNumbers from convertBase may have trailing zeros.
                  for ( i = 0; yc[i] == ( xc[i] || 0 ); i++ );
                  if ( yc[i] > ( xc[i] || 0 ) ) e--;
  
                  if ( s < 0 ) {
                      qc.push(1);
                      more = true;
                  } else {
                      xL = xc.length;
                      yL = yc.length;
                      i = 0;
                      s += 2;
  
                      // Normalise xc and yc so highest order digit of yc is >= base / 2.
  
                      n = mathfloor( base / ( yc[0] + 1 ) );
  
                      // Not necessary, but to handle odd bases where yc[0] == ( base / 2 ) - 1.
                      // if ( n > 1 || n++ == 1 && yc[0] < base / 2 ) {
                      if ( n > 1 ) {
                          yc = multiply( yc, n, base );
                          xc = multiply( xc, n, base );
                          yL = yc.length;
                          xL = xc.length;
                      }
  
                      xi = yL;
                      rem = xc.slice( 0, yL );
                      remL = rem.length;
  
                      // Add zeros to make remainder as long as divisor.
                      for ( ; remL < yL; rem[remL++] = 0 );
                      yz = yc.slice();
                      yz.unshift(0);
                      yc0 = yc[0];
                      if ( yc[1] >= base / 2 ) yc0++;
                      // Not necessary, but to prevent trial digit n > base, when using base 3.
                      // else if ( base == 3 && yc0 == 1 ) yc0 = 1 + 1e-15;
  
                      do {
                          n = 0;
  
                          // Compare divisor and remainder.
                          cmp = compare( yc, rem, yL, remL );
  
                          // If divisor < remainder.
                          if ( cmp < 0 ) {
  
                              // Calculate trial digit, n.
  
                              rem0 = rem[0];
                              if ( yL != remL ) rem0 = rem0 * base + ( rem[1] || 0 );
  
                              // n is how many times the divisor goes into the current remainder.
                              n = mathfloor( rem0 / yc0 );
  
                              //  Algorithm:
                              //  1. product = divisor * trial digit (n)
                              //  2. if product > remainder: product -= divisor, n--
                              //  3. remainder -= product
                              //  4. if product was < remainder at 2:
                              //    5. compare new remainder and divisor
                              //    6. If remainder > divisor: remainder -= divisor, n++
  
                              if ( n > 1 ) {
  
                                  // n may be > base only when base is 3.
                                  if (n >= base) n = base - 1;
  
                                  // product = divisor * trial digit.
                                  prod = multiply( yc, n, base );
                                  prodL = prod.length;
                                  remL = rem.length;
  
                                  // Compare product and remainder.
                                  // If product > remainder.
                                  // Trial digit n too high.
                                  // n is 1 too high about 5% of the time, and is not known to have
                                  // ever been more than 1 too high.
                                  while ( compare( prod, rem, prodL, remL ) == 1 ) {
                                      n--;
  
                                      // Subtract divisor from product.
                                      subtract( prod, yL < prodL ? yz : yc, prodL, base );
                                      prodL = prod.length;
                                      cmp = 1;
                                  }
                              } else {
  
                                  // n is 0 or 1, cmp is -1.
                                  // If n is 0, there is no need to compare yc and rem again below,
                                  // so change cmp to 1 to avoid it.
                                  // If n is 1, leave cmp as -1, so yc and rem are compared again.
                                  if ( n == 0 ) {
  
                                      // divisor < remainder, so n must be at least 1.
                                      cmp = n = 1;
                                  }
  
                                  // product = divisor
                                  prod = yc.slice();
                                  prodL = prod.length;
                              }
  
                              if ( prodL < remL ) prod.unshift(0);
  
                              // Subtract product from remainder.
                              subtract( rem, prod, remL, base );
                              remL = rem.length;
  
                               // If product was < remainder.
                              if ( cmp == -1 ) {
  
                                  // Compare divisor and new remainder.
                                  // If divisor < new remainder, subtract divisor from remainder.
                                  // Trial digit n too low.
                                  // n is 1 too low about 5% of the time, and very rarely 2 too low.
                                  while ( compare( yc, rem, yL, remL ) < 1 ) {
                                      n++;
  
                                      // Subtract divisor from remainder.
                                      subtract( rem, yL < remL ? yz : yc, remL, base );
                                      remL = rem.length;
                                  }
                              }
                          } else if ( cmp === 0 ) {
                              n++;
                              rem = [0];
                          } // else cmp === 1 and n will be 0
  
                          // Add the next digit, n, to the result array.
                          qc[i++] = n;
  
                          // Update the remainder.
                          if ( rem[0] ) {
                              rem[remL++] = xc[xi] || 0;
                          } else {
                              rem = [ xc[xi] ];
                              remL = 1;
                          }
                      } while ( ( xi++ < xL || rem[0] != null ) && s-- );
  
                      more = rem[0] != null;
  
                      // Leading zero?
                      if ( !qc[0] ) qc.shift();
                  }
  
                  if ( base == BASE ) {
  
                      // To calculate q.e, first get the number of digits of qc[0].
                      for ( i = 1, s = qc[0]; s >= 10; s /= 10, i++ );
                      round( q, dp + ( q.e = i + e * LOG_BASE - 1 ) + 1, rm, more );
  
                  // Caller is convertBase.
                  } else {
                      q.e = e;
                      q.r = +more;
                  }
  
                  return q;
              };
          })();
  
  
          /*
           * Return a string representing the value of BigNumber n in fixed-point or exponential
           * notation rounded to the specified decimal places or significant digits.
           *
           * n is a BigNumber.
           * i is the index of the last digit required (i.e. the digit that may be rounded up).
           * rm is the rounding mode.
           * caller is caller id: toExponential 19, toFixed 20, toFormat 21, toPrecision 24.
           */
          function format( n, i, rm, caller ) {
              var c0, e, ne, len, str;
  
              rm = rm != null && isValidInt( rm, 0, 8, caller, roundingMode )
                ? rm | 0 : ROUNDING_MODE;
  
              if ( !n.c ) return n.toString();
              c0 = n.c[0];
              ne = n.e;
  
              if ( i == null ) {
                  str = coeffToString( n.c );
                  str = caller == 19 || caller == 24 && ne <= TO_EXP_NEG
                    ? toExponential( str, ne )
                    : toFixedPoint( str, ne );
              } else {
                  n = round( new BigNumber(n), i, rm );
  
                  // n.e may have changed if the value was rounded up.
                  e = n.e;
  
                  str = coeffToString( n.c );
                  len = str.length;
  
                  // toPrecision returns exponential notation if the number of significant digits
                  // specified is less than the number of digits necessary to represent the integer
                  // part of the value in fixed-point notation.
  
                  // Exponential notation.
                  if ( caller == 19 || caller == 24 && ( i <= e || e <= TO_EXP_NEG ) ) {
  
                      // Append zeros?
                      for ( ; len < i; str += '0', len++ );
                      str = toExponential( str, e );
  
                  // Fixed-point notation.
                  } else {
                      i -= ne;
                      str = toFixedPoint( str, e );
  
                      // Append zeros?
                      if ( e + 1 > len ) {
                          if ( --i > 0 ) for ( str += '.'; i--; str += '0' );
                      } else {
                          i += e - len;
                          if ( i > 0 ) {
                              if ( e + 1 == len ) str += '.';
                              for ( ; i--; str += '0' );
                          }
                      }
                  }
              }
  
              return n.s < 0 && c0 ? '-' + str : str;
          }
  
  
          // Handle BigNumber.max and BigNumber.min.
          function maxOrMin( args, method ) {
              var m, n,
                  i = 0;
  
              if ( isArray( args[0] ) ) args = args[0];
              m = new BigNumber( args[0] );
  
              for ( ; ++i < args.length; ) {
                  n = new BigNumber( args[i] );
  
                  // If any number is NaN, return NaN.
                  if ( !n.s ) {
                      m = n;
                      break;
                  } else if ( method.call( m, n ) ) {
                      m = n;
                  }
              }
  
              return m;
          }
  
  
          /*
           * Return true if n is an integer in range, otherwise throw.
           * Use for argument validation when ERRORS is true.
           */
          function intValidatorWithErrors( n, min, max, caller, name ) {
              if ( n < min || n > max || n != truncate(n) ) {
                  raise( caller, ( name || 'decimal places' ) +
                    ( n < min || n > max ? ' out of range' : ' not an integer' ), n );
              }
  
              return true;
          }
  
  
          /*
           * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.
           * Called by minus, plus and times.
           */
          function normalise( n, c, e ) {
              var i = 1,
                  j = c.length;
  
               // Remove trailing zeros.
              for ( ; !c[--j]; c.pop() );
  
              // Calculate the base 10 exponent. First get the number of digits of c[0].
              for ( j = c[0]; j >= 10; j /= 10, i++ );
  
              // Overflow?
              if ( ( e = i + e * LOG_BASE - 1 ) > MAX_EXP ) {
  
                  // Infinity.
                  n.c = n.e = null;
  
              // Underflow?
              } else if ( e < MIN_EXP ) {
  
                  // Zero.
                  n.c = [ n.e = 0 ];
              } else {
                  n.e = e;
                  n.c = c;
              }
  
              return n;
          }
  
  
          // Handle values that fail the validity test in BigNumber.
          parseNumeric = (function () {
              var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i,
                  dotAfter = /^([^.]+)\.$/,
                  dotBefore = /^\.([^.]+)$/,
                  isInfinityOrNaN = /^-?(Infinity|NaN)$/,
                  whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g;
  
              return function ( x, str, num, b ) {
                  var base,
                      s = num ? str : str.replace( whitespaceOrPlus, '' );
  
                  // No exception on ±Infinity or NaN.
                  if ( isInfinityOrNaN.test(s) ) {
                      x.s = isNaN(s) ? null : s < 0 ? -1 : 1;
                  } else {
                      if ( !num ) {
  
                          // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i
                          s = s.replace( basePrefix, function ( m, p1, p2 ) {
                              base = ( p2 = p2.toLowerCase() ) == 'x' ? 16 : p2 == 'b' ? 2 : 8;
                              return !b || b == base ? p1 : m;
                          });
  
                          if (b) {
                              base = b;
  
                              // E.g. '1.' to '1', '.1' to '0.1'
                              s = s.replace( dotAfter, '$1' ).replace( dotBefore, '0.$1' );
                          }
  
                          if ( str != s ) return new BigNumber( s, base );
                      }
  
                      // 'new BigNumber() not a number: {n}'
                      // 'new BigNumber() not a base {b} number: {n}'
                      if (ERRORS) raise( id, 'not a' + ( b ? ' base ' + b : '' ) + ' number', str );
                      x.s = null;
                  }
  
                  x.c = x.e = null;
                  id = 0;
              }
          })();
  
  
          // Throw a BigNumber Error.
          function raise( caller, msg, val ) {
              var error = new Error( [
                  'new BigNumber',     // 0
                  'cmp',               // 1
                  'config',            // 2
                  'div',               // 3
                  'divToInt',          // 4
                  'eq',                // 5
                  'gt',                // 6
                  'gte',               // 7
                  'lt',                // 8
                  'lte',               // 9
                  'minus',             // 10
                  'mod',               // 11
                  'plus',              // 12
                  'precision',         // 13
                  'random',            // 14
                  'round',             // 15
                  'shift',             // 16
                  'times',             // 17
                  'toDigits',          // 18
                  'toExponential',     // 19
                  'toFixed',           // 20
                  'toFormat',          // 21
                  'toFraction',        // 22
                  'pow',               // 23
                  'toPrecision',       // 24
                  'toString',          // 25
                  'BigNumber'          // 26
              ][caller] + '() ' + msg + ': ' + val );
  
              error.name = 'BigNumber Error';
              id = 0;
              throw error;
          }
  
  
          /*
           * Round x to sd significant digits using rounding mode rm. Check for over/under-flow.
           * If r is truthy, it is known that there are more digits after the rounding digit.
           */
          function round( x, sd, rm, r ) {
              var d, i, j, k, n, ni, rd,
                  xc = x.c,
                  pows10 = POWS_TEN;
  
              // if x is not Infinity or NaN...
              if (xc) {
  
                  // rd is the rounding digit, i.e. the digit after the digit that may be rounded up.
                  // n is a base 1e14 number, the value of the element of array x.c containing rd.
                  // ni is the index of n within x.c.
                  // d is the number of digits of n.
                  // i is the index of rd within n including leading zeros.
                  // j is the actual index of rd within n (if < 0, rd is a leading zero).
                  out: {
  
                      // Get the number of digits of the first element of xc.
                      for ( d = 1, k = xc[0]; k >= 10; k /= 10, d++ );
                      i = sd - d;
  
                      // If the rounding digit is in the first element of xc...
                      if ( i < 0 ) {
                          i += LOG_BASE;
                          j = sd;
                          n = xc[ ni = 0 ];
  
                          // Get the rounding digit at index j of n.
                          rd = n / pows10[ d - j - 1 ] % 10 | 0;
                      } else {
                          ni = mathceil( ( i + 1 ) / LOG_BASE );
  
                          if ( ni >= xc.length ) {
  
                              if (r) {
  
                                  // Needed by sqrt.
                                  for ( ; xc.length <= ni; xc.push(0) );
                                  n = rd = 0;
                                  d = 1;
                                  i %= LOG_BASE;
                                  j = i - LOG_BASE + 1;
                              } else {
                                  break out;
                              }
                          } else {
                              n = k = xc[ni];
  
                              // Get the number of digits of n.
                              for ( d = 1; k >= 10; k /= 10, d++ );
  
                              // Get the index of rd within n.
                              i %= LOG_BASE;
  
                              // Get the index of rd within n, adjusted for leading zeros.
                              // The number of leading zeros of n is given by LOG_BASE - d.
                              j = i - LOG_BASE + d;
  
                              // Get the rounding digit at index j of n.
                              rd = j < 0 ? 0 : n / pows10[ d - j - 1 ] % 10 | 0;
                          }
                      }
  
                      r = r || sd < 0 ||
  
                      // Are there any non-zero digits after the rounding digit?
                      // The expression  n % pows10[ d - j - 1 ]  returns all digits of n to the right
                      // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.
                        xc[ni + 1] != null || ( j < 0 ? n : n % pows10[ d - j - 1 ] );
  
                      r = rm < 4
                        ? ( rd || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )
                        : rd > 5 || rd == 5 && ( rm == 4 || r || rm == 6 &&
  
                          // Check whether the digit to the left of the rounding digit is odd.
                          ( ( i > 0 ? j > 0 ? n / pows10[ d - j ] : 0 : xc[ni - 1] ) % 10 ) & 1 ||
                            rm == ( x.s < 0 ? 8 : 7 ) );
  
                      if ( sd < 1 || !xc[0] ) {
                          xc.length = 0;
  
                          if (r) {
  
                              // Convert sd to decimal places.
                              sd -= x.e + 1;
  
                              // 1, 0.1, 0.01, 0.001, 0.0001 etc.
                              xc[0] = pows10[ ( LOG_BASE - sd % LOG_BASE ) % LOG_BASE ];
                              x.e = -sd || 0;
                          } else {
  
                              // Zero.
                              xc[0] = x.e = 0;
                          }
  
                          return x;
                      }
  
                      // Remove excess digits.
                      if ( i == 0 ) {
                          xc.length = ni;
                          k = 1;
                          ni--;
                      } else {
                          xc.length = ni + 1;
                          k = pows10[ LOG_BASE - i ];
  
                          // E.g. 56700 becomes 56000 if 7 is the rounding digit.
                          // j > 0 means i > number of leading zeros of n.
                          xc[ni] = j > 0 ? mathfloor( n / pows10[ d - j ] % pows10[j] ) * k : 0;
                      }
  
                      // Round up?
                      if (r) {
  
                          for ( ; ; ) {
  
                              // If the digit to be rounded up is in the first element of xc...
                              if ( ni == 0 ) {
  
                                  // i will be the length of xc[0] before k is added.
                                  for ( i = 1, j = xc[0]; j >= 10; j /= 10, i++ );
                                  j = xc[0] += k;
                                  for ( k = 1; j >= 10; j /= 10, k++ );
  
                                  // if i != k the length has increased.
                                  if ( i != k ) {
                                      x.e++;
                                      if ( xc[0] == BASE ) xc[0] = 1;
                                  }
  
                                  break;
                              } else {
                                  xc[ni] += k;
                                  if ( xc[ni] != BASE ) break;
                                  xc[ni--] = 0;
                                  k = 1;
                              }
                          }
                      }
  
                      // Remove trailing zeros.
                      for ( i = xc.length; xc[--i] === 0; xc.pop() );
                  }
  
                  // Overflow? Infinity.
                  if ( x.e > MAX_EXP ) {
                      x.c = x.e = null;
  
                  // Underflow? Zero.
                  } else if ( x.e < MIN_EXP ) {
                      x.c = [ x.e = 0 ];
                  }
              }
  
              return x;
          }
  
  
          // PROTOTYPE/INSTANCE METHODS
  
  
          /*
           * Return a new BigNumber whose value is the absolute value of this BigNumber.
           */
          P.absoluteValue = P.abs = function () {
              var x = new BigNumber(this);
              if ( x.s < 0 ) x.s = 1;
              return x;
          };
  
  
          /*
           * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole
           * number in the direction of Infinity.
           */
          P.ceil = function () {
              return round( new BigNumber(this), this.e + 1, 2 );
          };
  
  
          /*
           * Return
           * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),
           * -1 if the value of this BigNumber is less than the value of BigNumber(y, b),
           * 0 if they have the same value,
           * or null if the value of either is NaN.
           */
          P.comparedTo = P.cmp = function ( y, b ) {
              id = 1;
              return compare( this, new BigNumber( y, b ) );
          };
  
  
          /*
           * Return the number of decimal places of the value of this BigNumber, or null if the value
           * of this BigNumber is ±Infinity or NaN.
           */
          P.decimalPlaces = P.dp = function () {
              var n, v,
                  c = this.c;
  
              if ( !c ) return null;
              n = ( ( v = c.length - 1 ) - bitFloor( this.e / LOG_BASE ) ) * LOG_BASE;
  
              // Subtract the number of trailing zeros of the last number.
              if ( v = c[v] ) for ( ; v % 10 == 0; v /= 10, n-- );
              if ( n < 0 ) n = 0;
  
              return n;
          };
  
  
          /*
           *  n / 0 = I
           *  n / N = N
           *  n / I = 0
           *  0 / n = 0
           *  0 / 0 = N
           *  0 / N = N
           *  0 / I = 0
           *  N / n = N
           *  N / 0 = N
           *  N / N = N
           *  N / I = N
           *  I / n = I
           *  I / 0 = I
           *  I / N = N
           *  I / I = N
           *
           * Return a new BigNumber whose value is the value of this BigNumber divided by the value of
           * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.
           */
          P.dividedBy = P.div = function ( y, b ) {
              id = 3;
              return div( this, new BigNumber( y, b ), DECIMAL_PLACES, ROUNDING_MODE );
          };
  
  
          /*
           * Return a new BigNumber whose value is the integer part of dividing the value of this
           * BigNumber by the value of BigNumber(y, b).
           */
          P.dividedToIntegerBy = P.divToInt = function ( y, b ) {
              id = 4;
              return div( this, new BigNumber( y, b ), 0, 1 );
          };
  
  
          /*
           * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),
           * otherwise returns false.
           */
          P.equals = P.eq = function ( y, b ) {
              id = 5;
              return compare( this, new BigNumber( y, b ) ) === 0;
          };
  
  
          /*
           * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole
           * number in the direction of -Infinity.
           */
          P.floor = function () {
              return round( new BigNumber(this), this.e + 1, 3 );
          };
  
  
          /*
           * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),
           * otherwise returns false.
           */
          P.greaterThan = P.gt = function ( y, b ) {
              id = 6;
              return compare( this, new BigNumber( y, b ) ) > 0;
          };
  
  
          /*
           * Return true if the value of this BigNumber is greater than or equal to the value of
           * BigNumber(y, b), otherwise returns false.
           */
          P.greaterThanOrEqualTo = P.gte = function ( y, b ) {
              id = 7;
              return ( b = compare( this, new BigNumber( y, b ) ) ) === 1 || b === 0;
  
          };
  
  
          /*
           * Return true if the value of this BigNumber is a finite number, otherwise returns false.
           */
          P.isFinite = function () {
              return !!this.c;
          };
  
  
          /*
           * Return true if the value of this BigNumber is an integer, otherwise return false.
           */
          P.isInteger = P.isInt = function () {
              return !!this.c && bitFloor( this.e / LOG_BASE ) > this.c.length - 2;
          };
  
  
          /*
           * Return true if the value of this BigNumber is NaN, otherwise returns false.
           */
          P.isNaN = function () {
              return !this.s;
          };
  
  
          /*
           * Return true if the value of this BigNumber is negative, otherwise returns false.
           */
          P.isNegative = P.isNeg = function () {
              return this.s < 0;
          };
  
  
          /*
           * Return true if the value of this BigNumber is 0 or -0, otherwise returns false.
           */
          P.isZero = function () {
              return !!this.c && this.c[0] == 0;
          };
  
  
          /*
           * Return true if the value of this BigNumber is less than the value of BigNumber(y, b),
           * otherwise returns false.
           */
          P.lessThan = P.lt = function ( y, b ) {
              id = 8;
              return compare( this, new BigNumber( y, b ) ) < 0;
          };
  
  
          /*
           * Return true if the value of this BigNumber is less than or equal to the value of
           * BigNumber(y, b), otherwise returns false.
           */
          P.lessThanOrEqualTo = P.lte = function ( y, b ) {
              id = 9;
              return ( b = compare( this, new BigNumber( y, b ) ) ) === -1 || b === 0;
          };
  
  
          /*
           *  n - 0 = n
           *  n - N = N
           *  n - I = -I
           *  0 - n = -n
           *  0 - 0 = 0
           *  0 - N = N
           *  0 - I = -I
           *  N - n = N
           *  N - 0 = N
           *  N - N = N
           *  N - I = N
           *  I - n = I
           *  I - 0 = I
           *  I - N = N
           *  I - I = N
           *
           * Return a new BigNumber whose value is the value of this BigNumber minus the value of
           * BigNumber(y, b).
           */
          P.minus = P.sub = function ( y, b ) {
              var i, j, t, xLTy,
                  x = this,
                  a = x.s;
  
              id = 10;
              y = new BigNumber( y, b );
              b = y.s;
  
              // Either NaN?
              if ( !a || !b ) return new BigNumber(NaN);
  
              // Signs differ?
              if ( a != b ) {
                  y.s = -b;
                  return x.plus(y);
              }
  
              var xe = x.e / LOG_BASE,
                  ye = y.e / LOG_BASE,
                  xc = x.c,
                  yc = y.c;
  
              if ( !xe || !ye ) {
  
                  // Either Infinity?
                  if ( !xc || !yc ) return xc ? ( y.s = -b, y ) : new BigNumber( yc ? x : NaN );
  
                  // Either zero?
                  if ( !xc[0] || !yc[0] ) {
  
                      // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
                      return yc[0] ? ( y.s = -b, y ) : new BigNumber( xc[0] ? x :
  
                        // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity
                        ROUNDING_MODE == 3 ? -0 : 0 );
                  }
              }
  
              xe = bitFloor(xe);
              ye = bitFloor(ye);
              xc = xc.slice();
  
              // Determine which is the bigger number.
              if ( a = xe - ye ) {
  
                  if ( xLTy = a < 0 ) {
                      a = -a;
                      t = xc;
                  } else {
                      ye = xe;
                      t = yc;
                  }
  
                  t.reverse();
  
                  // Prepend zeros to equalise exponents.
                  for ( b = a; b--; t.push(0) );
                  t.reverse();
              } else {
  
                  // Exponents equal. Check digit by digit.
                  j = ( xLTy = ( a = xc.length ) < ( b = yc.length ) ) ? a : b;
  
                  for ( a = b = 0; b < j; b++ ) {
  
                      if ( xc[b] != yc[b] ) {
                          xLTy = xc[b] < yc[b];
                          break;
                      }
                  }
              }
  
              // x < y? Point xc to the array of the bigger number.
              if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s;
  
              b = ( j = yc.length ) - ( i = xc.length );
  
              // Append zeros to xc if shorter.
              // No need to add zeros to yc if shorter as subtract only needs to start at yc.length.
              if ( b > 0 ) for ( ; b--; xc[i++] = 0 );
              b = BASE - 1;
  
              // Subtract yc from xc.
              for ( ; j > a; ) {
  
                  if ( xc[--j] < yc[j] ) {
                      for ( i = j; i && !xc[--i]; xc[i] = b );
                      --xc[i];
                      xc[j] += BASE;
                  }
  
                  xc[j] -= yc[j];
              }
  
              // Remove leading zeros and adjust exponent accordingly.
              for ( ; xc[0] == 0; xc.shift(), --ye );
  
              // Zero?
              if ( !xc[0] ) {
  
                  // Following IEEE 754 (2008) 6.3,
                  // n - n = +0  but  n - n = -0  when rounding towards -Infinity.
                  y.s = ROUNDING_MODE == 3 ? -1 : 1;
                  y.c = [ y.e = 0 ];
                  return y;
              }
  
              // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity
              // for finite x and y.
              return normalise( y, xc, ye );
          };
  
  
          /*
           *   n % 0 =  N
           *   n % N =  N
           *   n % I =  n
           *   0 % n =  0
           *  -0 % n = -0
           *   0 % 0 =  N
           *   0 % N =  N
           *   0 % I =  0
           *   N % n =  N
           *   N % 0 =  N
           *   N % N =  N
           *   N % I =  N
           *   I % n =  N
           *   I % 0 =  N
           *   I % N =  N
           *   I % I =  N
           *
           * Return a new BigNumber whose value is the value of this BigNumber modulo the value of
           * BigNumber(y, b). The result depends on the value of MODULO_MODE.
           */
          P.modulo = P.mod = function ( y, b ) {
              var q, s,
                  x = this;
  
              id = 11;
              y = new BigNumber( y, b );
  
              // Return NaN if x is Infinity or NaN, or y is NaN or zero.
              if ( !x.c || !y.s || y.c && !y.c[0] ) {
                  return new BigNumber(NaN);
  
              // Return x if y is Infinity or x is zero.
              } else if ( !y.c || x.c && !x.c[0] ) {
                  return new BigNumber(x);
              }
  
              if ( MODULO_MODE == 9 ) {
  
                  // Euclidian division: q = sign(y) * floor(x / abs(y))
                  // r = x - qy    where  0 <= r < abs(y)
                  s = y.s;
                  y.s = 1;
                  q = div( x, y, 0, 3 );
                  y.s = s;
                  q.s *= s;
              } else {
                  q = div( x, y, 0, MODULO_MODE );
              }
  
              return x.minus( q.times(y) );
          };
  
  
          /*
           * Return a new BigNumber whose value is the value of this BigNumber negated,
           * i.e. multiplied by -1.
           */
          P.negated = P.neg = function () {
              var x = new BigNumber(this);
              x.s = -x.s || null;
              return x;
          };
  
  
          /*
           *  n + 0 = n
           *  n + N = N
           *  n + I = I
           *  0 + n = n
           *  0 + 0 = 0
           *  0 + N = N
           *  0 + I = I
           *  N + n = N
           *  N + 0 = N
           *  N + N = N
           *  N + I = N
           *  I + n = I
           *  I + 0 = I
           *  I + N = N
           *  I + I = I
           *
           * Return a new BigNumber whose value is the value of this BigNumber plus the value of
           * BigNumber(y, b).
           */
          P.plus = P.add = function ( y, b ) {
              var t,
                  x = this,
                  a = x.s;
  
              id = 12;
              y = new BigNumber( y, b );
              b = y.s;
  
              // Either NaN?
              if ( !a || !b ) return new BigNumber(NaN);
  
              // Signs differ?
               if ( a != b ) {
                  y.s = -b;
                  return x.minus(y);
              }
  
              var xe = x.e / LOG_BASE,
                  ye = y.e / LOG_BASE,
                  xc = x.c,
                  yc = y.c;
  
              if ( !xe || !ye ) {
  
                  // Return ±Infinity if either ±Infinity.
                  if ( !xc || !yc ) return new BigNumber( a / 0 );
  
                  // Either zero?
                  // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
                  if ( !xc[0] || !yc[0] ) return yc[0] ? y : new BigNumber( xc[0] ? x : a * 0 );
              }
  
              xe = bitFloor(xe);
              ye = bitFloor(ye);
              xc = xc.slice();
  
              // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.
              if ( a = xe - ye ) {
                  if ( a > 0 ) {
                      ye = xe;
                      t = yc;
                  } else {
                      a = -a;
                      t = xc;
                  }
  
                  t.reverse();
                  for ( ; a--; t.push(0) );
                  t.reverse();
              }
  
              a = xc.length;
              b = yc.length;
  
              // Point xc to the longer array, and b to the shorter length.
              if ( a - b < 0 ) t = yc, yc = xc, xc = t, b = a;
  
              // Only start adding at yc.length - 1 as the further digits of xc can be ignored.
              for ( a = 0; b; ) {
                  a = ( xc[--b] = xc[b] + yc[b] + a ) / BASE | 0;
                  xc[b] %= BASE;
              }
  
              if (a) {
                  xc.unshift(a);
                  ++ye;
              }
  
              // No need to check for zero, as +x + +y != 0 && -x + -y != 0
              // ye = MAX_EXP + 1 possible
              return normalise( y, xc, ye );
          };
  
  
          /*
           * Return the number of significant digits of the value of this BigNumber.
           *
           * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
           */
          P.precision = P.sd = function (z) {
              var n, v,
                  x = this,
                  c = x.c;
  
              // 'precision() argument not a boolean or binary digit: {z}'
              if ( z != null && z !== !!z && z !== 1 && z !== 0 ) {
                  if (ERRORS) raise( 13, 'argument' + notBool, z );
                  if ( z != !!z ) z = null;
              }
  
              if ( !c ) return null;
              v = c.length - 1;
              n = v * LOG_BASE + 1;
  
              if ( v = c[v] ) {
  
                  // Subtract the number of trailing zeros of the last element.
                  for ( ; v % 10 == 0; v /= 10, n-- );
  
                  // Add the number of digits of the first element.
                  for ( v = c[0]; v >= 10; v /= 10, n++ );
              }
  
              if ( z && x.e + 1 > n ) n = x.e + 1;
  
              return n;
          };
  
  
          /*
           * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of
           * dp decimal places using rounding mode rm, or to 0 and ROUNDING_MODE respectively if
           * omitted.
           *
           * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
           * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
           *
           * 'round() decimal places out of range: {dp}'
           * 'round() decimal places not an integer: {dp}'
           * 'round() rounding mode not an integer: {rm}'
           * 'round() rounding mode out of range: {rm}'
           */
          P.round = function ( dp, rm ) {
              var n = new BigNumber(this);
  
              if ( dp == null || isValidInt( dp, 0, MAX, 15 ) ) {
                  round( n, ~~dp + this.e + 1, rm == null ||
                    !isValidInt( rm, 0, 8, 15, roundingMode ) ? ROUNDING_MODE : rm | 0 );
              }
  
              return n;
          };
  
  
          /*
           * Return a new BigNumber whose value is the value of this BigNumber shifted by k places
           * (powers of 10). Shift to the right if n > 0, and to the left if n < 0.
           *
           * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
           *
           * If k is out of range and ERRORS is false, the result will be ±0 if k < 0, or ±Infinity
           * otherwise.
           *
           * 'shift() argument not an integer: {k}'
           * 'shift() argument out of range: {k}'
           */
          P.shift = function (k) {
              var n = this;
              return isValidInt( k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 16, 'argument' )
  
                // k < 1e+21, or truncate(k) will produce exponential notation.
                ? n.times( '1e' + truncate(k) )
                : new BigNumber( n.c && n.c[0] && ( k < -MAX_SAFE_INTEGER || k > MAX_SAFE_INTEGER )
                  ? n.s * ( k < 0 ? 0 : 1 / 0 )
                  : n );
          };
  
  
          /*
           *  sqrt(-n) =  N
           *  sqrt( N) =  N
           *  sqrt(-I) =  N
           *  sqrt( I) =  I
           *  sqrt( 0) =  0
           *  sqrt(-0) = -0
           *
           * Return a new BigNumber whose value is the square root of the value of this BigNumber,
           * rounded according to DECIMAL_PLACES and ROUNDING_MODE.
           */
          P.squareRoot = P.sqrt = function () {
              var m, n, r, rep, t,
                  x = this,
                  c = x.c,
                  s = x.s,
                  e = x.e,
                  dp = DECIMAL_PLACES + 4,
                  half = new BigNumber('0.5');
  
              // Negative/NaN/Infinity/zero?
              if ( s !== 1 || !c || !c[0] ) {
                  return new BigNumber( !s || s < 0 && ( !c || c[0] ) ? NaN : c ? x : 1 / 0 );
              }
  
              // Initial estimate.
              s = Math.sqrt( +x );
  
              // Math.sqrt underflow/overflow?
              // Pass x to Math.sqrt as integer, then adjust the exponent of the result.
              if ( s == 0 || s == 1 / 0 ) {
                  n = coeffToString(c);
                  if ( ( n.length + e ) % 2 == 0 ) n += '0';
                  s = Math.sqrt(n);
                  e = bitFloor( ( e + 1 ) / 2 ) - ( e < 0 || e % 2 );
  
                  if ( s == 1 / 0 ) {
                      n = '1e' + e;
                  } else {
                      n = s.toExponential();
                      n = n.slice( 0, n.indexOf('e') + 1 ) + e;
                  }
  
                  r = new BigNumber(n);
              } else {
                  r = new BigNumber( s + '' );
              }
  
              // Check for zero.
              // r could be zero if MIN_EXP is changed after the this value was created.
              // This would cause a division by zero (x/t) and hence Infinity below, which would cause
              // coeffToString to throw.
              if ( r.c[0] ) {
                  e = r.e;
                  s = e + dp;
                  if ( s < 3 ) s = 0;
  
                  // Newton-Raphson iteration.
                  for ( ; ; ) {
                      t = r;
                      r = half.times( t.plus( div( x, t, dp, 1 ) ) );
  
                      if ( coeffToString( t.c   ).slice( 0, s ) === ( n =
                           coeffToString( r.c ) ).slice( 0, s ) ) {
  
                          // The exponent of r may here be one less than the final result exponent,
                          // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits
                          // are indexed correctly.
                          if ( r.e < e ) --s;
                          n = n.slice( s - 3, s + 1 );
  
                          // The 4th rounding digit may be in error by -1 so if the 4 rounding digits
                          // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the
                          // iteration.
                          if ( n == '9999' || !rep && n == '4999' ) {
  
                              // On the first iteration only, check to see if rounding up gives the
                              // exact result as the nines may infinitely repeat.
                              if ( !rep ) {
                                  round( t, t.e + DECIMAL_PLACES + 2, 0 );
  
                                  if ( t.times(t).eq(x) ) {
                                      r = t;
                                      break;
                                  }
                              }
  
                              dp += 4;
                              s += 4;
                              rep = 1;
                          } else {
  
                              // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact
                              // result. If not, then there are further digits and m will be truthy.
                              if ( !+n || !+n.slice(1) && n.charAt(0) == '5' ) {
  
                                  // Truncate to the first rounding digit.
                                  round( r, r.e + DECIMAL_PLACES + 2, 1 );
                                  m = !r.times(r).eq(x);
                              }
  
                              break;
                          }
                      }
                  }
              }
  
              return round( r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m );
          };
  
  
          /*
           *  n * 0 = 0
           *  n * N = N
           *  n * I = I
           *  0 * n = 0
           *  0 * 0 = 0
           *  0 * N = N
           *  0 * I = N
           *  N * n = N
           *  N * 0 = N
           *  N * N = N
           *  N * I = N
           *  I * n = I
           *  I * 0 = N
           *  I * N = N
           *  I * I = I
           *
           * Return a new BigNumber whose value is the value of this BigNumber times the value of
           * BigNumber(y, b).
           */
          P.times = P.mul = function ( y, b ) {
              var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc,
                  base, sqrtBase,
                  x = this,
                  xc = x.c,
                  yc = ( id = 17, y = new BigNumber( y, b ) ).c;
  
              // Either NaN, ±Infinity or ±0?
              if ( !xc || !yc || !xc[0] || !yc[0] ) {
  
                  // Return NaN if either is NaN, or one is 0 and the other is Infinity.
                  if ( !x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc ) {
                      y.c = y.e = y.s = null;
                  } else {
                      y.s *= x.s;
  
                      // Return ±Infinity if either is ±Infinity.
                      if ( !xc || !yc ) {
                          y.c = y.e = null;
  
                      // Return ±0 if either is ±0.
                      } else {
                          y.c = [0];
                          y.e = 0;
                      }
                  }
  
                  return y;
              }
  
              e = bitFloor( x.e / LOG_BASE ) + bitFloor( y.e / LOG_BASE );
              y.s *= x.s;
              xcL = xc.length;
              ycL = yc.length;
  
              // Ensure xc points to longer array and xcL to its length.
              if ( xcL < ycL ) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i;
  
              // Initialise the result array with zeros.
              for ( i = xcL + ycL, zc = []; i--; zc.push(0) );
  
              base = BASE;
              sqrtBase = SQRT_BASE;
  
              for ( i = ycL; --i >= 0; ) {
                  c = 0;
                  ylo = yc[i] % sqrtBase;
                  yhi = yc[i] / sqrtBase | 0;
  
                  for ( k = xcL, j = i + k; j > i; ) {
                      xlo = xc[--k] % sqrtBase;
                      xhi = xc[k] / sqrtBase | 0;
                      m = yhi * xlo + xhi * ylo;
                      xlo = ylo * xlo + ( ( m % sqrtBase ) * sqrtBase ) + zc[j] + c;
                      c = ( xlo / base | 0 ) + ( m / sqrtBase | 0 ) + yhi * xhi;
                      zc[j--] = xlo % base;
                  }
  
                  zc[j] = c;
              }
  
              if (c) {
                  ++e;
              } else {
                  zc.shift();
              }
  
              return normalise( y, zc, e );
          };
  
  
          /*
           * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of
           * sd significant digits using rounding mode rm, or ROUNDING_MODE if rm is omitted.
           *
           * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
           * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
           *
           * 'toDigits() precision out of range: {sd}'
           * 'toDigits() precision not an integer: {sd}'
           * 'toDigits() rounding mode not an integer: {rm}'
           * 'toDigits() rounding mode out of range: {rm}'
           */
          P.toDigits = function ( sd, rm ) {
              var n = new BigNumber(this);
              sd = sd == null || !isValidInt( sd, 1, MAX, 18, 'precision' ) ? null : sd | 0;
              rm = rm == null || !isValidInt( rm, 0, 8, 18, roundingMode ) ? ROUNDING_MODE : rm | 0;
              return sd ? round( n, sd, rm ) : n;
          };
  
  
          /*
           * Return a string representing the value of this BigNumber in exponential notation and
           * rounded using ROUNDING_MODE to dp fixed decimal places.
           *
           * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
           * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
           *
           * 'toExponential() decimal places not an integer: {dp}'
           * 'toExponential() decimal places out of range: {dp}'
           * 'toExponential() rounding mode not an integer: {rm}'
           * 'toExponential() rounding mode out of range: {rm}'
           */
          P.toExponential = function ( dp, rm ) {
              return format( this,
                dp != null && isValidInt( dp, 0, MAX, 19 ) ? ~~dp + 1 : null, rm, 19 );
          };
  
  
          /*
           * Return a string representing the value of this BigNumber in fixed-point notation rounding
           * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.
           *
           * Note: as with JavaScript's number type, (-0).toFixed(0) is '0',
           * but e.g. (-0.00001).toFixed(0) is '-0'.
           *
           * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
           * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
           *
           * 'toFixed() decimal places not an integer: {dp}'
           * 'toFixed() decimal places out of range: {dp}'
           * 'toFixed() rounding mode not an integer: {rm}'
           * 'toFixed() rounding mode out of range: {rm}'
           */
          P.toFixed = function ( dp, rm ) {
              return format( this, dp != null && isValidInt( dp, 0, MAX, 20 )
                ? ~~dp + this.e + 1 : null, rm, 20 );
          };
  
  
          /*
           * Return a string representing the value of this BigNumber in fixed-point notation rounded
           * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties
           * of the FORMAT object (see BigNumber.config).
           *
           * FORMAT = {
           *      decimalSeparator : '.',
           *      groupSeparator : ',',
           *      groupSize : 3,
           *      secondaryGroupSize : 0,
           *      fractionGroupSeparator : '\xA0',    // non-breaking space
           *      fractionGroupSize : 0
           * };
           *
           * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
           * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
           *
           * 'toFormat() decimal places not an integer: {dp}'
           * 'toFormat() decimal places out of range: {dp}'
           * 'toFormat() rounding mode not an integer: {rm}'
           * 'toFormat() rounding mode out of range: {rm}'
           */
          P.toFormat = function ( dp, rm ) {
              var str = format( this, dp != null && isValidInt( dp, 0, MAX, 21 )
                ? ~~dp + this.e + 1 : null, rm, 21 );
  
              if ( this.c ) {
                  var i,
                      arr = str.split('.'),
                      g1 = +FORMAT.groupSize,
                      g2 = +FORMAT.secondaryGroupSize,
                      groupSeparator = FORMAT.groupSeparator,
                      intPart = arr[0],
                      fractionPart = arr[1],
                      isNeg = this.s < 0,
                      intDigits = isNeg ? intPart.slice(1) : intPart,
                      len = intDigits.length;
  
                  if (g2) i = g1, g1 = g2, g2 = i, len -= i;
  
                  if ( g1 > 0 && len > 0 ) {
                      i = len % g1 || g1;
                      intPart = intDigits.substr( 0, i );
  
                      for ( ; i < len; i += g1 ) {
                          intPart += groupSeparator + intDigits.substr( i, g1 );
                      }
  
                      if ( g2 > 0 ) intPart += groupSeparator + intDigits.slice(i);
                      if (isNeg) intPart = '-' + intPart;
                  }
  
                  str = fractionPart
                    ? intPart + FORMAT.decimalSeparator + ( ( g2 = +FORMAT.fractionGroupSize )
                      ? fractionPart.replace( new RegExp( '\\d{' + g2 + '}\\B', 'g' ),
                        '$&' + FORMAT.fractionGroupSeparator )
                      : fractionPart )
                    : intPart;
              }
  
              return str;
          };
  
  
          /*
           * Return a string array representing the value of this BigNumber as a simple fraction with
           * an integer numerator and an integer denominator. The denominator will be a positive
           * non-zero value less than or equal to the specified maximum denominator. If a maximum
           * denominator is not specified, the denominator will be the lowest value necessary to
           * represent the number exactly.
           *
           * [md] {number|string|BigNumber} Integer >= 1 and < Infinity. The maximum denominator.
           *
           * 'toFraction() max denominator not an integer: {md}'
           * 'toFraction() max denominator out of range: {md}'
           */
          P.toFraction = function (md) {
              var arr, d0, d2, e, exp, n, n0, q, s,
                  k = ERRORS,
                  x = this,
                  xc = x.c,
                  d = new BigNumber(ONE),
                  n1 = d0 = new BigNumber(ONE),
                  d1 = n0 = new BigNumber(ONE);
  
              if ( md != null ) {
                  ERRORS = false;
                  n = new BigNumber(md);
                  ERRORS = k;
  
                  if ( !( k = n.isInt() ) || n.lt(ONE) ) {
  
                      if (ERRORS) {
                          raise( 22,
                            'max denominator ' + ( k ? 'out of range' : 'not an integer' ), md );
                      }
  
                      // ERRORS is false:
                      // If md is a finite non-integer >= 1, round it to an integer and use it.
                      md = !k && n.c && round( n, n.e + 1, 1 ).gte(ONE) ? n : null;
                  }
              }
  
              if ( !xc ) return x.toString();
              s = coeffToString(xc);
  
              // Determine initial denominator.
              // d is a power of 10 and the minimum max denominator that specifies the value exactly.
              e = d.e = s.length - x.e - 1;
              d.c[0] = POWS_TEN[ ( exp = e % LOG_BASE ) < 0 ? LOG_BASE + exp : exp ];
              md = !md || n.cmp(d) > 0 ? ( e > 0 ? d : n1 ) : n;
  
              exp = MAX_EXP;
              MAX_EXP = 1 / 0;
              n = new BigNumber(s);
  
              // n0 = d1 = 0
              n0.c[0] = 0;
  
              for ( ; ; )  {
                  q = div( n, d, 0, 1 );
                  d2 = d0.plus( q.times(d1) );
                  if ( d2.cmp(md) == 1 ) break;
                  d0 = d1;
                  d1 = d2;
                  n1 = n0.plus( q.times( d2 = n1 ) );
                  n0 = d2;
                  d = n.minus( q.times( d2 = d ) );
                  n = d2;
              }
  
              d2 = div( md.minus(d0), d1, 0, 1 );
              n0 = n0.plus( d2.times(n1) );
              d0 = d0.plus( d2.times(d1) );
              n0.s = n1.s = x.s;
              e *= 2;
  
              // Determine which fraction is closer to x, n0/d0 or n1/d1
              arr = div( n1, d1, e, ROUNDING_MODE ).minus(x).abs().cmp(
                    div( n0, d0, e, ROUNDING_MODE ).minus(x).abs() ) < 1
                      ? [ n1.toString(), d1.toString() ]
                      : [ n0.toString(), d0.toString() ];
  
              MAX_EXP = exp;
              return arr;
          };
  
  
          /*
           * Return the value of this BigNumber converted to a number primitive.
           */
          P.toNumber = function () {
              return +this;
          };
  
  
          /*
           * Return a BigNumber whose value is the value of this BigNumber raised to the power n.
           * If m is present, return the result modulo m.
           * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.
           * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using
           * ROUNDING_MODE.
           *
           * The modular power operation works efficiently when x, n, and m are positive integers,
           * otherwise it is equivalent to calculating x.toPower(n).modulo(m) (with POW_PRECISION 0).
           *
           * n {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
           * [m] {number|string|BigNumber} The modulus.
           *
           * 'pow() exponent not an integer: {n}'
           * 'pow() exponent out of range: {n}'
           *
           * Performs 54 loop iterations for n of 9007199254740991.
           */
          P.toPower = P.pow = function ( n, m ) {
              var k, y, z,
                  i = mathfloor( n < 0 ? -n : +n ),
                  x = this;
  
              if ( m != null ) {
                  id = 23;
                  m = new BigNumber(m);
              }
  
              // Pass ±Infinity to Math.pow if exponent is out of range.
              if ( !isValidInt( n, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 23, 'exponent' ) &&
                ( !isFinite(n) || i > MAX_SAFE_INTEGER && ( n /= 0 ) ||
                  parseFloat(n) != n && !( n = NaN ) ) || n == 0 ) {
                  k = Math.pow( +x, n );
                  return new BigNumber( m ? k % m : k );
              }
  
              if (m) {
                  if ( n > 1 && x.gt(ONE) && x.isInt() && m.gt(ONE) && m.isInt() ) {
                      x = x.mod(m);
                  } else {
                      z = m;
  
                      // Nullify m so only a single mod operation is performed at the end.
                      m = null;
                  }
              } else if (POW_PRECISION) {
  
                  // Truncating each coefficient array to a length of k after each multiplication
                  // equates to truncating significant digits to POW_PRECISION + [28, 41],
                  // i.e. there will be a minimum of 28 guard digits retained.
                  // (Using + 1.5 would give [9, 21] guard digits.)
                  k = mathceil( POW_PRECISION / LOG_BASE + 2 );
              }
  
              y = new BigNumber(ONE);
  
              for ( ; ; ) {
                  if ( i % 2 ) {
                      y = y.times(x);
                      if ( !y.c ) break;
                      if (k) {
                          if ( y.c.length > k ) y.c.length = k;
                      } else if (m) {
                          y = y.mod(m);
                      }
                  }
  
                  i = mathfloor( i / 2 );
                  if ( !i ) break;
                  x = x.times(x);
                  if (k) {
                      if ( x.c && x.c.length > k ) x.c.length = k;
                  } else if (m) {
                      x = x.mod(m);
                  }
              }
  
              if (m) return y;
              if ( n < 0 ) y = ONE.div(y);
  
              return z ? y.mod(z) : k ? round( y, POW_PRECISION, ROUNDING_MODE ) : y;
          };
  
  
          /*
           * Return a string representing the value of this BigNumber rounded to sd significant digits
           * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits
           * necessary to represent the integer part of the value in fixed-point notation, then use
           * exponential notation.
           *
           * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
           * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
           *
           * 'toPrecision() precision not an integer: {sd}'
           * 'toPrecision() precision out of range: {sd}'
           * 'toPrecision() rounding mode not an integer: {rm}'
           * 'toPrecision() rounding mode out of range: {rm}'
           */
          P.toPrecision = function ( sd, rm ) {
              return format( this, sd != null && isValidInt( sd, 1, MAX, 24, 'precision' )
                ? sd | 0 : null, rm, 24 );
          };
  
  
          /*
           * Return a string representing the value of this BigNumber in base b, or base 10 if b is
           * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and
           * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent
           * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than
           * TO_EXP_NEG, return exponential notation.
           *
           * [b] {number} Integer, 2 to 64 inclusive.
           *
           * 'toString() base not an integer: {b}'
           * 'toString() base out of range: {b}'
           */
          P.toString = function (b) {
              var str,
                  n = this,
                  s = n.s,
                  e = n.e;
  
              // Infinity or NaN?
              if ( e === null ) {
  
                  if (s) {
                      str = 'Infinity';
                      if ( s < 0 ) str = '-' + str;
                  } else {
                      str = 'NaN';
                  }
              } else {
                  str = coeffToString( n.c );
  
                  if ( b == null || !isValidInt( b, 2, 64, 25, 'base' ) ) {
                      str = e <= TO_EXP_NEG || e >= TO_EXP_POS
                        ? toExponential( str, e )
                        : toFixedPoint( str, e );
                  } else {
                      str = convertBase( toFixedPoint( str, e ), b | 0, 10, s );
                  }
  
                  if ( s < 0 && n.c[0] ) str = '-' + str;
              }
  
              return str;
          };
  
  
          /*
           * Return a new BigNumber whose value is the value of this BigNumber truncated to a whole
           * number.
           */
          P.truncated = P.trunc = function () {
              return round( new BigNumber(this), this.e + 1, 1 );
          };
  
  
  
          /*
           * Return as toString, but do not accept a base argument, and include the minus sign for
           * negative zero.
           */
          P.valueOf = P.toJSON = function () {
              var str,
                  n = this,
                  e = n.e;
  
              if ( e === null ) return n.toString();
  
              str = coeffToString( n.c );
  
              str = e <= TO_EXP_NEG || e >= TO_EXP_POS
                  ? toExponential( str, e )
                  : toFixedPoint( str, e );
  
              return n.s < 0 ? '-' + str : str;
          };
  
  
          // Aliases for BigDecimal methods.
          //P.add = P.plus;         // P.add included above
          //P.subtract = P.minus;   // P.sub included above
          //P.multiply = P.times;   // P.mul included above
          //P.divide = P.div;
          //P.remainder = P.mod;
          //P.compareTo = P.cmp;
          //P.negate = P.neg;
  
  
          if ( configObj != null ) BigNumber.config(configObj);
  
          return BigNumber;
      }
  
  
      // PRIVATE HELPER FUNCTIONS
  
  
      function bitFloor(n) {
          var i = n | 0;
          return n > 0 || n === i ? i : i - 1;
      }
  
  
      // Return a coefficient array as a string of base 10 digits.
      function coeffToString(a) {
          var s, z,
              i = 1,
              j = a.length,
              r = a[0] + '';
  
          for ( ; i < j; ) {
              s = a[i++] + '';
              z = LOG_BASE - s.length;
              for ( ; z--; s = '0' + s );
              r += s;
          }
  
          // Determine trailing zeros.
          for ( j = r.length; r.charCodeAt(--j) === 48; );
          return r.slice( 0, j + 1 || 1 );
      }
  
  
      // Compare the value of BigNumbers x and y.
      function compare( x, y ) {
          var a, b,
              xc = x.c,
              yc = y.c,
              i = x.s,
              j = y.s,
              k = x.e,
              l = y.e;
  
          // Either NaN?
          if ( !i || !j ) return null;
  
          a = xc && !xc[0];
          b = yc && !yc[0];
  
          // Either zero?
          if ( a || b ) return a ? b ? 0 : -j : i;
  
          // Signs differ?
          if ( i != j ) return i;
  
          a = i < 0;
          b = k == l;
  
          // Either Infinity?
          if ( !xc || !yc ) return b ? 0 : !xc ^ a ? 1 : -1;
  
          // Compare exponents.
          if ( !b ) return k > l ^ a ? 1 : -1;
  
          j = ( k = xc.length ) < ( l = yc.length ) ? k : l;
  
          // Compare digit by digit.
          for ( i = 0; i < j; i++ ) if ( xc[i] != yc[i] ) return xc[i] > yc[i] ^ a ? 1 : -1;
  
          // Compare lengths.
          return k == l ? 0 : k > l ^ a ? 1 : -1;
      }
  
  
      /*
       * Return true if n is a valid number in range, otherwise false.
       * Use for argument validation when ERRORS is false.
       * Note: parseInt('1e+1') == 1 but parseFloat('1e+1') == 10.
       */
      function intValidatorNoErrors( n, min, max ) {
          return ( n = truncate(n) ) >= min && n <= max;
      }
  
  
      function isArray(obj) {
          return Object.prototype.toString.call(obj) == '[object Array]';
      }
  
  
      /*
       * Convert string of baseIn to an array of numbers of baseOut.
       * Eg. convertBase('255', 10, 16) returns [15, 15].
       * Eg. convertBase('ff', 16, 10) returns [2, 5, 5].
       */
      function toBaseOut( str, baseIn, baseOut ) {
          var j,
              arr = [0],
              arrL,
              i = 0,
              len = str.length;
  
          for ( ; i < len; ) {
              for ( arrL = arr.length; arrL--; arr[arrL] *= baseIn );
              arr[ j = 0 ] += ALPHABET.indexOf( str.charAt( i++ ) );
  
              for ( ; j < arr.length; j++ ) {
  
                  if ( arr[j] > baseOut - 1 ) {
                      if ( arr[j + 1] == null ) arr[j + 1] = 0;
                      arr[j + 1] += arr[j] / baseOut | 0;
                      arr[j] %= baseOut;
                  }
              }
          }
  
          return arr.reverse();
      }
  
  
      function toExponential( str, e ) {
          return ( str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str ) +
            ( e < 0 ? 'e' : 'e+' ) + e;
      }
  
  
      function toFixedPoint( str, e ) {
          var len, z;
  
          // Negative exponent?
          if ( e < 0 ) {
  
              // Prepend zeros.
              for ( z = '0.'; ++e; z += '0' );
              str = z + str;
  
          // Positive exponent
          } else {
              len = str.length;
  
              // Append zeros.
              if ( ++e > len ) {
                  for ( z = '0', e -= len; --e; z += '0' );
                  str += z;
              } else if ( e < len ) {
                  str = str.slice( 0, e ) + '.' + str.slice(e);
              }
          }
  
          return str;
      }
  
  
      function truncate(n) {
          n = parseFloat(n);
          return n < 0 ? mathceil(n) : mathfloor(n);
      }
  
  
      // EXPORT
  
  
     // AMD.
      if ( typeof define == 'function' && define.amd ) {
          define( function () { return constructorFactory(); } );
  
      // Node.js and other environments that support module.exports.
      } else if ( typeof module != 'undefined' && module.exports ) {
          module.exports = constructorFactory();
  
          // Split string stops browserify adding crypto shim.
          if ( !cryptoObj ) try { cryptoObj = require('cry' + 'pto'); } catch (e) {}
  
      // Browser.
      } else {
          if ( !globalObj ) globalObj = typeof self != 'undefined' ? self : Function('return this')();
          globalObj.BigNumber = constructorFactory();
      }
  })(this);
  
  },{}],3:[function(require,module,exports){
  (function (module, exports) {
  
  'use strict';
  
  // Utils
  
  function assert(val, msg) {
    if (!val)
      throw new Error(msg || 'Assertion failed');
  }
  
  // Could use `inherits` module, but don't want to move from single file
  // architecture yet.
  function inherits(ctor, superCtor) {
    ctor.super_ = superCtor;
    var TempCtor = function () {};
    TempCtor.prototype = superCtor.prototype;
    ctor.prototype = new TempCtor();
    ctor.prototype.constructor = ctor;
  }
  
  // BN
  
  function BN(number, base, endian) {
    // May be `new BN(bn)` ?
    if (number !== null &&
        typeof number === 'object' &&
        Array.isArray(number.words)) {
      return number;
    }
  
    this.sign = false;
    this.words = null;
    this.length = 0;
  
    // Reduction context
    this.red = null;
  
    if (base === 'le' || base === 'be') {
      endian = base;
      base = 10;
    }
  
    if (number !== null)
      this._init(number || 0, base || 10, endian || 'be');
  }
  if (typeof module === 'object')
    module.exports = BN;
  else
    exports.BN = BN;
  
  BN.BN = BN;
  BN.wordSize = 26;
  
  BN.max = function max(left, right) {
    if (left.cmp(right) > 0)
      return left;
    else
      return right;
  };
  
  BN.min = function min(left, right) {
    if (left.cmp(right) < 0)
      return left;
    else
      return right;
  };
  
  BN.prototype._init = function init(number, base, endian) {
    if (typeof number === 'number') {
      return this._initNumber(number, base, endian);
    } else if (typeof number === 'object') {
      return this._initArray(number, base, endian);
    }
    if (base === 'hex')
      base = 16;
    assert(base === (base | 0) && base >= 2 && base <= 36);
  
    number = number.toString().replace(/\s+/g, '');
    var start = 0;
    if (number[0] === '-')
      start++;
  
    if (base === 16)
      this._parseHex(number, start);
    else
      this._parseBase(number, base, start);
  
    if (number[0] === '-')
      this.sign = true;
  
    this.strip();
  
    if (endian !== 'le')
      return;
  
    this._initArray(this.toArray(), base, endian);
  };
  
  BN.prototype._initNumber = function _initNumber(number, base, endian) {
    if (number < 0) {
      this.sign = true;
      number = -number;
    }
    if (number < 0x4000000) {
      this.words = [ number & 0x3ffffff ];
      this.length = 1;
    } else if (number < 0x10000000000000) {
      this.words = [
        number & 0x3ffffff,
        (number / 0x4000000) & 0x3ffffff
      ];
      this.length = 2;
    } else {
      assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
      this.words = [
        number & 0x3ffffff,
        (number / 0x4000000) & 0x3ffffff,
        1
      ];
      this.length = 3;
    }
  
    if (endian !== 'le')
      return;
  
    // Reverse the bytes
    this._initArray(this.toArray(), base, endian);
  };
  
  BN.prototype._initArray = function _initArray(number, base, endian) {
    // Perhaps a Uint8Array
    assert(typeof number.length === 'number');
    if (number.length <= 0) {
      this.words = [ 0 ];
      this.length = 1;
      return this;
    }
  
    this.length = Math.ceil(number.length / 3);
    this.words = new Array(this.length);
    for (var i = 0; i < this.length; i++)
      this.words[i] = 0;
  
    var off = 0;
    if (endian === 'be') {
      for (var i = number.length - 1, j = 0; i >= 0; i -= 3) {
        var w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
        this.words[j] |= (w << off) & 0x3ffffff;
        this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
        off += 24;
        if (off >= 26) {
          off -= 26;
          j++;
        }
      }
    } else if (endian === 'le') {
      for (var i = 0, j = 0; i < number.length; i += 3) {
        var w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
        this.words[j] |= (w << off) & 0x3ffffff;
        this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
        off += 24;
        if (off >= 26) {
          off -= 26;
          j++;
        }
      }
    }
    return this.strip();
  };
  
  function parseHex(str, start, end) {
    var r = 0;
    var len = Math.min(str.length, end);
    for (var i = start; i < len; i++) {
      var c = str.charCodeAt(i) - 48;
  
      r <<= 4;
  
      // 'a' - 'f'
      if (c >= 49 && c <= 54)
        r |= c - 49 + 0xa;
  
      // 'A' - 'F'
      else if (c >= 17 && c <= 22)
        r |= c - 17 + 0xa;
  
      // '0' - '9'
      else
        r |= c & 0xf;
    }
    return r;
  }
  
  BN.prototype._parseHex = function _parseHex(number, start) {
    // Create possibly bigger array to ensure that it fits the number
    this.length = Math.ceil((number.length - start) / 6);
    this.words = new Array(this.length);
    for (var i = 0; i < this.length; i++)
      this.words[i] = 0;
  
    // Scan 24-bit chunks and add them to the number
    var off = 0;
    for (var i = number.length - 6, j = 0; i >= start; i -= 6) {
      var w = parseHex(number, i, i + 6);
      this.words[j] |= (w << off) & 0x3ffffff;
      this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
      off += 24;
      if (off >= 26) {
        off -= 26;
        j++;
      }
    }
    if (i + 6 !== start) {
      var w = parseHex(number, start, i + 6);
      this.words[j] |= (w << off) & 0x3ffffff;
      this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
    }
    this.strip();
  };
  
  function parseBase(str, start, end, mul) {
    var r = 0;
    var len = Math.min(str.length, end);
    for (var i = start; i < len; i++) {
      var c = str.charCodeAt(i) - 48;
  
      r *= mul;
  
      // 'a'
      if (c >= 49)
        r += c - 49 + 0xa;
  
      // 'A'
      else if (c >= 17)
        r += c - 17 + 0xa;
  
      // '0' - '9'
      else
        r += c;
    }
    return r;
  }
  
  BN.prototype._parseBase = function _parseBase(number, base, start) {
    // Initialize as zero
    this.words = [ 0 ];
    this.length = 1;
  
    // Find length of limb in base
    for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base)
      limbLen++;
    limbLen--;
    limbPow = (limbPow / base) | 0;
  
    var total = number.length - start;
    var mod = total % limbLen;
    var end = Math.min(total, total - mod) + start;
  
    var word = 0;
    for (var i = start; i < end; i += limbLen) {
      word = parseBase(number, i, i + limbLen, base);
  
      this.imuln(limbPow);
      if (this.words[0] + word < 0x4000000)
        this.words[0] += word;
      else
        this._iaddn(word);
    }
  
    if (mod !== 0) {
      var pow = 1;
      var word = parseBase(number, i, number.length, base);
  
      for (var i = 0; i < mod; i++)
        pow *= base;
      this.imuln(pow);
      if (this.words[0] + word < 0x4000000)
        this.words[0] += word;
      else
        this._iaddn(word);
    }
  };
  
  BN.prototype.copy = function copy(dest) {
    dest.words = new Array(this.length);
    for (var i = 0; i < this.length; i++)
      dest.words[i] = this.words[i];
    dest.length = this.length;
    dest.sign = this.sign;
    dest.red = this.red;
  };
  
  BN.prototype.clone = function clone() {
    var r = new BN(null);
    this.copy(r);
    return r;
  };
  
  // Remove leading `0` from `this`
  BN.prototype.strip = function strip() {
    while (this.length > 1 && this.words[this.length - 1] === 0)
      this.length--;
    return this._normSign();
  };
  
  BN.prototype._normSign = function _normSign() {
    // -0 = 0
    if (this.length === 1 && this.words[0] === 0)
      this.sign = false;
    return this;
  };
  
  BN.prototype.inspect = function inspect() {
    return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
  };
  
  /*
  
  var zeros = [];
  var groupSizes = [];
  var groupBases = [];
  
  var s = '';
  var i = -1;
  while (++i < BN.wordSize) {
    zeros[i] = s;
    s += '0';
  }
  groupSizes[0] = 0;
  groupSizes[1] = 0;
  groupBases[0] = 0;
  groupBases[1] = 0;
  var base = 2 - 1;
  while (++base < 36 + 1) {
    var groupSize = 0;
    var groupBase = 1;
    while (groupBase < (1 << BN.wordSize) / base) {
      groupBase *= base;
      groupSize += 1;
    }
    groupSizes[base] = groupSize;
    groupBases[base] = groupBase;
  }
  
  */
  
  var zeros = [
    '',
    '0',
    '00',
    '000',
    '0000',
    '00000',
    '000000',
    '0000000',
    '00000000',
    '000000000',
    '0000000000',
    '00000000000',
    '000000000000',
    '0000000000000',
    '00000000000000',
    '000000000000000',
    '0000000000000000',
    '00000000000000000',
    '000000000000000000',
    '0000000000000000000',
    '00000000000000000000',
    '000000000000000000000',
    '0000000000000000000000',
    '00000000000000000000000',
    '000000000000000000000000',
    '0000000000000000000000000'
  ];
  
  var groupSizes = [
    0, 0,
    25, 16, 12, 11, 10, 9, 8,
    8, 7, 7, 7, 7, 6, 6,
    6, 6, 6, 6, 6, 5, 5,
    5, 5, 5, 5, 5, 5, 5,
    5, 5, 5, 5, 5, 5, 5
  ];
  
  var groupBases = [
    0, 0,
    33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
    43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
    16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
    6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
    24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
  ];
  
  BN.prototype.toString = function toString(base, padding) {
    base = base || 10;
    var padding = padding | 0 || 1;
    if (base === 16 || base === 'hex') {
      var out = '';
      var off = 0;
      var carry = 0;
      for (var i = 0; i < this.length; i++) {
        var w = this.words[i];
        var word = (((w << off) | carry) & 0xffffff).toString(16);
        carry = (w >>> (24 - off)) & 0xffffff;
        if (carry !== 0 || i !== this.length - 1)
          out = zeros[6 - word.length] + word + out;
        else
          out = word + out;
        off += 2;
        if (off >= 26) {
          off -= 26;
          i--;
        }
      }
      if (carry !== 0)
        out = carry.toString(16) + out;
      while (out.length % padding !== 0)
        out = '0' + out;
      if (this.sign)
        out = '-' + out;
      return out;
    } else if (base === (base | 0) && base >= 2 && base <= 36) {
      // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
      var groupSize = groupSizes[base];
      // var groupBase = Math.pow(base, groupSize);
      var groupBase = groupBases[base];
      var out = '';
      var c = this.clone();
      c.sign = false;
      while (c.cmpn(0) !== 0) {
        var r = c.modn(groupBase).toString(base);
        c = c.idivn(groupBase);
  
        if (c.cmpn(0) !== 0)
          out = zeros[groupSize - r.length] + r + out;
        else
          out = r + out;
      }
      if (this.cmpn(0) === 0)
        out = '0' + out;
      while (out.length % padding !== 0)
        out = '0' + out;
      if (this.sign)
        out = '-' + out;
      return out;
    } else {
      assert(false, 'Base should be between 2 and 36');
    }
  };
  
  BN.prototype.toJSON = function toJSON() {
    return this.toString(16);
  };
  
  BN.prototype.toArray = function toArray(endian, length) {
    this.strip();
    var littleEndian = endian === 'le';
    var res = new Array(this.byteLength());
    res[0] = 0;
  
    var q = this.clone();
    if (!littleEndian) {
      // Assume big-endian
      for (var i = 0; q.cmpn(0) !== 0; i++) {
        var b = q.andln(0xff);
        q.iushrn(8);
  
        res[res.length - i - 1] = b;
      }
    } else {
      for (var i = 0; q.cmpn(0) !== 0; i++) {
        var b = q.andln(0xff);
        q.iushrn(8);
  
        res[i] = b;
      }
    }
  
    if (length) {
      assert(res.length <= length, 'byte array longer than desired length');
  
      while (res.length < length) {
        if (littleEndian)
          res.push(0);
        else
          res.unshift(0);
      }
    }
  
    return res;
  };
  
  if (Math.clz32) {
    BN.prototype._countBits = function _countBits(w) {
      return 32 - Math.clz32(w);
    };
  } else {
    BN.prototype._countBits = function _countBits(w) {
      var t = w;
      var r = 0;
      if (t >= 0x1000) {
        r += 13;
        t >>>= 13;
      }
      if (t >= 0x40) {
        r += 7;
        t >>>= 7;
      }
      if (t >= 0x8) {
        r += 4;
        t >>>= 4;
      }
      if (t >= 0x02) {
        r += 2;
        t >>>= 2;
      }
      return r + t;
    };
  }
  
  BN.prototype._zeroBits = function _zeroBits(w) {
    // Short-cut
    if (w === 0)
      return 26;
  
    var t = w;
    var r = 0;
    if ((t & 0x1fff) === 0) {
      r += 13;
      t >>>= 13;
    }
    if ((t & 0x7f) === 0) {
      r += 7;
      t >>>= 7;
    }
    if ((t & 0xf) === 0) {
      r += 4;
      t >>>= 4;
    }
    if ((t & 0x3) === 0) {
      r += 2;
      t >>>= 2;
    }
    if ((t & 0x1) === 0)
      r++;
    return r;
  };
  
  // Return number of used bits in a BN
  BN.prototype.bitLength = function bitLength() {
    var hi = 0;
    var w = this.words[this.length - 1];
    var hi = this._countBits(w);
    return (this.length - 1) * 26 + hi;
  };
  
  function toBitArray(num) {
    var w = new Array(num.bitLength());
  
    for (var bit = 0; bit < w.length; bit++) {
      var off = (bit / 26) | 0;
      var wbit = bit % 26;
  
      w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
    }
  
    return w;
  }
  
  // Number of trailing zero bits
  BN.prototype.zeroBits = function zeroBits() {
    if (this.cmpn(0) === 0)
      return 0;
  
    var r = 0;
    for (var i = 0; i < this.length; i++) {
      var b = this._zeroBits(this.words[i]);
      r += b;
      if (b !== 26)
        break;
    }
    return r;
  };
  
  BN.prototype.byteLength = function byteLength() {
    return Math.ceil(this.bitLength() / 8);
  };
  
  // Return negative clone of `this`
  BN.prototype.neg = function neg() {
    if (this.cmpn(0) === 0)
      return this.clone();
  
    var r = this.clone();
    r.sign = !this.sign;
    return r;
  };
  
  
  // Or `num` with `this` in-place
  BN.prototype.iuor = function iuor(num) {
    while (this.length < num.length)
      this.words[this.length++] = 0;
  
    for (var i = 0; i < num.length; i++)
      this.words[i] = this.words[i] | num.words[i];
  
    return this.strip();
  };
  
  BN.prototype.ior = function ior(num) {
    assert(!this.sign && !num.sign);
    return this.iuor(num);
  };
  
  
  // Or `num` with `this`
  BN.prototype.or = function or(num) {
    if (this.length > num.length)
      return this.clone().ior(num);
    else
      return num.clone().ior(this);
  };
  
  BN.prototype.uor = function uor(num) {
    if (this.length > num.length)
      return this.clone().iuor(num);
    else
      return num.clone().iuor(this);
  };
  
  
  // And `num` with `this` in-place
  BN.prototype.iuand = function iuand(num) {
    // b = min-length(num, this)
    var b;
    if (this.length > num.length)
      b = num;
    else
      b = this;
  
    for (var i = 0; i < b.length; i++)
      this.words[i] = this.words[i] & num.words[i];
  
    this.length = b.length;
  
    return this.strip();
  };
  
  BN.prototype.iand = function iand(num) {
    assert(!this.sign && !num.sign);
    return this.iuand(num);
  };
  
  
  // And `num` with `this`
  BN.prototype.and = function and(num) {
    if (this.length > num.length)
      return this.clone().iand(num);
    else
      return num.clone().iand(this);
  };
  
  BN.prototype.uand = function uand(num) {
    if (this.length > num.length)
      return this.clone().iuand(num);
    else
      return num.clone().iuand(this);
  };
  
  
  // Xor `num` with `this` in-place
  BN.prototype.iuxor = function iuxor(num) {
    // a.length > b.length
    var a;
    var b;
    if (this.length > num.length) {
      a = this;
      b = num;
    } else {
      a = num;
      b = this;
    }
  
    for (var i = 0; i < b.length; i++)
      this.words[i] = a.words[i] ^ b.words[i];
  
    if (this !== a)
      for (; i < a.length; i++)
        this.words[i] = a.words[i];
  
    this.length = a.length;
  
    return this.strip();
  };
  
  BN.prototype.ixor = function ixor(num) {
    assert(!this.sign && !num.sign);
    return this.iuxor(num);
  };
  
  
  // Xor `num` with `this`
  BN.prototype.xor = function xor(num) {
    if (this.length > num.length)
      return this.clone().ixor(num);
    else
      return num.clone().ixor(this);
  };
  
  BN.prototype.uxor = function uxor(num) {
    if (this.length > num.length)
      return this.clone().iuxor(num);
    else
      return num.clone().iuxor(this);
  };
  
  
  // Set `bit` of `this`
  BN.prototype.setn = function setn(bit, val) {
    assert(typeof bit === 'number' && bit >= 0);
  
    var off = (bit / 26) | 0;
    var wbit = bit % 26;
  
    while (this.length <= off)
      this.words[this.length++] = 0;
  
    if (val)
      this.words[off] = this.words[off] | (1 << wbit);
    else
      this.words[off] = this.words[off] & ~(1 << wbit);
  
    return this.strip();
  };
  
  
  // Add `num` to `this` in-place
  BN.prototype.iadd = function iadd(num) {
    // negative + positive
    if (this.sign && !num.sign) {
      this.sign = false;
      var r = this.isub(num);
      this.sign = !this.sign;
      return this._normSign();
  
    // positive + negative
    } else if (!this.sign && num.sign) {
      num.sign = false;
      var r = this.isub(num);
      num.sign = true;
      return r._normSign();
    }
  
    // a.length > b.length
    var a;
    var b;
    if (this.length > num.length) {
      a = this;
      b = num;
    } else {
      a = num;
      b = this;
    }
  
    var carry = 0;
    for (var i = 0; i < b.length; i++) {
      var r = a.words[i] + b.words[i] + carry;
      this.words[i] = r & 0x3ffffff;
      carry = r >>> 26;
    }
    for (; carry !== 0 && i < a.length; i++) {
      var r = a.words[i] + carry;
      this.words[i] = r & 0x3ffffff;
      carry = r >>> 26;
    }
  
    this.length = a.length;
    if (carry !== 0) {
      this.words[this.length] = carry;
      this.length++;
    // Copy the rest of the words
    } else if (a !== this) {
      for (; i < a.length; i++)
        this.words[i] = a.words[i];
    }
  
    return this;
  };
  
  // Add `num` to `this`
  BN.prototype.add = function add(num) {
    if (num.sign && !this.sign) {
      num.sign = false;
      var res = this.sub(num);
      num.sign = true;
      return res;
    } else if (!num.sign && this.sign) {
      this.sign = false;
      var res = num.sub(this);
      this.sign = true;
      return res;
    }
  
    if (this.length > num.length)
      return this.clone().iadd(num);
    else
      return num.clone().iadd(this);
  };
  
  // Subtract `num` from `this` in-place
  BN.prototype.isub = function isub(num) {
    // this - (-num) = this + num
    if (num.sign) {
      num.sign = false;
      var r = this.iadd(num);
      num.sign = true;
      return r._normSign();
  
    // -this - num = -(this + num)
    } else if (this.sign) {
      this.sign = false;
      this.iadd(num);
      this.sign = true;
      return this._normSign();
    }
  
    // At this point both numbers are positive
    var cmp = this.cmp(num);
  
    // Optimization - zeroify
    if (cmp === 0) {
      this.sign = false;
      this.length = 1;
      this.words[0] = 0;
      return this;
    }
  
    // a > b
    var a;
    var b;
    if (cmp > 0) {
      a = this;
      b = num;
    } else {
      a = num;
      b = this;
    }
  
    var carry = 0;
    for (var i = 0; i < b.length; i++) {
      var r = a.words[i] - b.words[i] + carry;
      carry = r >> 26;
      this.words[i] = r & 0x3ffffff;
    }
    for (; carry !== 0 && i < a.length; i++) {
      var r = a.words[i] + carry;
      carry = r >> 26;
      this.words[i] = r & 0x3ffffff;
    }
  
    // Copy rest of the words
    if (carry === 0 && i < a.length && a !== this)
      for (; i < a.length; i++)
        this.words[i] = a.words[i];
    this.length = Math.max(this.length, i);
  
    if (a !== this)
      this.sign = true;
  
    return this.strip();
  };
  
  // Subtract `num` from `this`
  BN.prototype.sub = function sub(num) {
    return this.clone().isub(num);
  };
  
  /*
  // NOTE: This could be potentionally used to generate loop-less multiplications
  function _genCombMulTo(alen, blen) {
    var len = alen + blen - 1;
    var src = [
      'var a = this.words, b = num.words, o = out.words, c = 0, w, ' +
          'mask = 0x3ffffff, shift = 0x4000000;',
      'out.length = ' + len + ';'
    ];
    for (var k = 0; k < len; k++) {
      var minJ = Math.max(0, k - alen + 1);
      var maxJ = Math.min(k, blen - 1);
  
      for (var j = minJ; j <= maxJ; j++) {
        var i = k - j;
        var mul = 'a[' + i + '] * b[' + j + ']';
  
        if (j === minJ) {
          src.push('w = ' + mul + ' + c;');
          src.push('c = (w / shift) | 0;');
        } else {
          src.push('w += ' + mul + ';');
          src.push('c += (w / shift) | 0;');
        }
        src.push('w &= mask;');
      }
      src.push('o[' + k + '] = w;');
    }
    src.push('if (c !== 0) {',
             '  o[' + k + '] = c;',
             '  out.length++;',
             '}',
             'return out;');
  
    return src.join('\n');
  }
  */
  
  BN.prototype._smallMulTo = function _smallMulTo(num, out) {
    out.sign = num.sign !== this.sign;
    out.length = this.length + num.length;
  
    var carry = 0;
    for (var k = 0; k < out.length - 1; k++) {
      // Sum all words with the same `i + j = k` and accumulate `ncarry`,
      // note that ncarry could be >= 0x3ffffff
      var ncarry = carry >>> 26;
      var rword = carry & 0x3ffffff;
      var maxJ = Math.min(k, num.length - 1);
      for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) {
        var i = k - j;
        var a = this.words[i] | 0;
        var b = num.words[j] | 0;
        var r = a * b;
  
        var lo = r & 0x3ffffff;
        ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
        lo = (lo + rword) | 0;
        rword = lo & 0x3ffffff;
        ncarry = (ncarry + (lo >>> 26)) | 0;
      }
      out.words[k] = rword;
      carry = ncarry;
    }
    if (carry !== 0) {
      out.words[k] = carry;
    } else {
      out.length--;
    }
  
    return out.strip();
  };
  
  BN.prototype._bigMulTo = function _bigMulTo(num, out) {
    out.sign = num.sign !== this.sign;
    out.length = this.length + num.length;
  
    var carry = 0;
    var hncarry = 0;
    for (var k = 0; k < out.length - 1; k++) {
      // Sum all words with the same `i + j = k` and accumulate `ncarry`,
      // note that ncarry could be >= 0x3ffffff
      var ncarry = hncarry;
      hncarry = 0;
      var rword = carry & 0x3ffffff;
      var maxJ = Math.min(k, num.length - 1);
      for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) {
        var i = k - j;
        var a = this.words[i] | 0;
        var b = num.words[j] | 0;
        var r = a * b;
  
        var lo = r & 0x3ffffff;
        ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
        lo = (lo + rword) | 0;
        rword = lo & 0x3ffffff;
        ncarry = (ncarry + (lo >>> 26)) | 0;
  
        hncarry += ncarry >>> 26;
        ncarry &= 0x3ffffff;
      }
      out.words[k] = rword;
      carry = ncarry;
      ncarry = hncarry;
    }
    if (carry !== 0) {
      out.words[k] = carry;
    } else {
      out.length--;
    }
  
    return out.strip();
  };
  
  BN.prototype.mulTo = function mulTo(num, out) {
    var res;
    if (this.length + num.length < 63)
      res = this._smallMulTo(num, out);
    else
      res = this._bigMulTo(num, out);
    return res;
  };
  
  // Multiply `this` by `num`
  BN.prototype.mul = function mul(num) {
    var out = new BN(null);
    out.words = new Array(this.length + num.length);
    return this.mulTo(num, out);
  };
  
  // In-place Multiplication
  BN.prototype.imul = function imul(num) {
    if (this.cmpn(0) === 0 || num.cmpn(0) === 0) {
      this.words[0] = 0;
      this.length = 1;
      return this;
    }
  
    var tlen = this.length;
    var nlen = num.length;
  
    this.sign = num.sign !== this.sign;
    this.length = this.length + num.length;
    this.words[this.length - 1] = 0;
  
    for (var k = this.length - 2; k >= 0; k--) {
      // Sum all words with the same `i + j = k` and accumulate `carry`,
      // note that carry could be >= 0x3ffffff
      var carry = 0;
      var rword = 0;
      var maxJ = Math.min(k, nlen - 1);
      for (var j = Math.max(0, k - tlen + 1); j <= maxJ; j++) {
        var i = k - j;
        var a = this.words[i];
        var b = num.words[j];
        var r = a * b;
  
        var lo = r & 0x3ffffff;
        carry += (r / 0x4000000) | 0;
        lo += rword;
        rword = lo & 0x3ffffff;
        carry += lo >>> 26;
      }
      this.words[k] = rword;
      this.words[k + 1] += carry;
      carry = 0;
    }
  
    // Propagate overflows
    var carry = 0;
    for (var i = 1; i < this.length; i++) {
      var w = this.words[i] + carry;
      this.words[i] = w & 0x3ffffff;
      carry = w >>> 26;
    }
  
    return this.strip();
  };
  
  BN.prototype.imuln = function imuln(num) {
    assert(typeof num === 'number');
  
    // Carry
    var carry = 0;
    for (var i = 0; i < this.length; i++) {
      var w = this.words[i] * num;
      var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
      carry >>= 26;
      carry += (w / 0x4000000) | 0;
      // NOTE: lo is 27bit maximum
      carry += lo >>> 26;
      this.words[i] = lo & 0x3ffffff;
    }
  
    if (carry !== 0) {
      this.words[i] = carry;
      this.length++;
    }
  
    return this;
  };
  
  BN.prototype.muln = function muln(num) {
    return this.clone().imuln(num);
  };
  
  // `this` * `this`
  BN.prototype.sqr = function sqr() {
    return this.mul(this);
  };
  
  // `this` * `this` in-place
  BN.prototype.isqr = function isqr() {
    return this.mul(this);
  };
  
  // Math.pow(`this`, `num`)
  BN.prototype.pow = function pow(num) {
    var w = toBitArray(num);
    if (w.length === 0)
      return new BN(1);
  
    // Skip leading zeroes
    var res = this;
    for (var i = 0; i < w.length; i++, res = res.sqr())
      if (w[i] !== 0)
        break;
  
    if (++i < w.length) {
      for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
        if (w[i] === 0)
          continue;
        res = res.mul(q);
      }
    }
  
    return res;
  };
  
  // Shift-left in-place
  BN.prototype.iushln = function iushln(bits) {
    assert(typeof bits === 'number' && bits >= 0);
    var r = bits % 26;
    var s = (bits - r) / 26;
    var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
  
    if (r !== 0) {
      var carry = 0;
      for (var i = 0; i < this.length; i++) {
        var newCarry = this.words[i] & carryMask;
        var c = (this.words[i] - newCarry) << r;
        this.words[i] = c | carry;
        carry = newCarry >>> (26 - r);
      }
      if (carry) {
        this.words[i] = carry;
        this.length++;
      }
    }
  
    if (s !== 0) {
      for (var i = this.length - 1; i >= 0; i--)
        this.words[i + s] = this.words[i];
      for (var i = 0; i < s; i++)
        this.words[i] = 0;
      this.length += s;
    }
  
    return this.strip();
  };
  
  BN.prototype.ishln = function ishln(bits) {
    // TODO(indutny): implement me
    assert(!this.sign);
    return this.iushln(bits);
  };
  
  // Shift-right in-place
  // NOTE: `hint` is a lowest bit before trailing zeroes
  // NOTE: if `extended` is present - it will be filled with destroyed bits
  BN.prototype.iushrn = function iushrn(bits, hint, extended) {
    assert(typeof bits === 'number' && bits >= 0);
    var h;
    if (hint)
      h = (hint - (hint % 26)) / 26;
    else
      h = 0;
  
    var r = bits % 26;
    var s = Math.min((bits - r) / 26, this.length);
    var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
    var maskedWords = extended;
  
    h -= s;
    h = Math.max(0, h);
  
    // Extended mode, copy masked part
    if (maskedWords) {
      for (var i = 0; i < s; i++)
        maskedWords.words[i] = this.words[i];
      maskedWords.length = s;
    }
  
    if (s === 0) {
      // No-op, we should not move anything at all
    } else if (this.length > s) {
      this.length -= s;
      for (var i = 0; i < this.length; i++)
        this.words[i] = this.words[i + s];
    } else {
      this.words[0] = 0;
      this.length = 1;
    }
  
    var carry = 0;
    for (var i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
      var word = this.words[i];
      this.words[i] = (carry << (26 - r)) | (word >>> r);
      carry = word & mask;
    }
  
    // Push carried bits as a mask
    if (maskedWords && carry !== 0)
      maskedWords.words[maskedWords.length++] = carry;
  
    if (this.length === 0) {
      this.words[0] = 0;
      this.length = 1;
    }
  
    this.strip();
  
    return this;
  };
  
  BN.prototype.ishrn = function ishrn(bits, hint, extended) {
    // TODO(indutny): implement me
    assert(!this.sign);
    return this.iushrn(bits, hint, extended);
  };
  
  // Shift-left
  BN.prototype.shln = function shln(bits) {
    return this.clone().ishln(bits);
  };
  
  BN.prototype.ushln = function ushln(bits) {
    return this.clone().iushln(bits);
  };
  
  // Shift-right
  BN.prototype.shrn = function shrn(bits) {
    return this.clone().ishrn(bits);
  };
  
  BN.prototype.ushrn = function ushrn(bits) {
    return this.clone().iushrn(bits);
  };
  
  // Test if n bit is set
  BN.prototype.testn = function testn(bit) {
    assert(typeof bit === 'number' && bit >= 0);
    var r = bit % 26;
    var s = (bit - r) / 26;
    var q = 1 << r;
  
    // Fast case: bit is much higher than all existing words
    if (this.length <= s) {
      return false;
    }
  
    // Check bit and return
    var w = this.words[s];
  
    return !!(w & q);
  };
  
  // Return only lowers bits of number (in-place)
  BN.prototype.imaskn = function imaskn(bits) {
    assert(typeof bits === 'number' && bits >= 0);
    var r = bits % 26;
    var s = (bits - r) / 26;
  
    assert(!this.sign, 'imaskn works only with positive numbers');
  
    if (r !== 0)
      s++;
    this.length = Math.min(s, this.length);
  
    if (r !== 0) {
      var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
      this.words[this.length - 1] &= mask;
    }
  
    return this.strip();
  };
  
  // Return only lowers bits of number
  BN.prototype.maskn = function maskn(bits) {
    return this.clone().imaskn(bits);
  };
  
  // Add plain number `num` to `this`
  BN.prototype.iaddn = function iaddn(num) {
    assert(typeof num === 'number');
    if (num < 0)
      return this.isubn(-num);
  
    // Possible sign change
    if (this.sign) {
      if (this.length === 1 && this.words[0] < num) {
        this.words[0] = num - this.words[0];
        this.sign = false;
        return this;
      }
  
      this.sign = false;
      this.isubn(num);
      this.sign = true;
      return this;
    }
  
    // Add without checks
    return this._iaddn(num);
  };
  
  BN.prototype._iaddn = function _iaddn(num) {
    this.words[0] += num;
  
    // Carry
    for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
      this.words[i] -= 0x4000000;
      if (i === this.length - 1)
        this.words[i + 1] = 1;
      else
        this.words[i + 1]++;
    }
    this.length = Math.max(this.length, i + 1);
  
    return this;
  };
  
  // Subtract plain number `num` from `this`
  BN.prototype.isubn = function isubn(num) {
    assert(typeof num === 'number');
    if (num < 0)
      return this.iaddn(-num);
  
    if (this.sign) {
      this.sign = false;
      this.iaddn(num);
      this.sign = true;
      return this;
    }
  
    this.words[0] -= num;
  
    // Carry
    for (var i = 0; i < this.length && this.words[i] < 0; i++) {
      this.words[i] += 0x4000000;
      this.words[i + 1] -= 1;
    }
  
    return this.strip();
  };
  
  BN.prototype.addn = function addn(num) {
    return this.clone().iaddn(num);
  };
  
  BN.prototype.subn = function subn(num) {
    return this.clone().isubn(num);
  };
  
  BN.prototype.iabs = function iabs() {
    this.sign = false;
  
    return this;
  };
  
  BN.prototype.abs = function abs() {
    return this.clone().iabs();
  };
  
  BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) {
    // Bigger storage is needed
    var len = num.length + shift;
    var i;
    if (this.words.length < len) {
      var t = new Array(len);
      for (var i = 0; i < this.length; i++)
        t[i] = this.words[i];
      this.words = t;
    } else {
      i = this.length;
    }
  
    // Zeroify rest
    this.length = Math.max(this.length, len);
    for (; i < this.length; i++)
      this.words[i] = 0;
  
    var carry = 0;
    for (var i = 0; i < num.length; i++) {
      var w = this.words[i + shift] + carry;
      var right = num.words[i] * mul;
      w -= right & 0x3ffffff;
      carry = (w >> 26) - ((right / 0x4000000) | 0);
      this.words[i + shift] = w & 0x3ffffff;
    }
    for (; i < this.length - shift; i++) {
      var w = this.words[i + shift] + carry;
      carry = w >> 26;
      this.words[i + shift] = w & 0x3ffffff;
    }
  
    if (carry === 0)
      return this.strip();
  
    // Subtraction overflow
    assert(carry === -1);
    carry = 0;
    for (var i = 0; i < this.length; i++) {
      var w = -this.words[i] + carry;
      carry = w >> 26;
      this.words[i] = w & 0x3ffffff;
    }
    this.sign = true;
  
    return this.strip();
  };
  
  BN.prototype._wordDiv = function _wordDiv(num, mode) {
    var shift = this.length - num.length;
  
    var a = this.clone();
    var b = num;
  
    // Normalize
    var bhi = b.words[b.length - 1];
    var bhiBits = this._countBits(bhi);
    shift = 26 - bhiBits;
    if (shift !== 0) {
      b = b.ushln(shift);
      a.iushln(shift);
      bhi = b.words[b.length - 1];
    }
  
    // Initialize quotient
    var m = a.length - b.length;
    var q;
  
    if (mode !== 'mod') {
      q = new BN(null);
      q.length = m + 1;
      q.words = new Array(q.length);
      for (var i = 0; i < q.length; i++)
        q.words[i] = 0;
    }
  
    var diff = a.clone()._ishlnsubmul(b, 1, m);
    if (!diff.sign) {
      a = diff;
      if (q)
        q.words[m] = 1;
    }
  
    for (var j = m - 1; j >= 0; j--) {
      var qj = a.words[b.length + j] * 0x4000000 + a.words[b.length + j - 1];
  
      // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
      // (0x7ffffff)
      qj = Math.min((qj / bhi) | 0, 0x3ffffff);
  
      a._ishlnsubmul(b, qj, j);
      while (a.sign) {
        qj--;
        a.sign = false;
        a._ishlnsubmul(b, 1, j);
        if (a.cmpn(0) !== 0)
          a.sign = !a.sign;
      }
      if (q)
        q.words[j] = qj;
    }
    if (q)
      q.strip();
    a.strip();
  
    // Denormalize
    if (mode !== 'div' && shift !== 0)
      a.iushrn(shift);
    return { div: q ? q : null, mod: a };
  };
  
  BN.prototype.divmod = function divmod(num, mode, positive) {
    assert(num.cmpn(0) !== 0);
  
    if (this.sign && !num.sign) {
      var res = this.neg().divmod(num, mode);
      var div;
      var mod;
      if (mode !== 'mod')
        div = res.div.neg();
      if (mode !== 'div') {
        mod = res.mod.neg();
        if (positive && mod.neg)
          mod = mod.add(num);
      }
      return {
        div: div,
        mod: mod
      };
    } else if (!this.sign && num.sign) {
      var res = this.divmod(num.neg(), mode);
      var div;
      if (mode !== 'mod')
        div = res.div.neg();
      return { div: div, mod: res.mod };
    } else if (this.sign && num.sign) {
      var res = this.neg().divmod(num.neg(), mode);
      var mod;
      if (mode !== 'div') {
        mod = res.mod.neg();
        if (positive && mod.neg)
          mod = mod.isub(num);
      }
      return {
        div: res.div,
        mod: mod
      };
    }
  
    // Both numbers are positive at this point
  
    // Strip both numbers to approximate shift value
    if (num.length > this.length || this.cmp(num) < 0)
      return { div: new BN(0), mod: this };
  
    // Very short reduction
    if (num.length === 1) {
      if (mode === 'div')
        return { div: this.divn(num.words[0]), mod: null };
      else if (mode === 'mod')
        return { div: null, mod: new BN(this.modn(num.words[0])) };
      return {
        div: this.divn(num.words[0]),
        mod: new BN(this.modn(num.words[0]))
      };
    }
  
    return this._wordDiv(num, mode);
  };
  
  // Find `this` / `num`
  BN.prototype.div = function div(num) {
    return this.divmod(num, 'div', false).div;
  };
  
  // Find `this` % `num`
  BN.prototype.mod = function mod(num) {
    return this.divmod(num, 'mod', false).mod;
  };
  
  BN.prototype.umod = function umod(num) {
    return this.divmod(num, 'mod', true).mod;
  };
  
  // Find Round(`this` / `num`)
  BN.prototype.divRound = function divRound(num) {
    var dm = this.divmod(num);
  
    // Fast case - exact division
    if (dm.mod.cmpn(0) === 0)
      return dm.div;
  
    var mod = dm.div.sign ? dm.mod.isub(num) : dm.mod;
  
    var half = num.ushrn(1);
    var r2 = num.andln(1);
    var cmp = mod.cmp(half);
  
    // Round down
    if (cmp < 0 || r2 === 1 && cmp === 0)
      return dm.div;
  
    // Round up
    return dm.div.sign ? dm.div.isubn(1) : dm.div.iaddn(1);
  };
  
  BN.prototype.modn = function modn(num) {
    assert(num <= 0x3ffffff);
    var p = (1 << 26) % num;
  
    var acc = 0;
    for (var i = this.length - 1; i >= 0; i--)
      acc = (p * acc + this.words[i]) % num;
  
    return acc;
  };
  
  // In-place division by number
  BN.prototype.idivn = function idivn(num) {
    assert(num <= 0x3ffffff);
  
    var carry = 0;
    for (var i = this.length - 1; i >= 0; i--) {
      var w = this.words[i] + carry * 0x4000000;
      this.words[i] = (w / num) | 0;
      carry = w % num;
    }
  
    return this.strip();
  };
  
  BN.prototype.divn = function divn(num) {
    return this.clone().idivn(num);
  };
  
  BN.prototype.egcd = function egcd(p) {
    assert(!p.sign);
    assert(p.cmpn(0) !== 0);
  
    var x = this;
    var y = p.clone();
  
    if (x.sign)
      x = x.umod(p);
    else
      x = x.clone();
  
    // A * x + B * y = x
    var A = new BN(1);
    var B = new BN(0);
  
    // C * x + D * y = y
    var C = new BN(0);
    var D = new BN(1);
  
    var g = 0;
  
    while (x.isEven() && y.isEven()) {
      x.iushrn(1);
      y.iushrn(1);
      ++g;
    }
  
    var yp = y.clone();
    var xp = x.clone();
  
    while (x.cmpn(0) !== 0) {
      while (x.isEven()) {
        x.iushrn(1);
        if (A.isEven() && B.isEven()) {
          A.iushrn(1);
          B.iushrn(1);
        } else {
          A.iadd(yp).iushrn(1);
          B.isub(xp).iushrn(1);
        }
      }
  
      while (y.isEven()) {
        y.iushrn(1);
        if (C.isEven() && D.isEven()) {
          C.iushrn(1);
          D.iushrn(1);
        } else {
          C.iadd(yp).iushrn(1);
          D.isub(xp).iushrn(1);
        }
      }
  
      if (x.cmp(y) >= 0) {
        x.isub(y);
        A.isub(C);
        B.isub(D);
      } else {
        y.isub(x);
        C.isub(A);
        D.isub(B);
      }
    }
  
    return {
      a: C,
      b: D,
      gcd: y.iushln(g)
    };
  };
  
  // This is reduced incarnation of the binary EEA
  // above, designated to invert members of the
  // _prime_ fields F(p) at a maximal speed
  BN.prototype._invmp = function _invmp(p) {
    assert(!p.sign);
    assert(p.cmpn(0) !== 0);
  
    var a = this;
    var b = p.clone();
  
    if (a.sign)
      a = a.umod(p);
    else
      a = a.clone();
  
    var x1 = new BN(1);
    var x2 = new BN(0);
  
    var delta = b.clone();
  
    while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
      while (a.isEven()) {
        a.iushrn(1);
        if (x1.isEven())
          x1.iushrn(1);
        else
          x1.iadd(delta).iushrn(1);
      }
      while (b.isEven()) {
        b.iushrn(1);
        if (x2.isEven())
          x2.iushrn(1);
        else
          x2.iadd(delta).iushrn(1);
      }
      if (a.cmp(b) >= 0) {
        a.isub(b);
        x1.isub(x2);
      } else {
        b.isub(a);
        x2.isub(x1);
      }
    }
  
    var res;
    if (a.cmpn(1) === 0)
      res = x1;
    else
      res = x2;
  
    if (res.cmpn(0) < 0)
      res.iadd(p);
  
    return res;
  };
  
  BN.prototype.gcd = function gcd(num) {
    if (this.cmpn(0) === 0)
      return num.clone();
    if (num.cmpn(0) === 0)
      return this.clone();
  
    var a = this.clone();
    var b = num.clone();
    a.sign = false;
    b.sign = false;
  
    // Remove common factor of two
    for (var shift = 0; a.isEven() && b.isEven(); shift++) {
      a.iushrn(1);
      b.iushrn(1);
    }
  
    do {
      while (a.isEven())
        a.iushrn(1);
      while (b.isEven())
        b.iushrn(1);
  
      var r = a.cmp(b);
      if (r < 0) {
        // Swap `a` and `b` to make `a` always bigger than `b`
        var t = a;
        a = b;
        b = t;
      } else if (r === 0 || b.cmpn(1) === 0) {
        break;
      }
  
      a.isub(b);
    } while (true);
  
    return b.iushln(shift);
  };
  
  // Invert number in the field F(num)
  BN.prototype.invm = function invm(num) {
    return this.egcd(num).a.umod(num);
  };
  
  BN.prototype.isEven = function isEven() {
    return (this.words[0] & 1) === 0;
  };
  
  BN.prototype.isOdd = function isOdd() {
    return (this.words[0] & 1) === 1;
  };
  
  // And first word and num
  BN.prototype.andln = function andln(num) {
    return this.words[0] & num;
  };
  
  // Increment at the bit position in-line
  BN.prototype.bincn = function bincn(bit) {
    assert(typeof bit === 'number');
    var r = bit % 26;
    var s = (bit - r) / 26;
    var q = 1 << r;
  
    // Fast case: bit is much higher than all existing words
    if (this.length <= s) {
      for (var i = this.length; i < s + 1; i++)
        this.words[i] = 0;
      this.words[s] |= q;
      this.length = s + 1;
      return this;
    }
  
    // Add bit and propagate, if needed
    var carry = q;
    for (var i = s; carry !== 0 && i < this.length; i++) {
      var w = this.words[i];
      w += carry;
      carry = w >>> 26;
      w &= 0x3ffffff;
      this.words[i] = w;
    }
    if (carry !== 0) {
      this.words[i] = carry;
      this.length++;
    }
    return this;
  };
  
  BN.prototype.cmpn = function cmpn(num) {
    var sign = num < 0;
    if (sign)
      num = -num;
  
    if (this.sign && !sign)
      return -1;
    else if (!this.sign && sign)
      return 1;
  
    num &= 0x3ffffff;
    this.strip();
  
    var res;
    if (this.length > 1) {
      res = 1;
    } else {
      var w = this.words[0];
      res = w === num ? 0 : w < num ? -1 : 1;
    }
    if (this.sign)
      res = -res;
    return res;
  };
  
  // Compare two numbers and return:
  // 1 - if `this` > `num`
  // 0 - if `this` == `num`
  // -1 - if `this` < `num`
  BN.prototype.cmp = function cmp(num) {
    if (this.sign && !num.sign)
      return -1;
    else if (!this.sign && num.sign)
      return 1;
  
    var res = this.ucmp(num);
    if (this.sign)
      return -res;
    else
      return res;
  };
  
  // Unsigned comparison
  BN.prototype.ucmp = function ucmp(num) {
    // At this point both numbers have the same sign
    if (this.length > num.length)
      return 1;
    else if (this.length < num.length)
      return -1;
  
    var res = 0;
    for (var i = this.length - 1; i >= 0; i--) {
      var a = this.words[i];
      var b = num.words[i];
  
      if (a === b)
        continue;
      if (a < b)
        res = -1;
      else if (a > b)
        res = 1;
      break;
    }
    return res;
  };
  
  //
  // A reduce context, could be using montgomery or something better, depending
  // on the `m` itself.
  //
  BN.red = function red(num) {
    return new Red(num);
  };
  
  BN.prototype.toRed = function toRed(ctx) {
    assert(!this.red, 'Already a number in reduction context');
    assert(!this.sign, 'red works only with positives');
    return ctx.convertTo(this)._forceRed(ctx);
  };
  
  BN.prototype.fromRed = function fromRed() {
    assert(this.red, 'fromRed works only with numbers in reduction context');
    return this.red.convertFrom(this);
  };
  
  BN.prototype._forceRed = function _forceRed(ctx) {
    this.red = ctx;
    return this;
  };
  
  BN.prototype.forceRed = function forceRed(ctx) {
    assert(!this.red, 'Already a number in reduction context');
    return this._forceRed(ctx);
  };
  
  BN.prototype.redAdd = function redAdd(num) {
    assert(this.red, 'redAdd works only with red numbers');
    return this.red.add(this, num);
  };
  
  BN.prototype.redIAdd = function redIAdd(num) {
    assert(this.red, 'redIAdd works only with red numbers');
    return this.red.iadd(this, num);
  };
  
  BN.prototype.redSub = function redSub(num) {
    assert(this.red, 'redSub works only with red numbers');
    return this.red.sub(this, num);
  };
  
  BN.prototype.redISub = function redISub(num) {
    assert(this.red, 'redISub works only with red numbers');
    return this.red.isub(this, num);
  };
  
  BN.prototype.redShl = function redShl(num) {
    assert(this.red, 'redShl works only with red numbers');
    return this.red.ushl(this, num);
  };
  
  BN.prototype.redMul = function redMul(num) {
    assert(this.red, 'redMul works only with red numbers');
    this.red._verify2(this, num);
    return this.red.mul(this, num);
  };
  
  BN.prototype.redIMul = function redIMul(num) {
    assert(this.red, 'redMul works only with red numbers');
    this.red._verify2(this, num);
    return this.red.imul(this, num);
  };
  
  BN.prototype.redSqr = function redSqr() {
    assert(this.red, 'redSqr works only with red numbers');
    this.red._verify1(this);
    return this.red.sqr(this);
  };
  
  BN.prototype.redISqr = function redISqr() {
    assert(this.red, 'redISqr works only with red numbers');
    this.red._verify1(this);
    return this.red.isqr(this);
  };
  
  // Square root over p
  BN.prototype.redSqrt = function redSqrt() {
    assert(this.red, 'redSqrt works only with red numbers');
    this.red._verify1(this);
    return this.red.sqrt(this);
  };
  
  BN.prototype.redInvm = function redInvm() {
    assert(this.red, 'redInvm works only with red numbers');
    this.red._verify1(this);
    return this.red.invm(this);
  };
  
  // Return negative clone of `this` % `red modulo`
  BN.prototype.redNeg = function redNeg() {
    assert(this.red, 'redNeg works only with red numbers');
    this.red._verify1(this);
    return this.red.neg(this);
  };
  
  BN.prototype.redPow = function redPow(num) {
    assert(this.red && !num.red, 'redPow(normalNum)');
    this.red._verify1(this);
    return this.red.pow(this, num);
  };
  
  // Prime numbers with efficient reduction
  var primes = {
    k256: null,
    p224: null,
    p192: null,
    p25519: null
  };
  
  // Pseudo-Mersenne prime
  function MPrime(name, p) {
    // P = 2 ^ N - K
    this.name = name;
    this.p = new BN(p, 16);
    this.n = this.p.bitLength();
    this.k = new BN(1).iushln(this.n).isub(this.p);
  
    this.tmp = this._tmp();
  }
  
  MPrime.prototype._tmp = function _tmp() {
    var tmp = new BN(null);
    tmp.words = new Array(Math.ceil(this.n / 13));
    return tmp;
  };
  
  MPrime.prototype.ireduce = function ireduce(num) {
    // Assumes that `num` is less than `P^2`
    // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
    var r = num;
    var rlen;
  
    do {
      this.split(r, this.tmp);
      r = this.imulK(r);
      r = r.iadd(this.tmp);
      rlen = r.bitLength();
    } while (rlen > this.n);
  
    var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
    if (cmp === 0) {
      r.words[0] = 0;
      r.length = 1;
    } else if (cmp > 0) {
      r.isub(this.p);
    } else {
      r.strip();
    }
  
    return r;
  };
  
  MPrime.prototype.split = function split(input, out) {
    input.iushrn(this.n, 0, out);
  };
  
  MPrime.prototype.imulK = function imulK(num) {
    return num.imul(this.k);
  };
  
  function K256() {
    MPrime.call(
      this,
      'k256',
      'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
  }
  inherits(K256, MPrime);
  
  K256.prototype.split = function split(input, output) {
    // 256 = 9 * 26 + 22
    var mask = 0x3fffff;
  
    var outLen = Math.min(input.length, 9);
    for (var i = 0; i < outLen; i++)
      output.words[i] = input.words[i];
    output.length = outLen;
  
    if (input.length <= 9) {
      input.words[0] = 0;
      input.length = 1;
      return;
    }
  
    // Shift by 9 limbs
    var prev = input.words[9];
    output.words[output.length++] = prev & mask;
  
    for (var i = 10; i < input.length; i++) {
      var next = input.words[i];
      input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
      prev = next;
    }
    input.words[i - 10] = prev >>> 22;
    input.length -= 9;
  };
  
  K256.prototype.imulK = function imulK(num) {
    // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
    num.words[num.length] = 0;
    num.words[num.length + 1] = 0;
    num.length += 2;
  
    // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
    var hi;
    var lo = 0;
    for (var i = 0; i < num.length; i++) {
      var w = num.words[i];
      hi = w * 0x40;
      lo += w * 0x3d1;
      hi += (lo / 0x4000000) | 0;
      lo &= 0x3ffffff;
  
      num.words[i] = lo;
  
      lo = hi;
    }
  
    // Fast length reduction
    if (num.words[num.length - 1] === 0) {
      num.length--;
      if (num.words[num.length - 1] === 0)
        num.length--;
    }
    return num;
  };
  
  function P224() {
    MPrime.call(
      this,
      'p224',
      'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
  }
  inherits(P224, MPrime);
  
  function P192() {
    MPrime.call(
      this,
      'p192',
      'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
  }
  inherits(P192, MPrime);
  
  function P25519() {
    // 2 ^ 255 - 19
    MPrime.call(
      this,
      '25519',
      '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
  }
  inherits(P25519, MPrime);
  
  P25519.prototype.imulK = function imulK(num) {
    // K = 0x13
    var carry = 0;
    for (var i = 0; i < num.length; i++) {
      var hi = num.words[i] * 0x13 + carry;
      var lo = hi & 0x3ffffff;
      hi >>>= 26;
  
      num.words[i] = lo;
      carry = hi;
    }
    if (carry !== 0)
      num.words[num.length++] = carry;
    return num;
  };
  
  // Exported mostly for testing purposes, use plain name instead
  BN._prime = function prime(name) {
    // Cached version of prime
    if (primes[name])
      return primes[name];
  
    var prime;
    if (name === 'k256')
      prime = new K256();
    else if (name === 'p224')
      prime = new P224();
    else if (name === 'p192')
      prime = new P192();
    else if (name === 'p25519')
      prime = new P25519();
    else
      throw new Error('Unknown prime ' + name);
    primes[name] = prime;
  
    return prime;
  };
  
  //
  // Base reduction engine
  //
  function Red(m) {
    if (typeof m === 'string') {
      var prime = BN._prime(m);
      this.m = prime.p;
      this.prime = prime;
    } else {
      this.m = m;
      this.prime = null;
    }
  }
  
  Red.prototype._verify1 = function _verify1(a) {
    assert(!a.sign, 'red works only with positives');
    assert(a.red, 'red works only with red numbers');
  };
  
  Red.prototype._verify2 = function _verify2(a, b) {
    assert(!a.sign && !b.sign, 'red works only with positives');
    assert(a.red && a.red === b.red,
           'red works only with red numbers');
  };
  
  Red.prototype.imod = function imod(a) {
    if (this.prime)
      return this.prime.ireduce(a)._forceRed(this);
    return a.umod(this.m)._forceRed(this);
  };
  
  Red.prototype.neg = function neg(a) {
    var r = a.clone();
    r.sign = !r.sign;
    return r.iadd(this.m)._forceRed(this);
  };
  
  Red.prototype.add = function add(a, b) {
    this._verify2(a, b);
  
    var res = a.add(b);
    if (res.cmp(this.m) >= 0)
      res.isub(this.m);
    return res._forceRed(this);
  };
  
  Red.prototype.iadd = function iadd(a, b) {
    this._verify2(a, b);
  
    var res = a.iadd(b);
    if (res.cmp(this.m) >= 0)
      res.isub(this.m);
    return res;
  };
  
  Red.prototype.sub = function sub(a, b) {
    this._verify2(a, b);
  
    var res = a.sub(b);
    if (res.cmpn(0) < 0)
      res.iadd(this.m);
    return res._forceRed(this);
  };
  
  Red.prototype.isub = function isub(a, b) {
    this._verify2(a, b);
  
    var res = a.isub(b);
    if (res.cmpn(0) < 0)
      res.iadd(this.m);
    return res;
  };
  
  Red.prototype.shl = function shl(a, num) {
    this._verify1(a);
    return this.imod(a.ushln(num));
  };
  
  Red.prototype.imul = function imul(a, b) {
    this._verify2(a, b);
    return this.imod(a.imul(b));
  };
  
  Red.prototype.mul = function mul(a, b) {
    this._verify2(a, b);
    return this.imod(a.mul(b));
  };
  
  Red.prototype.isqr = function isqr(a) {
    return this.imul(a, a);
  };
  
  Red.prototype.sqr = function sqr(a) {
    return this.mul(a, a);
  };
  
  Red.prototype.sqrt = function sqrt(a) {
    if (a.cmpn(0) === 0)
      return a.clone();
  
    var mod3 = this.m.andln(3);
    assert(mod3 % 2 === 1);
  
    // Fast case
    if (mod3 === 3) {
      var pow = this.m.add(new BN(1)).iushrn(2);
      var r = this.pow(a, pow);
      return r;
    }
  
    // Tonelli-Shanks algorithm (Totally unoptimized and slow)
    //
    // Find Q and S, that Q * 2 ^ S = (P - 1)
    var q = this.m.subn(1);
    var s = 0;
    while (q.cmpn(0) !== 0 && q.andln(1) === 0) {
      s++;
      q.iushrn(1);
    }
    assert(q.cmpn(0) !== 0);
  
    var one = new BN(1).toRed(this);
    var nOne = one.redNeg();
  
    // Find quadratic non-residue
    // NOTE: Max is such because of generalized Riemann hypothesis.
    var lpow = this.m.subn(1).iushrn(1);
    var z = this.m.bitLength();
    z = new BN(2 * z * z).toRed(this);
    while (this.pow(z, lpow).cmp(nOne) !== 0)
      z.redIAdd(nOne);
  
    var c = this.pow(z, q);
    var r = this.pow(a, q.addn(1).iushrn(1));
    var t = this.pow(a, q);
    var m = s;
    while (t.cmp(one) !== 0) {
      var tmp = t;
      for (var i = 0; tmp.cmp(one) !== 0; i++)
        tmp = tmp.redSqr();
      assert(i < m);
      var b = this.pow(c, new BN(1).iushln(m - i - 1));
  
      r = r.redMul(b);
      c = b.redSqr();
      t = t.redMul(c);
      m = i;
    }
  
    return r;
  };
  
  Red.prototype.invm = function invm(a) {
    var inv = a._invmp(this.m);
    if (inv.sign) {
      inv.sign = false;
      return this.imod(inv).redNeg();
    } else {
      return this.imod(inv);
    }
  };
  
  Red.prototype.pow = function pow(a, num) {
    var w = toBitArray(num);
    if (w.length === 0)
      return new BN(1);
  
    // Skip leading zeroes
    var res = a;
    for (var i = 0; i < w.length; i++, res = this.sqr(res))
      if (w[i] !== 0)
        break;
  
    if (++i < w.length) {
      for (var q = this.sqr(res); i < w.length; i++, q = this.sqr(q)) {
        if (w[i] === 0)
          continue;
        res = this.mul(res, q);
      }
    }
  
    return res;
  };
  
  Red.prototype.convertTo = function convertTo(num) {
    var r = num.umod(this.m);
    if (r === num)
      return r.clone();
    else
      return r;
  };
  
  Red.prototype.convertFrom = function convertFrom(num) {
    var res = num.clone();
    res.red = null;
    return res;
  };
  
  //
  // Montgomery method engine
  //
  
  BN.mont = function mont(num) {
    return new Mont(num);
  };
  
  function Mont(m) {
    Red.call(this, m);
  
    this.shift = this.m.bitLength();
    if (this.shift % 26 !== 0)
      this.shift += 26 - (this.shift % 26);
    this.r = new BN(1).iushln(this.shift);
    this.r2 = this.imod(this.r.sqr());
    this.rinv = this.r._invmp(this.m);
  
    this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
    this.minv = this.minv.umod(this.r);
    this.minv = this.r.sub(this.minv);
  }
  inherits(Mont, Red);
  
  Mont.prototype.convertTo = function convertTo(num) {
    return this.imod(num.ushln(this.shift));
  };
  
  Mont.prototype.convertFrom = function convertFrom(num) {
    var r = this.imod(num.mul(this.rinv));
    r.red = null;
    return r;
  };
  
  Mont.prototype.imul = function imul(a, b) {
    if (a.cmpn(0) === 0 || b.cmpn(0) === 0) {
      a.words[0] = 0;
      a.length = 1;
      return a;
    }
  
    var t = a.imul(b);
    var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
    var u = t.isub(c).iushrn(this.shift);
    var res = u;
    if (u.cmp(this.m) >= 0)
      res = u.isub(this.m);
    else if (u.cmpn(0) < 0)
      res = u.iadd(this.m);
  
    return res._forceRed(this);
  };
  
  Mont.prototype.mul = function mul(a, b) {
    if (a.cmpn(0) === 0 || b.cmpn(0) === 0)
      return new BN(0)._forceRed(this);
  
    var t = a.mul(b);
    var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
    var u = t.isub(c).iushrn(this.shift);
    var res = u;
    if (u.cmp(this.m) >= 0)
      res = u.isub(this.m);
    else if (u.cmpn(0) < 0)
      res = u.iadd(this.m);
  
    return res._forceRed(this);
  };
  
  Mont.prototype.invm = function invm(a) {
    // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
    var res = this.imod(a._invmp(this.m).mul(this.r2));
    return res._forceRed(this);
  };
  
  })(typeof module === 'undefined' || module, this);
  
  },{}],4:[function(require,module,exports){
  var r;
  
  module.exports = function rand(len) {
    if (!r)
      r = new Rand(null);
  
    return r.generate(len);
  };
  
  function Rand(rand) {
    this.rand = rand;
  }
  module.exports.Rand = Rand;
  
  Rand.prototype.generate = function generate(len) {
    return this._rand(len);
  };
  
  if (typeof window === 'object') {
    if (window.crypto && window.crypto.getRandomValues) {
      // Modern browsers
      Rand.prototype._rand = function _rand(n) {
        var arr = new Uint8Array(n);
        window.crypto.getRandomValues(arr);
        return arr;
      };
    } else if (window.msCrypto && window.msCrypto.getRandomValues) {
      // IE
      Rand.prototype._rand = function _rand(n) {
        var arr = new Uint8Array(n);
        window.msCrypto.getRandomValues(arr);
        return arr;
      };
    } else {
      // Old junk
      Rand.prototype._rand = function() {
        throw new Error('Not implemented yet');
      };
    }
  } else {
    // Node.js or Web worker
    try {
      var crypto = require('cry' + 'pto');
  
      Rand.prototype._rand = function _rand(n) {
        return crypto.randomBytes(n);
      };
    } catch (e) {
      // Emulate crypto API using randy
      Rand.prototype._rand = function _rand(n) {
        var res = new Uint8Array(n);
        for (var i = 0; i < res.length; i++)
          res[i] = this.rand.getByte();
        return res;
      };
    }
  }
  
  },{}],5:[function(require,module,exports){
  /*
  CryptoJS v3.1.2
  code.google.com/p/crypto-js
  (c) 2009-2013 by Jeff Mott. All rights reserved.
  code.google.com/p/crypto-js/wiki/License
  */
  (function () {
      // Shortcuts
      var C = CryptoJS;
      var C_lib = C.lib;
      var BlockCipher = C_lib.BlockCipher;
      var C_algo = C.algo;
  
      // Lookup tables
      var SBOX = [];
      var INV_SBOX = [];
      var SUB_MIX_0 = [];
      var SUB_MIX_1 = [];
      var SUB_MIX_2 = [];
      var SUB_MIX_3 = [];
      var INV_SUB_MIX_0 = [];
      var INV_SUB_MIX_1 = [];
      var INV_SUB_MIX_2 = [];
      var INV_SUB_MIX_3 = [];
  
      // Compute lookup tables
      (function () {
          // Compute double table
          var d = [];
          for (var i = 0; i < 256; i++) {
              if (i < 128) {
                  d[i] = i << 1;
              } else {
                  d[i] = (i << 1) ^ 0x11b;
              }
          }
  
          // Walk GF(2^8)
          var x = 0;
          var xi = 0;
          for (var i = 0; i < 256; i++) {
              // Compute sbox
              var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);
              sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;
              SBOX[x] = sx;
              INV_SBOX[sx] = x;
  
              // Compute multiplication
              var x2 = d[x];
              var x4 = d[x2];
              var x8 = d[x4];
  
              // Compute sub bytes, mix columns tables
              var t = (d[sx] * 0x101) ^ (sx * 0x1010100);
              SUB_MIX_0[x] = (t << 24) | (t >>> 8);
              SUB_MIX_1[x] = (t << 16) | (t >>> 16);
              SUB_MIX_2[x] = (t << 8)  | (t >>> 24);
              SUB_MIX_3[x] = t;
  
              // Compute inv sub bytes, inv mix columns tables
              var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);
              INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8);
              INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16);
              INV_SUB_MIX_2[sx] = (t << 8)  | (t >>> 24);
              INV_SUB_MIX_3[sx] = t;
  
              // Compute next counter
              if (!x) {
                  x = xi = 1;
              } else {
                  x = x2 ^ d[d[d[x8 ^ x2]]];
                  xi ^= d[d[xi]];
              }
          }
      }());
  
      // Precomputed Rcon lookup
      var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
  
      /**
       * AES block cipher algorithm.
       */
      var AES = C_algo.AES = BlockCipher.extend({
          _doReset: function () {
              // Shortcuts
              var key = this._key;
              var keyWords = key.words;
              var keySize = key.sigBytes / 4;
  
              // Compute number of rounds
              var nRounds = this._nRounds = keySize + 6
  
              // Compute number of key schedule rows
              var ksRows = (nRounds + 1) * 4;
  
              // Compute key schedule
              var keySchedule = this._keySchedule = [];
              for (var ksRow = 0; ksRow < ksRows; ksRow++) {
                  if (ksRow < keySize) {
                      keySchedule[ksRow] = keyWords[ksRow];
                  } else {
                      var t = keySchedule[ksRow - 1];
  
                      if (!(ksRow % keySize)) {
                          // Rot word
                          t = (t << 8) | (t >>> 24);
  
                          // Sub word
                          t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
  
                          // Mix Rcon
                          t ^= RCON[(ksRow / keySize) | 0] << 24;
                      } else if (keySize > 6 && ksRow % keySize == 4) {
                          // Sub word
                          t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
                      }
  
                      keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t;
                  }
              }
  
              // Compute inv key schedule
              var invKeySchedule = this._invKeySchedule = [];
              for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) {
                  var ksRow = ksRows - invKsRow;
  
                  if (invKsRow % 4) {
                      var t = keySchedule[ksRow];
                  } else {
                      var t = keySchedule[ksRow - 4];
                  }
  
                  if (invKsRow < 4 || ksRow <= 4) {
                      invKeySchedule[invKsRow] = t;
                  } else {
                      invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^
                                                 INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]];
                  }
              }
          },
  
          encryptBlock: function (M, offset) {
              this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX);
          },
  
          decryptBlock: function (M, offset) {
              // Swap 2nd and 4th rows
              var t = M[offset + 1];
              M[offset + 1] = M[offset + 3];
              M[offset + 3] = t;
  
              this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX);
  
              // Inv swap 2nd and 4th rows
              var t = M[offset + 1];
              M[offset + 1] = M[offset + 3];
              M[offset + 3] = t;
          },
  
          _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) {
              // Shortcut
              var nRounds = this._nRounds;
  
              // Get input, add round key
              var s0 = M[offset]     ^ keySchedule[0];
              var s1 = M[offset + 1] ^ keySchedule[1];
              var s2 = M[offset + 2] ^ keySchedule[2];
              var s3 = M[offset + 3] ^ keySchedule[3];
  
              // Key schedule row counter
              var ksRow = 4;
  
              // Rounds
              for (var round = 1; round < nRounds; round++) {
                  // Shift rows, sub bytes, mix columns, add round key
                  var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++];
                  var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++];
                  var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++];
                  var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++];
  
                  // Update state
                  s0 = t0;
                  s1 = t1;
                  s2 = t2;
                  s3 = t3;
              }
  
              // Shift rows, sub bytes, add round key
              var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++];
              var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++];
              var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++];
              var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++];
  
              // Set output
              M[offset]     = t0;
              M[offset + 1] = t1;
              M[offset + 2] = t2;
              M[offset + 3] = t3;
          },
  
          keySize: 256/32
      });
  
      /**
       * Shortcut functions to the cipher's object interface.
       *
       * @example
       *
       *     var ciphertext = CryptoJS.AES.encrypt(message, key, cfg);
       *     var plaintext  = CryptoJS.AES.decrypt(ciphertext, key, cfg);
       */
      C.AES = BlockCipher._createHelper(AES);
  }());
  
  },{}],6:[function(require,module,exports){
  /*
  CryptoJS v3.1.2
  code.google.com/p/crypto-js
  (c) 2009-2013 by Jeff Mott. All rights reserved.
  code.google.com/p/crypto-js/wiki/License
  */
  /**
   * Cipher core components.
   */
  CryptoJS.lib.Cipher || (function (undefined) {
      // Shortcuts
      var C = CryptoJS;
      var C_lib = C.lib;
      var Base = C_lib.Base;
      var WordArray = C_lib.WordArray;
      var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm;
      var C_enc = C.enc;
      var Utf8 = C_enc.Utf8;
      var Base64 = C_enc.Base64;
      var C_algo = C.algo;
      var EvpKDF = C_algo.EvpKDF;
  
      /**
       * Abstract base cipher template.
       *
       * @property {number} keySize This cipher's key size. Default: 4 (128 bits)
       * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits)
       * @property {number} _ENC_XFORM_MODE A constant representing encryption mode.
       * @property {number} _DEC_XFORM_MODE A constant representing decryption mode.
       */
      var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({
          /**
           * Configuration options.
           *
           * @property {WordArray} iv The IV to use for this operation.
           */
          cfg: Base.extend(),
  
          /**
           * Creates this cipher in encryption mode.
           *
           * @param {WordArray} key The key.
           * @param {Object} cfg (Optional) The configuration options to use for this operation.
           *
           * @return {Cipher} A cipher instance.
           *
           * @static
           *
           * @example
           *
           *     var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
           */
          createEncryptor: function (key, cfg) {
              return this.create(this._ENC_XFORM_MODE, key, cfg);
          },
  
          /**
           * Creates this cipher in decryption mode.
           *
           * @param {WordArray} key The key.
           * @param {Object} cfg (Optional) The configuration options to use for this operation.
           *
           * @return {Cipher} A cipher instance.
           *
           * @static
           *
           * @example
           *
           *     var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray });
           */
          createDecryptor: function (key, cfg) {
              return this.create(this._DEC_XFORM_MODE, key, cfg);
          },
  
          /**
           * Initializes a newly created cipher.
           *
           * @param {number} xformMode Either the encryption or decryption transormation mode constant.
           * @param {WordArray} key The key.
           * @param {Object} cfg (Optional) The configuration options to use for this operation.
           *
           * @example
           *
           *     var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray });
           */
          init: function (xformMode, key, cfg) {
              // Apply config defaults
              this.cfg = this.cfg.extend(cfg);
  
              // Store transform mode and key
              this._xformMode = xformMode;
              this._key = key;
  
              // Set initial values
              this.reset();
          },
  
          /**
           * Resets this cipher to its initial state.
           *
           * @example
           *
           *     cipher.reset();
           */
          reset: function () {
              // Reset data buffer
              BufferedBlockAlgorithm.reset.call(this);
  
              // Perform concrete-cipher logic
              this._doReset();
          },
  
          /**
           * Adds data to be encrypted or decrypted.
           *
           * @param {WordArray|string} dataUpdate The data to encrypt or decrypt.
           *
           * @return {WordArray} The data after processing.
           *
           * @example
           *
           *     var encrypted = cipher.process('data');
           *     var encrypted = cipher.process(wordArray);
           */
          process: function (dataUpdate) {
              // Append
              this._append(dataUpdate);
  
              // Process available blocks
              return this._process();
          },
  
          /**
           * Finalizes the encryption or decryption process.
           * Note that the finalize operation is effectively a destructive, read-once operation.
           *
           * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt.
           *
           * @return {WordArray} The data after final processing.
           *
           * @example
           *
           *     var encrypted = cipher.finalize();
           *     var encrypted = cipher.finalize('data');
           *     var encrypted = cipher.finalize(wordArray);
           */
          finalize: function (dataUpdate) {
              // Final data update
              if (dataUpdate) {
                  this._append(dataUpdate);
              }
  
              // Perform concrete-cipher logic
              var finalProcessedData = this._doFinalize();
  
              return finalProcessedData;
          },
  
          keySize: 128/32,
  
          ivSize: 128/32,
  
          _ENC_XFORM_MODE: 1,
  
          _DEC_XFORM_MODE: 2,
  
          /**
           * Creates shortcut functions to a cipher's object interface.
           *
           * @param {Cipher} cipher The cipher to create a helper for.
           *
           * @return {Object} An object with encrypt and decrypt shortcut functions.
           *
           * @static
           *
           * @example
           *
           *     var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
           */
          _createHelper: (function () {
              function selectCipherStrategy(key) {
                  if (typeof key == 'string') {
                      return PasswordBasedCipher;
                  } else {
                      return SerializableCipher;
                  }
              }
  
              return function (cipher) {
                  return {
                      encrypt: function (message, key, cfg) {
                          return selectCipherStrategy(key).encrypt(cipher, message, key, cfg);
                      },
  
                      decrypt: function (ciphertext, key, cfg) {
                          return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg);
                      }
                  };
              };
          }())
      });
  
      /**
       * Abstract base stream cipher template.
       *
       * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits)
       */
      var StreamCipher = C_lib.StreamCipher = Cipher.extend({
          _doFinalize: function () {
              // Process partial blocks
              var finalProcessedBlocks = this._process(!!'flush');
  
              return finalProcessedBlocks;
          },
  
          blockSize: 1
      });
  
      /**
       * Mode namespace.
       */
      var C_mode = C.mode = {};
  
      /**
       * Abstract base block cipher mode template.
       */
      var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({
          /**
           * Creates this mode for encryption.
           *
           * @param {Cipher} cipher A block cipher instance.
           * @param {Array} iv The IV words.
           *
           * @static
           *
           * @example
           *
           *     var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
           */
          createEncryptor: function (cipher, iv) {
              return this.Encryptor.create(cipher, iv);
          },
  
          /**
           * Creates this mode for decryption.
           *
           * @param {Cipher} cipher A block cipher instance.
           * @param {Array} iv The IV words.
           *
           * @static
           *
           * @example
           *
           *     var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
           */
          createDecryptor: function (cipher, iv) {
              return this.Decryptor.create(cipher, iv);
          },
  
          /**
           * Initializes a newly created mode.
           *
           * @param {Cipher} cipher A block cipher instance.
           * @param {Array} iv The IV words.
           *
           * @example
           *
           *     var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words);
           */
          init: function (cipher, iv) {
              this._cipher = cipher;
              this._iv = iv;
          }
      });
  
      /**
       * Cipher Block Chaining mode.
       */
      var CBC = C_mode.CBC = (function () {
          /**
           * Abstract base CBC mode.
           */
          var CBC = BlockCipherMode.extend();
  
          /**
           * CBC encryptor.
           */
          CBC.Encryptor = CBC.extend({
              /**
               * Processes the data block at offset.
               *
               * @param {Array} words The data words to operate on.
               * @param {number} offset The offset where the block starts.
               *
               * @example
               *
               *     mode.processBlock(data.words, offset);
               */
              processBlock: function (words, offset) {
                  // Shortcuts
                  var cipher = this._cipher;
                  var blockSize = cipher.blockSize;
  
                  // XOR and encrypt
                  xorBlock.call(this, words, offset, blockSize);
                  cipher.encryptBlock(words, offset);
  
                  // Remember this block to use with next block
                  this._prevBlock = words.slice(offset, offset + blockSize);
              }
          });
  
          /**
           * CBC decryptor.
           */
          CBC.Decryptor = CBC.extend({
              /**
               * Processes the data block at offset.
               *
               * @param {Array} words The data words to operate on.
               * @param {number} offset The offset where the block starts.
               *
               * @example
               *
               *     mode.processBlock(data.words, offset);
               */
              processBlock: function (words, offset) {
                  // Shortcuts
                  var cipher = this._cipher;
                  var blockSize = cipher.blockSize;
  
                  // Remember this block to use with next block
                  var thisBlock = words.slice(offset, offset + blockSize);
  
                  // Decrypt and XOR
                  cipher.decryptBlock(words, offset);
                  xorBlock.call(this, words, offset, blockSize);
  
                  // This block becomes the previous block
                  this._prevBlock = thisBlock;
              }
          });
  
          function xorBlock(words, offset, blockSize) {
              // Shortcut
              var iv = this._iv;
  
              // Choose mixing block
              if (iv) {
                  var block = iv;
  
                  // Remove IV for subsequent blocks
                  this._iv = undefined;
              } else {
                  var block = this._prevBlock;
              }
  
              // XOR blocks
              for (var i = 0; i < blockSize; i++) {
                  words[offset + i] ^= block[i];
              }
          }
  
          return CBC;
      }());
  
      /**
       * Padding namespace.
       */
      var C_pad = C.pad = {};
  
      /**
       * PKCS #5/7 padding strategy.
       */
      var Pkcs7 = C_pad.Pkcs7 = {
          /**
           * Pads data using the algorithm defined in PKCS #5/7.
           *
           * @param {WordArray} data The data to pad.
           * @param {number} blockSize The multiple that the data should be padded to.
           *
           * @static
           *
           * @example
           *
           *     CryptoJS.pad.Pkcs7.pad(wordArray, 4);
           */
          pad: function (data, blockSize) {
              // Shortcut
              var blockSizeBytes = blockSize * 4;
  
              // Count padding bytes
              var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
  
              // Create padding word
              var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes;
  
              // Create padding
              var paddingWords = [];
              for (var i = 0; i < nPaddingBytes; i += 4) {
                  paddingWords.push(paddingWord);
              }
              var padding = WordArray.create(paddingWords, nPaddingBytes);
  
              // Add padding
              data.concat(padding);
          },
  
          /**
           * Unpads data that had been padded using the algorithm defined in PKCS #5/7.
           *
           * @param {WordArray} data The data to unpad.
           *
           * @static
           *
           * @example
           *
           *     CryptoJS.pad.Pkcs7.unpad(wordArray);
           */
          unpad: function (data) {
              // Get number of padding bytes from last byte
              var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
  
              // Remove padding
              data.sigBytes -= nPaddingBytes;
          }
      };
  
      /**
       * Abstract base block cipher template.
       *
       * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits)
       */
      var BlockCipher = C_lib.BlockCipher = Cipher.extend({
          /**
           * Configuration options.
           *
           * @property {Mode} mode The block mode to use. Default: CBC
           * @property {Padding} padding The padding strategy to use. Default: Pkcs7
           */
          cfg: Cipher.cfg.extend({
              mode: CBC,
              padding: Pkcs7
          }),
  
          reset: function () {
              // Reset cipher
              Cipher.reset.call(this);
  
              // Shortcuts
              var cfg = this.cfg;
              var iv = cfg.iv;
              var mode = cfg.mode;
  
              // Reset block mode
              if (this._xformMode == this._ENC_XFORM_MODE) {
                  var modeCreator = mode.createEncryptor;
              } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
                  var modeCreator = mode.createDecryptor;
  
                  // Keep at least one block in the buffer for unpadding
                  this._minBufferSize = 1;
              }
              this._mode = modeCreator.call(mode, this, iv && iv.words);
          },
  
          _doProcessBlock: function (words, offset) {
              this._mode.processBlock(words, offset);
          },
  
          _doFinalize: function () {
              // Shortcut
              var padding = this.cfg.padding;
  
              // Finalize
              if (this._xformMode == this._ENC_XFORM_MODE) {
                  // Pad data
                  padding.pad(this._data, this.blockSize);
  
                  // Process final blocks
                  var finalProcessedBlocks = this._process(!!'flush');
              } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
                  // Process final blocks
                  var finalProcessedBlocks = this._process(!!'flush');
  
                  // Unpad data
                  padding.unpad(finalProcessedBlocks);
              }
  
              return finalProcessedBlocks;
          },
  
          blockSize: 128/32
      });
  
      /**
       * A collection of cipher parameters.
       *
       * @property {WordArray} ciphertext The raw ciphertext.
       * @property {WordArray} key The key to this ciphertext.
       * @property {WordArray} iv The IV used in the ciphering operation.
       * @property {WordArray} salt The salt used with a key derivation function.
       * @property {Cipher} algorithm The cipher algorithm.
       * @property {Mode} mode The block mode used in the ciphering operation.
       * @property {Padding} padding The padding scheme used in the ciphering operation.
       * @property {number} blockSize The block size of the cipher.
       * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string.
       */
      var CipherParams = C_lib.CipherParams = Base.extend({
          /**
           * Initializes a newly created cipher params object.
           *
           * @param {Object} cipherParams An object with any of the possible cipher parameters.
           *
           * @example
           *
           *     var cipherParams = CryptoJS.lib.CipherParams.create({
           *         ciphertext: ciphertextWordArray,
           *         key: keyWordArray,
           *         iv: ivWordArray,
           *         salt: saltWordArray,
           *         algorithm: CryptoJS.algo.AES,
           *         mode: CryptoJS.mode.CBC,
           *         padding: CryptoJS.pad.PKCS7,
           *         blockSize: 4,
           *         formatter: CryptoJS.format.OpenSSL
           *     });
           */
          init: function (cipherParams) {
              this.mixIn(cipherParams);
          },
  
          /**
           * Converts this cipher params object to a string.
           *
           * @param {Format} formatter (Optional) The formatting strategy to use.
           *
           * @return {string} The stringified cipher params.
           *
           * @throws Error If neither the formatter nor the default formatter is set.
           *
           * @example
           *
           *     var string = cipherParams + '';
           *     var string = cipherParams.toString();
           *     var string = cipherParams.toString(CryptoJS.format.OpenSSL);
           */
          toString: function (formatter) {
              return (formatter || this.formatter).stringify(this);
          }
      });
  
      /**
       * Format namespace.
       */
      var C_format = C.format = {};
  
      /**
       * OpenSSL formatting strategy.
       */
      var OpenSSLFormatter = C_format.OpenSSL = {
          /**
           * Converts a cipher params object to an OpenSSL-compatible string.
           *
           * @param {CipherParams} cipherParams The cipher params object.
           *
           * @return {string} The OpenSSL-compatible string.
           *
           * @static
           *
           * @example
           *
           *     var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams);
           */
          stringify: function (cipherParams) {
              // Shortcuts
              var ciphertext = cipherParams.ciphertext;
              var salt = cipherParams.salt;
  
              // Format
              if (salt) {
                  var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext);
              } else {
                  var wordArray = ciphertext;
              }
  
              return wordArray.toString(Base64);
          },
  
          /**
           * Converts an OpenSSL-compatible string to a cipher params object.
           *
           * @param {string} openSSLStr The OpenSSL-compatible string.
           *
           * @return {CipherParams} The cipher params object.
           *
           * @static
           *
           * @example
           *
           *     var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString);
           */
          parse: function (openSSLStr) {
              // Parse base64
              var ciphertext = Base64.parse(openSSLStr);
  
              // Shortcut
              var ciphertextWords = ciphertext.words;
  
              // Test for salt
              if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) {
                  // Extract salt
                  var salt = WordArray.create(ciphertextWords.slice(2, 4));
  
                  // Remove salt from ciphertext
                  ciphertextWords.splice(0, 4);
                  ciphertext.sigBytes -= 16;
              }
  
              return CipherParams.create({ ciphertext: ciphertext, salt: salt });
          }
      };
  
      /**
       * A cipher wrapper that returns ciphertext as a serializable cipher params object.
       */
      var SerializableCipher = C_lib.SerializableCipher = Base.extend({
          /**
           * Configuration options.
           *
           * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL
           */
          cfg: Base.extend({
              format: OpenSSLFormatter
          }),
  
          /**
           * Encrypts a message.
           *
           * @param {Cipher} cipher The cipher algorithm to use.
           * @param {WordArray|string} message The message to encrypt.
           * @param {WordArray} key The key.
           * @param {Object} cfg (Optional) The configuration options to use for this operation.
           *
           * @return {CipherParams} A cipher params object.
           *
           * @static
           *
           * @example
           *
           *     var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key);
           *     var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv });
           *     var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL });
           */
          encrypt: function (cipher, message, key, cfg) {
              // Apply config defaults
              cfg = this.cfg.extend(cfg);
  
              // Encrypt
              var encryptor = cipher.createEncryptor(key, cfg);
              var ciphertext = encryptor.finalize(message);
  
              // Shortcut
              var cipherCfg = encryptor.cfg;
  
              // Create and return serializable cipher params
              return CipherParams.create({
                  ciphertext: ciphertext,
                  key: key,
                  iv: cipherCfg.iv,
                  algorithm: cipher,
                  mode: cipherCfg.mode,
                  padding: cipherCfg.padding,
                  blockSize: cipher.blockSize,
                  formatter: cfg.format
              });
          },
  
          /**
           * Decrypts serialized ciphertext.
           *
           * @param {Cipher} cipher The cipher algorithm to use.
           * @param {CipherParams|string} ciphertext The ciphertext to decrypt.
           * @param {WordArray} key The key.
           * @param {Object} cfg (Optional) The configuration options to use for this operation.
           *
           * @return {WordArray} The plaintext.
           *
           * @static
           *
           * @example
           *
           *     var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL });
           *     var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL });
           */
          decrypt: function (cipher, ciphertext, key, cfg) {
              // Apply config defaults
              cfg = this.cfg.extend(cfg);
  
              // Convert string to CipherParams
              ciphertext = this._parse(ciphertext, cfg.format);
  
              // Decrypt
              var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext);
  
              return plaintext;
          },
  
          /**
           * Converts serialized ciphertext to CipherParams,
           * else assumed CipherParams already and returns ciphertext unchanged.
           *
           * @param {CipherParams|string} ciphertext The ciphertext.
           * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext.
           *
           * @return {CipherParams} The unserialized ciphertext.
           *
           * @static
           *
           * @example
           *
           *     var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format);
           */
          _parse: function (ciphertext, format) {
              if (typeof ciphertext == 'string') {
                  return format.parse(ciphertext, this);
              } else {
                  return ciphertext;
              }
          }
      });
  
      /**
       * Key derivation function namespace.
       */
      var C_kdf = C.kdf = {};
  
      /**
       * OpenSSL key derivation function.
       */
      var OpenSSLKdf = C_kdf.OpenSSL = {
          /**
           * Derives a key and IV from a password.
           *
           * @param {string} password The password to derive from.
           * @param {number} keySize The size in words of the key to generate.
           * @param {number} ivSize The size in words of the IV to generate.
           * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly.
           *
           * @return {CipherParams} A cipher params object with the key, IV, and salt.
           *
           * @static
           *
           * @example
           *
           *     var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32);
           *     var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
           */
          execute: function (password, keySize, ivSize, salt) {
              // Generate random salt
              if (!salt) {
                  salt = WordArray.random(64/8);
              }
  
              // Derive key and IV
              var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt);
  
              // Separate key and IV
              var iv = WordArray.create(key.words.slice(keySize), ivSize * 4);
              key.sigBytes = keySize * 4;
  
              // Return params
              return CipherParams.create({ key: key, iv: iv, salt: salt });
          }
      };
  
      /**
       * A serializable cipher wrapper that derives the key from a password,
       * and returns ciphertext as a serializable cipher params object.
       */
      var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({
          /**
           * Configuration options.
           *
           * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL
           */
          cfg: SerializableCipher.cfg.extend({
              kdf: OpenSSLKdf
          }),
  
          /**
           * Encrypts a message using a password.
           *
           * @param {Cipher} cipher The cipher algorithm to use.
           * @param {WordArray|string} message The message to encrypt.
           * @param {string} password The password.
           * @param {Object} cfg (Optional) The configuration options to use for this operation.
           *
           * @return {CipherParams} A cipher params object.
           *
           * @static
           *
           * @example
           *
           *     var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password');
           *     var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL });
           */
          encrypt: function (cipher, message, password, cfg) {
              // Apply config defaults
              cfg = this.cfg.extend(cfg);
  
              // Derive key and other params
              var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize);
  
              // Add IV to config
              cfg.iv = derivedParams.iv;
  
              // Encrypt
              var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg);
  
              // Mix in derived params
              ciphertext.mixIn(derivedParams);
  
              return ciphertext;
          },
  
          /**
           * Decrypts serialized ciphertext using a password.
           *
           * @param {Cipher} cipher The cipher algorithm to use.
           * @param {CipherParams|string} ciphertext The ciphertext to decrypt.
           * @param {string} password The password.
           * @param {Object} cfg (Optional) The configuration options to use for this operation.
           *
           * @return {WordArray} The plaintext.
           *
           * @static
           *
           * @example
           *
           *     var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL });
           *     var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL });
           */
          decrypt: function (cipher, ciphertext, password, cfg) {
              // Apply config defaults
              cfg = this.cfg.extend(cfg);
  
              // Convert string to CipherParams
              ciphertext = this._parse(ciphertext, cfg.format);
  
              // Derive key and other params
              var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt);
  
              // Add IV to config
              cfg.iv = derivedParams.iv;
  
              // Decrypt
              var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg);
  
              return plaintext;
          }
      });
  }());
  
  },{}],7:[function(require,module,exports){
  /*
  CryptoJS v3.1.2
  code.google.com/p/crypto-js
  (c) 2009-2013 by Jeff Mott. All rights reserved.
  code.google.com/p/crypto-js/wiki/License
  */
  (function () {
      // Shortcuts
      var C = CryptoJS;
      var C_lib = C.lib;
      var WordArray = C_lib.WordArray;
      var C_enc = C.enc;
  
      /**
       * Base64 encoding strategy.
       */
      var Base64 = C_enc.Base64 = {
          /**
           * Converts a word array to a Base64 string.
           *
           * @param {WordArray} wordArray The word array.
           *
           * @return {string} The Base64 string.
           *
           * @static
           *
           * @example
           *
           *     var base64String = CryptoJS.enc.Base64.stringify(wordArray);
           */
          stringify: function (wordArray) {
              // Shortcuts
              var words = wordArray.words;
              var sigBytes = wordArray.sigBytes;
              var map = this._map;
  
              // Clamp excess bits
              wordArray.clamp();
  
              // Convert
              var base64Chars = [];
              for (var i = 0; i < sigBytes; i += 3) {
                  var byte1 = (words[i >>> 2]       >>> (24 - (i % 4) * 8))       & 0xff;
                  var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;
                  var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;
  
                  var triplet = (byte1 << 16) | (byte2 << 8) | byte3;
  
                  for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) {
                      base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));
                  }
              }
  
              // Add padding
              var paddingChar = map.charAt(64);
              if (paddingChar) {
                  while (base64Chars.length % 4) {
                      base64Chars.push(paddingChar);
                  }
              }
  
              return base64Chars.join('');
          },
  
          /**
           * Converts a Base64 string to a word array.
           *
           * @param {string} base64Str The Base64 string.
           *
           * @return {WordArray} The word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.enc.Base64.parse(base64String);
           */
          parse: function (base64Str) {
              // Shortcuts
              var base64StrLength = base64Str.length;
              var map = this._map;
  
              // Ignore padding
              var paddingChar = map.charAt(64);
              if (paddingChar) {
                  var paddingIndex = base64Str.indexOf(paddingChar);
                  if (paddingIndex != -1) {
                      base64StrLength = paddingIndex;
                  }
              }
  
              // Convert
              var words = [];
              var nBytes = 0;
              for (var i = 0; i < base64StrLength; i++) {
                  if (i % 4) {
                      var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2);
                      var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2);
                      words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8);
                      nBytes++;
                  }
              }
  
              return WordArray.create(words, nBytes);
          },
  
          _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
      };
  }());
  
  },{}],8:[function(require,module,exports){
  /*
  CryptoJS v3.1.2
  code.google.com/p/crypto-js
  (c) 2009-2013 by Jeff Mott. All rights reserved.
  code.google.com/p/crypto-js/wiki/License
  */
  (function () {
      // Shortcuts
      var C = CryptoJS;
      var C_lib = C.lib;
      var Base = C_lib.Base;
      var WordArray = C_lib.WordArray;
      var C_algo = C.algo;
      var MD5 = C_algo.MD5;
  
      /**
       * This key derivation function is meant to conform with EVP_BytesToKey.
       * www.openssl.org/docs/crypto/EVP_BytesToKey.html
       */
      var EvpKDF = C_algo.EvpKDF = Base.extend({
          /**
           * Configuration options.
           *
           * @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
           * @property {Hasher} hasher The hash algorithm to use. Default: MD5
           * @property {number} iterations The number of iterations to perform. Default: 1
           */
          cfg: Base.extend({
              keySize: 128/32,
              hasher: MD5,
              iterations: 1
          }),
  
          /**
           * Initializes a newly created key derivation function.
           *
           * @param {Object} cfg (Optional) The configuration options to use for the derivation.
           *
           * @example
           *
           *     var kdf = CryptoJS.algo.EvpKDF.create();
           *     var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 });
           *     var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 });
           */
          init: function (cfg) {
              this.cfg = this.cfg.extend(cfg);
          },
  
          /**
           * Derives a key from a password.
           *
           * @param {WordArray|string} password The password.
           * @param {WordArray|string} salt A salt.
           *
           * @return {WordArray} The derived key.
           *
           * @example
           *
           *     var key = kdf.compute(password, salt);
           */
          compute: function (password, salt) {
              // Shortcut
              var cfg = this.cfg;
  
              // Init hasher
              var hasher = cfg.hasher.create();
  
              // Initial values
              var derivedKey = WordArray.create();
  
              // Shortcuts
              var derivedKeyWords = derivedKey.words;
              var keySize = cfg.keySize;
              var iterations = cfg.iterations;
  
              // Generate key
              while (derivedKeyWords.length < keySize) {
                  if (block) {
                      hasher.update(block);
                  }
                  var block = hasher.update(password).finalize(salt);
                  hasher.reset();
  
                  // Iterations
                  for (var i = 1; i < iterations; i++) {
                      block = hasher.finalize(block);
                      hasher.reset();
                  }
  
                  derivedKey.concat(block);
              }
              derivedKey.sigBytes = keySize * 4;
  
              return derivedKey;
          }
      });
  
      /**
       * Derives a key from a password.
       *
       * @param {WordArray|string} password The password.
       * @param {WordArray|string} salt A salt.
       * @param {Object} cfg (Optional) The configuration options to use for this computation.
       *
       * @return {WordArray} The derived key.
       *
       * @static
       *
       * @example
       *
       *     var key = CryptoJS.EvpKDF(password, salt);
       *     var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 });
       *     var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 });
       */
      C.EvpKDF = function (password, salt, cfg) {
          return EvpKDF.create(cfg).compute(password, salt);
      };
  }());
  
  },{}],9:[function(require,module,exports){
  /*
  CryptoJS v3.1.2
  code.google.com/p/crypto-js
  (c) 2009-2013 by Jeff Mott. All rights reserved.
  code.google.com/p/crypto-js/wiki/License
  */
  (function (Math) {
      // Shortcuts
      var C = CryptoJS;
      var C_lib = C.lib;
      var WordArray = C_lib.WordArray;
      var Hasher = C_lib.Hasher;
      var C_algo = C.algo;
  
      // Constants table
      var T = [];
  
      // Compute constants
      (function () {
          for (var i = 0; i < 64; i++) {
              T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0;
          }
      }());
  
      /**
       * MD5 hash algorithm.
       */
      var MD5 = C_algo.MD5 = Hasher.extend({
          _doReset: function () {
              this._hash = new WordArray.init([
                  0x67452301, 0xefcdab89,
                  0x98badcfe, 0x10325476
              ]);
          },
  
          _doProcessBlock: function (M, offset) {
              // Swap endian
              for (var i = 0; i < 16; i++) {
                  // Shortcuts
                  var offset_i = offset + i;
                  var M_offset_i = M[offset_i];
  
                  M[offset_i] = (
                      (((M_offset_i << 8)  | (M_offset_i >>> 24)) & 0x00ff00ff) |
                      (((M_offset_i << 24) | (M_offset_i >>> 8))  & 0xff00ff00)
                  );
              }
  
              // Shortcuts
              var H = this._hash.words;
  
              var M_offset_0  = M[offset + 0];
              var M_offset_1  = M[offset + 1];
              var M_offset_2  = M[offset + 2];
              var M_offset_3  = M[offset + 3];
              var M_offset_4  = M[offset + 4];
              var M_offset_5  = M[offset + 5];
              var M_offset_6  = M[offset + 6];
              var M_offset_7  = M[offset + 7];
              var M_offset_8  = M[offset + 8];
              var M_offset_9  = M[offset + 9];
              var M_offset_10 = M[offset + 10];
              var M_offset_11 = M[offset + 11];
              var M_offset_12 = M[offset + 12];
              var M_offset_13 = M[offset + 13];
              var M_offset_14 = M[offset + 14];
              var M_offset_15 = M[offset + 15];
  
              // Working varialbes
              var a = H[0];
              var b = H[1];
              var c = H[2];
              var d = H[3];
  
              // Computation
              a = FF(a, b, c, d, M_offset_0,  7,  T[0]);
              d = FF(d, a, b, c, M_offset_1,  12, T[1]);
              c = FF(c, d, a, b, M_offset_2,  17, T[2]);
              b = FF(b, c, d, a, M_offset_3,  22, T[3]);
              a = FF(a, b, c, d, M_offset_4,  7,  T[4]);
              d = FF(d, a, b, c, M_offset_5,  12, T[5]);
              c = FF(c, d, a, b, M_offset_6,  17, T[6]);
              b = FF(b, c, d, a, M_offset_7,  22, T[7]);
              a = FF(a, b, c, d, M_offset_8,  7,  T[8]);
              d = FF(d, a, b, c, M_offset_9,  12, T[9]);
              c = FF(c, d, a, b, M_offset_10, 17, T[10]);
              b = FF(b, c, d, a, M_offset_11, 22, T[11]);
              a = FF(a, b, c, d, M_offset_12, 7,  T[12]);
              d = FF(d, a, b, c, M_offset_13, 12, T[13]);
              c = FF(c, d, a, b, M_offset_14, 17, T[14]);
              b = FF(b, c, d, a, M_offset_15, 22, T[15]);
  
              a = GG(a, b, c, d, M_offset_1,  5,  T[16]);
              d = GG(d, a, b, c, M_offset_6,  9,  T[17]);
              c = GG(c, d, a, b, M_offset_11, 14, T[18]);
              b = GG(b, c, d, a, M_offset_0,  20, T[19]);
              a = GG(a, b, c, d, M_offset_5,  5,  T[20]);
              d = GG(d, a, b, c, M_offset_10, 9,  T[21]);
              c = GG(c, d, a, b, M_offset_15, 14, T[22]);
              b = GG(b, c, d, a, M_offset_4,  20, T[23]);
              a = GG(a, b, c, d, M_offset_9,  5,  T[24]);
              d = GG(d, a, b, c, M_offset_14, 9,  T[25]);
              c = GG(c, d, a, b, M_offset_3,  14, T[26]);
              b = GG(b, c, d, a, M_offset_8,  20, T[27]);
              a = GG(a, b, c, d, M_offset_13, 5,  T[28]);
              d = GG(d, a, b, c, M_offset_2,  9,  T[29]);
              c = GG(c, d, a, b, M_offset_7,  14, T[30]);
              b = GG(b, c, d, a, M_offset_12, 20, T[31]);
  
              a = HH(a, b, c, d, M_offset_5,  4,  T[32]);
              d = HH(d, a, b, c, M_offset_8,  11, T[33]);
              c = HH(c, d, a, b, M_offset_11, 16, T[34]);
              b = HH(b, c, d, a, M_offset_14, 23, T[35]);
              a = HH(a, b, c, d, M_offset_1,  4,  T[36]);
              d = HH(d, a, b, c, M_offset_4,  11, T[37]);
              c = HH(c, d, a, b, M_offset_7,  16, T[38]);
              b = HH(b, c, d, a, M_offset_10, 23, T[39]);
              a = HH(a, b, c, d, M_offset_13, 4,  T[40]);
              d = HH(d, a, b, c, M_offset_0,  11, T[41]);
              c = HH(c, d, a, b, M_offset_3,  16, T[42]);
              b = HH(b, c, d, a, M_offset_6,  23, T[43]);
              a = HH(a, b, c, d, M_offset_9,  4,  T[44]);
              d = HH(d, a, b, c, M_offset_12, 11, T[45]);
              c = HH(c, d, a, b, M_offset_15, 16, T[46]);
              b = HH(b, c, d, a, M_offset_2,  23, T[47]);
  
              a = II(a, b, c, d, M_offset_0,  6,  T[48]);
              d = II(d, a, b, c, M_offset_7,  10, T[49]);
              c = II(c, d, a, b, M_offset_14, 15, T[50]);
              b = II(b, c, d, a, M_offset_5,  21, T[51]);
              a = II(a, b, c, d, M_offset_12, 6,  T[52]);
              d = II(d, a, b, c, M_offset_3,  10, T[53]);
              c = II(c, d, a, b, M_offset_10, 15, T[54]);
              b = II(b, c, d, a, M_offset_1,  21, T[55]);
              a = II(a, b, c, d, M_offset_8,  6,  T[56]);
              d = II(d, a, b, c, M_offset_15, 10, T[57]);
              c = II(c, d, a, b, M_offset_6,  15, T[58]);
              b = II(b, c, d, a, M_offset_13, 21, T[59]);
              a = II(a, b, c, d, M_offset_4,  6,  T[60]);
              d = II(d, a, b, c, M_offset_11, 10, T[61]);
              c = II(c, d, a, b, M_offset_2,  15, T[62]);
              b = II(b, c, d, a, M_offset_9,  21, T[63]);
  
              // Intermediate hash value
              H[0] = (H[0] + a) | 0;
              H[1] = (H[1] + b) | 0;
              H[2] = (H[2] + c) | 0;
              H[3] = (H[3] + d) | 0;
          },
  
          _doFinalize: function () {
              // Shortcuts
              var data = this._data;
              var dataWords = data.words;
  
              var nBitsTotal = this._nDataBytes * 8;
              var nBitsLeft = data.sigBytes * 8;
  
              // Add padding
              dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
  
              var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000);
              var nBitsTotalL = nBitsTotal;
              dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = (
                  (((nBitsTotalH << 8)  | (nBitsTotalH >>> 24)) & 0x00ff00ff) |
                  (((nBitsTotalH << 24) | (nBitsTotalH >>> 8))  & 0xff00ff00)
              );
              dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
                  (((nBitsTotalL << 8)  | (nBitsTotalL >>> 24)) & 0x00ff00ff) |
                  (((nBitsTotalL << 24) | (nBitsTotalL >>> 8))  & 0xff00ff00)
              );
  
              data.sigBytes = (dataWords.length + 1) * 4;
  
              // Hash final blocks
              this._process();
  
              // Shortcuts
              var hash = this._hash;
              var H = hash.words;
  
              // Swap endian
              for (var i = 0; i < 4; i++) {
                  // Shortcut
                  var H_i = H[i];
  
                  H[i] = (((H_i << 8)  | (H_i >>> 24)) & 0x00ff00ff) |
                         (((H_i << 24) | (H_i >>> 8))  & 0xff00ff00);
              }
  
              // Return final computed hash
              return hash;
          },
  
          clone: function () {
              var clone = Hasher.clone.call(this);
              clone._hash = this._hash.clone();
  
              return clone;
          }
      });
  
      function FF(a, b, c, d, x, s, t) {
          var n = a + ((b & c) | (~b & d)) + x + t;
          return ((n << s) | (n >>> (32 - s))) + b;
      }
  
      function GG(a, b, c, d, x, s, t) {
          var n = a + ((b & d) | (c & ~d)) + x + t;
          return ((n << s) | (n >>> (32 - s))) + b;
      }
  
      function HH(a, b, c, d, x, s, t) {
          var n = a + (b ^ c ^ d) + x + t;
          return ((n << s) | (n >>> (32 - s))) + b;
      }
  
      function II(a, b, c, d, x, s, t) {
          var n = a + (c ^ (b | ~d)) + x + t;
          return ((n << s) | (n >>> (32 - s))) + b;
      }
  
      /**
       * Shortcut function to the hasher's object interface.
       *
       * @param {WordArray|string} message The message to hash.
       *
       * @return {WordArray} The hash.
       *
       * @static
       *
       * @example
       *
       *     var hash = CryptoJS.MD5('message');
       *     var hash = CryptoJS.MD5(wordArray);
       */
      C.MD5 = Hasher._createHelper(MD5);
  
      /**
       * Shortcut function to the HMAC's object interface.
       *
       * @param {WordArray|string} message The message to hash.
       * @param {WordArray|string} key The secret key.
       *
       * @return {WordArray} The HMAC.
       *
       * @static
       *
       * @example
       *
       *     var hmac = CryptoJS.HmacMD5(message, key);
       */
      C.HmacMD5 = Hasher._createHmacHelper(MD5);
  }(Math));
  
  },{}],10:[function(require,module,exports){
  /*
  CryptoJS v3.1.2
  code.google.com/p/crypto-js
  (c) 2009-2013 by Jeff Mott. All rights reserved.
  code.google.com/p/crypto-js/wiki/License
  */
  /**
   * CryptoJS core components.
   */
  var CryptoJS = CryptoJS || (function (Math, undefined) {
      /**
       * CryptoJS namespace.
       */
      var C = {};
  
      /**
       * Library namespace.
       */
      var C_lib = C.lib = {};
  
      /**
       * Base object for prototypal inheritance.
       */
      var Base = C_lib.Base = (function () {
          function F() {}
  
          return {
              /**
               * Creates a new object that inherits from this object.
               *
               * @param {Object} overrides Properties to copy into the new object.
               *
               * @return {Object} The new object.
               *
               * @static
               *
               * @example
               *
               *     var MyType = CryptoJS.lib.Base.extend({
               *         field: 'value',
               *
               *         method: function () {
               *         }
               *     });
               */
              extend: function (overrides) {
                  // Spawn
                  F.prototype = this;
                  var subtype = new F();
  
                  // Augment
                  if (overrides) {
                      subtype.mixIn(overrides);
                  }
  
                  // Create default initializer
                  if (!subtype.hasOwnProperty('init')) {
                      subtype.init = function () {
                          subtype.$super.init.apply(this, arguments);
                      };
                  }
  
                  // Initializer's prototype is the subtype object
                  subtype.init.prototype = subtype;
  
                  // Reference supertype
                  subtype.$super = this;
  
                  return subtype;
              },
  
              /**
               * Extends this object and runs the init method.
               * Arguments to create() will be passed to init().
               *
               * @return {Object} The new object.
               *
               * @static
               *
               * @example
               *
               *     var instance = MyType.create();
               */
              create: function () {
                  var instance = this.extend();
                  instance.init.apply(instance, arguments);
  
                  return instance;
              },
  
              /**
               * Initializes a newly created object.
               * Override this method to add some logic when your objects are created.
               *
               * @example
               *
               *     var MyType = CryptoJS.lib.Base.extend({
               *         init: function () {
               *             // ...
               *         }
               *     });
               */
              init: function () {
              },
  
              /**
               * Copies properties into this object.
               *
               * @param {Object} properties The properties to mix in.
               *
               * @example
               *
               *     MyType.mixIn({
               *         field: 'value'
               *     });
               */
              mixIn: function (properties) {
                  for (var propertyName in properties) {
                      if (properties.hasOwnProperty(propertyName)) {
                          this[propertyName] = properties[propertyName];
                      }
                  }
  
                  // IE won't copy toString using the loop above
                  if (properties.hasOwnProperty('toString')) {
                      this.toString = properties.toString;
                  }
              },
  
              /**
               * Creates a copy of this object.
               *
               * @return {Object} The clone.
               *
               * @example
               *
               *     var clone = instance.clone();
               */
              clone: function () {
                  return this.init.prototype.extend(this);
              }
          };
      }());
  
      /**
       * An array of 32-bit words.
       *
       * @property {Array} words The array of 32-bit words.
       * @property {number} sigBytes The number of significant bytes in this word array.
       */
      var WordArray = C_lib.WordArray = Base.extend({
          /**
           * Initializes a newly created word array.
           *
           * @param {Array} words (Optional) An array of 32-bit words.
           * @param {number} sigBytes (Optional) The number of significant bytes in the words.
           *
           * @example
           *
           *     var wordArray = CryptoJS.lib.WordArray.create();
           *     var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
           *     var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
           */
          init: function (words, sigBytes) {
              words = this.words = words || [];
  
              if (sigBytes != undefined) {
                  this.sigBytes = sigBytes;
              } else {
                  this.sigBytes = words.length * 4;
              }
          },
  
          /**
           * Converts this word array to a string.
           *
           * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
           *
           * @return {string} The stringified word array.
           *
           * @example
           *
           *     var string = wordArray + '';
           *     var string = wordArray.toString();
           *     var string = wordArray.toString(CryptoJS.enc.Utf8);
           */
          toString: function (encoder) {
              return (encoder || Hex).stringify(this);
          },
  
          /**
           * Concatenates a word array to this word array.
           *
           * @param {WordArray} wordArray The word array to append.
           *
           * @return {WordArray} This word array.
           *
           * @example
           *
           *     wordArray1.concat(wordArray2);
           */
          concat: function (wordArray) {
              // Shortcuts
              var thisWords = this.words;
              var thatWords = wordArray.words;
              var thisSigBytes = this.sigBytes;
              var thatSigBytes = wordArray.sigBytes;
  
              // Clamp excess bits
              this.clamp();
  
              // Concat
              if (thisSigBytes % 4) {
                  // Copy one byte at a time
                  for (var i = 0; i < thatSigBytes; i++) {
                      var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
                      thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
                  }
              } else if (thatWords.length > 0xffff) {
                  // Copy one word at a time
                  for (var i = 0; i < thatSigBytes; i += 4) {
                      thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2];
                  }
              } else {
                  // Copy all words at once
                  thisWords.push.apply(thisWords, thatWords);
              }
              this.sigBytes += thatSigBytes;
  
              // Chainable
              return this;
          },
  
          /**
           * Removes insignificant bits.
           *
           * @example
           *
           *     wordArray.clamp();
           */
          clamp: function () {
              // Shortcuts
              var words = this.words;
              var sigBytes = this.sigBytes;
  
              // Clamp
              words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
              words.length = Math.ceil(sigBytes / 4);
          },
  
          /**
           * Creates a copy of this word array.
           *
           * @return {WordArray} The clone.
           *
           * @example
           *
           *     var clone = wordArray.clone();
           */
          clone: function () {
              var clone = Base.clone.call(this);
              clone.words = this.words.slice(0);
  
              return clone;
          },
  
          /**
           * Creates a word array filled with random bytes.
           *
           * @param {number} nBytes The number of random bytes to generate.
           *
           * @return {WordArray} The random word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.lib.WordArray.random(16);
           */
          random: function (nBytes) {
              var words = [];
              for (var i = 0; i < nBytes; i += 4) {
                  words.push((Math.random() * 0x100000000) | 0);
              }
  
              return new WordArray.init(words, nBytes);
          }
      });
  
      /**
       * Encoder namespace.
       */
      var C_enc = C.enc = {};
  
      /**
       * Hex encoding strategy.
       */
      var Hex = C_enc.Hex = {
          /**
           * Converts a word array to a hex string.
           *
           * @param {WordArray} wordArray The word array.
           *
           * @return {string} The hex string.
           *
           * @static
           *
           * @example
           *
           *     var hexString = CryptoJS.enc.Hex.stringify(wordArray);
           */
          stringify: function (wordArray) {
              // Shortcuts
              var words = wordArray.words;
              var sigBytes = wordArray.sigBytes;
  
              // Convert
              var hexChars = [];
              for (var i = 0; i < sigBytes; i++) {
                  var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
                  hexChars.push((bite >>> 4).toString(16));
                  hexChars.push((bite & 0x0f).toString(16));
              }
  
              return hexChars.join('');
          },
  
          /**
           * Converts a hex string to a word array.
           *
           * @param {string} hexStr The hex string.
           *
           * @return {WordArray} The word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.enc.Hex.parse(hexString);
           */
          parse: function (hexStr) {
              // Shortcut
              var hexStrLength = hexStr.length;
  
              // Convert
              var words = [];
              for (var i = 0; i < hexStrLength; i += 2) {
                  words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
              }
  
              return new WordArray.init(words, hexStrLength / 2);
          }
      };
  
      /**
       * Latin1 encoding strategy.
       */
      var Latin1 = C_enc.Latin1 = {
          /**
           * Converts a word array to a Latin1 string.
           *
           * @param {WordArray} wordArray The word array.
           *
           * @return {string} The Latin1 string.
           *
           * @static
           *
           * @example
           *
           *     var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
           */
          stringify: function (wordArray) {
              // Shortcuts
              var words = wordArray.words;
              var sigBytes = wordArray.sigBytes;
  
              // Convert
              var latin1Chars = [];
              for (var i = 0; i < sigBytes; i++) {
                  var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
                  latin1Chars.push(String.fromCharCode(bite));
              }
  
              return latin1Chars.join('');
          },
  
          /**
           * Converts a Latin1 string to a word array.
           *
           * @param {string} latin1Str The Latin1 string.
           *
           * @return {WordArray} The word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
           */
          parse: function (latin1Str) {
              // Shortcut
              var latin1StrLength = latin1Str.length;
  
              // Convert
              var words = [];
              for (var i = 0; i < latin1StrLength; i++) {
                  words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
              }
  
              return new WordArray.init(words, latin1StrLength);
          }
      };
  
      /**
       * UTF-8 encoding strategy.
       */
      var Utf8 = C_enc.Utf8 = {
          /**
           * Converts a word array to a UTF-8 string.
           *
           * @param {WordArray} wordArray The word array.
           *
           * @return {string} The UTF-8 string.
           *
           * @static
           *
           * @example
           *
           *     var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
           */
          stringify: function (wordArray) {
              try {
                  return decodeURIComponent(escape(Latin1.stringify(wordArray)));
              } catch (e) {
                  throw new Error('Malformed UTF-8 data');
              }
          },
  
          /**
           * Converts a UTF-8 string to a word array.
           *
           * @param {string} utf8Str The UTF-8 string.
           *
           * @return {WordArray} The word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
           */
          parse: function (utf8Str) {
              return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
          }
      };
  
      /**
       * Abstract buffered block algorithm template.
       *
       * The property blockSize must be implemented in a concrete subtype.
       *
       * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
       */
      var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
          /**
           * Resets this block algorithm's data buffer to its initial state.
           *
           * @example
           *
           *     bufferedBlockAlgorithm.reset();
           */
          reset: function () {
              // Initial values
              this._data = new WordArray.init();
              this._nDataBytes = 0;
          },
  
          /**
           * Adds new data to this block algorithm's buffer.
           *
           * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
           *
           * @example
           *
           *     bufferedBlockAlgorithm._append('data');
           *     bufferedBlockAlgorithm._append(wordArray);
           */
          _append: function (data) {
              // Convert string to WordArray, else assume WordArray already
              if (typeof data == 'string') {
                  data = Utf8.parse(data);
              }
  
              // Append
              this._data.concat(data);
              this._nDataBytes += data.sigBytes;
          },
  
          /**
           * Processes available data blocks.
           *
           * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
           *
           * @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
           *
           * @return {WordArray} The processed data.
           *
           * @example
           *
           *     var processedData = bufferedBlockAlgorithm._process();
           *     var processedData = bufferedBlockAlgorithm._process(!!'flush');
           */
          _process: function (doFlush) {
              // Shortcuts
              var data = this._data;
              var dataWords = data.words;
              var dataSigBytes = data.sigBytes;
              var blockSize = this.blockSize;
              var blockSizeBytes = blockSize * 4;
  
              // Count blocks ready
              var nBlocksReady = dataSigBytes / blockSizeBytes;
              if (doFlush) {
                  // Round up to include partial blocks
                  nBlocksReady = Math.ceil(nBlocksReady);
              } else {
                  // Round down to include only full blocks,
                  // less the number of blocks that must remain in the buffer
                  nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
              }
  
              // Count words ready
              var nWordsReady = nBlocksReady * blockSize;
  
              // Count bytes ready
              var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
  
              // Process blocks
              if (nWordsReady) {
                  for (var offset = 0; offset < nWordsReady; offset += blockSize) {
                      // Perform concrete-algorithm logic
                      this._doProcessBlock(dataWords, offset);
                  }
  
                  // Remove processed words
                  var processedWords = dataWords.splice(0, nWordsReady);
                  data.sigBytes -= nBytesReady;
              }
  
              // Return processed words
              return new WordArray.init(processedWords, nBytesReady);
          },
  
          /**
           * Creates a copy of this object.
           *
           * @return {Object} The clone.
           *
           * @example
           *
           *     var clone = bufferedBlockAlgorithm.clone();
           */
          clone: function () {
              var clone = Base.clone.call(this);
              clone._data = this._data.clone();
  
              return clone;
          },
  
          _minBufferSize: 0
      });
  
      /**
       * Abstract hasher template.
       *
       * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
       */
      var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
          /**
           * Configuration options.
           */
          cfg: Base.extend(),
  
          /**
           * Initializes a newly created hasher.
           *
           * @param {Object} cfg (Optional) The configuration options to use for this hash computation.
           *
           * @example
           *
           *     var hasher = CryptoJS.algo.SHA256.create();
           */
          init: function (cfg) {
              // Apply config defaults
              this.cfg = this.cfg.extend(cfg);
  
              // Set initial values
              this.reset();
          },
  
          /**
           * Resets this hasher to its initial state.
           *
           * @example
           *
           *     hasher.reset();
           */
          reset: function () {
              // Reset data buffer
              BufferedBlockAlgorithm.reset.call(this);
  
              // Perform concrete-hasher logic
              this._doReset();
          },
  
          /**
           * Updates this hasher with a message.
           *
           * @param {WordArray|string} messageUpdate The message to append.
           *
           * @return {Hasher} This hasher.
           *
           * @example
           *
           *     hasher.update('message');
           *     hasher.update(wordArray);
           */
          update: function (messageUpdate) {
              // Append
              this._append(messageUpdate);
  
              // Update the hash
              this._process();
  
              // Chainable
              return this;
          },
  
          /**
           * Finalizes the hash computation.
           * Note that the finalize operation is effectively a destructive, read-once operation.
           *
           * @param {WordArray|string} messageUpdate (Optional) A final message update.
           *
           * @return {WordArray} The hash.
           *
           * @example
           *
           *     var hash = hasher.finalize();
           *     var hash = hasher.finalize('message');
           *     var hash = hasher.finalize(wordArray);
           */
          finalize: function (messageUpdate) {
              // Final message update
              if (messageUpdate) {
                  this._append(messageUpdate);
              }
  
              // Perform concrete-hasher logic
              var hash = this._doFinalize();
  
              return hash;
          },
  
          blockSize: 512/32,
  
          /**
           * Creates a shortcut function to a hasher's object interface.
           *
           * @param {Hasher} hasher The hasher to create a helper for.
           *
           * @return {Function} The shortcut function.
           *
           * @static
           *
           * @example
           *
           *     var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
           */
          _createHelper: function (hasher) {
              return function (message, cfg) {
                  return new hasher.init(cfg).finalize(message);
              };
          },
  
          /**
           * Creates a shortcut function to the HMAC's object interface.
           *
           * @param {Hasher} hasher The hasher to use in this HMAC helper.
           *
           * @return {Function} The shortcut function.
           *
           * @static
           *
           * @example
           *
           *     var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
           */
          _createHmacHelper: function (hasher) {
              return function (message, key) {
                  return new C_algo.HMAC.init(hasher, key).finalize(message);
              };
          }
      });
  
      /**
       * Algorithm namespace.
       */
      var C_algo = C.algo = {};
  
      return C;
  }(Math));
  
  module.exports = CryptoJS;
  },{}],11:[function(require,module,exports){
  (function (Buffer){
  const Sha3 = require('js-sha3')
  
  var hash = function (bitcount) {
    this.content = ''
    this.bitcount = bitcount ? 'keccak_' + bitcount : 'keccak_512'
  }
  
  hash.prototype.update = function (i) {
    this.content = Buffer.isBuffer(i) ? i : new Buffer(i);
  }
  
  hash.prototype.digest = function (encoding) {
    var result = Sha3[this.bitcount](this.content) 
    if(encoding === 'hex')
      return result
    else
      return new Buffer(result, 'hex').toString('binary')
  }
  
  module.exports = {
    SHA3Hash: hash
  }
  
  }).call(this,require("buffer").Buffer)
  },{"buffer":88,"js-sha3":40}],12:[function(require,module,exports){
  'use strict';
  
  var elliptic = exports;
  
  elliptic.version = require('../package.json').version;
  elliptic.utils = require('./elliptic/utils');
  elliptic.rand = require('brorand');
  elliptic.hmacDRBG = require('./elliptic/hmac-drbg');
  elliptic.curve = require('./elliptic/curve');
  elliptic.curves = require('./elliptic/curves');
  
  // Protocols
  elliptic.ec = require('./elliptic/ec');
  elliptic.eddsa = require('./elliptic/eddsa');
  
  },{"../package.json":28,"./elliptic/curve":15,"./elliptic/curves":18,"./elliptic/ec":19,"./elliptic/eddsa":22,"./elliptic/hmac-drbg":25,"./elliptic/utils":27,"brorand":4}],13:[function(require,module,exports){
  'use strict';
  
  var bn = require('bn.js');
  var elliptic = require('../../elliptic');
  var utils = elliptic.utils;
  var getNAF = utils.getNAF;
  var getJSF = utils.getJSF;
  var assert = utils.assert;
  
  function BaseCurve(type, conf) {
    this.type = type;
    this.p = new bn(conf.p, 16);
  
    // Use Montgomery, when there is no fast reduction for the prime
    this.red = conf.prime ? bn.red(conf.prime) : bn.mont(this.p);
  
    // Useful for many curves
    this.zero = new bn(0).toRed(this.red);
    this.one = new bn(1).toRed(this.red);
    this.two = new bn(2).toRed(this.red);
  
    // Curve configuration, optional
    this.n = conf.n && new bn(conf.n, 16);
    this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);
  
    // Temporary arrays
    this._wnafT1 = new Array(4);
    this._wnafT2 = new Array(4);
    this._wnafT3 = new Array(4);
    this._wnafT4 = new Array(4);
  }
  module.exports = BaseCurve;
  
  BaseCurve.prototype.point = function point() {
    throw new Error('Not implemented');
  };
  
  BaseCurve.prototype.validate = function validate() {
    throw new Error('Not implemented');
  };
  
  BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {
    assert(p.precomputed);
    var doubles = p._getDoubles();
  
    var naf = getNAF(k, 1);
    var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);
    I /= 3;
  
    // Translate into more windowed form
    var repr = [];
    for (var j = 0; j < naf.length; j += doubles.step) {
      var nafW = 0;
      for (var k = j + doubles.step - 1; k >= j; k--)
        nafW = (nafW << 1) + naf[k];
      repr.push(nafW);
    }
  
    var a = this.jpoint(null, null, null);
    var b = this.jpoint(null, null, null);
    for (var i = I; i > 0; i--) {
      for (var j = 0; j < repr.length; j++) {
        var nafW = repr[j];
        if (nafW === i)
          b = b.mixedAdd(doubles.points[j]);
        else if (nafW === -i)
          b = b.mixedAdd(doubles.points[j].neg());
      }
      a = a.add(b);
    }
    return a.toP();
  };
  
  BaseCurve.prototype._wnafMul = function _wnafMul(p, k) {
    var w = 4;
  
    // Precompute window
    var nafPoints = p._getNAFPoints(w);
    w = nafPoints.wnd;
    var wnd = nafPoints.points;
  
    // Get NAF form
    var naf = getNAF(k, w);
  
    // Add `this`*(N+1) for every w-NAF index
    var acc = this.jpoint(null, null, null);
    for (var i = naf.length - 1; i >= 0; i--) {
      // Count zeroes
      for (var k = 0; i >= 0 && naf[i] === 0; i--)
        k++;
      if (i >= 0)
        k++;
      acc = acc.dblp(k);
  
      if (i < 0)
        break;
      var z = naf[i];
      assert(z !== 0);
      if (p.type === 'affine') {
        // J +- P
        if (z > 0)
          acc = acc.mixedAdd(wnd[(z - 1) >> 1]);
        else
          acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());
      } else {
        // J +- J
        if (z > 0)
          acc = acc.add(wnd[(z - 1) >> 1]);
        else
          acc = acc.add(wnd[(-z - 1) >> 1].neg());
      }
    }
    return p.type === 'affine' ? acc.toP() : acc;
  };
  
  BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,
                                                         points,
                                                         coeffs,
                                                         len) {
    var wndWidth = this._wnafT1;
    var wnd = this._wnafT2;
    var naf = this._wnafT3;
  
    // Fill all arrays
    var max = 0;
    for (var i = 0; i < len; i++) {
      var p = points[i];
      var nafPoints = p._getNAFPoints(defW);
      wndWidth[i] = nafPoints.wnd;
      wnd[i] = nafPoints.points;
    }
  
    // Comb small window NAFs
    for (var i = len - 1; i >= 1; i -= 2) {
      var a = i - 1;
      var b = i;
      if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {
        naf[a] = getNAF(coeffs[a], wndWidth[a]);
        naf[b] = getNAF(coeffs[b], wndWidth[b]);
        max = Math.max(naf[a].length, max);
        max = Math.max(naf[b].length, max);
        continue;
      }
  
      var comb = [
        points[a], /* 1 */
        null, /* 3 */
        null, /* 5 */
        points[b] /* 7 */
      ];
  
      // Try to avoid Projective points, if possible
      if (points[a].y.cmp(points[b].y) === 0) {
        comb[1] = points[a].add(points[b]);
        comb[2] = points[a].toJ().mixedAdd(points[b].neg());
      } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {
        comb[1] = points[a].toJ().mixedAdd(points[b]);
        comb[2] = points[a].add(points[b].neg());
      } else {
        comb[1] = points[a].toJ().mixedAdd(points[b]);
        comb[2] = points[a].toJ().mixedAdd(points[b].neg());
      }
  
      var index = [
        -3, /* -1 -1 */
        -1, /* -1 0 */
        -5, /* -1 1 */
        -7, /* 0 -1 */
        0, /* 0 0 */
        7, /* 0 1 */
        5, /* 1 -1 */
        1, /* 1 0 */
        3  /* 1 1 */
      ];
  
      var jsf = getJSF(coeffs[a], coeffs[b]);
      max = Math.max(jsf[0].length, max);
      naf[a] = new Array(max);
      naf[b] = new Array(max);
      for (var j = 0; j < max; j++) {
        var ja = jsf[0][j] | 0;
        var jb = jsf[1][j] | 0;
  
        naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];
        naf[b][j] = 0;
        wnd[a] = comb;
      }
    }
  
    var acc = this.jpoint(null, null, null);
    var tmp = this._wnafT4;
    for (var i = max; i >= 0; i--) {
      var k = 0;
  
      while (i >= 0) {
        var zero = true;
        for (var j = 0; j < len; j++) {
          tmp[j] = naf[j][i] | 0;
          if (tmp[j] !== 0)
            zero = false;
        }
        if (!zero)
          break;
        k++;
        i--;
      }
      if (i >= 0)
        k++;
      acc = acc.dblp(k);
      if (i < 0)
        break;
  
      for (var j = 0; j < len; j++) {
        var z = tmp[j];
        var p;
        if (z === 0)
          continue;
        else if (z > 0)
          p = wnd[j][(z - 1) >> 1];
        else if (z < 0)
          p = wnd[j][(-z - 1) >> 1].neg();
  
        if (p.type === 'affine')
          acc = acc.mixedAdd(p);
        else
          acc = acc.add(p);
      }
    }
    // Zeroify references
    for (var i = 0; i < len; i++)
      wnd[i] = null;
    return acc.toP();
  };
  
  function BasePoint(curve, type) {
    this.curve = curve;
    this.type = type;
    this.precomputed = null;
  }
  BaseCurve.BasePoint = BasePoint;
  
  BasePoint.prototype.eq = function eq(/*other*/) {
    throw new Error('Not implemented');
  };
  
  BasePoint.prototype.validate = function validate() {
    return this.curve.validate(this);
  };
  
  BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
    bytes = utils.toArray(bytes, enc);
  
    var len = this.p.byteLength();
    if (bytes[0] === 0x04 && bytes.length - 1 === 2 * len) {
      return this.point(bytes.slice(1, 1 + len),
                        bytes.slice(1 + len, 1 + 2 * len));
    } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&
                bytes.length - 1 === len) {
      return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);
    }
    throw new Error('Unknown point format');
  };
  
  BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {
    return this.encode(enc, true);
  };
  
  BasePoint.prototype._encode = function _encode(compact) {
    var len = this.curve.p.byteLength();
    var x = this.getX().toArray('be', len);
  
    if (compact)
      return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);
  
    return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ;
  };
  
  BasePoint.prototype.encode = function encode(enc, compact) {
    return utils.encode(this._encode(compact), enc);
  };
  
  BasePoint.prototype.precompute = function precompute(power) {
    if (this.precomputed)
      return this;
  
    var precomputed = {
      doubles: null,
      naf: null,
      beta: null
    };
    precomputed.naf = this._getNAFPoints(8);
    precomputed.doubles = this._getDoubles(4, power);
    precomputed.beta = this._getBeta();
    this.precomputed = precomputed;
  
    return this;
  };
  
  BasePoint.prototype._hasDoubles = function _hasDoubles(k) {
    if (!this.precomputed)
      return false;
  
    var doubles = this.precomputed.doubles;
    if (!doubles)
      return false;
  
    return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);
  };
  
  BasePoint.prototype._getDoubles = function _getDoubles(step, power) {
    if (this.precomputed && this.precomputed.doubles)
      return this.precomputed.doubles;
  
    var doubles = [ this ];
    var acc = this;
    for (var i = 0; i < power; i += step) {
      for (var j = 0; j < step; j++)
        acc = acc.dbl();
      doubles.push(acc);
    }
    return {
      step: step,
      points: doubles
    };
  };
  
  BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {
    if (this.precomputed && this.precomputed.naf)
      return this.precomputed.naf;
  
    var res = [ this ];
    var max = (1 << wnd) - 1;
    var dbl = max === 1 ? null : this.dbl();
    for (var i = 1; i < max; i++)
      res[i] = res[i - 1].add(dbl);
    return {
      wnd: wnd,
      points: res
    };
  };
  
  BasePoint.prototype._getBeta = function _getBeta() {
    return null;
  };
  
  BasePoint.prototype.dblp = function dblp(k) {
    var r = this;
    for (var i = 0; i < k; i++)
      r = r.dbl();
    return r;
  };
  
  },{"../../elliptic":12,"bn.js":3}],14:[function(require,module,exports){
  'use strict';
  
  var curve = require('../curve');
  var elliptic = require('../../elliptic');
  var bn = require('bn.js');
  var inherits = require('inherits');
  var Base = curve.base;
  
  var assert = elliptic.utils.assert;
  
  function EdwardsCurve(conf) {
    // NOTE: Important as we are creating point in Base.call()
    this.twisted = (conf.a | 0) !== 1;
    this.mOneA = this.twisted && (conf.a | 0) === -1;
    this.extended = this.mOneA;
  
    Base.call(this, 'edwards', conf);
  
    this.a = new bn(conf.a, 16).umod(this.red.m);
    this.a = this.a.toRed(this.red);
    this.c = new bn(conf.c, 16).toRed(this.red);
    this.c2 = this.c.redSqr();
    this.d = new bn(conf.d, 16).toRed(this.red);
    this.dd = this.d.redAdd(this.d);
  
    assert(!this.twisted || this.c.fromRed().cmpn(1) === 0);
    this.oneC = (conf.c | 0) === 1;
  }
  inherits(EdwardsCurve, Base);
  module.exports = EdwardsCurve;
  
  EdwardsCurve.prototype._mulA = function _mulA(num) {
    if (this.mOneA)
      return num.redNeg();
    else
      return this.a.redMul(num);
  };
  
  EdwardsCurve.prototype._mulC = function _mulC(num) {
    if (this.oneC)
      return num;
    else
      return this.c.redMul(num);
  };
  
  // Just for compatibility with Short curve
  EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {
    return this.point(x, y, z, t);
  };
  
  EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) {
    x = new bn(x, 16);
    if (!x.red)
      x = x.toRed(this.red);
  
    var x2 = x.redSqr();
    var rhs = this.c2.redSub(this.a.redMul(x2));
    var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));
  
    var y = rhs.redMul(lhs.redInvm()).redSqrt();
    var isOdd = y.fromRed().isOdd();
    if (odd && !isOdd || !odd && isOdd)
      y = y.redNeg();
  
    return this.point(x, y);
  };
  
  EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) {
    y = new bn(y, 16);
    if (!y.red)
      y = y.toRed(this.red);
  
    // x^2 = (y^2 - 1) / (d y^2 + 1)
    var y2 = y.redSqr();
    var lhs = y2.redSub(this.one);
    var rhs = y2.redMul(this.d).redAdd(this.one);
    var x2 = lhs.redMul(rhs.redInvm());
  
    if (x2.cmp(this.zero) === 0) {
      if (odd)
        throw new Error('invalid point');
      else
        return this.point(this.zero, y);
    }
  
    var x = x2.redSqrt();
    if (x.redSqr().redSub(x2).cmp(this.zero) !== 0)
      throw new Error('invalid point');
  
    if (x.isOdd() !== odd)
      x = x.redNeg();
  
    return this.point(x, y);
  };
  
  EdwardsCurve.prototype.validate = function validate(point) {
    if (point.isInfinity())
      return true;
  
    // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)
    point.normalize();
  
    var x2 = point.x.redSqr();
    var y2 = point.y.redSqr();
    var lhs = x2.redMul(this.a).redAdd(y2);
    var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));
  
    return lhs.cmp(rhs) === 0;
  };
  
  function Point(curve, x, y, z, t) {
    Base.BasePoint.call(this, curve, 'projective');
    if (x === null && y === null && z === null) {
      this.x = this.curve.zero;
      this.y = this.curve.one;
      this.z = this.curve.one;
      this.t = this.curve.zero;
      this.zOne = true;
    } else {
      this.x = new bn(x, 16);
      this.y = new bn(y, 16);
      this.z = z ? new bn(z, 16) : this.curve.one;
      this.t = t && new bn(t, 16);
      if (!this.x.red)
        this.x = this.x.toRed(this.curve.red);
      if (!this.y.red)
        this.y = this.y.toRed(this.curve.red);
      if (!this.z.red)
        this.z = this.z.toRed(this.curve.red);
      if (this.t && !this.t.red)
        this.t = this.t.toRed(this.curve.red);
      this.zOne = this.z === this.curve.one;
  
      // Use extended coordinates
      if (this.curve.extended && !this.t) {
        this.t = this.x.redMul(this.y);
        if (!this.zOne)
          this.t = this.t.redMul(this.z.redInvm());
      }
    }
  }
  inherits(Point, Base.BasePoint);
  
  EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
    return Point.fromJSON(this, obj);
  };
  
  EdwardsCurve.prototype.point = function point(x, y, z, t) {
    return new Point(this, x, y, z, t);
  };
  
  Point.fromJSON = function fromJSON(curve, obj) {
    return new Point(curve, obj[0], obj[1], obj[2]);
  };
  
  Point.prototype.inspect = function inspect() {
    if (this.isInfinity())
      return '<EC Point Infinity>';
    return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
        ' y: ' + this.y.fromRed().toString(16, 2) +
        ' z: ' + this.z.fromRed().toString(16, 2) + '>';
  };
  
  Point.prototype.isInfinity = function isInfinity() {
    // XXX This code assumes that zero is always zero in red
    return this.x.cmpn(0) === 0 &&
           this.y.cmp(this.z) === 0;
  };
  
  Point.prototype._extDbl = function _extDbl() {
    // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
    //     #doubling-dbl-2008-hwcd
    // 4M + 4S
  
    // A = X1^2
    var a = this.x.redSqr();
    // B = Y1^2
    var b = this.y.redSqr();
    // C = 2 * Z1^2
    var c = this.z.redSqr();
    c = c.redIAdd(c);
    // D = a * A
    var d = this.curve._mulA(a);
    // E = (X1 + Y1)^2 - A - B
    var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);
    // G = D + B
    var g = d.redAdd(b);
    // F = G - C
    var f = g.redSub(c);
    // H = D - B
    var h = d.redSub(b);
    // X3 = E * F
    var nx = e.redMul(f);
    // Y3 = G * H
    var ny = g.redMul(h);
    // T3 = E * H
    var nt = e.redMul(h);
    // Z3 = F * G
    var nz = f.redMul(g);
    return this.curve.point(nx, ny, nz, nt);
  };
  
  Point.prototype._projDbl = function _projDbl() {
    // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
    //     #doubling-dbl-2008-bbjlp
    //     #doubling-dbl-2007-bl
    // and others
    // Generally 3M + 4S or 2M + 4S
  
    // B = (X1 + Y1)^2
    var b = this.x.redAdd(this.y).redSqr();
    // C = X1^2
    var c = this.x.redSqr();
    // D = Y1^2
    var d = this.y.redSqr();
  
    var nx;
    var ny;
    var nz;
    if (this.curve.twisted) {
      // E = a * C
      var e = this.curve._mulA(c);
      // F = E + D
      var f = e.redAdd(d);
      if (this.zOne) {
        // X3 = (B - C - D) * (F - 2)
        nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));
        // Y3 = F * (E - D)
        ny = f.redMul(e.redSub(d));
        // Z3 = F^2 - 2 * F
        nz = f.redSqr().redSub(f).redSub(f);
      } else {
        // H = Z1^2
        var h = this.z.redSqr();
        // J = F - 2 * H
        var j = f.redSub(h).redISub(h);
        // X3 = (B-C-D)*J
        nx = b.redSub(c).redISub(d).redMul(j);
        // Y3 = F * (E - D)
        ny = f.redMul(e.redSub(d));
        // Z3 = F * J
        nz = f.redMul(j);
      }
    } else {
      // E = C + D
      var e = c.redAdd(d);
      // H = (c * Z1)^2
      var h = this.curve._mulC(this.c.redMul(this.z)).redSqr();
      // J = E - 2 * H
      var j = e.redSub(h).redSub(h);
      // X3 = c * (B - E) * J
      nx = this.curve._mulC(b.redISub(e)).redMul(j);
      // Y3 = c * E * (C - D)
      ny = this.curve._mulC(e).redMul(c.redISub(d));
      // Z3 = E * J
      nz = e.redMul(j);
    }
    return this.curve.point(nx, ny, nz);
  };
  
  Point.prototype.dbl = function dbl() {
    if (this.isInfinity())
      return this;
  
    // Double in extended coordinates
    if (this.curve.extended)
      return this._extDbl();
    else
      return this._projDbl();
  };
  
  Point.prototype._extAdd = function _extAdd(p) {
    // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
    //     #addition-add-2008-hwcd-3
    // 8M
  
    // A = (Y1 - X1) * (Y2 - X2)
    var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));
    // B = (Y1 + X1) * (Y2 + X2)
    var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));
    // C = T1 * k * T2
    var c = this.t.redMul(this.curve.dd).redMul(p.t);
    // D = Z1 * 2 * Z2
    var d = this.z.redMul(p.z.redAdd(p.z));
    // E = B - A
    var e = b.redSub(a);
    // F = D - C
    var f = d.redSub(c);
    // G = D + C
    var g = d.redAdd(c);
    // H = B + A
    var h = b.redAdd(a);
    // X3 = E * F
    var nx = e.redMul(f);
    // Y3 = G * H
    var ny = g.redMul(h);
    // T3 = E * H
    var nt = e.redMul(h);
    // Z3 = F * G
    var nz = f.redMul(g);
    return this.curve.point(nx, ny, nz, nt);
  };
  
  Point.prototype._projAdd = function _projAdd(p) {
    // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
    //     #addition-add-2008-bbjlp
    //     #addition-add-2007-bl
    // 10M + 1S
  
    // A = Z1 * Z2
    var a = this.z.redMul(p.z);
    // B = A^2
    var b = a.redSqr();
    // C = X1 * X2
    var c = this.x.redMul(p.x);
    // D = Y1 * Y2
    var d = this.y.redMul(p.y);
    // E = d * C * D
    var e = this.curve.d.redMul(c).redMul(d);
    // F = B - E
    var f = b.redSub(e);
    // G = B + E
    var g = b.redAdd(e);
    // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)
    var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);
    var nx = a.redMul(f).redMul(tmp);
    var ny;
    var nz;
    if (this.curve.twisted) {
      // Y3 = A * G * (D - a * C)
      ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));
      // Z3 = F * G
      nz = f.redMul(g);
    } else {
      // Y3 = A * G * (D - C)
      ny = a.redMul(g).redMul(d.redSub(c));
      // Z3 = c * F * G
      nz = this.curve._mulC(f).redMul(g);
    }
    return this.curve.point(nx, ny, nz);
  };
  
  Point.prototype.add = function add(p) {
    if (this.isInfinity())
      return p;
    if (p.isInfinity())
      return this;
  
    if (this.curve.extended)
      return this._extAdd(p);
    else
      return this._projAdd(p);
  };
  
  Point.prototype.mul = function mul(k) {
    if (this._hasDoubles(k))
      return this.curve._fixedNafMul(this, k);
    else
      return this.curve._wnafMul(this, k);
  };
  
  Point.prototype.mulAdd = function mulAdd(k1, p, k2) {
    return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2);
  };
  
  Point.prototype.normalize = function normalize() {
    if (this.zOne)
      return this;
  
    // Normalize coordinates
    var zi = this.z.redInvm();
    this.x = this.x.redMul(zi);
    this.y = this.y.redMul(zi);
    if (this.t)
      this.t = this.t.redMul(zi);
    this.z = this.curve.one;
    this.zOne = true;
    return this;
  };
  
  Point.prototype.neg = function neg() {
    return this.curve.point(this.x.redNeg(),
                            this.y,
                            this.z,
                            this.t && this.t.redNeg());
  };
  
  Point.prototype.getX = function getX() {
    this.normalize();
    return this.x.fromRed();
  };
  
  Point.prototype.getY = function getY() {
    this.normalize();
    return this.y.fromRed();
  };
  
  Point.prototype.eq = function eq(other) {
    return this === other ||
           this.getX().cmp(other.getX()) === 0 &&
           this.getY().cmp(other.getY()) === 0;
  };
  
  // Compatibility with BaseCurve
  Point.prototype.toP = Point.prototype.normalize;
  Point.prototype.mixedAdd = Point.prototype.add;
  
  },{"../../elliptic":12,"../curve":15,"bn.js":3,"inherits":39}],15:[function(require,module,exports){
  'use strict';
  
  var curve = exports;
  
  curve.base = require('./base');
  curve.short = require('./short');
  curve.mont = require('./mont');
  curve.edwards = require('./edwards');
  
  },{"./base":13,"./edwards":14,"./mont":16,"./short":17}],16:[function(require,module,exports){
  'use strict';
  
  var curve = require('../curve');
  var bn = require('bn.js');
  var inherits = require('inherits');
  var Base = curve.base;
  
  var elliptic = require('../../elliptic');
  var utils = elliptic.utils;
  
  function MontCurve(conf) {
    Base.call(this, 'mont', conf);
  
    this.a = new bn(conf.a, 16).toRed(this.red);
    this.b = new bn(conf.b, 16).toRed(this.red);
    this.i4 = new bn(4).toRed(this.red).redInvm();
    this.two = new bn(2).toRed(this.red);
    this.a24 = this.i4.redMul(this.a.redAdd(this.two));
  }
  inherits(MontCurve, Base);
  module.exports = MontCurve;
  
  MontCurve.prototype.validate = function validate(point) {
    var x = point.normalize().x;
    var x2 = x.redSqr();
    var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);
    var y = rhs.redSqrt();
  
    return y.redSqr().cmp(rhs) === 0;
  };
  
  function Point(curve, x, z) {
    Base.BasePoint.call(this, curve, 'projective');
    if (x === null && z === null) {
      this.x = this.curve.one;
      this.z = this.curve.zero;
    } else {
      this.x = new bn(x, 16);
      this.z = new bn(z, 16);
      if (!this.x.red)
        this.x = this.x.toRed(this.curve.red);
      if (!this.z.red)
        this.z = this.z.toRed(this.curve.red);
    }
  }
  inherits(Point, Base.BasePoint);
  
  MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
    return this.point(utils.toArray(bytes, enc), 1);
  };
  
  MontCurve.prototype.point = function point(x, z) {
    return new Point(this, x, z);
  };
  
  MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
    return Point.fromJSON(this, obj);
  };
  
  Point.prototype.precompute = function precompute() {
    // No-op
  };
  
  Point.prototype._encode = function _encode() {
    return this.getX().toArray('be', this.curve.p.byteLength());
  };
  
  Point.fromJSON = function fromJSON(curve, obj) {
    return new Point(curve, obj[0], obj[1] || curve.one);
  };
  
  Point.prototype.inspect = function inspect() {
    if (this.isInfinity())
      return '<EC Point Infinity>';
    return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
        ' z: ' + this.z.fromRed().toString(16, 2) + '>';
  };
  
  Point.prototype.isInfinity = function isInfinity() {
    // XXX This code assumes that zero is always zero in red
    return this.z.cmpn(0) === 0;
  };
  
  Point.prototype.dbl = function dbl() {
    // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3
    // 2M + 2S + 4A
  
    // A = X1 + Z1
    var a = this.x.redAdd(this.z);
    // AA = A^2
    var aa = a.redSqr();
    // B = X1 - Z1
    var b = this.x.redSub(this.z);
    // BB = B^2
    var bb = b.redSqr();
    // C = AA - BB
    var c = aa.redSub(bb);
    // X3 = AA * BB
    var nx = aa.redMul(bb);
    // Z3 = C * (BB + A24 * C)
    var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));
    return this.curve.point(nx, nz);
  };
  
  Point.prototype.add = function add() {
    throw new Error('Not supported on Montgomery curve');
  };
  
  Point.prototype.diffAdd = function diffAdd(p, diff) {
    // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3
    // 4M + 2S + 6A
  
    // A = X2 + Z2
    var a = this.x.redAdd(this.z);
    // B = X2 - Z2
    var b = this.x.redSub(this.z);
    // C = X3 + Z3
    var c = p.x.redAdd(p.z);
    // D = X3 - Z3
    var d = p.x.redSub(p.z);
    // DA = D * A
    var da = d.redMul(a);
    // CB = C * B
    var cb = c.redMul(b);
    // X5 = Z1 * (DA + CB)^2
    var nx = diff.z.redMul(da.redAdd(cb).redSqr());
    // Z5 = X1 * (DA - CB)^2
    var nz = diff.x.redMul(da.redISub(cb).redSqr());
    return this.curve.point(nx, nz);
  };
  
  Point.prototype.mul = function mul(k) {
    var t = k.clone();
    var a = this; // (N / 2) * Q + Q
    var b = this.curve.point(null, null); // (N / 2) * Q
    var c = this; // Q
  
    for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1))
      bits.push(t.andln(1));
  
    for (var i = bits.length - 1; i >= 0; i--) {
      if (bits[i] === 0) {
        // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q
        a = a.diffAdd(b, c);
        // N * Q = 2 * ((N / 2) * Q + Q))
        b = b.dbl();
      } else {
        // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)
        b = a.diffAdd(b, c);
        // N * Q + Q = 2 * ((N / 2) * Q + Q)
        a = a.dbl();
      }
    }
    return b;
  };
  
  Point.prototype.mulAdd = function mulAdd() {
    throw new Error('Not supported on Montgomery curve');
  };
  
  Point.prototype.eq = function eq(other) {
    return this.getX().cmp(other.getX()) === 0;
  };
  
  Point.prototype.normalize = function normalize() {
    this.x = this.x.redMul(this.z.redInvm());
    this.z = this.curve.one;
    return this;
  };
  
  Point.prototype.getX = function getX() {
    // Normalize coordinates
    this.normalize();
  
    return this.x.fromRed();
  };
  
  },{"../../elliptic":12,"../curve":15,"bn.js":3,"inherits":39}],17:[function(require,module,exports){
  'use strict';
  
  var curve = require('../curve');
  var elliptic = require('../../elliptic');
  var bn = require('bn.js');
  var inherits = require('inherits');
  var Base = curve.base;
  
  var assert = elliptic.utils.assert;
  
  function ShortCurve(conf) {
    Base.call(this, 'short', conf);
  
    this.a = new bn(conf.a, 16).toRed(this.red);
    this.b = new bn(conf.b, 16).toRed(this.red);
    this.tinv = this.two.redInvm();
  
    this.zeroA = this.a.fromRed().cmpn(0) === 0;
    this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;
  
    // If the curve is endomorphic, precalculate beta and lambda
    this.endo = this._getEndomorphism(conf);
    this._endoWnafT1 = new Array(4);
    this._endoWnafT2 = new Array(4);
  }
  inherits(ShortCurve, Base);
  module.exports = ShortCurve;
  
  ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {
    // No efficient endomorphism
    if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)
      return;
  
    // Compute beta and lambda, that lambda * P = (beta * Px; Py)
    var beta;
    var lambda;
    if (conf.beta) {
      beta = new bn(conf.beta, 16).toRed(this.red);
    } else {
      var betas = this._getEndoRoots(this.p);
      // Choose the smallest beta
      beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];
      beta = beta.toRed(this.red);
    }
    if (conf.lambda) {
      lambda = new bn(conf.lambda, 16);
    } else {
      // Choose the lambda that is matching selected beta
      var lambdas = this._getEndoRoots(this.n);
      if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {
        lambda = lambdas[0];
      } else {
        lambda = lambdas[1];
        assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);
      }
    }
  
    // Get basis vectors, used for balanced length-two representation
    var basis;
    if (conf.basis) {
      basis = conf.basis.map(function(vec) {
        return {
          a: new bn(vec.a, 16),
          b: new bn(vec.b, 16)
        };
      });
    } else {
      basis = this._getEndoBasis(lambda);
    }
  
    return {
      beta: beta,
      lambda: lambda,
      basis: basis
    };
  };
  
  ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {
    // Find roots of for x^2 + x + 1 in F
    // Root = (-1 +- Sqrt(-3)) / 2
    //
    var red = num === this.p ? this.red : bn.mont(num);
    var tinv = new bn(2).toRed(red).redInvm();
    var ntinv = tinv.redNeg();
  
    var s = new bn(3).toRed(red).redNeg().redSqrt().redMul(tinv);
  
    var l1 = ntinv.redAdd(s).fromRed();
    var l2 = ntinv.redSub(s).fromRed();
    return [ l1, l2 ];
  };
  
  ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {
    // aprxSqrt >= sqrt(this.n)
    var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));
  
    // 3.74
    // Run EGCD, until r(L + 1) < aprxSqrt
    var u = lambda;
    var v = this.n.clone();
    var x1 = new bn(1);
    var y1 = new bn(0);
    var x2 = new bn(0);
    var y2 = new bn(1);
  
    // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)
    var a0;
    var b0;
    // First vector
    var a1;
    var b1;
    // Second vector
    var a2;
    var b2;
  
    var prevR;
    var i = 0;
    var r;
    var x;
    while (u.cmpn(0) !== 0) {
      var q = v.div(u);
      r = v.sub(q.mul(u));
      x = x2.sub(q.mul(x1));
      var y = y2.sub(q.mul(y1));
  
      if (!a1 && r.cmp(aprxSqrt) < 0) {
        a0 = prevR.neg();
        b0 = x1;
        a1 = r.neg();
        b1 = x;
      } else if (a1 && ++i === 2) {
        break;
      }
      prevR = r;
  
      v = u;
      u = r;
      x2 = x1;
      x1 = x;
      y2 = y1;
      y1 = y;
    }
    a2 = r.neg();
    b2 = x;
  
    var len1 = a1.sqr().add(b1.sqr());
    var len2 = a2.sqr().add(b2.sqr());
    if (len2.cmp(len1) >= 0) {
      a2 = a0;
      b2 = b0;
    }
  
    // Normalize signs
    if (a1.sign) {
      a1 = a1.neg();
      b1 = b1.neg();
    }
    if (a2.sign) {
      a2 = a2.neg();
      b2 = b2.neg();
    }
  
    return [
      { a: a1, b: b1 },
      { a: a2, b: b2 }
    ];
  };
  
  ShortCurve.prototype._endoSplit = function _endoSplit(k) {
    var basis = this.endo.basis;
    var v1 = basis[0];
    var v2 = basis[1];
  
    var c1 = v2.b.mul(k).divRound(this.n);
    var c2 = v1.b.neg().mul(k).divRound(this.n);
  
    var p1 = c1.mul(v1.a);
    var p2 = c2.mul(v2.a);
    var q1 = c1.mul(v1.b);
    var q2 = c2.mul(v2.b);
  
    // Calculate answer
    var k1 = k.sub(p1).sub(p2);
    var k2 = q1.add(q2).neg();
    return { k1: k1, k2: k2 };
  };
  
  ShortCurve.prototype.pointFromX = function pointFromX(x, odd) {
    x = new bn(x, 16);
    if (!x.red)
      x = x.toRed(this.red);
  
    var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);
    var y = y2.redSqrt();
  
    // XXX Is there any way to tell if the number is odd without converting it
    // to non-red form?
    var isOdd = y.fromRed().isOdd();
    if (odd && !isOdd || !odd && isOdd)
      y = y.redNeg();
  
    return this.point(x, y);
  };
  
  ShortCurve.prototype.validate = function validate(point) {
    if (point.inf)
      return true;
  
    var x = point.x;
    var y = point.y;
  
    var ax = this.a.redMul(x);
    var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);
    return y.redSqr().redISub(rhs).cmpn(0) === 0;
  };
  
  ShortCurve.prototype._endoWnafMulAdd =
      function _endoWnafMulAdd(points, coeffs) {
    var npoints = this._endoWnafT1;
    var ncoeffs = this._endoWnafT2;
    for (var i = 0; i < points.length; i++) {
      var split = this._endoSplit(coeffs[i]);
      var p = points[i];
      var beta = p._getBeta();
  
      if (split.k1.sign) {
        split.k1.sign = !split.k1.sign;
        p = p.neg(true);
      }
      if (split.k2.sign) {
        split.k2.sign = !split.k2.sign;
        beta = beta.neg(true);
      }
  
      npoints[i * 2] = p;
      npoints[i * 2 + 1] = beta;
      ncoeffs[i * 2] = split.k1;
      ncoeffs[i * 2 + 1] = split.k2;
    }
    var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2);
  
    // Clean-up references to points and coefficients
    for (var j = 0; j < i * 2; j++) {
      npoints[j] = null;
      ncoeffs[j] = null;
    }
    return res;
  };
  
  function Point(curve, x, y, isRed) {
    Base.BasePoint.call(this, curve, 'affine');
    if (x === null && y === null) {
      this.x = null;
      this.y = null;
      this.inf = true;
    } else {
      this.x = new bn(x, 16);
      this.y = new bn(y, 16);
      // Force redgomery representation when loading from JSON
      if (isRed) {
        this.x.forceRed(this.curve.red);
        this.y.forceRed(this.curve.red);
      }
      if (!this.x.red)
        this.x = this.x.toRed(this.curve.red);
      if (!this.y.red)
        this.y = this.y.toRed(this.curve.red);
      this.inf = false;
    }
  }
  inherits(Point, Base.BasePoint);
  
  ShortCurve.prototype.point = function point(x, y, isRed) {
    return new Point(this, x, y, isRed);
  };
  
  ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {
    return Point.fromJSON(this, obj, red);
  };
  
  Point.prototype._getBeta = function _getBeta() {
    if (!this.curve.endo)
      return;
  
    var pre = this.precomputed;
    if (pre && pre.beta)
      return pre.beta;
  
    var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);
    if (pre) {
      var curve = this.curve;
      var endoMul = function(p) {
        return curve.point(p.x.redMul(curve.endo.beta), p.y);
      };
      pre.beta = beta;
      beta.precomputed = {
        beta: null,
        naf: pre.naf && {
          wnd: pre.naf.wnd,
          points: pre.naf.points.map(endoMul)
        },
        doubles: pre.doubles && {
          step: pre.doubles.step,
          points: pre.doubles.points.map(endoMul)
        }
      };
    }
    return beta;
  };
  
  Point.prototype.toJSON = function toJSON() {
    if (!this.precomputed)
      return [ this.x, this.y ];
  
    return [ this.x, this.y, this.precomputed && {
      doubles: this.precomputed.doubles && {
        step: this.precomputed.doubles.step,
        points: this.precomputed.doubles.points.slice(1)
      },
      naf: this.precomputed.naf && {
        wnd: this.precomputed.naf.wnd,
        points: this.precomputed.naf.points.slice(1)
      }
    } ];
  };
  
  Point.fromJSON = function fromJSON(curve, obj, red) {
    if (typeof obj === 'string')
      obj = JSON.parse(obj);
    var res = curve.point(obj[0], obj[1], red);
    if (!obj[2])
      return res;
  
    function obj2point(obj) {
      return curve.point(obj[0], obj[1], red);
    }
  
    var pre = obj[2];
    res.precomputed = {
      beta: null,
      doubles: pre.doubles && {
        step: pre.doubles.step,
        points: [ res ].concat(pre.doubles.points.map(obj2point))
      },
      naf: pre.naf && {
        wnd: pre.naf.wnd,
        points: [ res ].concat(pre.naf.points.map(obj2point))
      }
    };
    return res;
  };
  
  Point.prototype.inspect = function inspect() {
    if (this.isInfinity())
      return '<EC Point Infinity>';
    return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
        ' y: ' + this.y.fromRed().toString(16, 2) + '>';
  };
  
  Point.prototype.isInfinity = function isInfinity() {
    return this.inf;
  };
  
  Point.prototype.add = function add(p) {
    // O + P = P
    if (this.inf)
      return p;
  
    // P + O = P
    if (p.inf)
      return this;
  
    // P + P = 2P
    if (this.eq(p))
      return this.dbl();
  
    // P + (-P) = O
    if (this.neg().eq(p))
      return this.curve.point(null, null);
  
    // P + Q = O
    if (this.x.cmp(p.x) === 0)
      return this.curve.point(null, null);
  
    var c = this.y.redSub(p.y);
    if (c.cmpn(0) !== 0)
      c = c.redMul(this.x.redSub(p.x).redInvm());
    var nx = c.redSqr().redISub(this.x).redISub(p.x);
    var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
    return this.curve.point(nx, ny);
  };
  
  Point.prototype.dbl = function dbl() {
    if (this.inf)
      return this;
  
    // 2P = O
    var ys1 = this.y.redAdd(this.y);
    if (ys1.cmpn(0) === 0)
      return this.curve.point(null, null);
  
    var a = this.curve.a;
  
    var x2 = this.x.redSqr();
    var dyinv = ys1.redInvm();
    var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);
  
    var nx = c.redSqr().redISub(this.x.redAdd(this.x));
    var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
    return this.curve.point(nx, ny);
  };
  
  Point.prototype.getX = function getX() {
    return this.x.fromRed();
  };
  
  Point.prototype.getY = function getY() {
    return this.y.fromRed();
  };
  
  Point.prototype.mul = function mul(k) {
    k = new bn(k, 16);
  
    if (this._hasDoubles(k))
      return this.curve._fixedNafMul(this, k);
    else if (this.curve.endo)
      return this.curve._endoWnafMulAdd([ this ], [ k ]);
    else
      return this.curve._wnafMul(this, k);
  };
  
  Point.prototype.mulAdd = function mulAdd(k1, p2, k2) {
    var points = [ this, p2 ];
    var coeffs = [ k1, k2 ];
    if (this.curve.endo)
      return this.curve._endoWnafMulAdd(points, coeffs);
    else
      return this.curve._wnafMulAdd(1, points, coeffs, 2);
  };
  
  Point.prototype.eq = function eq(p) {
    return this === p ||
           this.inf === p.inf &&
               (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);
  };
  
  Point.prototype.neg = function neg(_precompute) {
    if (this.inf)
      return this;
  
    var res = this.curve.point(this.x, this.y.redNeg());
    if (_precompute && this.precomputed) {
      var pre = this.precomputed;
      var negate = function(p) {
        return p.neg();
      };
      res.precomputed = {
        naf: pre.naf && {
          wnd: pre.naf.wnd,
          points: pre.naf.points.map(negate)
        },
        doubles: pre.doubles && {
          step: pre.doubles.step,
          points: pre.doubles.points.map(negate)
        }
      };
    }
    return res;
  };
  
  Point.prototype.toJ = function toJ() {
    if (this.inf)
      return this.curve.jpoint(null, null, null);
  
    var res = this.curve.jpoint(this.x, this.y, this.curve.one);
    return res;
  };
  
  function JPoint(curve, x, y, z) {
    Base.BasePoint.call(this, curve, 'jacobian');
    if (x === null && y === null && z === null) {
      this.x = this.curve.one;
      this.y = this.curve.one;
      this.z = new bn(0);
    } else {
      this.x = new bn(x, 16);
      this.y = new bn(y, 16);
      this.z = new bn(z, 16);
    }
    if (!this.x.red)
      this.x = this.x.toRed(this.curve.red);
    if (!this.y.red)
      this.y = this.y.toRed(this.curve.red);
    if (!this.z.red)
      this.z = this.z.toRed(this.curve.red);
  
    this.zOne = this.z === this.curve.one;
  }
  inherits(JPoint, Base.BasePoint);
  
  ShortCurve.prototype.jpoint = function jpoint(x, y, z) {
    return new JPoint(this, x, y, z);
  };
  
  JPoint.prototype.toP = function toP() {
    if (this.isInfinity())
      return this.curve.point(null, null);
  
    var zinv = this.z.redInvm();
    var zinv2 = zinv.redSqr();
    var ax = this.x.redMul(zinv2);
    var ay = this.y.redMul(zinv2).redMul(zinv);
  
    return this.curve.point(ax, ay);
  };
  
  JPoint.prototype.neg = function neg() {
    return this.curve.jpoint(this.x, this.y.redNeg(), this.z);
  };
  
  JPoint.prototype.add = function add(p) {
    // O + P = P
    if (this.isInfinity())
      return p;
  
    // P + O = P
    if (p.isInfinity())
      return this;
  
    // 12M + 4S + 7A
    var pz2 = p.z.redSqr();
    var z2 = this.z.redSqr();
    var u1 = this.x.redMul(pz2);
    var u2 = p.x.redMul(z2);
    var s1 = this.y.redMul(pz2.redMul(p.z));
    var s2 = p.y.redMul(z2.redMul(this.z));
  
    var h = u1.redSub(u2);
    var r = s1.redSub(s2);
    if (h.cmpn(0) === 0) {
      if (r.cmpn(0) !== 0)
        return this.curve.jpoint(null, null, null);
      else
        return this.dbl();
    }
  
    var h2 = h.redSqr();
    var h3 = h2.redMul(h);
    var v = u1.redMul(h2);
  
    var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
    var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
    var nz = this.z.redMul(p.z).redMul(h);
  
    return this.curve.jpoint(nx, ny, nz);
  };
  
  JPoint.prototype.mixedAdd = function mixedAdd(p) {
    // O + P = P
    if (this.isInfinity())
      return p.toJ();
  
    // P + O = P
    if (p.isInfinity())
      return this;
  
    // 8M + 3S + 7A
    var z2 = this.z.redSqr();
    var u1 = this.x;
    var u2 = p.x.redMul(z2);
    var s1 = this.y;
    var s2 = p.y.redMul(z2).redMul(this.z);
  
    var h = u1.redSub(u2);
    var r = s1.redSub(s2);
    if (h.cmpn(0) === 0) {
      if (r.cmpn(0) !== 0)
        return this.curve.jpoint(null, null, null);
      else
        return this.dbl();
    }
  
    var h2 = h.redSqr();
    var h3 = h2.redMul(h);
    var v = u1.redMul(h2);
  
    var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
    var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
    var nz = this.z.redMul(h);
  
    return this.curve.jpoint(nx, ny, nz);
  };
  
  JPoint.prototype.dblp = function dblp(pow) {
    if (pow === 0)
      return this;
    if (this.isInfinity())
      return this;
    if (!pow)
      return this.dbl();
  
    if (this.curve.zeroA || this.curve.threeA) {
      var r = this;
      for (var i = 0; i < pow; i++)
        r = r.dbl();
      return r;
    }
  
    // 1M + 2S + 1A + N * (4S + 5M + 8A)
    // N = 1 => 6M + 6S + 9A
    var a = this.curve.a;
    var tinv = this.curve.tinv;
  
    var jx = this.x;
    var jy = this.y;
    var jz = this.z;
    var jz4 = jz.redSqr().redSqr();
  
    // Reuse results
    var jyd = jy.redAdd(jy);
    for (var i = 0; i < pow; i++) {
      var jx2 = jx.redSqr();
      var jyd2 = jyd.redSqr();
      var jyd4 = jyd2.redSqr();
      var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
  
      var t1 = jx.redMul(jyd2);
      var nx = c.redSqr().redISub(t1.redAdd(t1));
      var t2 = t1.redISub(nx);
      var dny = c.redMul(t2);
      dny = dny.redIAdd(dny).redISub(jyd4);
      var nz = jyd.redMul(jz);
      if (i + 1 < pow)
        jz4 = jz4.redMul(jyd4);
  
      jx = nx;
      jz = nz;
      jyd = dny;
    }
  
    return this.curve.jpoint(jx, jyd.redMul(tinv), jz);
  };
  
  JPoint.prototype.dbl = function dbl() {
    if (this.isInfinity())
      return this;
  
    if (this.curve.zeroA)
      return this._zeroDbl();
    else if (this.curve.threeA)
      return this._threeDbl();
    else
      return this._dbl();
  };
  
  JPoint.prototype._zeroDbl = function _zeroDbl() {
    var nx;
    var ny;
    var nz;
    // Z = 1
    if (this.zOne) {
      // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
      //     #doubling-mdbl-2007-bl
      // 1M + 5S + 14A
  
      // XX = X1^2
      var xx = this.x.redSqr();
      // YY = Y1^2
      var yy = this.y.redSqr();
      // YYYY = YY^2
      var yyyy = yy.redSqr();
      // S = 2 * ((X1 + YY)^2 - XX - YYYY)
      var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
      s = s.redIAdd(s);
      // M = 3 * XX + a; a = 0
      var m = xx.redAdd(xx).redIAdd(xx);
      // T = M ^ 2 - 2*S
      var t = m.redSqr().redISub(s).redISub(s);
  
      // 8 * YYYY
      var yyyy8 = yyyy.redIAdd(yyyy);
      yyyy8 = yyyy8.redIAdd(yyyy8);
      yyyy8 = yyyy8.redIAdd(yyyy8);
  
      // X3 = T
      nx = t;
      // Y3 = M * (S - T) - 8 * YYYY
      ny = m.redMul(s.redISub(t)).redISub(yyyy8);
      // Z3 = 2*Y1
      nz = this.y.redAdd(this.y);
    } else {
      // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
      //     #doubling-dbl-2009-l
      // 2M + 5S + 13A
  
      // A = X1^2
      var a = this.x.redSqr();
      // B = Y1^2
      var b = this.y.redSqr();
      // C = B^2
      var c = b.redSqr();
      // D = 2 * ((X1 + B)^2 - A - C)
      var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);
      d = d.redIAdd(d);
      // E = 3 * A
      var e = a.redAdd(a).redIAdd(a);
      // F = E^2
      var f = e.redSqr();
  
      // 8 * C
      var c8 = c.redIAdd(c);
      c8 = c8.redIAdd(c8);
      c8 = c8.redIAdd(c8);
  
      // X3 = F - 2 * D
      nx = f.redISub(d).redISub(d);
      // Y3 = E * (D - X3) - 8 * C
      ny = e.redMul(d.redISub(nx)).redISub(c8);
      // Z3 = 2 * Y1 * Z1
      nz = this.y.redMul(this.z);
      nz = nz.redIAdd(nz);
    }
  
    return this.curve.jpoint(nx, ny, nz);
  };
  
  JPoint.prototype._threeDbl = function _threeDbl() {
    var nx;
    var ny;
    var nz;
    // Z = 1
    if (this.zOne) {
      // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html
      //     #doubling-mdbl-2007-bl
      // 1M + 5S + 15A
  
      // XX = X1^2
      var xx = this.x.redSqr();
      // YY = Y1^2
      var yy = this.y.redSqr();
      // YYYY = YY^2
      var yyyy = yy.redSqr();
      // S = 2 * ((X1 + YY)^2 - XX - YYYY)
      var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
      s = s.redIAdd(s);
      // M = 3 * XX + a
      var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);
      // T = M^2 - 2 * S
      var t = m.redSqr().redISub(s).redISub(s);
      // X3 = T
      nx = t;
      // Y3 = M * (S - T) - 8 * YYYY
      var yyyy8 = yyyy.redIAdd(yyyy);
      yyyy8 = yyyy8.redIAdd(yyyy8);
      yyyy8 = yyyy8.redIAdd(yyyy8);
      ny = m.redMul(s.redISub(t)).redISub(yyyy8);
      // Z3 = 2 * Y1
      nz = this.y.redAdd(this.y);
    } else {
      // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
      // 3M + 5S
  
      // delta = Z1^2
      var delta = this.z.redSqr();
      // gamma = Y1^2
      var gamma = this.y.redSqr();
      // beta = X1 * gamma
      var beta = this.x.redMul(gamma);
      // alpha = 3 * (X1 - delta) * (X1 + delta)
      var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));
      alpha = alpha.redAdd(alpha).redIAdd(alpha);
      // X3 = alpha^2 - 8 * beta
      var beta4 = beta.redIAdd(beta);
      beta4 = beta4.redIAdd(beta4);
      var beta8 = beta4.redAdd(beta4);
      nx = alpha.redSqr().redISub(beta8);
      // Z3 = (Y1 + Z1)^2 - gamma - delta
      nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);
      // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2
      var ggamma8 = gamma.redSqr();
      ggamma8 = ggamma8.redIAdd(ggamma8);
      ggamma8 = ggamma8.redIAdd(ggamma8);
      ggamma8 = ggamma8.redIAdd(ggamma8);
      ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);
    }
  
    return this.curve.jpoint(nx, ny, nz);
  };
  
  JPoint.prototype._dbl = function _dbl() {
    var a = this.curve.a;
  
    // 4M + 6S + 10A
    var jx = this.x;
    var jy = this.y;
    var jz = this.z;
    var jz4 = jz.redSqr().redSqr();
  
    var jx2 = jx.redSqr();
    var jy2 = jy.redSqr();
  
    var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
  
    var jxd4 = jx.redAdd(jx);
    jxd4 = jxd4.redIAdd(jxd4);
    var t1 = jxd4.redMul(jy2);
    var nx = c.redSqr().redISub(t1.redAdd(t1));
    var t2 = t1.redISub(nx);
  
    var jyd8 = jy2.redSqr();
    jyd8 = jyd8.redIAdd(jyd8);
    jyd8 = jyd8.redIAdd(jyd8);
    jyd8 = jyd8.redIAdd(jyd8);
    var ny = c.redMul(t2).redISub(jyd8);
    var nz = jy.redAdd(jy).redMul(jz);
  
    return this.curve.jpoint(nx, ny, nz);
  };
  
  JPoint.prototype.trpl = function trpl() {
    if (!this.curve.zeroA)
      return this.dbl().add(this);
  
    // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl
    // 5M + 10S + ...
  
    // XX = X1^2
    var xx = this.x.redSqr();
    // YY = Y1^2
    var yy = this.y.redSqr();
    // ZZ = Z1^2
    var zz = this.z.redSqr();
    // YYYY = YY^2
    var yyyy = yy.redSqr();
    // M = 3 * XX + a * ZZ2; a = 0
    var m = xx.redAdd(xx).redIAdd(xx);
    // MM = M^2
    var mm = m.redSqr();
    // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM
    var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
    e = e.redIAdd(e);
    e = e.redAdd(e).redIAdd(e);
    e = e.redISub(mm);
    // EE = E^2
    var ee = e.redSqr();
    // T = 16*YYYY
    var t = yyyy.redIAdd(yyyy);
    t = t.redIAdd(t);
    t = t.redIAdd(t);
    t = t.redIAdd(t);
    // U = (M + E)^2 - MM - EE - T
    var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);
    // X3 = 4 * (X1 * EE - 4 * YY * U)
    var yyu4 = yy.redMul(u);
    yyu4 = yyu4.redIAdd(yyu4);
    yyu4 = yyu4.redIAdd(yyu4);
    var nx = this.x.redMul(ee).redISub(yyu4);
    nx = nx.redIAdd(nx);
    nx = nx.redIAdd(nx);
    // Y3 = 8 * Y1 * (U * (T - U) - E * EE)
    var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));
    ny = ny.redIAdd(ny);
    ny = ny.redIAdd(ny);
    ny = ny.redIAdd(ny);
    // Z3 = (Z1 + E)^2 - ZZ - EE
    var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);
  
    return this.curve.jpoint(nx, ny, nz);
  };
  
  JPoint.prototype.mul = function mul(k, kbase) {
    k = new bn(k, kbase);
  
    return this.curve._wnafMul(this, k);
  };
  
  JPoint.prototype.eq = function eq(p) {
    if (p.type === 'affine')
      return this.eq(p.toJ());
  
    if (this === p)
      return true;
  
    // x1 * z2^2 == x2 * z1^2
    var z2 = this.z.redSqr();
    var pz2 = p.z.redSqr();
    if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)
      return false;
  
    // y1 * z2^3 == y2 * z1^3
    var z3 = z2.redMul(this.z);
    var pz3 = pz2.redMul(p.z);
    return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;
  };
  
  JPoint.prototype.inspect = function inspect() {
    if (this.isInfinity())
      return '<EC JPoint Infinity>';
    return '<EC JPoint x: ' + this.x.toString(16, 2) +
        ' y: ' + this.y.toString(16, 2) +
        ' z: ' + this.z.toString(16, 2) + '>';
  };
  
  JPoint.prototype.isInfinity = function isInfinity() {
    // XXX This code assumes that zero is always zero in red
    return this.z.cmpn(0) === 0;
  };
  
  },{"../../elliptic":12,"../curve":15,"bn.js":3,"inherits":39}],18:[function(require,module,exports){
  'use strict';
  
  var curves = exports;
  
  var hash = require('hash.js');
  var elliptic = require('../elliptic');
  
  var assert = elliptic.utils.assert;
  
  function PresetCurve(options) {
    if (options.type === 'short')
      this.curve = new elliptic.curve.short(options);
    else if (options.type === 'edwards')
      this.curve = new elliptic.curve.edwards(options);
    else
      this.curve = new elliptic.curve.mont(options);
    this.g = this.curve.g;
    this.n = this.curve.n;
    this.hash = options.hash;
  
    assert(this.g.validate(), 'Invalid curve');
    assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O');
  }
  curves.PresetCurve = PresetCurve;
  
  function defineCurve(name, options) {
    Object.defineProperty(curves, name, {
      configurable: true,
      enumerable: true,
      get: function() {
        var curve = new PresetCurve(options);
        Object.defineProperty(curves, name, {
          configurable: true,
          enumerable: true,
          value: curve
        });
        return curve;
      }
    });
  }
  
  defineCurve('p192', {
    type: 'short',
    prime: 'p192',
    p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',
    a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',
    b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',
    n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',
    hash: hash.sha256,
    gRed: false,
    g: [
      '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',
      '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811'
    ]
  });
  
  defineCurve('p224', {
    type: 'short',
    prime: 'p224',
    p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',
    a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',
    b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',
    n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',
    hash: hash.sha256,
    gRed: false,
    g: [
      'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',
      'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34'
    ]
  });
  
  defineCurve('p256', {
    type: 'short',
    prime: null,
    p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',
    a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',
    b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',
    n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',
    hash: hash.sha256,
    gRed: false,
    g: [
      '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',
      '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5'
    ]
  });
  
  defineCurve('p384', {
    type: 'short',
    prime: null,
    p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
       'fffffffe ffffffff 00000000 00000000 ffffffff',
    a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
       'fffffffe ffffffff 00000000 00000000 fffffffc',
    b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +
       '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',
    n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +
       'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',
    hash: hash.sha384,
    gRed: false,
    g: [
      'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +
      '5502f25d bf55296c 3a545e38 72760ab7',
      '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +
      '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'
    ]
  });
  
  defineCurve('p521', {
    type: 'short',
    prime: null,
    p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
       'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
       'ffffffff ffffffff ffffffff ffffffff ffffffff',
    a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
       'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
       'ffffffff ffffffff ffffffff ffffffff fffffffc',
    b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +
       '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +
       '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',
    n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
       'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +
       'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',
    hash: hash.sha512,
    gRed: false,
    g: [
      '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +
      '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +
      'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',
      '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +
      '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +
      '3fad0761 353c7086 a272c240 88be9476 9fd16650'
    ]
  });
  
  defineCurve('curve25519', {
    type: 'mont',
    prime: 'p25519',
    p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
    a: '76d06',
    b: '0',
    n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
    hash: hash.sha256,
    gRed: false,
    g: [
      '9'
    ]
  });
  
  defineCurve('ed25519', {
    type: 'edwards',
    prime: 'p25519',
    p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
    a: '-1',
    c: '1',
    // -121665 * (121666^(-1)) (mod P)
    d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',
    n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
    hash: hash.sha256,
    gRed: false,
    g: [
      '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',
  
      // 4/5
      '6666666666666666666666666666666666666666666666666666666666666658'
    ]
  });
  
  var pre;
  try {
    pre = require('./precomputed/secp256k1');
  } catch (e) {
    pre = undefined;
  }
  
  defineCurve('secp256k1', {
    type: 'short',
    prime: 'k256',
    p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',
    a: '0',
    b: '7',
    n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',
    h: '1',
    hash: hash.sha256,
  
    // Precomputed endomorphism
    beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',
    lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',
    basis: [
      {
        a: '3086d221a7d46bcde86c90e49284eb15',
        b: '-e4437ed6010e88286f547fa90abfe4c3'
      },
      {
        a: '114ca50f7a8e2f3f657c1108d9d44cfd8',
        b: '3086d221a7d46bcde86c90e49284eb15'
      }
    ],
  
    gRed: false,
    g: [
      '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
      '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',
      pre
    ]
  });
  
  },{"../elliptic":12,"./precomputed/secp256k1":26,"hash.js":33}],19:[function(require,module,exports){
  'use strict';
  
  var bn = require('bn.js');
  var elliptic = require('../../elliptic');
  var utils = elliptic.utils;
  var assert = utils.assert;
  
  var KeyPair = require('./key');
  var Signature = require('./signature');
  
  function EC(options) {
    if (!(this instanceof EC))
      return new EC(options);
  
    // Shortcut `elliptic.ec(curve-name)`
    if (typeof options === 'string') {
      assert(elliptic.curves.hasOwnProperty(options), 'Unknown curve ' + options);
  
      options = elliptic.curves[options];
    }
  
    // Shortcut for `elliptic.ec(elliptic.curves.curveName)`
    if (options instanceof elliptic.curves.PresetCurve)
      options = { curve: options };
  
    this.curve = options.curve.curve;
    this.n = this.curve.n;
    this.nh = this.n.ushrn(1);
    this.g = this.curve.g;
  
    // Point on curve
    this.g = options.curve.g;
    this.g.precompute(options.curve.n.bitLength() + 1);
  
    // Hash for function for DRBG
    this.hash = options.hash || options.curve.hash;
  }
  module.exports = EC;
  
  EC.prototype.keyPair = function keyPair(options) {
    return new KeyPair(this, options);
  };
  
  EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {
    return KeyPair.fromPrivate(this, priv, enc);
  };
  
  EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {
    return KeyPair.fromPublic(this, pub, enc);
  };
  
  EC.prototype.genKeyPair = function genKeyPair(options) {
    if (!options)
      options = {};
  
    // Instantiate Hmac_DRBG
    var drbg = new elliptic.hmacDRBG({
      hash: this.hash,
      pers: options.pers,
      entropy: options.entropy || elliptic.rand(this.hash.hmacStrength),
      nonce: this.n.toArray()
    });
  
    var bytes = this.n.byteLength();
    var ns2 = this.n.sub(new bn(2));
    do {
      var priv = new bn(drbg.generate(bytes));
      if (priv.cmp(ns2) > 0)
        continue;
  
      priv.iaddn(1);
      return this.keyFromPrivate(priv);
    } while (true);
  };
  
  EC.prototype._truncateToN = function truncateToN(msg, truncOnly) {
    var delta = msg.byteLength() * 8 - this.n.bitLength();
    if (delta > 0)
      msg = msg.ushrn(delta);
    if (!truncOnly && msg.cmp(this.n) >= 0)
      return msg.sub(this.n);
    else
      return msg;
  };
  
  EC.prototype.sign = function sign(msg, key, enc, options) {
    if (typeof enc === 'object') {
      options = enc;
      enc = null;
    }
    if (!options)
      options = {};
  
    key = this.keyFromPrivate(key, enc);
    msg = this._truncateToN(new bn(msg, 16));
  
    // Zero-extend key to provide enough entropy
    var bytes = this.n.byteLength();
    var bkey = key.getPrivate().toArray();
    for (var i = bkey.length; i < bytes; i++)
      bkey.unshift(0);
  
    // Zero-extend nonce to have the same byte size as N
    var nonce = msg.toArray();
    for (var i = nonce.length; i < bytes; i++)
      nonce.unshift(0);
  
    // Instantiate Hmac_DRBG
    var drbg = new elliptic.hmacDRBG({
      hash: this.hash,
      entropy: bkey,
      nonce: nonce
    });
  
    // Number of bytes to generate
    var ns1 = this.n.sub(new bn(1));
    do {
      var k = new bn(drbg.generate(this.n.byteLength()));
      k = this._truncateToN(k, true);
      if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)
        continue;
  
      var kp = this.g.mul(k);
      if (kp.isInfinity())
        continue;
  
      var kpX = kp.getX();
      var r = kpX.umod(this.n);
      if (r.cmpn(0) === 0)
        continue;
  
      var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));
      s = s.umod(this.n);
      if (s.cmpn(0) === 0)
        continue;
  
      // Use complement of `s`, if it is > `n / 2`
      if (options.canonical && s.cmp(this.nh) > 0)
        s = this.n.sub(s);
  
      var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |
                          (kpX.cmp(r) !== 0 ? 2 : 0);
  
      return new Signature({ r: r, s: s, recoveryParam: recoveryParam });
    } while (true);
  };
  
  EC.prototype.verify = function verify(msg, signature, key, enc) {
    msg = this._truncateToN(new bn(msg, 16));
    key = this.keyFromPublic(key, enc);
    signature = new Signature(signature, 'hex');
  
    // Perform primitive values validation
    var r = signature.r;
    var s = signature.s;
    if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)
      return false;
    if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)
      return false;
  
    // Validate signature
    var sinv = s.invm(this.n);
    var u1 = sinv.mul(msg).umod(this.n);
    var u2 = sinv.mul(r).umod(this.n);
  
    var p = this.g.mulAdd(u1, key.getPublic(), u2);
    if (p.isInfinity())
      return false;
  
    return p.getX().umod(this.n).cmp(r) === 0;
  };
  
  EC.prototype.recoverPubKey = function(msg, signature, j, enc) {
    assert((3 & j) === j, 'The recovery param is more than two bits');
    signature = new Signature(signature, enc);
  
    var n = this.n;
    var e = new bn(msg);
    var r = signature.r;
    var s = signature.s;
  
    // A set LSB signifies that the y-coordinate is odd
    var isYOdd = j & 1;
    var isSecondKey = j >> 1;
    if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)
      throw new Error('Unable to find sencond key candinate');
  
    // 1.1. Let x = r + jn.
    r = this.curve.pointFromX(r, isYOdd);
    var eNeg = e.neg().umod(n);
  
    // 1.6.1 Compute Q = r^-1 (sR -  eG)
    //               Q = r^-1 (sR + -eG)
    var rInv = signature.r.invm(n);
    return r.mul(s).add(this.g.mul(eNeg)).mul(rInv);
  };
  
  EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {
    signature = new Signature(signature, enc);
    if (signature.recoveryParam !== null)
      return signature.recoveryParam;
  
    for (var i = 0; i < 4; i++) {
      var Qprime = this.recoverPubKey(e, signature, i);
  
      if (Qprime.eq(Q))
        return i;
    }
    throw new Error('Unable to find valid recovery factor');
  };
  
  },{"../../elliptic":12,"./key":20,"./signature":21,"bn.js":3}],20:[function(require,module,exports){
  'use strict';
  
  var bn = require('bn.js');
  
  function KeyPair(ec, options) {
    this.ec = ec;
    this.priv = null;
    this.pub = null;
  
    // KeyPair(ec, { priv: ..., pub: ... })
    if (options.priv)
      this._importPrivate(options.priv, options.privEnc);
    if (options.pub)
      this._importPublic(options.pub, options.pubEnc);
  }
  module.exports = KeyPair;
  
  KeyPair.fromPublic = function fromPublic(ec, pub, enc) {
    if (pub instanceof KeyPair)
      return pub;
  
    return new KeyPair(ec, {
      pub: pub,
      pubEnc: enc
    });
  };
  
  KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {
    if (priv instanceof KeyPair)
      return priv;
  
    return new KeyPair(ec, {
      priv: priv,
      privEnc: enc
    });
  };
  
  KeyPair.prototype.validate = function validate() {
    var pub = this.getPublic();
  
    if (pub.isInfinity())
      return { result: false, reason: 'Invalid public key' };
    if (!pub.validate())
      return { result: false, reason: 'Public key is not a point' };
    if (!pub.mul(this.ec.curve.n).isInfinity())
      return { result: false, reason: 'Public key * N != O' };
  
    return { result: true, reason: null };
  };
  
  KeyPair.prototype.getPublic = function getPublic(compact, enc) {
    // compact is optional argument
    if (typeof compact === 'string') {
      enc = compact;
      compact = null;
    }
  
    if (!this.pub)
      this.pub = this.ec.g.mul(this.priv);
  
    if (!enc)
      return this.pub;
  
    return this.pub.encode(enc, compact);
  };
  
  KeyPair.prototype.getPrivate = function getPrivate(enc) {
    if (enc === 'hex')
      return this.priv.toString(16, 2);
    else
      return this.priv;
  };
  
  KeyPair.prototype._importPrivate = function _importPrivate(key, enc) {
    this.priv = new bn(key, enc || 16);
  
    // Ensure that the priv won't be bigger than n, otherwise we may fail
    // in fixed multiplication method
    this.priv = this.priv.umod(this.ec.curve.n);
  };
  
  KeyPair.prototype._importPublic = function _importPublic(key, enc) {
    if (key.x || key.y) {
      this.pub = this.ec.curve.point(key.x, key.y);
      return;
    }
    this.pub = this.ec.curve.decodePoint(key, enc);
  };
  
  // ECDH
  KeyPair.prototype.derive = function derive(pub) {
    return pub.mul(this.priv).getX();
  };
  
  // ECDSA
  KeyPair.prototype.sign = function sign(msg, enc, options) {
    return this.ec.sign(msg, this, enc, options);
  };
  
  KeyPair.prototype.verify = function verify(msg, signature) {
    return this.ec.verify(msg, signature, this);
  };
  
  KeyPair.prototype.inspect = function inspect() {
    return '<Key priv: ' + (this.priv && this.priv.toString(16, 2)) +
           ' pub: ' + (this.pub && this.pub.inspect()) + ' >';
  };
  
  },{"bn.js":3}],21:[function(require,module,exports){
  'use strict';
  
  var bn = require('bn.js');
  
  var elliptic = require('../../elliptic');
  var utils = elliptic.utils;
  var assert = utils.assert;
  
  function Signature(options, enc) {
    if (options instanceof Signature)
      return options;
  
    if (this._importDER(options, enc))
      return;
  
    assert(options.r && options.s, 'Signature without r or s');
    this.r = new bn(options.r, 16);
    this.s = new bn(options.s, 16);
    if (options.recoveryParam !== null)
      this.recoveryParam = options.recoveryParam;
    else
      this.recoveryParam = null;
  }
  module.exports = Signature;
  
  function Position() {
    this.place = 0;
  }
  
  function getLength(buf, p) {
    var initial = buf[p.place++];
    if (!(initial & 0x80)) {
      return initial;
    }
    var octetLen = initial & 0xf;
    var val = 0;
    for (var i = 0, off = p.place; i < octetLen; i++, off++) {
      val <<= 8;
      val |= buf[off];
    }
    p.place = off;
    return val;
  }
  
  function rmPadding(buf) {
    var i = 0;
    var len = buf.length - 1;
    while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {
      i++;
    }
    if (i === 0) {
      return buf;
    }
    return buf.slice(i);
  }
  
  Signature.prototype._importDER = function _importDER(data, enc) {
    data = utils.toArray(data, enc);
    var p = new Position();
    if (data[p.place++] !== 0x30) {
      return false;
    }
    var len = getLength(data, p);
    if ((len + p.place) !== data.length) {
      return false;
    }
    if (data[p.place++] !== 0x02) {
      return false;
    }
    var rlen = getLength(data, p);
    var r = data.slice(p.place, rlen + p.place);
    p.place += rlen;
    if (data[p.place++] !== 0x02) {
      return false;
    }
    var slen = getLength(data, p);
    if (data.length !== slen + p.place) {
      return false;
    }
    var s = data.slice(p.place, slen + p.place);
    if (r[0] === 0 && (r[1] & 0x80)) {
      r = r.slice(1);
    }
    if (s[0] === 0 && (s[1] & 0x80)) {
      s = s.slice(1);
    }
  
    this.r = new bn(r);
    this.s = new bn(s);
    this.recoveryParam = null;
  
    return true;
  };
  
  function constructLength(arr, len) {
    if (len < 0x80) {
      arr.push(len);
      return;
    }
    var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);
    arr.push(octets | 0x80);
    while (--octets) {
      arr.push((len >>> (octets << 3)) & 0xff);
    }
    arr.push(len);
  }
  
  Signature.prototype.toDER = function toDER(enc) {
    var r = this.r.toArray();
    var s = this.s.toArray();
  
    // Pad values
    if (r[0] & 0x80)
      r = [ 0 ].concat(r);
    // Pad values
    if (s[0] & 0x80)
      s = [ 0 ].concat(s);
  
    r = rmPadding(r);
    s = rmPadding(s);
  
    while (!s[0] && !(s[1] & 0x80)) {
      s = s.slice(1);
    }
    var arr = [ 0x02 ];
    constructLength(arr, r.length);
    arr = arr.concat(r);
    arr.push(0x02);
    constructLength(arr, s.length);
    var backHalf = arr.concat(s);
    var res = [ 0x30 ];
    constructLength(res, backHalf.length);
    res = res.concat(backHalf);
    return utils.encode(res, enc);
  };
  
  },{"../../elliptic":12,"bn.js":3}],22:[function(require,module,exports){
  'use strict';
  
  var hash = require('hash.js');
  var elliptic = require('../../elliptic');
  var utils = elliptic.utils;
  var assert = utils.assert;
  var parseBytes = utils.parseBytes;
  var KeyPair = require('./key');
  var Signature = require('./signature');
  
  function EDDSA(curve) {
    assert(curve === 'ed25519', 'only tested with ed25519 so far');
  
    if (!(this instanceof EDDSA))
      return new EDDSA(curve);
  
    var curve = elliptic.curves[curve].curve;
    this.curve = curve;
    this.g = curve.g;
    this.g.precompute(curve.n.bitLength() + 1);
  
    this.pointClass = curve.point().constructor;
    this.encodingLength = Math.ceil(curve.n.bitLength() / 8);
    this.hash = hash.sha512;
  }
  
  module.exports = EDDSA;
  
  /**
  * @param {Array|String} message - message bytes
  * @param {Array|String|KeyPair} secret - secret bytes or a keypair
  * @returns {Signature} - signature
  */
  EDDSA.prototype.sign = function sign(message, secret) {
    message = parseBytes(message);
    var key = this.keyFromSecret(secret);
    var r = this.hashInt(key.messagePrefix(), message);
    var R = this.g.mul(r);
    var Rencoded = this.encodePoint(R);
    var s_ = this.hashInt(Rencoded, key.pubBytes(), message)
                 .mul(key.priv());
    var S = r.add(s_).umod(this.curve.n);
    return this.makeSignature({ R: R, S: S, Rencoded: Rencoded });
  };
  
  /**
  * @param {Array} message - message bytes
  * @param {Array|String|Signature} sig - sig bytes
  * @param {Array|String|Point|KeyPair} pub - public key
  * @returns {Boolean} - true if public key matches sig of message
  */
  EDDSA.prototype.verify = function verify(message, sig, pub) {
    message = parseBytes(message);
    sig = this.makeSignature(sig);
    var key = this.keyFromPublic(pub);
    var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message);
    var SG = this.g.mul(sig.S());
    var RplusAh = sig.R().add(key.pub().mul(h));
    return RplusAh.eq(SG);
  };
  
  EDDSA.prototype.hashInt = function hashInt() {
    var hash = this.hash();
    for (var i = 0; i < arguments.length; i++)
      hash.update(arguments[i]);
    return utils.intFromLE(hash.digest()).umod(this.curve.n);
  };
  
  EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) {
    return KeyPair.fromPublic(this, pub);
  };
  
  EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) {
    return KeyPair.fromSecret(this, secret);
  };
  
  EDDSA.prototype.makeSignature = function makeSignature(sig) {
    if (sig instanceof Signature)
      return sig;
    return new Signature(this, sig);
  };
  
  /**
  * * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2
  *
  * EDDSA defines methods for encoding and decoding points and integers. These are
  * helper convenience methods, that pass along to utility functions implied
  * parameters.
  *
  */
  EDDSA.prototype.encodePoint = function encodePoint(point) {
    var enc = point.getY().toArray('le', this.encodingLength);
    enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0;
    return enc;
  };
  
  EDDSA.prototype.decodePoint = function decodePoint(bytes) {
    bytes = utils.parseBytes(bytes);
  
    var lastIx = bytes.length - 1;
    var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80);
    var xIsOdd = (bytes[lastIx] & 0x80) !== 0;
  
    var y = utils.intFromLE(normed);
    return this.curve.pointFromY(y, xIsOdd);
  };
  
  EDDSA.prototype.encodeInt = function encodeInt(num) {
    return num.toArray('le', this.encodingLength);
  };
  
  EDDSA.prototype.decodeInt = function decodeInt(bytes) {
    return utils.intFromLE(bytes);
  };
  
  EDDSA.prototype.isPoint = function isPoint(val) {
    return val instanceof this.pointClass;
  };
  
  },{"../../elliptic":12,"./key":23,"./signature":24,"hash.js":33}],23:[function(require,module,exports){
  'use strict';
  
  var elliptic = require('../../elliptic');
  var utils = elliptic.utils;
  var assert = utils.assert;
  var parseBytes = utils.parseBytes;
  var cachedProperty = utils.cachedProperty;
  
  /**
  * @param {EDDSA} eddsa - instance
  * @param {Object} params - public/private key parameters
  *
  * @param {Array<Byte>} [params.secret] - secret seed bytes
  * @param {Point} [params.pub] - public key point (aka `A` in eddsa terms)
  * @param {Array<Byte>} [params.pub] - public key point encoded as bytes
  *
  */
  function KeyPair(eddsa, params) {
    this.eddsa = eddsa;
    this._secret = parseBytes(params.secret);
    if (eddsa.isPoint(params.pub))
      this._pub = params.pub;
    else
      this._pubBytes = parseBytes(params.pub);
  }
  
  KeyPair.fromPublic = function fromPublic(eddsa, pub) {
    if (pub instanceof KeyPair)
      return pub;
    return new KeyPair(eddsa, { pub: pub });
  };
  
  KeyPair.fromSecret = function fromSecret(eddsa, secret) {
    if (secret instanceof KeyPair)
      return secret;
    return new KeyPair(eddsa, { secret: secret });
  };
  
  KeyPair.prototype.secret = function secret() {
    return this._secret;
  };
  
  cachedProperty(KeyPair, function pubBytes() {
    return this.eddsa.encodePoint(this.pub());
  });
  
  cachedProperty(KeyPair, function pub() {
    if (this._pubBytes)
      return this.eddsa.decodePoint(this._pubBytes);
    return this.eddsa.g.mul(this.priv());
  });
  
  cachedProperty(KeyPair, function privBytes() {
    var eddsa = this.eddsa;
    var hash = this.hash();
    var lastIx = eddsa.encodingLength - 1;
  
    var a = hash.slice(0, eddsa.encodingLength);
    a[0] &= 248;
    a[lastIx] &= 127;
    a[lastIx] |= 64;
  
    return a;
  });
  
  cachedProperty(KeyPair, function priv() {
    return this.eddsa.decodeInt(this.privBytes());
  });
  
  cachedProperty(KeyPair, function hash() {
    return this.eddsa.hash().update(this.secret()).digest();
  });
  
  cachedProperty(KeyPair, function messagePrefix() {
    return this.hash().slice(this.eddsa.encodingLength);
  });
  
  KeyPair.prototype.sign = function sign(message) {
    assert(this._secret, 'KeyPair can only verify');
    return this.eddsa.sign(message, this);
  };
  
  KeyPair.prototype.verify = function verify(message, sig) {
    return this.eddsa.verify(message, sig, this);
  };
  
  KeyPair.prototype.getSecret = function getSecret(enc) {
    assert(this._secret, 'KeyPair is public only');
    return utils.encode(this.secret(), enc);
  };
  
  KeyPair.prototype.getPublic = function getPublic(enc) {
    return utils.encode(this.pubBytes(), enc);
  };
  
  module.exports = KeyPair;
  
  },{"../../elliptic":12}],24:[function(require,module,exports){
  'use strict';
  
  var bn = require('bn.js');
  var elliptic = require('../../elliptic');
  var utils = elliptic.utils;
  var assert = utils.assert;
  var cachedProperty = utils.cachedProperty;
  var parseBytes = utils.parseBytes;
  
  /**
  * @param {EDDSA} eddsa - eddsa instance
  * @param {Array<Bytes>|Object} sig -
  * @param {Array<Bytes>|Point} [sig.R] - R point as Point or bytes
  * @param {Array<Bytes>|bn} [sig.S] - S scalar as bn or bytes
  * @param {Array<Bytes>} [sig.Rencoded] - R point encoded
  * @param {Array<Bytes>} [sig.Sencoded] - S scalar encoded
  */
  function Signature(eddsa, sig) {
    this.eddsa = eddsa;
  
    if (typeof sig !== 'object')
      sig = parseBytes(sig);
  
    if (Array.isArray(sig)) {
      sig = {
        R: sig.slice(0, eddsa.encodingLength),
        S: sig.slice(eddsa.encodingLength)
      };
    }
  
    assert(sig.R && sig.S, 'Signature without R or S');
  
    if (eddsa.isPoint(sig.R))
      this._R = sig.R;
    if (sig.S instanceof bn)
      this._S = sig.S;
  
    this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;
    this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;
  }
  
  cachedProperty(Signature, function S() {
    return this.eddsa.decodeInt(this.Sencoded());
  });
  
  cachedProperty(Signature, function R() {
    return this.eddsa.decodePoint(this.Rencoded());
  });
  
  cachedProperty(Signature, function Rencoded() {
    return this.eddsa.encodePoint(this.R());
  });
  
  cachedProperty(Signature, function Sencoded() {
    return this.eddsa.encodeInt(this.S());
  });
  
  Signature.prototype.toBytes = function toBytes() {
    return this.Rencoded().concat(this.Sencoded());
  };
  
  Signature.prototype.toHex = function toHex() {
    return utils.encode(this.toBytes(), 'hex').toUpperCase();
  };
  
  module.exports = Signature;
  
  },{"../../elliptic":12,"bn.js":3}],25:[function(require,module,exports){
  'use strict';
  
  var hash = require('hash.js');
  var elliptic = require('../elliptic');
  var utils = elliptic.utils;
  var assert = utils.assert;
  
  function HmacDRBG(options) {
    if (!(this instanceof HmacDRBG))
      return new HmacDRBG(options);
    this.hash = options.hash;
    this.predResist = !!options.predResist;
  
    this.outLen = this.hash.outSize;
    this.minEntropy = options.minEntropy || this.hash.hmacStrength;
  
    this.reseed = null;
    this.reseedInterval = null;
    this.K = null;
    this.V = null;
  
    var entropy = utils.toArray(options.entropy, options.entropyEnc);
    var nonce = utils.toArray(options.nonce, options.nonceEnc);
    var pers = utils.toArray(options.pers, options.persEnc);
    assert(entropy.length >= (this.minEntropy / 8),
           'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
    this._init(entropy, nonce, pers);
  }
  module.exports = HmacDRBG;
  
  HmacDRBG.prototype._init = function init(entropy, nonce, pers) {
    var seed = entropy.concat(nonce).concat(pers);
  
    this.K = new Array(this.outLen / 8);
    this.V = new Array(this.outLen / 8);
    for (var i = 0; i < this.V.length; i++) {
      this.K[i] = 0x00;
      this.V[i] = 0x01;
    }
  
    this._update(seed);
    this.reseed = 1;
    this.reseedInterval = 0x1000000000000;  // 2^48
  };
  
  HmacDRBG.prototype._hmac = function hmac() {
    return new hash.hmac(this.hash, this.K);
  };
  
  HmacDRBG.prototype._update = function update(seed) {
    var kmac = this._hmac()
                   .update(this.V)
                   .update([ 0x00 ]);
    if (seed)
      kmac = kmac.update(seed);
    this.K = kmac.digest();
    this.V = this._hmac().update(this.V).digest();
    if (!seed)
      return;
  
    this.K = this._hmac()
                 .update(this.V)
                 .update([ 0x01 ])
                 .update(seed)
                 .digest();
    this.V = this._hmac().update(this.V).digest();
  };
  
  HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {
    // Optional entropy enc
    if (typeof entropyEnc !== 'string') {
      addEnc = add;
      add = entropyEnc;
      entropyEnc = null;
    }
  
    entropy = utils.toBuffer(entropy, entropyEnc);
    add = utils.toBuffer(add, addEnc);
  
    assert(entropy.length >= (this.minEntropy / 8),
           'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
  
    this._update(entropy.concat(add || []));
    this.reseed = 1;
  };
  
  HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {
    if (this.reseed > this.reseedInterval)
      throw new Error('Reseed is required');
  
    // Optional encoding
    if (typeof enc !== 'string') {
      addEnc = add;
      add = enc;
      enc = null;
    }
  
    // Optional additional data
    if (add) {
      add = utils.toArray(add, addEnc);
      this._update(add);
    }
  
    var temp = [];
    while (temp.length < len) {
      this.V = this._hmac().update(this.V).digest();
      temp = temp.concat(this.V);
    }
  
    var res = temp.slice(0, len);
    this._update(add);
    this.reseed++;
    return utils.encode(res, enc);
  };
  
  },{"../elliptic":12,"hash.js":33}],26:[function(require,module,exports){
  module.exports = {
    doubles: {
      step: 4,
      points: [
        [
          'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',
          'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821'
        ],
        [
          '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',
          '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf'
        ],
        [
          '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',
          'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695'
        ],
        [
          '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',
          '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9'
        ],
        [
          '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',
          '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36'
        ],
        [
          '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',
          '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f'
        ],
        [
          'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',
          '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999'
        ],
        [
          '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',
          'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09'
        ],
        [
          'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',
          '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d'
        ],
        [
          'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',
          'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088'
        ],
        [
          'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',
          '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d'
        ],
        [
          '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',
          '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8'
        ],
        [
          '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',
          '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a'
        ],
        [
          '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',
          '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453'
        ],
        [
          '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',
          '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160'
        ],
        [
          '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',
          '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0'
        ],
        [
          '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',
          '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6'
        ],
        [
          '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',
          '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589'
        ],
        [
          '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',
          'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17'
        ],
        [
          'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',
          '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda'
        ],
        [
          'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',
          '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd'
        ],
        [
          '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',
          '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2'
        ],
        [
          '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',
          '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6'
        ],
        [
          'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',
          '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f'
        ],
        [
          '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',
          'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01'
        ],
        [
          'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',
          '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3'
        ],
        [
          'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',
          'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f'
        ],
        [
          'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',
          '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7'
        ],
        [
          'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',
          'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78'
        ],
        [
          'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',
          '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1'
        ],
        [
          '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',
          'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150'
        ],
        [
          '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',
          '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82'
        ],
        [
          'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',
          '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc'
        ],
        [
          '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',
          'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b'
        ],
        [
          'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',
          '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51'
        ],
        [
          'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',
          '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45'
        ],
        [
          'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',
          'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120'
        ],
        [
          '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',
          '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84'
        ],
        [
          '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',
          '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d'
        ],
        [
          '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',
          'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d'
        ],
        [
          '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',
          '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8'
        ],
        [
          'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',
          '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8'
        ],
        [
          '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',
          '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac'
        ],
        [
          '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',
          'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f'
        ],
        [
          '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',
          '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962'
        ],
        [
          'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',
          '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907'
        ],
        [
          '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',
          'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec'
        ],
        [
          'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',
          'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d'
        ],
        [
          'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',
          '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414'
        ],
        [
          '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',
          'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd'
        ],
        [
          '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',
          'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0'
        ],
        [
          'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',
          '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811'
        ],
        [
          'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',
          '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1'
        ],
        [
          'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',
          '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c'
        ],
        [
          '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',
          'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73'
        ],
        [
          '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',
          '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd'
        ],
        [
          'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',
          'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405'
        ],
        [
          '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',
          'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589'
        ],
        [
          '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',
          '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e'
        ],
        [
          '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',
          '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27'
        ],
        [
          'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',
          'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1'
        ],
        [
          '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',
          '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482'
        ],
        [
          '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',
          '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945'
        ],
        [
          'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',
          '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573'
        ],
        [
          'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',
          'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82'
        ]
      ]
    },
    naf: {
      wnd: 7,
      points: [
        [
          'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',
          '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672'
        ],
        [
          '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',
          'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6'
        ],
        [
          '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',
          '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da'
        ],
        [
          'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',
          'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37'
        ],
        [
          '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',
          'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b'
        ],
        [
          'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',
          'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81'
        ],
        [
          'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',
          '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58'
        ],
        [
          'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',
          '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77'
        ],
        [
          '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',
          '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a'
        ],
        [
          '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',
          '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c'
        ],
        [
          '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',
          '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67'
        ],
        [
          '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',
          '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402'
        ],
        [
          'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',
          'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55'
        ],
        [
          'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',
          '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482'
        ],
        [
          '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',
          'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82'
        ],
        [
          '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',
          'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396'
        ],
        [
          '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',
          '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49'
        ],
        [
          '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',
          '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf'
        ],
        [
          '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',
          '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a'
        ],
        [
          '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',
          'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7'
        ],
        [
          'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',
          'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933'
        ],
        [
          '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',
          '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a'
        ],
        [
          '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',
          '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6'
        ],
        [
          'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',
          'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37'
        ],
        [
          '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',
          '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e'
        ],
        [
          'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',
          'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6'
        ],
        [
          'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',
          'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476'
        ],
        [
          '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',
          '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40'
        ],
        [
          '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',
          '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61'
        ],
        [
          '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',
          '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683'
        ],
        [
          'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',
          '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5'
        ],
        [
          '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',
          '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b'
        ],
        [
          'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',
          '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417'
        ],
        [
          '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',
          'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868'
        ],
        [
          '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',
          'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a'
        ],
        [
          'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',
          'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6'
        ],
        [
          '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',
          '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996'
        ],
        [
          '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',
          'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e'
        ],
        [
          'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',
          'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d'
        ],
        [
          '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',
          '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2'
        ],
        [
          '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',
          'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e'
        ],
        [
          '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',
          '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437'
        ],
        [
          '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',
          'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311'
        ],
        [
          'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',
          '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4'
        ],
        [
          '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',
          '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575'
        ],
        [
          '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',
          'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d'
        ],
        [
          '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',
          'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d'
        ],
        [
          'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',
          'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629'
        ],
        [
          'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',
          'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06'
        ],
        [
          '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',
          '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374'
        ],
        [
          '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',
          '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee'
        ],
        [
          'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',
          '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1'
        ],
        [
          'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',
          'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b'
        ],
        [
          '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',
          '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661'
        ],
        [
          '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',
          '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6'
        ],
        [
          'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',
          '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e'
        ],
        [
          '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',
          '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d'
        ],
        [
          'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',
          'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc'
        ],
        [
          '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',
          'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4'
        ],
        [
          '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',
          '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c'
        ],
        [
          'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',
          '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b'
        ],
        [
          'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',
          '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913'
        ],
        [
          '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',
          '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154'
        ],
        [
          '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',
          '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865'
        ],
        [
          '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',
          'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc'
        ],
        [
          '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',
          'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224'
        ],
        [
          '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',
          '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e'
        ],
        [
          '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',
          '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6'
        ],
        [
          '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',
          '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511'
        ],
        [
          '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',
          'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b'
        ],
        [
          'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',
          'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2'
        ],
        [
          '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',
          'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c'
        ],
        [
          'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',
          '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3'
        ],
        [
          'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',
          '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d'
        ],
        [
          'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',
          '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700'
        ],
        [
          'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',
          '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4'
        ],
        [
          '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',
          'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196'
        ],
        [
          '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',
          '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4'
        ],
        [
          '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',
          'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257'
        ],
        [
          'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',
          'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13'
        ],
        [
          'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',
          '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096'
        ],
        [
          'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',
          'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38'
        ],
        [
          'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',
          '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f'
        ],
        [
          '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',
          '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448'
        ],
        [
          'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',
          '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a'
        ],
        [
          'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',
          '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4'
        ],
        [
          '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',
          '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437'
        ],
        [
          '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',
          'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7'
        ],
        [
          'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',
          '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d'
        ],
        [
          'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',
          '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a'
        ],
        [
          'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',
          '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54'
        ],
        [
          '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',
          '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77'
        ],
        [
          'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',
          'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517'
        ],
        [
          '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',
          'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10'
        ],
        [
          'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',
          'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125'
        ],
        [
          'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',
          '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e'
        ],
        [
          '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',
          'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1'
        ],
        [
          'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',
          '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2'
        ],
        [
          'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',
          '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423'
        ],
        [
          'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',
          '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8'
        ],
        [
          '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',
          'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758'
        ],
        [
          '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',
          'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375'
        ],
        [
          'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',
          '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d'
        ],
        [
          '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',
          'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec'
        ],
        [
          '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',
          '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0'
        ],
        [
          '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',
          'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c'
        ],
        [
          'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',
          'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4'
        ],
        [
          '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',
          'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f'
        ],
        [
          '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',
          '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649'
        ],
        [
          '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',
          'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826'
        ],
        [
          '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',
          '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5'
        ],
        [
          'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',
          'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87'
        ],
        [
          '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',
          '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b'
        ],
        [
          'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',
          '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc'
        ],
        [
          '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',
          '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c'
        ],
        [
          'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',
          'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f'
        ],
        [
          'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',
          '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a'
        ],
        [
          'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',
          'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46'
        ],
        [
          '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',
          'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f'
        ],
        [
          '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',
          '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03'
        ],
        [
          '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',
          'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08'
        ],
        [
          '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',
          '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8'
        ],
        [
          '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',
          '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373'
        ],
        [
          '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',
          'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3'
        ],
        [
          '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',
          '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8'
        ],
        [
          '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',
          '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1'
        ],
        [
          '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',
          '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9'
        ]
      ]
    }
  };
  
  },{}],27:[function(require,module,exports){
  'use strict';
  
  var utils = exports;
  var bn = require('bn.js');
  
  utils.assert = function assert(val, msg) {
    if (!val)
      throw new Error(msg || 'Assertion failed');
  };
  
  function toArray(msg, enc) {
    if (Array.isArray(msg))
      return msg.slice();
    if (!msg)
      return [];
    var res = [];
    if (typeof msg !== 'string') {
      for (var i = 0; i < msg.length; i++)
        res[i] = msg[i] | 0;
      return res;
    }
    if (!enc) {
      for (var i = 0; i < msg.length; i++) {
        var c = msg.charCodeAt(i);
        var hi = c >> 8;
        var lo = c & 0xff;
        if (hi)
          res.push(hi, lo);
        else
          res.push(lo);
      }
    } else if (enc === 'hex') {
      msg = msg.replace(/[^a-z0-9]+/ig, '');
      if (msg.length % 2 !== 0)
        msg = '0' + msg;
      for (var i = 0; i < msg.length; i += 2)
        res.push(parseInt(msg[i] + msg[i + 1], 16));
    }
    return res;
  }
  utils.toArray = toArray;
  
  function zero2(word) {
    if (word.length === 1)
      return '0' + word;
    else
      return word;
  }
  utils.zero2 = zero2;
  
  function toHex(msg) {
    var res = '';
    for (var i = 0; i < msg.length; i++)
      res += zero2(msg[i].toString(16));
    return res;
  }
  utils.toHex = toHex;
  
  utils.encode = function encode(arr, enc) {
    if (enc === 'hex')
      return toHex(arr);
    else
      return arr;
  };
  
  // Represent num in a w-NAF form
  function getNAF(num, w) {
    var naf = [];
    var ws = 1 << (w + 1);
    var k = num.clone();
    while (k.cmpn(1) >= 0) {
      var z;
      if (k.isOdd()) {
        var mod = k.andln(ws - 1);
        if (mod > (ws >> 1) - 1)
          z = (ws >> 1) - mod;
        else
          z = mod;
        k.isubn(z);
      } else {
        z = 0;
      }
      naf.push(z);
  
      // Optimization, shift by word if possible
      var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1;
      for (var i = 1; i < shift; i++)
        naf.push(0);
      k.iushrn(shift);
    }
  
    return naf;
  }
  utils.getNAF = getNAF;
  
  // Represent k1, k2 in a Joint Sparse Form
  function getJSF(k1, k2) {
    var jsf = [
      [],
      []
    ];
  
    k1 = k1.clone();
    k2 = k2.clone();
    var d1 = 0;
    var d2 = 0;
    while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {
  
      // First phase
      var m14 = (k1.andln(3) + d1) & 3;
      var m24 = (k2.andln(3) + d2) & 3;
      if (m14 === 3)
        m14 = -1;
      if (m24 === 3)
        m24 = -1;
      var u1;
      if ((m14 & 1) === 0) {
        u1 = 0;
      } else {
        var m8 = (k1.andln(7) + d1) & 7;
        if ((m8 === 3 || m8 === 5) && m24 === 2)
          u1 = -m14;
        else
          u1 = m14;
      }
      jsf[0].push(u1);
  
      var u2;
      if ((m24 & 1) === 0) {
        u2 = 0;
      } else {
        var m8 = (k2.andln(7) + d2) & 7;
        if ((m8 === 3 || m8 === 5) && m14 === 2)
          u2 = -m24;
        else
          u2 = m24;
      }
      jsf[1].push(u2);
  
      // Second phase
      if (2 * d1 === u1 + 1)
        d1 = 1 - d1;
      if (2 * d2 === u2 + 1)
        d2 = 1 - d2;
      k1.iushrn(1);
      k2.iushrn(1);
    }
  
    return jsf;
  }
  utils.getJSF = getJSF;
  
  function cachedProperty(obj, computer) {
    var name = computer.name;
    var key = '_' + name;
    obj.prototype[name] = function cachedProperty() {
      return this[key] !== undefined ? this[key] :
             this[key] = computer.call(this);
    };
  }
  utils.cachedProperty = cachedProperty;
  
  function parseBytes(bytes) {
    return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :
                                       bytes;
  }
  utils.parseBytes = parseBytes;
  
  function intFromLE(bytes) {
    return new bn(bytes, 'hex', 'le');
  }
  utils.intFromLE = intFromLE;
  
  
  },{"bn.js":3}],28:[function(require,module,exports){
  module.exports={
    "_args": [
      [
        "elliptic@^5.0.0",
        "/Users/fabio/ethereum/pocket/ethereumjs-accounts/node_modules/ethereumjs-util"
      ]
    ],
    "_from": "elliptic@>=5.0.0 <6.0.0",
    "_id": "elliptic@5.2.1",
    "_inCache": true,
    "_location": "/elliptic",
    "_nodeVersion": "4.2.1",
    "_npmUser": {
      "email": "fedor@indutny.com",
      "name": "indutny"
    },
    "_npmVersion": "2.14.7",
    "_phantomChildren": {},
    "_requested": {
      "name": "elliptic",
      "raw": "elliptic@^5.0.0",
      "rawSpec": "^5.0.0",
      "scope": null,
      "spec": ">=5.0.0 <6.0.0",
      "type": "range"
    },
    "_requiredBy": [
      "/ethereumjs-util",
      "/secp256k1-browserify"
    ],
    "_resolved": "https://registry.npmjs.org/elliptic/-/elliptic-5.2.1.tgz",
    "_shasum": "fa294b6563c6ddbc9ba3dc8594687ae840858f10",
    "_shrinkwrap": null,
    "_spec": "elliptic@^5.0.0",
    "_where": "/Users/fabio/ethereum/pocket/ethereumjs-accounts/node_modules/ethereumjs-util",
    "author": {
      "email": "fedor@indutny.com",
      "name": "Fedor Indutny"
    },
    "bugs": {
      "url": "https://github.com/indutny/elliptic/issues"
    },
    "dependencies": {
      "bn.js": "^3.1.1",
      "brorand": "^1.0.1",
      "hash.js": "^1.0.0",
      "inherits": "^2.0.1"
    },
    "description": "EC cryptography",
    "devDependencies": {
      "browserify": "^3.44.2",
      "coveralls": "^2.11.3",
      "istanbul": "^0.3.17",
      "jscs": "^1.11.3",
      "jshint": "^2.6.0",
      "mocha": "^2.1.0",
      "uglify-js": "^2.4.13"
    },
    "directories": {},
    "dist": {
      "shasum": "fa294b6563c6ddbc9ba3dc8594687ae840858f10",
      "tarball": "http://registry.npmjs.org/elliptic/-/elliptic-5.2.1.tgz"
    },
    "gitHead": "676db36e64399e5b4c0e31ae5aa4cdf8e8362014",
    "homepage": "https://github.com/indutny/elliptic",
    "installable": true,
    "keywords": [
      "Cryptography",
      "EC",
      "Elliptic",
      "curve"
    ],
    "license": "MIT",
    "main": "lib/elliptic.js",
    "maintainers": [
      {
        "name": "indutny",
        "email": "fedor@indutny.com"
      }
    ],
    "name": "elliptic",
    "optionalDependencies": {},
    "repository": {
      "type": "git",
      "url": "git+ssh://git@github.com/indutny/elliptic.git"
    },
    "scripts": {
      "coveralls": "cat ./coverage/lcov.info | coveralls",
      "test": "make lint && istanbul test _mocha --reporter=spec test/*-test.js"
    },
    "version": "5.2.1"
  }
  
  },{}],29:[function(require,module,exports){
  var params = module.exports = require('./params.json')
  
  //load it dynamical because it's slow
  Object.defineProperties(params, {
    genesisState: {
      get: require.bind(this, './genesisState.json')
    }
  })
  
  },{"./params.json":30}],30:[function(require,module,exports){
  module.exports={
    "genesisGasLimit": {
      "v": 5000,
      "d": "Gas limit of the Genesis block."
    },
    "genesisDifficulty": {
      "v": 17179869184,
      "d": "Difficulty of the Genesis block."
    },
    "genesisNonce": {
      "v": "0x0000000000000042",
      "d": "the geneis nonce"
    },
    "genesisExtraData": {
      "v": "0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa",
      "d": "extra data "
    },
    "genesisHash": {
      "v": "0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3",
      "d": "genesis hash"
    },
    "genesisStateRoot": {
      "v": "0xd7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544",
      "d": "the genesis state root"
    },
    "minGasLimit": {
      "v": 5000,
      "d": "Minimum the gas limit may ever be."
    },
    "gasLimitBoundDivisor": {
      "v": 1024,
      "d": "The bound divisor of the gas limit, used in update calculations."
    },
    "minimumDifficulty": {
      "v": 131072,
      "d": "The minimum that the difficulty may ever be."
    },
    "difficultyBoundDivisor": {
      "v": 2048,
      "d": "The bound divisor of the difficulty, used in the update calculations."
    },
    "durationLimit": {
      "v": 13,
      "d": "The decision boundary on the blocktime duration used to determine whether difficulty should go up or not."
    },
    "maximumExtraDataSize": {
      "v": 32,
      "d": "Maximum size extra data may be after Genesis."
    },
    "epochDuration": {
      "v": 30000,
      "d": "Duration between proof-of-work epochs."
    },
    "stackLimit": {
      "v": 1024,
      "d": "Maximum size of VM stack allowed."
    },
    "callCreateDepth": {
      "v": 1024,
      "d": "Maximum depth of call/create stack."
    },
  
    "tierStepGas": {
      "v": [0, 2, 3, 5, 8, 10, 20],
      "d": "Once per operation, for a selection of them."
    },
    "expGas": {
      "v": 10,
      "d": "Once per EXP instuction."
    },
    "expByteGas": {
      "v": 10,
      "d": "Times ceil(log256(exponent)) for the EXP instruction."
    },
  
    "sha3Gas": {
      "v": 30,
      "d": "Once per SHA3 operation."
    },
    "sha3WordGas": {
      "v": 6,
      "d": "Once per word of the SHA3 operation's data."
    },
    "sloadGas": {
      "v": 50,
      "d": "Once per SLOAD operation."
    },
    "sstoreSetGas": {
      "v": 20000,
      "d": "Once per SSTORE operation if the zeroness changes from zero."
    },
    "sstoreResetGas": {
      "v": 5000,
      "d": "Once per SSTORE operation if the zeroness does not change from zero."
    },
    "sstoreRefundGas": {
      "v": 15000,
      "d": "Once per SSTORE operation if the zeroness changes to zero."
    },
    "jumpdestGas": {
      "v": 1,
      "d": "Refunded gas, once per SSTORE operation if the zeroness changes to zero."
    },
  
    "logGas": {
      "v": 375,
      "d": "Per LOG* operation."
    },
    "logDataGas": {
      "v": 8,
      "d": "Per byte in a LOG* operation's data."
    },
    "logTopicGas": {
      "v": 375,
      "d": "Multiplied by the * of the LOG*, per LOG transaction. e.g. LOG0 incurs 0 * c_txLogTopicGas, LOG4 incurs 4 * c_txLogTopicGas."
    },
  
    "createGas": {
      "v": 32000,
      "d": "Once per CREATE operation & contract-creation transaction."
    },
  
    "callGas": {
      "v": 40,
      "d": "Once per CALL operation & message call transaction."
    },
    "callStipend": {
      "v": 2300,
      "d": "Free gas given at beginning of call."
    },
    "callValueTransferGas": {
      "v": 9000,
      "d": "Paid for CALL when the value transfor is non-zero."
    },
    "callNewAccountGas": {
      "v": 25000,
      "d": "Paid for CALL when the destination address didn't exist prior."
    },
  
    "suicideRefundGas": {
      "v": 24000,
      "d": "Refunded following a suicide operation."
    },
  
    "memoryGas": {
      "v": 3,
      "d": "Times the address of the (highest referenced byte in memory + 1). NOTE: referencing happens on read, write and in instructions such as RETURN and CALL."
    },
    "quadCoeffDiv": {
      "v": 512,
      "d": "Divisor for the quadratic particle of the memory cost equation."
    },
  
    "createDataGas": {
      "v": 200,
      "d": ""
    },
    "txGas": {
      "v": 21000,
      "d": "Per transaction. NOTE: Not payable on data of calls between transactions."
    },
    "txDataZeroGas": {
      "v": 4,
      "d": "Per byte of data attached to a transaction that equals zero. NOTE: Not payable on data of calls between transactions."
    },
    "txDataNonZeroGas": {
      "v": 68,
      "d": "Per byte of data attached to a transaction that is not equal to zero. NOTE: Not payable on data of calls between transactions."
    },
  
    "copyGas": {
      "v": 3,
      "d": "Multiplied by the number of 32-byte words that are copied (round up) for any *COPY operation and added."
    },
  
    "ecrecoverGas": {
      "v": 3000,
      "d": ""
    },
    "sha256Gas": {
      "v": 60,
      "d": ""
    },
    "sha256WordGas": {
      "v": 12,
      "d": ""
    },
    "ripemd160Gas": {
      "v": 600,
      "d": ""
    },
    "ripemd160WordGas": {
      "v": 120,
      "d": ""
    },
    "identityGas": {
      "v": 15,
      "d": ""
    },
    "identityWordGas": {
      "v": 3,
      "d": ""
    },
    "minerReward": {
      "v": "5000000000000000000",
      "d": "the amount a miner get rewarded for mining a block"
    },
    "ommerReward": {
      "v": "625000000000000000",
      "d": "The amount of wei a miner of an uncle block gets for being inculded in the blockchain"
    },
    "niblingReward": {
      "v": "156250000000000000",
      "d": "the amount a miner gets for inculding a uncle"
    }
  }
  
  },{}],31:[function(require,module,exports){
  (function (global,Buffer){
  const ethUtil = require('ethereumjs-util')
  const fees = require('ethereum-common')
  const ecdsa = require('secp256k1')
  const BN = ethUtil.BN
  const rlp = ethUtil.rlp
  
  // give browser access to Buffers
  global.Buffer = Buffer
  global.ethUtil = ethUtil
  
  /**
   * Represents a transaction
   * @constructor
   * @param {Buffer|Array} data raw data, deserialized
   */
  var Transaction = module.exports = function (data) {
    // Define Properties
    const fields = [{
      name: 'nonce',
      length: 32,
      allowLess: true,
      default: new Buffer([])
    }, {
      name: 'gasPrice',
      length: 32,
      allowLess: true,
      default: new Buffer([])
    }, {
      name: 'gasLimit',
      length: 32,
      allowLess: true,
      default: new Buffer([])
    }, {
      name: 'to',
      allowZero: true,
      length: 20,
      default: new Buffer([])
    }, {
      name: 'value',
      length: 32,
      allowLess: true,
      default: new Buffer([])
    }, {
      name: 'data',
      allowZero: true,
      default: new Buffer([])
    }, {
      name: 'v',
      length: 1,
      default: new Buffer([0x1c])
    }, {
      name: 'r',
      length: 32,
      allowLess: true,
      default: new Buffer([])
    }, {
      name: 's',
      length: 32,
      allowLess: true,
      default: new Buffer([])
    }]
  
    Object.defineProperty(this, 'from', {
      enumerable: false,
      configurable: true,
      get: function () {
        if (this._from) {
          return this._from
        }
        this._from = this.getSenderAddress()
        return this._from
      },
      set: function (v) {
        this._from = v
      }
    })
  
    ethUtil.defineProperties(this, fields, data)
  }
  
  /**
   * Returns the rlp encoding of the transaction
   * @method serialize
   * @return {Buffer}
   */
  Transaction.prototype.serialize = function () {
    return rlp.encode(this.raw)
  }
  
  /**
   * Computes a sha3-256 hash of the tx
   * @method hash
   * @param {Boolean} [true] signature - whether or not to inculde the signature
   * @return {Buffer}
   */
  Transaction.prototype.hash = function (signature) {
    var toHash
  
    if (typeof signature === 'undefined') {
      signature = true
    }
  
    if (signature) {
      toHash = this.raw
    } else {
      toHash = this.raw.slice(0, 6)
    }
  
    // create hash
    return ethUtil.sha3(rlp.encode(toHash))
  }
  
  /**
   * gets the senders address
   * @method getSenderAddress
   * @return {Buffer}
   */
  Transaction.prototype.getSenderAddress = function () {
    const pubKey = this.getSenderPublicKey()
    return ethUtil.pubToAddress(pubKey)
  }
  
  /**
   * gets the senders public key
   * @method getSenderPublicKey
   * @return {Buffer}
   */
  Transaction.prototype.getSenderPublicKey = function () {
    if (!this._senderPubKey || !this._senderPubKey.length) {
      this.verifySignature()
    }
  
    return this._senderPubKey
  }
  
  /**
   * @method verifySignature
   * @return {Boolean}
   */
  Transaction.prototype.verifySignature = function () {
    var msgHash = this.hash(false)
    var sig = {
      signature: Buffer.concat([ethUtil.pad(this.r, 32), ethUtil.pad(this.s, 32)], 64),
      recovery: ethUtil.bufferToInt(this.v) - 27
    }
  
    try {
      this._senderPubKey = ecdsa.recover(msgHash, sig, false)
    } catch (e) {
      return false
    }
  
    if (!this._senderPubKey) {
      return false
    }
  
    var result = ecdsa.verify(msgHash, sig, this._senderPubKey)
    if (!result) {
      this._senderPubKey = null
    }
  
    return result
  }
  /**
   * sign a transaction with a given a private key
   * @method sign
   * @param {Buffer} privateKey
   */
  Transaction.prototype.sign = function (privateKey) {
    var msgHash = this.hash(false)
    var sig = ecdsa.sign(msgHash, privateKey)
  
    this.r = sig.signature.slice(0, 32)
    this.s = sig.signature.slice(32, 64)
    this.v = sig.recovery + 27
  }
  /**
   * The amount of gas paid for the data in this tx
   * @method getDataFee
   * @return {bn.js}
   */
  Transaction.prototype.getDataFee = function () {
    const data = this.raw[5]
    var cost = new BN(0)
    for (var i = 0; i < data.length; i++) {
      if (data[i] === 0) {
        cost.iaddn(fees.txDataZeroGas.v)
      } else {
        cost.iaddn(fees.txDataNonZeroGas.v)
      }
    }
    return cost
  }
  
  /**
   * the base amount of gas it takes to be a valid tx
   * @method getBaseFee
   * @return {bn.js}
   */
  Transaction.prototype.getBaseFee = function () {
    return this.getDataFee().addn(fees.txGas.v)
  }
  
  /**
   * the up front amount that an account must have for this transaction to be valid
   * @method getUpfrontCost
   * @return {BN}
   */
  Transaction.prototype.getUpfrontCost = function () {
    return new BN(this.gasLimit)
      .mul(new BN(this.gasPrice))
      .add(new BN(this.value))
  }
  
  /**
   * validates the signature and checks to see if it has enough gas
   * @method validate
   * @return {Boolean}
   */
  Transaction.prototype.validate = function () {
    return this.verifySignature() && (Number(this.getBaseFee().toString()) <= ethUtil.bufferToInt(this.gasLimit))
  }
  
  }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
  },{"buffer":88,"ethereum-common":29,"ethereumjs-util":32,"secp256k1":84}],32:[function(require,module,exports){
  (function (Buffer){
  const SHA3 = require('sha3')
  const ec = require('elliptic').ec('secp256k1')
  const assert = require('assert')
  const rlp = require('rlp')
  const BN = require('bn.js')
  
  // the max interger that this VM can handle
  exports.MAX_INTEGER = new BN('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16)
  exports.TWO_POW256 = new BN('115792089237316195423570985008687907853269984665640564039457584007913129639936')
  
  // hex string of SHA3-256 hash of `null`
  exports.SHA3_NULL = 'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470'
  
  // SHA3-256 hash of the rlp of []
  exports.SHA3_RLP_ARRAY = '1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347'
  
  // SHA3-256 hash of the rlp of `null`
  exports.SHA3_RLP = '56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421'
  
  exports.BN = BN
  exports.rlp = rlp
  
  /**
   * Returns a buffer filled with 0s
   * @method zeros
   * @param {Integer} bytes  the number of bytes the buffer should be
   * @return {Buffer}
   */
  exports.zeros = function (bytes) {
    var buf = new Buffer(bytes)
    buf.fill(0)
    return buf
  }
  
  /**
   * pads an array of buffer with leading zeros till it has `length` bytes
   * @method pad
   * @param {Buffer|Array} array
   * @param {Integer}  length the number of bytes the output should be
   * @return {Buffer|Array}
   */
  exports.pad = function (msg, length) {
    msg = exports.toBuffer(msg)
    if (msg.length < length) {
      var buf = exports.zeros(length)
      msg.copy(buf, length - msg.length)
      return buf
    }
    return msg.slice(-length)
  }
  
  /**
   * Trims leading zeros from a buffer or an array
   * @method unpad
   * @param {Buffer|Array|String}
   * @return {Buffer|Array|String}
   */
  exports.unpad = exports.stripZeros = function (a) {
    a = exports.stripHexPrefix(a)
    var first = a[0]
    while (a.length > 0 && first.toString() === '0') {
      a = a.slice(1)
      first = a[0]
    }
    return a
  }
  
  exports.toBuffer = function (v) {
    if (!Buffer.isBuffer(v)) {
      if (typeof v === 'string') {
        v = new Buffer(padToEven(exports.stripHexPrefix(v)), 'hex')
      } else if (typeof v === 'number') {
        v = exports.intToBuffer(v)
      } else if (v === null || v === undefined) {
        v = new Buffer([])
      } else if (v.toArray) {
        // converts a BN to a Buffer
        v = new Buffer(v.toArray())
      } else {
        throw new Error('invalid type')
      }
    }
    return v
  }
  
  /**
   * Converts an integer into a hex string
   * @method intToHex
   * @param {Number}
   * @return {String}
   */
  exports.intToHex = function (i) {
    assert(i % 1 === 0, 'number is not a interger')
    assert(i >= 0, 'number must be positive')
    var hex = i.toString(16)
    if (hex.length % 2) {
      hex = '0' + hex
    }
  
    return hex
  }
  
  /**
   * Converts an integer to a buffer
   * @method intToBuffer
   * @param {Number}
   * @return {Buffer}
   */
  exports.intToBuffer = function (i) {
    var hex = exports.intToHex(i)
    return new Buffer(hex, 'hex')
  }
  
  /**
   * Converts a buffer to an Interger
   * @method bufferToInt
   * @par[MaÅam {B[M`Êuffer}
   * @return {Number}
   */
  exports.bufferToInt = function (buf) {
    buf = exports.toBuffer(buf)
    if (buf.length === 0) {
      return 0
    }
  
    return parseInt(buf.toString('hex'), 16)
  }
  
  /**
   * interpets a buffer as a signed integer and returns a bignum
   * @method fromSigned
   * @param {Buffer} num
   * @return {BN}
   */
  exports.fromSigned = function (num) {
    if (num.length === 32 && num[0] >= 128) {
      return new BN(num).sub(exports.TWO_POW256)
    }
  
    return new BN(num)
  }
  
  /**
   * Converts a bignum to an unsigned interger and returns it as a buffer
   * @method toUnsigned
   * @param {Bignum} num
   * @return {Buffer}
   */
  exports.toUnsigned = function (num) {
    if (num.cmpn(0) === -1) {
      return new Buffer(num.add(exports.TWO_POW256).toArray())
    }
  
    return new Buffer(num.toArray())
  }
  
  exports.sha3 = function (a, bytes) {
    a = exports.toBuffer(a)
    if (!bytes) bytes = 256
  
    var h = new SHA3.SHA3Hash(bytes)
    if (a) {
      h.update(a)
    }
    return new Buffer(h.digest('hex'), 'hex')
  }
  
  /**
   * Returns the ethereum address of a given public key
   * @method pubToAddress
   * @param {Buffer}
   * @return {Buffer}
   */
  exports.pubToAddress = exports.publicToAddress = function (pubKey) {
    pubKey = exports.toBuffer(pubKey)
    var hash = new SHA3.SHA3Hash(256)
    hash.update(pubKey.slice(-64))
    return new Buffer(hash.digest('hex').slice(-40), 'hex')
  }
  
  /**
   * Returns the ethereum public key of a given private key
   * @method privateToPublic
   * @param {Buffer} privateKey
   * @return {Buffer}
   */
  var privateToPublic = exports.privateToPublic = function (privateKey) {
    privateKey = exports.toBuffer(privateKey)
    privateKey = new BN(privateKey)
    var key = ec.keyFromPrivate(privateKey).getPublic().toJSON()
    return new Buffer(key[0].toArray().concat(key[1].toArray()))
  }
  
  /**
   * Returns the ethereum address of a given private key
   * @method privateToAddress
   * @param {Buffer} privateKey
   * @return {Buffer}
   */
  exports.privateToAddress = function (privateKey) {
    return exports.publicToAddress(privateToPublic(privateKey))
  }
  
  /**
   * Generates a new address
   * @method generateAddress
   * @param {Buffer} from the address which is creating this new address
   * @param {Buffer} nonce the nonce of the from account
   */
  exports.generateAddress = function (from, nonce) {
    from = exports.toBuffer(from)
    nonce = new Buffer(new BN(nonce).toArray())
  
    if (nonce.toString('hex') === '00') {
      nonce = 0
    }
  
    var hash = exports.sha3(rlp.encode([new Buffer(from, 'hex'), nonce]))
    return hash.slice(12)
  }
  
  // Returns a Boolean on whether or not the a sting starts with 0x
  exports.isHexPrefixed = function (str) {
    return str.slice(0, 2) === '0x'
  }
  
  // Removes 0x from a given String
  exports.stripHexPrefix = function (str) {
    if (typeof str !== 'string') {
      return str
    }
    return exports.isHexPrefixed(str) ? str.slice(2) : str
  }
  
  // Adds 0x to a given string if it does not already start with 0x
  exports.addHexPrefix = function (str) {
    if (typeof str !== 'string') {
      return str
    }
    return exports.isHexPrefixed(str) ? '0x' + str : str
  }
  
  /**
   * defines properties on a `Object`
   * @method defineProperties
   * @para[M`Êm {Object} self the `Object` to define properties on
   * @param {Array} fields an array fields to define
   */
  exports.defineProperties = function (self, fields, data) {
    self.raw = []
    self._fields = []
  
    self.toJSON = function (label) {
      if (label) {
        var obj = {}
  
        for (var prop in this) {
          if (typeof this[prop] !== 'function' && prop !== 'raw' && prop !== '_fields') {
            obj[prop] = this[prop].toString('hex')
          }
        }
        return obj
      }
  
      return exports.baToJSON(this.raw)
    }
  
    fields.forEach(function (field, i) {
      self._fields.push(field.name)
      Object.defineProperty(self, field.name, {
        enumerable: true,
        configurable: true,
        get: function () {
          return this.raw[i]
        },
        set: function (v) {
          v = exports.toBuffer(v)
  
          if (v.toString('hex') === '00' && !field.allowZero) {
            v = new Buffer([])
          }
  
          if (field.allowLess && field.length) {
            v = exports.stripZeros(v)
            assert(field.length >= v.length)
          } else if (!(field.empty && v.length === 0) && field.length) {
            assert(field.length === v.length, 'The field ' + field.name + 'must have byte length of ' + field.length)
          }
  
          this.raw[i] = v
        }
      })
  
      if (field.default) {
        self[field.name] = field.default
      }
    })
  
    if (data) {
      if (typeof data === 'string') {
        data = new Buffer(exports.stripHexPrefix(data), 'hex')
      }
  
      if (Buffer.isBuffer(data)) {
        data = rlp.decode(data)
      }
  
      if (Array.isArray(data)) {
        if (data.length > self._fields.length) {
          throw (new Error('wrong number of fields in data'))
        }
  
        // make sure all the items are buffers
        data.forEach(function (d, i) {
          self[self._fields[i]] = typeof d === 'string' ? new Buffer(d, 'hex') : d
        })
      } else if (typeof data === 'object') {
        for (var prop in data) {
          if (self._fields.indexOf(prop) !== -1) {
            self[prop] = data[prop]
          }
        }
      } else {
        throw new Error('invalid data')
      }
    }
  }
  
  /**
   * Print a Buffer Array
   * @method printBA
   * @param {Buffer|Array}
   */
  exports.printBA = function (ba) {
    if (Buffer.isBuffer(ba)) {
      if (ba.length === 0) {
        console.log('new Buffer(0)')
      } else {
        console.log("new Buffer('" + ba.toString('hex') + "', 'hex')")
      }
    } else if (ba instanceof Array) {
      console.log('[')
      for (var i = 0; i < ba.length; i++) {
        exports.printBA(ba[i])
        console.log(',')
      }
      console.log(']')
    } else {
      console.log(ba)
    }
  }
  
  /**
   * converts a buffer array to JSON
   * @method BAToJSON
   * @param {Buffer|Array}
   */
  exports.baToJSON = function (ba) {
    if (Buffer.isBuffer(ba)) {
      return ba.toString('hex')
    } else if (ba instanceof Array) {
      var array = []
      for (var i = 0; i < ba.length; i++) {
        array.push(exports.baToJSON(ba[i]))
      }
      return array
    }
  }
  
  function padToEven (a) {
    if (a.length % 2) a = '0' + a
    return a
  }
  
  }).call(this,require("buffer").Buffer)
  },{"assert":86,"bn.js":3,"buffer":88,"elliptic":12,"rlp":83,"sha3":11}],33:[function(require,module,exports){
  var hash = exports;
  
  hash.utils = require('./hash/utils');
  hash.common = require('./hash/common');
  hash.sha = require('./hash/sha');
  hash.ripemd = require('./hash/ripemd');
  hash.hmac = require('./hash/hmac');
  
  // Proxy hash functions to the main object
  hash.sha1 = hash.sha.sha1;
  hash.sha256 = hash.sha.sha256;
  hash.sha224 = hash.sha.sha224;
  hash.sha384 = hash.sha.sha384;
  hash.sha512 = hash.sha.sha512;
  hash.ripemd160 = hash.ripemd.ripemd160;
  
  },{"./hash/common":34,"./hash/hmac":35,"./hash/ripemd":36,"./hash/sha":37,"./hash/utils":38}],34:[function(require,module,exports){
  var hash = require('../hash');
  var utils = hash.utils;
  var assert = utils.assert;
  
  function BlockHash() {
    this.pending = null;
    this.pendingTotal = 0;
    this.blockSize = this.constructor.blockSize;
    this.outSize = this.constructor.outSize;
    this.hmacStrength = this.constructor.hmacStrength;
    this.padLength = this.constructor.padLength / 8;
    this.endian = 'big';
  
    this._delta8 = this.blockSize / 8;
    this._delta32 = this.blockSize / 32;
  }
  exports.BlockHash = BlockHash;
  
  BlockHash.prototype.update = function update(msg, enc) {
    // Convert message to array, pad it, and join into 32bit blocks
    msg = utils.toArray(msg, enc);
    if (!this.pending)
      this.pending = msg;
    else
      this.pending = this.pending.concat(msg);
    this.pendingTotal += msg.length;
  
    // Enough data, try updating
    if (this.pending.length >= this._delta8) {
      msg = this.pending;
  
      // Process pending data in blocks
      var r = msg.length % this._delta8;
      this.pending = msg.slice(msg.length - r, msg.length);
      if (this.pending.length === 0)
        this.pending = null;
  
      msg = utils.join32(msg, 0, msg.length - r, this.endian);
      for (var i = 0; i < msg.length; i += this._delta32)
        this._update(msg, i, i + this._delta32);
    }
  
    return this;
  };
  
  BlockHash.prototype.digest = function digest(enc) {
    this.update(this._pad());
    assert(this.pending === null);
  
    return this._digest(enc);
  };
  
  BlockHash.prototype._pad = function pad() {
    var len = this.pendingTotal;
    var bytes = this._delta8;
    var k = bytes - ((len + this.padLength) % bytes);
    var res = new Array(k + this.padLength);
    res[0] = 0x80;
    for (var i = 1; i < k; i++)
      res[i] = 0;
  
    // Append length
    len <<= 3;
    if (this.endian === 'big') {
      for (var t = 8; t < this.padLength; t++)
        res[i++] = 0;
  
      res[i++] = 0;
      res[i++] = 0;
      res[i++] = 0;
      res[i++] = 0;
      res[i++] = (len >>> 24) & 0xff;
      res[i++] = (len >>> 16) & 0xff;
      res[i++] = (len >>> 8) & 0xff;
      res[i++] = len & 0xff;
    } else {
      res[i++] = len & 0xff;
      res[i++] = (len >>> 8) & 0xff;
      res[i++] = (len >>> 16) & 0xff;
      res[i++] = (len >>> 24) & 0xff;
      res[i++] = 0;
      res[i++] = 0;
      res[i++] = 0;
      res[i++] = 0;
  
      for (var t = 8; t < this.padLength; t++)
        res[i++] = 0;
    }
  
    return res;
  };
  
  },{"../hash":33}],35:[function(require,module,exports){
  var hmac = exports;
  
  var hash = require('../hash');
  var utils = hash.utils;
  var assert = utils.assert;
  
  function Hmac(hash, key, enc) {
    if (!(this instanceof Hmac))
      return new Hmac(hash, key, enc);
    this.Hash = hash;
    this.blockSize = hash.blockSize / 8;
    this.outSize = hash.outSize / 8;
    this.inner = null;
    this.outer = null;
  
    this._init(utils.toArray(key, enc));
  }
  module.exports = Hmac;
  
  Hmac.prototype._init = function init(key) {
    // Shorten key, if needed
    if (key.length > this.blockSize)
      key = new this.Hash().update(key).digest();
    assert(key.length <= this.blockSize);
  
    // Add padding to key
    for (var i = key.length; i < this.blockSize; i++)
      key.push(0);
  
    for (var i = 0; i < key.length; i++)
      key[i] ^= 0x36;
    this.inner = new this.Hash().update(key);
  
    // 0x36 ^ 0x5c = 0x6a
    for (var i = 0; i < key.length; i++)
      key[i] ^= 0x6a;
    this.outer = new this.Hash().update(key);
  };
  
  Hmac.prototype.update = function update(msg, enc) {
    this.inner.update(msg, enc);
    return this;
  };
  
  Hmac.prototype.digest = function digest(enc) {
    this.outer.update(this.inner.digest());
    return this.outer.digest(enc);
  };
  
  },{"../hash":33}],36:[function(require,module,exports){
  var hash = require('../hash');
  var utils = hash.utils;
  
  var rotl32 = utils.rotl32;
  var sum32 = utils.sum32;
  var sum32_3 = utils.sum32_3;
  var sum32_4 = utils.sum32_4;
  var BlockHash = hash.common.BlockHash;
  
  function RIPEMD160() {
    if (!(this instanceof RIPEMD160))
      return new RIPEMD160();
  
    BlockHash.call(this);
  
    this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];
    this.endian = 'little';
  }
  utils.inherits(RIPEMD160, BlockHash);
  exports.ripemd160 = RIPEMD160;
  
  RIPEMD160.blockSize = 512;
  RIPEMD160.outSize = 160;
  RIPEMD160.hmacStrength = 192;
  RIPEMD160.padLength = 64;
  
  RIPEMD160.prototype._update = function update(msg, start) {
    var A = this.h[0];
    var B = this.h[1];
    var C = this.h[2];
    var D = this.h[3];
    var E = this.h[4];
    var Ah = A;
    var Bh = B;
    var Ch = C;
    var Dh = D;
    var Eh = E;
    for (var j = 0; j < 80; j++) {
      var T = sum32(
        rotl32(
          sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)),
          s[j]),
        E);
      A = E;
      E = D;
      D = rotl32(C, 10);
      C = B;
      B = T;
      T = sum32(
        rotl32(
          sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),
          sh[j]),
        Eh);
      Ah = Eh;
      Eh = Dh;
      Dh = rotl32(Ch, 10);
      Ch = Bh;
      Bh = T;
    }
    T = sum32_3(this.h[1], C, Dh);
    this.h[1] = sum32_3(this.h[2], D, Eh);
    this.h[2] = sum32_3(this.h[3], E, Ah);
    this.h[3] = sum32_3(this.h[4], A, Bh);
    this.h[4] = sum32_3(this.h[0], B, Ch);
    this.h[0] = T;
  };
  
  RIPEMD160.prototype._digest = function digest(enc) {
    if (enc === 'hex')
      return utils.toHex32(this.h, 'little');
    else
      return utils.split32(this.h, 'little');
  };
  
  function f(j, x, y, z) {
    if (j <= 15)
      return x ^ y ^ z;
    else if (j <= 31)
      return (x & y) | ((~x) & z);
    else if (j <= 47)
      return (x | (~y)) ^ z;
    else if (j <= 63)
      return (x & z) | (y & (~z));
    else
      return x ^ (y | (~z));
  }
  
  function K(j) {
    if (j <= 15)
      return 0x00000000;
    else if (j <= 31)
      return 0x5a827999;
    else if (j <= 47)
      return 0x6ed9eba1;
    else if (j <= 63)
      return 0x8f1bbcdc;
    else
      return 0xa953fd4e;
  }
  
  function Kh(j) {
    if (j <= 15)
      return 0x50a28be6;
    else if (j <= 31)
      return 0x5c4dd124;
    else if (j <= 47)
      return 0x6d703ef3;
    else if (j <= 63)
      return 0x7a6d76e9;
    else
      return 0x00000000;
  }
  
  var r = [
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
    7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
    3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
    1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
    4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
  ];
  
  var rh = [
    5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
    6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
    15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
    8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
    12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
  ];
  
  var s = [
    11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
    7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
    11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
    11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
    9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
  ];
  
  var sh = [
    8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
    9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
    9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
    15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
    8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
  ];
  
  },{"../hash":33}],37:[function(require,module,exports){
  var hash = require('../hash');
  var utils = hash.utils;
  var assert = utils.assert;
  
  var rotr32 = utils.rotr32;
  var rotl32 = utils.rotl32;
  var sum32 = utils.sum32;
  var sum32_4 = utils.sum32_4;
  var sum32_5 = utils.sum32_5;
  var rotr64_hi = utils.rotr64_hi;
  var rotr64_lo = utils.rotr64_lo;
  var shr64_hi = utils.shr64_hi;
  var shr64_lo = utils.shr64_lo;
  var sum64 = utils.sum64;
  var sum64_hi = utils.sum64_hi;
  var sum64_lo = utils.sum64_lo;
  var sum64_4_hi = utils.sum64_4_hi;
  var sum64_4_lo = utils.sum64_4_lo;
  var sum64_5_hi = utils.sum64_5_hi;
  var sum64_5_lo = utils.sum64_5_lo;
  var BlockHash = hash.common.BlockHash;
  
  var sha256_K = [
    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
    0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
    0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
    0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
    0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
    0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
    0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
    0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
    0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
  ];
  
  var sha512_K = [
    0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
    0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
    0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
    0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
    0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
    0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
    0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
    0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
    0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
    0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
    0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
    0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
    0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
    0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
    0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
    0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
    0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
    0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
    0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
    0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
    0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
    0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
    0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
    0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
    0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
    0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
    0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
    0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
    0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
    0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
    0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
    0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
    0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
    0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
    0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
    0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
    0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
    0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
    0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
    0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
  ];
  
  var sha1_K = [
    0x5A827999, 0x6ED9EBA1,
    0x8F1BBCDC, 0xCA62C1D6
  ];
  
  function SHA256() {
    if (!(this instanceof SHA256))
      return new SHA256();
  
    BlockHash.call(this);
    this.h = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
               0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 ];
    this.k = sha256_K;
    this.W = new Array(64);
  }
  utils.inherits(SHA256, BlockHash);
  exports.sha256 = SHA256;
  
  SHA256.blockSize = 512;
  SHA256.outSize = 256;
  SHA256.hmacStrength = 192;
  SHA256.padLength = 64;
  
  SHA256.prototype._update = function _update(msg, start) {
    var W = this.W;
  
    for (var i = 0; i < 16; i++)
      W[i] = msg[start + i];
    for (; i < W.length; i++)
      W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]);
  
    var a = this.h[0];
    var b = this.h[1];
    var c = this.h[2];
    var d = this.h[3];
    var e = this.h[4];
    var f = this.h[5];
    var g = this.h[6];
    var h = this.h[7];
  
    assert(this.k.length === W.length);
    for (var i = 0; i < W.length; i++) {
      var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]);
      var T2 = sum32(s0_256(a), maj32(a, b, c));
      h = g;
      g = f;
      f = e;
      e = sum32(d, T1);
      d = c;
      c = b;
      b = a;
      a = sum32(T1, T2);
    }
  
    this.h[0] = sum32(this.h[0], a);
    this.h[1] = sum32(this.h[1], b);
    this.h[2] = sum32(this.h[2], c);
    this.h[3] = sum32(this.h[3], d);
    this.h[4] = sum32(this.h[4], e);
    this.h[5] = sum32(this.h[5], f);
    this.h[6] = sum32(this.h[6], g);
    this.h[7] = sum32(this.h[7], h);
  };
  
  SHA256.prototype._digest = function digest(enc) {
    if (enc === 'hex')
      return utils.toHex32(this.h, 'big');
    else
      return utils.split32(this.h, 'big');
  };
  
  function SHA224() {
    if (!(this instanceof SHA224))
      return new SHA224();
  
    SHA256.call(this);
    this.h = [ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
               0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];
  }
  utils.inherits(SHA224, SHA256);
  exports.sha224 = SHA224;
  
  SHA224.blockSize = 512;
  SHA224.outSize = 224;
  SHA224.hmacStrength = 192;
  SHA224.padLength = 64;
  
  SHA224.prototype._digest = function digest(enc) {
    // Just truncate output
    if (enc === 'hex')
      return utils.toHex32(this.h.slice(0, 7), 'big');
    else
      return utils.split32(this.h.slice(0, 7), 'big');
  };
  
  function SHA512() {
    if (!(this instanceof SHA512))
      return new SHA512();
  
    BlockHash.call(this);
    this.h = [ 0x6a09e667, 0xf3bcc908,
               0xbb67ae85, 0x84caa73b,
               0x3c6ef372, 0xfe94f82b,
               0xa54ff53a, 0x5f1d36f1,
               0x510e527f, 0xade682d1,
               0x9b05688c, 0x2b3e6c1f,
               0x1f83d9ab, 0xfb41bd6b,
               0x5be0cd19, 0x137e2179 ];
    this.k = sha512_K;
    this.W = new Array(160);
  }
  utils.inherits(SHA512, BlockHash);
  exports.sha512 = SHA512;
  
  SHA512.blockSize = 1024;
  SHA512.outSize = 512;
  SHA512.hmacStrength = 192;
  SHA512.padLength = 128;
  
  SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {
    var W = this.W;
  
    // 32 x 32bit words
    for (var i = 0; i < 32; i++)
      W[i] = msg[start + i];
    for (; i < W.length; i += 2) {
      var c0_hi = g1_512_hi(W[i - 4], W[i - 3]);  // i - 2
      var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);
      var c1_hi = W[i - 14];  // i - 7
      var c1_lo = W[i - 13];
      var c2_hi = g0_512_hi(W[i - 30], W[i - 29]);  // i - 15
      var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);
      var c3_hi = W[i - 32];  // i - 16
      var c3_lo = W[i - 31];
  
      W[i] = sum64_4_hi(c0_hi, c0_lo,
                        c1_hi, c1_lo,
                        c2_hi, c2_lo,
                        c3_hi, c3_lo);
      W[i + 1] = sum64_4_lo(c0_hi, c0_lo,
                            c1_hi, c1_lo,
                            c2_hi, c2_lo,
                            c3_hi, c3_lo);
    }
  };
  
  SHA512.prototype._update = function _update(msg, start) {
    this._prepareBlock(msg, start);
  
    var W = this.W;
  
    var ah = this.h[0];
    var al = this.h[1];
    var bh = this.h[2];
    var bl = this.h[3];
    var ch = this.h[4];
    var cl = this.h[5];
    var dh = this.h[6];
    var dl = this.h[7];
    var eh = this.h[8];
    var el = this.h[9];
    var fh = this.h[10];
    var fl = this.h[11];
    var gh = this.h[12];
    var gl = this.h[13];
    var hh = this.h[14];
    var hl = this.h[15];
  
    assert(this.k.length === W.length);
    for (var i = 0; i < W.length; i += 2) {
      var c0_hi = hh;
      var c0_lo = hl;
      var c1_hi = s1_512_hi(eh, el);
      var c1_lo = s1_512_lo(eh, el);
      var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl);
      var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);
      var c3_hi = this.k[i];
      var c3_lo = this.k[i + 1];
      var c4_hi = W[i];
      var c4_lo = W[i + 1];
  
      var T1_hi = sum64_5_hi(c0_hi, c0_lo,
                             c1_hi, c1_lo,
                             c2_hi, c2_lo,
                             c3_hi, c3_lo,
                             c4_hi, c4_lo);
      var T1_lo = sum64_5_lo(c0_hi, c0_lo,
                             c1_hi, c1_lo,
                             c2_hi, c2_lo,
                             c3_hi, c3_lo,
                             c4_hi, c4_lo);
  
      var c0_hi = s0_512_hi(ah, al);
      var c0_lo = s0_512_lo(ah, al);
      var c1_hi = maj64_hi(ah, al, bh, bl, ch, cl);
      var c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);
  
      var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo);
      var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo);
  
      hh = gh;
      hl = gl;
  
      gh = fh;
      gl = fl;
  
      fh = eh;
      fl = el;
  
      eh = sum64_hi(dh, dl, T1_hi, T1_lo);
      el = sum64_lo(dl, dl, T1_hi, T1_lo);
  
      dh = ch;
      dl = cl;
  
      ch = bh;
      cl = bl;
  
      bh = ah;
      bl = al;
  
      ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo);
      al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo);
    }
  
    sum64(this.h, 0, ah, al);
    sum64(this.h, 2, bh, bl);
    sum64(this.h, 4, ch, cl);
    sum64(this.h, 6, dh, dl);
    sum64(this.h, 8, eh, el);
    sum64(this.h, 10, fh, fl);
    sum64(this.h, 12, gh, gl);
    sum64(this.h, 14, hh, hl);
  };
  
  SHA512.prototype._digest = function digest(enc) {
    if (enc === 'hex')
      return utils.toHex32(this.h, 'big');
    else
      return utils.split32(this.h, 'big');
  };
  
  function SHA384() {
    if (!(this instanceof SHA384))
      return new SHA384();
  
    SHA512.call(this);
    this.h = [ 0xcbbb9d5d, 0xc1059ed8,
               0x629a292a, 0x367cd507,
               0x9159015a, 0x3070dd17,
               0x152fecd8, 0xf70e5939,
               0x67332667, 0xffc00b31,
               0x8eb44a87, 0x68581511,
               0xdb0c2e0d, 0x64f98fa7,
               0x47b5481d, 0xbefa4fa4 ];
  }
  utils.inherits(SHA384, SHA512);
  exports.sha384 = SHA384;
  
  SHA384.blockSize = 1024;
  SHA384.outSize = 384;
  SHA384.hmacStrength = 192;
  SHA384.padLength = 128;
  
  SHA384.prototype._digest = function digest(enc) {
    if (enc === 'hex')
      return utils.toHex32(this.h.slice(0, 12), 'big');
    else
      return utils.split32(this.h.slice(0, 12), 'big');
  };
  
  function SHA1() {
    if (!(this instanceof SHA1))
      return new SHA1();
  
    BlockHash.call(this);
    this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe,
               0x10325476, 0xc3d2e1f0 ];
    this.W = new Array(80);
  }
  
  utils.inherits(SHA1, BlockHash);
  exports.sha1 = SHA1;
  
  SHA1.blockSize = 512;
  SHA1.outSize = 160;
  SHA1.hmacStrength = 80;
  SHA1.padLength = 64;
  
  SHA1.prototype._update = function _update(msg, start) {
    var W = this.W;
  
    for (var i = 0; i < 16; i++)
      W[i] = msg[start + i];
  
    for(; i < W.length; i++)
      W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
  
    var a = this.h[0];
    var b = this.h[1];
    var c = this.h[2];
    var d = this.h[3];
    var e = this.h[4];
  
    for (var i = 0; i < W.length; i++) {
      var s = ~~(i / 20);
      var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]);
      e = d;
      d = c;
      c = rotl32(b, 30);
      b = a;
      a = t;
    }
  
    this.h[0] = sum32(this.h[0], a);
    this.h[1] = sum32(this.h[1], b);
    this.h[2] = sum32(this.h[2], c);
    this.h[3] = sum32(this.h[3], d);
    this.h[4] = sum32(this.h[4], e);
  };
  
  SHA1.prototype._digest = function digest(enc) {
    if (enc === 'hex')
      return utils.toHex32(this.h, 'big');
    else
      return utils.split32(this.h, 'big');
  };
  
  function ch32(x, y, z) {
    return (x & y) ^ ((~x) & z);
  }
  
  function maj32(x, y, z) {
    return (x & y) ^ (x & z) ^ (y & z);
  }
  
  function p32(x, y, z) {
    return x ^ y ^ z;
  }
  
  function s0_256(x) {
    return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22);
  }
  
  function s1_256(x) {
    return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25);
  }
  
  function g0_256(x) {
    return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3);
  }
  
  function g1_256(x) {
    return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10);
  }
  
  function ft_1(s, x, y, z) {
    if (s === 0)
      return ch32(x, y, z);
    if (s === 1 || s === 3)
      return p32(x, y, z);
    if (s === 2)
      return maj32(x, y, z);
  }
  
  function ch64_hi(xh, xl, yh, yl, zh, zl) {
    var r = (xh & yh) ^ ((~xh) & zh);
    if (r < 0)
      r += 0x100000000;
    return r;
  }
  
  function ch64_lo(xh, xl, yh, yl, zh, zl) {
    var r = (xl & yl) ^ ((~xl) & zl);
    if (r < 0)
      r += 0x100000000;
    return r;
  }
  
  function maj64_hi(xh, xl, yh, yl, zh, zl) {
    var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);
    if (r < 0)
      r += 0x100000000;
    return r;
  }
  
  function maj64_lo(xh, xl, yh, yl, zh, zl) {
    var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);
    if (r < 0)
      r += 0x100000000;
    return r;
  }
  
  function s0_512_hi(xh, xl) {
    var c0_hi = rotr64_hi(xh, xl, 28);
    var c1_hi = rotr64_hi(xl, xh, 2);  // 34
    var c2_hi = rotr64_hi(xl, xh, 7);  // 39
  
    var r = c0_hi ^ c1_hi ^ c2_hi;
    if (r < 0)
      r += 0x100000000;
    return r;
  }
  
  function s0_512_lo(xh, xl) {
    var c0_lo = rotr64_lo(xh, xl, 28);
    var c1_lo = rotr64_lo(xl, xh, 2);  // 34
    var c2_lo = rotr64_lo(xl, xh, 7);  // 39
  
    var r = c0_lo ^ c1_lo ^ c2_lo;
    if (r < 0)
      r += 0x100000000;
    return r;
  }
  
  function s1_512_hi(xh, xl) {
    var c0_hi = rotr64_hi(xh, xl, 14);
    var c1_hi = rotr64_hi(xh, xl, 18);
    var c2_hi = rotr64_hi(xl, xh, 9);  // 41
  
    var r = c0_hi ^ c1_hi ^ c2_hi;
    if (r < 0)
      r += 0x100000000;
    return r;
  }
  
  function s1_512_lo(xh, xl) {
    var c0_lo = rotr64_lo(xh, xl, 14);
    var c1_lo = rotr64_lo(xh, xl, 18);
    var c2_lo = rotr64_lo(xl, xh, 9);  // 41
  
    var r = c0_lo ^ c1_lo ^ c2_lo;
    if (r < 0)
      r += 0x100000000;
    return r;
  }
  
  function g0_512_hi(xh, xl) {
    var c0_hi = rotr64_hi(xh, xl, 1);
    var c1_hi = rotr64_hi(xh, xl, 8);
    var c2_hi = shr64_hi(xh, xl, 7);
  
    var r = c0_hi ^ c1_hi ^ c2_hi;
    if (r < 0)
      r += 0x100000000;
    return r;
  }
  
  function g0_512_lo(xh, xl) {
    var c0_lo = rotr64_lo(xh, xl, 1);
    var c1_lo = rotr64_lo(xh, xl, 8);
    var c2_lo = shr64_lo(xh, xl, 7);
  
    var r = c0_lo ^ c1_lo ^ c2_lo;
    if (r < 0)
      r += 0x100000000;
    return r;
  }
  
  function g1_512_hi(xh, xl) {
    var c0_hi = rotr64_hi(xh, xl, 19);
    var c1_hi = rotr64_hi(xl, xh, 29);  // 61
    var c2_hi = shr64_hi(xh, xl, 6);
  
    var r = c0_hi ^ c1_hi ^ c2_hi;
    if (r < 0)
      r += 0x100000000;
    return r;
  }
  
  function g1_512_lo(xh, xl) {
    var c0_lo = rotr64_lo(xh, xl, 19);
    var c1_lo = rotr64_lo(xl, xh, 29);  // 61
    var c2_lo = shr64_lo(xh, xl, 6);
  
    var r = c0_lo ^ c1_lo ^ c2_lo;
    if (r < 0)
      r += 0x100000000;
    return r;
  }
  
  },{"../hash":33}],38:[function(require,module,exports){
  var utils = exports;
  var inherits = require('inherits');
  
  function toArray(msg, enc) {
    if (Array.isArray(msg))
      return msg.slice();
    if (!msg)
      return [];
    var res = [];
    if (typeof msg === 'string') {
      if (!enc) {
        for (var i = 0; i < msg.length; i++) {
          var c = msg.charCodeAt(i);
          var hi = c >> 8;
          var lo = c & 0xff;
          if (hi)
            res.push(hi, lo);
          else
            res.push(lo);
        }
      } else if (enc === 'hex') {
        msg = msg.replace(/[^a-z0-9]+/ig, '');
        if (msg.length % 2 !== 0)
          msg = '0' + msg;
        for (var i = 0; i < msg.length; i += 2)
          res.push(parseInt(msg[i] + msg[i + 1], 16));
      }
    } else {
      for (var i = 0; i < msg.length; i++)
        res[i] = msg[i] | 0;
    }
    return res;
  }
  utils.toArray = toArray;
  
  function toHex(msg) {
    var res = '';
    for (var i = 0; i < msg.length; i++)
      res += zero2(msg[i].toString(16));
    return res;
  }
  utils.toHex = toHex;
  
  function htonl(w) {
    var res = (w >>> 24) |
              ((w >>> 8) & 0xff00) |
              ((w << 8) & 0xff0000) |
              ((w & 0xff) << 24);
    return res >>> 0;
  }
  utils.htonl = htonl;
  
  function toHex32(msg, endian) {
    var res = '';
    for (var i = 0; i < msg.length; i++) {
      var w = msg[i];
      if (endian === 'little')
        w = htonl(w);
      res += zero8(w.toString(16));
    }
    return res;
  }
  utils.toHex32 = toHex32;
  
  function zero2(word) {
    if (word.length === 1)
      return '0' + word;
    else
      return word;
  }
  utils.zero2 = zero2;
  
  function zero8(word) {
    if (word.length === 7)
      return '0' + word;
    else if (word.length === 6)
      return '00' + word;
    else if (word.length === 5)
      return '000' + word;
    else if (word.length === 4)
      return '0000' + word;
    else if (word.length === 3)
      return '00000' + word;
    else if (word.length === 2)
      return '000000' + word;
    else if (word.length === 1)
      return '0000000' + word;
    else
      return word;
  }
  utils.zero8 = zero8;
  
  function join32(msg, start, end, endian) {
    var len = end - start;
    assert(len % 4 === 0);
    var res = new Array(len / 4);
    for (var i = 0, k = start; i < res.length; i++, k += 4) {
      var w;
      if (endian === 'big')
        w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
      else
        w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
      res[i] = w >>> 0;
    }
    return res;
  }
  utils.join32 = join32;
  
  function split32(msg, endian) {
    var res = new Array(msg.length * 4);
    for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
      var m = msg[i];
      if (endian === 'big') {
        res[k] = m >>> 24;
        res[k + 1] = (m >>> 16) & 0xff;
        res[k + 2] = (m >>> 8) & 0xff;
        res[k + 3] = m & 0xff;
      } else {
        res[k + 3] = m >>> 24;
        res[k + 2] = (m >>> 16) & 0xff;
        res[k + 1] = (m >>> 8) & 0xff;
        res[k] = m & 0xff;
      }
    }
    return res;
  }
  utils.split32 = split32;
  
  function rotr32(w, b) {
    return (w >>> b) | (w << (32 - b));
  }
  utils.rotr32 = rotr32;
  
  function rotl32(w, b) {
    return (w << b) | (w >>> (32 - b));
  }
  utils.rotl32 = rotl32;
  
  function sum32(a, b) {
    return (a + b) >>> 0;
  }
  utils.sum32 = sum32;
  
  function sum32_3(a, b, c) {
    return (a + b + c) >>> 0;
  }
  utils.sum32_3 = sum32_3;
  
  function sum32_4(a, b, c, d) {
    return (a + b + c + d) >>> 0;
  }
  utils.sum32_4 = sum32_4;
  
  function sum32_5(a, b, c, d, e) {
    return (a + b + c + d + e) >>> 0;
  }
  utils.sum32_5 = sum32_5;
  
  function assert(cond, msg) {
    if (!cond)
      throw new Error(msg || 'Assertion failed');
  }
  utils.assert = assert;
  
  utils.inherits = inherits;
  
  function sum64(buf, pos, ah, al) {
    var bh = buf[pos];
    var bl = buf[pos + 1];
  
    var lo = (al + bl) >>> 0;
    var hi = (lo < al ? 1 : 0) + ah + bh;
    buf[pos] = hi >>> 0;
    buf[pos + 1] = lo;
  }
  exports.sum64 = sum64;
  
  function sum64_hi(ah, al, bh, bl) {
    var lo = (al + bl) >>> 0;
    var hi = (lo < al ? 1 : 0) + ah + bh;
    return hi >>> 0;
  };
  exports.sum64_hi = sum64_hi;
  
  function sum64_lo(ah, al, bh, bl) {
    var lo = al + bl;
    return lo >>> 0;
  };
  exports.sum64_lo = sum64_lo;
  
  function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
    var carry = 0;
    var lo = al;
    lo = (lo + bl) >>> 0;
    carry += lo < al ? 1 : 0;
    lo = (lo + cl) >>> 0;
    carry += lo < cl ? 1 : 0;
    lo = (lo + dl) >>> 0;
    carry += lo < dl ? 1 : 0;
  
    var hi = ah + bh + ch + dh + carry;
    return hi >>> 0;
  };
  exports.sum64_4_hi = sum64_4_hi;
  
  function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
    var lo = al + bl + cl + dl;
    return lo >>> 0;
  };
  exports.sum64_4_lo = sum64_4_lo;
  
  function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
    var carry = 0;
    var lo = al;
    lo = (lo + bl) >>> 0;
    carry += lo < al ? 1 : 0;
    lo = (lo + cl) >>> 0;
    carry += lo < cl ? 1 : 0;
    lo = (lo + dl) >>> 0;
    carry += lo < dl ? 1 : 0;
    lo = (lo + el) >>> 0;
    carry += lo < el ? 1 : 0;
  
    var hi = ah + bh + ch + dh + eh + carry;
    return hi >>> 0;
  };
  exports.sum64_5_hi = sum64_5_hi;
  
  function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
    var lo = al + bl + cl + dl + el;
  
    return lo >>> 0;
  };
  exports.sum64_5_lo = sum64_5_lo;
  
  function rotr64_hi(ah, al, num) {
    var r = (al << (32 - num)) | (ah >>> num);
    return r >>> 0;
  };
  exports.rotr64_hi = rotr64_hi;
  
  function rotr64_lo(ah, al, num) {
    var r = (ah << (32 - num)) | (al >>> num);
    return r >>> 0;
  };
  exports.rotr64_lo = rotr64_lo;
  
  function shr64_hi(ah, al, num) {
    return ah >>> num;
  };
  exports.shr64_hi = shr64_hi;
  
  function shr64_lo(ah, al, num) {
    var r = (ah << (32 - num)) | (al >>> num);
    return r >>> 0;
  };
  exports.shr64_lo = shr64_lo;
  
  },{"inherits":39}],39:[function(require,module,exports){
  if (typeof Object.create === 'function') {
    // implementation from standard node.js 'util' module
    module.exports = function inherits(ctor, superCtor) {
      ctor.super_ = superCtor
      ctor.prototype = Object.create(superCtor.prototype, {
        constructor: {
          value: ctor,
          enumerable: false,
          writable: true,
          configurable: true
        }
      });
    };
  } else {
    // old school shim for old browsers
    module.exports = function inherits(ctor, superCtor) {
      ctor.super_ = superCtor
      var TempCtor = function () {}
      TempCtor.prototype = superCtor.prototype
      ctor.prototype = new TempCtor()
      ctor.prototype.constructor = ctor
    }
  }
  
  },{}],40:[function(require,module,exports){
  (function (global){
  /*
   * js-sha3 v0.3.1
   * https://github.com/emn178/js-sha3
   *
   * Copyright 2015, emn178@gmail.com
   *
   * Licensed under the MIT license:
   * http://www.opensource.org/licenses/MIT
   */
  ;(function(root, undefined) {
    'use strict';
  
    var NODE_JS = typeof(module) != 'undefined';
    if(NODE_JS) {
      root = global;
      if(root.JS_SHA3_TEST) {
        root.navigator = { userAgent: 'Chrome'};
      }
    }
    var CHROME = (root.JS_SHA3_TEST || !NODE_JS) && navigator.userAgent.indexOf('Chrome') != -1;
    var HEX_CHARS = '0123456789abcdef'.split('');
    var KECCAK_PADDING = [1, 256, 65536, 16777216];
    var PADDING = [6, 1536, 393216, 100663296];
    var SHIFT = [0, 8, 16, 24];
    var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649,
              0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, 
              2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, 
              2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648,
              2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648];
  
    var blocks = [], s = [];
  
    var keccak_224 = function(message) {
      return keccak(message, 224, KECCAK_PADDING);
    };
  
    var keccak_256 = function(message) {
      return keccak(message, 256, KECCAK_PADDING);
    };
  
    var keccak_384 = function(message) {
      return keccak(message, 384, KECCAK_PADDING);
    };
  
    var sha3_224 = function(message) {
      return keccak(message, 224, PADDING);
    };
  
    var sha3_256 = function(message) {
      return keccak(message, 256, PADDING);
    };
  
    var sha3_384 = function(message) {
      return keccak(message, 384, PADDING);
    };
  
    var sha3_512 = function(message) {
      return keccak(message, 512, PADDING);
    };
  
    var keccak = function(message, bits, padding) {
      var notString = typeof(message) != 'string';
      if(notString && message.constructor == root.ArrayBuffer) {
        message = new Uint8Array(message);
      }
  
      if(bits === undefined) {
        bits = 512;
        padding = KECCAK_PADDING;
      }
  
      var block, code, end = false, index = 0, start = 0, length = message.length,
          n, i, h, l, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, 
          b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, 
          b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33, 
          b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49;
      var blockCount = (1600 - bits * 2) / 32;
      var byteCount = blockCount * 4;
  
      for(i = 0;i < 50;++i) {
        s[i] = 0;
      }
  
      block = 0;
      do {
        blocks[0] = block;
        for(i = 1;i < blockCount + 1;++i) {
          blocks[i] = 0;
        }
        if(notString) {
          for (i = start;index < length && i < byteCount; ++index) {
            blocks[i >> 2] |= message[index] << SHIFT[i++ & 3];
          }
        } else {
          for (i = start;index < length && i < byteCount; ++index) {
            code = message.charCodeAt(index);
            if (code < 0x80) {
              blocks[i >> 2] |= code << SHIFT[i++ & 3];
            } else if (code < 0x800) {
              blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3];
              blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
            } else if (code < 0xd800 || code >= 0xe000) {
              blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3];
              blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];
              blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
            } else {
              code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff));
              blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3];
              blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3];
              blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];
              blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
            }
          }
        }
        start = i - byteCount;
        if(index == length) {
          blocks[i >> 2] |= padding[i & 3];
          ++index;
        }
        block = blocks[blockCount];
        if(index > length && i < byteCount) {
          blocks[blockCount - 1] |= 0x80000000;
          end = true;
        }
  
        for(i = 0;i < blockCount;++i) {
          s[i] ^= blocks[i];
        }
  
        for(n = 0; n < 48; n += 2) {
          c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40];
          c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41];
          c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42];
          c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43];
          c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44];
          c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45];
          c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46];
          c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47];
          c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48];
          c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49];
  
          h = c8 ^ ((c2 << 1) | (c3 >>> 31));
          l = c9 ^ ((c3 << 1) | (c2 >>> 31));
          s[0] ^= h;
          s[1] ^= l;
          s[10] ^= h;
          s[11] ^= l;
          s[20] ^= h;
          s[21] ^= l;
          s[30] ^= h;
          s[31] ^= l;
          s[40] ^= h;
          s[41] ^= l;
          h = c0 ^ ((c4 << 1) | (c5 >>> 31));
          l = c1 ^ ((c5 << 1) | (c4 >>> 31));
          s[2] ^= h;
          s[3] ^= l;
          s[12] ^= h;
          s[13] ^= l;
          s[22] ^= h;
          s[23] ^= l;
          s[32] ^= h;
          s[33] ^= l;
          s[42] ^= h;
          s[43] ^= l;
          h = c2 ^ ((c6 << 1) | (c7 >>> 31));
          l = c3 ^ ((c7 << 1) | (c6 >>> 31));
          s[4] ^= h;
          s[5] ^= l;
          s[14] ^= h;
          s[15] ^= l;
          s[24] ^= h;
          s[25] ^= l;
          s[34] ^= h;
          s[35] ^= l;
          s[44] ^= h;
          s[45] ^= l;
          h = c4 ^ ((c8 << 1) | (c9 >>> 31));
          l = c5 ^ ((c9 << 1) | (c8 >>> 31));
          s[6] ^= h;
          s[7] ^= l;
          s[16] ^= h;
          s[17] ^= l;
          s[26] ^= h;
          s[27] ^= l;
          s[36] ^= h;
          s[37] ^= l;
          s[46] ^= h;
          s[47] ^= l;
          h = c6 ^ ((c0 << 1) | (c1 >>> 31));
          l = c7 ^ ((c1 << 1) | (c0 >>> 31));
          s[8] ^= h;
          s[9] ^= l;
          s[18] ^= h;
          s[19] ^= l;
          s[28] ^= h;
          s[29] ^= l;
          s[38] ^= h;
          s[39] ^= l;
          s[48] ^= h;
          s[49] ^= l;
  
          b0 = s[0];
          b1 = s[1];
          b32 = (s[11] << 4) | (s[10] >>> 28);
          b33 = (s[10] << 4) | (s[11] >>> 28);
          b14 = (s[20] << 3) | (s[21] >>> 29);
          b15 = (s[21] << 3) | (s[20] >>> 29);
          b46 = (s[31] << 9) | (s[30] >>> 23);
          b47 = (s[30] << 9) | (s[31] >>> 23);
          b28 = (s[40] << 18) | (s[41] >>> 14);
          b29 = (s[41] << 18) | (s[40] >>> 14);
          b20 = (s[2] << 1) | (s[3] >>> 31);
          b21 = (s[3] << 1) | (s[2] >>> 31);
          b2 = (s[13] << 12) | (s[12] >>> 20);
          b3 = (s[12] << 12) | (s[13] >>> 20);
          b34 = (s[22] << 10) | (s[23] >>> 22);
          b35 = (s[23] << 10) | (s[22] >>> 22);
          b16 = (s[33] << 13) | (s[32] >>> 19);
          b17 = (s[32] << 13) | (s[33] >>> 19);
          b48 = (s[42] << 2) | (s[43] >>> 30);
          b49 = (s[43] << 2) | (s[42] >>> 30);
          b40 = (s[5] << 30) | (s[4] >>> 2);
          b41 = (s[4] << 30) | (s[5] >>> 2);
          b22 = (s[14] << 6) | (s[15] >>> 26);
          b23 = (s[15] << 6) | (s[14] >>> 26);
          b4 = (s[25] << 11) | (s[24] >>> 21);
          b5 = (s[24] << 11) | (s[25] >>> 21);
          b36 = (s[34] << 15) | (s[35] >>> 17);
          b37 = (s[35] << 15) | (s[34] >>> 17);
          b18 = (s[45] << 29) | (s[44] >>> 3);
          b19 = (s[44] << 29) | (s[45] >>> 3);
          b10 = (s[6] << 28) | (s[7] >>> 4);
          b11 = (s[7] << 28) | (s[6] >>> 4);
          b42 = (s[17] << 23) | (s[16] >>> 9);
          b43 = (s[16] << 23) | (s[17] >>> 9);
          b24 = (s[26] << 25) | (s[27] >>> 7);
          b25 = (s[27] << 25) | (s[26] >>> 7);
          b6 = (s[36] << 21) | (s[37] >>> 11);
          b7 = (s[37] << 21) | (s[36] >>> 11);
          b38 = (s[47] << 24) | (s[46] >>> 8);
          b39 = (s[46] << 24) | (s[47] >>> 8);
          b30 = (s[8] << 27) | (s[9] >>> 5);
          b31 = (s[9] << 27) | (s[8] >>> 5);
          b12 = (s[18] << 20) | (s[19] >>> 12);
          b13 = (s[19] << 20) | (s[18] >>> 12);
          b44 = (s[29] << 7) | (s[28] >>> 25);
          b45 = (s[28] << 7) | (s[29] >>> 25);
          b26 = (s[38] << 8) | (s[39] >>> 24);
          b27 = (s[39] << 8) | (s[38] >>> 24);
          b8 = (s[48] << 14) | (s[49] >>> 18);
          b9 = (s[49] << 14) | (s[48] >>> 18);
  
          s[0] = b0 ^ (~b2 & b4);
          s[1] = b1 ^ (~b3 & b5);
          s[10] = b10 ^ (~b12 & b14);
          s[11] = b11 ^ (~b13 & b15);
          s[20] = b20 ^ (~b22 & b24);
          s[21] = b21 ^ (~b23 & b25);
          s[30] = b30 ^ (~b32 & b34);
          s[31] = b31 ^ (~b33 & b35);
          s[40] = b40 ^ (~b42 & b44);
          s[41] = b41 ^ (~b43 & b45);
          s[2] = b2 ^ (~b4 & b6);
          s[3] = b3 ^ (~b5 & b7);
          s[12] = b12 ^ (~b14 & b16);
          s[13] = b13 ^ (~b15 & b17);
          s[22] = b22 ^ (~b24 & b26);
          s[23] = b23 ^ (~b25 & b27);
          s[32] = b32 ^ (~b34 & b36);
          s[33] = b33 ^ (~b35 & b37);
          s[42] = b42 ^ (~b44 & b46);
          s[43] = b43 ^ (~b45 & b47);
          s[4] = b4 ^ (~b6 & b8);
          s[5] = b5 ^ (~b7 & b9);
          s[14] = b14 ^ (~b16 & b18);
          s[15] = b15 ^ (~b17 & b19);
          s[24] = b24 ^ (~b26 & b28);
          s[25] = b25 ^ (~b27 & b29);
          s[34] = b34 ^ (~b36 & b38);
          s[35] = b35 ^ (~b37 & b39);
          s[44] = b44 ^ (~b46 & b48);
          s[45] = b45 ^ (~b47 & b49);
          s[6] = b6 ^ (~b8 & b0);
          s[7] = b7 ^ (~b9 & b1);
          s[16] = b16 ^ (~b18 & b10);
          s[17] = b17 ^ (~b19 & b11);
          s[26] = b26 ^ (~b28 & b20);
          s[27] = b27 ^ (~b29 & b21);
          s[36] = b36 ^ (~b38 & b30);
          s[37] = b37 ^ (~b39 & b31);
          s[46] = b46 ^ (~b48 & b40);
          s[47] = b47 ^ (~b49 & b41);
          s[8] = b8 ^ (~b0 & b2);
          s[9] = b9 ^ (~b1 & b3);
          s[18] = b18 ^ (~b10 & b12);
          s[19] = b19 ^ (~b11 & b13);
          s[28] = b28 ^ (~b20 & b22);
          s[29] = b29 ^ (~b21 & b23);
          s[38] = b38 ^ (~b30 & b32);
          s[39] = b39 ^ (~b31 & b33);
          s[48] = b48 ^ (~b40 & b42);
          s[49] = b49 ^ (~b41 & b43);
  
          s[0] ^= RC[n];
          s[1] ^= RC[n + 1];
        }
      } while(!end);
  
      var hex = '';
      if(CHROME) {
        b0 = s[0];
        b1 = s[1];
        b2 = s[2];
        b3 = s[3];
        b4 = s[4];
        b5 = s[5];
        b6 = s[6];
        b7 = s[7];
        b8 = s[8];
        b9 = s[9];
        b10 = s[10];
        b11 = s[11];
        b12 = s[12];
        b13 = s[13];
        b14 = s[14];
        b15 = s[15];
        hex += HEX_CHARS[(b0 >> 4) & 0x0F] + HEX_CHARS[b0 & 0x0F] +
               HEX_CHARS[(b0 >> 12) & 0x0F] + HEX_CHARS[(b0 >> 8) & 0x0F] +
               HEX_CHARS[(b0 >> 20) & 0x0F] + HEX_CHARS[(b0 >> 16) & 0x0F] +
               HEX_CHARS[(b0 >> 28) & 0x0F] + HEX_CHARS[(b0 >> 24) & 0x0F] +
               HEX_CHARS[(b1 >> 4) & 0x0F] + HEX_CHARS[b1 & 0x0F] +
               HEX_CHARS[(b1 >> 12) & 0x0F] + HEX_CHARS[(b1 >> 8) & 0x0F] +
               HEX_CHARS[(b1 >> 20) & 0x0F] + HEX_CHARS[(b1 >> 16) & 0x0F] +
               HEX_CHARS[(b1 >> 28) & 0x0F] + HEX_CHARS[(b1 >> 24) & 0x0F] +
               HEX_CHARS[(b2 >> 4) & 0x0F] + HEX_CHARS[b2 & 0x0F] +
               HEX_CHARS[(b2 >> 12) & 0x0F] + HEX_CHARS[(b2 >> 8) & 0x0F] +
               HEX_CHARS[(b2 >> 20) & 0x0F] + HEX_CHARS[(b2 >> 16) & 0x0F] +
               HEX_CHARS[(b2 >> 28) & 0x0F] + HEX_CHARS[(b2 >> 24) & 0x0F] +
               HEX_CHARS[(b3 >> 4) & 0x0F] + HEX_CHARS[b3 & 0x0F] +
               HEX_CHARS[(b3 >> 12) & 0x0F] + HEX_CHARS[(b3 >> 8) & 0x0F] +
               HEX_CHARS[(b3 >> 20) & 0x0F] + HEX_CHARS[(b3 >> 16) & 0x0F] +
               HEX_CHARS[(b3 >> 28) & 0x0F] + HEX_CHARS[(b3 >> 24) & 0x0F] +
               HEX_CHARS[(b4 >> 4) & 0x0F] + HEX_CHARS[b4 & 0x0F] +
               HEX_CHARS[(b4 >> 12) & 0x0F] + HEX_CHARS[(b4 >> 8) & 0x0F] +
               HEX_CHARS[(b4 >> 20) & 0x0F] + HEX_CHARS[(b4 >> 16) & 0x0F] +
               HEX_CHARS[(b4 >> 28) & 0x0F] + HEX_CHARS[(b4 >> 24) & 0x0F] +
               HEX_CHARS[(b5 >> 4) & 0x0F] + HEX_CHARS[b5 & 0x0F] +
               HEX_CHARS[(b5 >> 12) & 0x0F] + HEX_CHARS[(b5 >> 8) & 0x0F] +
               HEX_CHARS[(b5 >> 20) & 0x0F] + HEX_CHARS[(b5 >> 16) & 0x0F] +
               HEX_CHARS[(b5 >> 28) & 0x0F] + HEX_CHARS[(b5 >> 24) & 0x0F] +
               HEX_CHARS[(b6 >> 4) & 0x0F] + HEX_CHARS[b6 & 0x0F] +
               HEX_CHARS[(b6 >> 12) & 0x0F] + HEX_CHARS[(b6 >> 8) & 0x0F] +
               HEX_CHARS[(b6 >> 20) & 0x0F] + HEX_CHARS[(b6 >> 16) & 0x0F] +
               HEX_CHARS[(b6 >> 28) & 0x0F] + HEX_CHARS[(b6 >> 24) & 0x0F];
  
        if(bits >= 256) {
          hex += HEX_CHARS[(b7 >> 4) & 0x0F] + HEX_CHARS[b7 & 0x0F] +
                 HEX_CHARS[(b7 >> 12) & 0x0F] + HEX_CHARS[(b7 >> 8) & 0x0F] +
                 HEX_CHARS[(b7 >> 20) & 0x0F] + HEX_CHARS[(b7 >> 16) & 0x0F] +
                 HEX_CHARS[(b7 >> 28) & 0x0F] + HEX_CHARS[(b7 >> 24) & 0x0F];
        }
        if(bits >= 384) {
          hex += HEX_CHARS[(b8 >> 4) & 0x0F] + HEX_CHARS[b8 & 0x0F] +
                 HEX_CHARS[(b8 >> 12) & 0x0F] + HEX_CHARS[(b8 >> 8) & 0x0F] +
                 HEX_CHARS[(b8 >> 20) & 0x0F] + HEX_CHARS[(b8 >> 16) & 0x0F] +
                 HEX_CHARS[(b8 >> 28) & 0x0F] + HEX_CHARS[(b8 >> 24) & 0x0F] +
                 HEX_CHARS[(b9 >> 4) & 0x0F] + HEX_CHARS[b9 & 0x0F] +
                 HEX_CHARS[(b9 >> 12) & 0x0F] + HEX_CHARS[(b9 >> 8) & 0x0F] +
                 HEX_CHARS[(b9 >> 20) & 0x0F] + HEX_CHARS[(b9 >> 16) & 0x0F] +
                 HEX_CHARS[(b9 >> 28) & 0x0F] + HEX_CHARS[(b9 >> 24) & 0x0F] +
                 HEX_CHARS[(b10 >> 4) & 0x0F] + HEX_CHARS[b10 & 0x0F] +
                 HEX_CHARS[(b10 >> 12) & 0x0F] + HEX_CHARS[(b10 >> 8) & 0x0F] +
                 HEX_CHARS[(b10 >> 20) & 0x0F] + HEX_CHARS[(b10 >> 16) & 0x0F] +
                 HEX_CHARS[(b10 >> 28) & 0x0F] + HEX_CHARS[(b10 >> 24) & 0x0F] +
                 HEX_CHARS[(b11 >> 4) & 0x0F] + HEX_CHARS[b11 & 0x0F] +
                 HEX_CHARS[(b11 >> 12) & 0x0F] + HEX_CHARS[(b11 >> 8) & 0x0F] +
                 HEX_CHARS[(b11 >> 20) & 0x0F] + HEX_CHARS[(b11 >> 16) & 0x0F] +
                 HEX_CHARS[(b11 >> 28) & 0x0F] + HEX_CHARS[(b11 >> 24) & 0x0F];
        }
        if(bits == 512) {
          hex += HEX_CHARS[(b12 >> 4) & 0x0F] + HEX_CHARS[b12 & 0x0F] +
                 HEX_CHARS[(b12 >> 12) & 0x0F] + HEX_CHARS[(b12 >> 8) & 0x0F] +
                 HEX_CHARS[(b12 >> 20) & 0x0F] + HEX_CHARS[(b12 >> 16) & 0x0F] +
                 HEX_CHARS[(b12 >> 28) & 0x0F] + HEX_CHARS[(b12 >> 24) & 0x0F] +
                 HEX_CHARS[(b13 >> 4) & 0x0F] + HEX_CHARS[b13 & 0x0F] +
                 HEX_CHARS[(b13 >> 12) & 0x0F] + HEX_CHARS[(b13 >> 8) & 0x0F] +
                 HEX_CHARS[(b13 >> 20) & 0x0F] + HEX_CHARS[(b13 >> 16) & 0x0F] +
                 HEX_CHARS[(b13 >> 28) & 0x0F] + HEX_CHARS[(b13 >> 24) & 0x0F] +
                 HEX_CHARS[(b14 >> 4) & 0x0F] + HEX_CHARS[b14 & 0x0F] +
                 HEX_CHARS[(b14 >> 12) & 0x0F] + HEX_CHARS[(b14 >> 8) & 0x0F] +
                 HEX_CHARS[(b14 >> 20) & 0x0F] + HEX_CHARS[(b14 >> 16) & 0x0F] +
                 HEX_CHARS[(b14 >> 28) & 0x0F] + HEX_CHARS[(b14 >> 24) & 0x0F] +
                 HEX_CHARS[(b15 >> 4) & 0x0F] + HEX_CHARS[b15 & 0x0F] +
                 HEX_CHARS[(b15 >> 12) & 0x0F] + HEX_CHARS[(b15 >> 8) & 0x0F] +
                 HEX_CHARS[(b15 >> 20) & 0x0F] + HEX_CHARS[(b15 >> 16) & 0x0F] +
                 HEX_CHARS[(b15 >> 28) & 0x0F] + HEX_CHARS[(b15 >> 24) & 0x0F];
        }
      } else {
        for(i = 0, n = bits / 32;i < n;++i) {
          h = s[i];
          hex += HEX_CHARS[(h >> 4) & 0x0F] + HEX_CHARS[h & 0x0F] +
                 HEX_CHARS[(h >> 12) & 0x0F] + HEX_CHARS[(h >> 8) & 0x0F] +
                 HEX_CHARS[(h >> 20) & 0x0F] + HEX_CHARS[(h >> 16) & 0x0F] +
                 HEX_CHARS[(h >> 28) & 0x0F] + HEX_CHARS[(h >> 24) & 0x0F];
        }
      }
      return hex;
    };
    
    if(!root.JS_SHA3_TEST && NODE_JS) {
      module.exports = {
        sha3_512: sha3_512,
        sha3_384: sha3_384,
        sha3_256: sha3_256,
        sha3_224: sha3_224,
        keccak_512: keccak,
        keccak_384: keccak_384,
        keccak_256: keccak_256,
        keccak_224: keccak_224
      };
    } else if(root) {
      root.sha3_512 = sha3_512;
      root.sha3_384 = sha3_384;
      root.sha3_256 = sha3_256;
      root.sha3_224 = sha3_224;
      root.keccak_512 = keccak;
      root.keccak_384 = keccak_384;
      root.keccak_256 = keccak_256;
      root.keccak_224 = keccak_224;
    }
  }(this));
  
  }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  },{}],41:[function(require,module,exports){
  'use strict';
  var DataReader = require('./dataReader');
  
  function ArrayReader(data) {
      if (data) {
          this.data = data;
          this.length = this.data.length;
          this.index = 0;
          this.zero = 0;
  
          for(var i = 0; i < this.data.length; i++) {
              data[i] = data[i] & 0xFF;
          }
      }
  }
  ArrayReader.prototype = new DataReader();
  /**
   * @see DataReader.byteAt
   */
  ArrayReader.prototype.byteAt = function(i) {
      return this.data[this.zero + i];
  };
  /**
   * @see DataReader.lastIndexOfSignature
   */
  ArrayReader.prototype.lastIndexOfSignature = function(sig) {
      var sig0 = sig.charCodeAt(0),
          sig1 = sig.charCodeAt(1),
          sig2 = sig.charCodeAt(2),
          sig3 = sig.charCodeAt(3);
      for (var i = this.length - 4; i >= 0; --i) {
          if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) {
              return i - this.zero;
          }
      }
  
      return -1;
  };
  /**
   * @see DataReader.readData
   */
  ArrayReader.prototype.readData = function(size) {
      this.checkOffset(size);
      if(size === 0) {
          return [];
      }
      var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
      this.index += size;
      return result;
  };
  module.exports = ArrayReader;
  
  },{"./dataReader":46}],42:[function(require,module,exports){
  'use strict';
  // private property
  var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  
  
  // public method for encoding
  exports.encode = function(input, utf8) {
      var output = "";
      var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
      var i = 0;
  
      while (i < input.length) {
  
          chr1 = input.charCodeAt(i++);
          chr2 = input.charCodeAt(i++);
          chr3 = input.charCodeAt(i++);
  
          enc1 = chr1 >> 2;
          enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
          enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
          enc4 = chr3 & 63;
  
          if (isNaN(chr2)) {
              enc3 = enc4 = 64;
          }
          else if (isNaN(chr3)) {
              enc4 = 64;
          }
  
          output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
  
      }
  
      return output;
  };
  
  // public method for decoding
  exports.decode = function(input, utf8) {
      var output = "";
      var chr1, chr2, chr3;
      var enc1, enc2, enc3, enc4;
      var i = 0;
  
      input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  
      while (i < input.length) {
  
          enc1 = _keyStr.indexOf(input.charAt(i++));
          enc2 = _keyStr.indexOf(input.charAt(i++));
          enc3 = _keyStr.indexOf(input.charAt(i++));
          enc4 = _keyStr.indexOf(input.charAt(i++));
  
          chr1 = (enc1 << 2) | (enc2 >> 4);
          chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
          chr3 = ((enc3 & 3) << 6) | enc4;
  
          output = output + String.fromCharCode(chr1);
  
          if (enc3 != 64) {
              output = output + String.fromCharCode(chr2);
          }
          if (enc4 != 64) {
              output = output + String.fromCharCode(chr3);
          }
  
      }
  
      return output;
  
  };
  
  },{}],43:[function(require,module,exports){
  'use strict';
  function CompressedObject() {
      this.compressedSize = 0;
      this.uncompressedSize = 0;
      this.crc32 = 0;
      this.compressionMethod = null;
      this.compressedContent = null;
  }
  
  CompressedObject.prototype = {
      /**
       * Return the decompressed content in an unspecified format.
       * The format will depend on the decompressor.
       * @return {Object} the decompressed content.
       */
      getContent: function() {
          return null; // see implementation
      },
      /**
       * Return the compressed content in an unspecified format.
       * The format will depend on the compressed conten source.
       * @return {Object} the compressed content.
       */
      getCompressedContent: function() {
          return null; // see implementation
      }
  };
  module.exports = CompressedObject;
  
  },{}],44:[function(require,module,exports){
  'use strict';
  exports.STORE = {
      magic: "\x00\x00",
      compress: function(content, compressionOptions) {
          return content; // no compression
      },
      uncompress: function(content) {
          return content; // no compression
      },
      compressInputType: null,
      uncompressInputType: null
  };
  exports.DEFLATE = require('./flate');
  
  },{"./flate":49}],45:[function(require,module,exports){
  'use strict';
  
  var utils = require('./utils');
  
  var table = [
      0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
      0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
      0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
      0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
      0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
      0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
      0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
      0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
      0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
      0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
      0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
      0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
      0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
      0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
      0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
      0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
      0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
      0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
      0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
      0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
      0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
      0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
      0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
      0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
      0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
      0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
      0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
      0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
      0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
      0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
      0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
      0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
      0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
      0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
      0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
      0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
      0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
      0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
      0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
      0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
      0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,
      0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
      0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,
      0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
      0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
      0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
      0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,
      0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
      0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
      0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
      0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
      0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
      0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,
      0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
      0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
      0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
      0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
      0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
      0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,
      0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
      0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,
      0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
      0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
      0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
  ];
  
  /**
   *
   *  Javascript crc32
   *  http://www.webtoolkit.info/
   *
   */
  module.exports = function crc32(input, crc) {
      if (typeof input === "undefined" || !input.length) {
          return 0;
      }
  
      var isArray = utils.getTypeOf(input) !== "string";
  
      if (typeof(crc) == "undefined") {
          crc = 0;
      }
      var x = 0;
      var y = 0;
      var b = 0;
  
      crc = crc ^ (-1);
      for (var i = 0, iTop = input.length; i < iTop; i++) {
          b = isArray ? input[i] : input.charCodeAt(i);
          y = (crc ^ b) & 0xFF;
          x = table[y];
          crc = (crc >>> 8) ^ x;
      }
  
      return crc ^ (-1);
  };
  // vim: set shiftwidth=4 softtabstop=4:
  
  },{"./utils":62}],46:[function(require,module,exports){
  'use strict';
  var utils = require('./utils');
  
  function DataReader(data) {
      this.data = null; // type : see implementation
      this.length = 0;
      this.index = 0;
      this.zero = 0;
  }
  DataReader.prototype = {
      /**
       * Check that the offset will not go too far.
       * @param {string} offset the additional offset to check.
       * @throws {Error} an Error if the offset is out of bounds.
       */
      checkOffset: function(offset) {
          this.checkIndex(this.index + offset);
      },
      /**
       * Check that the specifed index will not be too far.
       * @param {string} newIndex the index to check.
       * @throws {Error} an Error if the index is out of bounds.
       */
      checkIndex: function(newIndex) {
          if (this.length < this.zero + newIndex || newIndex < 0) {
              throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?");
          }
      },
      /**
       * Change the index.
       * @param {number} newIndex The new index.
       * @throws {Error} if the new index is out of the data.
       */
      setIndex: function(newIndex) {
          this.checkIndex(newIndex);
          this.index = newIndex;
      },
      /**
       * Skip the next n bytes.
       * @param {number} n the number of bytes to skip.
       * @throws {Error} if the new index is out of the data.
       */
      skip: function(n) {
          this.setIndex(this.index + n);
      },
      /**
       * Get the byte at the specified index.
       * @param {number} i the index to use.
       * @return {number} a byte.
       */
      byteAt: function(i) {
          // see implementations
      },
      /**
       * Get the next number with a given byte size.
       * @param {number} size the number of bytes to read.
       * @return {number} the corresponding number.
       */
      readInt: function(size) {
          var result = 0,
              i;
          this.checkOffset(size);
          for (i = this.index + size - 1; i >= this.index; i--) {
              result = (result << 8) + this.byteAt(i);
          }
          this.index += size;
          return result;
      },
      /**
       * Get the next string with a given byte size.
       * @param {number} size the number of bytes to read.
       * @return {string} the corresponding string.
       */
      readString: function(size) {
          return utils.transformTo("string", this.readData(size));
      },
      /**
       * Get raw data without conversion, <size> bytes.
       * @param {number} size the number of bytes to read.
       * @return {Object} the raw data, implementation specific.
       */
      readData: function(size) {
          // see implementations
      },
      /**
       * Find the last occurence of a zip signature (4 bytes).
       * @param {string} sig the signature to find.
       * @return {number} the index of the last occurence, -1 if not found.
       */
      lastIndexOfSignature: function(sig) {
          // see implementations
      },
      /**
       * Get the next date.
       * @return {Date} the date.
       */
      readDate: function() {
          var dostime = this.readInt(4);
          return new Date(
          ((dostime >> 25) & 0x7f) + 1980, // year
          ((dostime >> 21) & 0x0f) - 1, // month
          (dostime >> 16) & 0x1f, // day
          (dostime >> 11) & 0x1f, // hour
          (dostime >> 5) & 0x3f, // minute
          (dostime & 0x1f) << 1); // second
      }
  };
  module.exports = DataReader;
  
  },{"./utils":62}],47:[function(require,module,exports){
  'use strict';
  exports.base64 = false;
  exports.binary = false;
  exports.dir = false;
  exports.createFolders = false;
  exports.date = null;
  exports.compression = null;
  exports.compressionOptions = null;
  exports.comment = null;
  exports.unixPermissions = null;
  exports.dosPermissions = null;
  
  },{}],48:[function(require,module,exports){
  'use strict';
  var utils = require('./utils');
  
  /**
   * @deprecated
   * This function will be removed in a future version without replacement.
   */
  exports.string2binary = function(str) {
      return utils.string2binary(str);
  };
  
  /**
   * @deprecated
   * This function will be removed in a future version without replacement.
   */
  exports.string2Uint8Array = function(str) {
      return utils.transformTo("uint8array", str);
  };
  
  /**
   * @deprecated
   * This function will be removed in a future version without replacement.
   */
  exports.uint8Array2String = function(array) {
      return utils.transformTo("string", array);
  };
  
  /**
   * @deprecated
   * This function will be removed in a future version without replacement.
   */
  exports.string2Blob = function(str) {
      var buffer = utils.transformTo("arraybuffer", str);
      return utils.arrayBuffer2Blob(buffer);
  };
  
  /**
   * @deprecated
   * This function will be removed in a future version without replacement.
   */
  exports.arrayBuffer2Blob = function(buffer) {
      return utils.arrayBuffer2Blob(buffer);
  };
  
  /**
   * @deprecated
   * This function will be removed in a future version without replacement.
   */
  exports.transformTo = function(outputType, input) {
      return utils.transformTo(outputType, input);
  };
  
  /**
   * @deprecated
   * This function will be removed in a future version without replacement.
   */
  exports.getTypeOf = function(input) {
      return utils.getTypeOf(input);
  };
  
  /**
   * @deprecated
   * This function will be removed in a future version without replacement.
   */
  exports.checkSupport = function(type) {
      return utils.checkSupport(type);
  };
  
  /**
   * @deprecated
   * This value will be removed in a future version without replacement.
   */
  exports.MAX_VALUE_16BITS = utils.MAX_VALUE_16BITS;
  
  /**
   * @deprecated
   * This value will be removed in a future version without replacement.
   */
  exports.MAX_VALUE_32BITS = utils.MAX_VALUE_32BITS;
  
  
  /**
   * @deprecated
   * This function will be removed in a future version without replacement.
   */
  exports.pretty = function(str) {
      return utils.pretty(str);
  };
  
  /**
   * @deprecated
   * This function will be removed in a future version without replacement.
   */
  exports.findCompression = function(compressionMethod) {
      return utils.findCompression(compressionMethod);
  };
  
  /**
   * @deprecated
   * This function will be removed in a future version without replacement.
   */
  exports.isRegExp = function (object) {
      return utils.isRegExp(object);
  };
  
  
  },{"./utils":62}],49:[function(require,module,exports){
  'use strict';
  var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined');
  
  var pako = require("pako");
  exports.uncompressInputType = USE_TYPEDARRAY ? "uint8array" : "array";
  exports.compressInputType = USE_TYPEDARRAY ? "uint8array" : "array";
  
  exports.magic = "\x08\x00";
  exports.compress = function(input, compressionOptions) {
      return pako.deflateRaw(input, {
          level : compressionOptions.level || -1 // default compression
      });
  };
  exports.uncompress =  function(input) {
      return pako.inflateRaw(input);
  };
  
  },{"pako":67}],50:[function(require,module,exports){
  'use strict';
  
  var base64 = require('./base64');
  
  /**
  Usage:
     zip = new JSZip();
     zip.file("hello.txt", "Hello, World!").file("tempfile", "nothing");
     zip.folder("images").file("smile.gif", base64Data, {base64: true});
     zip.file("Xmas.txt", "Ho ho ho !", {date : new Date("December 25, 2007 00:00:01")});
     zip.remove("tempfile");
  
     base64zip = zip.generate();
  
  **/
  
  /**
   * Representation a of zip file in js
   * @constructor
   * @param {String=|ArrayBuffer=|Uint8Array=} data the data to load, if any (optional).
   * @param {Object=} options the options for creating this objects (optional).
   */
  function JSZip(data, options) {
      // if this constructor is used without `new`, it adds `new` before itself:
      if(!(this instanceof JSZip)) return new JSZip(data, options);
  
      // object containing the files :
      // {
      //   "folder/" : {...},
      //   "folder/data.txt" : {...}
      // }
      this.files = {};
  
      this.comment = null;
  
      // Where we are in the hierarchy
      this.root = "";
      if (data) {
          this.load(data, options);
      }
      this.clone = function() {
          var newObj = new JSZip();
          for (var i in this) {
              if (typeof this[i] !== "function") {
                  newObj[i] = this[i];
              }
          }
          return newObj;
      };
  }
  JSZip.prototype = require('./object');
  JSZip.prototype.load = require('./load');
  JSZip.support = require('./support');
  JSZip.defaults = require('./defaults');
  
  /**
   * @deprecated
   * This namespace will be removed in a future version without replacement.
   */
  JSZip.utils = require('./deprecatedPublicUtils');
  
  JSZip.base64 = {
      /**
       * @deprecated
       * This method will be removed in a future version without replacement.
       */
      encode : function(input) {
          return base64.encode(input);
      },
      /**
       * @deprecated
       * This method will be removed in a future version without replacement.
       */
      decode : function(input) {
          return base64.decode(input);
      }
  };
  JSZip.compressions = require('./compressions');
  module.exports = JSZip;
  
  },{"./base64":42,"./compressions":44,"./defaults":47,"./deprecatedPublicUtils":48,"./load":51,"./object":54,"./support":58}],51:[function(require,module,exports){
  'use strict';
  var base64 = require('./base64');
  var utf8 = require('./utf8');
  var utils = require('./utils');
  var ZipEntries = require('./zipEntries');
  module.exports = function(data, options) {
      var files, zipEntries, i, input;
      options = utils.extend(options || {}, {
          base64: false,
          checkCRC32: false,
          optimizedBinaryString : false,
          createFolders: false,
          decodeFileName: utf8.utf8decode
      });
      if (options.base64) {
          data = base64.decode(data);
      }
  
      zipEntries = new ZipEntries(data, options);
      files = zipEntries.files;
      for (i = 0; i < files.length; i++) {
          input = files[i];
          this.file(input.fileNameStr, input.decompressed, {
              binary: true,
              optimizedBinaryString: true,
              date: input.date,
              dir: input.dir,
              comment : input.fileCommentStr.length ? input.fileCommentStr : null,
              unixPermissions : input.unixPermissions,
              dosPermissions : input.dosPermissions,
              createFolders: options.createFolders
          });
      }
      if (zipEntries.zipComment.length) {
          this.comment = zipEntries.zipComment;
      }
  
      return this;
  };
  
  },{"./base64":42,"./utf8":61,"./utils":62,"./zipEntries":63}],52:[function(require,module,exports){
  (function (Buffer){
  'use strict';
  module.exports = function(data, encoding){
      return new Buffer(data, encoding);
  };
  module.exports.test = function(b){
      return Buffer.isBuffer(b);
  };
  
  }).call(this,require("buffer").Buffer)
  },{"buffer":88}],53:[function(require,module,exports){
  'use strict';
  var Uint8ArrayReader = require('./uint8ArrayReader');
  
  function NodeBufferReader(data) {
      this.data = data;
      this.length = this.data.length;
      this.index = 0;
      this.zero = 0;
  }
  NodeBufferReader.prototype = new Uint8ArrayReader();
  
  /**
   * @see DataReader.readData
   */
  NodeBufferReader.prototype.readData = function(size) {
      this.checkOffset(size);
      var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
      this.index += size;
      return result;
  };
  module.exports = NodeBufferReader;
  
  },{"./uint8ArrayReader":59}],54:[function(require,module,exports){
  'use strict';
  var support = require('./support');
  var utils = require('./utils');
  var crc32 = require('./crc32');
  var signature = require('./signature');
  var defaults = require('./defaults');
  var base64 = require('./base64');
  var compressions = require('./compressions');
  var CompressedObject = require('./compressedObject');
  var nodeBuffer = require('./nodeBuffer');
  var utf8 = require('./utf8');
  var StringWriter = require('./stringWriter');
  var Uint8ArrayWriter = require('./uint8ArrayWriter');
  
  /**
   * Returns the raw data of a ZipObject, decompress the content if necessary.
   * @param {ZipObject} file the file to use.
   * @return {String|ArrayBuffer|Uint8Array|Buffer} the data.
   */
  var getRawData = function(file) {
      if (file._data instanceof CompressedObject) {
          file._data = file._data.getContent();
          file.options.binary = true;
          file.options.base64 = false;
  
          if (utils.getTypeOf(file._data) === "uint8array") {
              var copy = file._data;
              // when reading an arraybuffer, the CompressedObject mechanism will keep it and subarray() a Uint8Array.
              // if we request a file in the same format, we might get the same Uint8Array or its ArrayBuffer (the original zip file).
              file._data = new Uint8Array(copy.length);
              // with an empty Uint8Array, Opera fails with a "Offset larger than array size"
              if (copy.length !== 0) {
                  file._data.set(copy, 0);
              }
          }
      }
      return file._data;
  };
  
  /**
   * Returns the data of a ZipObject in a binary form. If the content is an unicode string, encode it.
   * @param {ZipObject} file the file to use.
   * @return {String|ArrayBuffer|Uint8Array|Buffer} the data.
   */
  var getBinaryData = function(file) {
      var result = getRawData(file),
          type = utils.getTypeOf(result);
      if (type === "string") {
          if (!file.options.binary) {
              // unicode text !
              // unicode string => binary string is a painful process, check if we can avoid it.
              if (support.nodebuffer) {
                  return nodeBuffer(result, "utf-8");
              }
          }
          return file.asBinary();
      }
      return result;
  };
  
  /**
   * Transform this._data into a string.
   * @param {function} filter a function String -> String, applied if not null on the result.
   * @return {String} the string representing this._data.
   */
  var dataToString = function(asUTF8) {
      var result = getRawData(this);
      if (result === null || typeof result === "undefined") {
          return "";
      }
      // if the data is a base64 string, we decode it before checking the encoding !
      if (this.options.base64) {
          result = base64.decode(result);
      }
      if (asUTF8 && this.options.binary) {
          // JSZip.prototype.utf8decode supports arrays as input
          // skip to array => string step, utf8decode will do it.
          result = out.utf8decode(result);
      }
      else {
          // no utf8 transformation, do the array => string step.
          result = utils.transformTo("string", result);
      }
  
      if (!asUTF8 && !this.options.binary) {
          result = utils.transformTo("string", out.utf8encode(result));
      }
      return result;
  };
  /**
   * A simple object representing a file in the zip file.
   * @constructor
   * @param {string} name the name of the file
   * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data
   * @param {Object} options the options of the file
   */
  var ZipObject = function(name, data, options) {
      this.name = name;
      this.dir = options.dir;
      this.date = options.date;
      this.comment = options.comment;
      this.unixPermissions = options.unixPermissions;
      this.dosPermissions = options.dosPermissions;
  
      this._data = data;
      this.options = options;
  
      /*
       * This object contains initial values for dir and date.
       * With them, we can check if the user changed the deprecated metadata in
       * `ZipObject#options` or not.
       */
      this._initialMetadata = {
        dir : options.dir,
        date : options.date
      };
  };
  
  ZipObject.prototype = {
      /**
       * Return the content as UTF8 string.
       * @return {string} the UTF8 string.
       */
      asText: function() {
          return dataToString.call(this, true);
      },
      /**
       * Returns the binary content.
       * @return {string} the content as binary.
       */
      asBinary: function() {
          return dataToString.call(this, false);
      },
      /**
       * Returns the content as a nodejs Buffer.
       * @return {Buffer} the content as a Buffer.
       */
      asNodeBuffer: function() {
          var result = getBinaryData(this);
          return utils.transformTo("nodebuffer", result);
      },
      /**
       * Returns the content as an Uint8Array.
       * @return {Uint8Array} the content as an Uint8Array.
       */
      asUint8Array: function() {
          var result = getBinaryData(this);
          return utils.transformTo("uint8array", result);
      },
      /**
       * Returns the content as an ArrayBuffer.
       * @return {ArrayBuffer} the content as an ArrayBufer.
       */
      asArrayBuffer: function() {
          return this.asUint8Array().buffer;
      }
  };
  
  /**
   * Transform an integer into a string in hexadecimal.
   * @private
   * @param {number} dec the number to convert.
   * @param {number} bytes the number of bytes to generate.
   * @returns {string} the result.
   */
  var decToHex = function(dec, bytes) {
      var hex = "",
          i;
      for (i = 0; i < bytes; i++) {
          hex += String.fromCharCode(dec & 0xff);
          dec = dec >>> 8;
      }
      return hex;
  };
  
  /**
   * Transforms the (incomplete) options from the user into the complete
   * set of options to create a file.
   * @private
   * @param {Object} o the options from the user.
   * @return {Object} the complete set of options.
   */
  var prepareFileAttrs = function(o) {
      o = o || {};
      if (o.base64 === true && (o.binary === null || o.binary === undefined)) {
          o.binary = true;
      }
      o = utils.extend(o, defaults);
      o.date = o.date || new Date();
      if (o.compression !== null) o.compression = o.compression.toUpperCase();
  
      return o;
  };
  
  /**
   * Add a file in the current folder.
   * @private
   * @param {string} name the name of the file
   * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file
   * @param {Object} o the options of the file
   * @return {Object} the new file.
   */
  var fileAdd = function(name, data, o) {
      // be sure sub folders exist
      var dataType = utils.getTypeOf(data),
          parent;
  
      o = prepareFileAttrs(o);
  
      if (typeof o.unixPermissions === "string") {
          o.unixPermissions = parseInt(o.unixPermissions, 8);
      }
  
      // UNX_IFDIR  0040000 see zipinfo.c
      if (o.unixPermissions && (o.unixPermissions & 0x4000)) {
          o.dir = true;
      }
      // Bit 4    Directory
      if (o.dosPermissions && (o.dosPermissions & 0x0010)) {
          o.dir = true;
      }
  
      if (o.dir) {
          name = forceTrailingSlash(name);
      }
  
      if (o.createFolders && (parent = parentFolder(name))) {
          folderAdd.call(this, parent, true);
      }
  
      if (o.dir || data === null || typeof data === "undefined") {
          o.base64 = false;
          o.binary = false;
          data = null;
          dataType = null;
      }
      else if (dataType === "string") {
          if (o.binary && !o.base64) {
              // optimizedBinaryString == true means that the file has already been filtered with a 0xFF mask
              if (o.optimizedBinaryString !== true) {
                  // this is a string, not in a base64 format.
                  // Be sure that this is a correct "binary string"
                  data = utils.string2binary(data);
              }
          }
      }
      else { // arraybuffer, uint8array, ...
          o.base64 = false;
          o.binary = true;
  
          if (!dataType && !(data instanceof CompressedObject)) {
              throw new Error("The data of '" + name + "' is in an unsupported format !");
          }
  
          // special case : it's way easier to work with Uint8Array than with ArrayBuffer
          if (dataType === "arraybuffer") {
              data = utils.transformTo("uint8array", data);
          }
      }
  
      var object = new ZipObject(name, data, o);
      this.files[name] = object;
      return object;
  };
  
  /**
   * Find the parent folder of the path.
   * @private
   * @param {string} path the path to use
   * @return {string} the parent folder, or ""
   */
  var parentFolder = function (path) {
      if (path.slice(-1) == '/') {
          path = path.substring(0, path.length - 1);
      }
      var lastSlash = path.lastIndexOf('/');
      return (lastSlash > 0) ? path.substring(0, lastSlash) : "";
  };
  
  
  /**
   * Returns the path with a slash at the end.
   * @private
   * @param {String} path the path to check.
   * @return {String} the path with a trailing slash.
   */
  var forceTrailingSlash = function(path) {
      // Check the name ends with a /
      if (path.slice(-1) != "/") {
          path += "/"; // IE doesn't like substr(-1)
      }
      return path;
  };
  /**
   * Add a (sub) folder in the current folder.
   * @private
   * @param {string} name the folder's name
   * @param {boolean=} [createFolders] If true, automatically create sub
   *  folders. Defaults to false.
   * @return {Object} the new folder.
   */
  var folderAdd = function(name, createFolders) {
      createFolders = (typeof createFolders !== 'undefined') ? createFolders : false;
  
      name = forceTrailingSlash(name);
  
      // Does this folder already exist?
      if (!this.files[name]) {
          fileAdd.call(this, name, null, {
              dir: true,
              createFolders: createFolders
          });
      }
      return this.files[name];
  };
  
  /**
   * Generate a JSZip.CompressedObject for a given zipOject.
   * @param {ZipObject} file the object to read.
   * @param {JSZip.compression} compression the compression to use.
   * @param {Object} compressionOptions the options to use when compressing.
   * @return {JSZip.CompressedObject} the compressed result.
   */
  var generateCompressedObjectFrom = function(file, compression, compressionOptions) {
      var result = new CompressedObject(),
          content;
  
      // the data has not been decompressed, we might reuse things !
      if (file._data instanceof CompressedObject) {
          result.uncompressedSize = file._data.uncompressedSize;
          result.crc32 = file._data.crc32;
  
          if (result.uncompressedSize === 0 || file.dir) {
              compression = compressions['STORE'];
              result.compressedContent = "";
              result.crc32 = 0;
          }
          else if (file._data.compressionMethod === compression.magic) {
              result.compressedContent = file._data.getCompressedContent();
          }
          else {
              content = file._data.getContent();
              // need to decompress / recompress
              result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content), compressionOptions);
          }
      }
      else {
          // have uncompressed data
          content = getBinaryData(file);
          if (!content || content.length === 0 || file.dir) {
              compression = compressions['STORE'];
              content = "";
          }
          result.uncompressedSize = content.length;
          result.crc32 = crc32(content);
          result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content), compressionOptions);
      }
  
      result.compressedSize = result.compressedContent.length;
      result.compressionMethod = compression.magic;
  
      return result;
  };
  
  
  
  
  /**
   * Generate the UNIX part of the external file attributes.
   * @param {Object} unixPermissions the unix permissions or null.
   * @param {Boolean} isDir true if the entry is a directory, false otherwise.
   * @return {Number} a 32 bit integer.
   *
   * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute :
   *
   * TTTTsstrwxrwxrwx0000000000ADVSHR
   * ^^^^____________________________ file type, see zipinfo.c (UNX_*)
   *     ^^^_________________________ setuid, setgid, sticky
   *        ^^^^^^^^^________________ permissions
   *                 ^^^^^^^^^^______ not used ?
   *                           ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only
   */
  var generateUnixExternalFileAttr = function (unixPermissions, isDir) {
  
      var result = unixPermissions;
      if (!unixPermissions) {
          // I can't use octal values in strict mode, hence the hexa.
          //  040775 => 0x41fd
          // 0100664 => 0x81b4
          result = isDir ? 0x41fd : 0x81b4;
      }
  
      return (result & 0xFFFF) << 16;
  };
  
  /**
   * Generate the DOS part of the external file attributes.
   * @param {Object} dosPermissions the dos permissions or null.
   * @param {Boolean} isDir true if the entry is a directory, false otherwise.
   * @return {Number} a 32 bit integer.
   *
   * Bit 0     Read-Only
   * Bit 1     Hidden
   * Bit 2     System
   * Bit 3     Volume Label
   * Bit 4     Directory
   * Bit 5     Archive
   */
  var generateDosExternalFileAttr = function (dosPermissions, isDir) {
  
      // the dir flag is already set for compatibility
  
      return (dosPermissions || 0)  & 0x3F;
  };
  
  /**
   * Generate the various parts used in the construction of the final zip file.
   * @param {string} name the file name.
   * @param {ZipObject} file the file content.
   * @param {JSZip.CompressedObject} compressedObject the compressed object.
   * @param {number} offset the current offset from the start of the zip file.
   * @param {String} platform let's pretend we are this platform (change platform dependents fields)
   * @param {Function} encodeFileName the function to encode the file name / comment.
   * @return {object} the zip parts.
   */
  var generateZipParts = function(name, file, compressedObject, offset, platform, encodeFileName) {
      var data = compressedObject.compressedContent,
          useCustomEncoding = encodeFileName !== utf8.utf8encode,
          encodedFileName = utils.transformTo("string", encodeFileName(file.name)),
          utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)),
          comment = file.comment || "",
          encodedComment = utils.transformTo("string", encodeFileName(comment)),
          utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)),
          useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,
          useUTF8ForComment = utfEncodedComment.length !== comment.length,
          o = file.options,
          dosTime,
          dosDate,
          extraFields = "",
          unicodePathExtraField = "",
          unicodeCommentExtraField = "",
          dir, date;
  
  
      // handle the deprecated options.dir
      if (file._initialMetadata.dir !== file.dir) {
          dir = file.dir;
      } else {
          dir = o.dir;
      }
  
      // handle the deprecated options.date
      if(file._initialMetadata.date !== file.date) {
          date = file.date;
      } else {
          date = o.date;
      }
  
      var extFileAttr = 0;
      var versionMadeBy = 0;
      if (dir) {
          // dos or unix, we set the dos dir flag
          extFileAttr |= 0x00010;
      }
      if(platform === "UNIX") {
          versionMadeBy = 0x031E; // UNIX, version 3.0
          extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir);
      } else { // DOS or other, fallback to DOS
          versionMadeBy = 0x0014; // DOS, version 2.0
          extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir);
      }
  
      // date
      // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html
      // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html
      // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html
  
      dosTime = date.getHours();
      dosTime = dosTime << 6;
      dosTime = dosTime | date.getMinutes();
      dosTime = dosTime << 5;
      dosTime = dosTime | date.getSeconds() / 2;
  
      dosDate = date.getFullYear() - 1980;
      dosDate = dosDate << 4;
      dosDate = dosDate | (date.getMonth() + 1);
      dosDate = dosDate << 5;
      dosDate = dosDate | date.getDate();
  
      if (useUTF8ForFileName) {
          // set the unicode path extra field. unzip needs at least one extra
          // field to correctly handle unicode path, so using the path is as good
          // as any other information. This could improve the situation with
          // other archive managers too.
          // This field is usually used without the utf8 flag, with a non
          // unicode path in the header (winrar, winzip). This helps (a bit)
          // with the messy Windows' default compressed folders feature but
          // breaks on p7zip which doesn't seek the unicode path extra field.
          // So for now, UTF-8 everywhere !
          unicodePathExtraField =
              // Version
              decToHex(1, 1) +
              // NameCRC32
              decToHex(crc32(encodedFileName), 4) +
              // UnicodeName
              utfEncodedFileName;
  
          extraFields +=
              // Info-ZIP Unicode Path Extra Field
              "\x75\x70" +
              // size
              decToHex(unicodePathExtraField.length, 2) +
              // content
              unicodePathExtraField;
      }
  
      if(useUTF8ForComment) {
  
          unicodeCommentExtraField =
              // Version
              decToHex(1, 1) +
              // CommentCRC32
              decToHex(this.crc32(encodedComment), 4) +
              // UnicodeName
              utfEncodedComment;
  
          extraFields +=
              // Info-ZIP Unicode Path Extra Field
              "\x75\x63" +
              // size
              decToHex(unicodeCommentExtraField.length, 2) +
              // content
              unicodeCommentExtraField;
      }
  
      var header = "";
  
      // version needed to extract
      header += "\x0A\x00";
      // general purpose bit flag
      // set bit 11 if utf8
      header += !useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment) ? "\x00\x08" : "\x00\x00";
      // compression method
      header += compressedObject.compressionMethod;
      // last mod file time
      header += decToHex(dosTime, 2);
      // last mod file date
      header += decToHex(dosDate, 2);
      // crc-32
      header += decToHex(compressedObject.crc32, 4);
      // compressed size
      header += decToHex(compressedObject.compressedSize, 4);
      // uncompressed size
      header += decToHex(compressedObject.uncompressedSize, 4);
      // file name length
      header += decToHex(encodedFileName.length, 2);
      // extra field length
      header += decToHex(extraFields.length, 2);
  
  
      var fileRecord = signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields;
  
      var dirRecord = signature.CENTRAL_FILE_HEADER +
      // version made by (00: DOS)
      decToHex(versionMadeBy, 2) +
      // file header (common to file and central directory)
      header +
      // file comment length
      decToHex(encodedComment.length, 2) +
      // disk number start
      "\x00\x00" +
      // internal file attributes TODO
      "\x00\x00" +
      // external file attributes
      decToHex(extFileAttr, 4) +
      // relative offset of local header
      decToHex(offset, 4) +
      // file name
      encodedFileName +
      // extra field
      extraFields +
      // file comment
      encodedComment;
  
      return {
          fileRecord: fileRecord,
          dirRecord: dirRecord,
          compressedObject: compressedObject
      };
  };
  
  
  // return the actual prototype of JSZip
  var out = {
      /**
       * Read an existing zip and merge the data in the current JSZip object.
       * The implementation is in jszip-load.js, don't forget to include it.
       * @param {String|ArrayBuffer|Uint8Array|Buffer} stream  The stream to load
       * @param {Object} options Options for loading the stream.
       *  options.base64 : is the stream in base64 ? default : false
       * @return {JSZip} the current JSZip object
       */
      load: function(stream, options) {
          throw new Error("Load method is not defined. Is the file jszip-load.js included ?");
      },
  
      /**
       * Filter nested files/folders with the specified function.
       * @param {Function} search the predicate to use :
       * function (relativePath, file) {...}
       * It takes 2 arguments : the relative path and the file.
       * @return {Array} An array of matching elements.
       */
      filter: function(search) {
          var result = [],
              filename, relativePath, file, fileClone;
          for (filename in this.files) {
              if (!this.files.hasOwnProperty(filename)) {
                  continue;
              }
              file = this.files[filename];
              // return a new object, don't let the user mess with our internal objects :)
              fileClone = new ZipObject(file.name, file._data, utils.extend(file.options));
              relativePath = filename.slice(this.root.length, filename.length);
              if (filename.slice(0, this.root.length) === this.root && // the file is in the current root
              search(relativePath, fileClone)) { // and the file matches the function
                  result.push(fileClone);
              }
          }
          return result;
      },
  
      /**
       * Add a file to the zip file, or search a file.
       * @param   {string|RegExp} name The name of the file to add (if data is defined),
       * the name of the file to find (if no data) or a regex to match files.
       * @param   {String|ArrayBuffer|Uint8Array|Buffer} data  The file data, either raw or base64 encoded
       * @param   {Object} o     File options
       * @return  {JSZip|Object|Array} this JSZip object (when adding a file),
       * a file (when searching by string) or an array of files (when searching by regex).
       */
      file: function(name, data, o) {
          if (arguments.length === 1) {
              if (utils.isRegExp(name)) {
                  var regexp = name;
                  return this.filter(function(relativePath, file) {
                      return !file.dir && regexp.test(relativePath);
                  });
              }
              else { // text
                  return this.filter(function(relativePath, file) {
                      return !file.dir && relativePath === name;
                  })[0] || null;
              }
          }
          else { // more than one argument : we have data !
              name = this.root + name;
              fileAdd.call(this, name, data, o);
          }
          return this;
      },
  
      /**
       * Add a directory to the zip file, or search.
       * @param   {String|RegExp} arg The name of the directory to add, or a regex to search folders.
       * @return  {JSZip} an object with the new directory as the root, or an array containing matching folders.
       */
      folder: function(arg) {
          if (!arg) {
              return this;
          }
  
          if (utils.isRegExp(arg)) {
              return this.filter(function(relativePath, file) {
                  return file.dir && arg.test(relativePath);
              });
          }
  
          // else, name is a new folder
          var name = this.root + arg;
          var newFolder = folderAdd.call(this, name);
  
          // Allow chaining by returning a new object with this folder as the root
          var ret = this.clone();
          ret.root = newFolder.name;
          return ret;
      },
  
      /**
       * Delete a file, or a directory and all sub-files, from the zip
       * @param {string} name the name of the file to delete
       * @return {JSZip} this JSZip object
       */
      remove: function(name) {
          name = this.root + name;
          var file = this.files[name];
          if (!file) {
              // Look for any folders
              if (name.slice(-1) != "/") {
                  name += "/";
              }
              file = this.files[name];
          }
  
          if (file && !file.dir) {
              // file
              delete this.files[name];
          } else {
              // maybe a folder, delete recursively
              var kids = this.filter(function(relativePath, file) {
                  return file.name.slice(0, name.length) === name;
              });
              for (var i = 0; i < kids.length; i++) {
                  delete this.files[kids[i].name];
              }
          }
  
          return this;
      },
  
      /**
       * Generate the complete zip file
       * @param {Object} options the options to generate the zip file :
       * - base64, (deprecated, use type instead) true to generate base64.
       * - compression, "STORE" by default.
       * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
       * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file
       */
      generate: function(options) {
          options = utils.extend(options || {}, {
              base64: true,
              compression: "STORE",
              compressionOptions : null,
              type: "base64",
              platform: "DOS",
              comment: null,
              mimeType: 'application/zip',
              encodeFileName: utf8.utf8encode
          });
  
          utils.checkSupport(options.type);
  
          // accept nodejs `process.platform`
          if(
            options.platform === 'darwin' ||
            options.platform === 'freebsd' ||
            options.platform === 'linux' ||
            options.platform === 'sunos'
          ) {
            options.platform = "UNIX";
          }
          if (options.platform === 'win32') {
            options.platform = "DOS";
          }
  
          var zipData = [],
              localDirLength = 0,
              centralDirLength = 0,
              writer, i,
              encodedComment = utils.transformTo("string", options.encodeFileName(options.comment || this.comment || ""));
  
          // first, generate all the zip parts.
          for (var name in this.files) {
              if (!this.files.hasOwnProperty(name)) {
                  continue;
              }
              var file = this.files[name];
  
              var compressionName = file.options.compression || options.compression.toUpperCase();
              var compression = compressions[compressionName];
              if (!compression) {
                  throw new Error(compressionName + " is not a valid compression method !");
              }
              var compressionOptions = file.options.compressionOptions || options.compressionOptions || {};
  
              var compressedObject = generateCompressedObjectFrom.call(this, file, compression, compressionOptions);
  
              var zipPart = generateZipParts.call(this, name, file, compressedObject, localDirLength, options.platform, options.encodeFileName);
              localDirLength += zipPart.fileRecord.length + compressedObject.compressedSize;
              centralDirLength += zipPart.dirRecord.length;
              zipData.push(zipPart);
          }
  
          var dirEnd = "";
  
          // end of central dir signature
          dirEnd = signature.CENTRAL_DIRECTORY_END +
          // number of this disk
          "\x00\x00" +
          // number of the disk with the start of the central directory
          "\x00\x00" +
          // total number of entries in the central directory on this disk
          decToHex(zipData.length, 2) +
          // total number of entries in the central directory
          decToHex(zipData.length, 2) +
          // size of the central directory   4 bytes
          decToHex(centralDirLength, 4) +
          // offset of start of central directory with respect to the starting disk number
          decToHex(localDirLength, 4) +
          // .ZIP file comment length
          decToHex(encodedComment.length, 2) +
          // .ZIP file comment
          encodedComment;
  
  
          // we have all the parts (and the total length)
          // time to create a writer !
          var typeName = options.type.toLowerCase();
          if(typeName==="uint8array"||typeName==="arraybuffer"||typeName==="blob"||typeName==="nodebuffer") {
              writer = new Uint8ArrayWriter(localDirLength + centralDirLength + dirEnd.length);
          }else{
              writer = new StringWriter(localDirLength + centralDirLength + dirEnd.length);
          }
  
          for (i = 0; i < zipData.length; i++) {
              writer.append(zipData[i].fileRecord);
              writer.append(zipData[i].compressedObject.compressedContent);
          }
          for (i = 0; i < zipData.length; i++) {
              writer.append(zipData[i].dirRecord);
          }
  
          writer.append(dirEnd);
  
          var zip = writer.finalize();
  
  
  
          switch(options.type.toLowerCase()) {
              // case "zip is an Uint8Array"
              case "uint8array" :
              case "arraybuffer" :
              case "nodebuffer" :
                 return utils.transformTo(options.type.toLowerCase(), zip);
              case "blob" :
                 return utils.arrayBuffer2Blob(utils.transformTo("arraybuffer", zip), options.mimeType);
              // case "zip is a string"
              case "base64" :
                 return (options.base64) ? base64.encode(zip) : zip;
              default : // case "string" :
                 return zip;
           }
  
      },
  
      /**
       * @deprecated
       * This method will be removed in a future version without replacement.
       */
      crc32: function (input, crc) {
          return crc32(input, crc);
      },
  
      /**
       * @deprecated
       * This method will be removed in a future version without replacement.
       */
      utf8encode: function (string) {
          return utils.transformTo("string", utf8.utf8encode(string));
      },
  
      /**
       * @deprecated
       * This method will be removed in a future version without replacement.
       */
      utf8decode: function (input) {
          return utf8.utf8decode(input);
      }
  };
  module.exports = out;
  
  },{"./base64":42,"./compressedObject":43,"./compressions":44,"./crc32":45,"./defaults":47,"./nodeBuffer":52,"./signature":55,"./stringWriter":57,"./support":58,"./uint8ArrayWriter":60,"./utf8":61,"./utils":62}],55:[function(require,module,exports){
  'use strict';
  exports.LOCAL_FILE_HEADER = "PK\x03\x04";
  exports.CENTRAL_FILE_HEADER = "PK\x01\x02";
  exports.CENTRAL_DIRECTORY_END = "PK\x05\x06";
  exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07";
  exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06";
  exports.DATA_DESCRIPTOR = "PK\x07\x08";
  
  },{}],56:[function(require,module,exports){
  'use strict';
  var DataReader = require('./dataReader');
  var utils = require('./utils');
  
  function StringReader(data, optimizedBinaryString) {
      this.data = data;
      if (!optimizedBinaryString) {
          this.data = utils.string2binary(this.data);
      }
      this.length = this.data.length;
      this.index = 0;
      this.zero = 0;
  }
  StringReader.prototype = new DataReader();
  /**
   * @see DataReader.byteAt
   */
  StringReader.prototype.byteAt = function(i) {
      return this.data.charCodeAt(this.zero + i);
  };
  /**
   * @see DataReader.lastIndexOfSignature
   */
  StringReader.prototype.lastIndexOfSignature = function(sig) {
      return this.data.lastIndexOf(sig) - this.zero;
  };
  /**
   * @see DataReader.readData
   */
  StringReader.prototype.readData = function(size) {
      this.checkOffset(size);
      // this will work because the constructor applied the "& 0xff" mask.
      var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
      this.index += size;
      return result;
  };
  module.exports = StringReader;
  
  },{"./dataReader":46,"./utils":62}],57:[function(require,module,exports){
  'use strict';
  
  var utils = require('./utils');
  
  /**
   * An object to write any content to a string.
   * @constructor
   */
  var StringWriter = function() {
      this.data = [];
  };
  StringWriter.prototype = {
      /**
       * Append any content to the current string.
       * @param {Object} input the content to add.
       */
      append: function(input) {
          input = utils.transformTo("string", input);
          this.data.push(input);
      },
      /**
       * Finalize the construction an return the result.
       * @return {string} the generated string.
       */
      finalize: function() {
          return this.data.join("");
      }
  };
  
  module.exports = StringWriter;
  
  },{"./utils":62}],58:[function(require,module,exports){
  (function (Buffer){
  'use strict';
  exports.base64 = true;
  exports.array = true;
  exports.string = true;
  exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
  // contains true if JSZip can read/generate nodejs Buffer, false otherwise.
  // Browserify will provide a Buffer implementation for browsers, which is
  // an augmented Uint8Array (i.e., can be used as either Buffer or U8).
  exports.nodebuffer = typeof Buffer !== "undefined";
  // contains true if JSZip can read/generate Uint8Array, false otherwise.
  exports.uint8array = typeof Uint8Array !== "undefined";
  
  if (typeof ArrayBuffer === "undefined") {
      exports.blob = false;
  }
  else {
      var buffer = new ArrayBuffer(0);
      try {
          exports.blob = new Blob([buffer], {
              type: "application/zip"
          }).size === 0;
      }
      catch (e) {
          try {
              var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
              var builder = new Builder();
              builder.append(buffer);
              exports.blob = builder.getBlob('application/zip').size === 0;
          }
          catch (e) {
              exports.blob = false;
          }
      }
  }
  
  }).call(this,require("buffer").Buffer)
  },{"buffer":88}],59:[function(require,module,exports){
  'use strict';
  var ArrayReader = require('./arrayReader');
  
  function Uint8ArrayReader(data) {
      if (data) {
          this.data = data;
          this.length = this.data.length;
          this.index = 0;
          this.zero = 0;
      }
  }
  Uint8ArrayReader.prototype = new ArrayReader();
  /**
   * @see DataReader.readData
   */
  Uint8ArrayReader.prototype.readData = function(size) {
      this.checkOffset(size);
      if(size === 0) {
          // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].
          return new Uint8Array(0);
      }
      var result = this.data.subarray(this.zero + this.index, this.zero + this.index + size);
      this.index += size;
      return result;
  };
  module.exports = Uint8ArrayReader;
  
  },{"./arrayReader":41}],60:[function(require,module,exports){
  'use strict';
  
  var utils = require('./utils');
  
  /**
   * An object to write any content to an Uint8Array.
   * @constructor
   * @param {number} length The length of the array.
   */
  var Uint8ArrayWriter = function(length) {
      this.data = new Uint8Array(length);
      this.index = 0;
  };
  Uint8ArrayWriter.prototype = {
      /**
       * Append any content to the current array.
       * @param {Object} input the content to add.
       */
      append: function(input) {
          if (input.length !== 0) {
              // with an empty Uint8Array, Opera fails with a "Offset larger than array size"
              input = utils.transformTo("uint8array", input);
              this.data.set(input, this.index);
              this.index += input.length;
          }
      },
      /**
       * Finalize the construction an return the result.
       * @return {Uint8Array} the generated array.
       */
      finalize: function() {
          return this.data;
      }
  };
  
  module.exports = Uint8ArrayWriter;
  
  },{"./utils":62}],61:[function(require,module,exports){
  'use strict';
  
  var utils = require('./utils');
  var support = require('./support');
  var nodeBuffer = require('./nodeBuffer');
  
  /**
   * The following functions come from pako, from pako/lib/utils/strings
   * released under the MIT license, see pako https://github.com/nodeca/pako/
   */
  
  // 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
  var _utf8len = new Array(256);
  for (var i=0; i<256; i++) {
    _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  }
  _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  
  // convert string to array (typed, when possible)
  var string2buf = function (str) {
      var 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
      if (support.uint8array) {
          buf = new Uint8Array(buf_len);
      } else {
          buf = new Array(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;
  };
  
  // 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 = function(buf, max) {
      var pos;
  
      max = max || buf.length;
      if (max > buf.length) { max = buf.length; }
  
      // go back from last position, until start of sequence found
      pos = max-1;
      while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  
      // Fuckup - 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 vuffer is too small,
      // return max too.
      if (pos === 0) { return max; }
  
      return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  };
  
  // convert array to string
  var buf2string = function (buf) {
      var str, i, out, c, c_len;
      var len = buf.length;
  
      // Reserve max possible length (2 words per char)
      // NB: by unknown reasons, Array is significantly faster for
      //     String.fromCharCode.apply than Uint16Array.
      var utf16buf = new Array(len*2);
  
      for (out=0, i=0; i<len;) {
          c = buf[i++];
          // quick process ascii
          if (c < 0x80) { utf16buf[out++] = c; continue; }
  
          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);
          }
      }
  
      // shrinkBuf(utf16buf, out)
      if (utf16buf.length !== out) {
          if(utf16buf.subarray) {
              utf16buf = utf16buf.subarray(0, out);
          } else {
              utf16buf.length = out;
          }
      }
  
      // return String.fromCharCode.apply(null, utf16buf);
      return utils.applyFromCharCode(utf16buf);
  };
  
  
  // That's all for the pako functions.
  
  
  /**
   * Transform a javascript string into an array (typed if possible) of bytes,
   * UTF-8 encoded.
   * @param {String} str the string to encode
   * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.
   */
  exports.utf8encode = function utf8encode(str) {
      if (support.nodebuffer) {
          return nodeBuffer(str, "utf-8");
      }
  
      return string2buf(str);
  };
  
  
  /**
   * Transform a bytes array (or a representation) representing an UTF-8 encoded
   * string into a javascript string.
   * @param {Array|Uint8Array|Buffer} buf the data de decode
   * @return {String} the decoded string.
   */
  exports.utf8decode = function utf8decode(buf) {
      if (support.nodebuffer) {
          return utils.transformTo("nodebuffer", buf).toString("utf-8");
      }
  
      buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf);
  
      // return buf2string(buf);
      // Chrome prefers to work with "small" chunks of data
      // for the method buf2string.
      // Firefox and Chrome has their own shortcut, IE doesn't seem to really care.
      var result = [], k = 0, len = buf.length, chunk = 65536;
      while (k < len) {
          var nextBoundary = utf8border(buf, Math.min(k + chunk, len));
          if (support.uint8array) {
              result.push(buf2string(buf.subarray(k, nextBoundary)));
          } else {
              result.push(buf2string(buf.slice(k, nextBoundary)));
          }
          k = nextBoundary;
      }
      return result.join("");
  
  };
  // vim: set shiftwidth=4 softtabstop=4:
  
  },{"./nodeBuffer":52,"./support":58,"./utils":62}],62:[function(require,module,exports){
  'use strict';
  var support = require('./support');
  var compressions = require('./compressions');
  var nodeBuffer = require('./nodeBuffer');
  /**
   * Convert a string to a "binary string" : a string containing only char codes between 0 and 255.
   * @param {string} str the string to transform.
   * @return {String} the binary string.
   */
  exports.string2binary = function(str) {
      var result = "";
      for (var i = 0; i < str.length; i++) {
          result += String.fromCharCode(str.charCodeAt(i) & 0xff);
      }
      return result;
  };
  exports.arrayBuffer2Blob = function(buffer, mimeType) {
      exports.checkSupport("blob");
  	mimeType = mimeType || 'application/zip';
  
      try {
          // Blob constructor
          return new Blob([buffer], {
              type: mimeType
          });
      }
      catch (e) {
  
          try {
              // deprecated, browser only, old way
              var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
              var builder = new Builder();
              builder.append(buffer);
              return builder.getBlob(mimeType);
          }
          catch (e) {
  
              // well, fuck ?!
              throw new Error("Bug : can't construct the Blob.");
          }
      }
  
  
  };
  /**
   * The identity function.
   * @param {Object} input the input.
   * @return {Object} the same input.
   */
  function identity(input) {
      return input;
  }
  
  /**
   * Fill in an array with a string.
   * @param {String} str the string to use.
   * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).
   * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.
   */
  function stringToArrayLike(str, array) {
      for (var i = 0; i < str.length; ++i) {
          array[i] = str.charCodeAt(i) & 0xFF;
      }
      return array;
  }
  
  /**
   * Transform an array-like object to a string.
   * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
   * @return {String} the result.
   */
  function arrayLikeToString(array) {
      // Performances notes :
      // --------------------
      // String.fromCharCode.apply(null, array) is the fastest, see
      // see http://jsperf.com/converting-a-uint8array-to-a-string/2
      // but the stack is limited (and we can get huge arrays !).
      //
      // result += String.fromCharCode(array[i]); generate too many strings !
      //
      // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2
      var chunk = 65536;
      var result = [],
          len = array.length,
          type = exports.getTypeOf(array),
          k = 0,
          canUseApply = true;
        try {
           switch(type) {
              case "uint8array":
                 String.fromCharCode.apply(null, new Uint8Array(0));
                 break;
              case "nodebuffer":
                 String.fromCharCode.apply(null, nodeBuffer(0));
                 break;
           }
        } catch(e) {
           canUseApply = false;
        }
  
        // no apply : slow and painful algorithm
        // default browser on android 4.*
        if (!canUseApply) {
           var resultStr = "";
           for(var i = 0; i < array.length;i++) {
              resultStr += String.fromCharCode(array[i]);
           }
      return resultStr;
      }
      while (k < len && chunk > 1) {
          try {
              if (type === "array" || type === "nodebuffer") {
                  result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));
              }
              else {
                  result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));
              }
              k += chunk;
          }
          catch (e) {
              chunk = Math.floor(chunk / 2);
          }
      }
      return result.join("");
  }
  
  exports.applyFromCharCode = arrayLikeToString;
  
  
  /**
   * Copy the data from an array-like to an other array-like.
   * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.
   * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.
   * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.
   */
  function arrayLikeToArrayLike(arrayFrom, arrayTo) {
      for (var i = 0; i < arrayFrom.length; i++) {
          arrayTo[i] = arrayFrom[i];
      }
      return arrayTo;
  }
  
  // a matrix containing functions to transform everything into everything.
  var transform = {};
  
  // string to ?
  transform["string"] = {
      "string": identity,
      "array": function(input) {
          return stringToArrayLike(input, new Array(input.length));
      },
      "arraybuffer": function(input) {
          return transform["string"]["uint8array"](input).buffer;
      },
      "uint8array": function(input) {
          return stringToArrayLike(input, new Uint8Array(input.length));
      },
      "nodebuffer": function(input) {
          return stringToArrayLike(input, nodeBuffer(input.length));
      }
  };
  
  // array to ?
  transform["array"] = {
      "string": arrayLikeToString,
      "array": identity,
      "arraybuffer": function(input) {
          return (new Uint8Array(input)).buffer;
      },
      "uint8array": function(input) {
          return new Uint8Array(input);
      },
      "nodebuffer": function(input) {
          return nodeBuffer(input);
      }
  };
  
  // arraybuffer to ?
  transform["arraybuffer"] = {
      "string": function(input) {
          return arrayLikeToString(new Uint8Array(input));
      },
      "array": function(input) {
          return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));
      },
      "arraybuffer": identity,
      "uint8array": function(input) {
          return new Uint8Array(input);
      },
      "nodebuffer": function(input) {
          return nodeBuffer(new Uint8Array(input));
      }
  };
  
  // uint8array to ?
  transform["uint8array"] = {
      "string": arrayLikeToString,
      "array": function(input) {
          return arrayLikeToArrayLike(input, new Array(input.length));
      },
      "arraybuffer": function(input) {
          return input.buffer;
      },
      "uint8array": identity,
      "nodebuffer": function(input) {
          return nodeBuffer(input);
      }
  };
  
  // nodebuffer to ?
  transform["nodebuffer"] = {
      "string": arrayLikeToString,
      "array": function(input) {
          return arrayLikeToArrayLike(input, new Array(input.length));
      },
      "arraybuffer": function(input) {
          return transform["nodebuffer"]["uint8array"](input).buffer;
      },
      "uint8array": function(input) {
          return arrayLikeToArrayLike(input, new Uint8Array(input.length));
      },
      "nodebuffer": identity
  };
  
  /**
   * Transform an input into any type.
   * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.
   * If no output type is specified, the unmodified input will be returned.
   * @param {String} outputType the output type.
   * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.
   * @throws {Error} an Error if the browser doesn't support the requested output type.
   */
  exports.transformTo = function(outputType, input) {
      if (!input) {
          // undefined, null, etc
          // an empty string won't harm.
          input = "";
      }
      if (!outputType) {
          return input;
      }
      exports.checkSupport(outputType);
      var inputType = exports.getTypeOf(input);
      var result = transform[inputType][outputType](input);
      return result;
  };
  
  /**
   * Return the type of the input.
   * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.
   * @param {Object} input the input to identify.
   * @return {String} the (lowercase) type of the input.
   */
  exports.getTypeOf = function(input) {
      if (typeof input === "string") {
          return "string";
      }
      if (Object.prototype.toString.call(input) === "[object Array]") {
          return "array";
      }
      if (support.nodebuffer && nodeBuffer.test(input)) {
          return "nodebuffer";
      }
      if (support.uint8array && input instanceof Uint8Array) {
          return "uint8array";
      }
      if (support.arraybuffer && input instanceof ArrayBuffer) {
          return "arraybuffer";
      }
  };
  
  /**
   * Throw an exception if the type is not supported.
   * @param {String} type the type to check.
   * @throws {Error} an Error if the browser doesn't support the requested type.
   */
  exports.checkSupport = function(type) {
      var supported = support[type.toLowerCase()];
      if (!supported) {
          throw new Error(type + " is not supported by this browser");
      }
  };
  exports.MAX_VALUE_16BITS = 65535;
  exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1
  
  /**
   * Prettify a string read as binary.
   * @param {string} str the string to prettify.
   * @return {string} a pretty string.
   */
  exports.pretty = function(str) {
      var res = '',
          code, i;
      for (i = 0; i < (str || "").length; i++) {
          code = str.charCodeAt(i);
          res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();
      }
      return res;
  };
  
  /**
   * Find a compression registered in JSZip.
   * @param {string} compressionMethod the method magic to find.
   * @return {Object|null} the JSZip compression object, null if none found.
   */
  exports.findCompression = function(compressionMethod) {
      for (var method in compressions) {
          if (!compressions.hasOwnProperty(method)) {
              continue;
          }
          if (compressions[method].magic === compressionMethod) {
              return compressions[method];
          }
      }
      return null;
  };
  /**
  * Cross-window, cross-Node-context regular expression detection
  * @param  {Object}  object Anything
  * @return {Boolean}        true if the object is a regular expression,
  * false otherwise
  */
  exports.isRegExp = function (object) {
      return Object.prototype.toString.call(object) === "[object RegExp]";
  };
  
  /**
   * Merge the objects passed as parameters into a new one.
   * @private
   * @param {...Object} var_args All objects to merge.
   * @return {Object} a new object with the data of the others.
   */
  exports.extend = function() {
      var result = {}, i, attr;
      for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers
          for (attr in arguments[i]) {
              if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") {
                  result[attr] = arguments[i][attr];
              }
          }
      }
      return result;
  };
  
  
  },{"./compressions":44,"./nodeBuffer":52,"./support":58}],63:[function(require,module,exports){
  'use strict';
  var StringReader = require('./stringReader');
  var NodeBufferReader = require('./nodeBufferReader');
  var Uint8ArrayReader = require('./uint8ArrayReader');
  var ArrayReader = require('./arrayReader');
  var utils = require('./utils');
  var sig = require('./signature');
  var ZipEntry = require('./zipEntry');
  var support = require('./support');
  var jszipProto = require('./object');
  //  class ZipEntries {{{
  /**
   * All the entries in the zip file.
   * @constructor
   * @param {String|ArrayBuffer|Uint8Array} data the binary stream to load.
   * @param {Object} loadOptions Options for loading the stream.
   */
  function ZipEntries(data, loadOptions) {
      this.files = [];
      this.loadOptions = loadOptions;
      if (data) {
          this.load(data);
      }
  }
  ZipEntries.prototype = {
      /**
       * Check that the reader is on the speficied signature.
       * @param {string} expectedSignature the expected signature.
       * @throws {Error} if it is an other signature.
       */
      checkSignature: function(expectedSignature) {
          var signature = this.reader.readString(4);
          if (signature !== expectedSignature) {
              throw new Error("Corrupted zip or bug : unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")");
          }
      },
      /**
       * Check if the given signature is at the given index.
       * @param {number} askedIndex the index to check.
       * @param {string} expectedSignature the signature to expect.
       * @return {boolean} true if the signature is here, false otherwise.
       */
      isSignature: function(askedIndex, expectedSignature) {
          var currentIndex = this.reader.index;
          this.reader.setIndex(askedIndex);
          var signature = this.reader.readString(4);
          var result = signature === expectedSignature;
          this.reader.setIndex(currentIndex);
          return result;
      },
      /**
       * Read the end of the central directory.
       */
      readBlockEndOfCentral: function() {
          this.diskNumber = this.reader.readInt(2);
          this.diskWithCentralDirStart = this.reader.readInt(2);
          this.centralDirRecordsOnThisDisk = this.reader.readInt(2);
          this.centralDirRecords = this.reader.readInt(2);
          this.centralDirSize = this.reader.readInt(4);
          this.centralDirOffset = this.reader.readInt(4);
  
          this.zipCommentLength = this.reader.readInt(2);
          // warning : the encoding depends of the system locale
          // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded.
          // On a windows machine, this field is encoded with the localized windows code page.
          var zipComment = this.reader.readData(this.zipCommentLength);
          var decodeParamType = support.uint8array ? "uint8array" : "array";
          // To get consistent behavior with the generation part, we will assume that
          // this is utf8 encoded unless specified otherwise.
          var decodeContent = utils.transformTo(decodeParamType, zipComment);
          this.zipComment = this.loadOptions.decodeFileName(decodeContent);
      },
      /**
       * Read the end of the Zip 64 central directory.
       * Not merged with the method readEndOfCentral :
       * The end of central can coexist with its Zip64 brother,
       * I don't want to read the wrong number of bytes !
       */
      readBlockZip64EndOfCentral: function() {
          this.zip64EndOfCentralSize = this.reader.readInt(8);
          this.versionMadeBy = this.reader.readString(2);
          this.versionNeeded = this.reader.readInt(2);
          this.diskNumber = this.reader.readInt(4);
          this.diskWithCentralDirStart = this.reader.readInt(4);
          this.centralDirRecordsOnThisDisk = this.reader.readInt(8);
          this.centralDirRecords = this.reader.readInt(8);
          this.centralDirSize = this.reader.readInt(8);
          this.centralDirOffset = this.reader.readInt(8);
  
          this.zip64ExtensibleData = {};
          var extraDataSize = this.zip64EndOfCentralSize - 44,
              index = 0,
              extraFieldId,
              extraFieldLength,
              extraFieldValue;
          while (index < extraDataSize) {
              extraFieldId = this.reader.readInt(2);
              extraFieldLength = this.reader.readInt(4);
              extraFieldValue = this.reader.readString(extraFieldLength);
              this.zip64ExtensibleData[extraFieldId] = {
                  id: extraFieldId,
                  length: extraFieldLength,
                  value: extraFieldValue
              };
          }
      },
      /**
       * Read the end of the Zip 64 central directory locator.
       */
      readBlockZip64EndOfCentralLocator: function() {
          this.diskWithZip64CentralDirStart = this.reader.readInt(4);
          this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8);
          this.disksCount = this.reader.readInt(4);
          if (this.disksCount > 1) {
              throw new Error("Multi-volumes zip are not supported");
          }
      },
      /**
       * Read the local files, based on the offset read in the central part.
       */
      readLocalFiles: function() {
          var i, file;
          for (i = 0; i < this.files.length; i++) {
              file = this.files[i];
              this.reader.setIndex(file.localHeaderOffset);
              this.checkSignature(sig.LOCAL_FILE_HEADER);
              file.readLocalPart(this.reader);
              file.handleUTF8();
              file.processAttributes();
          }
      },
      /**
       * Read the central directory.
       */
      readCentralDir: function() {
          var file;
  
          this.reader.setIndex(this.centralDirOffset);
          while (this.reader.readString(4) === sig.CENTRAL_FILE_HEADER) {
              file = new ZipEntry({
                  zip64: this.zip64
              }, this.loadOptions);
              file.readCentralPart(this.reader);
              this.files.push(file);
          }
  
          if (this.centralDirRecords !== this.files.length) {
              if (this.centralDirRecords !== 0 && this.files.length === 0) {
                  // We expected some records but couldn't find ANY.
                  // This is really suspicious, as if something went wrong.
                  throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length);
              } else {
                  // We found some records but not all.
                  // Something is wrong but we got something for the user: no error here.
                  // console.warn("expected", this.centralDirRecords, "records in central dir, got", this.files.length);
              }
          }
      },
      /**
       * Read the end of central directory.
       */
      readEndOfCentral: function() {
          var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END);
          if (offset < 0) {
              // Check if the content is a truncated zip or complete garbage.
              // A "LOCAL_FILE_HEADER" is not required at the beginning (auto
              // extractible zip for example) but it can give a good hint.
              // If an ajax request was used without responseType, we will also
              // get unreadable data.
              var isGarbage = !this.isSignature(0, sig.LOCAL_FILE_HEADER);
  
              if (isGarbage) {
                  throw new Error("Can't find end of central directory : is this a zip file ? " +
                                  "If it is, see http://stuk.github.io/jszip/documentation/howto/read_zip.html");
              } else {
                  throw new Error("Corrupted zip : can't find end of central directory");
              }
          }
          this.reader.setIndex(offset);
          var endOfCentralDirOffset = offset;
          this.checkSignature(sig.CENTRAL_DIRECTORY_END);
          this.readBlockEndOfCentral();
  
  
          /* extract from the zip spec :
              4)  If one of the fields in the end of central directory
                  record is too small to hold required data, the field
                  should be set to -1 (0xFFFF or 0xFFFFFFFF) and the
                  ZIP64 format record should be created.
              5)  The end of central directory record and the
                  Zip64 end of central directory locator record must
                  reside on the same disk when splitting or spanning
                  an archive.
           */
          if (this.diskNumber === utils.MAX_VALUE_16BITS || this.diskWithCentralDirStart === utils.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === utils.MAX_VALUE_16BITS || this.centralDirRecords === utils.MAX_VALUE_16BITS || this.centralDirSize === utils.MAX_VALUE_32BITS || this.centralDirOffset === utils.MAX_VALUE_32BITS) {
              this.zip64 = true;
  
              /*
              Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from
              the zip file can fit into a 32bits integer. This cannot be solved : Javascript represents
              all numbers as 64-bit double precision IEEE 754 floating point numbers.
              So, we have 53bits for integers and bitwise operations treat everything as 32bits.
              see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators
              and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5
              */
  
              // should look for a zip64 EOCD locator
              offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
              if (offset < 0) {
                  throw new Error("Corrupted zip : can't find the ZIP64 end of central directory locator");
              }
              this.reader.setIndex(offset);
              this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
              this.readBlockZip64EndOfCentralLocator();
  
              // now the zip64 EOCD record
              if (!this.isSignature(this.relativeOffsetEndOfZip64CentralDir, sig.ZIP64_CENTRAL_DIRECTORY_END)) {
                  // console.warn("ZIP64 end of central directory not where expected.");
                  this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
                  if (this.relativeOffsetEndOfZip64CentralDir < 0) {
                      throw new Error("Corrupted zip : can't find the ZIP64 end of central directory");
                  }
              }
              this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir);
              this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
              this.readBlockZip64EndOfCentral();
          }
  
          var expectedEndOfCentralDirOffset = this.centralDirOffset + this.centralDirSize;
          if (this.zip64) {
              expectedEndOfCentralDirOffset += 20; // end of central dir 64 locator
              expectedEndOfCentralDirOffset += 12 /* should not include the leading 12 bytes */ + this.zip64EndOfCentralSize;
          }
  
          var extraBytes = endOfCentralDirOffset - expectedEndOfCentralDirOffset;
  
          if (extraBytes > 0) {
              // console.warn(extraBytes, "extra bytes at beginning or within zipfile");
              if (this.isSignature(endOfCentralDirOffset, sig.CENTRAL_FILE_HEADER)) {
                  // The offsets seem wrong, but we have something at the specified offset.
                  // So… we keep it.
              } else {
                  // the offset is wrong, update the "zero" of the reader
                  // this happens if data has been prepended (crx files for example)
                  this.reader.zero = extraBytes;
              }
          } else if (extraBytes < 0) {
              throw new Error("Corrupted zip: missing " + Math.abs(extraBytes) + " bytes.");
          }
      },
      prepareReader: function(data) {
          var type = utils.getTypeOf(data);
          utils.checkSupport(type);
          if (type === "string" && !support.uint8array) {
              this.reader = new StringReader(data, this.loadOptions.optimizedBinaryString);
          }
          else if (type === "nodebuffer") {
              this.reader = new NodeBufferReader(data);
          }
          else if (support.uint8array) {
              this.reader = new Uint8ArrayReader(utils.transformTo("uint8array", data));
          } else if (support.array) {
              this.reader = new ArrayReader(utils.transformTo("array", data));
          } else {
              throw new Error("Unexpected error: unsupported type '" + type + "'");
          }
      },
      /**
       * Read a zip file and create ZipEntries.
       * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file.
       */
      load: function(data) {
          this.prepareReader(data);
          this.readEndOfCentral();
          this.readCentralDir();
          this.readLocalFiles();
      }
  };
  // }}} end of ZipEntries
  module.exports = ZipEntries;
  
  },{"./arrayReader":41,"./nodeBufferReader":53,"./object":54,"./signature":55,"./stringReader":56,"./support":58,"./uint8ArrayReader":59,"./utils":62,"./zipEntry":64}],64:[function(require,module,exports){
  'use strict';
  var StringReader = require('./stringReader');
  var utils = require('./utils');
  var CompressedObject = require('./compressedObject');
  var jszipProto = require('./object');
  var support = require('./support');
  
  var MADE_BY_DOS = 0x00;
  var MADE_BY_UNIX = 0x03;
  
  // class ZipEntry {{{
  /**
   * An entry in the zip file.
   * @constructor
   * @param {Object} options Options of the current file.
   * @param {Object} loadOptions Options for loading the stream.
   */
  function ZipEntry(options, loadOptions) {
      this.options = options;
      this.loadOptions = loadOptions;
  }
  ZipEntry.prototype = {
      /**
       * say if the file is encrypted.
       * @return {boolean} true if the file is encrypted, false otherwise.
       */
      isEncrypted: function() {
          // bit 1 is set
          return (this.bitFlag & 0x0001) === 0x0001;
      },
      /**
       * say if the file has utf-8 filename/comment.
       * @return {boolean} true if the filename/comment is in utf-8, false otherwise.
       */
      useUTF8: function() {
          // bit 11 is set
          return (this.bitFlag & 0x0800) === 0x0800;
      },
      /**
       * Prepare the function used to generate the compressed content from this ZipFile.
       * @param {DataReader} reader the reader to use.
       * @param {number} from the offset from where we should read the data.
       * @param {number} length the length of the data to read.
       * @return {Function} the callback to get the compressed content (the type depends of the DataReader class).
       */
      prepareCompressedContent: function(reader, from, length) {
          return function() {
              var previousIndex = reader.index;
              reader.setIndex(from);
              var compressedFileData = reader.readData(length);
              reader.setIndex(previousIndex);
  
              return compressedFileData;
          };
      },
      /**
       * Prepare the function used to generate the uncompressed content from this ZipFile.
       * @param {DataReader} reader the reader to use.
       * @param {number} from the offset from where we should read the data.
       * @param {number} length the length of the data to read.
       * @param {JSZip.compression} compression the compression used on this file.
       * @param {number} uncompressedSize the uncompressed size to expect.
       * @return {Function} the callback to get the uncompressed content (the type depends of the DataReader class).
       */
      prepareContent: function(reader, from, length, compression, uncompressedSize) {
          return function() {
  
              var compressedFileData = utils.transformTo(compression.uncompressInputType, this.getCompressedContent());
              var uncompressedFileData = compression.uncompress(compressedFileData);
  
              if (uncompressedFileData.length !== uncompressedSize) {
                  throw new Error("Bug : uncompressed data size mismatch");
              }
  
              return uncompressedFileData;
          };
      },
      /**
       * Read the local part of a zip file and add the info in this object.
       * @param {DataReader} reader the reader to use.
       */
      readLocalPart: function(reader) {
          var compression, localExtraFieldsLength;
  
          // we already know everything from the central dir !
          // If the central dir data are false, we are doomed.
          // On the bright side, the local part is scary  : zip64, data descriptors, both, etc.
          // The less data we get here, the more reliable this should be.
          // Let's skip the whole header and dash to the data !
          reader.skip(22);
          // in some zip created on windows, the filename stored in the central dir contains \ instead of /.
          // Strangely, the filename here is OK.
          // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes
          // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators...
          // Search "unzip mismatching "local" filename continuing with "central" filename version" on
          // the internet.
          //
          // I think I see the logic here : the central directory is used to display
          // content and the local directory is used to extract the files. Mixing / and \
          // may be used to display \ to windows users and use / when extracting the files.
          // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394
          this.fileNameLength = reader.readInt(2);
          localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir
          this.fileName = reader.readData(this.fileNameLength);
          reader.skip(localExtraFieldsLength);
  
          if (this.compressedSize == -1 || this.uncompressedSize == -1) {
              throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory " + "(compressedSize == -1 || uncompressedSize == -1)");
          }
  
          compression = utils.findCompression(this.compressionMethod);
          if (compression === null) { // no compression found
              throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " +  utils.transformTo("string", this.fileName) + ")");
          }
          this.decompressed = new CompressedObject();
          this.decompressed.compressedSize = this.compressedSize;
          this.decompressed.uncompressedSize = this.uncompressedSize;
          this.decompressed.crc32 = this.crc32;
          this.decompressed.compressionMethod = this.compressionMethod;
          this.decompressed.getCompressedContent = this.prepareCompressedContent(reader, reader.index, this.compressedSize, compression);
          this.decompressed.getContent = this.prepareContent(reader, reader.index, this.compressedSize, compression, this.uncompressedSize);
  
          // we need to compute the crc32...
          if (this.loadOptions.checkCRC32) {
              this.decompressed = utils.transformTo("string", this.decompressed.getContent());
              if (jszipProto.crc32(this.decompressed) !== this.crc32) {
                  throw new Error("Corrupted zip : CRC32 mismatch");
              }
          }
      },
  
      /**
       * Read the central part of a zip file and add the info in this object.
       * @param {DataReader} reader the reader to use.
       */
      readCentralPart: function(reader) {
          this.versionMadeBy = reader.readInt(2);
          this.versionNeeded = reader.readInt(2);
          this.bitFlag = reader.readInt(2);
          this.compressionMethod = reader.readString(2);
          this.date = reader.readDate();
          this.crc32 = reader.readInt(4);
          this.compressedSize = reader.readInt(4);
          this.uncompressedSize = reader.readInt(4);
          this.fileNameLength = reader.readInt(2);
          this.extraFieldsLength = reader.readInt(2);
          this.fileCommentLength = reader.readInt(2);
          this.diskNumberStart = reader.readInt(2);
          this.internalFileAttributes = reader.readInt(2);
          this.externalFileAttributes = reader.readInt(4);
          this.localHeaderOffset = reader.readInt(4);
  
          if (this.isEncrypted()) {
              throw new Error("Encrypted zip are not supported");
          }
  
          this.fileName = reader.readData(this.fileNameLength);
          this.readExtraFields(reader);
          this.parseZIP64ExtraField(reader);
          this.fileComment = reader.readData(this.fileCommentLength);
      },
  
      /**
       * Parse the external file attributes and get the unix/dos permissions.
       */
      processAttributes: function () {
          this.unixPermissions = null;
          this.dosPermissions = null;
          var madeBy = this.versionMadeBy >> 8;
  
          // Check if we have the DOS directory flag set.
          // We look for it in the DOS and UNIX permissions
          // but some unknown platform could set it as a compatibility flag.
          this.dir = this.externalFileAttributes & 0x0010 ? true : false;
  
          if(madeBy === MADE_BY_DOS) {
              // first 6 bits (0 to 5)
              this.dosPermissions = this.externalFileAttributes & 0x3F;
          }
  
          if(madeBy === MADE_BY_UNIX) {
              this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF;
              // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8);
          }
  
          // fail safe : if the name ends with a / it probably means a folder
          if (!this.dir && this.fileNameStr.slice(-1) === '/') {
              this.dir = true;
          }
      },
  
      /**
       * Parse the ZIP64 extra field and merge the info in the current ZipEntry.
       * @param {DataReader} reader the reader to use.
       */
      parseZIP64ExtraField: function(reader) {
  
          if (!this.extraFields[0x0001]) {
              return;
          }
  
          // should be something, preparing the extra reader
          var extraReader = new StringReader(this.extraFields[0x0001].value);
  
          // I really hope that these 64bits integer can fit in 32 bits integer, because js
          // won't let us have more.
          if (this.uncompressedSize === utils.MAX_VALUE_32BITS) {
              this.uncompressedSize = extraReader.readInt(8);
          }
          if (this.compressedSize === utils.MAX_VALUE_32BITS) {
              this.compressedSize = extraReader.readInt(8);
          }
          if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) {
              this.localHeaderOffset = extraReader.readInt(8);
          }
          if (this.diskNumberStart === utils.MAX_VALUE_32BITS) {
              this.diskNumberStart = extraReader.readInt(4);
          }
      },
      /**
       * Read the central part of a zip file and add the info in this object.
       * @param {DataReader} reader the reader to use.
       */
      readExtraFields: function(reader) {
          var start = reader.index,
              extraFieldId,
              extraFieldLength,
              extraFieldValue;
  
          this.extraFields = this.extraFields || {};
  
          while (reader.index < start + this.extraFieldsLength) {
              extraFieldId = reader.readInt(2);
              extraFieldLength = reader.readInt(2);
              extraFieldValue = reader.readString(extraFieldLength);
  
              this.extraFields[extraFieldId] = {
                  id: extraFieldId,
                  length: extraFieldLength,
                  value: extraFieldValue
              };
          }
      },
      /**
       * Apply an UTF8 transformation if needed.
       */
      handleUTF8: function() {
          var decodeParamType = support.uint8array ? "uint8array" : "array";
          if (this.useUTF8()) {
              this.fileNameStr = jszipProto.utf8decode(this.fileName);
              this.fileCommentStr = jszipProto.utf8decode(this.fileComment);
          } else {
              var upath = this.findExtraFieldUnicodePath();
              if (upath !== null) {
                  this.fileNameStr = upath;
              } else {
                  var fileNameByteArray =  utils.transformTo(decodeParamType, this.fileName);
                  this.fileNameStr = this.loadOptions.decodeFileName(fileNameByteArray);
              }
  
              var ucomment = this.findExtraFieldUnicodeComment();
              if (ucomment !== null) {
                  this.fileCommentStr = ucomment;
              } else {
                  var commentByteArray =  utils.transformTo(decodeParamType, this.fileComment);
                  this.fileCommentStr = this.loadOptions.decodeFileName(commentByteArray);
              }
          }
      },
  
      /**
       * Find the unicode path declared in the extra field, if any.
       * @return {String} the unicode path, null otherwise.
       */
      findExtraFieldUnicodePath: function() {
          var upathField = this.extraFields[0x7075];
          if (upathField) {
              var extraReader = new StringReader(upathField.value);
  
              // wrong version
              if (extraReader.readInt(1) !== 1) {
                  return null;
              }
  
              // the crc of the filename changed, this field is out of date.
              if (jszipProto.crc32(this.fileName) !== extraReader.readInt(4)) {
                  return null;
              }
  
              return jszipProto.utf8decode(extraReader.readString(upathField.length - 5));
          }
          return null;
      },
  
      /**
       * Find the unicode comment declared in the extra field, if any.
       * @return {String} the unicode comment, null otherwise.
       */
      findExtraFieldUnicodeComment: function() {
          var ucommentField = this.extraFields[0x6375];
          if (ucommentField) {
              var extraReader = new StringReader(ucommentField.value);
  
              // wrong version
              if (extraReader.readInt(1) !== 1) {
                  return null;
              }
  
              // the crc of the comment changed, this field is out of date.
              if (jszipProto.crc32(this.fileComment) !== extraReader.readInt(4)) {
                  return null;
              }
  
              return jszipProto.utf8decode(extraReader.readString(ucommentField.length - 5));
          }
          return null;
      }
  };
  module.exports = ZipEntry;
  
  },{"./compressedObject":43,"./object":54,"./stringReader":56,"./support":58,"./utils":62}],65:[function(require,module,exports){
  var _ = require('underscore');
  
  /**
  The LocalStore singleton.
  
  @class TemplateStore
  @constructor
  **/
  var LocalStore = module.exports = {
      /**
      This object stores all keys and their values.
  
      @property keys
      @type Object
      @default {}
      @example
  
          {
              name->myProperty: "myValue",
              ...
          }
  
      **/
      keys: {},
  
  
      /**
      Keeps the dependencies for the keys in the store.
  
      @property deps
      @type Object
      @default {}
      @example
  
          {
              name->myProperty: new Tracker.Dependency,
              ...
          }
  
      **/
      deps: {},
  
      // METHODS
  
      // PRIVATE
      /**
      Creates at least ones a `Tracker.Dependency` object to a key.
  
      @method _ensureDeps
      @private
      @param {String} key     the name of the key to add a dependecy tracker to
      @return undefined
      **/
      _ensureDeps: function (key) {
          if (!this.deps[key] && (typeof Tracker !== "undefined")){
              this.deps[key] = new Tracker.Dependency;
          }
      },
  	set: function(key, value, options, callback){
  
          this._ensureDeps(key);
  
  		// USE CHROME STORAGE
  		if(typeof chrome !== 'undefined' && chrome.storage) {
  			var item = {};
  			item[key] = value;
  
  			// set
  			chrome.storage.local.set(item, function(){
  
  				// re-run reactive functions
  				if((!options || options.reactive !== false)
                     && (typeof Tracker != "undefined"))
  	                this.deps[key].changed();
  
  	            // run callbacks
  				if(_.isFunction(callback))
  					callback();
  			});
  
  
  		// USE LOCALSTORAGE
  		} else {
  			// stringify
  			if(_.isObject(value))
  				value = JSON.stringify(value);
  
  			// set
              // use try to prevent warnings from low cache storages
              try {
      			localStorage.setItem(key, value);
              } catch(e) {
  
              }
  
  			// re-run reactive functions
  			if((!options || options.reactive !== false)
                  && (typeof Tracker !== "undefined"))
                  this.deps[key].changed();
  
  			// run callbacks
  			if(_.isFunction(callback))
  				callback();
  		}
  	},
  	get: function(key, options, callback){
  
          this._ensureDeps(key);
  
  
          // DEPEND REACTIVE FUNCTIONS
  		if((!options || options.reactive !== false)
              && (typeof Tracker !== "undefined"))
              this.deps[key].depend();
  
  
  		// use chrome storage
  		if(typeof chrome !== 'undefined' && chrome.storage) {
  
  			// get
  			chrome.storage.local.get(key, callback);
  
  
  		// USE LOCALSTORAGE
  		} else {
  			// get
  			var value = localStorage.getItem(key),
  				retunValue = value;
  
  			// try to parse
              if(value && _.isString(value)) {
              	try {
  	                retunValue = JSON.parse(value);
              	} catch(error){
              		retunValue = value;
              	}
              }
  
              return retunValue;
  		}
  
  	}
  }
  },{"underscore":85}],66:[function(require,module,exports){
  /* FileSaver.js
   * A saveAs() FileSaver implementation.
   * 2015-05-07.2
   *
   * By Eli Grey, http://eligrey.com
   * License: X11/MIT
   *   See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
   */
  
  /*global self */
  /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
  
  /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
  
  var saveAs = saveAs || (function(view) {
  	"use strict";
  	
  	// If no view just quit, probably we are in node.js
  	if(typeof view === "undefined") {
  	  	return;
  	}
  	
  	// IE <10 is explicitly unsupported
  	if (typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) {
  		return;
  	}
  	var
  		  doc = view.document
  		  // only get URL when necessary in case Blob.js hasn't overridden it yet
  		, get_URL = function() {
  			return view.URL || view.webkitURL || view;
  		}
  		, save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
  		, can_use_save_link = "download" in save_link
  		, click = function(node) {
  			var event = doc.createEvent("MouseEvents");
  			event.initMouseEvent(
  				"click", true, false, view, 0, 0, 0, 0, 0
  				, false, false, false, false, 0, null
  			);
  			node.dispatchEvent(event);
  		}
  		, webkit_req_fs = view.webkitRequestFileSystem
  		, req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem
  		, throw_outside = function(ex) {
  			(view.setImmediate || view.setTimeout)(function() {
  				throw ex;
  			}, 0);
  		}
  		, force_saveable_type = "application/octet-stream"
  		, fs_min_size = 0
  		// See https://code.google.com/p/chromium/issues/detail?id=375297#c7 and
  		// https://github.com/eligrey/FileSaver.js/commit/485930a#commitcomment-8768047
  		// for the reasoning behind the timeout and revocation flow
  		, arbitrary_revoke_timeout = 500 // in ms
  		, revoke = function(file) {
  			var revoker = function() {
  				if (typeof file === "string") { // file is an object URL
  					get_URL().revokeObjectURL(file);
  				} else { // file is a File
  					file.remove();
  				}
  			};
  			if (view.chrome) {
  				revoker();
  			} else {
  				setTimeout(revoker, arbitrary_revoke_timeout);
  			}
  		}
  		, dispatch = function(filesaver, event_types, event) {
  			event_types = [].concat(event_types);
  			var i = event_types.length;
  			while (i--) {
  				var listener = filesaver["on" + event_types[i]];
  				if (typeof listener === "function") {
  					try {
  						listener.call(filesaver, event || filesaver);
  					} catch (ex) {
  						throw_outside(ex);
  					}
  				}
  			}
  		}
  		, auto_bom = function(blob) {
  			// prepend BOM for UTF-8 XML and text/* types (including HTML)
  			if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
  				return new Blob(["\ufeff", blob], {type: blob.type});
  			}
  			return blob;
  		}
  		, FileSaver = function(blob, name) {
  			blob = auto_bom(blob);
  			// First try a.download, then web filesystem, then object URLs
  			var
  				  filesaver = this
  				, type = blob.type
  				, blob_changed = false
  				, object_url
  				, target_view
  				, dispatch_all = function() {
  					dispatch(filesaver, "writestart progress write writeend".split(" "));
  				}
  				// on any filesys errors revert to saving with object URLs
  				, fs_error = function() {
  					// don't create more object URLs than needed
  					if (blob_changed || !object_url) {
  						object_url = get_URL().createObjectURL(blob);
  					}
  					if (target_view) {
  						target_view.location.href = object_url;
  					} else {
  						var new_tab = view.open(object_url, "_blank");
  						if (new_tab == undefined && typeof safari !== "undefined") {
  							//Apple do not allow window.open, see http://bit.ly/1kZffRI
  							view.location.href = object_url
  						}
  					}
  					filesaver.readyState = filesaver.DONE;
  					dispatch_all();
  					revoke(object_url);
  				}
  				, abortable = function(func) {
  					return function() {
  						if (filesaver.readyState !== filesaver.DONE) {
  							return func.apply(this, arguments);
  						}
  					};
  				}
  				, create_if_not_found = {create: true, exclusive: false}
  				, slice
  			;
  			filesaver.readyState = filesaver.INIT;
  			if (!name) {
  				name = "download";
  			}
  			if (can_use_save_link) {
  				object_url = get_URL().createObjectURL(blob);
  				save_link.href = object_url;
  				save_link.download = name;
  				click(save_link);
  				filesaver.readyState = filesaver.DONE;
  				dispatch_all();
  				revoke(object_url);
  				return;
  			}
  			// Object and web filesystem URLs have a problem saving in Google Chrome when
  			// viewed in a tab, so I force save with application/octet-stream
  			// http://code.google.com/p/chromium/issues/detail?id=91158
  			// Update: Google errantly closed 91158, I submitted it again:
  			// https://code.google.com/p/chromium/issues/detail?id=389642
  			if (view.chrome && type && type !== force_saveable_type) {
  				slice = blob.slice || blob.webkitSlice;
  				blob = slice.call(blob, 0, blob.size, force_saveable_type);
  				blob_changed = true;
  			}
  			// Since I can't be sure that the guessed media type will trigger a download
  			// in WebKit, I append .download to the filename.
  			// https://bugs.webkit.org/show_bug.cgi?id=65440
  			if (webkit_req_fs && name !== "download") {
  				name += ".download";
  			}
  			if (type === force_saveable_type || webkit_req_fs) {
  				target_view = view;
  			}
  			if (!req_fs) {
  				fs_error();
  				return;
  			}
  			fs_min_size += blob.size;
  			req_fs(view.TEMPORARY, fs_min_size, abortable(function(fs) {
  				fs.root.getDirectory("saved", create_if_not_found, abortable(function(dir) {
  					var save = function() {
  						dir.getFile(name, create_if_not_found, abortable(function(file) {
  							file.createWriter(abortable(function(writer) {
  								writer.onwriteend = function(event) {
  									target_view.location.href = file.toURL();
  									filesaver.readyState = filesaver.DONE;
  									dispatch(filesaver, "writeend", event);
  									revoke(file);
  								};
  								writer.onerror = function() {
  									var error = writer.error;
  									if (error.code !== error.ABORT_ERR) {
  										fs_error();
  									}
  								};
  								"writestart progress write abort".split(" ").forEach(function(event) {
  									writer["on" + event] = filesaver["on" + event];
  								});
  								writer.write(blob);
  								filesaver.abort = function() {
  									writer.abort();
  									filesaver.readyState = filesaver.DONE;
  								};
  								filesaver.readyState = filesaver.WRITING;
  							}), fs_error);
  						}), fs_error);
  					};
  					dir.getFile(name, {create: false}, abortable(function(file) {
  						// delete file if it already exists
  						file.remove();
  						save();
  					}), abortable(function(ex) {
  						if (ex.code === ex.NOT_FOUND_ERR) {
  							save();
  						} else {
  							fs_error();
  						}
  					}));
  				}), fs_error);
  			}), fs_error);
  		}
  		, FS_proto = FileSaver.prototype
  		, saveAs = function(blob, name) {
  			return new FileSaver(blob, name);
  		}
  	;
  	// IE 10+ (native saveAs)
  	if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
  		return function(blob, name) {
  			return navigator.msSaveOrOpenBlob(auto_bom(blob), name);
  		};
  	}
  
  	FS_proto.abort = function() {
  		var filesaver = this;
  		filesaver.readyState = filesaver.DONE;
  		dispatch(filesaver, "abort");
  	};
  	FS_proto.readyState = FS_proto.INIT = 0;
  	FS_proto.WRITING = 1;
  	FS_proto.DONE = 2;
  
  	FS_proto.error =
  	FS_proto.onwritestart =
  	FS_proto.onprogress =
  	FS_proto.onwrite =
  	FS_proto.onabort =
  	FS_proto.onerror =
  	FS_proto.onwriteend =
  		null;
  
  	return saveAs;
  }(
  	   typeof self !== "undefined" && self
  	|| typeof window !== "undefined" && window
  	|| this.content
  ));
  // `self` is undefined in Firefox for Android content script context
  // while `this` is nsIContentFrameMessageManager
  // with an attribute `content` that corresponds to the window
  
  if (typeof module !== "undefined" && module.exports) {
    module.exports.saveAs = saveAs;
  } else if ((typeof define !== "undefined" && define !== null) && (define.amd != null)) {
    define([], function() {
      return saveAs;
    });
  }
  
  },{}],67:[function(require,module,exports){
  // Top level file is just a mixin of submodules & constants
  'use strict';
  
  var assign    = require('./lib/utils/common').assign;
  
  var deflate   = require('./lib/deflate');
  var inflate   = require('./lib/inflate');
  var constants = require('./lib/zlib/constants');
  
  var pako = {};
  
  assign(pako, deflate, inflate, constants);
  
  module.exports = pako;
  
  },{"./lib/deflate":68,"./lib/inflate":69,"./lib/utils/common":70,"./lib/zlib/constants":73}],68:[function(require,module,exports){
  'use strict';
  
  
  var zlib_deflate = require('./zlib/deflate');
  var utils        = require('./utils/common');
  var strings      = require('./utils/strings');
  var msg          = require('./zlib/messages');
  var ZStream      = require('./zlib/zstream');
  
  var toString = Object.prototype.toString;
  
  /* Public constants ==========================================================*/
  /* ===========================================================================*/
  
  var Z_NO_FLUSH      = 0;
  var Z_FINISH        = 4;
  
  var Z_OK            = 0;
  var Z_STREAM_END    = 1;
  var Z_SYNC_FLUSH    = 2;
  
  var Z_DEFAULT_COMPRESSION = -1;
  
  var Z_DEFAULT_STRATEGY    = 0;
  
  var Z_DEFLATED  = 8;
  
  /* ===========================================================================*/
  
  
  /**
   * 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 overriden.
   **/
  
  /**
   * Deflate.result -> Uint8Array|Array
   *
   * 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)  or if you
   * push a chunk with explicit flush (call [[Deflate#push]] with
   * `Z_SYNC_FLUSH` 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
   * - `to` (String) - if equal to 'string', then result will be "binary string"
   *    (each char code [0..255])
   * - `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
   * var pako = require('pako')
   *   , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
   *   , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
   *
   * var 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(options) {
    if (!(this instanceof Deflate)) return new Deflate(options);
  
    this.options = utils.assign({
      level: Z_DEFAULT_COMPRESSION,
      method: Z_DEFLATED,
      chunkSize: 16384,
      windowBits: 15,
      memLevel: 8,
      strategy: Z_DEFAULT_STRATEGY,
      to: ''
    }, options || {});
  
    var 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;
  
    var status = zlib_deflate.deflateInit2(
      this.strm,
      opt.level,
      opt.method,
      opt.windowBits,
      opt.memLevel,
      opt.strategy
    );
  
    if (status !== Z_OK) {
      throw new Error(msg[status]);
    }
  
    if (opt.header) {
      zlib_deflate.deflateSetHeader(this.strm, opt.header);
    }
  
    if (opt.dictionary) {
      var 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.call(opt.dictionary) === '[object ArrayBuffer]') {
        dict = new Uint8Array(opt.dictionary);
      } else {
        dict = opt.dictionary;
      }
  
      status = zlib_deflate.deflateSetDictionary(this.strm, dict);
  
      if (status !== Z_OK) {
        throw new Error(msg[status]);
      }
  
      this._dict_set = true;
    }
  }
  
  /**
   * Deflate#push(data[, mode]) -> Boolean
   * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
   *   converted to utf8 byte sequence.
   * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
   *   See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh 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
   * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
   * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
   * can use mode Z_SYNC_FLUSH, keeping the compression context.
   *
   * On fail call [[Deflate#onEnd]] with error code and return false.
   *
   * We strongly recommend to use `Uint8Array` on input for best speed (output
   * array format is detected automatically). Also, don't skip last param and always
   * use the same type in your code (boolean or number). That will improve JS speed.
   *
   * For regular `Array`-s make sure all elements are [0..255].
   *
   * ##### Example
   *
   * ```javascript
   * push(chunk, false); // push one of data chunks
   * ...
   * push(chunk, true);  // push last chunk
   * ```
   **/
  Deflate.prototype.push = function (data, mode) {
    var strm = this.strm;
    var chunkSize = this.options.chunkSize;
    var status, _mode;
  
    if (this.ended) { return false; }
  
    _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  
    // 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.call(data) === '[object ArrayBuffer]') {
      strm.input = new Uint8Array(data);
    } else {
      strm.input = data;
    }
  
    strm.next_in = 0;
    strm.avail_in = strm.input.length;
  
    do {
      if (strm.avail_out === 0) {
        strm.output = new utils.Buf8(chunkSize);
        strm.next_out = 0;
        strm.avail_out = chunkSize;
      }
      status = zlib_deflate.deflate(strm, _mode);    /* no bad return value */
  
      if (status !== Z_STREAM_END && status !== Z_OK) {
        this.onEnd(status);
        this.ended = true;
        return false;
      }
      if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
        if (this.options.to === 'string') {
          this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
        } else {
          this.onData(utils.shrinkBuf(strm.output, strm.next_out));
        }
      }
    } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  
    // Finalize on the last chunk.
    if (_mode === Z_FINISH) {
      status = zlib_deflate.deflateEnd(this.strm);
      this.onEnd(status);
      this.ended = true;
      return status === Z_OK;
    }
  
    // callback interim results if Z_SYNC_FLUSH.
    if (_mode === Z_SYNC_FLUSH) {
      this.onEnd(Z_OK);
      strm.avail_out = 0;
      return true;
    }
  
    return true;
  };
  
  
  /**
   * Deflate#onData(chunk) -> Void
   * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
   *   on js engine support. 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.
   **/
  Deflate.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) or should be flushed (Z_SYNC_FLUSH)
   * or if an error happened. By default - join collected chunks,
   * free memory and fill `results` / `err` properties.
   **/
  Deflate.prototype.onEnd = function (status) {
    // On success - join
    if (status === Z_OK) {
      if (this.options.to === 'string') {
        this.result = this.chunks.join('');
      } else {
        this.result = utils.flattenChunks(this.chunks);
      }
    }
    this.chunks = [];
    this.err = status;
    this.msg = this.strm.msg;
  };
  
  
  /**
   * deflate(data[, options]) -> Uint8Array|Array|String
   * - data (Uint8Array|Array|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.
   * - `to` (String) - if equal to 'string', then result will be "binary string"
   *    (each char code [0..255])
   *
   * ##### Example:
   *
   * ```javascript
   * var pako = require('pako')
   *   , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
   *
   * console.log(pako.deflate(data));
   * ```
   **/
  function deflate(input, options) {
    var deflator = new Deflate(options);
  
    deflator.push(input, true);
  
    // That will never happens, if you don't cheat with options :)
    if (deflator.err) { throw deflator.msg; }
  
    return deflator.result;
  }
  
  
  /**
   * deflateRaw(data[, options]) -> Uint8Array|Array|String
   * - data (Uint8Array|Array|String): input data to compress.
   * - options (Object): zlib deflate options.
   *
   * The same as [[deflate]], but creates raw data, without wrapper
   * (header and adler32 crc).
   **/
  function deflateRaw(input, options) {
    options = options || {};
    options.raw = true;
    return deflate(input, options);
  }
  
  
  /**
   * gzip(data[, options]) -> Uint8Array|Array|String
   * - data (Uint8Array|Array|String): input data to compress.
   * - options (Object): zlib deflate options.
   *
   * The same as [[deflate]], but create gzip wrapper instead of
   * deflate one.
   **/
  function gzip(input, options) {
    options = options || {};
    options.gzip = true;
    return deflate(input, options);
  }
  
  
  exports.Deflate = Deflate;
  exports.deflate = deflate;
  exports.deflateRaw = deflateRaw;
  exports.gzip = gzip;
  
  },{"./utils/common":70,"./utils/strings":71,"./zlib/deflate":75,"./zlib/messages":80,"./zlib/zstream":82}],69:[function(require,module,exports){
  'use strict';
  
  
  var zlib_inflate = require('./zlib/inflate');
  var utils        = require('./utils/common');
  var strings      = require('./utils/strings');
  var c            = require('./zlib/constants');
  var msg          = require('./zlib/messages');
  var ZStream      = require('./zlib/zstream');
  var GZheader     = require('./zlib/gzheader');
  
  var toString = Object.prototype.toString;
  
  /**
   * 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 overriden.
   **/
  
  /**
   * Inflate.result -> Uint8Array|Array|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) or if you
   * push a chunk with explicit flush (call [[Inflate#push]] with
   * `Z_SYNC_FLUSH` 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
   * var pako = require('pako')
   *   , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
   *   , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
   *
   * var 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(options) {
    if (!(this instanceof Inflate)) return new Inflate(options);
  
    this.options = utils.assign({
      chunkSize: 16384,
      windowBits: 0,
      to: ''
    }, options || {});
  
    var 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;
  
    var status  = zlib_inflate.inflateInit2(
      this.strm,
      opt.windowBits
    );
  
    if (status !== c.Z_OK) {
      throw new Error(msg[status]);
    }
  
    this.header = new GZheader();
  
    zlib_inflate.inflateGetHeader(this.strm, this.header);
  }
  
  /**
   * Inflate#push(data[, mode]) -> Boolean
   * - data (Uint8Array|Array|ArrayBuffer|String): input data
   * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
   *   See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
   *
   * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
   * new output chunks. Returns `true` on success. The last data block must have
   * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
   * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
   * can use mode Z_SYNC_FLUSH, keeping the decompression context.
   *
   * On fail call [[Inflate#onEnd]] with error code and return false.
   *
   * We strongly recommend to use `Uint8Array` on input for best speed (output
   * format is detected automatically). Also, don't skip last param and always
   * use the same type in your code (boolean or number). That will improve JS speed.
   *
   * For regular `Array`-s make sure all elements are [0..255].
   *
   * ##### Example
   *
   * ```javascript
   * push(chunk, false); // push one of data chunks
   * ...
   * push(chunk, true);  // push last chunk
   * ```
   **/
  Inflate.prototype.push = function (data, mode) {
    var strm = this.strm;
    var chunkSize = this.options.chunkSize;
    var dictionary = this.options.dictionary;
    var status, _mode;
    var next_out_utf8, tail, utf8str;
    var dict;
  
    // Flag to properly process Z_BUF_ERROR on testing inflate call
    // when we check that all output data was flushed.
    var allowBufError = false;
  
    if (this.ended) { return false; }
    _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  
    // Convert data if needed
    if (typeof data === 'string') {
      // Only binary strings can be decompressed on practice
      strm.input = strings.binstring2buf(data);
    } else if (toString.call(data) === '[object ArrayBuffer]') {
      strm.input = new Uint8Array(data);
    } else {
      strm.input = data;
    }
  
    strm.next_in = 0;
    strm.avail_in = strm.input.length;
  
    do {
      if (strm.avail_out === 0) {
        strm.output = new utils.Buf8(chunkSize);
        strm.next_out = 0;
        strm.avail_out = chunkSize;
      }
  
      status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH);    /* no bad return value */
  
      if (status === c.Z_NEED_DICT && dictionary) {
        // Convert data if needed
        if (typeof dictionary === 'string') {
          dict = strings.string2buf(dictionary);
        } else if (toString.call(dictionary) === '[object ArrayBuffer]') {
          dict = new Uint8Array(dictionary);
        } else {
          dict = dictionary;
        }
  
        status = zlib_inflate.inflateSetDictionary(this.strm, dict);
  
      }
  
      if (status === c.Z_BUF_ERROR && allowBufError === true) {
        status = c.Z_OK;
        allowBufError = false;
      }
  
      if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
        this.onEnd(status);
        this.ended = true;
        return false;
      }
  
      if (strm.next_out) {
        if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  
          if (this.options.to === 'string') {
  
            next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  
            tail = strm.next_out - next_out_utf8;
            utf8str = strings.buf2string(strm.output, next_out_utf8);
  
            // move tail
            strm.next_out = tail;
            strm.avail_out = chunkSize - tail;
            if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  
            this.onData(utf8str);
  
          } else {
            this.onData(utils.shrinkBuf(strm.output, strm.next_out));
          }
        }
      }
  
      // When no more input data, we should check that internal inflate buffers
      // are flushed. The only way to do it when avail_out = 0 - run one more
      // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
      // Here we set flag to process this error properly.
      //
      // NOTE. Deflate does not return error in this case and does not needs such
      // logic.
      if (strm.avail_in === 0 && strm.avail_out === 0) {
        allowBufError = true;
      }
  
    } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  
    if (status === c.Z_STREAM_END) {
      _mode = c.Z_FINISH;
    }
  
    // Finalize on the last chunk.
    if (_mode === c.Z_FINISH) {
      status = zlib_inflate.inflateEnd(this.strm);
      this.onEnd(status);
      this.ended = true;
      return status === c.Z_OK;
    }
  
    // callback interim results if Z_SYNC_FLUSH.
    if (_mode === c.Z_SYNC_FLUSH) {
      this.onEnd(c.Z_OK);
      strm.avail_out = 0;
      return true;
    }
  
    return true;
  };
  
  
  /**
   * Inflate#onData(chunk) -> Void
   * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
   *   on js engine support. 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.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) or should be flushed (Z_SYNC_FLUSH)
   * or if an error happened. By default - join collected chunks,
   * free memory and fill `results` / `err` properties.
   **/
  Inflate.prototype.onEnd = function (status) {
    // On success - join
    if (status === c.Z_OK) {
      if (this.options.to === 'string') {
        // Glue & convert here, until we teach pako to send
        // utf8 alligned strings to onData
        this.result = this.chunks.join('');
      } else {
        this.result = utils.flattenChunks(this.chunks);
      }
    }
    this.chunks = [];
    this.err = status;
    this.msg = this.strm.msg;
  };
  
  
  /**
   * inflate(data[, options]) -> Uint8Array|Array|String
   * - data (Uint8Array|Array|String): 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
   * var pako = require('pako')
   *   , input = pako.deflate([1,2,3,4,5,6,7,8,9])
   *   , output;
   *
   * try {
   *   output = pako.inflate(input);
   * } catch (err)
   *   console.log(err);
   * }
   * ```
   **/
  function inflate(input, options) {
    var inflator = new Inflate(options);
  
    inflator.push(input, true);
  
    // That will never happens, if you don't cheat with options :)
    if (inflator.err) { throw inflator.msg; }
  
    return inflator.result;
  }
  
  
  /**
   * inflateRaw(data[, options]) -> Uint8Array|Array|String
   * - data (Uint8Array|Array|String): input data to decompress.
   * - options (Object): zlib inflate options.
   *
   * The same as [[inflate]], but creates raw data, without wrapper
   * (header and adler32 crc).
   **/
  function inflateRaw(input, options) {
    options = options || {};
    options.raw = true;
    return inflate(input, options);
  }
  
  
  /**
   * ungzip(data[, options]) -> Uint8Array|Array|String
   * - data (Uint8Array|Array|String): input data to decompress.
   * - options (Object): zlib inflate options.
   *
   * Just shortcut to [[inflate]], because it autodetects format
   * by header.content. Done for convenience.
   **/
  
  
  exports.Inflate = Inflate;
  exports.inflate = inflate;
  exports.inflateRaw = inflateRaw;
  exports.ungzip  = inflate;
  
  },{"./utils/common":70,"./utils/strings":71,"./zlib/constants":73,"./zlib/gzheader":76,"./zlib/inflate":78,"./zlib/messages":80,"./zlib/zstream":82}],70:[function(require,module,exports){
  'use strict';
  
  
  var TYPED_OK =  (typeof Uint8Array !== 'undefined') &&
                  (typeof Uint16Array !== 'undefined') &&
                  (typeof Int32Array !== 'undefined');
  
  
  exports.assign = function (obj /*from1, from2, from3, ...*/) {
    var sources = Array.prototype.slice.call(arguments, 1);
    while (sources.length) {
      var source = sources.shift();
      if (!source) { continue; }
  
      if (typeof source !== 'object') {
        throw new TypeError(source + 'must be non-object');
      }
  
      for (var p in source) {
        if (source.hasOwnProperty(p)) {
          obj[p] = source[p];
        }
      }
    }
  
    return obj;
  };
  
  
  // reduce buffer size, avoiding mem copy
  exports.shrinkBuf = function (buf, size) {
    if (buf.length === size) { return buf; }
    if (buf.subarray) { return buf.subarray(0, size); }
    buf.length = size;
    return buf;
  };
  
  
  var fnTyped = {
    arraySet: function (dest, src, src_offs, len, dest_offs) {
      if (src.subarray && dest.subarray) {
        dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
        return;
      }
      // Fallback to ordinary array
      for (var i = 0; i < len; i++) {
        dest[dest_offs + i] = src[src_offs + i];
      }
    },
    // Join array of chunks to single array.
    flattenChunks: function (chunks) {
      var i, l, len, pos, chunk, result;
  
      // calculate data length
      len = 0;
      for (i = 0, l = chunks.length; i < l; i++) {
        len += chunks[i].length;
      }
  
      // join chunks
      result = new Uint8Array(len);
      pos = 0;
      for (i = 0, l = chunks.length; i < l; i++) {
        chunk = chunks[i];
        result.set(chunk, pos);
        pos += chunk.length;
      }
  
      return result;
    }
  };
  
  var fnUntyped = {
    arraySet: function (dest, src, src_offs, len, dest_offs) {
      for (var i = 0; i < len; i++) {
        dest[dest_offs + i] = src[src_offs + i];
      }
    },
    // Join array of chunks to single array.
    flattenChunks: function (chunks) {
      return [].concat.apply([], chunks);
    }
  };
  
  
  // Enable/Disable typed arrays use, for testing
  //
  exports.setTyped = function (on) {
    if (on) {
      exports.Buf8  = Uint8Array;
      exports.Buf16 = Uint16Array;
      exports.Buf32 = Int32Array;
      exports.assign(exports, fnTyped);
    } else {
      exports.Buf8  = Array;
      exports.Buf16 = Array;
      exports.Buf32 = Array;
      exports.assign(exports, fnUntyped);
    }
  };
  
  exports.setTyped(TYPED_OK);
  
  },{}],71:[function(require,module,exports){
  // String encode/decode helpers
  'use strict';
  
  
  var utils = require('./common');
  
  
  // 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 Safary
  //
  var STR_APPLY_OK = true;
  var STR_APPLY_UIA_OK = true;
  
  try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }
  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
  var _utf8len = new utils.Buf8(256);
  for (var 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)
  exports.string2buf = function (str) {
    var 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 utils.Buf8(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 (used in 2 places)
  function buf2binstring(buf, len) {
    // use fallback for big arrays to avoid stack overflow
    if (len < 65537) {
      if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
        return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
      }
    }
  
    var result = '';
    for (var i = 0; i < len; i++) {
      result += String.fromCharCode(buf[i]);
    }
    return result;
  }
  
  
  // Convert byte array to binary string
  exports.buf2binstring = function (buf) {
    return buf2binstring(buf, buf.length);
  };
  
  
  // Convert binary string (typed, when possible)
  exports.binstring2buf = function (str) {
    var buf = new utils.Buf8(str.length);
    for (var i = 0, len = buf.length; i < len; i++) {
      buf[i] = str.charCodeAt(i);
    }
    return buf;
  };
  
  
  // convert array to string
  exports.buf2string = function (buf, max) {
    var i, out, c, c_len;
    var len = max || buf.length;
  
    // Reserve max possible length (2 words per char)
    // NB: by unknown reasons, Array is significantly faster for
    //     String.fromCharCode.apply than Uint16Array.
    var utf16buf = new Array(len * 2);
  
    for (out = 0, i = 0; i < len;) {
      c = buf[i++];
      // quick process ascii
      if (c < 0x80) { utf16buf[out++] = c; continue; }
  
      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);
  exports.utf8border = function (buf, max) {
    var pos;
  
    max = max || buf.length;
    if (max > buf.length) { max = buf.length; }
  
    // go back from last position, until start of sequence found
    pos = max - 1;
    while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  
    // Fuckup - 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 vuffer is too small,
    // return max too.
    if (pos === 0) { return max; }
  
    return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  };
  
  },{"./common":70}],72:[function(require,module,exports){
  'use strict';
  
  // Note: adler32 takes 12% for level 0 and 2% for level 6.
  // It doesn't worth to make additional optimizationa as in original.
  // Small size is preferable.
  
  function adler32(adler, buf, len, pos) {
    var s1 = (adler & 0xffff) |0,
        s2 = ((adler >>> 16) & 0xffff) |0,
        n = 0;
  
    while (len !== 0) {
      // Set limit ~ twice less than 5552, to keep
      // s2 in 31-bits, because we force signed ints.
      // in other case %= will fail.
      n = len > 2000 ? 2000 : len;
      len -= n;
  
      do {
        s1 = (s1 + buf[pos++]) |0;
        s2 = (s2 + s1) |0;
      } while (--n);
  
      s1 %= 65521;
      s2 %= 65521;
    }
  
    return (s1 | (s2 << 16)) |0;
  }
  
  
  module.exports = adler32;
  
  },{}],73:[function(require,module,exports){
  'use strict';
  
  
  module.exports = {
  
    /* Allowed flush values; see deflate() and inflate() below for details */
    Z_NO_FLUSH:         0,
    Z_PARTIAL_FLUSH:    1,
    Z_SYNC_FLUSH:       2,
    Z_FULL_FLUSH:       3,
    Z_FINISH:           4,
    Z_BLOCK:            5,
    Z_TREES:            6,
  
    /* Return codes for the compression/decompression functions. Negative values
    * are errors, positive values are used for special but normal events.
    */
    Z_OK:               0,
    Z_STREAM_END:       1,
    Z_NEED_DICT:        2,
    Z_ERRNO:           -1,
    Z_STREAM_ERROR:    -2,
    Z_DATA_ERROR:      -3,
    //Z_MEM_ERROR:     -4,
    Z_BUF_ERROR:       -5,
    //Z_VERSION_ERROR: -6,
  
    /* compression levels */
    Z_NO_COMPRESSION:         0,
    Z_BEST_SPEED:             1,
    Z_BEST_COMPRESSION:       9,
    Z_DEFAULT_COMPRESSION:   -1,
  
  
    Z_FILTERED:               1,
    Z_HUFFMAN_ONLY:           2,
    Z_RLE:                    3,
    Z_FIXED:                  4,
    Z_DEFAULT_STRATEGY:       0,
  
    /* Possible values of the data_type field (though see inflate()) */
    Z_BINARY:                 0,
    Z_TEXT:                   1,
    //Z_ASCII:                1, // = Z_TEXT (deprecated)
    Z_UNKNOWN:                2,
  
    /* The deflate compression method */
    Z_DEFLATED:               8
    //Z_NULL:                 null // Use -1 or null inline, depending on var type
  };
  
  },{}],74:[function(require,module,exports){
  'use strict';
  
  // Note: we can't get significant speed boost here.
  // So write code to minimize size - no pregenerated tables
  // and array tools dependencies.
  
  
  // Use ordinary array, since untyped makes no boost here
  function makeTable() {
    var c, table = [];
  
    for (var n = 0; n < 256; n++) {
      c = n;
      for (var k = 0; k < 8; k++) {
        c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
      }
      table[n] = c;
    }
  
    return table;
  }
  
  // Create table on load. Just 255 signed longs. Not a problem.
  var crcTable = makeTable();
  
  
  function crc32(crc, buf, len, pos) {
    var t = crcTable,
        end = pos + len;
  
    crc ^= -1;
  
    for (var i = pos; i < end; i++) {
      crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
    }
  
    return (crc ^ (-1)); // >>> 0;
  }
  
  
  module.exports = crc32;
  
  },{}],75:[function(require,module,exports){
  'use strict';
  
  var utils   = require('../utils/common');
  var trees   = require('./trees');
  var adler32 = require('./adler32');
  var crc32   = require('./crc32');
  var msg     = require('./messages');
  
  /* Public constants ==========================================================*/
  /* ===========================================================================*/
  
  
  /* Allowed flush values; see deflate() and inflate() below for details */
  var Z_NO_FLUSH      = 0;
  var Z_PARTIAL_FLUSH = 1;
  //var Z_SYNC_FLUSH    = 2;
  var Z_FULL_FLUSH    = 3;
  var Z_FINISH        = 4;
  var Z_BLOCK         = 5;
  //var Z_TREES         = 6;
  
  
  /* Return codes for the compression/decompression functions. Negative values
   * are errors, positive values are used for special but normal events.
   */
  var Z_OK            = 0;
  var Z_STREAM_END    = 1;
  //var Z_NEED_DICT     = 2;
  //var Z_ERRNO         = -1;
  var Z_STREAM_ERROR  = -2;
  var Z_DATA_ERROR    = -3;
  //var Z_MEM_ERROR     = -4;
  var Z_BUF_ERROR     = -5;
  //var Z_VERSION_ERROR = -6;
  
  
  /* compression levels */
  //var Z_NO_COMPRESSION      = 0;
  //var Z_BEST_SPEED          = 1;
  //var Z_BEST_COMPRESSION    = 9;
  var Z_DEFAULT_COMPRESSION = -1;
  
  
  var Z_FILTERED            = 1;
  var Z_HUFFMAN_ONLY        = 2;
  var Z_RLE                 = 3;
  var Z_FIXED               = 4;
  var Z_DEFAULT_STRATEGY    = 0;
  
  /* Possible values of the data_type field (though see inflate()) */
  //var Z_BINARY              = 0;
  //var Z_TEXT                = 1;
  //var Z_ASCII               = 1; // = Z_TEXT
  var Z_UNKNOWN             = 2;
  
  
  /* The deflate compression method */
  var Z_DEFLATED  = 8;
  
  /*============================================================================*/
  
  
  var MAX_MEM_LEVEL = 9;
  /* Maximum value for memLevel in deflateInit2 */
  var MAX_WBITS = 15;
  /* 32K LZ77 window */
  var DEF_MEM_LEVEL = 8;
  
  
  var LENGTH_CODES  = 29;
  /* number of length codes, not counting the special END_BLOCK code */
  var LITERALS      = 256;
  /* number of literal bytes 0..255 */
  var L_CODES       = LITERALS + 1 + LENGTH_CODES;
  /* number of Literal or Length codes, including the END_BLOCK code */
  var D_CODES       = 30;
  /* number of distance codes */
  var BL_CODES      = 19;
  /* number of codes used to transfer the bit lengths */
  var HEAP_SIZE     = 2 * L_CODES + 1;
  /* maximum heap size */
  var MAX_BITS  = 15;
  /* All codes must not exceed MAX_BITS bits */
  
  var MIN_MATCH = 3;
  var MAX_MATCH = 258;
  var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  
  var PRESET_DICT = 0x20;
  
  var INIT_STATE = 42;
  var EXTRA_STATE = 69;
  var NAME_STATE = 73;
  var COMMENT_STATE = 91;
  var HCRC_STATE = 103;
  var BUSY_STATE = 113;
  var FINISH_STATE = 666;
  
  var BS_NEED_MORE      = 1; /* block not completed, need more input or more output */
  var BS_BLOCK_DONE     = 2; /* block flush performed */
  var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  var BS_FINISH_DONE    = 4; /* finish done, accept no more input or output */
  
  var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  
  function err(strm, errorCode) {
    strm.msg = msg[errorCode];
    return errorCode;
  }
  
  function rank(f) {
    return ((f) << 1) - ((f) > 4 ? 9 : 0);
  }
  
  function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  
  
  /* =========================================================================
   * Flush as much pending output as possible. All deflate() output goes
   * through this function so some applications may wish to modify it
   * to avoid allocating a large strm->output buffer and copying into it.
   * (See also read_buf()).
   */
  function flush_pending(strm) {
    var s = strm.state;
  
    //_tr_flush_bits(s);
    var len = s.pending;
    if (len > strm.avail_out) {
      len = strm.avail_out;
    }
    if (len === 0) { return; }
  
    utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
    strm.next_out += len;
    s.pending_out += len;
    strm.total_out += len;
    strm.avail_out -= len;
    s.pending -= len;
    if (s.pending === 0) {
      s.pending_out = 0;
    }
  }
  
  
  function flush_block_only(s, last) {
    trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
    s.block_start = s.strstart;
    flush_pending(s.strm);
  }
  
  
  function put_byte(s, b) {
    s.pending_buf[s.pending++] = b;
  }
  
  
  /* =========================================================================
   * Put a short in the pending buffer. The 16-bit value is put in MSB order.
   * IN assertion: the stream state is correct and there is enough room in
   * pending_buf.
   */
  function putShortMSB(s, b) {
  //  put_byte(s, (Byte)(b >> 8));
  //  put_byte(s, (Byte)(b & 0xff));
    s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
    s.pending_buf[s.pending++] = b & 0xff;
  }
  
  
  /* ===========================================================================
   * Read a new buffer from the current input stream, update the adler32
   * and total number of bytes read.  All deflate() input goes through
   * this function so some applications may wish to modify it to avoid
   * allocating a large strm->input buffer and copying from it.
   * (See also flush_pending()).
   */
  function read_buf(strm, buf, start, size) {
    var len = strm.avail_in;
  
    if (len > size) { len = size; }
    if (len === 0) { return 0; }
  
    strm.avail_in -= len;
  
    // zmemcpy(buf, strm->next_in, len);
    utils.arraySet(buf, strm.input, strm.next_in, len, start);
    if (strm.state.wrap === 1) {
      strm.adler = adler32(strm.adler, buf, len, start);
    }
  
    else if (strm.state.wrap === 2) {
      strm.adler = crc32(strm.adler, buf, len, start);
    }
  
    strm.next_in += len;
    strm.total_in += len;
  
    return len;
  }
  
  
  /* ===========================================================================
   * Set match_start to the longest match starting at the given string and
   * return its length. Matches shorter or equal to prev_length are discarded,
   * in which case the result is equal to prev_length and match_start is
   * garbage.
   * IN assertions: cur_match is the head of the hash chain for the current
   *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
   * OUT assertion: the match length is not greater than s->lookahead.
   */
  function longest_match(s, cur_match) {
    var chain_length = s.max_chain_length;      /* max hash chain length */
    var scan = s.strstart; /* current string */
    var match;                       /* matched string */
    var len;                           /* length of current match */
    var best_len = s.prev_length;              /* best match length so far */
    var nice_match = s.nice_match;             /* stop if match long enough */
    var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
        s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  
    var _win = s.window; // shortcut
  
    var wmask = s.w_mask;
    var prev  = s.prev;
  
    /* Stop when cur_match becomes <= limit. To simplify the code,
     * we prevent matches with the string of window index 0.
     */
  
    var strend = s.strstart + MAX_MATCH;
    var scan_end1  = _win[scan + best_len - 1];
    var scan_end   = _win[scan + best_len];
  
    /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
     * It is easy to get rid of this optimization if necessary.
     */
    // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  
    /* Do not waste too much time if we already have a good match: */
    if (s.prev_length >= s.good_match) {
      chain_length >>= 2;
    }
    /* Do not look for matches beyond the end of the input. This is necessary
     * to make deflate deterministic.
     */
    if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  
    // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  
    do {
      // Assert(cur_match < s->strstart, "no future");
      match = cur_match;
  
      /* Skip to next match if the match length cannot increase
       * or if the match length is less than 2.  Note that the checks below
       * for insufficient lookahead only occur occasionally for performance
       * reasons.  Therefore uninitialized memory will be accessed, and
       * conditional jumps will be made that depend on those values.
       * However the length of the match is limited to the lookahead, so
       * the output of deflate is not affected by the uninitialized values.
       */
  
      if (_win[match + best_len]     !== scan_end  ||
          _win[match + best_len - 1] !== scan_end1 ||
          _win[match]                !== _win[scan] ||
          _win[++match]              !== _win[scan + 1]) {
        continue;
      }
  
      /* The check at best_len-1 can be removed because it will be made
       * again later. (This heuristic is not always a win.)
       * It is not necessary to compare scan[2] and match[2] since they
       * are always equal when the other bytes match, given that
       * the hash keys are equal and that HASH_BITS >= 8.
       */
      scan += 2;
      match++;
      // Assert(*scan == *match, "match[2]?");
  
      /* We check for insufficient lookahead only every 8th comparison;
       * the 256th check will be made at strstart+258.
       */
      do {
        /*jshint noempty:false*/
      } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
               _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
               _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
               _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
               scan < strend);
  
      // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  
      len = MAX_MATCH - (strend - scan);
      scan = strend - MAX_MATCH;
  
      if (len > best_len) {
        s.match_start = cur_match;
        best_len = len;
        if (len >= nice_match) {
          break;
        }
        scan_end1  = _win[scan + best_len - 1];
        scan_end   = _win[scan + best_len];
      }
    } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  
    if (best_len <= s.lookahead) {
      return best_len;
    }
    return s.lookahead;
  }
  
  
  /* ===========================================================================
   * Fill the window when the lookahead becomes insufficient.
   * Updates strstart and lookahead.
   *
   * IN assertion: lookahead < MIN_LOOKAHEAD
   * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
   *    At least one byte has been read, or avail_in == 0; reads are
   *    performed for at least two bytes (required for the zip translate_eol
   *    option -- not supported here).
   */
  function fill_window(s) {
    var _w_size = s.w_size;
    var p, n, m, more, str;
  
    //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  
    do {
      more = s.window_size - s.lookahead - s.strstart;
  
      // JS ints have 32 bit, block below not needed
      /* Deal with !@#$% 64K limit: */
      //if (sizeof(int) <= 2) {
      //    if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
      //        more = wsize;
      //
      //  } else if (more == (unsigned)(-1)) {
      //        /* Very unlikely, but possible on 16 bit machine if
      //         * strstart == 0 && lookahead == 1 (input done a byte at time)
      //         */
      //        more--;
      //    }
      //}
  
  
      /* If the window is almost full and there is insufficient lookahead,
       * move the upper half to the lower one to make room in the upper half.
       */
      if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  
        utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
        s.match_start -= _w_size;
        s.strstart -= _w_size;
        /* we now have strstart >= MAX_DIST */
        s.block_start -= _w_size;
  
        /* Slide the hash table (could be avoided with 32 bit values
         at the expense of memory usage). We slide even when level == 0
         to keep the hash table consistent if we switch back to level > 0
         later. (Using level 0 permanently is not an optimal usage of
         zlib, so we don't care about this pathological case.)
         */
  
        n = s.hash_size;
        p = n;
        do {
          m = s.head[--p];
          s.head[p] = (m >= _w_size ? m - _w_size : 0);
        } while (--n);
  
        n = _w_size;
        p = n;
        do {
          m = s.prev[--p];
          s.prev[p] = (m >= _w_size ? m - _w_size : 0);
          /* If n is not on any hash chain, prev[n] is garbage but
           * its value will never be used.
           */
        } while (--n);
  
        more += _w_size;
      }
      if (s.strm.avail_in === 0) {
        break;
      }
  
      /* If there was no sliding:
       *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
       *    more == window_size - lookahead - strstart
       * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
       * => more >= window_size - 2*WSIZE + 2
       * In the BIG_MEM or MMAP case (not yet supported),
       *   window_size == input_size + MIN_LOOKAHEAD  &&
       *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
       * Otherwise, window_size == 2*WSIZE so more >= 2.
       * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
       */
      //Assert(more >= 2, "more < 2");
      n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
      s.lookahead += n;
  
      /* Initialize the hash value now that we have some input: */
      if (s.lookahead + s.insert >= MIN_MATCH) {
        str = s.strstart - s.insert;
        s.ins_h = s.window[str];
  
        /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
        s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  //#if MIN_MATCH != 3
  //        Call update_hash() MIN_MATCH-3 more times
  //#endif
        while (s.insert) {
          /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
          s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  
          s.prev[str & s.w_mask] = s.head[s.ins_h];
          s.head[s.ins_h] = str;
          str++;
          s.insert--;
          if (s.lookahead + s.insert < MIN_MATCH) {
            break;
          }
        }
      }
      /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
       * but this is not important since only literal bytes will be emitted.
       */
  
    } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  
    /* If the WIN_INIT bytes after the end of the current data have never been
     * written, then zero those bytes in order to avoid memory check reports of
     * the use of uninitialized (or uninitialised as Julian writes) bytes by
     * the longest match routines.  Update the high water mark for the next
     * time through here.  WIN_INIT is set to MAX_MATCH since the longest match
     * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
     */
  //  if (s.high_water < s.window_size) {
  //    var curr = s.strstart + s.lookahead;
  //    var init = 0;
  //
  //    if (s.high_water < curr) {
  //      /* Previous high water mark below current data -- zero WIN_INIT
  //       * bytes or up to end of window, whichever is less.
  //       */
  //      init = s.window_size - curr;
  //      if (init > WIN_INIT)
  //        init = WIN_INIT;
  //      zmemzero(s->window + curr, (unsigned)init);
  //      s->high_water = curr + init;
  //    }
  //    else if (s->high_water < (ulg)curr + WIN_INIT) {
  //      /* High water mark at or above current data, but below current data
  //       * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  //       * to end of window, whichever is less.
  //       */
  //      init = (ulg)curr + WIN_INIT - s->high_water;
  //      if (init > s->window_size - s->high_water)
  //        init = s->window_size - s->high_water;
  //      zmemzero(s->window + s->high_water, (unsigned)init);
  //      s->high_water += init;
  //    }
  //  }
  //
  //  Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  //    "not enough room for search");
  }
  
  /* ===========================================================================
   * Copy without compression as much as possible from the input stream, return
   * the current block state.
   * This function does not insert new strings in the dictionary since
   * uncompressible data is probably not useful. This function is used
   * only for the level=0 compression option.
   * NOTE: this function should be optimized to avoid extra copying from
   * window to pending_buf.
   */
  function deflate_stored(s, flush) {
    /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
     * to pending_buf_size, and each stored block has a 5 byte header:
     */
    var max_block_size = 0xffff;
  
    if (max_block_size > s.pending_buf_size - 5) {
      max_block_size = s.pending_buf_size - 5;
    }
  
    /* Copy as much as possible from input to output: */
    for (;;) {
      /* Fill the window as much as possible: */
      if (s.lookahead <= 1) {
  
        //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
        //  s->block_start >= (long)s->w_size, "slide too late");
  //      if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  //        s.block_start >= s.w_size)) {
  //        throw  new Error("slide too late");
  //      }
  
        fill_window(s);
        if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
          return BS_NEED_MORE;
        }
  
        if (s.lookahead === 0) {
          break;
        }
        /* flush the current block */
      }
      //Assert(s->block_start >= 0L, "block gone");
  //    if (s.block_start < 0) throw new Error("block gone");
  
      s.strstart += s.lookahead;
      s.lookahead = 0;
  
      /* Emit a stored block if pending_buf will be full: */
      var max_start = s.block_start + max_block_size;
  
      if (s.strstart === 0 || s.strstart >= max_start) {
        /* strstart == 0 is possible when wraparound on 16-bit machine */
        s.lookahead = s.strstart - max_start;
        s.strstart = max_start;
        /*** FLUSH_BLOCK(s, 0); ***/
        flush_block_only(s, false);
        if (s.strm.avail_out === 0) {
          return BS_NEED_MORE;
        }
        /***/
  
  
      }
      /* Flush if we may have to slide, otherwise block_start may become
       * negative and the data will be gone:
       */
      if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
        /*** FLUSH_BLOCK(s, 0); ***/
        flush_block_only(s, false);
        if (s.strm.avail_out === 0) {
          return BS_NEED_MORE;
        }
        /***/
      }
    }
  
    s.insert = 0;
  
    if (flush === Z_FINISH) {
      /*** FLUSH_BLOCK(s, 1); ***/
      flush_block_only(s, true);
      if (s.strm.avail_out === 0) {
        return BS_FINISH_STARTED;
      }
      /***/
      return BS_FINISH_DONE;
    }
  
    if (s.strstart > s.block_start) {
      /*** FLUSH_BLOCK(s, 0); ***/
      flush_block_only(s, false);
      if (s.strm.avail_out === 0) {
        return BS_NEED_MORE;
      }
      /***/
    }
  
    return BS_NEED_MORE;
  }
  
  /* ===========================================================================
   * Compress as much as possible from the input stream, return the current
   * block state.
   * This function does not perform lazy evaluation of matches and inserts
   * new strings in the dictionary only for unmatched strings or for short
   * matches. It is used only for the fast compression options.
   */
  function deflate_fast(s, flush) {
    var hash_head;        /* head of the hash chain */
    var bflush;           /* set if current block must be flushed */
  
    for (;;) {
      /* Make sure that we always have enough lookahead, except
       * at the end of the input file. We need MAX_MATCH bytes
       * for the next match, plus MIN_MATCH bytes to insert the
       * string following the next match.
       */
      if (s.lookahead < MIN_LOOKAHEAD) {
        fill_window(s);
        if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
          return BS_NEED_MORE;
        }
        if (s.lookahead === 0) {
          break; /* flush the current block */
        }
      }
  
      /* Insert the string window[strstart .. strstart+2] in the
       * dictionary, and set hash_head to the head of the hash chain:
       */
      hash_head = 0/*NIL*/;
      if (s.lookahead >= MIN_MATCH) {
        /*** INSERT_STRING(s, s.strstart, hash_head); ***/
        s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
        hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
        s.head[s.ins_h] = s.strstart;
        /***/
      }
  
      /* Find the longest match, discarding those <= prev_length.
       * At this point we have always match_length < MIN_MATCH
       */
      if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
        /* To simplify the code, we prevent matches with the string
         * of window index 0 (in particular we have to avoid a match
         * of the string with itself at the start of the input file).
         */
        s.match_length = longest_match(s, hash_head);
        /* longest_match() sets match_start */
      }
      if (s.match_length >= MIN_MATCH) {
        // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  
        /*** _tr_tally_dist(s, s.strstart - s.match_start,
                       s.match_length - MIN_MATCH, bflush); ***/
        bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  
        s.lookahead -= s.match_length;
  
        /* Insert new strings in the hash table only if the match length
         * is not too large. This saves time but degrades compression.
         */
        if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
          s.match_length--; /* string at strstart already in table */
          do {
            s.strstart++;
            /*** INSERT_STRING(s, s.strstart, hash_head); ***/
            s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
            hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
            s.head[s.ins_h] = s.strstart;
            /***/
            /* strstart never exceeds WSIZE-MAX_MATCH, so there are
             * always MIN_MATCH bytes ahead.
             */
          } while (--s.match_length !== 0);
          s.strstart++;
        } else
        {
          s.strstart += s.match_length;
          s.match_length = 0;
          s.ins_h = s.window[s.strstart];
          /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
          s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  
  //#if MIN_MATCH != 3
  //                Call UPDATE_HASH() MIN_MATCH-3 more times
  //#endif
          /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
           * matter since it will be recomputed at next deflate call.
           */
        }
      } else {
        /* No match, output a literal byte */
        //Tracevv((stderr,"%c", s.window[s.strstart]));
        /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
        bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  
        s.lookahead--;
        s.strstart++;
      }
      if (bflush) {
        /*** FLUSH_BLOCK(s, 0); ***/
        flush_block_only(s, false);
        if (s.strm.avail_out === 0) {
          return BS_NEED_MORE;
        }
        /***/
      }
    }
    s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
    if (flush === Z_FINISH) {
      /*** FLUSH_BLOCK(s, 1); ***/
      flush_block_only(s, true);
      if (s.strm.avail_out === 0) {
        return BS_FINISH_STARTED;
      }
      /***/
      return BS_FINISH_DONE;
    }
    if (s.last_lit) {
      /*** FLUSH_BLOCK(s, 0); ***/
      flush_block_only(s, false);
      if (s.strm.avail_out === 0) {
        return BS_NEED_MORE;
      }
      /***/
    }
    return BS_BLOCK_DONE;
  }
  
  /* ===========================================================================
   * Same as above, but achieves better compression. We use a lazy
   * evaluation for matches: a match is finally adopted only if there is
   * no better match at the next window position.
   */
  function deflate_slow(s, flush) {
    var hash_head;          /* head of hash chain */
    var bflush;              /* set if current block must be flushed */
  
    var max_insert;
  
    /* Process the input block. */
    for (;;) {
      /* Make sure that we always have enough lookahead, except
       * at the end of the input file. We need MAX_MATCH bytes
       * for the next match, plus MIN_MATCH bytes to insert the
       * string following the next match.
       */
      if (s.lookahead < MIN_LOOKAHEAD) {
        fill_window(s);
        if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
          return BS_NEED_MORE;
        }
        if (s.lookahead === 0) { break; } /* flush the current block */
      }
  
      /* Insert the string window[strstart .. strstart+2] in the
       * dictionary, and set hash_head to the head of the hash chain:
       */
      hash_head = 0/*NIL*/;
      if (s.lookahead >= MIN_MATCH) {
        /*** INSERT_STRING(s, s.strstart, hash_head); ***/
        s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
        hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
        s.head[s.ins_h] = s.strstart;
        /***/
      }
  
      /* Find the longest match, discarding those <= prev_length.
       */
      s.prev_length = s.match_length;
      s.prev_match = s.match_start;
      s.match_length = MIN_MATCH - 1;
  
      if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
          s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
        /* To simplify the code, we prevent matches with the string
         * of window index 0 (in particular we have to avoid a match
         * of the string with itself at the start of the input file).
         */
        s.match_length = longest_match(s, hash_head);
        /* longest_match() sets match_start */
  
        if (s.match_length <= 5 &&
           (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  
          /* If prev_match is also MIN_MATCH, match_start is garbage
           * but we will ignore the current match anyway.
           */
          s.match_length = MIN_MATCH - 1;
        }
      }
      /* If there was a match at the previous step and the current
       * match is not better, output the previous match:
       */
      if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
        max_insert = s.strstart + s.lookahead - MIN_MATCH;
        /* Do not insert strings in hash table beyond this. */
  
        //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  
        /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
                       s.prev_length - MIN_MATCH, bflush);***/
        bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
        /* Insert in hash table all strings up to the end of the match.
         * strstart-1 and strstart are already inserted. If there is not
         * enough lookahead, the last two strings are not inserted in
         * the hash table.
         */
        s.lookahead -= s.prev_length - 1;
        s.prev_length -= 2;
        do {
          if (++s.strstart <= max_insert) {
            /*** INSERT_STRING(s, s.strstart, hash_head); ***/
            s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
            hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
            s.head[s.ins_h] = s.strstart;
            /***/
          }
        } while (--s.prev_length !== 0);
        s.match_available = 0;
        s.match_length = MIN_MATCH - 1;
        s.strstart++;
  
        if (bflush) {
          /*** FLUSH_BLOCK(s, 0); ***/
          flush_block_only(s, false);
          if (s.strm.avail_out === 0) {
            return BS_NEED_MORE;
          }
          /***/
        }
  
      } else if (s.match_available) {
        /* If there was no match at the previous position, output a
         * single literal. If there was a match but the current match
         * is longer, truncate the previous match to a single literal.
         */
        //Tracevv((stderr,"%c", s->window[s->strstart-1]));
        /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
        bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  
        if (bflush) {
          /*** FLUSH_BLOCK_ONLY(s, 0) ***/
          flush_block_only(s, false);
          /***/
        }
        s.strstart++;
        s.lookahead--;
        if (s.strm.avail_out === 0) {
          return BS_NEED_MORE;
        }
      } else {
        /* There is no previous match to compare with, wait for
         * the next step to decide.
         */
        s.match_available = 1;
        s.strstart++;
        s.lookahead--;
      }
    }
    //Assert (flush != Z_NO_FLUSH, "no flush?");
    if (s.match_available) {
      //Tracevv((stderr,"%c", s->window[s->strstart-1]));
      /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
      bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  
      s.match_available = 0;
    }
    s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
    if (flush === Z_FINISH) {
      /*** FLUSH_BLOCK(s, 1); ***/
      flush_block_only(s, true);
      if (s.strm.avail_out === 0) {
        return BS_FINISH_STARTED;
      }
      /***/
      return BS_FINISH_DONE;
    }
    if (s.last_lit) {
      /*** FLUSH_BLOCK(s, 0); ***/
      flush_block_only(s, false);
      if (s.strm.avail_out === 0) {
        return BS_NEED_MORE;
      }
      /***/
    }
  
    return BS_BLOCK_DONE;
  }
  
  
  /* ===========================================================================
   * For Z_RLE, simply look for runs of bytes, generate matches only of distance
   * one.  Do not maintain a hash table.  (It will be regenerated if this run of
   * deflate switches away from Z_RLE.)
   */
  function deflate_rle(s, flush) {
    var bflush;            /* set if current block must be flushed */
    var prev;              /* byte at distance one to match */
    var scan, strend;      /* scan goes up to strend for length of run */
  
    var _win = s.window;
  
    for (;;) {
      /* Make sure that we always have enough lookahead, except
       * at the end of the input file. We need MAX_MATCH bytes
       * for the longest run, plus one for the unrolled loop.
       */
      if (s.lookahead <= MAX_MATCH) {
        fill_window(s);
        if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
          return BS_NEED_MORE;
        }
        if (s.lookahead === 0) { break; } /* flush the current block */
      }
  
      /* See how many times the previous byte repeats */
      s.match_length = 0;
      if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
        scan = s.strstart - 1;
        prev = _win[scan];
        if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
          strend = s.strstart + MAX_MATCH;
          do {
            /*jshint noempty:false*/
          } while (prev === _win[++scan] && prev === _win[++scan] &&
                   prev === _win[++scan] && prev === _win[++scan] &&
                   prev === _win[++scan] && prev === _win[++scan] &&
                   prev === _win[++scan] && prev === _win[++scan] &&
                   scan < strend);
          s.match_length = MAX_MATCH - (strend - scan);
          if (s.match_length > s.lookahead) {
            s.match_length = s.lookahead;
          }
        }
        //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
      }
  
      /* Emit match if have run of MIN_MATCH or longer, else emit literal */
      if (s.match_length >= MIN_MATCH) {
        //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  
        /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
        bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  
        s.lookahead -= s.match_length;
        s.strstart += s.match_length;
        s.match_length = 0;
      } else {
        /* No match, output a literal byte */
        //Tracevv((stderr,"%c", s->window[s->strstart]));
        /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
        bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  
        s.lookahead--;
        s.strstart++;
      }
      if (bflush) {
        /*** FLUSH_BLOCK(s, 0); ***/
        flush_block_only(s, false);
        if (s.strm.avail_out === 0) {
          return BS_NEED_MORE;
        }
        /***/
      }
    }
    s.insert = 0;
    if (flush === Z_FINISH) {
      /*** FLUSH_BLOCK(s, 1); ***/
      flush_block_only(s, true);
      if (s.strm.avail_out === 0) {
        return BS_FINISH_STARTED;
      }
      /***/
      return BS_FINISH_DONE;
    }
    if (s.last_lit) {
      /*** FLUSH_BLOCK(s, 0); ***/
      flush_block_only(s, false);
      if (s.strm.avail_out === 0) {
        return BS_NEED_MORE;
      }
      /***/
    }
    return BS_BLOCK_DONE;
  }
  
  /* ===========================================================================
   * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.
   * (It will be regenerated if this run of deflate switches away from Huffman.)
   */
  function deflate_huff(s, flush) {
    var bflush;             /* set if current block must be flushed */
  
    for (;;) {
      /* Make sure that we have a literal to write. */
      if (s.lookahead === 0) {
        fill_window(s);
        if (s.lookahead === 0) {
          if (flush === Z_NO_FLUSH) {
            return BS_NEED_MORE;
          }
          break;      /* flush the current block */
        }
      }
  
      /* Output a literal byte */
      s.match_length = 0;
      //Tracevv((stderr,"%c", s->window[s->strstart]));
      /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
      bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
      s.lookahead--;
      s.strstart++;
      if (bflush) {
        /*** FLUSH_BLOCK(s, 0); ***/
        flush_block_only(s, false);
        if (s.strm.avail_out === 0) {
          return BS_NEED_MORE;
        }
        /***/
      }
    }
    s.insert = 0;
    if (flush === Z_FINISH) {
      /*** FLUSH_BLOCK(s, 1); ***/
      flush_block_only(s, true);
      if (s.strm.avail_out === 0) {
        return BS_FINISH_STARTED;
      }
      /***/
      return BS_FINISH_DONE;
    }
    if (s.last_lit) {
      /*** FLUSH_BLOCK(s, 0); ***/
      flush_block_only(s, false);
      if (s.strm.avail_out === 0) {
        return BS_NEED_MORE;
      }
      /***/
    }
    return BS_BLOCK_DONE;
  }
  
  /* Values for max_lazy_match, good_match and max_chain_length, depending on
   * the desired pack level (0..9). The values given below have been tuned to
   * exclude worst case performance for pathological files. Better values may be
   * found for specific files.
   */
  function Config(good_length, max_lazy, nice_length, max_chain, func) {
    this.good_length = good_length;
    this.max_lazy = max_lazy;
    this.nice_length = nice_length;
    this.max_chain = max_chain;
    this.func = func;
  }
  
  var configuration_table;
  
  configuration_table = [
    /*      good lazy nice chain */
    new Config(0, 0, 0, 0, deflate_stored),          /* 0 store only */
    new Config(4, 4, 8, 4, deflate_fast),            /* 1 max speed, no lazy matches */
    new Config(4, 5, 16, 8, deflate_fast),           /* 2 */
    new Config(4, 6, 32, 32, deflate_fast),          /* 3 */
  
    new Config(4, 4, 16, 16, deflate_slow),          /* 4 lazy matches */
    new Config(8, 16, 32, 32, deflate_slow),         /* 5 */
    new Config(8, 16, 128, 128, deflate_slow),       /* 6 */
    new Config(8, 32, 128, 256, deflate_slow),       /* 7 */
    new Config(32, 128, 258, 1024, deflate_slow),    /* 8 */
    new Config(32, 258, 258, 4096, deflate_slow)     /* 9 max compression */
  ];
  
  
  /* ===========================================================================
   * Initialize the "longest match" routines for a new zlib stream
   */
  function lm_init(s) {
    s.window_size = 2 * s.w_size;
  
    /*** CLEAR_HASH(s); ***/
    zero(s.head); // Fill with NIL (= 0);
  
    /* Set the default configuration parameters:
     */
    s.max_lazy_match = configuration_table[s.level].max_lazy;
    s.good_match = configuration_table[s.level].good_length;
    s.nice_match = configuration_table[s.level].nice_length;
    s.max_chain_length = configuration_table[s.level].max_chain;
  
    s.strstart = 0;
    s.block_start = 0;
    s.lookahead = 0;
    s.insert = 0;
    s.match_length = s.prev_length = MIN_MATCH - 1;
    s.match_available = 0;
    s.ins_h = 0;
  }
  
  
  function DeflateState() {
    this.strm = null;            /* pointer back to this zlib stream */
    this.status = 0;            /* as the name implies */
    this.pending_buf = null;      /* output still pending */
    this.pending_buf_size = 0;  /* size of pending_buf */
    this.pending_out = 0;       /* next pending byte to output to the stream */
    this.pending = 0;           /* nb of bytes in the pending buffer */
    this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip */
    this.gzhead = null;         /* gzip header information to write */
    this.gzindex = 0;           /* where in extra, name, or comment */
    this.method = Z_DEFLATED; /* can only be DEFLATED */
    this.last_flush = -1;   /* value of flush param for previous deflate call */
  
    this.w_size = 0;  /* LZ77 window size (32K by default) */
    this.w_bits = 0;  /* log2(w_size)  (8..16) */
    this.w_mask = 0;  /* w_size - 1 */
  
    this.window = null;
    /* Sliding window. Input bytes are read into the second half of the window,
     * and move to the first half later to keep a dictionary of at least wSize
     * bytes. With this organization, matches are limited to a distance of
     * wSize-MAX_MATCH bytes, but this ensures that IO is always
     * performed with a length multiple of the block size.
     */
  
    this.window_size = 0;
    /* Actual size of window: 2*wSize, except when the user input buffer
     * is directly used as sliding window.
     */
  
    this.prev = null;
    /* Link to older string with same hash index. To limit the size of this
     * array to 64K, this link is maintained only for the last 32K strings.
     * An index in this array is thus a window index modulo 32K.
     */
  
    this.head = null;   /* Heads of the hash chains or NIL. */
  
    this.ins_h = 0;       /* hash index of string to be inserted */
    this.hash_size = 0;   /* number of elements in hash table */
    this.hash_bits = 0;   /* log2(hash_size) */
    this.hash_mask = 0;   /* hash_size-1 */
  
    this.hash_shift = 0;
    /* Number of bits by which ins_h must be shifted at each input
     * step. It must be such that after MIN_MATCH steps, the oldest
     * byte no longer takes part in the hash key, that is:
     *   hash_shift * MIN_MATCH >= hash_bits
     */
  
    this.block_start = 0;
    /* Window position at the beginning of the current output block. Gets
     * negative when the window is moved backwards.
     */
  
    this.match_length = 0;      /* length of best match */
    this.prev_match = 0;        /* previous match */
    this.match_available = 0;   /* set if previous match exists */
    this.strstart = 0;          /* start of string to insert */
    this.match_start = 0;       /* start of matching string */
    this.lookahead = 0;         /* number of valid bytes ahead in window */
  
    this.prev_length = 0;
    /* Length of the best match at previous step. Matches not greater than this
     * are discarded. This is used in the lazy match evaluation.
     */
  
    this.max_chain_length = 0;
    /* To speed up deflation, hash chains are never searched beyond this
     * length.  A higher limit improves compression ratio but degrades the
     * speed.
     */
  
    this.max_lazy_match = 0;
    /* Attempt to find a better match only when the current match is strictly
     * smaller than this value. This mechanism is used only for compression
     * levels >= 4.
     */
    // That's alias to max_lazy_match, don't use directly
    //this.max_insert_length = 0;
    /* Insert new strings in the hash table only if the match length is not
     * greater than this length. This saves time but degrades compression.
     * max_insert_length is used only for compression levels <= 3.
     */
  
    this.level = 0;     /* compression level (1..9) */
    this.strategy = 0;  /* favor or force Huffman coding*/
  
    this.good_match = 0;
    /* Use a faster search when the previous match is longer than this */
  
    this.nice_match = 0; /* Stop searching when current match exceeds this */
  
                /* used by trees.c: */
  
    /* Didn't use ct_data typedef below to suppress compiler warning */
  
    // struct ct_data_s dyn_ltree[HEAP_SIZE];   /* literal and length tree */
    // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
    // struct ct_data_s bl_tree[2*BL_CODES+1];  /* Huffman tree for bit lengths */
  
    // Use flat array of DOUBLE size, with interleaved fata,
    // because JS does not support effective
    this.dyn_ltree  = new utils.Buf16(HEAP_SIZE * 2);
    this.dyn_dtree  = new utils.Buf16((2 * D_CODES + 1) * 2);
    this.bl_tree    = new utils.Buf16((2 * BL_CODES + 1) * 2);
    zero(this.dyn_ltree);
    zero(this.dyn_dtree);
    zero(this.bl_tree);
  
    this.l_desc   = null;         /* desc. for literal tree */
    this.d_desc   = null;         /* desc. for distance tree */
    this.bl_desc  = null;         /* desc. for bit length tree */
  
    //ush bl_count[MAX_BITS+1];
    this.bl_count = new utils.Buf16(MAX_BITS + 1);
    /* number of codes at each bit length for an optimal tree */
  
    //int heap[2*L_CODES+1];      /* heap used to build the Huffman trees */
    this.heap = new utils.Buf16(2 * L_CODES + 1);  /* heap used to build the Huffman trees */
    zero(this.heap);
  
    this.heap_len = 0;               /* number of elements in the heap */
    this.heap_max = 0;               /* element of largest frequency */
    /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
     * The same heap array is used to build all trees.
     */
  
    this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
    zero(this.depth);
    /* Depth of each subtree used as tie breaker for trees of equal frequency
     */
  
    this.l_buf = 0;          /* buffer index for literals or lengths */
  
    this.lit_bufsize = 0;
    /* Size of match buffer for literals/lengths.  There are 4 reasons for
     * limiting lit_bufsize to 64K:
     *   - frequencies can be kept in 16 bit counters
     *   - if compression is not successful for the first block, all input
     *     data is still in the window so we can still emit a stored block even
     *     when input comes from standard input.  (This can also be done for
     *     all blocks if lit_bufsize is not greater than 32K.)
     *   - if compression is not successful for a file smaller than 64K, we can
     *     even emit a stored file instead of a stored block (saving 5 bytes).
     *     This is applicable only for zip (not gzip or zlib).
     *   - creating new Huffman trees less frequently may not provide fast
     *     adaptation to changes in the input data statistics. (Take for
     *     example a binary file with poorly compressible code followed by
     *     a highly compressible string table.) Smaller buffer sizes give
     *     fast adaptation but have of course the overhead of transmitting
     *     trees more frequently.
     *   - I can't count above 4
     */
  
    this.last_lit = 0;      /* running index in l_buf */
  
    this.d_buf = 0;
    /* Buffer index for distances. To simplify the code, d_buf and l_buf have
     * the same number of elements. To use different lengths, an extra flag
     * array would be necessary.
     */
  
    this.opt_len = 0;       /* bit length of current block with optimal trees */
    this.static_len = 0;    /* bit length of current block with static trees */
    this.matches = 0;       /* number of string matches in current block */
    this.insert = 0;        /* bytes at end of window left to insert */
  
  
    this.bi_buf = 0;
    /* Output buffer. bits are inserted starting at the bottom (least
     * significant bits).
     */
    this.bi_valid = 0;
    /* Number of valid bits in bi_buf.  All bits above the last valid bit
     * are always zero.
     */
  
    // Used for window memory init. We safely ignore it for JS. That makes
    // sense only for pointers and memory check tools.
    //this.high_water = 0;
    /* High water mark offset in window for initialized bytes -- bytes above
     * this are set to zero in order to avoid memory check warnings when
     * longest match routines access bytes past the input.  This is then
     * updated to the new high water mark.
     */
  }
  
  
  function deflateResetKeep(strm) {
    var s;
  
    if (!strm || !strm.state) {
      return err(strm, Z_STREAM_ERROR);
    }
  
    strm.total_in = strm.total_out = 0;
    strm.data_type = Z_UNKNOWN;
  
    s = strm.state;
    s.pending = 0;
    s.pending_out = 0;
  
    if (s.wrap < 0) {
      s.wrap = -s.wrap;
      /* was made negative by deflate(..., Z_FINISH); */
    }
    s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
    strm.adler = (s.wrap === 2) ?
      0  // crc32(0, Z_NULL, 0)
    :
      1; // adler32(0, Z_NULL, 0)
    s.last_flush = Z_NO_FLUSH;
    trees._tr_init(s);
    return Z_OK;
  }
  
  
  function deflateReset(strm) {
    var ret = deflateResetKeep(strm);
    if (ret === Z_OK) {
      lm_init(strm.state);
    }
    return ret;
  }
  
  
  function deflateSetHeader(strm, head) {
    if (!strm || !strm.state) { return Z_STREAM_ERROR; }
    if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
    strm.state.gzhead = head;
    return Z_OK;
  }
  
  
  function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
    if (!strm) { // === Z_NULL
      return Z_STREAM_ERROR;
    }
    var wrap = 1;
  
    if (level === Z_DEFAULT_COMPRESSION) {
      level = 6;
    }
  
    if (windowBits < 0) { /* suppress zlib wrapper */
      wrap = 0;
      windowBits = -windowBits;
    }
  
    else if (windowBits > 15) {
      wrap = 2;           /* write gzip wrapper instead */
      windowBits -= 16;
    }
  
  
    if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
      windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
      strategy < 0 || strategy > Z_FIXED) {
      return err(strm, Z_STREAM_ERROR);
    }
  
  
    if (windowBits === 8) {
      windowBits = 9;
    }
    /* until 256-byte window bug fixed */
  
    var s = new DeflateState();
  
    strm.state = s;
    s.strm = strm;
  
    s.wrap = wrap;
    s.gzhead = null;
    s.w_bits = windowBits;
    s.w_size = 1 << s.w_bits;
    s.w_mask = s.w_size - 1;
  
    s.hash_bits = memLevel + 7;
    s.hash_size = 1 << s.hash_bits;
    s.hash_mask = s.hash_size - 1;
    s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  
    s.window = new utils.Buf8(s.w_size * 2);
    s.head = new utils.Buf16(s.hash_size);
    s.prev = new utils.Buf16(s.w_size);
  
    // Don't need mem init magic for JS.
    //s.high_water = 0;  /* nothing written to s->window yet */
  
    s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  
    s.pending_buf_size = s.lit_bufsize * 4;
    s.pending_buf = new utils.Buf8(s.pending_buf_size);
  
    s.d_buf = s.lit_bufsize >> 1;
    s.l_buf = (1 + 2) * s.lit_bufsize;
  
    s.level = level;
    s.strategy = strategy;
    s.method = method;
  
    return deflateReset(strm);
  }
  
  function deflateInit(strm, level) {
    return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  }
  
  
  function deflate(strm, flush) {
    var old_flush, s;
    var beg, val; // for gzip header write only
  
    if (!strm || !strm.state ||
      flush > Z_BLOCK || flush < 0) {
      return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
    }
  
    s = strm.state;
  
    if (!strm.output ||
        (!strm.input && strm.avail_in !== 0) ||
        (s.status === FINISH_STATE && flush !== Z_FINISH)) {
      return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
    }
  
    s.strm = strm; /* just in case */
    old_flush = s.last_flush;
    s.last_flush = flush;
  
    /* Write the header */
    if (s.status === INIT_STATE) {
  
      if (s.wrap === 2) { // GZIP header
        strm.adler = 0;  //crc32(0L, Z_NULL, 0);
        put_byte(s, 31);
        put_byte(s, 139);
        put_byte(s, 8);
        if (!s.gzhead) { // s->gzhead == Z_NULL
          put_byte(s, 0);
          put_byte(s, 0);
          put_byte(s, 0);
          put_byte(s, 0);
          put_byte(s, 0);
          put_byte(s, s.level === 9 ? 2 :
                      (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
                       4 : 0));
          put_byte(s, OS_CODE);
          s.status = BUSY_STATE;
        }
        else {
          put_byte(s, (s.gzhead.text ? 1 : 0) +
                      (s.gzhead.hcrc ? 2 : 0) +
                      (!s.gzhead.extra ? 0 : 4) +
                      (!s.gzhead.name ? 0 : 8) +
                      (!s.gzhead.comment ? 0 : 16)
                  );
          put_byte(s, s.gzhead.time & 0xff);
          put_byte(s, (s.gzhead.time >> 8) & 0xff);
          put_byte(s, (s.gzhead.time >> 16) & 0xff);
          put_byte(s, (s.gzhead.time >> 24) & 0xff);
          put_byte(s, s.level === 9 ? 2 :
                      (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
                       4 : 0));
          put_byte(s, s.gzhead.os & 0xff);
          if (s.gzhead.extra && s.gzhead.extra.length) {
            put_byte(s, s.gzhead.extra.length & 0xff);
            put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
          }
          if (s.gzhead.hcrc) {
            strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
          }
          s.gzindex = 0;
          s.status = EXTRA_STATE;
        }
      }
      else // DEFLATE header
      {
        var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
        var level_flags = -1;
  
        if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
          level_flags = 0;
        } else if (s.level < 6) {
          level_flags = 1;
        } else if (s.level === 6) {
          level_flags = 2;
        } else {
          level_flags = 3;
        }
        header |= (level_flags << 6);
        if (s.strstart !== 0) { header |= PRESET_DICT; }
        header += 31 - (header % 31);
  
        s.status = BUSY_STATE;
        putShortMSB(s, header);
  
        /* Save the adler32 of the preset dictionary: */
        if (s.strstart !== 0) {
          putShortMSB(s, strm.adler >>> 16);
          putShortMSB(s, strm.adler & 0xffff);
        }
        strm.adler = 1; // adler32(0L, Z_NULL, 0);
      }
    }
  
  //#ifdef GZIP
    if (s.status === EXTRA_STATE) {
      if (s.gzhead.extra/* != Z_NULL*/) {
        beg = s.pending;  /* start of bytes to update crc */
  
        while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
          if (s.pending === s.pending_buf_size) {
            if (s.gzhead.hcrc && s.pending > beg) {
              strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
            }
            flush_pending(strm);
            beg = s.pending;
            if (s.pending === s.pending_buf_size) {
              break;
            }
          }
          put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
          s.gzindex++;
        }
        if (s.gzhead.hcrc && s.pending > beg) {
          strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
        }
        if (s.gzindex === s.gzhead.extra.length) {
          s.gzindex = 0;
          s.status = NAME_STATE;
        }
      }
      else {
        s.status = NAME_STATE;
      }
    }
    if (s.status === NAME_STATE) {
      if (s.gzhead.name/* != Z_NULL*/) {
        beg = s.pending;  /* start of bytes to update crc */
        //int val;
  
        do {
          if (s.pending === s.pending_buf_size) {
            if (s.gzhead.hcrc && s.pending > beg) {
              strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
            }
            flush_pending(strm);
            beg = s.pending;
            if (s.pending === s.pending_buf_size) {
              val = 1;
              break;
            }
          }
          // JS specific: little magic to add zero terminator to end of string
          if (s.gzindex < s.gzhead.name.length) {
            val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
          } else {
            val = 0;
          }
          put_byte(s, val);
        } while (val !== 0);
  
        if (s.gzhead.hcrc && s.pending > beg) {
          strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
        }
        if (val === 0) {
          s.gzindex = 0;
          s.status = COMMENT_STATE;
        }
      }
      else {
        s.status = COMMENT_STATE;
      }
    }
    if (s.status === COMMENT_STATE) {
      if (s.gzhead.comment/* != Z_NULL*/) {
        beg = s.pending;  /* start of bytes to update crc */
        //int val;
  
        do {
          if (s.pending === s.pending_buf_size) {
            if (s.gzhead.hcrc && s.pending > beg) {
              strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
            }
            flush_pending(strm);
            beg = s.pending;
            if (s.pending === s.pending_buf_size) {
              val = 1;
              break;
            }
          }
          // JS specific: little magic to add zero terminator to end of string
          if (s.gzindex < s.gzhead.comment.length) {
            val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
          } else {
            val = 0;
          }
          put_byte(s, val);
        } while (val !== 0);
  
        if (s.gzhead.hcrc && s.pending > beg) {
          strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
        }
        if (val === 0) {
          s.status = HCRC_STATE;
        }
      }
      else {
        s.status = HCRC_STATE;
      }
    }
    if (s.status === HCRC_STATE) {
      if (s.gzhead.hcrc) {
        if (s.pending + 2 > s.pending_buf_size) {
          flush_pending(strm);
        }
        if (s.pending + 2 <= s.pending_buf_size) {
          put_byte(s, strm.adler & 0xff);
          put_byte(s, (strm.adler >> 8) & 0xff);
          strm.adler = 0; //crc32(0L, Z_NULL, 0);
          s.status = BUSY_STATE;
        }
      }
      else {
        s.status = BUSY_STATE;
      }
    }
  //#endif
  
    /* Flush as much pending output as possible */
    if (s.pending !== 0) {
      flush_pending(strm);
      if (strm.avail_out === 0) {
        /* Since avail_out is 0, deflate will be called again with
         * more output space, but possibly with both pending and
         * avail_in equal to zero. There won't be anything to do,
         * but this is not an error situation so make sure we
         * return OK instead of BUF_ERROR at next call of deflate:
         */
        s.last_flush = -1;
        return Z_OK;
      }
  
      /* Make sure there is something to do and avoid duplicate consecutive
       * flushes. For repeated and useless calls with Z_FINISH, we keep
       * returning Z_STREAM_END instead of Z_BUF_ERROR.
       */
    } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
      flush !== Z_FINISH) {
      return err(strm, Z_BUF_ERROR);
    }
  
    /* User must not provide more input after the first FINISH: */
    if (s.status === FINISH_STATE && strm.avail_in !== 0) {
      return err(strm, Z_BUF_ERROR);
    }
  
    /* Start a new block or continue the current one.
     */
    if (strm.avail_in !== 0 || s.lookahead !== 0 ||
      (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
      var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
        (s.strategy === Z_RLE ? deflate_rle(s, flush) :
          configuration_table[s.level].func(s, flush));
  
      if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
        s.status = FINISH_STATE;
      }
      if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
        if (strm.avail_out === 0) {
          s.last_flush = -1;
          /* avoid BUF_ERROR next call, see above */
        }
        return Z_OK;
        /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
         * of deflate should use the same flush parameter to make sure
         * that the flush is complete. So we don't have to output an
         * empty block here, this will be done at next call. This also
         * ensures that for a very small output buffer, we emit at most
         * one empty block.
         */
      }
      if (bstate === BS_BLOCK_DONE) {
        if (flush === Z_PARTIAL_FLUSH) {
          trees._tr_align(s);
        }
        else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  
          trees._tr_stored_block(s, 0, 0, false);
          /* For a full flush, this empty block will be recognized
           * as a special marker by inflate_sync().
           */
          if (flush === Z_FULL_FLUSH) {
            /*** CLEAR_HASH(s); ***/             /* forget history */
            zero(s.head); // Fill with NIL (= 0);
  
            if (s.lookahead === 0) {
              s.strstart = 0;
              s.block_start = 0;
              s.insert = 0;
            }
          }
        }
        flush_pending(strm);
        if (strm.avail_out === 0) {
          s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
          return Z_OK;
        }
      }
    }
    //Assert(strm->avail_out > 0, "bug2");
    //if (strm.avail_out <= 0) { throw new Error("bug2");}
  
    if (flush !== Z_FINISH) { return Z_OK; }
    if (s.wrap <= 0) { return Z_STREAM_END; }
  
    /* Write the trailer */
    if (s.wrap === 2) {
      put_byte(s, strm.adler & 0xff);
      put_byte(s, (strm.adler >> 8) & 0xff);
      put_byte(s, (strm.adler >> 16) & 0xff);
      put_byte(s, (strm.adler >> 24) & 0xff);
      put_byte(s, strm.total_in & 0xff);
      put_byte(s, (strm.total_in >> 8) & 0xff);
      put_byte(s, (strm.total_in >> 16) & 0xff);
      put_byte(s, (strm.total_in >> 24) & 0xff);
    }
    else
    {
      putShortMSB(s, strm.adler >>> 16);
      putShortMSB(s, strm.adler & 0xffff);
    }
  
    flush_pending(strm);
    /* If avail_out is zero, the application will call deflate again
     * to flush the rest.
     */
    if (s.wrap > 0) { s.wrap = -s.wrap; }
    /* write the trailer only once! */
    return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  }
  
  function deflateEnd(strm) {
    var status;
  
    if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
      return Z_STREAM_ERROR;
    }
  
    status = strm.state.status;
    if (status !== INIT_STATE &&
      status !== EXTRA_STATE &&
      status !== NAME_STATE &&
      status !== COMMENT_STATE &&
      status !== HCRC_STATE &&
      status !== BUSY_STATE &&
      status !== FINISH_STATE
    ) {
      return err(strm, Z_STREAM_ERROR);
    }
  
    strm.state = null;
  
    return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  }
  
  
  /* =========================================================================
   * Initializes the compression dictionary from the given byte
   * sequence without producing any compressed output.
   */
  function deflateSetDictionary(strm, dictionary) {
    var dictLength = dictionary.length;
  
    var s;
    var str, n;
    var wrap;
    var avail;
    var next;
    var input;
    var tmpDict;
  
    if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
      return Z_STREAM_ERROR;
    }
  
    s = strm.state;
    wrap = s.wrap;
  
    if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
      return Z_STREAM_ERROR;
    }
  
    /* when using zlib wrappers, compute Adler-32 for provided dictionary */
    if (wrap === 1) {
      /* adler32(strm->adler, dictionary, dictLength); */
      strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
    }
  
    s.wrap = 0;   /* avoid computing Adler-32 in read_buf */
  
    /* if dictionary would fill window, just replace the history */
    if (dictLength >= s.w_size) {
      if (wrap === 0) {            /* already empty otherwise */
        /*** CLEAR_HASH(s); ***/
        zero(s.head); // Fill with NIL (= 0);
        s.strstart = 0;
        s.block_start = 0;
        s.insert = 0;
      }
      /* use the tail */
      // dictionary = dictionary.slice(dictLength - s.w_size);
      tmpDict = new utils.Buf8(s.w_size);
      utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
      dictionary = tmpDict;
      dictLength = s.w_size;
    }
    /* insert dictionary into window and hash */
    avail = strm.avail_in;
    next = strm.next_in;
    input = strm.input;
    strm.avail_in = dictLength;
    strm.next_in = 0;
    strm.input = dictionary;
    fill_window(s);
    while (s.lookahead >= MIN_MATCH) {
      str = s.strstart;
      n = s.lookahead - (MIN_MATCH - 1);
      do {
        /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
        s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  
        s.prev[str & s.w_mask] = s.head[s.ins_h];
  
        s.head[s.ins_h] = str;
        str++;
      } while (--n);
      s.strstart = str;
      s.lookahead = MIN_MATCH - 1;
      fill_window(s);
    }
    s.strstart += s.lookahead;
    s.block_start = s.strstart;
    s.insert = s.lookahead;
    s.lookahead = 0;
    s.match_length = s.prev_length = MIN_MATCH - 1;
    s.match_available = 0;
    strm.next_in = next;
    strm.input = input;
    strm.avail_in = avail;
    s.wrap = wrap;
    return Z_OK;
  }
  
  
  exports.deflateInit = deflateInit;
  exports.deflateInit2 = deflateInit2;
  exports.deflateReset = deflateReset;
  exports.deflateResetKeep = deflateResetKeep;
  exports.deflateSetHeader = deflateSetHeader;
  exports.deflate = deflate;
  exports.deflateEnd = deflateEnd;
  exports.deflateSetDictionary = deflateSetDictionary;
  exports.deflateInfo = 'pako deflate (from Nodeca project)';
  
  /* Not implemented
  exports.deflateBound = deflateBound;
  exports.deflateCopy = deflateCopy;
  exports.deflateParams = deflateParams;
  exports.deflatePending = deflatePending;
  exports.deflatePrime = deflatePrime;
  exports.deflateTune = deflateTune;
  */
  
  },{"../utils/common":70,"./adler32":72,"./crc32":74,"./messages":80,"./trees":81}],76:[function(require,module,exports){
  'use strict';
  
  
  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;
  }
  
  module.exports = GZheader;
  
  },{}],77:[function(require,module,exports){
  'use strict';
  
  // See state defs from inflate.js
  var BAD = 30;       /* got a data error -- remain here until reset */
  var TYPE = 12;      /* i: waiting for type bits, including last-flag bit */
  
  /*
     Decode literal, length, and distance codes and write out the resulting
     literal and match bytes until either not enough input or output is
     available, an end-of-block is encountered, or a data error is encountered.
     When large enough input and output buffers are supplied to inflate(), for
     example, a 16K input buffer and a 64K output buffer, more than 95% of the
     inflate execution time is spent in this routine.
  
     Entry assumptions:
  
          state.mode === LEN
          strm.avail_in >= 6
          strm.avail_out >= 258
          start >= strm.avail_out
          state.bits < 8
  
     On return, state.mode is one of:
  
          LEN -- ran out of enough output space or enough available input
          TYPE -- reached end of block code, inflate() to interpret next block
          BAD -- error in block data
  
     Notes:
  
      - The maximum input bits used by a length/distance pair is 15 bits for the
        length code, 5 bits for the length extra, 15 bits for the distance code,
        and 13 bits for the distance extra.  This totals 48 bits, or six bytes.
        Therefore if strm.avail_in >= 6, then there is enough input to avoid
        checking for available input while decoding.
  
      - The maximum bytes that a single length/distance pair can output is 258
        bytes, which is the maximum length that can be coded.  inflate_fast()
        requires strm.avail_out >= 258 for each loop to avoid checking for
        output space.
   */
  module.exports = function inflate_fast(strm, start) {
    var state;
    var _in;                    /* local strm.input */
    var last;                   /* have enough input while in < last */
    var _out;                   /* local strm.output */
    var beg;                    /* inflate()'s initial strm.output */
    var end;                    /* while out < end, enough space available */
  //#ifdef INFLATE_STRICT
    var dmax;                   /* maximum distance from zlib header */
  //#endif
    var wsize;                  /* window size or zero if not using window */
    var whave;                  /* valid bytes in the window */
    var wnext;                  /* window write index */
    // Use `s_window` instead `window`, avoid conflict with instrumentation tools
    var s_window;               /* allocated sliding window, if wsize != 0 */
    var hold;                   /* local strm.hold */
    var bits;                   /* local strm.bits */
    var lcode;                  /* local strm.lencode */
    var dcode;                  /* local strm.distcode */
    var lmask;                  /* mask for first level of length codes */
    var dmask;                  /* mask for first level of distance codes */
    var here;                   /* retrieved table entry */
    var op;                     /* code bits, operation, extra bits, or */
                                /*  window position, window bytes to copy */
    var len;                    /* match length, unused bytes */
    var dist;                   /* match distance */
    var from;                   /* where to copy match from */
    var from_source;
  
  
    var input, output; // JS specific, because we have no pointers
  
    /* copy state to local variables */
    state = strm.state;
    //here = state.here;
    _in = strm.next_in;
    input = strm.input;
    last = _in + (strm.avail_in - 5);
    _out = strm.next_out;
    output = strm.output;
    beg = _out - (start - strm.avail_out);
    end = _out + (strm.avail_out - 257);
  //#ifdef INFLATE_STRICT
    dmax = state.dmax;
  //#endif
    wsize = state.wsize;
    whave = state.whave;
    wnext = state.wnext;
    s_window = state.window;
    hold = state.hold;
    bits = state.bits;
    lcode = state.lencode;
    dcode = state.distcode;
    lmask = (1 << state.lenbits) - 1;
    dmask = (1 << state.distbits) - 1;
  
  
    /* decode literals and length/distances until end-of-block or not enough
       input data or output space */
  
    top:
    do {
      if (bits < 15) {
        hold += input[_in++] << bits;
        bits += 8;
        hold += input[_in++] << bits;
        bits += 8;
      }
  
      here = lcode[hold & lmask];
  
      dolen:
      for (;;) { // Goto emulation
        op = here >>> 24/*here.bits*/;
        hold >>>= op;
        bits -= op;
        op = (here >>> 16) & 0xff/*here.op*/;
        if (op === 0) {                          /* literal */
          //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
          //        "inflate:         literal '%c'\n" :
          //        "inflate:         literal 0x%02x\n", here.val));
          output[_out++] = here & 0xffff/*here.val*/;
        }
        else if (op & 16) {                     /* length base */
          len = here & 0xffff/*here.val*/;
          op &= 15;                           /* number of extra bits */
          if (op) {
            if (bits < op) {
              hold += input[_in++] << bits;
              bits += 8;
            }
            len += hold & ((1 << op) - 1);
            hold >>>= op;
            bits -= op;
          }
          //Tracevv((stderr, "inflate:         length %u\n", len));
          if (bits < 15) {
            hold += input[_in++] << bits;
            bits += 8;
            hold += input[_in++] << bits;
            bits += 8;
          }
          here = dcode[hold & dmask];
  
          dodist:
          for (;;) { // goto emulation
            op = here >>> 24/*here.bits*/;
            hold >>>= op;
            bits -= op;
            op = (here >>> 16) & 0xff/*here.op*/;
  
            if (op & 16) {                      /* distance base */
              dist = here & 0xffff/*here.val*/;
              op &= 15;                       /* number of extra bits */
              if (bits < op) {
                hold += input[_in++] << bits;
                bits += 8;
                if (bits < op) {
                  hold += input[_in++] << bits;
                  bits += 8;
                }
              }
              dist += hold & ((1 << op) - 1);
  //#ifdef INFLATE_STRICT
              if (dist > dmax) {
                strm.msg = 'invalid distance too far back';
                state.mode = BAD;
                break top;
              }
  //#endif
              hold >>>= op;
              bits -= op;
              //Tracevv((stderr, "inflate:         distance %u\n", dist));
              op = _out - beg;                /* max distance in output */
              if (dist > op) {                /* see if copy from window */
                op = dist - op;               /* distance back in window */
                if (op > whave) {
                  if (state.sane) {
                    strm.msg = 'invalid distance too far back';
                    state.mode = BAD;
                    break top;
                  }
  
  // (!) This block is disabled in zlib defailts,
  // don't enable it for binary compatibility
  //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  //                if (len <= op - whave) {
  //                  do {
  //                    output[_out++] = 0;
  //                  } while (--len);
  //                  continue top;
  //                }
  //                len -= op - whave;
  //                do {
  //                  output[_out++] = 0;
  //                } while (--op > whave);
  //                if (op === 0) {
  //                  from = _out - dist;
  //                  do {
  //                    output[_out++] = output[from++];
  //                  } while (--len);
  //                  continue top;
  //                }
  //#endif
                }
                from = 0; // window index
                from_source = s_window;
                if (wnext === 0) {           /* very common case */
                  from += wsize - op;
                  if (op < len) {         /* some from window */
                    len -= op;
                    do {
                      output[_out++] = s_window[from++];
                    } while (--op);
                    from = _out - dist;  /* rest from output */
                    from_source = output;
                  }
                }
                else if (wnext < op) {      /* wrap around window */
                  from += wsize + wnext - op;
                  op -= wnext;
                  if (op < len) {         /* some from end of window */
                    len -= op;
                    do {
                      output[_out++] = s_window[from++];
                    } while (--op);
                    from = 0;
                    if (wnext < len) {  /* some from start of window */
                      op = wnext;
                      len -= op;
                      do {
                        output[_out++] = s_window[from++];
                      } while (--op);
                      from = _out - dist;      /* rest from output */
                      from_source = output;
                    }
                  }
                }
                else {                      /* contiguous in window */
                  from += wnext - op;
                  if (op < len) {         /* some from window */
                    len -= op;
                    do {
                      output[_out++] = s_window[from++];
                    } while (--op);
                    from = _out - dist;  /* rest from output */
                    from_source = output;
                  }
                }
                while (len > 2) {
                  output[_out++] = from_source[from++];
                  output[_out++] = from_source[from++];
                  output[_out++] = from_source[from++];
                  len -= 3;
                }
                if (len) {
                  output[_out++] = from_source[from++];
                  if (len > 1) {
                    output[_out++] = from_source[from++];
                  }
                }
              }
              else {
                from = _out - dist;          /* copy direct from output */
                do {                        /* minimum length is three */
                  output[_out++] = output[from++];
                  output[_out++] = output[from++];
                  output[_out++] = output[from++];
                  len -= 3;
                } while (len > 2);
                if (len) {
                  output[_out++] = output[from++];
                  if (len > 1) {
                    output[_out++] = output[from++];
                  }
                }
              }
            }
            else if ((op & 64) === 0) {          /* 2nd level distance code */
              here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
              continue dodist;
            }
            else {
              strm.msg = 'invalid distance code';
              state.mode = BAD;
              break top;
            }
  
            break; // need to emulate goto via "continue"
          }
        }
        else if ((op & 64) === 0) {              /* 2nd level length code */
          here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
          continue dolen;
        }
        else if (op & 32) {                     /* end-of-block */
          //Tracevv((stderr, "inflate:         end of block\n"));
          state.mode = TYPE;
          break top;
        }
        else {
          strm.msg = 'invalid literal/length code';
          state.mode = BAD;
          break top;
        }
  
        break; // need to emulate goto via "continue"
      }
    } while (_in < last && _out < end);
  
    /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
    len = bits >> 3;
    _in -= len;
    bits -= len << 3;
    hold &= (1 << bits) - 1;
  
    /* update state and return */
    strm.next_in = _in;
    strm.next_out = _out;
    strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
    strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
    state.hold = hold;
    state.bits = bits;
    return;
  };
  
  },{}],78:[function(require,module,exports){
  'use strict';
  
  
  var utils         = require('../utils/common');
  var adler32       = require('./adler32');
  var crc32         = require('./crc32');
  var inflate_fast  = require('./inffast');
  var inflate_table = require('./inftrees');
  
  var CODES = 0;
  var LENS = 1;
  var DISTS = 2;
  
  /* Public constants ==========================================================*/
  /* ===========================================================================*/
  
  
  /* Allowed flush values; see deflate() and inflate() below for details */
  //var Z_NO_FLUSH      = 0;
  //var Z_PARTIAL_FLUSH = 1;
  //var Z_SYNC_FLUSH    = 2;
  //var Z_FULL_FLUSH    = 3;
  var Z_FINISH        = 4;
  var Z_BLOCK         = 5;
  var Z_TREES         = 6;
  
  
  /* Return codes for the compression/decompression functions. Negative values
   * are errors, positive values are used for special but normal events.
   */
  var Z_OK            = 0;
  var Z_STREAM_END    = 1;
  var Z_NEED_DICT     = 2;
  //var Z_ERRNO         = -1;
  var Z_STREAM_ERROR  = -2;
  var Z_DATA_ERROR    = -3;
  var Z_MEM_ERROR     = -4;
  var Z_BUF_ERROR     = -5;
  //var Z_VERSION_ERROR = -6;
  
  /* The deflate compression method */
  var Z_DEFLATED  = 8;
  
  
  /* STATES ====================================================================*/
  /* ===========================================================================*/
  
  
  var    HEAD = 1;       /* i: waiting for magic header */
  var    FLAGS = 2;      /* i: waiting for method and flags (gzip) */
  var    TIME = 3;       /* i: waiting for modification time (gzip) */
  var    OS = 4;         /* i: waiting for extra flags and operating system (gzip) */
  var    EXLEN = 5;      /* i: waiting for extra length (gzip) */
  var    EXTRA = 6;      /* i: waiting for extra bytes (gzip) */
  var    NAME = 7;       /* i: waiting for end of file name (gzip) */
  var    COMMENT = 8;    /* i: waiting for end of comment (gzip) */
  var    HCRC = 9;       /* i: waiting for header crc (gzip) */
  var    DICTID = 10;    /* i: waiting for dictionary check value */
  var    DICT = 11;      /* waiting for inflateSetDictionary() call */
  var        TYPE = 12;      /* i: waiting for type bits, including last-flag bit */
  var        TYPEDO = 13;    /* i: same, but skip check to exit inflate on new block */
  var        STORED = 14;    /* i: waiting for stored size (length and complement) */
  var        COPY_ = 15;     /* i/o: same as COPY below, but only first time in */
  var        COPY = 16;      /* i/o: waiting for input or output to copy stored block */
  var        TABLE = 17;     /* i: waiting for dynamic block table lengths */
  var        LENLENS = 18;   /* i: waiting for code length code lengths */
  var        CODELENS = 19;  /* i: waiting for length/lit and distance code lengths */
  var            LEN_ = 20;      /* i: same as LEN below, but only first time in */
  var            LEN = 21;       /* i: waiting for length/lit/eob code */
  var            LENEXT = 22;    /* i: waiting for length extra bits */
  var            DIST = 23;      /* i: waiting for distance code */
  var            DISTEXT = 24;   /* i: waiting for distance extra bits */
  var            MATCH = 25;     /* o: waiting for output space to copy string */
  var            LIT = 26;       /* o: waiting for output space to write literal */
  var    CHECK = 27;     /* i: waiting for 32-bit check value */
  var    LENGTH = 28;    /* i: waiting for 32-bit length (gzip) */
  var    DONE = 29;      /* finished check, done -- remain here until reset */
  var    BAD = 30;       /* got a data error -- remain here until reset */
  var    MEM = 31;       /* got an inflate() memory error -- remain here until reset */
  var    SYNC = 32;      /* looking for synchronization bytes to restart inflate() */
  
  /* ===========================================================================*/
  
  
  
  var ENOUGH_LENS = 852;
  var ENOUGH_DISTS = 592;
  //var ENOUGH =  (ENOUGH_LENS+ENOUGH_DISTS);
  
  var MAX_WBITS = 15;
  /* 32K LZ77 window */
  var DEF_WBITS = MAX_WBITS;
  
  
  function zswap32(q) {
    return  (((q >>> 24) & 0xff) +
            ((q >>> 8) & 0xff00) +
            ((q & 0xff00) << 8) +
            ((q & 0xff) << 24));
  }
  
  
  function InflateState() {
    this.mode = 0;             /* current inflate mode */
    this.last = false;          /* true if processing last block */
    this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip */
    this.havedict = false;      /* true if dictionary provided */
    this.flags = 0;             /* gzip header method and flags (0 if zlib) */
    this.dmax = 0;              /* zlib header max distance (INFLATE_STRICT) */
    this.check = 0;             /* protected copy of check value */
    this.total = 0;             /* protected copy of output count */
    // TODO: may be {}
    this.head = null;           /* where to save gzip header information */
  
    /* sliding window */
    this.wbits = 0;             /* log base 2 of requested window size */
    this.wsize = 0;             /* window size or zero if not using window */
    this.whave = 0;             /* valid bytes in the window */
    this.wnext = 0;             /* window write index */
    this.window = null;         /* allocated sliding window, if needed */
  
    /* bit accumulator */
    this.hold = 0;              /* input bit accumulator */
    this.bits = 0;              /* number of bits in "in" */
  
    /* for string and stored block copying */
    this.length = 0;            /* literal or length of data to copy */
    this.offset = 0;            /* distance back to copy string from */
  
    /* for table and code decoding */
    this.extra = 0;             /* extra bits needed */
  
    /* fixed and dynamic code tables */
    this.lencode = null;          /* starting table for length/literal codes */
    this.distcode = null;         /* starting table for distance codes */
    this.lenbits = 0;           /* index bits for lencode */
    this.distbits = 0;          /* index bits for distcode */
  
    /* dynamic table building */
    this.ncode = 0;             /* number of code length code lengths */
    this.nlen = 0;              /* number of length code lengths */
    this.ndist = 0;             /* number of distance code lengths */
    this.have = 0;              /* number of code lengths in lens[] */
    this.next = null;              /* next available space in codes[] */
  
    this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
    this.work = new utils.Buf16(288); /* work area for code table building */
  
    /*
     because we don't have pointers in js, we use lencode and distcode directly
     as buffers so we don't need codes
    */
    //this.codes = new utils.Buf32(ENOUGH);       /* space for code tables */
    this.lendyn = null;              /* dynamic table for length/literal codes (JS specific) */
    this.distdyn = null;             /* dynamic table for distance codes (JS specific) */
    this.sane = 0;                   /* if false, allow invalid distance too far */
    this.back = 0;                   /* bits back of last unprocessed length/lit */
    this.was = 0;                    /* initial length of match */
  }
  
  function inflateResetKeep(strm) {
    var state;
  
    if (!strm || !strm.state) { return Z_STREAM_ERROR; }
    state = strm.state;
    strm.total_in = strm.total_out = state.total = 0;
    strm.msg = ''; /*Z_NULL*/
    if (state.wrap) {       /* to support ill-conceived Java test suite */
      strm.adler = state.wrap & 1;
    }
    state.mode = HEAD;
    state.last = 0;
    state.havedict = 0;
    state.dmax = 32768;
    state.head = null/*Z_NULL*/;
    state.hold = 0;
    state.bits = 0;
    //state.lencode = state.distcode = state.next = state.codes;
    state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
    state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  
    state.sane = 1;
    state.back = -1;
    //Tracev((stderr, "inflate: reset\n"));
    return Z_OK;
  }
  
  function inflateReset(strm) {
    var state;
  
    if (!strm || !strm.state) { return Z_STREAM_ERROR; }
    state = strm.state;
    state.wsize = 0;
    state.whave = 0;
    state.wnext = 0;
    return inflateResetKeep(strm);
  
  }
  
  function inflateReset2(strm, windowBits) {
    var wrap;
    var state;
  
    /* get the state */
    if (!strm || !strm.state) { return Z_STREAM_ERROR; }
    state = strm.state;
  
    /* extract wrap request from windowBits parameter */
    if (windowBits < 0) {
      wrap = 0;
      windowBits = -windowBits;
    }
    else {
      wrap = (windowBits >> 4) + 1;
      if (windowBits < 48) {
        windowBits &= 15;
      }
    }
  
    /* set number of window bits, free window if different */
    if (windowBits && (windowBits < 8 || windowBits > 15)) {
      return Z_STREAM_ERROR;
    }
    if (state.window !== null && state.wbits !== windowBits) {
      state.window = null;
    }
  
    /* update state and reset the rest of it */
    state.wrap = wrap;
    state.wbits = windowBits;
    return inflateReset(strm);
  }
  
  function inflateInit2(strm, windowBits) {
    var ret;
    var state;
  
    if (!strm) { return Z_STREAM_ERROR; }
    //strm.msg = Z_NULL;                 /* in case we return an error */
  
    state = new InflateState();
  
    //if (state === Z_NULL) return Z_MEM_ERROR;
    //Tracev((stderr, "inflate: allocated\n"));
    strm.state = state;
    state.window = null/*Z_NULL*/;
    ret = inflateReset2(strm, windowBits);
    if (ret !== Z_OK) {
      strm.state = null/*Z_NULL*/;
    }
    return ret;
  }
  
  function inflateInit(strm) {
    return inflateInit2(strm, DEF_WBITS);
  }
  
  
  /*
   Return state with length and distance decoding tables and index sizes set to
   fixed code decoding.  Normally this returns fixed tables from inffixed.h.
   If BUILDFIXED is defined, then instead this routine builds the tables the
   first time it's called, and returns those tables the first time and
   thereafter.  This reduces the size of the code by about 2K bytes, in
   exchange for a little execution time.  However, BUILDFIXED should not be
   used for threaded applications, since the rewriting of the tables and virgin
   may not be thread-safe.
   */
  var virgin = true;
  
  var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  
  function fixedtables(state) {
    /* build fixed huffman tables if first call (may not be thread safe) */
    if (virgin) {
      var sym;
  
      lenfix = new utils.Buf32(512);
      distfix = new utils.Buf32(32);
  
      /* literal/length table */
      sym = 0;
      while (sym < 144) { state.lens[sym++] = 8; }
      while (sym < 256) { state.lens[sym++] = 9; }
      while (sym < 280) { state.lens[sym++] = 7; }
      while (sym < 288) { state.lens[sym++] = 8; }
  
      inflate_table(LENS,  state.lens, 0, 288, lenfix,   0, state.work, { bits: 9 });
  
      /* distance table */
      sym = 0;
      while (sym < 32) { state.lens[sym++] = 5; }
  
      inflate_table(DISTS, state.lens, 0, 32,   distfix, 0, state.work, { bits: 5 });
  
      /* do this just once */
      virgin = false;
    }
  
    state.lencode = lenfix;
    state.lenbits = 9;
    state.distcode = distfix;
    state.distbits = 5;
  }
  
  
  /*
   Update the window with the last wsize (normally 32K) bytes written before
   returning.  If window does not exist yet, create it.  This is only called
   when a window is already in use, or when output has been written during this
   inflate call, but the end of the deflate stream has not been reached yet.
   It is also called to create a window for dictionary data when a dictionary
   is loaded.
  
   Providing output buffers larger than 32K to inflate() should provide a speed
   advantage, since only the last 32K of output is copied to the sliding window
   upon return from inflate(), and since all distances after the first 32K of
   output will fall in the output data, making match copies simpler and faster.
   The advantage may be dependent on the size of the processor's data caches.
   */
  function updatewindow(strm, src, end, copy) {
    var dist;
    var state = strm.state;
  
    /* if it hasn't been done already, allocate space for the window */
    if (state.window === null) {
      state.wsize = 1 << state.wbits;
      state.wnext = 0;
      state.whave = 0;
  
      state.window = new utils.Buf8(state.wsize);
    }
  
    /* copy state->wsize or less output bytes into the circular window */
    if (copy >= state.wsize) {
      utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
      state.wnext = 0;
      state.whave = state.wsize;
    }
    else {
      dist = state.wsize - state.wnext;
      if (dist > copy) {
        dist = copy;
      }
      //zmemcpy(state->window + state->wnext, end - copy, dist);
      utils.arraySet(state.window, src, end - copy, dist, state.wnext);
      copy -= dist;
      if (copy) {
        //zmemcpy(state->window, end - copy, copy);
        utils.arraySet(state.window, src, end - copy, copy, 0);
        state.wnext = copy;
        state.whave = state.wsize;
      }
      else {
        state.wnext += dist;
        if (state.wnext === state.wsize) { state.wnext = 0; }
        if (state.whave < state.wsize) { state.whave += dist; }
      }
    }
    return 0;
  }
  
  function inflate(strm, flush) {
    var state;
    var input, output;          // input/output buffers
    var next;                   /* next input INDEX */
    var put;                    /* next output INDEX */
    var have, left;             /* available input and output */
    var hold;                   /* bit buffer */
    var bits;                   /* bits in bit buffer */
    var _in, _out;              /* save starting available input and output */
    var copy;                   /* number of stored or match bytes to copy */
    var from;                   /* where to copy match bytes from */
    var from_source;
    var here = 0;               /* current decoding table entry */
    var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
    //var last;                   /* parent table entry */
    var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
    var len;                    /* length to copy for repeats, bits to drop */
    var ret;                    /* return code */
    var hbuf = new utils.Buf8(4);    /* buffer for gzip header crc calculation */
    var opts;
  
    var n; // temporary var for NEED_BITS
  
    var order = /* permutation of code lengths */
      [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
  
  
    if (!strm || !strm.state || !strm.output ||
        (!strm.input && strm.avail_in !== 0)) {
      return Z_STREAM_ERROR;
    }
  
    state = strm.state;
    if (state.mode === TYPE) { state.mode = TYPEDO; }    /* skip check */
  
  
    //--- LOAD() ---
    put = strm.next_out;
    output = strm.output;
    left = strm.avail_out;
    next = strm.next_in;
    input = strm.input;
    have = strm.avail_in;
    hold = state.hold;
    bits = state.bits;
    //---
  
    _in = have;
    _out = left;
    ret = Z_OK;
  
    inf_leave: // goto emulation
    for (;;) {
      switch (state.mode) {
      case HEAD:
        if (state.wrap === 0) {
          state.mode = TYPEDO;
          break;
        }
        //=== NEEDBITS(16);
        while (bits < 16) {
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
        }
        //===//
        if ((state.wrap & 2) && hold === 0x8b1f) {  /* gzip header */
          state.check = 0/*crc32(0L, Z_NULL, 0)*/;
          //=== CRC2(state.check, hold);
          hbuf[0] = hold & 0xff;
          hbuf[1] = (hold >>> 8) & 0xff;
          state.check = crc32(state.check, hbuf, 2, 0);
          //===//
  
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
          state.mode = FLAGS;
          break;
        }
        state.flags = 0;           /* expect zlib header */
        if (state.head) {
          state.head.done = false;
        }
        if (!(state.wrap & 1) ||   /* check if zlib header allowed */
          (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
          strm.msg = 'incorrect header check';
          state.mode = BAD;
          break;
        }
        if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
          strm.msg = 'unknown compression method';
          state.mode = BAD;
          break;
        }
        //--- DROPBITS(4) ---//
        hold >>>= 4;
        bits -= 4;
        //---//
        len = (hold & 0x0f)/*BITS(4)*/ + 8;
        if (state.wbits === 0) {
          state.wbits = len;
        }
        else if (len > state.wbits) {
          strm.msg = 'invalid window size';
          state.mode = BAD;
          break;
        }
        state.dmax = 1 << len;
        //Tracev((stderr, "inflate:   zlib header ok\n"));
        strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
        state.mode = hold & 0x200 ? DICTID : TYPE;
        //=== INITBITS();
        hold = 0;
        bits = 0;
        //===//
        break;
      case FLAGS:
        //=== NEEDBITS(16); */
        while (bits < 16) {
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
        }
        //===//
        state.flags = hold;
        if ((state.flags & 0xff) !== Z_DEFLATED) {
          strm.msg = 'unknown compression method';
          state.mode = BAD;
          break;
        }
        if (state.flags & 0xe000) {
          strm.msg = 'unknown header flags set';
          state.mode = BAD;
          break;
        }
        if (state.head) {
          state.head.text = ((hold >> 8) & 1);
        }
        if (state.flags & 0x0200) {
          //=== CRC2(state.check, hold);
          hbuf[0] = hold & 0xff;
          hbuf[1] = (hold >>> 8) & 0xff;
          state.check = crc32(state.check, hbuf, 2, 0);
          //===//
        }
        //=== INITBITS();
        hold = 0;
        bits = 0;
        //===//
        state.mode = TIME;
        /* falls through */
      case TIME:
        //=== NEEDBITS(32); */
        while (bits < 32) {
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
        }
        //===//
        if (state.head) {
          state.head.time = hold;
        }
        if (state.flags & 0x0200) {
          //=== CRC4(state.check, hold)
          hbuf[0] = hold & 0xff;
          hbuf[1] = (hold >>> 8) & 0xff;
          hbuf[2] = (hold >>> 16) & 0xff;
          hbuf[3] = (hold >>> 24) & 0xff;
          state.check = crc32(state.check, hbuf, 4, 0);
          //===
        }
        //=== INITBITS();
        hold = 0;
        bits = 0;
        //===//
        state.mode = OS;
        /* falls through */
      case OS:
        //=== NEEDBITS(16); */
        while (bits < 16) {
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
        }
        //===//
        if (state.head) {
          state.head.xflags = (hold & 0xff);
          state.head.os = (hold >> 8);
        }
        if (state.flags & 0x0200) {
          //=== CRC2(state.check, hold);
          hbuf[0] = hold & 0xff;
          hbuf[1] = (hold >>> 8) & 0xff;
          state.check = crc32(state.check, hbuf, 2, 0);
          //===//
        }
        //=== INITBITS();
        hold = 0;
        bits = 0;
        //===//
        state.mode = EXLEN;
        /* falls through */
      case EXLEN:
        if (state.flags & 0x0400) {
          //=== NEEDBITS(16); */
          while (bits < 16) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          state.length = hold;
          if (state.head) {
            state.head.extra_len = hold;
          }
          if (state.flags & 0x0200) {
            //=== CRC2(state.check, hold);
            hbuf[0] = hold & 0xff;
            hbuf[1] = (hold >>> 8) & 0xff;
            state.check = crc32(state.check, hbuf, 2, 0);
            //===//
          }
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
        }
        else if (state.head) {
          state.head.extra = null/*Z_NULL*/;
        }
        state.mode = EXTRA;
        /* falls through */
      case EXTRA:
        if (state.flags & 0x0400) {
          copy = state.length;
          if (copy > have) { copy = have; }
          if (copy) {
            if (state.head) {
              len = state.head.extra_len - state.length;
              if (!state.head.extra) {
                // Use untyped array for more conveniend processing later
                state.head.extra = new Array(state.head.extra_len);
              }
              utils.arraySet(
                state.head.extra,
                input,
                next,
                // extra field is limited to 65536 bytes
                // - no need for additional size check
                copy,
                /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
                len
              );
              //zmemcpy(state.head.extra + len, next,
              //        len + copy > state.head.extra_max ?
              //        state.head.extra_max - len : copy);
            }
            if (state.flags & 0x0200) {
              state.check = crc32(state.check, input, copy, next);
            }
            have -= copy;
            next += copy;
            state.length -= copy;
          }
          if (state.length) { break inf_leave; }
        }
        state.length = 0;
        state.mode = NAME;
        /* falls through */
      case NAME:
        if (state.flags & 0x0800) {
          if (have === 0) { break inf_leave; }
          copy = 0;
          do {
            // TODO: 2 or 1 bytes?
            len = input[next + copy++];
            /* use constant limit because in js we should not preallocate memory */
            if (state.head && len &&
                (state.length < 65536 /*state.head.name_max*/)) {
              state.head.name += String.fromCharCode(len);
            }
          } while (len && copy < have);
  
          if (state.flags & 0x0200) {
            state.check = crc32(state.check, input, copy, next);
          }
          have -= copy;
          next += copy;
          if (len) { break inf_leave; }
        }
        else if (state.head) {
          state.head.name = null;
        }
        state.length = 0;
        state.mode = COMMENT;
        /* falls through */
      case COMMENT:
        if (state.flags & 0x1000) {
          if (have === 0) { break inf_leave; }
          copy = 0;
          do {
            len = input[next + copy++];
            /* use constant limit because in js we should not preallocate memory */
            if (state.head && len &&
                (state.length < 65536 /*state.head.comm_max*/)) {
              state.head.comment += String.fromCharCode(len);
            }
          } while (len && copy < have);
          if (state.flags & 0x0200) {
            state.check = crc32(state.check, input, copy, next);
          }
          have -= copy;
          next += copy;
          if (len) { break inf_leave; }
        }
        else if (state.head) {
          state.head.comment = null;
        }
        state.mode = HCRC;
        /* falls through */
      case HCRC:
        if (state.flags & 0x0200) {
          //=== NEEDBITS(16); */
          while (bits < 16) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          if (hold !== (state.check & 0xffff)) {
            strm.msg = 'header crc mismatch';
            state.mode = BAD;
            break;
          }
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
        }
        if (state.head) {
          state.head.hcrc = ((state.flags >> 9) & 1);
          state.head.done = true;
        }
        strm.adler = state.check = 0;
        state.mode = TYPE;
        break;
      case DICTID:
        //=== NEEDBITS(32); */
        while (bits < 32) {
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
        }
        //===//
        strm.adler = state.check = zswap32(hold);
        //=== INITBITS();
        hold = 0;
        bits = 0;
        //===//
        state.mode = DICT;
        /* falls through */
      case DICT:
        if (state.havedict === 0) {
          //--- RESTORE() ---
          strm.next_out = put;
          strm.avail_out = left;
          strm.next_in = next;
          strm.avail_in = have;
          state.hold = hold;
          state.bits = bits;
          //---
          return Z_NEED_DICT;
        }
        strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
        state.mode = TYPE;
        /* falls through */
      case TYPE:
        if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
        /* falls through */
      case TYPEDO:
        if (state.last) {
          //--- BYTEBITS() ---//
          hold >>>= bits & 7;
          bits -= bits & 7;
          //---//
          state.mode = CHECK;
          break;
        }
        //=== NEEDBITS(3); */
        while (bits < 3) {
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
        }
        //===//
        state.last = (hold & 0x01)/*BITS(1)*/;
        //--- DROPBITS(1) ---//
        hold >>>= 1;
        bits -= 1;
        //---//
  
        switch ((hold & 0x03)/*BITS(2)*/) {
        case 0:                             /* stored block */
          //Tracev((stderr, "inflate:     stored block%s\n",
          //        state.last ? " (last)" : ""));
          state.mode = STORED;
          break;
        case 1:                             /* fixed block */
          fixedtables(state);
          //Tracev((stderr, "inflate:     fixed codes block%s\n",
          //        state.last ? " (last)" : ""));
          state.mode = LEN_;             /* decode codes */
          if (flush === Z_TREES) {
            //--- DROPBITS(2) ---//
            hold >>>= 2;
            bits -= 2;
            //---//
            break inf_leave;
          }
          break;
        case 2:                             /* dynamic block */
          //Tracev((stderr, "inflate:     dynamic codes block%s\n",
          //        state.last ? " (last)" : ""));
          state.mode = TABLE;
          break;
        case 3:
          strm.msg = 'invalid block type';
          state.mode = BAD;
        }
        //--- DROPBITS(2) ---//
        hold >>>= 2;
        bits -= 2;
        //---//
        break;
      case STORED:
        //--- BYTEBITS() ---// /* go to byte boundary */
        hold >>>= bits & 7;
        bits -= bits & 7;
        //---//
        //=== NEEDBITS(32); */
        while (bits < 32) {
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
        }
        //===//
        if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
          strm.msg = 'invalid stored block lengths';
          state.mode = BAD;
          break;
        }
        state.length = hold & 0xffff;
        //Tracev((stderr, "inflate:       stored length %u\n",
        //        state.length));
        //=== INITBITS();
        hold = 0;
        bits = 0;
        //===//
        state.mode = COPY_;
        if (flush === Z_TREES) { break inf_leave; }
        /* falls through */
      case COPY_:
        state.mode = COPY;
        /* falls through */
      case COPY:
        copy = state.length;
        if (copy) {
          if (copy > have) { copy = have; }
          if (copy > left) { copy = left; }
          if (copy === 0) { break inf_leave; }
          //--- zmemcpy(put, next, copy); ---
          utils.arraySet(output, input, next, copy, put);
          //---//
          have -= copy;
          next += copy;
          left -= copy;
          put += copy;
          state.length -= copy;
          break;
        }
        //Tracev((stderr, "inflate:       stored end\n"));
        state.mode = TYPE;
        break;
      case TABLE:
        //=== NEEDBITS(14); */
        while (bits < 14) {
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
        }
        //===//
        state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
        //--- DROPBITS(5) ---//
        hold >>>= 5;
        bits -= 5;
        //---//
        state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
        //--- DROPBITS(5) ---//
        hold >>>= 5;
        bits -= 5;
        //---//
        state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
        //--- DROPBITS(4) ---//
        hold >>>= 4;
        bits -= 4;
        //---//
  //#ifndef PKZIP_BUG_WORKAROUND
        if (state.nlen > 286 || state.ndist > 30) {
          strm.msg = 'too many length or distance symbols';
          state.mode = BAD;
          break;
        }
  //#endif
        //Tracev((stderr, "inflate:       table sizes ok\n"));
        state.have = 0;
        state.mode = LENLENS;
        /* falls through */
      case LENLENS:
        while (state.have < state.ncode) {
          //=== NEEDBITS(3);
          while (bits < 3) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
          //--- DROPBITS(3) ---//
          hold >>>= 3;
          bits -= 3;
          //---//
        }
        while (state.have < 19) {
          state.lens[order[state.have++]] = 0;
        }
        // We have separate tables & no pointers. 2 commented lines below not needed.
        //state.next = state.codes;
        //state.lencode = state.next;
        // Switch to use dynamic table
        state.lencode = state.lendyn;
        state.lenbits = 7;
  
        opts = { bits: state.lenbits };
        ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
        state.lenbits = opts.bits;
  
        if (ret) {
          strm.msg = 'invalid code lengths set';
          state.mode = BAD;
          break;
        }
        //Tracev((stderr, "inflate:       code lengths ok\n"));
        state.have = 0;
        state.mode = CODELENS;
        /* falls through */
      case CODELENS:
        while (state.have < state.nlen + state.ndist) {
          for (;;) {
            here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
            here_bits = here >>> 24;
            here_op = (here >>> 16) & 0xff;
            here_val = here & 0xffff;
  
            if ((here_bits) <= bits) { break; }
            //--- PULLBYTE() ---//
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
            //---//
          }
          if (here_val < 16) {
            //--- DROPBITS(here.bits) ---//
            hold >>>= here_bits;
            bits -= here_bits;
            //---//
            state.lens[state.have++] = here_val;
          }
          else {
            if (here_val === 16) {
              //=== NEEDBITS(here.bits + 2);
              n = here_bits + 2;
              while (bits < n) {
                if (have === 0) { break inf_leave; }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              //===//
              //--- DROPBITS(here.bits) ---//
              hold >>>= here_bits;
              bits -= here_bits;
              //---//
              if (state.have === 0) {
                strm.msg = 'invalid bit length repeat';
                state.mode = BAD;
                break;
              }
              len = state.lens[state.have - 1];
              copy = 3 + (hold & 0x03);//BITS(2);
              //--- DROPBITS(2) ---//
              hold >>>= 2;
              bits -= 2;
              //---//
            }
            else if (here_val === 17) {
              //=== NEEDBITS(here.bits + 3);
              n = here_bits + 3;
              while (bits < n) {
                if (have === 0) { break inf_leave; }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              //===//
              //--- DROPBITS(here.bits) ---//
              hold >>>= here_bits;
              bits -= here_bits;
              //---//
              len = 0;
              copy = 3 + (hold & 0x07);//BITS(3);
              //--- DROPBITS(3) ---//
              hold >>>= 3;
              bits -= 3;
              //---//
            }
            else {
              //=== NEEDBITS(here.bits + 7);
              n = here_bits + 7;
              while (bits < n) {
                if (have === 0) { break inf_leave; }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              //===//
              //--- DROPBITS(here.bits) ---//
              hold >>>= here_bits;
              bits -= here_bits;
              //---//
              len = 0;
              copy = 11 + (hold & 0x7f);//BITS(7);
              //--- DROPBITS(7) ---//
              hold >>>= 7;
              bits -= 7;
              //---//
            }
            if (state.have + copy > state.nlen + state.ndist) {
              strm.msg = 'invalid bit length repeat';
              state.mode = BAD;
              break;
            }
            while (copy--) {
              state.lens[state.have++] = len;
            }
          }
        }
  
        /* handle error breaks in while */
        if (state.mode === BAD) { break; }
  
        /* check for end-of-block code (better have one) */
        if (state.lens[256] === 0) {
          strm.msg = 'invalid code -- missing end-of-block';
          state.mode = BAD;
          break;
        }
  
        /* build code tables -- note: do not change the lenbits or distbits
           values here (9 and 6) without reading the comments in inftrees.h
           concerning the ENOUGH constants, which depend on those values */
        state.lenbits = 9;
  
        opts = { bits: state.lenbits };
        ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
        // We have separate tables & no pointers. 2 commented lines below not needed.
        // state.next_index = opts.table_index;
        state.lenbits = opts.bits;
        // state.lencode = state.next;
  
        if (ret) {
          strm.msg = 'invalid literal/lengths set';
          state.mode = BAD;
          break;
        }
  
        state.distbits = 6;
        //state.distcode.copy(state.codes);
        // Switch to use dynamic table
        state.distcode = state.distdyn;
        opts = { bits: state.distbits };
        ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
        // We have separate tables & no pointers. 2 commented lines below not needed.
        // state.next_index = opts.table_index;
        state.distbits = opts.bits;
        // state.distcode = state.next;
  
        if (ret) {
          strm.msg = 'invalid distances set';
          state.mode = BAD;
          break;
        }
        //Tracev((stderr, 'inflate:       codes ok\n'));
        state.mode = LEN_;
        if (flush === Z_TREES) { break inf_leave; }
        /* falls through */
      case LEN_:
        state.mode = LEN;
        /* falls through */
      case LEN:
        if (have >= 6 && left >= 258) {
          //--- RESTORE() ---
          strm.next_out = put;
          strm.avail_out = left;
          strm.next_in = next;
          strm.avail_in = have;
          state.hold = hold;
          state.bits = bits;
          //---
          inflate_fast(strm, _out);
          //--- LOAD() ---
          put = strm.next_out;
          output = strm.output;
          left = strm.avail_out;
          next = strm.next_in;
          input = strm.input;
          have = strm.avail_in;
          hold = state.hold;
          bits = state.bits;
          //---
  
          if (state.mode === TYPE) {
            state.back = -1;
          }
          break;
        }
        state.back = 0;
        for (;;) {
          here = state.lencode[hold & ((1 << state.lenbits) - 1)];  /*BITS(state.lenbits)*/
          here_bits = here >>> 24;
          here_op = (here >>> 16) & 0xff;
          here_val = here & 0xffff;
  
          if (here_bits <= bits) { break; }
          //--- PULLBYTE() ---//
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
          //---//
        }
        if (here_op && (here_op & 0xf0) === 0) {
          last_bits = here_bits;
          last_op = here_op;
          last_val = here_val;
          for (;;) {
            here = state.lencode[last_val +
                    ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
            here_bits = here >>> 24;
            here_op = (here >>> 16) & 0xff;
            here_val = here & 0xffff;
  
            if ((last_bits + here_bits) <= bits) { break; }
            //--- PULLBYTE() ---//
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
            //---//
          }
          //--- DROPBITS(last.bits) ---//
          hold >>>= last_bits;
          bits -= last_bits;
          //---//
          state.back += last_bits;
        }
        //--- DROPBITS(here.bits) ---//
        hold >>>= here_bits;
        bits -= here_bits;
        //---//
        state.back += here_bits;
        state.length = here_val;
        if (here_op === 0) {
          //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
          //        "inflate:         literal '%c'\n" :
          //        "inflate:         literal 0x%02x\n", here.val));
          state.mode = LIT;
          break;
        }
        if (here_op & 32) {
          //Tracevv((stderr, "inflate:         end of block\n"));
          state.back = -1;
          state.mode = TYPE;
          break;
        }
        if (here_op & 64) {
          strm.msg = 'invalid literal/length code';
          state.mode = BAD;
          break;
        }
        state.extra = here_op & 15;
        state.mode = LENEXT;
        /* falls through */
      case LENEXT:
        if (state.extra) {
          //=== NEEDBITS(state.extra);
          n = state.extra;
          while (bits < n) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
          //--- DROPBITS(state.extra) ---//
          hold >>>= state.extra;
          bits -= state.extra;
          //---//
          state.back += state.extra;
        }
        //Tracevv((stderr, "inflate:         length %u\n", state.length));
        state.was = state.length;
        state.mode = DIST;
        /* falls through */
      case DIST:
        for (;;) {
          here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
          here_bits = here >>> 24;
          here_op = (here >>> 16) & 0xff;
          here_val = here & 0xffff;
  
          if ((here_bits) <= bits) { break; }
          //--- PULLBYTE() ---//
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
          //---//
        }
        if ((here_op & 0xf0) === 0) {
          last_bits = here_bits;
          last_op = here_op;
          last_val = here_val;
          for (;;) {
            here = state.distcode[last_val +
                    ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
            here_bits = here >>> 24;
            here_op = (here >>> 16) & 0xff;
            here_val = here & 0xffff;
  
            if ((last_bits + here_bits) <= bits) { break; }
            //--- PULLBYTE() ---//
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
            //---//
          }
          //--- DROPBITS(last.bits) ---//
          hold >>>= last_bits;
          bits -= last_bits;
          //---//
          state.back += last_bits;
        }
        //--- DROPBITS(here.bits) ---//
        hold >>>= here_bits;
        bits -= here_bits;
        //---//
        state.back += here_bits;
        if (here_op & 64) {
          strm.msg = 'invalid distance code';
          state.mode = BAD;
          break;
        }
        state.offset = here_val;
        state.extra = (here_op) & 15;
        state.mode = DISTEXT;
        /* falls through */
      case DISTEXT:
        if (state.extra) {
          //=== NEEDBITS(state.extra);
          n = state.extra;
          while (bits < n) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
          //--- DROPBITS(state.extra) ---//
          hold >>>= state.extra;
          bits -= state.extra;
          //---//
          state.back += state.extra;
        }
  //#ifdef INFLATE_STRICT
        if (state.offset > state.dmax) {
          strm.msg = 'invalid distance too far back';
          state.mode = BAD;
          break;
        }
  //#endif
        //Tracevv((stderr, "inflate:         distance %u\n", state.offset));
        state.mode = MATCH;
        /* falls through */
      case MATCH:
        if (left === 0) { break inf_leave; }
        copy = _out - left;
        if (state.offset > copy) {         /* copy from window */
          copy = state.offset - copy;
          if (copy > state.whave) {
            if (state.sane) {
              strm.msg = 'invalid distance too far back';
              state.mode = BAD;
              break;
            }
  // (!) This block is disabled in zlib defailts,
  // 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 '|' insdead of '+' to make sure that result is signed
            hold |= input[next++] << bits;
            bits += 8;
          }
          //===//
          _out -= left;
          strm.total_out += _out;
          state.total += _out;
          if (_out) {
            strm.adler = state.check =
                /*UPDATE(state.check, put - _out, _out);*/
                (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  
          }
          _out = left;
          // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
          if ((state.flags ? hold : zswap32(hold)) !== state.check) {
            strm.msg = 'incorrect data check';
            state.mode = BAD;
            break;
          }
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
          //Tracev((stderr, "inflate:   check matches trailer\n"));
        }
        state.mode = LENGTH;
        /* falls through */
      case LENGTH:
        if (state.wrap && state.flags) {
          //=== NEEDBITS(32);
          while (bits < 32) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          if (hold !== (state.total & 0xffffffff)) {
            strm.msg = 'incorrect length check';
            state.mode = BAD;
            break;
          }
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
          //Tracev((stderr, "inflate:   length matches trailer\n"));
        }
        state.mode = DONE;
        /* falls through */
      case DONE:
        ret = Z_STREAM_END;
        break inf_leave;
      case BAD:
        ret = Z_DATA_ERROR;
        break inf_leave;
      case MEM:
        return Z_MEM_ERROR;
      case SYNC:
        /* falls through */
      default:
        return Z_STREAM_ERROR;
      }
    }
  
    // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  
    /*
       Return from inflate(), updating the total counts and the check value.
       If there was no progress during the inflate() call, return a buffer
       error.  Call updatewindow() to create and/or update the window state.
       Note: a memory error from inflate() is non-recoverable.
     */
  
    //--- RESTORE() ---
    strm.next_out = put;
    strm.avail_out = left;
    strm.next_in = next;
    strm.avail_in = have;
    state.hold = hold;
    state.bits = bits;
    //---
  
    if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
                        (state.mode < CHECK || flush !== Z_FINISH))) {
      if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
        state.mode = MEM;
        return Z_MEM_ERROR;
      }
    }
    _in -= strm.avail_in;
    _out -= strm.avail_out;
    strm.total_in += _in;
    strm.total_out += _out;
    state.total += _out;
    if (state.wrap && _out) {
      strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
        (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
    }
    strm.data_type = state.bits + (state.last ? 64 : 0) +
                      (state.mode === TYPE ? 128 : 0) +
                      (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
    if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
      ret = Z_BUF_ERROR;
    }
    return ret;
  }
  
  function inflateEnd(strm) {
  
    if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
      return Z_STREAM_ERROR;
    }
  
    var state = strm.state;
    if (state.window) {
      state.window = null;
    }
    strm.state = null;
    return Z_OK;
  }
  
  function inflateGetHeader(strm, head) {
    var state;
  
    /* check state */
    if (!strm || !strm.state) { return Z_STREAM_ERROR; }
    state = strm.state;
    if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  
    /* save header structure */
    state.head = head;
    head.done = false;
    return Z_OK;
  }
  
  function inflateSetDictionary(strm, dictionary) {
    var dictLength = dictionary.length;
  
    var state;
    var dictid;
    var ret;
  
    /* check state */
    if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
    state = strm.state;
  
    if (state.wrap !== 0 && state.mode !== DICT) {
      return Z_STREAM_ERROR;
    }
  
    /* check for correct dictionary identifier */
    if (state.mode === DICT) {
      dictid = 1; /* adler32(0, null, 0)*/
      /* dictid = adler32(dictid, dictionary, dictLength); */
      dictid = adler32(dictid, dictionary, dictLength, 0);
      if (dictid !== state.check) {
        return Z_DATA_ERROR;
      }
    }
    /* copy dictionary to window using updatewindow(), which will amend the
     existing dictionary if appropriate */
    ret = updatewindow(strm, dictionary, dictLength, dictLength);
    if (ret) {
      state.mode = MEM;
      return Z_MEM_ERROR;
    }
    state.havedict = 1;
    // Tracev((stderr, "inflate:   dictionary set\n"));
    return Z_OK;
  }
  
  exports.inflateReset = inflateReset;
  exports.inflateReset2 = inflateReset2;
  exports.inflateResetKeep = inflateResetKeep;
  exports.inflateInit = inflateInit;
  exports.inflateInit2 = inflateInit2;
  exports.inflate = inflate;
  exports.inflateEnd = inflateEnd;
  exports.inflateGetHeader = inflateGetHeader;
  exports.inflateSetDictionary = inflateSetDictionary;
  exports.inflateInfo = 'pako inflate (from Nodeca project)';
  
  /* Not implemented
  exports.inflateCopy = inflateCopy;
  exports.inflateGetDictionary = inflateGetDictionary;
  exports.inflateMark = inflateMark;
  exports.inflatePrime = inflatePrime;
  exports.inflateSync = inflateSync;
  exports.inflateSyncPoint = inflateSyncPoint;
  exports.inflateUndermine = inflateUndermine;
  */
  
  },{"../utils/common":70,"./adler32":72,"./crc32":74,"./inffast":77,"./inftrees":79}],79:[function(require,module,exports){
  'use strict';
  
  
  var utils = require('../utils/common');
  
  var MAXBITS = 15;
  var ENOUGH_LENS = 852;
  var ENOUGH_DISTS = 592;
  //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  
  var CODES = 0;
  var LENS = 1;
  var DISTS = 2;
  
  var lbase = [ /* Length codes 257..285 base */
    3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
    35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  ];
  
  var lext = [ /* Length codes 257..285 extra */
    16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
    19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  ];
  
  var dbase = [ /* Distance codes 0..29 base */
    1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
    257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
    8193, 12289, 16385, 24577, 0, 0
  ];
  
  var dext = [ /* Distance codes 0..29 extra */
    16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
    23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
    28, 28, 29, 29, 64, 64
  ];
  
  module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  {
    var bits = opts.bits;
        //here = opts.here; /* table entry for duplication */
  
    var len = 0;               /* a code's length in bits */
    var sym = 0;               /* index of code symbols */
    var min = 0, max = 0;          /* minimum and maximum code lengths */
    var root = 0;              /* number of index bits for root table */
    var curr = 0;              /* number of index bits for current table */
    var drop = 0;              /* code bits to drop for sub-table */
    var left = 0;                   /* number of prefix codes available */
    var used = 0;              /* code entries in table used */
    var huff = 0;              /* Huffman code */
    var incr;              /* for incrementing code, index */
    var fill;              /* index for replicating entries */
    var low;               /* low bits for current root entry */
    var mask;              /* mask for low root bits */
    var next;             /* next available space in table */
    var base = null;     /* base value table to use */
    var base_index = 0;
  //  var shoextra;    /* extra bits table to use */
    var end;                    /* use base and extra for symbol > end */
    var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1];    /* number of codes of each length */
    var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1];     /* offsets in table for each length */
    var extra = null;
    var extra_index = 0;
  
    var here_bits, here_op, here_val;
  
    /*
     Process a set of code lengths to create a canonical Huffman code.  The
     code lengths are lens[0..codes-1].  Each length corresponds to the
     symbols 0..codes-1.  The Huffman code is generated by first sorting the
     symbols by length from short to long, and retaining the symbol order
     for codes with equal lengths.  Then the code starts with all zero bits
     for the first code of the shortest length, and the codes are integer
     increments for the same length, and zeros are appended as the length
     increases.  For the deflate format, these bits are stored backwards
     from their more natural integer increment ordering, and so when the
     decoding tables are built in the large loop below, the integer codes
     are incremented backwards.
  
     This routine assumes, but does not check, that all of the entries in
     lens[] are in the range 0..MAXBITS.  The caller must assure this.
     1..MAXBITS is interpreted as that code length.  zero means that that
     symbol does not occur in this code.
  
     The codes are sorted by computing a count of codes for each length,
     creating from that a table of starting indices for each length in the
     sorted table, and then entering the symbols in order in the sorted
     table.  The sorted table is work[], with that space being provided by
     the caller.
  
     The length counts are used for other purposes as well, i.e. finding
     the minimum and maximum length codes, determining if there are any
     codes at all, checking for a valid set of lengths, and looking ahead
     at length counts to determine sub-table sizes when building the
     decoding tables.
     */
  
    /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
    for (len = 0; len <= MAXBITS; len++) {
      count[len] = 0;
    }
    for (sym = 0; sym < codes; sym++) {
      count[lens[lens_index + sym]]++;
    }
  
    /* bound code lengths, force root to be within code lengths */
    root = bits;
    for (max = MAXBITS; max >= 1; max--) {
      if (count[max] !== 0) { break; }
    }
    if (root > max) {
      root = max;
    }
    if (max === 0) {                     /* no symbols to code at all */
      //table.op[opts.table_index] = 64;  //here.op = (var char)64;    /* invalid code marker */
      //table.bits[opts.table_index] = 1;   //here.bits = (var char)1;
      //table.val[opts.table_index++] = 0;   //here.val = (var short)0;
      table[table_index++] = (1 << 24) | (64 << 16) | 0;
  
  
      //table.op[opts.table_index] = 64;
      //table.bits[opts.table_index] = 1;
      //table.val[opts.table_index++] = 0;
      table[table_index++] = (1 << 24) | (64 << 16) | 0;
  
      opts.bits = 1;
      return 0;     /* no symbols, but wait for decoding to report error */
    }
    for (min = 1; min < max; min++) {
      if (count[min] !== 0) { break; }
    }
    if (root < min) {
      root = min;
    }
  
    /* check for an over-subscribed or incomplete set of lengths */
    left = 1;
    for (len = 1; len <= MAXBITS; len++) {
      left <<= 1;
      left -= count[len];
      if (left < 0) {
        return -1;
      }        /* over-subscribed */
    }
    if (left > 0 && (type === CODES || max !== 1)) {
      return -1;                      /* incomplete set */
    }
  
    /* generate offsets into symbol table for each length for sorting */
    offs[1] = 0;
    for (len = 1; len < MAXBITS; len++) {
      offs[len + 1] = offs[len] + count[len];
    }
  
    /* sort symbols by length, by symbol order within each length */
    for (sym = 0; sym < codes; sym++) {
      if (lens[lens_index + sym] !== 0) {
        work[offs[lens[lens_index + sym]]++] = sym;
      }
    }
  
    /*
     Create and fill in decoding tables.  In this loop, the table being
     filled is at next and has curr index bits.  The code being used is huff
     with length len.  That code is converted to an index by dropping drop
     bits off of the bottom.  For codes where len is less than drop + curr,
     those top drop + curr - len bits are incremented through all values to
     fill the table with replicated entries.
  
     root is the number of index bits for the root table.  When len exceeds
     root, sub-tables are created pointed to by the root entry with an index
     of the low root bits of huff.  This is saved in low to check for when a
     new sub-table should be started.  drop is zero when the root table is
     being filled, and drop is root when sub-tables are being filled.
  
     When a new sub-table is needed, it is necessary to look ahead in the
     code lengths to determine what size sub-table is needed.  The length
     counts are used for this, and so count[] is decremented as codes are
     entered in the tables.
  
     used keeps track of how many table entries have been allocated from the
     provided *table space.  It is checked for LENS and DIST tables against
     the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
     the initial root table size constants.  See the comments in inftrees.h
     for more information.
  
     sym increments through all symbols, and the loop terminates when
     all codes of length max, i.e. all codes, have been processed.  This
     routine permits incomplete codes, so another loop after this one fills
     in the rest of the decoding tables with invalid code markers.
     */
  
    /* set up for code type */
    // poor man optimization - use if-else instead of switch,
    // to avoid deopts in old v8
    if (type === CODES) {
      base = extra = work;    /* dummy value--not used */
      end = 19;
  
    } else if (type === LENS) {
      base = lbase;
      base_index -= 257;
      extra = lext;
      extra_index -= 257;
      end = 256;
  
    } else {                    /* DISTS */
      base = dbase;
      extra = dext;
      end = -1;
    }
  
    /* initialize opts for loop */
    huff = 0;                   /* starting code */
    sym = 0;                    /* starting code symbol */
    len = min;                  /* starting code length */
    next = table_index;              /* current table to fill in */
    curr = root;                /* current table index bits */
    drop = 0;                   /* current bits to drop from code for index */
    low = -1;                   /* trigger new sub-table when len > root */
    used = 1 << root;          /* use root table entries */
    mask = used - 1;            /* mask for comparing low */
  
    /* check available table space */
    if ((type === LENS && used > ENOUGH_LENS) ||
      (type === DISTS && used > ENOUGH_DISTS)) {
      return 1;
    }
  
    var i = 0;
    /* process all codes and make table entries */
    for (;;) {
      i++;
      /* create table entry */
      here_bits = len - drop;
      if (work[sym] < end) {
        here_op = 0;
        here_val = work[sym];
      }
      else if (work[sym] > end) {
        here_op = extra[extra_index + work[sym]];
        here_val = base[base_index + work[sym]];
      }
      else {
        here_op = 32 + 64;         /* end of block */
        here_val = 0;
      }
  
      /* replicate for those indices with low len bits equal to huff */
      incr = 1 << (len - drop);
      fill = 1 << curr;
      min = fill;                 /* save offset to next table */
      do {
        fill -= incr;
        table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
      } while (fill !== 0);
  
      /* backwards increment the len-bit code huff */
      incr = 1 << (len - 1);
      while (huff & incr) {
        incr >>= 1;
      }
      if (incr !== 0) {
        huff &= incr - 1;
        huff += incr;
      } else {
        huff = 0;
      }
  
      /* go to next symbol, update count, len */
      sym++;
      if (--count[len] === 0) {
        if (len === max) { break; }
        len = lens[lens_index + work[sym]];
      }
  
      /* create new sub-table if needed */
      if (len > root && (huff & mask) !== low) {
        /* if first time, transition to sub-tables */
        if (drop === 0) {
          drop = root;
        }
  
        /* increment past last table */
        next += min;            /* here min is 1 << curr */
  
        /* determine length of next table */
        curr = len - drop;
        left = 1 << curr;
        while (curr + drop < max) {
          left -= count[curr + drop];
          if (left <= 0) { break; }
          curr++;
          left <<= 1;
        }
  
        /* check for enough space */
        used += 1 << curr;
        if ((type === LENS && used > ENOUGH_LENS) ||
          (type === DISTS && used > ENOUGH_DISTS)) {
          return 1;
        }
  
        /* point entry in root table to sub-table */
        low = huff & mask;
        /*table.op[low] = curr;
        table.bits[low] = root;
        table.val[low] = next - opts.table_index;*/
        table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
      }
    }
  
    /* fill in remaining table entry if code is incomplete (guaranteed to have
     at most one remaining entry, since if the code is incomplete, the
     maximum code length that was allowed to get this far is one bit) */
    if (huff !== 0) {
      //table.op[next + huff] = 64;            /* invalid code marker */
      //table.bits[next + huff] = len - drop;
      //table.val[next + huff] = 0;
      table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
    }
  
    /* set return parameters */
    //opts.table_index += used;
    opts.bits = root;
    return 0;
  };
  
  },{"../utils/common":70}],80:[function(require,module,exports){
  'use strict';
  
  module.exports = {
    2:      'need dictionary',     /* Z_NEED_DICT       2  */
    1:      'stream end',          /* Z_STREAM_END      1  */
    0:      '',                    /* Z_OK              0  */
    '-1':   'file error',          /* Z_ERRNO         (-1) */
    '-2':   'stream error',        /* Z_STREAM_ERROR  (-2) */
    '-3':   'data error',          /* Z_DATA_ERROR    (-3) */
    '-4':   'insufficient memory', /* Z_MEM_ERROR     (-4) */
    '-5':   'buffer error',        /* Z_BUF_ERROR     (-5) */
    '-6':   'incompatible version' /* Z_VERSION_ERROR (-6) */
  };
  
  },{}],81:[function(require,module,exports){
  'use strict';
  
  
  var utils = require('../utils/common');
  
  /* Public constants ==========================================================*/
  /* ===========================================================================*/
  
  
  //var Z_FILTERED          = 1;
  //var Z_HUFFMAN_ONLY      = 2;
  //var Z_RLE               = 3;
  var Z_FIXED               = 4;
  //var Z_DEFAULT_STRATEGY  = 0;
  
  /* Possible values of the data_type field (though see inflate()) */
  var Z_BINARY              = 0;
  var Z_TEXT                = 1;
  //var Z_ASCII             = 1; // = Z_TEXT
  var Z_UNKNOWN             = 2;
  
  /*============================================================================*/
  
  
  function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  
  // From zutil.h
  
  var STORED_BLOCK = 0;
  var STATIC_TREES = 1;
  var DYN_TREES    = 2;
  /* The three kinds of block type */
  
  var MIN_MATCH    = 3;
  var MAX_MATCH    = 258;
  /* The minimum and maximum match lengths */
  
  // From deflate.h
  /* ===========================================================================
   * Internal compression state.
   */
  
  var LENGTH_CODES  = 29;
  /* number of length codes, not counting the special END_BLOCK code */
  
  var LITERALS      = 256;
  /* number of literal bytes 0..255 */
  
  var L_CODES       = LITERALS + 1 + LENGTH_CODES;
  /* number of Literal or Length codes, including the END_BLOCK code */
  
  var D_CODES       = 30;
  /* number of distance codes */
  
  var BL_CODES      = 19;
  /* number of codes used to transfer the bit lengths */
  
  var HEAP_SIZE     = 2 * L_CODES + 1;
  /* maximum heap size */
  
  var MAX_BITS      = 15;
  /* All codes must not exceed MAX_BITS bits */
  
  var Buf_size      = 16;
  /* size of bit buffer in bi_buf */
  
  
  /* ===========================================================================
   * Constants
   */
  
  var MAX_BL_BITS = 7;
  /* Bit length codes must not exceed MAX_BL_BITS bits */
  
  var END_BLOCK   = 256;
  /* end of block literal code */
  
  var REP_3_6     = 16;
  /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  
  var REPZ_3_10   = 17;
  /* repeat a zero length 3-10 times  (3 bits of repeat count) */
  
  var REPZ_11_138 = 18;
  /* repeat a zero length 11-138 times  (7 bits of repeat count) */
  
  /* eslint-disable comma-spacing,array-bracket-spacing */
  var extra_lbits =   /* extra bits for each length code */
    [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
  
  var extra_dbits =   /* extra bits for each distance code */
    [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
  
  var extra_blbits =  /* extra bits for each bit length code */
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  
  var bl_order =
    [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  /* eslint-enable comma-spacing,array-bracket-spacing */
  
  /* The lengths of the bit length codes are sent in order of decreasing
   * probability, to avoid transmitting the lengths for unused bit length codes.
   */
  
  /* ===========================================================================
   * Local data. These are initialized only once.
   */
  
  // We pre-fill arrays with 0 to avoid uninitialized gaps
  
  var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  
  // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  var static_ltree  = new Array((L_CODES + 2) * 2);
  zero(static_ltree);
  /* The static literal tree. Since the bit lengths are imposed, there is no
   * need for the L_CODES extra codes used during heap construction. However
   * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
   * below).
   */
  
  var static_dtree  = new Array(D_CODES * 2);
  zero(static_dtree);
  /* The static distance tree. (Actually a trivial tree since all codes use
   * 5 bits.)
   */
  
  var _dist_code    = new Array(DIST_CODE_LEN);
  zero(_dist_code);
  /* Distance codes. The first 256 values correspond to the distances
   * 3 .. 258, the last 256 values correspond to the top 8 bits of
   * the 15 bit distances.
   */
  
  var _length_code  = new Array(MAX_MATCH - MIN_MATCH + 1);
  zero(_length_code);
  /* length code for each normalized match length (0 == MIN_MATCH) */
  
  var base_length   = new Array(LENGTH_CODES);
  zero(base_length);
  /* First normalized length for each code (0 = MIN_MATCH) */
  
  var base_dist     = new Array(D_CODES);
  zero(base_dist);
  /* First normalized distance for each code (0 = distance of 1) */
  
  
  function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
  
    this.static_tree  = static_tree;  /* static tree or NULL */
    this.extra_bits   = extra_bits;   /* extra bits for each code or NULL */
    this.extra_base   = extra_base;   /* base index for extra_bits */
    this.elems        = elems;        /* max number of elements in the tree */
    this.max_length   = max_length;   /* max bit length for the codes */
  
    // show if `static_tree` has data or dummy - needed for monomorphic objects
    this.has_stree    = static_tree && static_tree.length;
  }
  
  
  var static_l_desc;
  var static_d_desc;
  var static_bl_desc;
  
  
  function TreeDesc(dyn_tree, stat_desc) {
    this.dyn_tree = dyn_tree;     /* the dynamic tree */
    this.max_code = 0;            /* largest code with non zero frequency */
    this.stat_desc = stat_desc;   /* the corresponding static tree */
  }
  
  
  
  function d_code(dist) {
    return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  }
  
  
  /* ===========================================================================
   * Output a short LSB first on the stream.
   * IN assertion: there is enough room in pendingBuf.
   */
  function put_short(s, w) {
  //    put_byte(s, (uch)((w) & 0xff));
  //    put_byte(s, (uch)((ush)(w) >> 8));
    s.pending_buf[s.pending++] = (w) & 0xff;
    s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  }
  
  
  /* ===========================================================================
   * Send a value on a given number of bits.
   * IN assertion: length <= 16 and value fits in length bits.
   */
  function send_bits(s, value, length) {
    if (s.bi_valid > (Buf_size - length)) {
      s.bi_buf |= (value << s.bi_valid) & 0xffff;
      put_short(s, s.bi_buf);
      s.bi_buf = value >> (Buf_size - s.bi_valid);
      s.bi_valid += length - Buf_size;
    } else {
      s.bi_buf |= (value << s.bi_valid) & 0xffff;
      s.bi_valid += length;
    }
  }
  
  
  function send_code(s, c, tree) {
    send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
  }
  
  
  /* ===========================================================================
   * Reverse the first len bits of a code, using straightforward code (a faster
   * method would use a table)
   * IN assertion: 1 <= len <= 15
   */
  function bi_reverse(code, len) {
    var res = 0;
    do {
      res |= code & 1;
      code >>>= 1;
      res <<= 1;
    } while (--len > 0);
    return res >>> 1;
  }
  
  
  /* ===========================================================================
   * Flush the bit buffer, keeping at most 7 bits in it.
   */
  function bi_flush(s) {
    if (s.bi_valid === 16) {
      put_short(s, s.bi_buf);
      s.bi_buf = 0;
      s.bi_valid = 0;
  
    } else if (s.bi_valid >= 8) {
      s.pending_buf[s.pending++] = s.bi_buf & 0xff;
      s.bi_buf >>= 8;
      s.bi_valid -= 8;
    }
  }
  
  
  /* ===========================================================================
   * Compute the optimal bit lengths for a tree and update the total bit length
   * for the current block.
   * IN assertion: the fields freq and dad are set, heap[heap_max] and
   *    above are the tree nodes sorted by increasing frequency.
   * OUT assertions: the field len is set to the optimal bit length, the
   *     array bl_count contains the frequencies for each bit length.
   *     The length opt_len is updated; static_len is also updated if stree is
   *     not null.
   */
  function gen_bitlen(s, desc)
  //    deflate_state *s;
  //    tree_desc *desc;    /* the tree descriptor */
  {
    var tree            = desc.dyn_tree;
    var max_code        = desc.max_code;
    var stree           = desc.stat_desc.static_tree;
    var has_stree       = desc.stat_desc.has_stree;
    var extra           = desc.stat_desc.extra_bits;
    var base            = desc.stat_desc.extra_base;
    var max_length      = desc.stat_desc.max_length;
    var h;              /* heap index */
    var n, m;           /* iterate over the tree elements */
    var bits;           /* bit length */
    var xbits;          /* extra bits */
    var f;              /* frequency */
    var overflow = 0;   /* number of elements with bit length too large */
  
    for (bits = 0; bits <= MAX_BITS; bits++) {
      s.bl_count[bits] = 0;
    }
  
    /* In a first pass, compute the optimal bit lengths (which may
     * overflow in the case of the bit length tree).
     */
    tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
  
    for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
      n = s.heap[h];
      bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
      if (bits > max_length) {
        bits = max_length;
        overflow++;
      }
      tree[n * 2 + 1]/*.Len*/ = bits;
      /* We overwrite tree[n].Dad which is no longer needed */
  
      if (n > max_code) { continue; } /* not a leaf node */
  
      s.bl_count[bits]++;
      xbits = 0;
      if (n >= base) {
        xbits = extra[n - base];
      }
      f = tree[n * 2]/*.Freq*/;
      s.opt_len += f * (bits + xbits);
      if (has_stree) {
        s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
      }
    }
    if (overflow === 0) { return; }
  
    // Trace((stderr,"\nbit length overflow\n"));
    /* This happens for example on obj2 and pic of the Calgary corpus */
  
    /* Find the first bit length which could increase: */
    do {
      bits = max_length - 1;
      while (s.bl_count[bits] === 0) { bits--; }
      s.bl_count[bits]--;      /* move one leaf down the tree */
      s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
      s.bl_count[max_length]--;
      /* The brother of the overflow item also moves one step up,
       * but this does not affect bl_count[max_length]
       */
      overflow -= 2;
    } while (overflow > 0);
  
    /* Now recompute all bit lengths, scanning in increasing frequency.
     * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
     * lengths instead of fixing only the wrong ones. This idea is taken
     * from 'ar' written by Haruhiko Okumura.)
     */
    for (bits = max_length; bits !== 0; bits--) {
      n = s.bl_count[bits];
      while (n !== 0) {
        m = s.heap[--h];
        if (m > max_code) { continue; }
        if (tree[m * 2 + 1]/*.Len*/ !== bits) {
          // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
          s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
          tree[m * 2 + 1]/*.Len*/ = bits;
        }
        n--;
      }
    }
  }
  
  
  /* ===========================================================================
   * Generate the codes for a given tree and bit counts (which need not be
   * optimal).
   * IN assertion: the array bl_count contains the bit length statistics for
   * the given tree and the field len is set for all tree elements.
   * OUT assertion: the field code is set for all tree elements of non
   *     zero code length.
   */
  function gen_codes(tree, max_code, bl_count)
  //    ct_data *tree;             /* the tree to decorate */
  //    int max_code;              /* largest code with non zero frequency */
  //    ushf *bl_count;            /* number of codes at each bit length */
  {
    var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
    var code = 0;              /* running code value */
    var bits;                  /* bit index */
    var n;                     /* code index */
  
    /* The distribution counts are first used to generate the code values
     * without bit reversal.
     */
    for (bits = 1; bits <= MAX_BITS; bits++) {
      next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
    }
    /* Check that the bit counts in bl_count are consistent. The last code
     * must be all ones.
     */
    //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
    //        "inconsistent bit counts");
    //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  
    for (n = 0;  n <= max_code; n++) {
      var len = tree[n * 2 + 1]/*.Len*/;
      if (len === 0) { continue; }
      /* Now reverse the bits */
      tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  
      //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
      //     n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
    }
  }
  
  
  /* ===========================================================================
   * Initialize the various 'constant' tables.
   */
  function tr_static_init() {
    var n;        /* iterates over tree elements */
    var bits;     /* bit counter */
    var length;   /* length value */
    var code;     /* code value */
    var dist;     /* distance index */
    var bl_count = new Array(MAX_BITS + 1);
    /* number of codes at each bit length for an optimal tree */
  
    // do check in _tr_init()
    //if (static_init_done) return;
  
    /* For some embedded targets, global variables are not initialized: */
  /*#ifdef NO_INIT_GLOBAL_POINTERS
    static_l_desc.static_tree = static_ltree;
    static_l_desc.extra_bits = extra_lbits;
    static_d_desc.static_tree = static_dtree;
    static_d_desc.extra_bits = extra_dbits;
    static_bl_desc.extra_bits = extra_blbits;
  #endif*/
  
    /* Initialize the mapping length (0..255) -> length code (0..28) */
    length = 0;
    for (code = 0; code < LENGTH_CODES - 1; code++) {
      base_length[code] = length;
      for (n = 0; n < (1 << extra_lbits[code]); n++) {
        _length_code[length++] = code;
      }
    }
    //Assert (length == 256, "tr_static_init: length != 256");
    /* Note that the length 255 (match length 258) can be represented
     * in two different ways: code 284 + 5 bits or code 285, so we
     * overwrite length_code[255] to use the best encoding:
     */
    _length_code[length - 1] = code;
  
    /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
    dist = 0;
    for (code = 0; code < 16; code++) {
      base_dist[code] = dist;
      for (n = 0; n < (1 << extra_dbits[code]); n++) {
        _dist_code[dist++] = code;
      }
    }
    //Assert (dist == 256, "tr_static_init: dist != 256");
    dist >>= 7; /* from now on, all distances are divided by 128 */
    for (; code < D_CODES; code++) {
      base_dist[code] = dist << 7;
      for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
        _dist_code[256 + dist++] = code;
      }
    }
    //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  
    /* Construct the codes of the static literal tree */
    for (bits = 0; bits <= MAX_BITS; bits++) {
      bl_count[bits] = 0;
    }
  
    n = 0;
    while (n <= 143) {
      static_ltree[n * 2 + 1]/*.Len*/ = 8;
      n++;
      bl_count[8]++;
    }
    while (n <= 255) {
      static_ltree[n * 2 + 1]/*.Len*/ = 9;
      n++;
      bl_count[9]++;
    }
    while (n <= 279) {
      static_ltree[n * 2 + 1]/*.Len*/ = 7;
      n++;
      bl_count[7]++;
    }
    while (n <= 287) {
      static_ltree[n * 2 + 1]/*.Len*/ = 8;
      n++;
      bl_count[8]++;
    }
    /* Codes 286 and 287 do not exist, but we must include them in the
     * tree construction to get a canonical Huffman tree (longest code
     * all ones)
     */
    gen_codes(static_ltree, L_CODES + 1, bl_count);
  
    /* The static distance tree is trivial: */
    for (n = 0; n < D_CODES; n++) {
      static_dtree[n * 2 + 1]/*.Len*/ = 5;
      static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
    }
  
    // Now data ready and we can init static trees
    static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
    static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS);
    static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0,         BL_CODES, MAX_BL_BITS);
  
    //static_init_done = true;
  }
  
  
  /* ===========================================================================
   * Initialize a new block.
   */
  function init_block(s) {
    var n; /* iterates over tree elements */
  
    /* Initialize the trees. */
    for (n = 0; n < L_CODES;  n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
    for (n = 0; n < D_CODES;  n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
    for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
  
    s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
    s.opt_len = s.static_len = 0;
    s.last_lit = s.matches = 0;
  }
  
  
  /* ===========================================================================
   * Flush the bit buffer and align the output on a byte boundary
   */
  function bi_windup(s)
  {
    if (s.bi_valid > 8) {
      put_short(s, s.bi_buf);
    } else if (s.bi_valid > 0) {
      //put_byte(s, (Byte)s->bi_buf);
      s.pending_buf[s.pending++] = s.bi_buf;
    }
    s.bi_buf = 0;
    s.bi_valid = 0;
  }
  
  /* ===========================================================================
   * Copy a stored block, storing first the length and its
   * one's complement if requested.
   */
  function copy_block(s, buf, len, header)
  //DeflateState *s;
  //charf    *buf;    /* the input data */
  //unsigned len;     /* its length */
  //int      header;  /* true if block header must be written */
  {
    bi_windup(s);        /* align on byte boundary */
  
    if (header) {
      put_short(s, len);
      put_short(s, ~len);
    }
  //  while (len--) {
  //    put_byte(s, *buf++);
  //  }
    utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
    s.pending += len;
  }
  
  /* ===========================================================================
   * Compares to subtrees, using the tree depth as tie breaker when
   * the subtrees have equal frequency. This minimizes the worst case length.
   */
  function smaller(tree, n, m, depth) {
    var _n2 = n * 2;
    var _m2 = m * 2;
    return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
           (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  }
  
  /* ===========================================================================
   * Restore the heap property by moving down the tree starting at node k,
   * exchanging a node with the smallest of its two sons if necessary, stopping
   * when the heap property is re-established (each father smaller than its
   * two sons).
   */
  function pqdownheap(s, tree, k)
  //    deflate_state *s;
  //    ct_data *tree;  /* the tree to restore */
  //    int k;               /* node to move down */
  {
    var v = s.heap[k];
    var j = k << 1;  /* left son of k */
    while (j <= s.heap_len) {
      /* Set j to the smallest of the two sons: */
      if (j < s.heap_len &&
        smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
        j++;
      }
      /* Exit if v is smaller than both sons */
      if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  
      /* Exchange v with the smallest son */
      s.heap[k] = s.heap[j];
      k = j;
  
      /* And continue down the tree, setting j to the left son of k */
      j <<= 1;
    }
    s.heap[k] = v;
  }
  
  
  // inlined manually
  // var SMALLEST = 1;
  
  /* ===========================================================================
   * Send the block data compressed using the given Huffman trees
   */
  function compress_block(s, ltree, dtree)
  //    deflate_state *s;
  //    const ct_data *ltree; /* literal tree */
  //    const ct_data *dtree; /* distance tree */
  {
    var dist;           /* distance of matched string */
    var lc;             /* match length or unmatched char (if dist == 0) */
    var lx = 0;         /* running index in l_buf */
    var code;           /* the code to send */
    var extra;          /* number of extra bits to send */
  
    if (s.last_lit !== 0) {
      do {
        dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
        lc = s.pending_buf[s.l_buf + lx];
        lx++;
  
        if (dist === 0) {
          send_code(s, lc, ltree); /* send a literal byte */
          //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
        } else {
          /* Here, lc is the match length - MIN_MATCH */
          code = _length_code[lc];
          send_code(s, code + LITERALS + 1, ltree); /* send the length code */
          extra = extra_lbits[code];
          if (extra !== 0) {
            lc -= base_length[code];
            send_bits(s, lc, extra);       /* send the extra length bits */
          }
          dist--; /* dist is now the match distance - 1 */
          code = d_code(dist);
          //Assert (code < D_CODES, "bad d_code");
  
          send_code(s, code, dtree);       /* send the distance code */
          extra = extra_dbits[code];
          if (extra !== 0) {
            dist -= base_dist[code];
            send_bits(s, dist, extra);   /* send the extra distance bits */
          }
        } /* literal or match pair ? */
  
        /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
        //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
        //       "pendingBuf overflow");
  
      } while (lx < s.last_lit);
    }
  
    send_code(s, END_BLOCK, ltree);
  }
  
  
  /* ===========================================================================
   * Construct one Huffman tree and assigns the code bit strings and lengths.
   * Update the total bit length for the current block.
   * IN assertion: the field freq is set for all tree elements.
   * OUT assertions: the fields len and code are set to the optimal bit length
   *     and corresponding code. The length opt_len is updated; static_len is
   *     also updated if stree is not null. The field max_code is set.
   */
  function build_tree(s, desc)
  //    deflate_state *s;
  //    tree_desc *desc; /* the tree descriptor */
  {
    var tree     = desc.dyn_tree;
    var stree    = desc.stat_desc.static_tree;
    var has_stree = desc.stat_desc.has_stree;
    var elems    = desc.stat_desc.elems;
    var n, m;          /* iterate over heap elements */
    var max_code = -1; /* largest code with non zero frequency */
    var node;          /* new node being created */
  
    /* Construct the initial heap, with least frequent element in
     * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
     * heap[0] is not used.
     */
    s.heap_len = 0;
    s.heap_max = HEAP_SIZE;
  
    for (n = 0; n < elems; n++) {
      if (tree[n * 2]/*.Freq*/ !== 0) {
        s.heap[++s.heap_len] = max_code = n;
        s.depth[n] = 0;
  
      } else {
        tree[n * 2 + 1]/*.Len*/ = 0;
      }
    }
  
    /* The pkzip format requires that at least one distance code exists,
     * and that at least one bit should be sent even if there is only one
     * possible code. So to avoid special checks later on we force at least
     * two codes of non zero frequency.
     */
    while (s.heap_len < 2) {
      node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
      tree[node * 2]/*.Freq*/ = 1;
      s.depth[node] = 0;
      s.opt_len--;
  
      if (has_stree) {
        s.static_len -= stree[node * 2 + 1]/*.Len*/;
      }
      /* node is 0 or 1 so it does not have extra bits */
    }
    desc.max_code = max_code;
  
    /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
     * establish sub-heaps of increasing lengths:
     */
    for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  
    /* Construct the Huffman tree by repeatedly combining the least two
     * frequent nodes.
     */
    node = elems;              /* next internal node of the tree */
    do {
      //pqremove(s, tree, n);  /* n = node of least frequency */
      /*** pqremove ***/
      n = s.heap[1/*SMALLEST*/];
      s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
      pqdownheap(s, tree, 1/*SMALLEST*/);
      /***/
  
      m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  
      s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
      s.heap[--s.heap_max] = m;
  
      /* Create a new node father of n and m */
      tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
      s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
      tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
  
      /* and insert the new node in the heap */
      s.heap[1/*SMALLEST*/] = node++;
      pqdownheap(s, tree, 1/*SMALLEST*/);
  
    } while (s.heap_len >= 2);
  
    s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  
    /* At this point, the fields freq and dad are set. We can now
     * generate the bit lengths.
     */
    gen_bitlen(s, desc);
  
    /* The field len is now set, we can generate the bit codes */
    gen_codes(tree, max_code, s.bl_count);
  }
  
  
  /* ===========================================================================
   * Scan a literal or distance tree to determine the frequencies of the codes
   * in the bit length tree.
   */
  function scan_tree(s, tree, max_code)
  //    deflate_state *s;
  //    ct_data *tree;   /* the tree to be scanned */
  //    int max_code;    /* and its largest code of non zero frequency */
  {
    var n;                     /* iterates over all tree elements */
    var prevlen = -1;          /* last emitted length */
    var curlen;                /* length of current code */
  
    var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  
    var count = 0;             /* repeat count of the current code */
    var max_count = 7;         /* max repeat count */
    var min_count = 4;         /* min repeat count */
  
    if (nextlen === 0) {
      max_count = 138;
      min_count = 3;
    }
    tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
  
    for (n = 0; n <= max_code; n++) {
      curlen = nextlen;
      nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  
      if (++count < max_count && curlen === nextlen) {
        continue;
  
      } else if (count < min_count) {
        s.bl_tree[curlen * 2]/*.Freq*/ += count;
  
      } else if (curlen !== 0) {
  
        if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
        s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
  
      } else if (count <= 10) {
        s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
  
      } else {
        s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
      }
  
      count = 0;
      prevlen = curlen;
  
      if (nextlen === 0) {
        max_count = 138;
        min_count = 3;
  
      } else if (curlen === nextlen) {
        max_count = 6;
        min_count = 3;
  
      } else {
        max_count = 7;
        min_count = 4;
      }
    }
  }
  
  
  /* ===========================================================================
   * Send a literal or distance tree in compressed form, using the codes in
   * bl_tree.
   */
  function send_tree(s, tree, max_code)
  //    deflate_state *s;
  //    ct_data *tree; /* the tree to be scanned */
  //    int max_code;       /* and its largest code of non zero frequency */
  {
    var n;                     /* iterates over all tree elements */
    var prevlen = -1;          /* last emitted length */
    var curlen;                /* length of current code */
  
    var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  
    var count = 0;             /* repeat count of the current code */
    var max_count = 7;         /* max repeat count */
    var min_count = 4;         /* min repeat count */
  
    /* tree[max_code+1].Len = -1; */  /* guard already set */
    if (nextlen === 0) {
      max_count = 138;
      min_count = 3;
    }
  
    for (n = 0; n <= max_code; n++) {
      curlen = nextlen;
      nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  
      if (++count < max_count && curlen === nextlen) {
        continue;
  
      } else if (count < min_count) {
        do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  
      } else if (curlen !== 0) {
        if (curlen !== prevlen) {
          send_code(s, curlen, s.bl_tree);
          count--;
        }
        //Assert(count >= 3 && count <= 6, " 3_6?");
        send_code(s, REP_3_6, s.bl_tree);
        send_bits(s, count - 3, 2);
  
      } else if (count <= 10) {
        send_code(s, REPZ_3_10, s.bl_tree);
        send_bits(s, count - 3, 3);
  
      } else {
        send_code(s, REPZ_11_138, s.bl_tree);
        send_bits(s, count - 11, 7);
      }
  
      count = 0;
      prevlen = curlen;
      if (nextlen === 0) {
        max_count = 138;
        min_count = 3;
  
      } else if (curlen === nextlen) {
        max_count = 6;
        min_count = 3;
  
      } else {
        max_count = 7;
        min_count = 4;
      }
    }
  }
  
  
  /* ===========================================================================
   * Construct the Huffman tree for the bit lengths and return the index in
   * bl_order of the last bit length code to send.
   */
  function build_bl_tree(s) {
    var max_blindex;  /* index of last bit length code of non zero freq */
  
    /* Determine the bit length frequencies for literal and distance trees */
    scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
    scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  
    /* Build the bit length tree: */
    build_tree(s, s.bl_desc);
    /* opt_len now includes the length of the tree representations, except
     * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
     */
  
    /* Determine the number of bit length codes to send. The pkzip format
     * requires that at least 4 bit length codes be sent. (appnote.txt says
     * 3 but the actual value used is 4.)
     */
    for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
      if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
        break;
      }
    }
    /* Update opt_len to include the bit length tree and counts */
    s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
    //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
    //        s->opt_len, s->static_len));
  
    return max_blindex;
  }
  
  
  /* ===========================================================================
   * Send the header for a block using dynamic Huffman trees: the counts, the
   * lengths of the bit length codes, the literal tree and the distance tree.
   * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
   */
  function send_all_trees(s, lcodes, dcodes, blcodes)
  //    deflate_state *s;
  //    int lcodes, dcodes, blcodes; /* number of codes for each tree */
  {
    var rank;                    /* index in bl_order */
  
    //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
    //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
    //        "too many codes");
    //Tracev((stderr, "\nbl counts: "));
    send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
    send_bits(s, dcodes - 1,   5);
    send_bits(s, blcodes - 4,  4); /* not -3 as stated in appnote.txt */
    for (rank = 0; rank < blcodes; rank++) {
      //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
      send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
    }
    //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  
    send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
    //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  
    send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
    //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  }
  
  
  /* ===========================================================================
   * Check if the data type is TEXT or BINARY, using the following algorithm:
   * - TEXT if the two conditions below are satisfied:
   *    a) There are no non-portable control characters belonging to the
   *       "black list" (0..6, 14..25, 28..31).
   *    b) There is at least one printable character belonging to the
   *       "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
   * - BINARY otherwise.
   * - The following partially-portable control characters form a
   *   "gray list" that is ignored in this detection algorithm:
   *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
   * IN assertion: the fields Freq of dyn_ltree are set.
   */
  function detect_data_type(s) {
    /* black_mask is the bit mask of black-listed bytes
     * set bits 0..6, 14..25, and 28..31
     * 0xf3ffc07f = binary 11110011111111111100000001111111
     */
    var black_mask = 0xf3ffc07f;
    var n;
  
    /* Check for non-textual ("black-listed") bytes. */
    for (n = 0; n <= 31; n++, black_mask >>>= 1) {
      if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
        return Z_BINARY;
      }
    }
  
    /* Check for textual ("white-listed") bytes. */
    if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
        s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
      return Z_TEXT;
    }
    for (n = 32; n < LITERALS; n++) {
      if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
        return Z_TEXT;
      }
    }
  
    /* There are no "black-listed" or "white-listed" bytes:
     * this stream either is empty or has tolerated ("gray-listed") bytes only.
     */
    return Z_BINARY;
  }
  
  
  var static_init_done = false;
  
  /* ===========================================================================
   * Initialize the tree data structures for a new zlib stream.
   */
  function _tr_init(s)
  {
  
    if (!static_init_done) {
      tr_static_init();
      static_init_done = true;
    }
  
    s.l_desc  = new TreeDesc(s.dyn_ltree, static_l_desc);
    s.d_desc  = new TreeDesc(s.dyn_dtree, static_d_desc);
    s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  
    s.bi_buf = 0;
    s.bi_valid = 0;
  
    /* Initialize the first block of the first file: */
    init_block(s);
  }
  
  
  /* ===========================================================================
   * Send a stored block
   */
  function _tr_stored_block(s, buf, stored_len, last)
  //DeflateState *s;
  //charf *buf;       /* input block */
  //ulg stored_len;   /* length of input block */
  //int last;         /* one if this is the last block for a file */
  {
    send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3);    /* send block type */
    copy_block(s, buf, stored_len, true); /* with header */
  }
  
  
  /* ===========================================================================
   * Send one empty static block to give enough lookahead for inflate.
   * This takes 10 bits, of which 7 may remain in the bit buffer.
   */
  function _tr_align(s) {
    send_bits(s, STATIC_TREES << 1, 3);
    send_code(s, END_BLOCK, static_ltree);
    bi_flush(s);
  }
  
  
  /* ===========================================================================
   * Determine the best encoding for the current block: dynamic trees, static
   * trees or store, and output the encoded block to the zip file.
   */
  function _tr_flush_block(s, buf, stored_len, last)
  //DeflateState *s;
  //charf *buf;       /* input block, or NULL if too old */
  //ulg stored_len;   /* length of input block */
  //int last;         /* one if this is the last block for a file */
  {
    var opt_lenb, static_lenb;  /* opt_len and static_len in bytes */
    var max_blindex = 0;        /* index of last bit length code of non zero freq */
  
    /* Build the Huffman trees unless a stored block is forced */
    if (s.level > 0) {
  
      /* Check if the file is binary or text */
      if (s.strm.data_type === Z_UNKNOWN) {
        s.strm.data_type = detect_data_type(s);
      }
  
      /* Construct the literal and distance trees */
      build_tree(s, s.l_desc);
      // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
      //        s->static_len));
  
      build_tree(s, s.d_desc);
      // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
      //        s->static_len));
      /* At this point, opt_len and static_len are the total bit lengths of
       * the compressed block data, excluding the tree representations.
       */
  
      /* Build the bit length tree for the above two trees, and get the index
       * in bl_order of the last bit length code to send.
       */
      max_blindex = build_bl_tree(s);
  
      /* Determine the best encoding. Compute the block lengths in bytes. */
      opt_lenb = (s.opt_len + 3 + 7) >>> 3;
      static_lenb = (s.static_len + 3 + 7) >>> 3;
  
      // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
      //        opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
      //        s->last_lit));
  
      if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  
    } else {
      // Assert(buf != (char*)0, "lost buf");
      opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
    }
  
    if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
      /* 4: two words for the lengths */
  
      /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
       * Otherwise we can't have processed more than WSIZE input bytes since
       * the last block flush, because compression would have been
       * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
       * transform a block into a stored block.
       */
      _tr_stored_block(s, buf, stored_len, last);
  
    } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  
      send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
      compress_block(s, static_ltree, static_dtree);
  
    } else {
      send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
      send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
      compress_block(s, s.dyn_ltree, s.dyn_dtree);
    }
    // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
    /* The above check is made mod 2^32, for files larger than 512 MB
     * and uLong implemented on 32 bits.
     */
    init_block(s);
  
    if (last) {
      bi_windup(s);
    }
    // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
    //       s->compressed_len-7*last));
  }
  
  /* ===========================================================================
   * Save the match info and tally the frequency counts. Return true if
   * the current block must be flushed.
   */
  function _tr_tally(s, dist, lc)
  //    deflate_state *s;
  //    unsigned dist;  /* distance of matched string */
  //    unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
  {
    //var out_length, in_length, dcode;
  
    s.pending_buf[s.d_buf + s.last_lit * 2]     = (dist >>> 8) & 0xff;
    s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  
    s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
    s.last_lit++;
  
    if (dist === 0) {
      /* lc is the unmatched char */
      s.dyn_ltree[lc * 2]/*.Freq*/++;
    } else {
      s.matches++;
      /* Here, lc is the match length - MIN_MATCH */
      dist--;             /* dist = match distance - 1 */
      //Assert((ush)dist < (ush)MAX_DIST(s) &&
      //       (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
      //       (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
  
      s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
      s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
    }
  
  // (!) This block is disabled in zlib defailts,
  // don't enable it for binary compatibility
  
  //#ifdef TRUNCATE_BLOCK
  //  /* Try to guess if it is profitable to stop the current block here */
  //  if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  //    /* Compute an upper bound for the compressed length */
  //    out_length = s.last_lit*8;
  //    in_length = s.strstart - s.block_start;
  //
  //    for (dcode = 0; dcode < D_CODES; dcode++) {
  //      out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  //    }
  //    out_length >>>= 3;
  //    //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  //    //       s->last_lit, in_length, out_length,
  //    //       100L - out_length*100L/in_length));
  //    if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  //      return true;
  //    }
  //  }
  //#endif
  
    return (s.last_lit === s.lit_bufsize - 1);
    /* We avoid equality with lit_bufsize because of wraparound at 64K
     * on 16 bit machines and because stored blocks are restricted to
     * 64K-1 bytes.
     */
  }
  
  exports._tr_init  = _tr_init;
  exports._tr_stored_block = _tr_stored_block;
  exports._tr_flush_block  = _tr_flush_block;
  exports._tr_tally = _tr_tally;
  exports._tr_align = _tr_align;
  
  },{"../utils/common":70}],82:[function(require,module,exports){
  'use strict';
  
  
  function ZStream() {
    /* next input byte */
    this.input = null; // JS specific, because we have no pointers
    this.next_in = 0;
    /* number of bytes available at input */
    this.avail_in = 0;
    /* total number of input bytes read so far */
    this.total_in = 0;
    /* next output byte should be put there */
    this.output = null; // JS specific, because we have no pointers
    this.next_out = 0;
    /* remaining free space at output */
    this.avail_out = 0;
    /* total number of bytes output so far */
    this.total_out = 0;
    /* last error message, NULL if no error */
    this.msg = ''/*Z_NULL*/;
    /* not visible by applications */
    this.state = null;
    /* best guess about the data type: binary or text */
    this.data_type = 2/*Z_UNKNOWN*/;
    /* adler32 value of the uncompressed data */
    this.adler = 0;
  }
  
  module.exports = ZStream;
  
  },{}],83:[function(require,module,exports){
  (function (Buffer){
  const assert = require('assert')
  /**
   * RLP Encoding based on: https://github.com/ethereum/wiki/wiki/%5BEnglish%5D-RLP
   * This function takes in a data, convert it to buffer if not, and a length for recursion
   *
   * @param {Buffer,String,Integer,Array} data - will be converted to buffer
   * @returns {Buffer} - returns buffer of encoded data
   **/
  exports.encode = function (input) {
    if (input instanceof Array) {
      var output = []
      for (var i = 0; i < input.length; i++) {
        output.push(exports.encode(input[i]))
      }
      var buf = Buffer.concat(output)
      return Buffer.concat([encodeLength(buf.length, 192), buf])
    } else {
      input = toBuffer(input)
      if (input.length === 1 && input[0] < 128) {
        return input
      } else {
        return Buffer.concat([encodeLength(input.length, 128), input])
      }
    }
  }
  
  function safeParseInt (v, base) {
    if (v.slice(0, 2) === '00') {
      throw (new Error('invalid RLP: extra zeros'))
    }
  
    return parseInt(v, base)
  }
  
  function encodeLength (len, offset) {
    if (len < 56) {
      return new Buffer([len + offset])
    } else {
      var hexLength = intToHex(len)
      var lLength = hexLength.length / 2
      var firstByte = intToHex(offset + 55 + lLength)
      return new Buffer(firstByte + hexLength, 'hex')
    }
  }
  
  /**
   * RLP Decoding based on: {@link https://github.com/ethereum/wiki/wiki/%5BEnglish%5D-RLP|RLP}
   * @param {Buffer,String,Integer,Array} data - will be converted to buffer
   * @returns {Array} - returns decode Array of Buffers containg the original message
   **/
  exports.decode = function (input, stream) {
    if (!input || input.length === 0) {
      return new Buffer([])
    }
  
    input = toBuffer(input)
    var decoded = _decode(input)
  
    if (stream) {
      return decoded
    }
  
    assert.equal(decoded.remainder.length, 0, 'invalid remainder')
    return decoded.data
  }
  
  exports.getLength = function (input) {
    if (!input || input.length === 0) {
      return new Buffer([])
    }
  
    input = toBuffer(input)
    var firstByte = input[0]
    if (firstByte <= 0x7f) {
      return input.length
    } else if (firstByte <= 0xb7) {
      return firstByte - 0x7f
    } else if (firstByte <= 0xbf) {
      return firstByte - 0xb6
    } else if (firstByte <= 0xf7) {
      // a list between  0-55 bytes long
      return firstByte - 0xbf
    } else {
      // a list  over 55 bytes long
      var llength = firstByte - 0xf6
      var length = safeParseInt(input.slice(1, llength).toString('hex'), 16)
      return llength + length
    }
  }
  
  function _decode (input) {
    var length, llength, data, innerRemainder, d
    var decoded = []
    var firstByte = input[0]
  
    if (firstByte <= 0x7f) {
      // a single byte whose value is in the [0x00, 0x7f] range, that byte is its own RLP encoding.
      return {
        data: input.slice(0, 1),
        remainder: input.slice(1)
      }
    } else if (firstByte <= 0xb7) {
      // string is 0-55 bytes long. A single byte with value 0x80 plus the length of the string followed by the string
      // The range of the first byte is [0x80, 0xb7]
      length = firstByte - 0x7f
  
      // set 0x80 null to 0
      if (firstByte === 0x80) {
        data = new Buffer([])
      } else {
        data = input.slice(1, length)
      }
  
      if (length === 2 && data[0] < 0x80) {
        throw new Error('invalid rlp encoding: byte must be less 0x80')
      }
  
      return {
        data: data,
        remainder: input.slice(length)
      }
    } else if (firstByte <= 0xbf) {
      llength = firstByte - 0xb6
      length = safeParseInt(input.slice(1, llength).toString('hex'), 16)
      data = input.slice(llength, length + llength)
      if (data.length < length) {
        throw (new Error('invalid RLP'))
      }
  
      return {
        data: data,
        remainder: input.slice(length + llength)
      }
    } else if (firstByte <= 0xf7) {
      // a list between  0-55 bytes long
      length = firstByte - 0xbf
      innerRemainder = input.slice(1, length)
      while (innerRemainder.length) {
        d = _decode(innerRemainder)
        decoded.push(d.data)
        innerRemainder = d.remainder
      }
  
      return {
        data: decoded,
        remainder: input.slice(length)
      }
    } else {
      // a list  over 55 bytes long
      llength = firstByte - 0xf6
      length = safeParseInt(input.slice(1, llength).toString('hex'), 16)
      var totalLength = llength + length
      if (totalLength > input.length) {
        throw new Error('invalid rlp: total length is larger than the data')
      }
  
      innerRemainder = input.slice(llength, totalLength)
      if (innerRemainder.length === 0) {
        throw new Error('invalid rlp, List has a invalid length')
      }
  
      while (innerRemainder.length) {
        d = _decode(innerRemainder)
        decoded.push(d.data)
        innerRemainder = d.remainder
      }
      return {
        data: decoded,
        remainder: input.slice(totalLength)
      }
    }
  }
  
  function isHexPrefixed (str) {
    return str.slice(0, 2) === '0x'
  }
  
  // Removes 0x from a given String
  function stripHexPrefix (str) {
    if (typeof str !== 'string') {
      return str
    }
    return isHexPrefixed(str) ? str.slice(2) : str
  }
  
  function intToHex (i) {
    var hex = i.toString(16)
    if (hex.length % 2) {
      hex = '0' + hex
    }
  
    return hex
  }
  
  function padToEven (a) {
    if (a.length % 2) a = '0' + a
    return a
  }
  
  function intToBuffer (i) {
    var hex = intToHex(i)
    return new Buffer(hex, 'hex')
  }
  
  function toBuffer (v) {
    if (!Buffer.isBuffer(v)) {
      if (typeof v === 'string') {
        v = new Buffer(padToEven(stripHexPrefix(v)), 'hex')
      } else if (typeof v === 'number') {
        if (!v) {
          v = new Buffer([])
        } else {
          v = intToBuffer(v)
        }
      } else if (v === null || v === undefined) {
        v = new Buffer([])
      } else if (v.toArray) {
        // converts a BN to a Buffer
        v = new Buffer(v.toArray())
      } else {
        throw new Error('invalid type')
      }
    }
    return v
  }
  
  }).call(this,require("buffer").Buffer)
  },{"assert":86,"buffer":88}],84:[function(require,module,exports){
  (function (Buffer){
  const EC = require('elliptic').ec
  const ec = new EC('secp256k1')
  const BN = require('bn.js')
  
  function pad32(msg) {
    var buf
    if (msg.length < 32) {
      buf = new Buffer(32)
      buf.fill(0)
      msg.copy(buf, 32 - msg.length)
      return buf
    } else
      return msg
  }
  
  function parseSig(sig) {
    var recid;
    if (sig.signature) {
      recid = sig.recovery
      sig = sig.signature
    }
  
    if (sig.length === 64)
      sig = {
        r: sig.slice(0, 32),
        s: sig.slice(32, 64)
      }
  
    return {
      sig: sig,
      recid: recid
    }
  }
  
  /**
   * Create an ECDSA signature.
   * @method sign
   * @param  {Buffer} secretkey a 32-byte secret key (assumed to be valid)
   * @param {Buffer} msg he message being signed
   */
  exports.sign = function (msg, secretKey, DER, cb) {
  
    if (typeof DER === 'function') {
      cb = DER
      DER = false
    }
  
    var result = ec.sign(new BN(msg), new BN(secretKey))
  
    if (DER)
      result = new Buffer(result.toDER())
    else {
      result = {
        signature: new Buffer(result.r.toArray().concat(result.s.toArray())),
        recovery: result.recoveryParam
      }
    }
  
    if (cb)
      cb(null, result)
    else
      return result
  }
  
  /**
   * Verify an ECDSA signature.
   * @method verify
   * @param {Buffer} mgs the message
   * @param {Buffer|Object} sig the signature
   * @param {Buffer} pubKey the public key
   * @return {Integer}
   *
   *    - 1: correct signature
   *    - 0: incorrect signature
   */
  exports.verify = function (msg, sig, pubKey, cb) {
  
    sig = parseSig(sig)
    var key = ec.keyFromPublic(pubKey)
    var result
  
    try {
      result = ec.verify(new BN(msg), sig.sig, key)
    } catch (e) {
      result = false
    }
    if (cb)
      cb(result)
    else
      return result
  }
  
  /**
   * Recover an ECDSA public key from a compact signature. In the process also verifing it.
   * @method recoverCompact
   * @param {Buffer} msg the message assumed to be signed
   * @param {Buffer} sig the signature as 64 byte buffer
   * @param {Integer} recid the recovery id (as returned by ecdsa_sign_compact)
   * @param {Boolean} compressed whether to recover a compressed or uncompressed pubkey
   * @param {Function} [cb]
   * @return {Buffer} the pubkey, a 33 or 65 byte buffer
   */
  exports.recover = function (msg, sig, compressed, cb) {
  
    if (typeof compressed === 'function') {
      cb = compressed
      compressed = true
    }
  
    if (compressed === undefined) {
      compressed = true
    }
  
    sig = parseSig(sig)
    var r = ec.recoverPubKey(new BN(msg), sig.sig, sig.recid, 'hex')
  
    if (compressed)
      r = r.encodeCompressed()
    else
      r = r.encode()
  
    r = new Buffer(r)
  
    if (cb)
      cb(null, r)
    else
      return r
  }
  
  /**
   * Compute the public key from a secret key.
   * @method createPubKey
   * @param {Buffer} secKey a 32-byte private key.
   * @param {Boolean} [compressed=0] whether the computed public key should be compressed
   * @return {Buffer} a 33-byte (if compressed) or 65-byte (if uncompressed) area to store the public key.
   */
  exports.createPublicKey = function (secKey, compressed) {
    if (!secKey)
      throw new Error('invalid private key')
  
    const key = ec.keyFromPrivate(secKey)
    const pub = key.getPublic()
  
    if (compressed === undefined) {
      compressed = true
    }
  
    if (compressed)
      return new Buffer(pub.encodeCompressed())
    else
      return new Buffer(pub.encode())
  }
  
  }).call(this,require("buffer").Buffer)
  },{"bn.js":3,"buffer":88,"elliptic":12}],85:[function(require,module,exports){
  //     Underscore.js 1.8.3
  //     http://underscorejs.org
  //     (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  //     Underscore may be freely distributed under the MIT license.
  
  (function() {
  
    // Baseline setup
    // --------------
  
    // Establish the root object, `window` in the browser, or `exports` on the server.
    var root = this;
  
    // Save the previous value of the `_` variable.
    var previousUnderscore = root._;
  
    // Save bytes in the minified (but not gzipped) version:
    var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
  
    // Create quick reference variables for speed access to core prototypes.
    var
      push             = ArrayProto.push,
      slice            = ArrayProto.slice,
      toString         = ObjProto.toString,
      hasOwnProperty   = ObjProto.hasOwnProperty;
  
    // All **ECMAScript 5** native function implementations that we hope to use
    // are declared here.
    var
      nativeIsArray      = Array.isArray,
      nativeKeys         = Object.keys,
      nativeBind         = FuncProto.bind,
      nativeCreate       = Object.create;
  
    // Naked function reference for surrogate-prototype-swapping.
    var Ctor = function(){};
  
    // Create a safe reference to the Underscore object for use below.
    var _ = function(obj) {
      if (obj instanceof _) return obj;
      if (!(this instanceof _)) return new _(obj);
      this._wrapped = obj;
    };
  
    // Export the Underscore object for **Node.js**, with
    // backwards-compatibility for the old `require()` API. If we're in
    // the browser, add `_` as a global object.
    if (typeof exports !== 'undefined') {
      if (typeof module !== 'undefined' && module.exports) {
        exports = module.exports = _;
      }
      exports._ = _;
    } else {
      root._ = _;
    }
  
    // Current version.
    _.VERSION = '1.8.3';
  
    // Internal function that returns an efficient (for current engines) version
    // of the passed-in callback, to be repeatedly applied in other Underscore
    // functions.
    var optimizeCb = function(func, context, argCount) {
      if (context === void 0) return func;
      switch (argCount == null ? 3 : argCount) {
        case 1: return function(value) {
          return func.call(context, value);
        };
        case 2: return function(value, other) {
          return func.call(context, value, other);
        };
        case 3: return function(value, index, collection) {
          return func.call(context, value, index, collection);
        };
        case 4: return function(accumulator, value, index, collection) {
          return func.call(context, accumulator, value, index, collection);
        };
      }
      return function() {
        return func.apply(context, arguments);
      };
    };
  
    // A mostly-internal function to generate callbacks that can be applied
    // to each element in a collection, returning the desired result — either
    // identity, an arbitrary callback, a property matcher, or a property accessor.
    var cb = function(value, context, argCount) {
      if (value == null) return _.identity;
      if (_.isFunction(value)) return optimizeCb(value, context, argCount);
      if (_.isObject(value)) return _.matcher(value);
      return _.property(value);
    };
    _.iteratee = function(value, context) {
      return cb(value, context, Infinity);
    };
  
    // An internal function for creating assigner functions.
    var createAssigner = function(keysFunc, undefinedOnly) {
      return function(obj) {
        var length = arguments.length;
        if (length < 2 || obj == null) return obj;
        for (var index = 1; index < length; index++) {
          var source = arguments[index],
              keys = keysFunc(source),
              l = keys.length;
          for (var i = 0; i < l; i++) {
            var key = keys[i];
            if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
          }
        }
        return obj;
      };
    };
  
    // An internal function for creating a new object that inherits from another.
    var baseCreate = function(prototype) {
      if (!_.isObject(prototype)) return {};
      if (nativeCreate) return nativeCreate(prototype);
      Ctor.prototype = prototype;
      var result = new Ctor;
      Ctor.prototype = null;
      return result;
    };
  
    var property = function(key) {
      return function(obj) {
        return obj == null ? void 0 : obj[key];
      };
    };
  
    // Helper for collection methods to determine whether a collection
    // should be iterated as an array or as an object
    // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
    // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
    var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
    var getLength = property('length');
    var isArrayLike = function(collection) {
      var length = getLength(collection);
      return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
    };
  
    // Collection Functions
    // --------------------
  
    // The cornerstone, an `each` implementation, aka `forEach`.
    // Handles raw objects in addition to array-likes. Treats all
    // sparse array-likes as if they were dense.
    _.each = _.forEach = function(obj, iteratee, context) {
      iteratee = optimizeCb(iteratee, context);
      var i, length;
      if (isArrayLike(obj)) {
        for (i = 0, length = obj.length; i < length; i++) {
          iteratee(obj[i], i, obj);
        }
      } else {
        var keys = _.keys(obj);
        for (i = 0, length = keys.length; i < length; i++) {
          iteratee(obj[keys[i]], keys[i], obj);
        }
      }
      return obj;
    };
  
    // Return the results of applying the iteratee to each element.
    _.map = _.collect = function(obj, iteratee, context) {
      iteratee = cb(iteratee, context);
      var keys = !isArrayLike(obj) && _.keys(obj),
          length = (keys || obj).length,
          results = Array(length);
      for (var index = 0; index < length; index++) {
        var currentKey = keys ? keys[index] : index;
        results[index] = iteratee(obj[currentKey], currentKey, obj);
      }
      return results;
    };
  
    // Create a reducing function iterating left or right.
    function createReduce(dir) {
      // Optimized iterator function as using arguments.length
      // in the main function will deoptimize the, see #1991.
      function iterator(obj, iteratee, memo, keys, index, length) {
        for (; index >= 0 && index < length; index += dir) {
          var currentKey = keys ? keys[index] : index;
          memo = iteratee(memo, obj[currentKey], currentKey, obj);
        }
        return memo;
      }
  
      return function(obj, iteratee, memo, context) {
        iteratee = optimizeCb(iteratee, context, 4);
        var keys = !isArrayLike(obj) && _.keys(obj),
            length = (keys || obj).length,
            index = dir > 0 ? 0 : length - 1;
        // Determine the initial value if none is provided.
        if (arguments.length < 3) {
          memo = obj[keys ? keys[index] : index];
          index += dir;
        }
        return iterator(obj, iteratee, memo, keys, index, length);
      };
    }
  
    // **Reduce** builds up a single result from a list of values, aka `inject`,
    // or `foldl`.
    _.reduce = _.foldl = _.inject = createReduce(1);
  
    // The right-associative version of reduce, also known as `foldr`.
    _.reduceRight = _.foldr = createReduce(-1);
  
    // Return the first value which passes a truth test. Aliased as `detect`.
    _.find = _.detect = function(obj, predicate, context) {
      var key;
      if (isArrayLike(obj)) {
        key = _.findIndex(obj, predicate, context);
      } else {
        key = _.findKey(obj, predicate, context);
      }
      if (key !== void 0 && key !== -1) return obj[key];
    };
  
    // Return all the elements that pass a truth test.
    // Aliased as `select`.
    _.filter = _.select = function(obj, predicate, context) {
      var results = [];
      predicate = cb(predicate, context);
      _.each(obj, function(value, index, list) {
        if (predicate(value, index, list)) results.push(value);
      });
      return results;
    };
  
    // Return all the elements for which a truth test fails.
    _.reject = function(obj, predicate, context) {
      return _.filter(obj, _.negate(cb(predicate)), context);
    };
  
    // Determine whether all of the elements match a truth test.
    // Aliased as `all`.
    _.every = _.all = function(obj, predicate, context) {
      predicate = cb(predicate, context);
      var keys = !isArrayLike(obj) && _.keys(obj),
          length = (keys || obj).length;
      for (var index = 0; index < length; index++) {
        var currentKey = keys ? keys[index] : index;
        if (!predicate(obj[currentKey], currentKey, obj)) return false;
      }
      return true;
    };
  
    // Determine if at least one element in the object matches a truth test.
    // Aliased as `any`.
    _.some = _.any = function(obj, predicate, context) {
      predicate = cb(predicate, context);
      var keys = !isArrayLike(obj) && _.keys(obj),
          length = (keys || obj).length;
      for (var index = 0; index < length; index++) {
        var currentKey = keys ? keys[index] : index;
        if (predicate(obj[currentKey], currentKey, obj)) return true;
      }
      return false;
    };
  
    // Determine if the array or object contains a given item (using `===`).
    // Aliased as `includes` and `include`.
    _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {
      if (!isArrayLike(obj)) obj = _.values(obj);
      if (typeof fromIndex != 'number' || guard) fromIndex = 0;
      return _.indexOf(obj, item, fromIndex) >= 0;
    };
  
    // Invoke a method (with arguments) on every item in a collection.
    _.invoke = function(obj, method) {
      var args = slice.call(arguments, 2);
      var isFunc = _.isFunction(method);
      return _.map(obj, function(value) {
        var func = isFunc ? method : value[method];
        return func == null ? func : func.apply(value, args);
      });
    };
  
    // Convenience version of a common use case of `map`: fetching a property.
    _.pluck = function(obj, key) {
      return _.map(obj, _.property(key));
    };
  
    // Convenience version of a common use case of `filter`: selecting only objects
    // containing specific `key:value` pairs.
    _.where = function(obj, attrs) {
      return _.filter(obj, _.matcher(attrs));
    };
  
    // Convenience version of a common use case of `find`: getting the first object
    // containing specific `key:value` pairs.
    _.findWhere = function(obj, attrs) {
      return _.find(obj, _.matcher(attrs));
    };
  
    // Return the maximum element (or element-based computation).
    _.max = function(obj, iteratee, context) {
      var result = -Infinity, lastComputed = -Infinity,
          value, computed;
      if (iteratee == null && obj != null) {
        obj = isArrayLike(obj) ? obj : _.values(obj);
        for (var i = 0, length = obj.length; i < length; i++) {
          value = obj[i];
          if (value > result) {
            result = value;
          }
        }
      } else {
        iteratee = cb(iteratee, context);
        _.each(obj, function(value, index, list) {
          computed = iteratee(value, index, list);
          if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
            result = value;
            lastComputed = computed;
          }
        });
      }
      return result;
    };
  
    // Return the minimum element (or element-based computation).
    _.min = function(obj, iteratee, context) {
      var result = Infinity, lastComputed = Infinity,
          value, computed;
      if (iteratee == null && obj != null) {
        obj = isArrayLike(obj) ? obj : _.values(obj);
        for (var i = 0, length = obj.length; i < length; i++) {
          value = obj[i];
          if (value < result) {
            result = value;
          }
        }
      } else {
        iteratee = cb(iteratee, context);
        _.each(obj, function(value, index, list) {
          computed = iteratee(value, index, list);
          if (computed < lastComputed || computed === Infinity && result === Infinity) {
            result = value;
            lastComputed = computed;
          }
        });
      }
      return result;
    };
  
    // Shuffle a collection, using the modern version of the
    // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
    _.shuffle = function(obj) {
      var set = isArrayLike(obj) ? obj : _.values(obj);
      var length = set.length;
      var shuffled = Array(length);
      for (var index = 0, rand; index < length; index++) {
        rand = _.random(0, index);
        if (rand !== index) shuffled[index] = shuffled[rand];
        shuffled[rand] = set[index];
      }
      return shuffled;
    };
  
    // Sample **n** random values from a collection.
    // If **n** is not specified, returns a single random element.
    // The internal `guard` argument allows it to work with `map`.
    _.sample = function(obj, n, guard) {
      if (n == null || guard) {
        if (!isArrayLike(obj)) obj = _.values(obj);
        return obj[_.random(obj.length - 1)];
      }
      return _.shuffle(obj).slice(0, Math.max(0, n));
    };
  
    // Sort the object's values by a criterion produced by an iteratee.
    _.sortBy = function(obj, iteratee, context) {
      iteratee = cb(iteratee, context);
      return _.pluck(_.map(obj, function(value, index, list) {
        return {
          value: value,
          index: index,
          criteria: iteratee(value, index, list)
        };
      }).sort(function(left, right) {
        var a = left.criteria;
        var b = right.criteria;
        if (a !== b) {
          if (a > b || a === void 0) return 1;
          if (a < b || b === void 0) return -1;
        }
        return left.index - right.index;
      }), 'value');
    };
  
    // An internal function used for aggregate "group by" operations.
    var group = function(behavior) {
      return function(obj, iteratee, context) {
        var result = {};
        iteratee = cb(iteratee, context);
        _.each(obj, function(value, index) {
          var key = iteratee(value, index, obj);
          behavior(result, value, key);
        });
        return result;
      };
    };
  
    // Groups the object's values by a criterion. Pass either a string attribute
    // to group by, or a function that returns the criterion.
    _.groupBy = group(function(result, value, key) {
      if (_.has(result, key)) result[key].push(value); else result[key] = [value];
    });
  
    // Indexes the object's values by a criterion, similar to `groupBy`, but for
    // when you know that your index values will be unique.
    _.indexBy = group(function(result, value, key) {
      result[key] = value;
    });
  
    // Counts instances of an object that group by a certain criterion. Pass
    // either a string attribute to count by, or a function that returns the
    // criterion.
    _.countBy = group(function(result, value, key) {
      if (_.has(result, key)) result[key]++; else result[key] = 1;
    });
  
    // Safely create a real, live array from anything iterable.
    _.toArray = function(obj) {
      if (!obj) return [];
      if (_.isArray(obj)) return slice.call(obj);
      if (isArrayLike(obj)) return _.map(obj, _.identity);
      return _.values(obj);
    };
  
    // Return the number of elements in an object.
    _.size = function(obj) {
      if (obj == null) return 0;
      return isArrayLike(obj) ? obj.length : _.keys(obj).length;
    };
  
    // Split a collection into two arrays: one whose elements all satisfy the given
    // predicate, and one whose elements all do not satisfy the predicate.
    _.partition = function(obj, predicate, context) {
      predicate = cb(predicate, context);
      var pass = [], fail = [];
      _.each(obj, function(value, key, obj) {
        (predicate(value, key, obj) ? pass : fail).push(value);
      });
      return [pass, fail];
    };
  
    // Array Functions
    // ---------------
  
    // Get the first element of an array. Passing **n** will return the first N
    // values in the array. Aliased as `head` and `take`. The **guard** check
    // allows it to work with `_.map`.
    _.first = _.head = _.take = function(array, n, guard) {
      if (array == null) return void 0;
      if (n == null || guard) return array[0];
      return _.initial(array, array.length - n);
    };
  
    // Returns everything but the last entry of the array. Especially useful on
    // the arguments object. Passing **n** will return all the values in
    // the array, excluding the last N.
    _.initial = function(array, n, guard) {
      return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
    };
  
    // Get the last element of an array. Passing **n** will return the last N
    // values in the array.
    _.last = function(array, n, guard) {
      if (array == null) return void 0;
      if (n == null || guard) return array[array.length - 1];
      return _.rest(array, Math.max(0, array.length - n));
    };
  
    // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
    // Especially useful on the arguments object. Passing an **n** will return
    // the rest N values in the array.
    _.rest = _.tail = _.drop = function(array, n, guard) {
      return slice.call(array, n == null || guard ? 1 : n);
    };
  
    // Trim out all falsy values from an array.
    _.compact = function(array) {
      return _.filter(array, _.identity);
    };
  
    // Internal implementation of a recursive `flatten` function.
    var flatten = function(input, shallow, strict, startIndex) {
      var output = [], idx = 0;
      for (var i = startIndex || 0, length = getLength(input); i < length; i++) {
        var value = input[i];
        if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
          //flatten current level of array or arguments object
          if (!shallow) value = flatten(value, shallow, strict);
          var j = 0, len = value.length;
          output.length += len;
          while (j < len) {
            output[idx++] = value[j++];
          }
        } else if (!strict) {
          output[idx++] = value;
        }
      }
      return output;
    };
  
    // Flatten out an array, either recursively (by default), or just one level.
    _.flatten = function(array, shallow) {
      return flatten(array, shallow, false);
    };
  
    // Return a version of the array that does not contain the specified value(s).
    _.without = function(array) {
      return _.difference(array, slice.call(arguments, 1));
    };
  
    // Produce a duplicate-free version of the array. If the array has already
    // been sorted, you have the option of using a faster algorithm.
    // Aliased as `unique`.
    _.uniq = _.unique = function(array, isSorted, iteratee, context) {
      if (!_.isBoolean(isSorted)) {
        context = iteratee;
        iteratee = isSorted;
        isSorted = false;
      }
      if (iteratee != null) iteratee = cb(iteratee, context);
      var result = [];
      var seen = [];
      for (var i = 0, length = getLength(array); i < length; i++) {
        var value = array[i],
            computed = iteratee ? iteratee(value, i, array) : value;
        if (isSorted) {
          if (!i || seen !== computed) result.push(value);
          seen = computed;
        } else if (iteratee) {
          if (!_.contains(seen, computed)) {
            seen.push(computed);
            result.push(value);
          }
        } else if (!_.contains(result, value)) {
          result.push(value);
        }
      }
      return result;
    };
  
    // Produce an array that contains the union: each distinct element from all of
    // the passed-in arrays.
    _.union = function() {
      return _.uniq(flatten(arguments, true, true));
    };
  
    // Produce an array that contains every item shared between all the
    // passed-in arrays.
    _.intersection = function(array) {
      var result = [];
      var argsLength = arguments.length;
      for (var i = 0, length = getLength(array); i < length; i++) {
        var item = array[i];
        if (_.contains(result, item)) continue;
        for (var j = 1; j < argsLength; j++) {
          if (!_.contains(arguments[j], item)) break;
        }
        if (j === argsLength) result.push(item);
      }
      return result;
    };
  
    // Take the difference between one array and a number of other arrays.
    // Only the elements present in just the first array will remain.
    _.difference = function(array) {
      var rest = flatten(arguments, true, true, 1);
      return _.filter(array, function(value){
        return !_.contains(rest, value);
      });
    };
  
    // Zip together multiple lists into a single array -- elements that share
    // an index go together.
    _.zip = function() {
      return _.unzip(arguments);
    };
  
    // Complement of _.zip. Unzip accepts an array of arrays and groups
    // each array's elements on shared indices
    _.unzip = function(array) {
      var length = array && _.max(array, getLength).length || 0;
      var result = Array(length);
  
      for (var index = 0; index < length; index++) {
        result[index] = _.pluck(array, index);
      }
      return result;
    };
  
    // Converts lists into objects. Pass either a single array of `[key, value]`
    // pairs, or two parallel arrays of the same length -- one of keys, and one of
    // the corresponding values.
    _.object = function(list, values) {
      var result = {};
      for (var i = 0, length = getLength(list); i < length; i++) {
        if (values) {
          result[list[i]] = values[i];
        } else {
          result[list[i][0]] = list[i][1];
        }
      }
      return result;
    };
  
    // Generator function to create the findIndex and findLastIndex functions
    function createPredicateIndexFinder(dir) {
      return function(array, predicate, context) {
        predicate = cb(predicate, context);
        var length = getLength(array);
        var index = dir > 0 ? 0 : length - 1;
        for (; index >= 0 && index < length; index += dir) {
          if (predicate(array[index], index, array)) return index;
        }
        return -1;
      };
    }
  
    // Returns the first index on an array-like that passes a predicate test
    _.findIndex = createPredicateIndexFinder(1);
    _.findLastIndex = createPredicateIndexFinder(-1);
  
    // Use a comparator function to figure out the smallest index at which
    // an object should be inserted so as to maintain order. Uses binary search.
    _.sortedIndex = function(array, obj, iteratee, context) {
      iteratee = cb(iteratee, context, 1);
      var value = iteratee(obj);
      var low = 0, high = getLength(array);
      while (low < high) {
        var mid = Math.floor((low + high) / 2);
        if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
      }
      return low;
    };
  
    // Generator function to create the indexOf and lastIndexOf functions
    function createIndexFinder(dir, predicateFind, sortedIndex) {
      return function(array, item, idx) {
        var i = 0, length = getLength(array);
        if (typeof idx == 'number') {
          if (dir > 0) {
              i = idx >= 0 ? idx : Math.max(idx + length, i);
          } else {
              length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
          }
        } else if (sortedIndex && idx && length) {
          idx = sortedIndex(array, item);
          return array[idx] === item ? idx : -1;
        }
        if (item !== item) {
          idx = predicateFind(slice.call(array, i, length), _.isNaN);
          return idx >= 0 ? idx + i : -1;
        }
        for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
          if (array[idx] === item) return idx;
        }
        return -1;
      };
    }
  
    // Return the position of the first occurrence of an item in an array,
    // or -1 if the item is not included in the array.
    // If the array is large and already in sort order, pass `true`
    // for **isSorted** to use binary search.
    _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
    _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);
  
    // Generate an integer Array containing an arithmetic progression. A port of
    // the native Python `range()` function. See
    // [the Python documentation](http://docs.python.org/library/functions.html#range).
    _.range = function(start, stop, step) {
      if (stop == null) {
        stop = start || 0;
        start = 0;
      }
      step = step || 1;
  
      var length = Math.max(Math.ceil((stop - start) / step), 0);
      var range = Array(length);
  
      for (var idx = 0; idx < length; idx++, start += step) {
        range[idx] = start;
      }
  
      return range;
    };
  
    // Function (ahem) Functions
    // ------------------
  
    // Determines whether to execute a function as a constructor
    // or a normal function with the provided arguments
    var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {
      if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
      var self = baseCreate(sourceFunc.prototype);
      var result = sourceFunc.apply(self, args);
      if (_.isObject(result)) return result;
      return self;
    };
  
    // Create a function bound to a given object (assigning `this`, and arguments,
    // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
    // available.
    _.bind = function(func, context) {
      if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
      if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
      var args = slice.call(arguments, 2);
      var bound = function() {
        return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));
      };
      return bound;
    };
  
    // Partially apply a function by creating a version that has had some of its
    // arguments pre-filled, without changing its dynamic `this` context. _ acts
    // as a placeholder, allowing any combination of arguments to be pre-filled.
    _.partial = function(func) {
      var boundArgs = slice.call(arguments, 1);
      var bound = function() {
        var position = 0, length = boundArgs.length;
        var args = Array(length);
        for (var i = 0; i < length; i++) {
          args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];
        }
        while (position < arguments.length) args.push(arguments[position++]);
        return executeBound(func, bound, this, this, args);
      };
      return bound;
    };
  
    // Bind a number of an object's methods to that object. Remaining arguments
    // are the method names to be bound. Useful for ensuring that all callbacks
    // defined on an object belong to it.
    _.bindAll = function(obj) {
      var i, length = arguments.length, key;
      if (length <= 1) throw new Error('bindAll must be passed function names');
      for (i = 1; i < length; i++) {
        key = arguments[i];
        obj[key] = _.bind(obj[key], obj);
      }
      return obj;
    };
  
    // Memoize an expensive function by storing its results.
    _.memoize = function(func, hasher) {
      var memoize = function(key) {
        var cache = memoize.cache;
        var address = '' + (hasher ? hasher.apply(this, arguments) : key);
        if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
        return cache[address];
      };
      memoize.cache = {};
      return memoize;
    };
  
    // Delays a function for the given number of milliseconds, and then calls
    // it with the arguments supplied.
    _.delay = function(func, wait) {
      var args = slice.call(arguments, 2);
      return setTimeout(function(){
        return func.apply(null, args);
      }, wait);
    };
  
    // Defers a function, scheduling it to run after the current call stack has
    // cleared.
    _.defer = _.partial(_.delay, _, 1);
  
    // Returns a function, that, when invoked, will only be triggered at most once
    // during a given window of time. Normally, the throttled function will run
    // as much as it can, without ever going more than once per `wait` duration;
    // but if you'd like to disable the execution on the leading edge, pass
    // `{leading: false}`. To disable execution on the trailing edge, ditto.
    _.throttle = function(func, wait, options) {
      var context, args, result;
      var timeout = null;
      var previous = 0;
      if (!options) options = {};
      var later = function() {
        previous = options.leading === false ? 0 : _.now();
        timeout = null;
        result = func.apply(context, args);
        if (!timeout) context = args = null;
      };
      return function() {
        var now = _.now();
        if (!previous && options.leading === false) previous = now;
        var remaining = wait - (now - previous);
        context = this;
        args = arguments;
        if (remaining <= 0 || remaining > wait) {
          if (timeout) {
            clearTimeout(timeout);
            timeout = null;
          }
          previous = now;
          result = func.apply(context, args);
          if (!timeout) context = args = null;
        } else if (!timeout && options.trailing !== false) {
          timeout = setTimeout(later, remaining);
        }
        return result;
      };
    };
  
    // Returns a function, that, as long as it continues to be invoked, will not
    // be triggered. The function will be called after it stops being called for
    // N milliseconds. If `immediate` is passed, trigger the function on the
    // leading edge, instead of the trailing.
    _.debounce = function(func, wait, immediate) {
      var timeout, args, context, timestamp, result;
  
      var later = function() {
        var last = _.now() - timestamp;
  
        if (last < wait && last >= 0) {
          timeout = setTimeout(later, wait - last);
        } else {
          timeout = null;
          if (!immediate) {
            result = func.apply(context, args);
            if (!timeout) context = args = null;
          }
        }
      };
  
      return function() {
        context = this;
        args = arguments;
        timestamp = _.now();
        var callNow = immediate && !timeout;
        if (!timeout) timeout = setTimeout(later, wait);
        if (callNow) {
          result = func.apply(context, args);
          context = args = null;
        }
  
        return result;
      };
    };
  
    // Returns the first function passed as an argument to the second,
    // allowing you to adjust arguments, run code before and after, and
    // conditionally execute the original function.
    _.wrap = function(func, wrapper) {
      return _.partial(wrapper, func);
    };
  
    // Returns a negated version of the passed-in predicate.
    _.negate = function(predicate) {
      return function() {
        return !predicate.apply(this, arguments);
      };
    };
  
    // Returns a function that is the composition of a list of functions, each
    // consuming the return value of the function that follows.
    _.compose = function() {
      var args = arguments;
      var start = args.length - 1;
      return function() {
        var i = start;
        var result = args[start].apply(this, arguments);
        while (i--) result = args[i].call(this, result);
        return result;
      };
    };
  
    // Returns a function that will only be executed on and after the Nth call.
    _.after = function(times, func) {
      return function() {
        if (--times < 1) {
          return func.apply(this, arguments);
        }
      };
    };
  
    // Returns a function that will only be executed up to (but not including) the Nth call.
    _.before = function(times, func) {
      var memo;
      return function() {
        if (--times > 0) {
          memo = func.apply(this, arguments);
        }
        if (times <= 1) func = null;
        return memo;
      };
    };
  
    // Returns a function that will be executed at most one time, no matter how
    // often you call it. Useful for lazy initialization.
    _.once = _.partial(_.before, 2);
  
    // Object Functions
    // ----------------
  
    // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
    var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
    var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
                        'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
  
    function collectNonEnumProps(obj, keys) {
      var nonEnumIdx = nonEnumerableProps.length;
      var constructor = obj.constructor;
      var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto;
  
      // Constructor is a special case.
      var prop = 'constructor';
      if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);
  
      while (nonEnumIdx--) {
        prop = nonEnumerableProps[nonEnumIdx];
        if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
          keys.push(prop);
        }
      }
    }
  
    // Retrieve the names of an object's own properties.
    // Delegates to **ECMAScript 5**'s native `Object.keys`
    _.keys = function(obj) {
      if (!_.isObject(obj)) return [];
      if (nativeKeys) return nativeKeys(obj);
      var keys = [];
      for (var key in obj) if (_.has(obj, key)) keys.push(key);
      // Ahem, IE < 9.
      if (hasEnumBug) collectNonEnumProps(obj, keys);
      return keys;
    };
  
    // Retrieve all the property names of an object.
    _.allKeys = function(obj) {
      if (!_.isObject(obj)) return [];
      var keys = [];
      for (var key in obj) keys.push(key);
      // Ahem, IE < 9.
      if (hasEnumBug) collectNonEnumProps(obj, keys);
      return keys;
    };
  
    // Retrieve the values of an object's properties.
    _.values = function(obj) {
      var keys = _.keys(obj);
      var length = keys.length;
      var values = Array(length);
      for (var i = 0; i < length; i++) {
        values[i] = obj[keys[i]];
      }
      return values;
    };
  
    // Returns the results of applying the iteratee to each element of the object
    // In contrast to _.map it returns an object
    _.mapObject = function(obj, iteratee, context) {
      iteratee = cb(iteratee, context);
      var keys =  _.keys(obj),
            length = keys.length,
            results = {},
            currentKey;
        for (var index = 0; index < length; index++) {
          currentKey = keys[index];
          results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
        }
        return results;
    };
  
    // Convert an object into a list of `[key, value]` pairs.
    _.pairs = function(obj) {
      var keys = _.keys(obj);
      var length = keys.length;
      var pairs = Array(length);
      for (var i = 0; i < length; i++) {
        pairs[i] = [keys[i], obj[keys[i]]];
      }
      return pairs;
    };
  
    // Invert the keys and values of an object. The values must be serializable.
    _.invert = function(obj) {
      var result = {};
      var keys = _.keys(obj);
      for (var i = 0, length = keys.length; i < length; i++) {
        result[obj[keys[i]]] = keys[i];
      }
      return result;
    };
  
    // Return a sorted list of the function names available on the object.
    // Aliased as `methods`
    _.functions = _.methods = function(obj) {
      var names = [];
      for (var key in obj) {
        if (_.isFunction(obj[key])) names.push(key);
      }
      return names.sort();
    };
  
    // Extend a given object with all the properties in passed-in object(s).
    _.extend = createAssigner(_.allKeys);
  
    // Assigns a given object with all the own properties in the passed-in object(s)
    // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
    _.extendOwn = _.assign = createAssigner(_.keys);
  
    // Returns the first key on an object that passes a predicate test
    _.findKey = function(obj, predicate, context) {
      predicate = cb(predicate, context);
      var keys = _.keys(obj), key;
      for (var i = 0, length = keys.length; i < length; i++) {
        key = keys[i];
        if (predicate(obj[key], key, obj)) return key;
      }
    };
  
    // Return a copy of the object only containing the whitelisted properties.
    _.pick = function(object, oiteratee, context) {
      var result = {}, obj = object, iteratee, keys;
      if (obj == null) return result;
      if (_.isFunction(oiteratee)) {
        keys = _.allKeys(obj);
        iteratee = optimizeCb(oiteratee, context);
      } else {
        keys = flatten(arguments, false, false, 1);
        iteratee = function(value, key, obj) { return key in obj; };
        obj = Object(obj);
      }
      for (var i = 0, length = keys.length; i < length; i++) {
        var key = keys[i];
        var value = obj[key];
        if (iteratee(value, key, obj)) result[key] = value;
      }
      return result;
    };
  
     // Return a copy of the object without the blacklisted properties.
    _.omit = function(obj, iteratee, context) {
      if (_.isFunction(iteratee)) {
        iteratee = _.negate(iteratee);
      } else {
        var keys = _.map(flatten(arguments, false, false, 1), String);
        iteratee = function(value, key) {
          return !_.contains(keys, key);
        };
      }
      return _.pick(obj, iteratee, context);
    };
  
    // Fill in a given object with default properties.
    _.defaults = createAssigner(_.allKeys, true);
  
    // Creates an object that inherits from the given prototype object.
    // If additional properties are provided then they will be added to the
    // created object.
    _.create = function(prototype, props) {
      var result = baseCreate(prototype);
      if (props) _.extendOwn(result, props);
      return result;
    };
  
    // Create a (shallow-cloned) duplicate of an object.
    _.clone = function(obj) {
      if (!_.isObject(obj)) return obj;
      return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
    };
  
    // Invokes interceptor with the obj, and then returns obj.
    // The primary purpose of this method is to "tap into" a method chain, in
    // order to perform operations on intermediate results within the chain.
    _.tap = function(obj, interceptor) {
      interceptor(obj);
      return obj;
    };
  
    // Returns whether an object has a given set of `key:value` pairs.
    _.isMatch = function(object, attrs) {
      var keys = _.keys(attrs), length = keys.length;
      if (object == null) return !length;
      var obj = Object(object);
      for (var i = 0; i < length; i++) {
        var key = keys[i];
        if (attrs[key] !== obj[key] || !(key in obj)) return false;
      }
      return true;
    };
  
  
    // Internal recursive comparison function for `isEqual`.
    var eq = function(a, b, aStack, bStack) {
      // Identical objects are equal. `0 === -0`, but they aren't identical.
      // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
      if (a === b) return a !== 0 || 1 / a === 1 / b;
      // A strict comparison is necessary because `null == undefined`.
      if (a == null || b == null) return a === b;
      // Unwrap any wrapped objects.
      if (a instanceof _) a = a._wrapped;
      if (b instanceof _) b = b._wrapped;
      // Compare `[[Class]]` names.
      var className = toString.call(a);
      if (className !== toString.call(b)) return false;
      switch (className) {
        // Strings, numbers, regular expressions, dates, and booleans are compared by value.
        case '[object RegExp]':
        // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
        case '[object String]':
          // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
          // equivalent to `new String("5")`.
          return '' + a === '' + b;
        case '[object Number]':
          // `NaN`s are equivalent, but non-reflexive.
          // Object(NaN) is equivalent to NaN
          if (+a !== +a) return +b !== +b;
          // An `egal` comparison is performed for other numeric values.
          return +a === 0 ? 1 / +a === 1 / b : +a === +b;
        case '[object Date]':
        case '[object Boolean]':
          // Coerce dates and booleans to numeric primitive values. Dates are compared by their
          // millisecond representations. Note that invalid dates with millisecond representations
          // of `NaN` are not equivalent.
          return +a === +b;
      }
  
      var areArrays = className === '[object Array]';
      if (!areArrays) {
        if (typeof a != 'object' || typeof b != 'object') return false;
  
        // Objects with different constructors are not equivalent, but `Object`s or `Array`s
        // from different frames are.
        var aCtor = a.constructor, bCtor = b.constructor;
        if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
                                 _.isFunction(bCtor) && bCtor instanceof bCtor)
                            && ('constructor' in a && 'constructor' in b)) {
          return false;
        }
      }
      // Assume equality for cyclic structures. The algorithm for detecting cyclic
      // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
  
      // Initializing stack of traversed objects.
      // It's done here since we only need them for objects and arrays comparison.
      aStack = aStack || [];
      bStack = bStack || [];
      var length = aStack.length;
      while (length--) {
        // Linear search. Performance is inversely proportional to the number of
        // unique nested structures.
        if (aStack[length] === a) return bStack[length] === b;
      }
  
      // Add the first object to the stack of traversed objects.
      aStack.push(a);
      bStack.push(b);
  
      // Recursively compare objects and arrays.
      if (areArrays) {
        // Compare array lengths to determine if a deep comparison is necessary.
        length = a.length;
        if (length !== b.length) return false;
        // Deep compare the contents, ignoring non-numeric properties.
        while (length--) {
          if (!eq(a[length], b[length], aStack, bStack)) return false;
        }
      } else {
        // Deep compare objects.
        var keys = _.keys(a), key;
        length = keys.length;
        // Ensure that both objects contain the same number of properties before comparing deep equality.
        if (_.keys(b).length !== length) return false;
        while (length--) {
          // Deep compare each member
          key = keys[length];
          if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
        }
      }
      // Remove the first object from the stack of traversed objects.
      aStack.pop();
      bStack.pop();
      return true;
    };
  
    // Perform a deep comparison to check if two objects are equal.
    _.isEqual = function(a, b) {
      return eq(a, b);
    };
  
    // Is a given array, string, or object empty?
    // An "empty" object has no enumerable own-properties.
    _.isEmpty = function(obj) {
      if (obj == null) return true;
      if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
      return _.keys(obj).length === 0;
    };
  
    // Is a given value a DOM element?
    _.isElement = function(obj) {
      return !!(obj && obj.nodeType === 1);
    };
  
    // Is a given value an array?
    // Delegates to ECMA5's native Array.isArray
    _.isArray = nativeIsArray || function(obj) {
      return toString.call(obj) === '[object Array]';
    };
  
    // Is a given variable an object?
    _.isObject = function(obj) {
      var type = typeof obj;
      return type === 'function' || type === 'object' && !!obj;
    };
  
    // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.
    _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {
      _['is' + name] = function(obj) {
        return toString.call(obj) === '[object ' + name + ']';
      };
    });
  
    // Define a fallback version of the method in browsers (ahem, IE < 9), where
    // there isn't any inspectable "Arguments" type.
    if (!_.isArguments(arguments)) {
      _.isArguments = function(obj) {
        return _.has(obj, 'callee');
      };
    }
  
    // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
    // IE 11 (#1621), and in Safari 8 (#1929).
    if (typeof /./ != 'function' && typeof Int8Array != 'object') {
      _.isFunction = function(obj) {
        return typeof obj == 'function' || false;
      };
    }
  
    // Is a given object a finite number?
    _.isFinite = function(obj) {
      return isFinite(obj) && !isNaN(parseFloat(obj));
    };
  
    // Is the given value `NaN`? (NaN is the only number which does not equal itself).
    _.isNaN = function(obj) {
      return _.isNumber(obj) && obj !== +obj;
    };
  
    // Is a given value a boolean?
    _.isBoolean = function(obj) {
      return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
    };
  
    // Is a given value equal to null?
    _.isNull = function(obj) {
      return obj === null;
    };
  
    // Is a given variable undefined?
    _.isUndefined = function(obj) {
      return obj === void 0;
    };
  
    // Shortcut function for checking if an object has a given property directly
    // on itself (in other words, not on a prototype).
    _.has = function(obj, key) {
      return obj != null && hasOwnProperty.call(obj, key);
    };
  
    // Utility Functions
    // -----------------
  
    // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
    // previous owner. Returns a reference to the Underscore object.
    _.noConflict = function() {
      root._ = previousUnderscore;
      return this;
    };
  
    // Keep the identity function around for default iteratees.
    _.identity = function(value) {
      return value;
    };
  
    // Predicate-generating functions. Often useful outside of Underscore.
    _.constant = function(value) {
      return function() {
        return value;
      };
    };
  
    _.noop = function(){};
  
    _.property = property;
  
    // Generates a function for a given object that returns a given property.
    _.propertyOf = function(obj) {
      return obj == null ? function(){} : function(key) {
        return obj[key];
      };
    };
  
    // Returns a predicate for checking whether an object has a given set of
    // `key:value` pairs.
    _.matcher = _.matches = function(attrs) {
      attrs = _.extendOwn({}, attrs);
      return function(obj) {
        return _.isMatch(obj, attrs);
      };
    };
  
    // Run a function **n** times.
    _.times = function(n, iteratee, context) {
      var accum = Array(Math.max(0, n));
      iteratee = optimizeCb(iteratee, context, 1);
      for (var i = 0; i < n; i++) accum[i] = iteratee(i);
      return accum;
    };
  
    // Return a random integer between min and max (inclusive).
    _.random = function(min, max) {
      if (max == null) {
        max = min;
        min = 0;
      }
      return min + Math.floor(Math.random() * (max - min + 1));
    };
  
    // A (possibly faster) way to get the current timestamp as an integer.
    _.now = Date.now || function() {
      return new Date().getTime();
    };
  
     // List of HTML entities for escaping.
    var escapeMap = {
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
      '"': '&quot;',
      "'": '&#x27;',
      '`': '&#x60;'
    };
    var unescapeMap = _.invert(escapeMap);
  
    // Functions for escaping and unescaping strings to/from HTML interpolation.
    var createEscaper = function(map) {
      var escaper = function(match) {
        return map[match];
      };
      // Regexes for identifying a key that needs to be escaped
      var source = '(?:' + _.keys(map).join('|') + ')';
      var testRegexp = RegExp(source);
      var replaceRegexp = RegExp(source, 'g');
      return function(string) {
        string = string == null ? '' : '' + string;
        return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
      };
    };
    _.escape = createEscaper(escapeMap);
    _.unescape = createEscaper(unescapeMap);
  
    // If the value of the named `property` is a function then invoke it with the
    // `object` as context; otherwise, return it.
    _.result = function(object, property, fallback) {
      var value = object == null ? void 0 : object[property];
      if (value === void 0) {
        value = fallback;
      }
      return _.isFunction(value) ? value.call(object) : value;
    };
  
    // Generate a unique integer id (unique within the entire client session).
    // Useful for temporary DOM ids.
    var idCounter = 0;
    _.uniqueId = function(prefix) {
      var id = ++idCounter + '';
      return prefix ? prefix + id : id;
    };
  
    // By default, Underscore uses ERB-style template delimiters, change the
    // following template settings to use alternative delimiters.
    _.templateSettings = {
      evaluate    : /<%([\s\S]+?)%>/g,
      interpolate : /<%=([\s\S]+?)%>/g,
      escape      : /<%-([\s\S]+?)%>/g
    };
  
    // When customizing `templateSettings`, if you don't want to define an
    // interpolation, evaluation or escaping regex, we need one that is
    // guaranteed not to match.
    var noMatch = /(.)^/;
  
    // Certain characters need to be escaped so that they can be put into a
    // string literal.
    var escapes = {
      "'":      "'",
      '\\':     '\\',
      '\r':     'r',
      '\n':     'n',
      '\u2028': 'u2028',
      '\u2029': 'u2029'
    };
  
    var escaper = /\\|'|\r|\n|\u2028|\u2029/g;
  
    var escapeChar = function(match) {
      return '\\' + escapes[match];
    };
  
    // JavaScript micro-templating, similar to John Resig's implementation.
    // Underscore templating handles arbitrary delimiters, preserves whitespace,
    // and correctly escapes quotes within interpolated code.
    // NB: `oldSettings` only exists for backwards compatibility.
    _.template = function(text, settings, oldSettings) {
      if (!settings && oldSettings) settings = oldSettings;
      settings = _.defaults({}, settings, _.templateSettings);
  
      // Combine delimiters into one regular expression via alternation.
      var matcher = RegExp([
        (settings.escape || noMatch).source,
        (settings.interpolate || noMatch).source,
        (settings.evaluate || noMatch).source
      ].join('|') + '|$', 'g');
  
      // Compile the template source, escaping string literals appropriately.
      var index = 0;
      var source = "__p+='";
      text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
        source += text.slice(index, offset).replace(escaper, escapeChar);
        index = offset + match.length;
  
        if (escape) {
          source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
        } else if (interpolate) {
          source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
        } else if (evaluate) {
          source += "';\n" + evaluate + "\n__p+='";
        }
  
        // Adobe VMs need the match returned to produce the correct offest.
        return match;
      });
      source += "';\n";
  
      // If a variable is not specified, place data values in local scope.
      if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
  
      source = "var __t,__p='',__j=Array.prototype.join," +
        "print=function(){__p+=__j.call(arguments,'');};\n" +
        source + 'return __p;\n';
  
      try {
        var render = new Function(settings.variable || 'obj', '_', source);
      } catch (e) {
        e.source = source;
        throw e;
      }
  
      var template = function(data) {
        return render.call(this, data, _);
      };
  
      // Provide the compiled source as a convenience for precompilation.
      var argument = settings.variable || 'obj';
      template.source = 'function(' + argument + '){\n' + source + '}';
  
      return template;
    };
  
    // Add a "chain" function. Start chaining a wrapped Underscore object.
    _.chain = function(obj) {
      var instance = _(obj);
      instance._chain = true;
      return instance;
    };
  
    // OOP
    // ---------------
    // If Underscore is called as a function, it returns a wrapped object that
    // can be used OO-style. This wrapper holds altered versions of all the
    // underscore functions. Wrapped objects may be chained.
  
    // Helper function to continue chaining intermediate results.
    var result = function(instance, obj) {
      return instance._chain ? _(obj).chain() : obj;
    };
  
    // Add your own custom functions to the Underscore object.
    _.mixin = function(obj) {
      _.each(_.functions(obj), function(name) {
        var func = _[name] = obj[name];
        _.prototype[name] = function() {
          var args = [this._wrapped];
          push.apply(args, arguments);
          return result(this, func.apply(_, args));
        };
      });
    };
  
    // Add all of the Underscore functions to the wrapper object.
    _.mixin(_);
  
    // Add all mutator Array functions to the wrapper.
    _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
      var method = ArrayProto[name];
      _.prototype[name] = function() {
        var obj = this._wrapped;
        method.apply(obj, arguments);
        if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
        return result(this, obj);
      };
    });
  
    // Add all accessor Array functions to the wrapper.
    _.each(['concat', 'join', 'slice'], function(name) {
      var method = ArrayProto[name];
      _.prototype[name] = function() {
        return result(this, method.apply(this._wrapped, arguments));
      };
    });
  
    // Extracts the result from a wrapped and chained object.
    _.prototype.value = function() {
      return this._wrapped;
    };
  
    // Provide unwrapping proxy for some methods used in engine operations
    // such as arithmetic and JSON stringification.
    _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
  
    _.prototype.toString = function() {
      return '' + this._wrapped;
    };
  
    // AMD registration happens at the end for compatibility with AMD loaders
    // that may not enforce next-turn semantics on modules. Even though general
    // practice for AMD registration is to be anonymous, underscore registers
    // as a named module because, like jQuery, it is a base library that is
    // popular enough to be bundled in a third party lib, but not be part of
    // an AMD load request. Those cases could generate an error when an
    // anonymous define() is called outside of a loader request.
    if (typeof define === 'function' && define.amd) {
      define('underscore', [], function() {
        return _;
      });
    }
  }.call(this));
  
  },{}],86:[function(require,module,exports){
  // http://wiki.commonjs.org/wiki/Unit_Testing/1.0
  //
  // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
  //
  // Originally from narwhal.js (http://narwhaljs.org)
  // Copyright (c) 2009 Thomas Robinson <280north.com>
  //
  // Permission is hereby granted, free of charge, to any person obtaining a copy
  // of this software and associated documentation files (the 'Software'), to
  // deal in the Software without restriction, including without limitation the
  // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  // sell copies of the Software, and to permit persons to whom the Software is
  // furnished to do so, subject to the following conditions:
  //
  // The above copyright notice and this permission notice shall be included in
  // all copies or substantial portions of the Software.
  //
  // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  
  // when used in node, this will actually load the util module we depend on
  // versus loading the builtin util module as happens otherwise
  // this is a bug in node module loading as far as I am concerned
  var util = require('util/');
  
  var pSlice = Array.prototype.slice;
  var hasOwn = Object.prototype.hasOwnProperty;
  
  // 1. The assert module provides functions that throw
  // AssertionError's when particular conditions are not met. The
  // assert module must conform to the following interface.
  
  var assert = module.exports = ok;
  
  // 2. The AssertionError is defined in assert.
  // new assert.AssertionError({ message: message,
  //                             actual: actual,
  //                             expected: expected })
  
  assert.AssertionError = function AssertionError(options) {
    this.name = 'AssertionError';
    this.actual = options.actual;
    this.expected = options.expected;
    this.operator = options.operator;
    if (options.message) {
      this.message = options.message;
      this.generatedMessage = false;
    } else {
      this.message = getMessage(this);
      this.generatedMessage = true;
    }
    var stackStartFunction = options.stackStartFunction || fail;
  
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, stackStartFunction);
    }
    else {
      // non v8 browsers so we can have a stacktrace
      var err = new Error();
      if (err.stack) {
        var out = err.stack;
  
        // try to strip useless frames
        var fn_name = stackStartFunction.name;
        var idx = out.indexOf('\n' + fn_name);
        if (idx >= 0) {
          // once we have located the function frame
          // we need to strip out everything before it (and its line)
          var next_line = out.indexOf('\n', idx + 1);
          out = out.substring(next_line + 1);
        }
  
        this.stack = out;
      }
    }
  };
  
  // assert.AssertionError instanceof Error
  util.inherits(assert.AssertionError, Error);
  
  function replacer(key, value) {
    if (util.isUndefined(value)) {
      return '' + value;
    }
    if (util.isNumber(value) && !isFinite(value)) {
      return value.toString();
    }
    if (util.isFunction(value) || util.isRegExp(value)) {
      return value.toString();
    }
    return value;
  }
  
  function truncate(s, n) {
    if (util.isString(s)) {
      return s.length < n ? s : s.slice(0, n);
    } else {
      return s;
    }
  }
  
  function getMessage(self) {
    return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' +
           self.operator + ' ' +
           truncate(JSON.stringify(self.expected, replacer), 128);
  }
  
  // At present only the three keys mentioned above are used and
  // understood by the spec. Implementations or sub modules can pass
  // other keys to the AssertionError's constructor - they will be
  // ignored.
  
  // 3. All of the following functions must throw an AssertionError
  // when a corresponding condition is not met, with a message that
  // may be undefined if not provided.  All assertion methods provide
  // both the actual and expected values to the assertion error for
  // display purposes.
  
  function fail(actual, expected, message, operator, stackStartFunction) {
    throw new assert.AssertionError({
      message: message,
      actual: actual,
      expected: expected,
      operator: operator,
      stackStartFunction: stackStartFunction
    });
  }
  
  // EXTENSION! allows for well behaved errors defined elsewhere.
  assert.fail = fail;
  
  // 4. Pure assertion tests whether a value is truthy, as determined
  // by !!guard.
  // assert.ok(guard, message_opt);
  // This statement is equivalent to assert.equal(true, !!guard,
  // message_opt);. To test strictly for the value true, use
  // assert.strictEqual(true, guard, message_opt);.
  
  function ok(value, message) {
    if (!value) fail(value, true, message, '==', assert.ok);
  }
  assert.ok = ok;
  
  // 5. The equality assertion tests shallow, coercive equality with
  // ==.
  // assert.equal(actual, expected, message_opt);
  
  assert.equal = function equal(actual, expected, message) {
    if (actual != expected) fail(actual, expected, message, '==', assert.equal);
  };
  
  // 6. The non-equality assertion tests for whether two objects are not equal
  // with != assert.notEqual(actual, expected, message_opt);
  
  assert.notEqual = function notEqual(actual, expected, message) {
    if (actual == expected) {
      fail(actual, expected, message, '!=', assert.notEqual);
    }
  };
  
  // 7. The equivalence assertion tests a deep equality relation.
  // assert.deepEqual(actual, expected, message_opt);
  
  assert.deepEqual = function deepEqual(actual, expected, message) {
    if (!_deepEqual(actual, expected)) {
      fail(actual, expected, message, 'deepEqual', assert.deepEqual);
    }
  };
  
  function _deepEqual(actual, expected) {
    // 7.1. All identical values are equivalent, as determined by ===.
    if (actual === expected) {
      return true;
  
    } else if (util.isBuffer(actual) && util.isBuffer(expected)) {
      if (actual.length != expected.length) return false;
  
      for (var i = 0; i < actual.length; i++) {
        if (actual[i] !== expected[i]) return false;
      }
  
      return true;
  
    // 7.2. If the expected value is a Date object, the actual value is
    // equivalent if it is also a Date object that refers to the same time.
    } else if (util.isDate(actual) && util.isDate(expected)) {
      return actual.getTime() === expected.getTime();
  
    // 7.3 If the expected value is a RegExp object, the actual value is
    // equivalent if it is also a RegExp object with the same source and
    // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
    } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
      return actual.source === expected.source &&
             actual.global === expected.global &&
             actual.multiline === expected.multiline &&
             actual.lastIndex === expected.lastIndex &&
             actual.ignoreCase === expected.ignoreCase;
  
    // 7.4. Other pairs that do not both pass typeof value == 'object',
    // equivalence is determined by ==.
    } else if (!util.isObject(actual) && !util.isObject(expected)) {
      return actual == expected;
  
    // 7.5 For all other Object pairs, including Array objects, equivalence is
    // determined by having the same number of owned properties (as verified
    // with Object.prototype.hasOwnProperty.call), the same set of keys
    // (although not necessarily the same order), equivalent values for every
    // corresponding key, and an identical 'prototype' property. Note: this
    // accounts for both named and indexed properties on Arrays.
    } else {
      return objEquiv(actual, expected);
    }
  }
  
  function isArguments(object) {
    return Object.prototype.toString.call(object) == '[object Arguments]';
  }
  
  function objEquiv(a, b) {
    if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b))
      return false;
    // an identical 'prototype' property.
    if (a.prototype !== b.prototype) return false;
    // if one is a primitive, the other must be same
    if (util.isPrimitive(a) || util.isPrimitive(b)) {
      return a === b;
    }
    var aIsArgs = isArguments(a),
        bIsArgs = isArguments(b);
    if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
      return false;
    if (aIsArgs) {
      a = pSlice.call(a);
      b = pSlice.call(b);
      return _deepEqual(a, b);
    }
    var ka = objectKeys(a),
        kb = objectKeys(b),
        key, i;
    // having the same number of owned properties (keys incorporates
    // hasOwnProperty)
    if (ka.length != kb.length)
      return false;
    //the same set of keys (although not necessarily the same order),
    ka.sort();
    kb.sort();
    //~~~cheap key test
    for (i = ka.length - 1; i >= 0; i--) {
      if (ka[i] != kb[i])
        return false;
    }
    //equivalent values for every corresponding key, and
    //~~~possibly expensive deep test
    for (i = ka.length - 1; i >= 0; i--) {
      key = ka[i];
      if (!_deepEqual(a[key], b[key])) return false;
    }
    return true;
  }
  
  // 8. The non-equivalence assertion tests for any deep inequality.
  // assert.notDeepEqual(actual, expected, message_opt);
  
  assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
    if (_deepEqual(actual, expected)) {
      fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
    }
  };
  
  // 9. The strict equality assertion tests strict equality, as determined by ===.
  // assert.strictEqual(actual, expected, message_opt);
  
  assert.strictEqual = function strictEqual(actual, expected, message) {
    if (actual !== expected) {
      fail(actual, expected, message, '===', assert.strictEqual);
    }
  };
  
  // 10. The strict non-equality assertion tests for strict inequality, as
  // determined by !==.  assert.notStrictEqual(actual, expected, message_opt);
  
  assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
    if (actual === expected) {
      fail(actual, expected, message, '!==', assert.notStrictEqual);
    }
  };
  
  function expectedException(actual, expected) {
    if (!actual || !expected) {
      return false;
    }
  
    if (Object.prototype.toString.call(expected) == '[object RegExp]') {
      return expected.test(actual);
    } else if (actual instanceof expected) {
      return true;
    } else if (expected.call({}, actual) === true) {
      return true;
    }
  
    return false;
  }
  
  function _throws(shouldThrow, block, expected, message) {
    var actual;
  
    if (util.isString(expected)) {
      message = expected;
      expected = null;
    }
  
    try {
      block();
    } catch (e) {
      actual = e;
    }
  
    message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
              (message ? ' ' + message : '.');
  
    if (shouldThrow && !actual) {
      fail(actual, expected, 'Missing expected exception' + message);
    }
  
    if (!shouldThrow && expectedException(actual, expected)) {
      fail(actual, expected, 'Got unwanted exception' + message);
    }
  
    if ((shouldThrow && actual && expected &&
        !expectedException(actual, expected)) || (!shouldThrow && actual)) {
      throw actual;
    }
  }
  
  // 11. Expected to throw an error:
  // assert.throws(block, Error_opt, message_opt);
  
  assert.throws = function(block, /*optional*/error, /*optional*/message) {
    _throws.apply(this, [true].concat(pSlice.call(arguments)));
  };
  
  // EXTENSION! This is annoying to write outside this module.
  assert.doesNotThrow = function(block, /*optional*/message) {
    _throws.apply(this, [false].concat(pSlice.call(arguments)));
  };
  
  assert.ifError = function(err) { if (err) {throw err;}};
  
  var objectKeys = Object.keys || function (obj) {
    var keys = [];
    for (var key in obj) {
      if (hasOwn.call(obj, key)) keys.push(key);
    }
    return keys;
  };
  
  },{"util/":94}],87:[function(require,module,exports){
  'use strict'
  
  exports.toByteArray = toByteArray
  exports.fromByteArray = fromByteArray
  
  var lookup = []
  var revLookup = []
  var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  
  function init () {
    var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
    for (var i = 0, len = code.length; i < len; ++i) {
      lookup[i] = code[i]
      revLookup[code.charCodeAt(i)] = i
    }
  
    revLookup['-'.charCodeAt(0)] = 62
    revLookup['_'.charCodeAt(0)] = 63
  }
  
  init()
  
  function toByteArray (b64) {
    var i, j, l, tmp, placeHolders, arr
    var len = b64.length
  
    if (len % 4 > 0) {
      throw new Error('Invalid string. Length must be a multiple of 4')
    }
  
    // the number of equal signs (place holders)
    // if there are two placeholders, than the two characters before it
    // represent one byte
    // if there is only one, then the three characters before it represent 2 bytes
    // this is just a cheap hack to not do indexOf twice
    placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
  
    // base64 is 4/3 + up to two characters of the original data
    arr = new Arr(len * 3 / 4 - placeHolders)
  
    // if there are placeholders, only get up to the last complete 4 chars
    l = placeHolders > 0 ? len - 4 : len
  
    var L = 0
  
    for (i = 0, j = 0; i < l; i += 4, j += 3) {
      tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
      arr[L++] = (tmp >> 16) & 0xFF
      arr[L++] = (tmp >> 8) & 0xFF
      arr[L++] = tmp & 0xFF
    }
  
    if (placeHolders === 2) {
      tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
      arr[L++] = tmp & 0xFF
    } else if (placeHolders === 1) {
      tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
      arr[L++] = (tmp >> 8) & 0xFF
      arr[L++] = tmp & 0xFF
    }
  
    return arr
  }
  
  function tripletToBase64 (num) {
    return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  }
  
  function encodeChunk (uint8, start, end) {
    var tmp
    var output = []
    for (var i = start; i < end; i += 3) {
      tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
      output.push(tripletToBase64(tmp))
    }
    return output.join('')
  }
  
  function fromByteArray (uint8) {
    var tmp
    var len = uint8.length
    var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
    var output = ''
    var parts = []
    var maxChunkLength = 16383 // must be multiple of 3
  
    // go through the array every three bytes, we'll deal with trailing stuff later
    for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
      parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
    }
  
    // pad the end with zeros, but make sure to not forget the extra bytes
    if (extraBytes === 1) {
      tmp = uint8[len - 1]
      output += lookup[tmp >> 2]
      output += lookup[(tmp << 4) & 0x3F]
      output += '=='
    } else if (extraBytes === 2) {
      tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
      output += lookup[tmp >> 10]
      output += lookup[(tmp >> 4) & 0x3F]
      output += lookup[(tmp << 2) & 0x3F]
      output += '='
    }
  
    parts.push(output)
  
    return parts.join('')
  }
  
  },{}],88:[function(require,module,exports){
  (function (global){
  /*!
   * The buffer module from node.js, for the browser.
   *
   * @author   Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
   * @license  MIT
   */
  /* eslint-disable no-proto */
  
  'use strict'
  
  var base64 = require('base64-js')
  var ieee754 = require('ieee754')
  var isArray = require('isarray')
  
  exports.Buffer = Buffer
  exports.SlowBuffer = SlowBuffer
  exports.INSPECT_MAX_BYTES = 50
  Buffer.poolSize = 8192 // not used by this implementation
  
  var rootParent = {}
  
  /**
   * If `Buffer.TYPED_ARRAY_SUPPORT`:
   *   === true    Use Uint8Array implementation (fastest)
   *   === false   Use Object implementation (most compatible, even IE6)
   *
   * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
   * Opera 11.6+, iOS 4.2+.
   *
   * Due to various browser bugs, sometimes the Object implementation will be used even
   * when the browser supports typed arrays.
   *
   * Note:
   *
   *   - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
   *     See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
   *
   *   - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
   *
   *   - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
   *     incorrect length in some situations.
  
   * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
   * get the Object implementation, which is slower but behaves correctly.
   */
  Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
    ? global.TYPED_ARRAY_SUPPORT
    : typedArraySupport()
  
  function typedArraySupport () {
    try {
      var arr = new Uint8Array(1)
      arr.foo = function () { return 42 }
      return arr.foo() === 42 && // typed array instances can be augmented
          typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
          arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
    } catch (e) {
      return false
    }
  }
  
  function kMaxLength () {
    return Buffer.TYPED_ARRAY_SUPPORT
      ? 0x7fffffff
      : 0x3fffffff
  }
  
  /**
   * The Buffer constructor returns instances of `Uint8Array` that have their
   * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
   * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
   * and the `Uint8Array` methods. Square bracket notation works as expected -- it
   * returns a single octet.
   *
   * The `Uint8Array` prototype remains unmodified.
   */
  function Buffer (arg) {
    if (!(this instanceof Buffer)) {
      // Avoid going through an ArgumentsAdaptorTrampoline in the common case.
      if (arguments.length > 1) return new Buffer(arg, arguments[1])
      return new Buffer(arg)
    }
  
    if (!Buffer.TYPED_ARRAY_SUPPORT) {
      this.length = 0
      this.parent = undefined
    }
  
    // Common case.
    if (typeof arg === 'number') {
      return fromNumber(this, arg)
    }
  
    // Slightly less common case.
    if (typeof arg === 'string') {
      return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8')
    }
  
    // Unusual.
    return fromObject(this, arg)
  }
  
  // TODO: Legacy, not needed anymore. Remove in next major version.
  Buffer._augment = function (arr) {
    arr.__proto__ = Buffer.prototype
    return arr
  }
  
  function fromNumber (that, length) {
    that = allocate(that, length < 0 ? 0 : checked(length) | 0)
    if (!Buffer.TYPED_ARRAY_SUPPORT) {
      for (var i = 0; i < length; i++) {
        that[i] = 0
      }
    }
    return that
  }
  
  function fromString (that, string, encoding) {
    if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8'
  
    // Assumption: byteLength() return value is always < kMaxLength.
    var length = byteLength(string, encoding) | 0
    that = allocate(that, length)
  
    that.write(string, encoding)
    return that
  }
  
  function fromObject (that, object) {
    if (Buffer.isBuffer(object)) return fromBuffer(that, object)
  
    if (isArray(object)) return fromArray(that, object)
  
    if (object == null) {
      throw new TypeError('must start with number, buffer, array or string')
    }
  
    if (typeof ArrayBuffer !== 'undefined') {
      if (object.buffer instanceof ArrayBuffer) {
        return fromTypedArray(that, object)
      }
      if (object instanceof ArrayBuffer) {
        return fromArrayBuffer(that, object)
      }
    }
  
    if (object.length) return fromArrayLike(that, object)
  
    return fromJsonObject(that, object)
  }
  
  function fromBuffer (that, buffer) {
    var length = checked(buffer.length) | 0
    that = allocate(that, length)
    buffer.copy(that, 0, 0, length)
    return that
  }
  
  function fromArray (that, array) {
    var length = checked(array.length) | 0
    that = allocate(that, length)
    for (var i = 0; i < length; i += 1) {
      that[i] = array[i] & 255
    }
    return that
  }
  
  // Duplicate of fromArray() to keep fromArray() monomorphic.
  function fromTypedArray (that, array) {
    var length = checked(array.length) | 0
    that = allocate(that, length)
    // Truncating the elements is probably not what people expect from typed
    // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior
    // of the old Buffer constructor.
    for (var i = 0; i < length; i += 1) {
      that[i] = array[i] & 255
    }
    return that
  }
  
  function fromArrayBuffer (that, array) {
    array.byteLength // this throws if `array` is not a valid ArrayBuffer
  
    if (Buffer.TYPED_ARRAY_SUPPORT) {
      // Return an augmented `Uint8Array` instance, for best performance
      that = new Uint8Array(array)
      that.__proto__ = Buffer.prototype
    } else {
      // Fallback: Return an object instance of the Buffer class
      that = fromTypedArray(that, new Uint8Array(array))
    }
    return that
  }
  
  function fromArrayLike (that, array) {
    var length = checked(array.length) | 0
    that = allocate(that, length)
    for (var i = 0; i < length; i += 1) {
      that[i] = array[i] & 255
    }
    return that
  }
  
  // Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object.
  // Returns a zero-length buffer for inputs that don't conform to the spec.
  function fromJsonObject (that, object) {
    var array
    var length = 0
  
    if (object.type === 'Buffer' && isArray(object.data)) {
      array = object.data
      length = checked(array.length) | 0
    }
    that = allocate(that, length)
  
    for (var i = 0; i < length; i += 1) {
      that[i] = array[i] & 255
    }
    return that
  }
  
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    Buffer.prototype.__proto__ = Uint8Array.prototype
    Buffer.__proto__ = Uint8Array
    if (typeof Symbol !== 'undefined' && Symbol.species &&
        Buffer[Symbol.species] === Buffer) {
      // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
      Object.defineProperty(Buffer, Symbol.species, {
        value: null,
        configurable: true
      })
    }
  } else {
    // pre-set for values that may exist in the future
    Buffer.prototype.length = undefined
    Buffer.prototype.parent = undefined
  }
  
  function allocate (that, length) {
    if (Buffer.TYPED_ARRAY_SUPPORT) {
      // Return an augmented `Uint8Array` instance, for best performance
      that = new Uint8Array(length)
      that.__proto__ = Buffer.prototype
    } else {
      // Fallback: Return an object instance of the Buffer class
      that.length = length
    }
  
    var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1
    if (fromPool) that.parent = rootParent
  
    return that
  }
  
  function checked (length) {
    // Note: cannot use `length < kMaxLength` here because that fails when
    // length is NaN (which is otherwise coerced to zero.)
    if (length >= kMaxLength()) {
      throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
                           'size: 0x' + kMaxLength().toString(16) + ' bytes')
    }
    return length | 0
  }
  
  function SlowBuffer (subject, encoding) {
    if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding)
  
    var buf = new Buffer(subject, encoding)
    delete buf.parent
    return buf
  }
  
  Buffer.isBuffer = function isBuffer (b) {
    return !!(b != null && b._isBuffer)
  }
  
  Buffer.compare = function compare (a, b) {
    if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
      throw new TypeError('Arguments must be Buffers')
    }
  
    if (a === b) return 0
  
    var x = a.length
    var y = b.length
  
    for (var i = 0, len = Math.min(x, y); i < len; ++i) {
      if (a[i] !== b[i]) {
        x = a[i]
        y = b[i]
        break
      }
    }
  
    if (x < y) return -1
    if (y < x) return 1
    return 0
  }
  
  Buffer.isEncoding = function isEncoding (encoding) {
    switch (String(encoding).toLowerCase()) {
      case 'hex':
      case 'utf8':
      case 'utf-8':
      case 'ascii':
      case 'binary':
      case 'base64':
      case 'raw':
      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return true
      default:
        return false
    }
  }
  
  Buffer.concat = function concat (list, length) {
    if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.')
  
    if (list.length === 0) {
      return new Buffer(0)
    }
  
    var i
    if (length === undefined) {
      length = 0
      for (i = 0; i < list.length; i++) {
        length += list[i].length
      }
    }
  
    var buf = new Buffer(length)
    var pos = 0
    for (i = 0; i < list.length; i++) {
      var item = list[i]
      item.copy(buf, pos)
      pos += item.length
    }
    return buf
  }
  
  function byteLength (string, encoding) {
    if (typeof string !== 'string') string = '' + string
  
    var len = string.length
    if (len === 0) return 0
  
    // Use a for loop to avoid recursion
    var loweredCase = false
    for (;;) {
      switch (encoding) {
        case 'ascii':
        case 'binary':
        // Deprecated
        case 'raw':
        case 'raws':
          return len
        case 'utf8':
        case 'utf-8':
          return utf8ToBytes(string).length
        case 'ucs2':
        case 'ucs-2':
        case 'utf16le':
        case 'utf-16le':
          return len * 2
        case 'hex':
          return len >>> 1
        case 'base64':
          return base64ToBytes(string).length
        default:
          if (loweredCase) return utf8ToBytes(string).length // assume utf8
          encoding = ('' + encoding).toLowerCase()
          loweredCase = true
      }
    }
  }
  Buffer.byteLength = byteLength
  
  function slowToString (encoding, start, end) {
    var loweredCase = false
  
    start = start | 0
    end = end === undefined || end === Infinity ? this.length : end | 0
  
    if (!encoding) encoding = 'utf8'
    if (start < 0) start = 0
    if (end > this.length) end = this.length
    if (end <= start) return ''
  
    while (true) {
      switch (encoding) {
        case 'hex':
          return hexSlice(this, start, end)
  
        case 'utf8':
        case 'utf-8':
          return utf8Slice(this, start, end)
  
        case 'ascii':
          return asciiSlice(this, start, end)
  
        case 'binary':
          return binarySlice(this, start, end)
  
        case 'base64':
          return base64Slice(this, start, end)
  
        case 'ucs2':
        case 'ucs-2':
        case 'utf16le':
        case 'utf-16le':
          return utf16leSlice(this, start, end)
  
        default:
          if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
          encoding = (encoding + '').toLowerCase()
          loweredCase = true
      }
    }
  }
  
  // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  // Buffer instances.
  Buffer.prototype._isBuffer = true
  
  Buffer.prototype.toString = function toString () {
    var length = this.length | 0
    if (length === 0) return ''
    if (arguments.length === 0) return utf8Slice(this, 0, length)
    return slowToString.apply(this, arguments)
  }
  
  Buffer.prototype.equals = function equals (b) {
    if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
    if (this === b) return true
    return Buffer.compare(this, b) === 0
  }
  
  Buffer.prototype.inspect = function inspect () {
    var str = ''
    var max = exports.INSPECT_MAX_BYTES
    if (this.length > 0) {
      str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
      if (this.length > max) str += ' ... '
    }
    return '<Buffer ' + str + '>'
  }
  
  Buffer.prototype.compare = function compare (b) {
    if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
    return Buffer.compare(this, b)
  }
  
  Buffer.prototype.indexOf = function indexOf (val, byteOffset) {
    if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff
    else if (byteOffset < -0x80000000) byteOffset = -0x80000000
    byteOffset >>= 0
  
    if (this.length === 0) return -1
    if (byteOffset >= this.length) return -1
  
    // Negative offsets start from the end of the buffer
    if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
  
    if (typeof val === 'string') {
      if (val.length === 0) return -1 // special case: looking for empty string always fails
      return String.prototype.indexOf.call(this, val, byteOffset)
    }
    if (Buffer.isBuffer(val)) {
      return arrayIndexOf(this, val, byteOffset)
    }
    if (typeof val === 'number') {
      if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
        return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
      }
      return arrayIndexOf(this, [ val ], byteOffset)
    }
  
    function arrayIndexOf (arr, val, byteOffset) {
      var foundIndex = -1
      for (var i = 0; byteOffset + i < arr.length; i++) {
        if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) {
          if (foundIndex === -1) foundIndex = i
          if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex
        } else {
          foundIndex = -1
        }
      }
      return -1
    }
  
    throw new TypeError('val must be string, number or Buffer')
  }
  
  function hexWrite (buf, string, offset, length) {
    offset = Number(offset) || 0
    var remaining = buf.length - offset
    if (!length) {
      length = remaining
    } else {
      length = Number(length)
      if (length > remaining) {
        length = remaining
      }
    }
  
    // must be an even number of digits
    var strLen = string.length
    if (strLen % 2 !== 0) throw new Error('Invalid hex string')
  
    if (length > strLen / 2) {
      length = strLen / 2
    }
    for (var i = 0; i < length; i++) {
      var parsed = parseInt(string.substr(i * 2, 2), 16)
      if (isNaN(parsed)) throw new Error('Invalid hex string')
      buf[offset + i] = parsed
    }
    return i
  }
  
  function utf8Write (buf, string, offset, length) {
    return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  }
  
  function asciiWrite (buf, string, offset, length) {
    return blitBuffer(asciiToBytes(string), buf, offset, length)
  }
  
  function binaryWrite (buf, string, offset, length) {
    return asciiWrite(buf, string, offset, length)
  }
  
  function base64Write (buf, string, offset, length) {
    return blitBuffer(base64ToBytes(string), buf, offset, length)
  }
  
  function ucs2Write (buf, string, offset, length) {
    return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  }
  
  Buffer.prototype.write = function write (string, offset, length, encoding) {
    // Buffer#write(string)
    if (offset === undefined) {
      encoding = 'utf8'
      length = this.length
      offset = 0
    // Buffer#write(string, encoding)
    } else if (length === undefined && typeof offset === 'string') {
      encoding = offset
      length = this.length
      offset = 0
    // Buffer#write(string, offset[, length][, encoding])
    } else if (isFinite(offset)) {
      offset = offset | 0
      if (isFinite(length)) {
        length = length | 0
        if (encoding === undefined) encoding = 'utf8'
      } else {
        encoding = length
        length = undefined
      }
    // legacy write(string, encoding, offset, length) - remove in v0.13
    } else {
      var swap = encoding
      encoding = offset
      offset = length | 0
      length = swap
    }
  
    var remaining = this.length - offset
    if (length === undefined || length > remaining) length = remaining
  
    if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
      throw new RangeError('attempt to write outside buffer bounds')
    }
  
    if (!encoding) encoding = 'utf8'
  
    var loweredCase = false
    for (;;) {
      switch (encoding) {
        case 'hex':
          return hexWrite(this, string, offset, length)
  
        case 'utf8':
        case 'utf-8':
          return utf8Write(this, string, offset, length)
  
        case 'ascii':
          return asciiWrite(this, string, offset, length)
  
        case 'binary':
          return binaryWrite(this, string, offset, length)
  
        case 'base64':
          // Warning: maxLength not taken into account in base64Write
          return base64Write(this, string, offset, length)
  
        case 'ucs2':
        case 'ucs-2':
        case 'utf16le':
        case 'utf-16le':
          return ucs2Write(this, string, offset, length)
  
        default:
          if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
          encoding = ('' + encoding).toLowerCase()
          loweredCase = true
      }
    }
  }
  
  Buffer.prototype.toJSON = function toJSON () {
    return {
      type: 'Buffer',
      data: Array.prototype.slice.call(this._arr || this, 0)
    }
  }
  
  function base64Slice (buf, start, end) {
    if (start === 0 && end === buf.length) {
      return base64.fromByteArray(buf)
    } else {
      return base64.fromByteArray(buf.slice(start, end))
    }
  }
  
  function utf8Slice (buf, start, end) {
    end = Math.min(buf.length, end)
    var res = []
  
    var i = start
    while (i < end) {
      var firstByte = buf[i]
      var codePoint = null
      var bytesPerSequence = (firstByte > 0xEF) ? 4
        : (firstByte > 0xDF) ? 3
        : (firstByte > 0xBF) ? 2
        : 1
  
      if (i + bytesPerSequence <= end) {
        var secondByte, thirdByte, fourthByte, tempCodePoint
  
        switch (bytesPerSequence) {
          case 1:
            if (firstByte < 0x80) {
              codePoint = firstByte
            }
            break
          case 2:
            secondByte = buf[i + 1]
            if ((secondByte & 0xC0) === 0x80) {
              tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
              if (tempCodePoint > 0x7F) {
                codePoint = tempCodePoint
              }
            }
            break
          case 3:
            secondByte = buf[i + 1]
            thirdByte = buf[i + 2]
            if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
              tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
              if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
                codePoint = tempCodePoint
              }
            }
            break
          case 4:
            secondByte = buf[i + 1]
            thirdByte = buf[i + 2]
            fourthByte = buf[i + 3]
            if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
              tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
              if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
                codePoint = tempCodePoint
              }
            }
        }
      }
  
      if (codePoint === null) {
        // we did not generate a valid codePoint so insert a
        // replacement char (U+FFFD) and advance only 1 byte
        codePoint = 0xFFFD
        bytesPerSequence = 1
      } else if (codePoint > 0xFFFF) {
        // encode to utf16 (surrogate pair dance)
        codePoint -= 0x10000
        res.push(codePoint >>> 10 & 0x3FF | 0xD800)
        codePoint = 0xDC00 | codePoint & 0x3FF
      }
  
      res.push(codePoint)
      i += bytesPerSequence
    }
  
    return decodeCodePointsArray(res)
  }
  
  // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  // the lowest limit is Chrome, with 0x10000 args.
  // We go 1 magnitude less, for safety
  var MAX_ARGUMENTS_LENGTH = 0x1000
  
  function decodeCodePointsArray (codePoints) {
    var len = codePoints.length
    if (len <= MAX_ARGUMENTS_LENGTH) {
      return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
    }
  
    // Decode in chunks to avoid "call stack size exceeded".
    var res = ''
    var i = 0
    while (i < len) {
      res += String.fromCharCode.apply(
        String,
        codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
      )
    }
    return res
  }
  
  function asciiSlice (buf, start, end) {
    var ret = ''
    end = Math.min(buf.length, end)
  
    for (var i = start; i < end; i++) {
      ret += String.fromCharCode(buf[i] & 0x7F)
    }
    return ret
  }
  
  function binarySlice (buf, start, end) {
    var ret = ''
    end = Math.min(buf.length, end)
  
    for (var i = start; i < end; i++) {
      ret += String.fromCharCode(buf[i])
    }
    return ret
  }
  
  function hexSlice (buf, start, end) {
    var len = buf.length
  
    if (!start || start < 0) start = 0
    if (!end || end < 0 || end > len) end = len
  
    var out = ''
    for (var i = start; i < end; i++) {
      out += toHex(buf[i])
    }
    return out
  }
  
  function utf16leSlice (buf, start, end) {
    var bytes = buf.slice(start, end)
    var res = ''
    for (var i = 0; i < bytes.length; i += 2) {
      res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
    }
    return res
  }
  
  Buffer.prototype.slice = function slice (start, end) {
    var len = this.length
    start = ~~start
    end = end === undefined ? len : ~~end
  
    if (start < 0) {
      start += len
      if (start < 0) start = 0
    } else if (start > len) {
      start = len
    }
  
    if (end < 0) {
      end += len
      if (end < 0) end = 0
    } else if (end > len) {
      end = len
    }
  
    if (end < start) end = start
  
    var newBuf
    if (Buffer.TYPED_ARRAY_SUPPORT) {
      newBuf = this.subarray(start, end)
      newBuf.__proto__ = Buffer.prototype
    } else {
      var sliceLen = end - start
      newBuf = new Buffer(sliceLen, undefined)
      for (var i = 0; i < sliceLen; i++) {
        newBuf[i] = this[i + start]
      }
    }
  
    if (newBuf.length) newBuf.parent = this.parent || this
  
    return newBuf
  }
  
  /*
   * Need to make sure that buffer isn't trying to write out of bounds.
   */
  function checkOffset (offset, ext, length) {
    if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
    if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  }
  
  Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
    offset = offset | 0
    byteLength = byteLength | 0
    if (!noAssert) checkOffset(offset, byteLength, this.length)
  
    var val = this[offset]
    var mul = 1
    var i = 0
    while (++i < byteLength && (mul *= 0x100)) {
      val += this[offset + i] * mul
    }
  
    return val
  }
  
  Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
    offset = offset | 0
    byteLength = byteLength | 0
    if (!noAssert) {
      checkOffset(offset, byteLength, this.length)
    }
  
    var val = this[offset + --byteLength]
    var mul = 1
    while (byteLength > 0 && (mul *= 0x100)) {
      val += this[offset + --byteLength] * mul
    }
  
    return val
  }
  
  Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
    if (!noAssert) checkOffset(offset, 1, this.length)
    return this[offset]
  }
  
  Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
    if (!noAssert) checkOffset(offset, 2, this.length)
    return this[offset] | (this[offset + 1] << 8)
  }
  
  Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
    if (!noAssert) checkOffset(offset, 2, this.length)
    return (this[offset] << 8) | this[offset + 1]
  }
  
  Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
    if (!noAssert) checkOffset(offset, 4, this.length)
  
    return ((this[offset]) |
        (this[offset + 1] << 8) |
        (this[offset + 2] << 16)) +
        (this[offset + 3] * 0x1000000)
  }
  
  Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
    if (!noAssert) checkOffset(offset, 4, this.length)
  
    return (this[offset] * 0x1000000) +
      ((this[offset + 1] << 16) |
      (this[offset + 2] << 8) |
      this[offset + 3])
  }
  
  Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
    offset = offset | 0
    byteLength = byteLength | 0
    if (!noAssert) checkOffset(offset, byteLength, this.length)
  
    var val = this[offset]
    var mul = 1
    var i = 0
    while (++i < byteLength && (mul *= 0x100)) {
      val += this[offset + i] * mul
    }
    mul *= 0x80
  
    if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  
    return val
  }
  
  Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
    offset = offset | 0
    byteLength = byteLength | 0
    if (!noAssert) checkOffset(offset, byteLength, this.length)
  
    var i = byteLength
    var mul = 1
    var val = this[offset + --i]
    while (i > 0 && (mul *= 0x100)) {
      val += this[offset + --i] * mul
    }
    mul *= 0x80
  
    if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  
    return val
  }
  
  Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
    if (!noAssert) checkOffset(offset, 1, this.length)
    if (!(this[offset] & 0x80)) return (this[offset])
    return ((0xff - this[offset] + 1) * -1)
  }
  
  Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
    if (!noAssert) checkOffset(offset, 2, this.length)
    var val = this[offset] | (this[offset + 1] << 8)
    return (val & 0x8000) ? val | 0xFFFF0000 : val
  }
  
  Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
    if (!noAssert) checkOffset(offset, 2, this.length)
    var val = this[offset + 1] | (this[offset] << 8)
    return (val & 0x8000) ? val | 0xFFFF0000 : val
  }
  
  Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
    if (!noAssert) checkOffset(offset, 4, this.length)
  
    return (this[offset]) |
      (this[offset + 1] << 8) |
      (this[offset + 2] << 16) |
      (this[offset + 3] << 24)
  }
  
  Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
    if (!noAssert) checkOffset(offset, 4, this.length)
  
    return (this[offset] << 24) |
      (this[offset + 1] << 16) |
      (this[offset + 2] << 8) |
      (this[offset + 3])
  }
  
  Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
    if (!noAssert) checkOffset(offset, 4, this.length)
    return ieee754.read(this, offset, true, 23, 4)
  }
  
  Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
    if (!noAssert) checkOffset(offset, 4, this.length)
    return ieee754.read(this, offset, false, 23, 4)
  }
  
  Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
    if (!noAssert) checkOffset(offset, 8, this.length)
    return ieee754.read(this, offset, true, 52, 8)
  }
  
  Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
    if (!noAssert) checkOffset(offset, 8, this.length)
    return ieee754.read(this, offset, false, 52, 8)
  }
  
  function checkInt (buf, value, offset, ext, max, min) {
    if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
    if (value > max || value < min) throw new RangeError('value is out of bounds')
    if (offset + ext > buf.length) throw new RangeError('index out of range')
  }
  
  Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
    value = +value
    offset = offset | 0
    byteLength = byteLength | 0
    if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
  
    var mul = 1
    var i = 0
    this[offset] = value & 0xFF
    while (++i < byteLength && (mul *= 0x100)) {
      this[offset + i] = (value / mul) & 0xFF
    }
  
    return offset + byteLength
  }
  
  Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
    value = +value
    offset = offset | 0
    byteLength = byteLength | 0
    if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
  
    var i = byteLength - 1
    var mul = 1
    this[offset + i] = value & 0xFF
    while (--i >= 0 && (mul *= 0x100)) {
      this[offset + i] = (value / mul) & 0xFF
    }
  
    return offset + byteLength
  }
  
  Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
    value = +value
    offset = offset | 0
    if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
    if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
    this[offset] = (value & 0xff)
    return offset + 1
  }
  
  function objectWriteUInt16 (buf, value, offset, littleEndian) {
    if (value < 0) value = 0xffff + value + 1
    for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
      buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
        (littleEndian ? i : 1 - i) * 8
    }
  }
  
  Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
    value = +value
    offset = offset | 0
    if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
    if (Buffer.TYPED_ARRAY_SUPPORT) {
      this[offset] = (value & 0xff)
      this[offset + 1] = (value >>> 8)
    } else {
      objectWriteUInt16(this, value, offset, true)
    }
    return offset + 2
  }
  
  Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
    value = +value
    offset = offset | 0
    if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
    if (Buffer.TYPED_ARRAY_SUPPORT) {
      this[offset] = (value >>> 8)
      this[offset + 1] = (value & 0xff)
    } else {
      objectWriteUInt16(this, value, offset, false)
    }
    return offset + 2
  }
  
  function objectWriteUInt32 (buf, value, offset, littleEndian) {
    if (value < 0) value = 0xffffffff + value + 1
    for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
      buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
    }
  }
  
  Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
    value = +value
    offset = offset | 0
    if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
    if (Buffer.TYPED_ARRAY_SUPPORT) {
      this[offset + 3] = (value >>> 24)
      this[offset + 2] = (value >>> 16)
      this[offset + 1] = (value >>> 8)
      this[offset] = (value & 0xff)
    } else {
      objectWriteUInt32(this, value, offset, true)
    }
    return offset + 4
  }
  
  Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
    value = +value
    offset = offset | 0
    if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
    if (Buffer.TYPED_ARRAY_SUPPORT) {
      this[offset] = (value >>> 24)
      this[offset + 1] = (value >>> 16)
      this[offset + 2] = (value >>> 8)
      this[offset + 3] = (value & 0xff)
    } else {
      objectWriteUInt32(this, value, offset, false)
    }
    return offset + 4
  }
  
  Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
    value = +value
    offset = offset | 0
    if (!noAssert) {
      var limit = Math.pow(2, 8 * byteLength - 1)
  
      checkInt(this, value, offset, byteLength, limit - 1, -limit)
    }
  
    var i = 0
    var mul = 1
    var sub = value < 0 ? 1 : 0
    this[offset] = value & 0xFF
    while (++i < byteLength && (mul *= 0x100)) {
      this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
    }
  
    return offset + byteLength
  }
  
  Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
    value = +value
    offset = offset | 0
    if (!noAssert) {
      var limit = Math.pow(2, 8 * byteLength - 1)
  
      checkInt(this, value, offset, byteLength, limit - 1, -limit)
    }
  
    var i = byteLength - 1
    var mul = 1
    var sub = value < 0 ? 1 : 0
    this[offset + i] = value & 0xFF
    while (--i >= 0 && (mul *= 0x100)) {
      this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
    }
  
    return offset + byteLength
  }
  
  Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
    value = +value
    offset = offset | 0
    if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
    if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
    if (value < 0) value = 0xff + value + 1
    this[offset] = (value & 0xff)
    return offset + 1
  }
  
  Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
    value = +value
    offset = offset | 0
    if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
    if (Buffer.TYPED_ARRAY_SUPPORT) {
      this[offset] = (value & 0xff)
      this[offset + 1] = (value >>> 8)
    } else {
      objectWriteUInt16(this, value, offset, true)
    }
    return offset + 2
  }
  
  Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
    value = +value
    offset = offset | 0
    if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
    if (Buffer.TYPED_ARRAY_SUPPORT) {
      this[offset] = (value >>> 8)
      this[offset + 1] = (value & 0xff)
    } else {
      objectWriteUInt16(this, value, offset, false)
    }
    return offset + 2
  }
  
  Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
    value = +value
    offset = offset | 0
    if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
    if (Buffer.TYPED_ARRAY_SUPPORT) {
      this[offset] = (value & 0xff)
      this[offset + 1] = (value >>> 8)
      this[offset + 2] = (value >>> 16)
      this[offset + 3] = (value >>> 24)
    } else {
      objectWriteUInt32(this, value, offset, true)
    }
    return offset + 4
  }
  
  Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
    value = +value
    offset = offset | 0
    if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
    if (value < 0) value = 0xffffffff + value + 1
    if (Buffer.TYPED_ARRAY_SUPPORT) {
      this[offset] = (value >>> 24)
      this[offset + 1] = (value >>> 16)
      this[offset + 2] = (value >>> 8)
      this[offset + 3] = (value & 0xff)
    } else {
      objectWriteUInt32(this, value, offset, false)
    }
    return offset + 4
  }
  
  function checkIEEE754 (buf, value, offset, ext, max, min) {
    if (offset + ext > buf.length) throw new RangeError('index out of range')
    if (offset < 0) throw new RangeError('index out of range')
  }
  
  function writeFloat (buf, value, offset, littleEndian, noAssert) {
    if (!noAssert) {
      checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
    }
    ieee754.write(buf, value, offset, littleEndian, 23, 4)
    return offset + 4
  }
  
  Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
    return writeFloat(this, value, offset, true, noAssert)
  }
  
  Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
    return writeFloat(this, value, offset, false, noAssert)
  }
  
  function writeDouble (buf, value, offset, littleEndian, noAssert) {
    if (!noAssert) {
      checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
    }
    ieee754.write(buf, value, offset, littleEndian, 52, 8)
    return offset + 8
  }
  
  Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
    return writeDouble(this, value, offset, true, noAssert)
  }
  
  Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
    return writeDouble(this, value, offset, false, noAssert)
  }
  
  // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  Buffer.prototype.copy = function copy (target, targetStart, start, end) {
    if (!start) start = 0
    if (!end && end !== 0) end = this.length
    if (targetStart >= target.length) targetStart = target.length
    if (!targetStart) targetStart = 0
    if (end > 0 && end < start) end = start
  
    // Copy 0 bytes; we're done
    if (end === start) return 0
    if (target.length === 0 || this.length === 0) return 0
  
    // Fatal error conditions
    if (targetStart < 0) {
      throw new RangeError('targetStart out of bounds')
    }
    if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
    if (end < 0) throw new RangeError('sourceEnd out of bounds')
  
    // Are we oob?
    if (end > this.length) end = this.length
    if (target.length - targetStart < end - start) {
      end = target.length - targetStart + start
    }
  
    var len = end - start
    var i
  
    if (this === target && start < targetStart && targetStart < end) {
      // descending copy from end
      for (i = len - 1; i >= 0; i--) {
        target[i + targetStart] = this[i + start]
      }
    } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
      // ascending copy from start
      for (i = 0; i < len; i++) {
        target[i + targetStart] = this[i + start]
      }
    } else {
      Uint8Array.prototype.set.call(
        target,
        this.subarray(start, start + len),
        targetStart
      )
    }
  
    return len
  }
  
  // fill(value, start=0, end=buffer.length)
  Buffer.prototype.fill = function fill (value, start, end) {
    if (!value) value = 0
    if (!start) start = 0
    if (!end) end = this.length
  
    if (end < start) throw new RangeError('end < start')
  
    // Fill 0 bytes; we're done
    if (end === start) return
    if (this.length === 0) return
  
    if (start < 0 || start >= this.length) throw new RangeError('start out of bounds')
    if (end < 0 || end > this.length) throw new RangeError('end out of bounds')
  
    var i
    if (typeof value === 'number') {
      for (i = start; i < end; i++) {
        this[i] = value
      }
    } else {
      var bytes = utf8ToBytes(value.toString())
      var len = bytes.length
      for (i = start; i < end; i++) {
        this[i] = bytes[i % len]
      }
    }
  
    return this
  }
  
  // HELPER FUNCTIONS
  // ================
  
  var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
  
  function base64clean (str) {
    // Node strips out invalid characters like \n and \t from the string, base64-js does not
    str = stringtrim(str).replace(INVALID_BASE64_RE, '')
    // Node converts strings with length < 2 to ''
    if (str.length < 2) return ''
    // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
    while (str.length % 4 !== 0) {
      str = str + '='
    }
    return str
  }
  
  function stringtrim (str) {
    if (str.trim) return str.trim()
    return str.replace(/^\s+|\s+$/g, '')
  }
  
  function toHex (n) {
    if (n < 16) return '0' + n.toString(16)
    return n.toString(16)
  }
  
  function utf8ToBytes (string, units) {
    units = units || Infinity
    var codePoint
    var length = string.length
    var leadSurrogate = null
    var bytes = []
  
    for (var i = 0; i < length; i++) {
      codePoint = string.charCodeAt(i)
  
      // is surrogate component
      if (codePoint > 0xD7FF && codePoint < 0xE000) {
        // last char was a lead
        if (!leadSurrogate) {
          // no lead yet
          if (codePoint > 0xDBFF) {
            // unexpected trail
            if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
            continue
          } else if (i + 1 === length) {
            // unpaired lead
            if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
            continue
          }
  
          // valid lead
          leadSurrogate = codePoint
  
          continue
        }
  
        // 2 leads in a row
        if (codePoint < 0xDC00) {
          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
          leadSurrogate = codePoint
          continue
        }
  
        // valid surrogate pair
        codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
      } else if (leadSurrogate) {
        // valid bmp char, but last char was a lead
        if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
      }
  
      leadSurrogate = null
  
      // encode utf8
      if (codePoint < 0x80) {
        if ((units -= 1) < 0) break
        bytes.push(codePoint)
      } else if (codePoint < 0x800) {
        if ((units -= 2) < 0) break
        bytes.push(
          codePoint >> 0x6 | 0xC0,
          codePoint & 0x3F | 0x80
        )
      } else if (codePoint < 0x10000) {
        if ((units -= 3) < 0) break
        bytes.push(
          codePoint >> 0xC | 0xE0,
          codePoint >> 0x6 & 0x3F | 0x80,
          codePoint & 0x3F | 0x80
        )
      } else if (codePoint < 0x110000) {
        if ((units -= 4) < 0) break
        bytes.push(
          codePoint >> 0x12 | 0xF0,
          codePoint >> 0xC & 0x3F | 0x80,
          codePoint >> 0x6 & 0x3F | 0x80,
          codePoint & 0x3F | 0x80
        )
      } else {
        throw new Error('Invalid code point')
      }
    }
  
    return bytes
  }
  
  function asciiToBytes (str) {
    var byteArray = []
    for (var i = 0; i < str.length; i++) {
      // Node's code seems to be doing this and not & 0x7F..
      byteArray.push(str.charCodeAt(i) & 0xFF)
    }
    return byteArray
  }
  
  function utf16leToBytes (str, units) {
    var c, hi, lo
    var byteArray = []
    for (var i = 0; i < str.length; i++) {
      if ((units -= 2) < 0) break
  
      c = str.charCodeAt(i)
      hi = c >> 8
      lo = c % 256
      byteArray.push(lo)
      byteArray.push(hi)
    }
  
    return byteArray
  }
  
  function base64ToBytes (str) {
    return base64.toByteArray(base64clean(str))
  }
  
  function blitBuffer (src, dst, offset, length) {
    for (var i = 0; i < length; i++) {
      if ((i + offset >= dst.length) || (i >= src.length)) break
      dst[i + offset] = src[i]
    }
    return i
  }
  
  }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  },{"base64-js":87,"ieee754":90,"isarray":89}],89:[function(require,module,exports){
  var toString = {}.toString;
  
  module.exports = Array.isArray || function (arr) {
    return toString.call(arr) == '[object Array]';
  };
  
  },{}],90:[function(require,module,exports){
  exports.read = function (buffer, offset, isLE, mLen, nBytes) {
    var e, m
    var eLen = nBytes * 8 - mLen - 1
    var eMax = (1 << eLen) - 1
    var eBias = eMax >> 1
    var nBits = -7
    var i = isLE ? (nBytes - 1) : 0
    var d = isLE ? -1 : 1
    var s = buffer[offset + i]
  
    i += d
  
    e = s & ((1 << (-nBits)) - 1)
    s >>= (-nBits)
    nBits += eLen
    for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  
    m = e & ((1 << (-nBits)) - 1)
    e >>= (-nBits)
    nBits += mLen
    for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  
    if (e === 0) {
      e = 1 - eBias
    } else if (e === eMax) {
      return m ? NaN : ((s ? -1 : 1) * Infinity)
    } else {
      m = m + Math.pow(2, mLen)
      e = e - eBias
    }
    return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  }
  
  exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
    var e, m, c
    var eLen = nBytes * 8 - mLen - 1
    var eMax = (1 << eLen) - 1
    var eBias = eMax >> 1
    var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
    var i = isLE ? 0 : (nBytes - 1)
    var d = isLE ? 1 : -1
    var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  
    value = Math.abs(value)
  
    if (isNaN(value) || value === Infinity) {
      m = isNaN(value) ? 1 : 0
      e = eMax
    } else {
      e = Math.floor(Math.log(value) / Math.LN2)
      if (value * (c = Math.pow(2, -e)) < 1) {
        e--
        c *= 2
      }
      if (e + eBias >= 1) {
        value += rt / c
      } else {
        value += rt * Math.pow(2, 1 - eBias)
      }
      if (value * c >= 2) {
        e++
        c /= 2
      }
  
      if (e + eBias >= eMax) {
        m = 0
        e = eMax
      } else if (e + eBias >= 1) {
        m = (value * c - 1) * Math.pow(2, mLen)
        e = e + eBias
      } else {
        m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
        e = 0
      }
    }
  
    for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  
    e = (e << mLen) | m
    eLen += mLen
    for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  
    buffer[offset + i - d] |= s * 128
  }
  
  },{}],91:[function(require,module,exports){
  arguments[4][39][0].apply(exports,arguments)
  },{"dup":39}],92:[function(require,module,exports){
  // shim for using process in browser
  
  var process = module.exports = {};
  var queue = [];
  var draining = false;
  var currentQueue;
  var queueIndex = -1;
  
  function cleanUpNextTick() {
      draining = false;
      if (currentQueue.length) {
          queue = currentQueue.concat(queue);
      } else {
          queueIndex = -1;
      }
      if (queue.length) {
          drainQueue();
      }
  }
  
  function drainQueue() {
      if (draining) {
          return;
      }
      var timeout = setTimeout(cleanUpNextTick);
      draining = true;
  
      var len = queue.length;
      while(len) {
          currentQueue = queue;
          queue = [];
          while (++queueIndex < len) {
              if (currentQueue) {
                  currentQueue[queueIndex].run();
              }
          }
          queueIndex = -1;
          len = queue.length;
      }
      currentQueue = null;
      draining = false;
      clearTimeout(timeout);
  }
  
  process.nextTick = function (fun) {
      var args = new Array(arguments.length - 1);
      if (arguments.length > 1) {
          for (var i = 1; i < arguments.length; i++) {
              args[i - 1] = arguments[i];
          }
      }
      queue.push(new Item(fun, args));
      if (queue.length === 1 && !draining) {
          setTimeout(drainQueue, 0);
      }
  };
  
  // v8 likes predictible objects
  function Item(fun, array) {
      this.fun = fun;
      this.array = array;
  }
  Item.prototype.run = function () {
      this.fun.apply(null, this.array);
  };
  process.title = 'browser';
  process.browser = true;
  process.env = {};
  process.argv = [];
  process.version = ''; // empty string to avoid regexp issues
  process.versions = {};
  
  function noop() {}
  
  process.on = noop;
  process.addListener = noop;
  process.once = noop;
  process.off = noop;
  process.removeListener = noop;
  process.removeAllListeners = noop;
  process.emit = noop;
  
  process.binding = function (name) {
      throw new Error('process.binding is not supported');
  };
  
  process.cwd = function () { return '/' };
  process.chdir = function (dir) {
      throw new Error('process.chdir is not supported');
  };
  process.umask = function() { return 0; };
  
  },{}],93:[function(require,module,exports){
  module.exports = function isBuffer(arg) {
    return arg && typeof arg === 'object'
      && typeof arg.copy === 'function'
      && typeof arg.fill === 'function'
      && typeof arg.readUInt8 === 'function';
  }
  },{}],94:[function(require,module,exports){
  (function (process,global){
  // Copyright Joyent, Inc. and other Node contributors.
  //
  // Permission is hereby granted, free of charge, to any person obtaining a
  // copy of this software and associated documentation files (the
  // "Software"), to deal in the Software without restriction, including
  // without limitation the rights to use, copy, modify, merge, publish,
  // distribute, sublicense, and/or sell copies of the Software, and to permit
  // persons to whom the Software is furnished to do so, subject to the
  // following conditions:
  //
  // The above copyright notice and this permission notice shall be included
  // in all copies or substantial portions of the Software.
  //
  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  // USE OR OTHER DEALINGS IN THE SOFTWARE.
  
  var formatRegExp = /%[sdj%]/g;
  exports.format = function(f) {
    if (!isString(f)) {
      var objects = [];
      for (var i = 0; i < arguments.length; i++) {
        objects.push(inspect(arguments[i]));
      }
      return objects.join(' ');
    }
  
    var i = 1;
    var args = arguments;
    var len = args.length;
    var str = String(f).replace(formatRegExp, function(x) {
      if (x === '%%') return '%';
      if (i >= len) return x;
      switch (x) {
        case '%s': return String(args[i++]);
        case '%d': return Number(args[i++]);
        case '%j':
          try {
            return JSON.stringify(args[i++]);
          } catch (_) {
            return '[Circular]';
          }
        default:
          return x;
      }
    });
    for (var x = args[i]; i < len; x = args[++i]) {
      if (isNull(x) || !isObject(x)) {
        str += ' ' + x;
      } else {
        str += ' ' + inspect(x);
      }
    }
    return str;
  };
  
  
  // Mark that a method should not be used.
  // Returns a modified function which warns once by default.
  // If --no-deprecation is set, then it is a no-op.
  exports.deprecate = function(fn, msg) {
    // Allow for deprecating things in the process of starting up.
    if (isUndefined(global.process)) {
      return function() {
        return exports.deprecate(fn, msg).apply(this, arguments);
      };
    }
  
    if (process.noDeprecation === true) {
      return fn;
    }
  
    var warned = false;
    function deprecated() {
      if (!warned) {
        if (process.throwDeprecation) {
          throw new Error(msg);
        } else if (process.traceDeprecation) {
          console.trace(msg);
        } else {
          console.error(msg);
        }
        warned = true;
      }
      return fn.apply(this, arguments);
    }
  
    return deprecated;
  };
  
  
  var debugs = {};
  var debugEnviron;
  exports.debuglog = function(set) {
    if (isUndefined(debugEnviron))
      debugEnviron = process.env.NODE_DEBUG || '';
    set = set.toUpperCase();
    if (!debugs[set]) {
      if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
        var pid = process.pid;
        debugs[set] = function() {
          var msg = exports.format.apply(exports, arguments);
          console.error('%s %d: %s', set, pid, msg);
        };
      } else {
        debugs[set] = function() {};
      }
    }
    return debugs[set];
  };
  
  
  /**
   * Echos the value of a value. Trys to print the value out
   * in the best way possible given the different types.
   *
   * @param {Object} obj The object to print out.
   * @param {Object} opts Optional options object that alters the output.
   */
  /* legacy: obj, showHidden, depth, colors*/
  function inspect(obj, opts) {
    // default options
    var ctx = {
      seen: [],
      stylize: stylizeNoColor
    };
    // legacy...
    if (arguments.length >= 3) ctx.depth = arguments[2];
    if (arguments.length >= 4) ctx.colors = arguments[3];
    if (isBoolean(opts)) {
      // legacy...
      ctx.showHidden = opts;
    } else if (opts) {
      // got an "options" object
      exports._extend(ctx, opts);
    }
    // set default options
    if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
    if (isUndefined(ctx.depth)) ctx.depth = 2;
    if (isUndefined(ctx.colors)) ctx.colors = false;
    if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
    if (ctx.colors) ctx.stylize = stylizeWithColor;
    return formatValue(ctx, obj, ctx.depth);
  }
  exports.inspect = inspect;
  
  
  // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  inspect.colors = {
    'bold' : [1, 22],
    'italic' : [3, 23],
    'underline' : [4, 24],
    'inverse' : [7, 27],
    'white' : [37, 39],
    'grey' : [90, 39],
    'black' : [30, 39],
    'blue' : [34, 39],
    'cyan' : [36, 39],
    'green' : [32, 39],
    'magenta' : [35, 39],
    'red' : [31, 39],
    'yellow' : [33, 39]
  };
  
  // Don't use 'blue' not visible on cmd.exe
  inspect.styles = {
    'special': 'cyan',
    'number': 'yellow',
    'boolean': 'yellow',
    'undefined': 'grey',
    'null': 'bold',
    'string': 'green',
    'date': 'magenta',
    // "name": intentionally not styling
    'regexp': 'red'
  };
  
  
  function stylizeWithColor(str, styleType) {
    var style = inspect.styles[styleType];
  
    if (style) {
      return '\u001b[' + inspect.colors[style][0] + 'm' + str +
             '\u001b[' + inspect.colors[style][1] + 'm';
    } else {
      return str;
    }
  }
  
  
  function stylizeNoColor(str, styleType) {
    return str;
  }
  
  
  function arrayToHash(array) {
    var hash = {};
  
    array.forEach(function(val, idx) {
      hash[val] = true;
    });
  
    return hash;
  }
  
  
  function formatValue(ctx, value, recurseTimes) {
    // Provide a hook for user-specified inspect functions.
    // Check that value is an object with an inspect function on it
    if (ctx.customInspect &&
        value &&
        isFunction(value.inspect) &&
        // Filter out the util module, it's inspect function is special
        value.inspect !== exports.inspect &&
        // Also filter out any prototype objects using the circular check.
        !(value.constructor && value.constructor.prototype === value)) {
      var ret = value.inspect(recurseTimes, ctx);
      if (!isString(ret)) {
        ret = formatValue(ctx, ret, recurseTimes);
      }
      return ret;
    }
  
    // Primitive types cannot have properties
    var primitive = formatPrimitive(ctx, value);
    if (primitive) {
      return primitive;
    }
  
    // Look up the keys of the object.
    var keys = Object.keys(value);
    var visibleKeys = arrayToHash(keys);
  
    if (ctx.showHidden) {
      keys = Object.getOwnPropertyNames(value);
    }
  
    // IE doesn't make error fields non-enumerable
    // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
    if (isError(value)
        && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
      return formatError(value);
    }
  
    // Some type of object without properties can be shortcutted.
    if (keys.length === 0) {
      if (isFunction(value)) {
        var name = value.name ? ': ' + value.name : '';
        return ctx.stylize('[Function' + name + ']', 'special');
      }
      if (isRegExp(value)) {
        return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
      }
      if (isDate(value)) {
        return ctx.stylize(Date.prototype.toString.call(value), 'date');
      }
      if (isError(value)) {
        return formatError(value);
      }
    }
  
    var base = '', array = false, braces = ['{', '}'];
  
    // Make Array say that they are Array
    if (isArray(value)) {
      array = true;
      braces = ['[', ']'];
    }
  
    // Make functions say that they are functions
    if (isFunction(value)) {
      var n = value.name ? ': ' + value.name : '';
      base = ' [Function' + n + ']';
    }
  
    // Make RegExps say that they are RegExps
    if (isRegExp(value)) {
      base = ' ' + RegExp.prototype.toString.call(value);
    }
  
    // Make dates with properties first say the date
    if (isDate(value)) {
      base = ' ' + Date.prototype.toUTCString.call(value);
    }
  
    // Make error with message first say the error
    if (isError(value)) {
      base = ' ' + formatError(value);
    }
  
    if (keys.length === 0 && (!array || value.length == 0)) {
      return braces[0] + base + braces[1];
    }
  
    if (recurseTimes < 0) {
      if (isRegExp(value)) {
        return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
      } else {
        return ctx.stylize('[Object]', 'special');
      }
    }
  
    ctx.seen.push(value);
  
    var output;
    if (array) {
      output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
    } else {
      output = keys.map(function(key) {
        return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
      });
    }
  
    ctx.seen.pop();
  
    return reduceToSingleString(output, base, braces);
  }
  
  
  function formatPrimitive(ctx, value) {
    if (isUndefined(value))
      return ctx.stylize('undefined', 'undefined');
    if (isString(value)) {
      var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
                                               .replace(/'/g, "\\'")
                                               .replace(/\\"/g, '"') + '\'';
      return ctx.stylize(simple, 'string');
    }
    if (isNumber(value))
      return ctx.stylize('' + value, 'number');
    if (isBoolean(value))
      return ctx.stylize('' + value, 'boolean');
    // For some reason typeof null is "object", so special case here.
    if (isNull(value))
      return ctx.stylize('null', 'null');
  }
  
  
  function formatError(value) {
    return '[' + Error.prototype.toString.call(value) + ']';
  }
  
  
  function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
    var output = [];
    for (var i = 0, l = value.length; i < l; ++i) {
      if (hasOwnProperty(value, String(i))) {
        output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
            String(i), true));
      } else {
        output.push('');
      }
    }
    keys.forEach(function(key) {
      if (!key.match(/^\d+$/)) {
        output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
            key, true));
      }
    });
    return output;
  }
  
  
  function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
    var name, str, desc;
    desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
    if (desc.get) {
      if (desc.set) {
        str = ctx.stylize('[Getter/Setter]', 'special');
      } else {
        str = ctx.stylize('[Getter]', 'special');
      }
    } else {
      if (desc.set) {
        str = ctx.stylize('[Setter]', 'special');
      }
    }
    if (!hasOwnProperty(visibleKeys, key)) {
      name = '[' + key + ']';
    }
    if (!str) {
      if (ctx.seen.indexOf(desc.value) < 0) {
        if (isNull(recurseTimes)) {
          str = formatValue(ctx, desc.value, null);
        } else {
          str = formatValue(ctx, desc.value, recurseTimes - 1);
        }
        if (str.indexOf('\n') > -1) {
          if (array) {
            str = str.split('\n').map(function(line) {
              return '  ' + line;
            }).join('\n').substr(2);
          } else {
            str = '\n' + str.split('\n').map(function(line) {
              return '   ' + line;
            }).join('\n');
          }
        }
      } else {
        str = ctx.stylize('[Circular]', 'special');
      }
    }
    if (isUndefined(name)) {
      if (array && key.match(/^\d+$/)) {
        return str;
      }
      name = JSON.stringify('' + key);
      if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
        name = name.substr(1, name.length - 2);
        name = ctx.stylize(name, 'name');
      } else {
        name = name.replace(/'/g, "\\'")
                   .replace(/\\"/g, '"')
                   .replace(/(^"|"$)/g, "'");
        name = ctx.stylize(name, 'string');
      }
    }
  
    return name + ': ' + str;
  }
  
  
  function reduceToSingleString(output, base, braces) {
    var numLinesEst = 0;
    var length = output.reduce(function(prev, cur) {
      numLinesEst++;
      if (cur.indexOf('\n') >= 0) numLinesEst++;
      return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
    }, 0);
  
    if (length > 60) {
      return braces[0] +
             (base === '' ? '' : base + '\n ') +
             ' ' +
             output.join(',\n  ') +
             ' ' +
             braces[1];
    }
  
    return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  }
  
  
  // NOTE: These type checking functions intentionally don't use `instanceof`
  // because it is fragile and can be easily faked with `Object.create()`.
  function isArray(ar) {
    return Array.isArray(ar);
  }
  exports.isArray = isArray;
  
  function isBoolean(arg) {
    return typeof arg === 'boolean';
  }
  exports.isBoolean = isBoolean;
  
  function isNull(arg) {
    return arg === null;
  }
  exports.isNull = isNull;
  
  function isNullOrUndefined(arg) {
    return arg == null;
  }
  exports.isNullOrUndefined = isNullOrUndefined;
  
  function isNumber(arg) {
    return typeof arg === 'number';
  }
  exports.isNumber = isNumber;
  
  function isString(arg) {
    return typeof arg === 'string';
  }
  exports.isString = isString;
  
  function isSymbol(arg) {
    return typeof arg === 'symbol';
  }
  exports.isSymbol = isSymbol;
  
  function isUndefined(arg) {
    return arg === void 0;
  }
  exports.isUndefined = isUndefined;
  
  function isRegExp(re) {
    return isObject(re) && objectToString(re) === '[object RegExp]';
  }
  exports.isRegExp = isRegExp;
  
  function isObject(arg) {
    return typeof arg === 'object' && arg !== null;
  }
  exports.isObject = isObject;
  
  function isDate(d) {
    return isObject(d) && objectToString(d) === '[object Date]';
  }
  exports.isDate = isDate;
  
  function isError(e) {
    return isObject(e) &&
        (objectToString(e) === '[object Error]' || e instanceof Error);
  }
  exports.isError = isError;
  
  function isFunction(arg) {
    return typeof arg === 'function';
  }
  exports.isFunction = isFunction;
  
  function isPrimitive(arg) {
    return arg === null ||
           typeof arg === 'boolean' ||
           typeof arg === 'number' ||
           typeof arg === 'string' ||
           typeof arg === 'symbol' ||  // ES6 symbol
           typeof arg === 'undefined';
  }
  exports.isPrimitive = isPrimitive;
  
  exports.isBuffer = require('./support/isBuffer');
  
  function objectToString(o) {
    return Object.prototype.toString.call(o);
  }
  
  
  function pad(n) {
    return n < 10 ? '0' + n.toString(10) : n.toString(10);
  }
  
  
  var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
                'Oct', 'Nov', 'Dec'];
  
  // 26 Feb 16:19:34
  function timestamp() {
    var d = new Date();
    var time = [pad(d.getHours()),
                pad(d.getMinutes()),
                pad(d.getSeconds())].join(':');
    return [d.getDate(), months[d.getMonth()], time].join(' ');
  }
  
  
  // log is just a thin wrapper to console.log that prepends a timestamp
  exports.log = function() {
    console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
  };
  
  
  /**
   * Inherit the prototype methods from one constructor into another.
   *
   * The Function.prototype.inherits from lang.js rewritten as a standalone
   * function (not on Function.prototype). NOTE: If this file is to be loaded
   * during bootstrapping this function needs to be rewritten using some native
   * functions as prototype setup using normal JavaScript does not work as
   * expected during bootstrapping (see mirror.js in r114903).
   *
   * @param {function} ctor Constructor function which needs to inherit the
   *     prototype.
   * @param {function} superCtor Constructor function to inherit prototype from.
   */
  exports.inherits = require('inherits');
  
  exports._extend = function(origin, add) {
    // Don't do anything if add isn't an object
    if (!add || !isObject(add)) return origin;
  
    var keys = Object.keys(add);
    var i = keys.length;
    while (i--) {
      origin[keys[i]] = add[keys[i]];
    }
    return origin;
  };
  
  function hasOwnProperty(obj, prop) {
    return Object.prototype.hasOwnProperty.call(obj, prop);
  }
  
  }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  },{"./support/isBuffer":93,"_process":92,"inherits":91}]},{},[1])(1)
  });