deploy1 7 éve
commit
2020a0ca92

+ 4 - 0
.travis.yml

@@ -0,0 +1,4 @@
+language: node_js
+node_js:
+  - "0.10"
+  - "0.11"

+ 21 - 0
LICENSE

@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (C) 2013 Feross Aboukhadijeh, and other 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.

+ 1 - 0
README.md

@@ -0,0 +1 @@
+##buffa

+ 1581 - 0
bigint.js

@@ -0,0 +1,1581 @@
+////////////////////////////////////////////////////////////////////////////////////////
+// Big Integer Library v. 5.5
+// Created 2000, last modified 2013
+// Leemon Baird
+// www.leemon.com
+//
+// Version history:
+// v 5.5  17 Mar 2013
+//   - two lines of a form like "if (x<0) x+=n" had the "if" changed to "while" to 
+//     handle the case when x<-n. (Thanks to James Ansell for finding that bug)
+// v 5.4  3 Oct 2009
+//   - added "var i" to greaterShift() so i is not global. (Thanks to PŽter Szab— for finding that bug)
+//
+// v 5.3  21 Sep 2009
+//   - added randProbPrime(k) for probable primes
+//   - unrolled loop in mont_ (slightly faster)
+//   - millerRabin now takes a bigInt parameter rather than an int
+//
+// v 5.2  15 Sep 2009
+//   - fixed capitalization in call to int2bigInt in randBigInt
+//     (thanks to Emili Evripidou, Reinhold Behringer, and Samuel Macaleese for finding that bug)
+//
+// v 5.1  8 Oct 2007 
+//   - renamed inverseModInt_ to inverseModInt since it doesn't change its parameters
+//   - added functions GCD and randBigInt, which call GCD_ and randBigInt_
+//   - fixed a bug found by Rob Visser (see comment with his name below)
+//   - improved comments
+//
+// This file is public domain.   You can use it for any purpose without restriction.
+// I do not guarantee that it is correct, so use it at your own risk.  If you use 
+// it for something interesting, I'd appreciate hearing about it.  If you find 
+// any bugs or make any improvements, I'd appreciate hearing about those too.
+// It would also be nice if my name and URL were left in the comments.  But none 
+// of that is required.
+//
+// This code defines a bigInt library for arbitrary-precision integers.
+// A bigInt is an array of integers storing the value in chunks of bpe bits, 
+// little endian (buff[0] is the least significant word).
+// Negative bigInts are stored two's complement.  Almost all the functions treat
+// bigInts as nonnegative.  The few that view them as two's complement say so
+// in their comments.  Some functions assume their parameters have at least one 
+// leading zero element. Functions with an underscore at the end of the name put
+// their answer into one of the arrays passed in, and have unpredictable behavior 
+// in case of overflow, so the caller must make sure the arrays are big enough to 
+// hold the answer.  But the average user should never have to call any of the 
+// underscored functions.  Each important underscored function has a wrapper function 
+// of the same name without the underscore that takes care of the details for you.  
+// For each underscored function where a parameter is modified, that same variable 
+// must not be used as another argument too.  So, you cannot square x by doing 
+// multMod_(x,x,n).  You must use squareMod_(x,n) instead, or do y=dup(x); multMod_(x,y,n).
+// Or simply use the multMod(x,x,n) function without the underscore, where
+// such issues never arise, because non-underscored functions never change
+// their parameters; they always allocate new memory for the answer that is returned.
+//
+// These functions are designed to avoid frequent dynamic memory allocation in the inner loop.
+// For most functions, if it needs a BigInt as a local variable it will actually use
+// a global, and will only allocate to it only when it's not the right size.  This ensures
+// that when a function is called repeatedly with same-sized parameters, it only allocates
+// memory on the first call.
+//
+// Note that for cryptographic purposes, the calls to Math.random() must 
+// be replaced with calls to a better pseudorandom number generator.
+//
+// In the following, "bigInt" means a bigInt with at least one leading zero element,
+// and "integer" means a nonnegative integer less than radix.  In some cases, integer 
+// can be negative.  Negative bigInts are 2s complement.
+// 
+// The following functions do not modify their inputs.
+// Those returning a bigInt, string, or Array will dynamically allocate memory for that value.
+// Those returning a boolean will return the integer 0 (false) or 1 (true).
+// Those returning boolean or int will not allocate memory except possibly on the first 
+// time they're called with a given parameter size.
+// 
+// bigInt  add(x,y)               //return (x+y) for bigInts x and y.  
+// bigInt  addInt(x,n)            //return (x+n) where x is a bigInt and n is an integer.
+// string  bigInt2str(x,base)     //return a string form of bigInt x in a given base, with 2 <= base <= 95
+// int     bitSize(x)             //return how many bits long the bigInt x is, not counting leading zeros
+// bigInt  dup(x)                 //return a copy of bigInt x
+// boolean equals(x,y)            //is the bigInt x equal to the bigint y?
+// boolean equalsInt(x,y)         //is bigint x equal to integer y?
+// bigInt  expand(x,n)            //return a copy of x with at least n elements, adding leading zeros if needed
+// Array   findPrimes(n)          //return array of all primes less than integer n
+// bigInt  GCD(x,y)               //return greatest common divisor of bigInts x and y (each with same number of elements).
+// boolean greater(x,y)           //is x>y?  (x and y are nonnegative bigInts)
+// boolean greaterShift(x,y,shift)//is (x <<(shift*bpe)) > y?
+// bigInt  int2bigInt(t,n,m)      //return a bigInt equal to integer t, with at least n bits and m array elements
+// bigInt  inverseMod(x,n)        //return (x**(-1) mod n) for bigInts x and n.  If no inverse exists, it returns null
+// int     inverseModInt(x,n)     //return x**(-1) mod n, for integers x and n.  Return 0 if there is no inverse
+// boolean isZero(x)              //is the bigInt x equal to zero?
+// boolean millerRabin(x,b)       //does one round of Miller-Rabin base integer b say that bigInt x is possibly prime? (b is bigInt, 1<b<x)
+// boolean millerRabinInt(x,b)    //does one round of Miller-Rabin base integer b say that bigInt x is possibly prime? (b is int,    1<b<x)
+// bigInt  mod(x,n)               //return a new bigInt equal to (x mod n) for bigInts x and n.
+// int     modInt(x,n)            //return x mod n for bigInt x and integer n.
+// bigInt  mult(x,y)              //return x*y for bigInts x and y. This is faster when y<x.
+// bigInt  multMod(x,y,n)         //return (x*y mod n) for bigInts x,y,n.  For greater speed, let y<x.
+// boolean negative(x)            //is bigInt x negative?
+// bigInt  powMod(x,y,n)          //return (x**y mod n) where x,y,n are bigInts and ** is exponentiation.  0**0=1. Faster for odd n.
+// bigInt  randBigInt(n,s)        //return an n-bit random BigInt (n>=1).  If s=1, then the most significant of those n bits is set to 1.
+// bigInt  randTruePrime(k)       //return a new, random, k-bit, true prime bigInt using Maurer's algorithm.
+// bigInt  randProbPrime(k)       //return a new, random, k-bit, probable prime bigInt (probability it's composite less than 2^-80).
+// bigInt  str2bigInt(s,b,n,m)    //return a bigInt for number represented in string s in base b with at least n bits and m array elements
+// bigInt  sub(x,y)               //return (x-y) for bigInts x and y.  Negative answers will be 2s complement
+// bigInt  trim(x,k)              //return a copy of x with exactly k leading zero elements
+//
+//
+// The following functions each have a non-underscored version, which most users should call instead.
+// These functions each write to a single parameter, and the caller is responsible for ensuring the array 
+// passed in is large enough to hold the result. 
+//
+// void    addInt_(x,n)          //do x=x+n where x is a bigInt and n is an integer
+// void    add_(x,y)             //do x=x+y for bigInts x and y
+// void    copy_(x,y)            //do x=y on bigInts x and y
+// void    copyInt_(x,n)         //do x=n on bigInt x and integer n
+// void    GCD_(x,y)             //set x to the greatest common divisor of bigInts x and y, (y is destroyed).  (This never overflows its array).
+// boolean inverseMod_(x,n)      //do x=x**(-1) mod n, for bigInts x and n. Returns 1 (0) if inverse does (doesn't) exist
+// void    mod_(x,n)             //do x=x mod n for bigInts x and n. (This never overflows its array).
+// void    mult_(x,y)            //do x=x*y for bigInts x and y.
+// void    multMod_(x,y,n)       //do x=x*y  mod n for bigInts x,y,n.
+// void    powMod_(x,y,n)        //do x=x**y mod n, where x,y,n are bigInts (n is odd) and ** is exponentiation.  0**0=1.
+// void    randBigInt_(b,n,s)    //do b = an n-bit random BigInt. if s=1, then nth bit (most significant bit) is set to 1. n>=1.
+// void    randTruePrime_(ans,k) //do ans = a random k-bit true random prime (not just probable prime) with 1 in the msb.
+// void    sub_(x,y)             //do x=x-y for bigInts x and y. Negative answers will be 2s complement.
+//
+// The following functions do NOT have a non-underscored version. 
+// They each write a bigInt result to one or more parameters.  The caller is responsible for
+// ensuring the arrays passed in are large enough to hold the results. 
+//
+// void addShift_(x,y,ys)       //do x=x+(y<<(ys*bpe))
+// void carry_(x)               //do carries and borrows so each element of the bigInt x fits in bpe bits.
+// void divide_(x,y,q,r)        //divide x by y giving quotient q and remainder r
+// int  divInt_(x,n)            //do x=floor(x/n) for bigInt x and integer n, and return the remainder. (This never overflows its array).
+// int  eGCD_(x,y,d,a,b)        //sets a,b,d to positive bigInts such that d = GCD_(x,y) = a*x-b*y
+// void halve_(x)               //do x=floor(|x|/2)*sgn(x) for bigInt x in 2's complement.  (This never overflows its array).
+// void leftShift_(x,n)         //left shift bigInt x by n bits.  n<bpe.
+// void linComb_(x,y,a,b)       //do x=a*x+b*y for bigInts x and y and integers a and b
+// void linCombShift_(x,y,b,ys) //do x=x+b*(y<<(ys*bpe)) for bigInts x and y, and integers b and ys
+// void mont_(x,y,n,np)         //Montgomery multiplication (see comments where the function is defined)
+// void multInt_(x,n)           //do x=x*n where x is a bigInt and n is an integer.
+// void rightShift_(x,n)        //right shift bigInt x by n bits.  0 <= n < bpe. (This never overflows its array).
+// void squareMod_(x,n)         //do x=x*x  mod n for bigInts x,n
+// void subShift_(x,y,ys)       //do x=x-(y<<(ys*bpe)). Negative answers will be 2s complement.
+//
+// The following functions are based on algorithms from the _Handbook of Applied Cryptography_
+//    powMod_()           = algorithm 14.94, Montgomery exponentiation
+//    eGCD_,inverseMod_() = algorithm 14.61, Binary extended GCD_
+//    GCD_()              = algorothm 14.57, Lehmer's algorithm
+//    mont_()             = algorithm 14.36, Montgomery multiplication
+//    divide_()           = algorithm 14.20  Multiple-precision division
+//    squareMod_()        = algorithm 14.16  Multiple-precision squaring
+//    randTruePrime_()    = algorithm  4.62, Maurer's algorithm
+//    millerRabin()       = algorithm  4.24, Miller-Rabin algorithm
+//
+// Profiling shows:
+//     randTruePrime_() spends:
+//         10% of its time in calls to powMod_()
+//         85% of its time in calls to millerRabin()
+//     millerRabin() spends:
+//         99% of its time in calls to powMod_()   (always with a base of 2)
+//     powMod_() spends:
+//         94% of its time in calls to mont_()  (almost always with x==y)
+//
+// This suggests there are several ways to speed up this library slightly:
+//     - convert powMod_ to use a Montgomery form of k-ary window (or maybe a Montgomery form of sliding window)
+//         -- this should especially focus on being fast when raising 2 to a power mod n
+//     - convert randTruePrime_() to use a minimum r of 1/3 instead of 1/2 with the appropriate change to the test
+//     - tune the parameters in randTruePrime_(), including c, m, and recLimit
+//     - speed up the single loop in mont_() that takes 95% of the runtime, perhaps by reducing checking
+//       within the loop when all the parameters are the same length.
+//
+// There are several ideas that look like they wouldn't help much at all:
+//     - replacing trial division in randTruePrime_() with a sieve (that speeds up something taking almost no time anyway)
+//     - increase bpe from 15 to 30 (that would help if we had a 32*32->64 multiplier, but not with JavaScript's 32*32->32)
+//     - speeding up mont_(x,y,n,np) when x==y by doing a non-modular, non-Montgomery square
+//       followed by a Montgomery reduction.  The intermediate answer will be twice as long as x, so that
+//       method would be slower.  This is unfortunate because the code currently spends almost all of its time
+//       doing mont_(x,x,...), both for randTruePrime_() and powMod_().  A faster method for Montgomery squaring
+//       would have a large impact on the speed of randTruePrime_() and powMod_().  HAC has a couple of poorly-worded
+//       sentences that seem to imply it's faster to do a non-modular square followed by a single
+//       Montgomery reduction, but that's obviously wrong.
+////////////////////////////////////////////////////////////////////////////////////////
+
+//globals
+bpe=0;         //bits stored per array element
+mask=0;        //AND this with an array element to chop it down to bpe bits
+radix=mask+1;  //equals 2^bpe.  A single 1 bit to the left of the last bit of mask.
+
+//the digits for converting to different bases
+digitsStr='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_=!@#$%^&*()[]{}|;:,.<>/?`~ \\\'\"+-';
+
+
+digitsStr= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_=ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþ!@#$%^&*()[]{}|;:,.<>/?`~+-¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿";
+
+
+
+
+//initialize the global variables
+for (bpe=0; (1<<(bpe+1)) > (1<<bpe); bpe++);  //bpe=number of bits in the mantissa on this platform
+bpe>>=1;                   //bpe=number of bits in one element of the array representing the bigInt
+mask=(1<<bpe)-1;           //AND the mask with an integer to get its bpe least significant bits
+radix=mask+1;              //2^bpe.  a single 1 bit to the left of the first bit of mask
+one=int2bigInt(1,1,1);     //constant used in powMod_()
+
+//the following global variables are scratchpad memory to 
+//reduce dynamic memory allocation in the inner loop
+t=new Array(0);
+ss=t;       //used in mult_()
+s0=t;       //used in multMod_(), squareMod_() 
+s1=t;       //used in powMod_(), multMod_(), squareMod_() 
+s2=t;       //used in powMod_(), multMod_()
+s3=t;       //used in powMod_()
+s4=t; s5=t; //used in mod_()
+s6=t;       //used in bigInt2str()
+s7=t;       //used in powMod_()
+T=t;        //used in GCD_()
+sa=t;       //used in mont_()
+mr_x1=t; mr_r=t; mr_a=t;                                      //used in millerRabin()
+eg_v=t; eg_u=t; eg_A=t; eg_B=t; eg_C=t; eg_D=t;               //used in eGCD_(), inverseMod_()
+md_q1=t; md_q2=t; md_q3=t; md_r=t; md_r1=t; md_r2=t; md_tt=t; //used in mod_()
+
+primes=t; pows=t; s_i=t; s_i2=t; s_R=t; s_rm=t; s_q=t; s_n1=t; 
+  s_a=t; s_r2=t; s_n=t; s_b=t; s_d=t; s_x1=t; s_x2=t, s_aa=t; //used in randTruePrime_()
+  
+rpprb=t; //used in randProbPrimeRounds() (which also uses "primes")
+
+////////////////////////////////////////////////////////////////////////////////////////
+
+
+ 
+
+//return array of all primes less than integer n
+function findPrimes(n) {
+  var i,s,p,ans;
+  s=new Array(n);
+  for (i=0;i<n;i++)
+    s[i]=0;
+  s[0]=2;
+  p=0;    //first p elements of s are primes, the rest are a sieve
+  for(;s[p]<n;) {                  //s[p] is the pth prime
+    for(i=s[p]*s[p]; i<n; i+=s[p]) //mark multiples of s[p]
+      s[i]=1;
+    p++;
+    s[p]=s[p-1]+1;
+    for(; s[p]<n && s[s[p]]; s[p]++); //find next prime (where s[p]==0)
+  }
+  ans=new Array(p);
+  for(i=0;i<p;i++)
+    ans[i]=s[i];
+  return ans;
+}
+
+
+//does a single round of Miller-Rabin base b consider x to be a possible prime?
+//x is a bigInt, and b is an integer, with b<x
+function millerRabinInt(x,b) {
+  if (mr_x1.length!=x.length) {
+    mr_x1=dup(x);
+    mr_r=dup(x);
+    mr_a=dup(x);
+  }
+
+  copyInt_(mr_a,b);
+  return millerRabin(x,mr_a);
+}
+
+//does a single round of Miller-Rabin base b consider x to be a possible prime?
+//x and b are bigInts with b<x
+function millerRabin(x,b) {
+  var i,j,k,s;
+
+  if (mr_x1.length!=x.length) {
+    mr_x1=dup(x);
+    mr_r=dup(x);
+    mr_a=dup(x);
+  }
+
+  copy_(mr_a,b);
+  copy_(mr_r,x);
+  copy_(mr_x1,x);
+
+  addInt_(mr_r,-1);
+  addInt_(mr_x1,-1);
+
+  //s=the highest power of two that divides mr_r
+  k=0;
+  for (i=0;i<mr_r.length;i++)
+    for (j=1;j<mask;j<<=1)
+      if (x[i] & j) {
+        s=(k<mr_r.length+bpe ? k : 0); 
+         i=mr_r.length;
+         j=mask;
+      } else
+        k++;
+
+  if (s)                
+    rightShift_(mr_r,s);
+
+  powMod_(mr_a,mr_r,x);
+
+  if (!equalsInt(mr_a,1) && !equals(mr_a,mr_x1)) {
+    j=1;
+    while (j<=s-1 && !equals(mr_a,mr_x1)) {
+      squareMod_(mr_a,x);
+      if (equalsInt(mr_a,1)) {
+        return 0;
+      }
+      j++;
+    }
+    if (!equals(mr_a,mr_x1)) {
+      return 0;
+    }
+  }
+  return 1;  
+}
+
+//returns how many bits long the bigInt is, not counting leading zeros.
+function bitSize(x) {
+  var j,z,w;
+  for (j=x.length-1; (x[j]==0) && (j>0); j--);
+  for (z=0,w=x[j]; w; (w>>=1),z++);
+  z+=bpe*j;
+  return z;
+}
+
+//return a copy of x with at least n elements, adding leading zeros if needed
+function expand(x,n) {
+  var ans=int2bigInt(0,(x.length>n ? x.length : n)*bpe,0);
+  copy_(ans,x);
+  return ans;
+}
+
+//return a k-bit true random prime using Maurer's algorithm.
+function randTruePrime(k) {
+  var ans=int2bigInt(0,k,0);
+  randTruePrime_(ans,k);
+  return trim(ans,1);
+}
+
+//return a k-bit random probable prime with probability of error < 2^-80
+function randProbPrime(k) {
+  if (k>=600) return randProbPrimeRounds(k,2); //numbers from HAC table 4.3
+  if (k>=550) return randProbPrimeRounds(k,4);
+  if (k>=500) return randProbPrimeRounds(k,5);
+  if (k>=400) return randProbPrimeRounds(k,6);
+  if (k>=350) return randProbPrimeRounds(k,7);
+  if (k>=300) return randProbPrimeRounds(k,9);
+  if (k>=250) return randProbPrimeRounds(k,12); //numbers from HAC table 4.4
+  if (k>=200) return randProbPrimeRounds(k,15);
+  if (k>=150) return randProbPrimeRounds(k,18);
+  if (k>=100) return randProbPrimeRounds(k,27);
+              return randProbPrimeRounds(k,40); //number from HAC remark 4.26 (only an estimate)
+}
+
+//return a k-bit probable random prime using n rounds of Miller Rabin (after trial division with small primes)	
+function randProbPrimeRounds(k,n) {
+  var ans, i, divisible, B; 
+  B=30000;  //B is largest prime to use in trial division
+  ans=int2bigInt(0,k,0);
+  
+  //optimization: try larger and smaller B to find the best limit.
+  
+  if (primes.length==0)
+    primes=findPrimes(30000);  //check for divisibility by primes <=30000
+
+  if (rpprb.length!=ans.length)
+    rpprb=dup(ans);
+
+  for (;;) { //keep trying random values for ans until one appears to be prime
+    //optimization: pick a random number times L=2*3*5*...*p, plus a 
+    //   random element of the list of all numbers in [0,L) not divisible by any prime up to p.
+    //   This can reduce the amount of random number generation.
+    
+    randBigInt_(ans,k,0); //ans = a random odd number to check
+    ans[0] |= 1; 
+    divisible=0;
+  
+    //check ans for divisibility by small primes up to B
+    for (i=0; (i<primes.length) && (primes[i]<=B); i++)
+      if (modInt(ans,primes[i])==0 && !equalsInt(ans,primes[i])) {
+        divisible=1;
+        break;
+      }      
+    
+    //optimization: change millerRabin so the base can be bigger than the number being checked, then eliminate the while here.
+    
+    //do n rounds of Miller Rabin, with random bases less than ans
+    for (i=0; i<n && !divisible; i++) {
+      randBigInt_(rpprb,k,0);
+      while(!greater(ans,rpprb)) //pick a random rpprb that's < ans
+        randBigInt_(rpprb,k,0);
+      if (!millerRabin(ans,rpprb))
+        divisible=1;
+    }
+    
+    if(!divisible)
+      return ans;
+  }  
+}
+
+//return a new bigInt equal to (x mod n) for bigInts x and n.
+function mod(x,n) {
+  var ans=dup(x);
+  mod_(ans,n);
+  return trim(ans,1);
+}
+
+//return (x+n) where x is a bigInt and n is an integer.
+function addInt(x,n) {
+  var ans=expand(x,x.length+1);
+  addInt_(ans,n);
+  return trim(ans,1);
+}
+
+//return x*y for bigInts x and y. This is faster when y<x.
+function mult(x,y) {
+  var ans=expand(x,x.length+y.length);
+  mult_(ans,y);
+  return trim(ans,1);
+}
+
+//return (x**y mod n) where x,y,n are bigInts and ** is exponentiation.  0**0=1. Faster for odd n.
+function powMod(x,y,n) {
+  var ans=expand(x,n.length);  
+  powMod_(ans,trim(y,2),trim(n,2),0);  //this should work without the trim, but doesn't
+  return trim(ans,1);
+}
+
+//return (x-y) for bigInts x and y.  Negative answers will be 2s complement
+function sub(x,y) {
+  var ans=expand(x,(x.length>y.length ? x.length+1 : y.length+1)); 
+  sub_(ans,y);
+  return trim(ans,1);
+}
+
+//return (x+y) for bigInts x and y.  
+function add(x,y) {
+  var ans=expand(x,(x.length>y.length ? x.length+1 : y.length+1)); 
+  add_(ans,y);
+  return trim(ans,1);
+}
+
+//return (x**(-1) mod n) for bigInts x and n.  If no inverse exists, it returns null
+function inverseMod(x,n) {
+  var ans=expand(x,n.length); 
+  var s;
+  s=inverseMod_(ans,n);
+  return s ? trim(ans,1) : null;
+}
+
+//return (x*y mod n) for bigInts x,y,n.  For greater speed, let y<x.
+function multMod(x,y,n) {
+  var ans=expand(x,n.length);
+  multMod_(ans,y,n);
+  return trim(ans,1);
+}
+
+//generate a k-bit true random prime using Maurer's algorithm,
+//and put it into ans.  The bigInt ans must be large enough to hold it.
+function randTruePrime_(ans,k) {
+  var c,m,pm,dd,j,r,B,divisible,z,zz,recSize;
+
+  if (primes.length==0)
+    primes=findPrimes(30000);  //check for divisibility by primes <=30000
+
+  if (pows.length==0) {
+    pows=new Array(512);
+    for (j=0;j<512;j++) {
+      pows[j]=Math.pow(2,j/511.-1.);
+    }
+  }
+
+  //c and m should be tuned for a particular machine and value of k, to maximize speed
+  c=0.1;  //c=0.1 in HAC
+  m=20;   //generate this k-bit number by first recursively generating a number that has between k/2 and k-m bits
+  recLimit=20; //stop recursion when k <=recLimit.  Must have recLimit >= 2
+
+  if (s_i2.length!=ans.length) {
+    s_i2=dup(ans);
+    s_R =dup(ans);
+    s_n1=dup(ans);
+    s_r2=dup(ans);
+    s_d =dup(ans);
+    s_x1=dup(ans);
+    s_x2=dup(ans);
+    s_b =dup(ans);
+    s_n =dup(ans);
+    s_i =dup(ans);
+    s_rm=dup(ans);
+    s_q =dup(ans);
+    s_a =dup(ans);
+    s_aa=dup(ans);
+  }
+
+  if (k <= recLimit) {  //generate small random primes by trial division up to its square root
+    pm=(1<<((k+2)>>1))-1; //pm is binary number with all ones, just over sqrt(2^k)
+    copyInt_(ans,0);
+    for (dd=1;dd;) {
+      dd=0;
+      ans[0]= 1 | (1<<(k-1)) | Math.floor(Math.random()*(1<<k));  //random, k-bit, odd integer, with msb 1
+      for (j=1;(j<primes.length) && ((primes[j]&pm)==primes[j]);j++) { //trial division by all primes 3...sqrt(2^k)
+        if (0==(ans[0]%primes[j])) {
+          dd=1;
+          break;
+        }
+      }
+    }
+    carry_(ans);
+    return;
+  }
+
+  B=c*k*k;    //try small primes up to B (or all the primes[] array if the largest is less than B).
+  if (k>2*m)  //generate this k-bit number by first recursively generating a number that has between k/2 and k-m bits
+    for (r=1; k-k*r<=m; )
+      r=pows[Math.floor(Math.random()*512)];   //r=Math.pow(2,Math.random()-1);
+  else
+    r=.5;
+
+  //simulation suggests the more complex algorithm using r=.333 is only slightly faster.
+
+  recSize=Math.floor(r*k)+1;
+
+  randTruePrime_(s_q,recSize);
+  copyInt_(s_i2,0);
+  s_i2[Math.floor((k-2)/bpe)] |= (1<<((k-2)%bpe));   //s_i2=2^(k-2)
+  divide_(s_i2,s_q,s_i,s_rm);                        //s_i=floor((2^(k-1))/(2q))
+
+  z=bitSize(s_i);
+
+  for (;;) {
+    for (;;) {  //generate z-bit numbers until one falls in the range [0,s_i-1]
+      randBigInt_(s_R,z,0);
+      if (greater(s_i,s_R))
+        break;
+    }                //now s_R is in the range [0,s_i-1]
+    addInt_(s_R,1);  //now s_R is in the range [1,s_i]
+    add_(s_R,s_i);   //now s_R is in the range [s_i+1,2*s_i]
+
+    copy_(s_n,s_q);
+    mult_(s_n,s_R); 
+    multInt_(s_n,2);
+    addInt_(s_n,1);    //s_n=2*s_R*s_q+1
+    
+    copy_(s_r2,s_R);
+    multInt_(s_r2,2);  //s_r2=2*s_R
+
+    //check s_n for divisibility by small primes up to B
+    for (divisible=0,j=0; (j<primes.length) && (primes[j]<B); j++)
+      if (modInt(s_n,primes[j])==0 && !equalsInt(s_n,primes[j])) {
+        divisible=1;
+        break;
+      }      
+
+    if (!divisible)    //if it passes small primes check, then try a single Miller-Rabin base 2
+      if (!millerRabinInt(s_n,2)) //this line represents 75% of the total runtime for randTruePrime_ 
+        divisible=1;
+
+    if (!divisible) {  //if it passes that test, continue checking s_n
+      addInt_(s_n,-3);
+      for (j=s_n.length-1;(s_n[j]==0) && (j>0); j--);  //strip leading zeros
+      for (zz=0,w=s_n[j]; w; (w>>=1),zz++);
+      zz+=bpe*j;                             //zz=number of bits in s_n, ignoring leading zeros
+      for (;;) {  //generate z-bit numbers until one falls in the range [0,s_n-1]
+        randBigInt_(s_a,zz,0);
+        if (greater(s_n,s_a))
+          break;
+      }                //now s_a is in the range [0,s_n-1]
+      addInt_(s_n,3);  //now s_a is in the range [0,s_n-4]
+      addInt_(s_a,2);  //now s_a is in the range [2,s_n-2]
+      copy_(s_b,s_a);
+      copy_(s_n1,s_n);
+      addInt_(s_n1,-1);
+      powMod_(s_b,s_n1,s_n);   //s_b=s_a^(s_n-1) modulo s_n
+      addInt_(s_b,-1);
+      if (isZero(s_b)) {
+        copy_(s_b,s_a);
+        powMod_(s_b,s_r2,s_n);
+        addInt_(s_b,-1);
+        copy_(s_aa,s_n);
+        copy_(s_d,s_b);
+        GCD_(s_d,s_n);  //if s_b and s_n are relatively prime, then s_n is a prime
+        if (equalsInt(s_d,1)) {
+          copy_(ans,s_aa);
+          return;     //if we've made it this far, then s_n is absolutely guaranteed to be prime
+        }
+      }
+    }
+  }
+}
+
+//Return an n-bit random BigInt (n>=1).  If s=1, then the most significant of those n bits is set to 1.
+function randBigInt(n,s) {
+  var a,b;
+  a=Math.floor((n-1)/bpe)+2; //# array elements to hold the BigInt with a leading 0 element
+  b=int2bigInt(0,0,a);
+  randBigInt_(b,n,s);
+  return b;
+}
+
+//Set b to an n-bit random BigInt.  If s=1, then the most significant of those n bits is set to 1.
+//Array b must be big enough to hold the result. Must have n>=1
+function randBigInt_(b,n,s) {
+  var i,a;
+  for (i=0;i<b.length;i++)
+    b[i]=0;
+  a=Math.floor((n-1)/bpe)+1; //# array elements to hold the BigInt
+  for (i=0;i<a;i++) {
+    b[i]=Math.floor(Math.random()*(1<<(bpe-1)));
+  }
+  b[a-1] &= (2<<((n-1)%bpe))-1;
+  if (s==1)
+    b[a-1] |= (1<<((n-1)%bpe));
+}
+
+//Return the greatest common divisor of bigInts x and y (each with same number of elements).
+function GCD(x,y) {
+  var xc,yc;
+  xc=dup(x);
+  yc=dup(y);
+  GCD_(xc,yc);
+  return xc;
+}
+
+//set x to the greatest common divisor of bigInts x and y (each with same number of elements).
+//y is destroyed.
+function GCD_(x,y) {
+  var i,xp,yp,A,B,C,D,q,sing;
+  if (T.length!=x.length)
+    T=dup(x);
+
+  sing=1;
+  while (sing) { //while y has nonzero elements other than y[0]
+    sing=0;
+    for (i=1;i<y.length;i++) //check if y has nonzero elements other than 0
+      if (y[i]) {
+        sing=1;
+        break;
+      }
+    if (!sing) break; //quit when y all zero elements except possibly y[0]
+
+    for (i=x.length;!x[i] && i>=0;i--);  //find most significant element of x
+    xp=x[i];
+    yp=y[i];
+    A=1; B=0; C=0; D=1;
+    while ((yp+C) && (yp+D)) {
+      q =Math.floor((xp+A)/(yp+C));
+      qp=Math.floor((xp+B)/(yp+D));
+      if (q!=qp)
+        break;
+      t= A-q*C;   A=C;   C=t;    //  do (A,B,xp, C,D,yp) = (C,D,yp, A,B,xp) - q*(0,0,0, C,D,yp)      
+      t= B-q*D;   B=D;   D=t;
+      t=xp-q*yp; xp=yp; yp=t;
+    }
+    if (B) {
+      copy_(T,x);
+      linComb_(x,y,A,B); //x=A*x+B*y
+      linComb_(y,T,D,C); //y=D*y+C*T
+    } else {
+      mod_(x,y);
+      copy_(T,x);
+      copy_(x,y);
+      copy_(y,T);
+    } 
+  }
+  if (y[0]==0)
+    return;
+  t=modInt(x,y[0]);
+  copyInt_(x,y[0]);
+  y[0]=t;
+  while (y[0]) {
+    x[0]%=y[0];
+    t=x[0]; x[0]=y[0]; y[0]=t;
+  }
+}
+
+//do x=x**(-1) mod n, for bigInts x and n.
+//If no inverse exists, it sets x to zero and returns 0, else it returns 1.
+//The x array must be at least as large as the n array.
+function inverseMod_(x,n) {
+  var k=1+2*Math.max(x.length,n.length);
+
+  if(!(x[0]&1)  && !(n[0]&1)) {  //if both inputs are even, then inverse doesn't exist
+    copyInt_(x,0);
+    return 0;
+  }
+
+  if (eg_u.length!=k) {
+    eg_u=new Array(k);
+    eg_v=new Array(k);
+    eg_A=new Array(k);
+    eg_B=new Array(k);
+    eg_C=new Array(k);
+    eg_D=new Array(k);
+  }
+
+  copy_(eg_u,x);
+  copy_(eg_v,n);
+  copyInt_(eg_A,1);
+  copyInt_(eg_B,0);
+  copyInt_(eg_C,0);
+  copyInt_(eg_D,1);
+  for (;;) {
+    while(!(eg_u[0]&1)) {  //while eg_u is even
+      halve_(eg_u);
+      if (!(eg_A[0]&1) && !(eg_B[0]&1)) { //if eg_A==eg_B==0 mod 2
+        halve_(eg_A);
+        halve_(eg_B);      
+      } else {
+        add_(eg_A,n);  halve_(eg_A);
+        sub_(eg_B,x);  halve_(eg_B);
+      }
+    }
+
+    while (!(eg_v[0]&1)) {  //while eg_v is even
+      halve_(eg_v);
+      if (!(eg_C[0]&1) && !(eg_D[0]&1)) { //if eg_C==eg_D==0 mod 2
+        halve_(eg_C);
+        halve_(eg_D);      
+      } else {
+        add_(eg_C,n);  halve_(eg_C);
+        sub_(eg_D,x);  halve_(eg_D);
+      }
+    }
+
+    if (!greater(eg_v,eg_u)) { //eg_v <= eg_u
+      sub_(eg_u,eg_v);
+      sub_(eg_A,eg_C);
+      sub_(eg_B,eg_D);
+    } else {                   //eg_v > eg_u
+      sub_(eg_v,eg_u);
+      sub_(eg_C,eg_A);
+      sub_(eg_D,eg_B);
+    }
+  
+    if (equalsInt(eg_u,0)) {
+      while (negative(eg_C)) //make sure answer is nonnegative
+        add_(eg_C,n);
+      copy_(x,eg_C);
+
+      if (!equalsInt(eg_v,1)) { //if GCD_(x,n)!=1, then there is no inverse
+        copyInt_(x,0);
+        return 0;
+      }
+      return 1;
+    }
+  }
+}
+
+//return x**(-1) mod n, for integers x and n.  Return 0 if there is no inverse
+function inverseModInt(x,n) {
+  var a=1,b=0,t;
+  for (;;) {
+    if (x==1) return a;
+    if (x==0) return 0;
+    b-=a*Math.floor(n/x);
+    n%=x;
+
+    if (n==1) return b; //to avoid negatives, change this b to n-b, and each -= to +=
+    if (n==0) return 0;
+    a-=b*Math.floor(x/n);
+    x%=n;
+  }
+}
+
+//this deprecated function is for backward compatibility only. 
+function inverseModInt_(x,n) {
+   return inverseModInt(x,n);
+}
+
+
+//Given positive bigInts x and y, change the bigints v, a, and b to positive bigInts such that:
+//     v = GCD_(x,y) = a*x-b*y
+//The bigInts v, a, b, must have exactly as many elements as the larger of x and y.
+function eGCD_(x,y,v,a,b) {
+  var g=0;
+  var k=Math.max(x.length,y.length);
+  if (eg_u.length!=k) {
+    eg_u=new Array(k);
+    eg_A=new Array(k);
+    eg_B=new Array(k);
+    eg_C=new Array(k);
+    eg_D=new Array(k);
+  }
+  while(!(x[0]&1)  && !(y[0]&1)) {  //while x and y both even
+    halve_(x);
+    halve_(y);
+    g++;
+  }
+  copy_(eg_u,x);
+  copy_(v,y);
+  copyInt_(eg_A,1);
+  copyInt_(eg_B,0);
+  copyInt_(eg_C,0);
+  copyInt_(eg_D,1);
+  for (;;) {
+    while(!(eg_u[0]&1)) {  //while u is even
+      halve_(eg_u);
+      if (!(eg_A[0]&1) && !(eg_B[0]&1)) { //if A==B==0 mod 2
+        halve_(eg_A);
+        halve_(eg_B);      
+      } else {
+        add_(eg_A,y);  halve_(eg_A);
+        sub_(eg_B,x);  halve_(eg_B);
+      }
+    }
+
+    while (!(v[0]&1)) {  //while v is even
+      halve_(v);
+      if (!(eg_C[0]&1) && !(eg_D[0]&1)) { //if C==D==0 mod 2
+        halve_(eg_C);
+        halve_(eg_D);      
+      } else {
+        add_(eg_C,y);  halve_(eg_C);
+        sub_(eg_D,x);  halve_(eg_D);
+      }
+    }
+
+    if (!greater(v,eg_u)) { //v<=u
+      sub_(eg_u,v);
+      sub_(eg_A,eg_C);
+      sub_(eg_B,eg_D);
+    } else {                //v>u
+      sub_(v,eg_u);
+      sub_(eg_C,eg_A);
+      sub_(eg_D,eg_B);
+    }
+    if (equalsInt(eg_u,0)) {
+      while (negative(eg_C)) {   //make sure a (C) is nonnegative
+        add_(eg_C,y);
+        sub_(eg_D,x);
+      }
+      multInt_(eg_D,-1);  ///make sure b (D) is nonnegative
+      copy_(a,eg_C);
+      copy_(b,eg_D);
+      leftShift_(v,g);
+      return;
+    }
+  }
+}
+
+
+//is bigInt x negative?
+function negative(x) {
+  return ((x[x.length-1]>>(bpe-1))&1);
+}
+
+
+//is (x << (shift*bpe)) > y?
+//x and y are nonnegative bigInts
+//shift is a nonnegative integer
+function greaterShift(x,y,shift) {
+  var i, kx=x.length, ky=y.length;
+  k=((kx+shift)<ky) ? (kx+shift) : ky;
+  for (i=ky-1-shift; i<kx && i>=0; i++) {
+    if (x[i]>0)
+      return 1; //if there are nonzeros in x to the left of the first column of y, then x is bigger
+  }
+  for (i=kx-1+shift; i<ky; i++){
+    if (y[i]>0)
+      return 0; //if there are nonzeros in y to the left of the first column of x, then x is not bigger
+  }
+  for (i=k-1; i>=shift; i--){
+    if      (x[i-shift]>y[i]) {  
+      return 1; 
+    } else if(x[i-shift]<y[i]) {
+      return 0 ;
+    }
+  }
+  return 0;
+}
+
+//is x > y? (x and y both nonnegative)
+function greater(x,y) {
+  var i;
+  var k=(x.length<y.length) ? x.length : y.length;
+
+  for (i=x.length;i<y.length;i++)
+    if (y[i])
+      return 0;  //y has more digits
+
+  for (i=y.length;i<x.length;i++){
+    if (x[i])
+      return 1;  //x has more digits
+  }
+
+  for (i=k-1;i>=0;i--){
+    if (x[i]>y[i]){
+      return 1;
+    } else if (x[i]<y[i]){
+      return 0;
+    }
+  }
+  return 0;
+}
+
+//divide x by y giving quotient q and remainder r.  (q=floor(x/y),  r=x mod y).  All 4 are bigints.
+//x must have at least one leading zero element.
+//y must be nonzero.
+//q and r must be arrays that are exactly the same length as x. (Or q can have more).
+//Must have x.length >= y.length >= 2.
+function divide_(x,y,q,r) {
+  var kx, ky;
+  var i,j,y1,y2,c,a,b;
+  copy_(r,x);
+  for (ky=y.length;y[ky-1]==0;ky--); //ky is number of elements in y, not including leading zeros
+
+  //normalize: ensure the most significant element of y has its highest bit set  
+  b=y[ky-1];
+  for (a=0; b; a++)
+    b>>=1;  
+  a=bpe-a;  //a is how many bits to shift so that the high order bit of y is leftmost in its array element
+  leftShift_(y,a);  //multiply both by 1<<a now, then divide both by that at the end
+  leftShift_(r,a);
+
+  //Rob Visser discovered a bug: the following line was originally just before the normalization.
+  for (kx=r.length;r[kx-1]==0 && kx>ky;kx--); //kx is number of elements in normalized x, not including leading zeros
+
+  copyInt_(q,0);                      // q=0
+  while (!greaterShift(y,r,kx-ky)) {  // while (leftShift_(y,kx-ky) <= r) {
+    subShift_(r,y,kx-ky);             //   r=r-leftShift_(y,kx-ky)
+    q[kx-ky]++;                       //   q[kx-ky]++;
+  }                                   // }
+
+  for (i=kx-1; i>=ky; i--) {
+    if (r[i]==y[ky-1]){
+      q[i-ky]=mask;
+    }
+    else{
+      q[i-ky]=Math.floor((r[i]*radix+r[i-1])/y[ky-1]);	
+    }
+
+    //The following for(;;) loop is equivalent to the commented while loop, 
+    //except that the uncommented version avoids overflow.
+    //The commented loop comes from HAC, which assumes r[-1]==y[-1]==0
+    //  while (q[i-ky]*(y[ky-1]*radix+y[ky-2]) > r[i]*radix*radix+r[i-1]*radix+r[i-2])
+    //    q[i-ky]--;    
+    for (;;) {
+      y2=(ky>1 ? y[ky-2] : 0)*q[i-ky];
+      c=y2>>bpe;
+      y2=y2 & mask;
+      y1=c+q[i-ky]*y[ky-1];
+      c=y1>>bpe;
+      y1=y1 & mask;
+
+      if (c==r[i] ? y1==r[i-1] ? y2>(i>1 ? r[i-2] : 0) : y1>r[i-1] : c>r[i]){
+        q[i-ky]--;
+      } 
+      else{
+        break;
+      }
+    }
+
+    linCombShift_(r,y,-q[i-ky],i-ky);    //r=r-q[i-ky]*leftShift_(y,i-ky)
+    if (negative(r)) {
+      addShift_(r,y,i-ky);         //r=r+leftShift_(y,i-ky)
+      q[i-ky]--;
+    }
+  }
+
+  rightShift_(y,a);  //undo the normalization step
+  rightShift_(r,a);  //undo the normalization step
+}
+
+//do carries and borrows so each element of the bigInt x fits in bpe bits.
+function carry_(x) {
+  var i,k,c,b;
+  k=x.length;
+  c=0;
+  for (i=0;i<k;i++) {
+    c+=x[i];
+    b=0;
+    if (c<0) {
+      b=-(c>>bpe);
+      c+=b*radix;
+    }
+    x[i]=c & mask;
+    c=(c>>bpe)-b;
+  }
+}
+
+//return x mod n for bigInt x and integer n.
+function modInt(x,n) {
+  var i,c=0;
+  for (i=x.length-1; i>=0; i--)
+    c=(c*radix+x[i])%n;
+  return c;
+}
+
+//convert the integer t into a bigInt with at least the given number of bits.
+//the returned array stores the bigInt in bpe-bit chunks, little endian (buff[0] is least significant word)
+//Pad the array with leading zeros so that it has at least minSize elements.
+//There will always be at least one leading 0 element.
+function int2bigInt(t,bits,minSize) {   
+  var i,k;
+  k=Math.ceil(bits/bpe)+1;
+  k=minSize>k ? minSize : k;
+  buff=new Array(k);
+  copyInt_(buff,t);
+  return buff;
+}
+
+//return the bigInt given a string representation in a given base.  
+//Pad the array with leading zeros so that it has at least minSize elements.
+//If base=-1, then it reads in a space-separated list of array elements in decimal.
+//The array will always have at least one leading zero, unless base=-1.
+function str2bigInt(s,base,minSize) {
+  var d, i, j, x, y, kk;
+  var k=s.length;
+  if (base==-1) { //comma-separated list of array elements in decimal
+    x=new Array(0);
+    for (;;) {
+      y=new Array(x.length+1);
+      for (i=0;i<x.length;i++)
+        y[i+1]=x[i];
+      y[0]=parseInt(s,10);
+      x=y;
+      d=s.indexOf(',',0);
+      if (d<1) 
+        break;
+      s=s.substring(d+1);
+      if (s.length==0)
+        break;
+    }
+    if (x.length<minSize) {
+      y=new Array(minSize);
+      copy_(y,x);
+      return y;
+    }
+    return x;
+  }
+
+  x=int2bigInt(0,base*k,0);
+  for (i=0;i<k;i++) {
+    d=digitsStr.indexOf(s.substring(i,i+1),0);
+    if (base<=36 && d>=36)  //convert lowercase to uppercase if base<=36
+      d-=26;
+    if (d>=base || d<0) {   //stop at first illegal character
+      break;
+    }
+    multInt_(x,base);
+    addInt_(x,d);
+  }
+
+  for (k=x.length;k>0 && !x[k-1];k--); //strip off leading zeros
+  k=minSize>k+1 ? minSize : k+1;
+  y=new Array(k);
+  kk=k<x.length ? k : x.length;
+  for (i=0;i<kk;i++)
+    y[i]=x[i];
+  for (;i<k;i++)
+    y[i]=0;
+  return y;
+}
+
+//is bigint x equal to integer y?
+//y must have less than bpe bits
+function equalsInt(x,y) {
+  var i;
+  if (x[0]!=y)
+    return 0;
+  for (i=1;i<x.length;i++)
+    if (x[i])
+      return 0;
+  return 1;
+}
+
+//are bigints x and y equal?
+//this works even if x and y are different lengths and have arbitrarily many leading zeros
+function equals(x,y) {
+  var i;
+  var k=x.length<y.length ? x.length : y.length;
+  for (i=0;i<k;i++)
+    if (x[i]!=y[i])
+      return 0;
+  if (x.length>y.length) {
+    for (;i<x.length;i++)
+      if (x[i])
+        return 0;
+  } else {
+    for (;i<y.length;i++)
+      if (y[i])
+        return 0;
+  }
+  return 1;
+}
+
+//is the bigInt x equal to zero?
+function isZero(x) {
+  var i;
+  for (i=0;i<x.length;i++)
+    if (x[i])
+      return 0;
+  return 1;
+}
+
+//convert a bigInt into a string in a given base, from base 2 up to base 95.
+//Base -1 prints the contents of the array representing the number.
+function bigInt2str(x,base) {
+  if(digitsStr.length-1 < base) {
+    var str = "base "+(digitsStr.length-1)+" is max";
+    throw new Error(str);
+  }
+  var i,t,s="";
+
+  if (s6.length!=x.length) {
+    s6=dup(x);
+  }
+  else{
+    copy_(s6,x);
+  }
+
+  if (base==-1) { //return the list of array contents
+    for (i=x.length-1;i>0;i--){
+      s+=x[i]+',';
+    }
+    s+=x[0];
+  }
+  else { //return it in the given base
+    while (!isZero(s6)) {
+      t=divInt_(s6,base);  //t=s6 % base; s6=floor(s6/base);
+      s=digitsStr.substring(t,t+1)+s;
+    }
+  }
+  if (s.length==0){
+    s="0";
+  }
+  return s;
+}
+
+//returns a duplicate of bigInt x
+function dup(x) {
+  var i;
+  buff=new Array(x.length);
+  copy_(buff,x);
+  return buff;
+}
+
+//do x=y on bigInts x and y.  x must be an array at least as big as y (not counting the leading zeros in y).
+function copy_(x,y) {
+  var i;
+  var k=x.length<y.length ? x.length : y.length;
+  for (i=0;i<k;i++)
+    x[i]=y[i];
+  for (i=k;i<x.length;i++)
+    x[i]=0;
+}
+
+//do x=y on bigInt x and integer y.  
+function copyInt_(x,n) {
+  var i,c;
+  for (c=n,i=0;i<x.length;i++) {
+    x[i]=c & mask;
+    c>>=bpe;
+  }
+}
+
+//do x=x+n where x is a bigInt and n is an integer.
+//x must be large enough to hold the result.
+function addInt_(x,n) {
+  var i,k,c,b;
+  x[0]+=n;
+  k=x.length;
+  c=0;
+  for (i=0;i<k;i++) {
+    c+=x[i];
+    b=0;
+    if (c<0) {
+      b=-(c>>bpe);
+      c+=b*radix;
+    }
+    x[i]=c & mask;
+    c=(c>>bpe)-b;
+    if (!c) return; //stop carrying as soon as the carry is zero
+  }
+}
+
+//right shift bigInt x by n bits.  0 <= n < bpe.
+function rightShift_(x,n) {
+  var i;
+  var k=Math.floor(n/bpe);
+  if (k) {
+    for (i=0;i<x.length-k;i++) //right shift x by k elements
+      x[i]=x[i+k];
+    for (;i<x.length;i++)
+      x[i]=0;
+    n%=bpe;
+  }
+  for (i=0;i<x.length-1;i++) {
+    x[i]=mask & ((x[i+1]<<(bpe-n)) | (x[i]>>n));
+  }
+  x[i]>>=n;
+}
+
+//do x=floor(|x|/2)*sgn(x) for bigInt x in 2's complement
+function halve_(x) {
+  var i;
+  for (i=0;i<x.length-1;i++) {
+    x[i]=mask & ((x[i+1]<<(bpe-1)) | (x[i]>>1));
+  }
+  x[i]=(x[i]>>1) | (x[i] & (radix>>1));  //most significant bit stays the same
+}
+
+//left shift bigInt x by n bits.
+function leftShift_(x,n) {
+  var i;
+  var k=Math.floor(n/bpe);
+  if (k) {
+    for (i=x.length; i>=k; i--) //left shift x by k elements
+      x[i]=x[i-k];
+    for (;i>=0;i--)
+      x[i]=0;  
+    n%=bpe;
+  }
+  if (!n)
+    return;
+  for (i=x.length-1;i>0;i--) {
+    x[i]=mask & ((x[i]<<n) | (x[i-1]>>(bpe-n)));
+  }
+  x[i]=mask & (x[i]<<n);
+}
+
+//do x=x*n where x is a bigInt and n is an integer.
+//x must be large enough to hold the result.
+function multInt_(x,n) {
+  var i,k,c,b;
+  if (!n)
+    return;
+  k=x.length;
+  c=0;
+  for (i=0;i<k;i++) {
+    c+=x[i]*n;
+    b=0;
+    if (c<0) {
+      b=-(c>>bpe);
+      c+=b*radix;
+    }
+    x[i]=c & mask;
+    c=(c>>bpe)-b;
+  }
+}
+
+//do x=floor(x/n) for bigInt x and integer n, and return the remainder
+function divInt_(x,n) {
+  var i,r=0,s;
+  for (i=x.length-1;i>=0;i--) {
+    s=r*radix+x[i];
+    x[i]=Math.floor(s/n);
+    r=s%n;
+  }
+  return r;
+}
+
+//do the linear combination x=a*x+b*y for bigInts x and y, and integers a and b.
+//x must be large enough to hold the answer.
+function linComb_(x,y,a,b) {
+  var i,c,k,kk;
+  k=x.length<y.length ? x.length : y.length;
+  kk=x.length;
+  for (c=0,i=0;i<k;i++) {
+    c+=a*x[i]+b*y[i];
+    x[i]=c & mask;
+    c>>=bpe;
+  }
+  for (i=k;i<kk;i++) {
+    c+=a*x[i];
+    x[i]=c & mask;
+    c>>=bpe;
+  }
+}
+
+//do the linear combination x=a*x+b*(y<<(ys*bpe)) for bigInts x and y, and integers a, b and ys.
+//x must be large enough to hold the answer.
+function linCombShift_(x,y,b,ys) {
+  var i,c,k,kk;
+  k=x.length<ys+y.length ? x.length : ys+y.length;
+  kk=x.length;
+  for (c=0,i=ys;i<k;i++) {
+    c+=x[i]+b*y[i-ys];
+    x[i]=c & mask;
+    c>>=bpe;
+  }
+  for (i=k;c && i<kk;i++) {
+    c+=x[i];
+    x[i]=c & mask;
+    c>>=bpe;
+  }
+}
+
+//do x=x+(y<<(ys*bpe)) for bigInts x and y, and integers a,b and ys.
+//x must be large enough to hold the answer.
+function addShift_(x,y,ys) {
+  var i,c,k,kk;
+  k=x.length<ys+y.length ? x.length : ys+y.length;
+  kk=x.length;
+  for (c=0,i=ys;i<k;i++) {
+    c+=x[i]+y[i-ys];
+    x[i]=c & mask;
+    c>>=bpe;
+  }
+  for (i=k;c && i<kk;i++) {
+    c+=x[i];
+    x[i]=c & mask;
+    c>>=bpe;
+  }
+}
+
+//do x=x-(y<<(ys*bpe)) for bigInts x and y, and integers a,b and ys.
+//x must be large enough to hold the answer.
+function subShift_(x,y,ys) {
+  var i,c,k,kk;
+  k=x.length<ys+y.length ? x.length : ys+y.length;
+  kk=x.length;
+  for (c=0,i=ys;i<k;i++) {
+    c+=x[i]-y[i-ys];
+    x[i]=c & mask;
+    c>>=bpe;
+  }
+  for (i=k;c && i<kk;i++) {
+    c+=x[i];
+    x[i]=c & mask;
+    c>>=bpe;
+  }
+}
+
+//do x=x-y for bigInts x and y.
+//x must be large enough to hold the answer.
+//negative answers will be 2s complement
+function sub_(x,y) {
+  var i,c,k,kk;
+  k=x.length<y.length ? x.length : y.length;
+  for (c=0,i=0;i<k;i++) {
+    c+=x[i]-y[i];
+    x[i]=c & mask;
+    c>>=bpe;
+  }
+  for (i=k;c && i<x.length;i++) {
+    c+=x[i];
+    x[i]=c & mask;
+    c>>=bpe;
+  }
+}
+
+//do x=x+y for bigInts x and y.
+//x must be large enough to hold the answer.
+function add_(x,y) {
+  var i,c,k,kk;
+  k=x.length<y.length ? x.length : y.length;
+  for (c=0,i=0;i<k;i++) {
+    c+=x[i]+y[i];
+    x[i]=c & mask;
+    c>>=bpe;
+  }
+  for (i=k;c && i<x.length;i++) {
+    c+=x[i];
+    x[i]=c & mask;
+    c>>=bpe;
+  }
+}
+
+//do x=x*y for bigInts x and y.  This is faster when y<x.
+function mult_(x,y) {
+  var i;
+  if (ss.length!=2*x.length)
+    ss=new Array(2*x.length);
+  copyInt_(ss,0);
+  for (i=0;i<y.length;i++)
+    if (y[i])
+      linCombShift_(ss,x,y[i],i);   //ss=1*ss+y[i]*(x<<(i*bpe))
+  copy_(x,ss);
+}
+
+//do x=x mod n for bigInts x and n.
+function mod_(x,n) {
+  if (s4.length!=x.length){
+    s4=dup(x);
+  }
+  else{
+    copy_(s4,x);
+  }
+  if (s5.length!=x.length){
+    s5=dup(x);  
+  }
+  divide_(s4,n,s5,x);  //x = remainder of s4 / n
+}
+
+//do x=x*y mod n for bigInts x,y,n.
+//for greater speed, let y<x.
+function multMod_(x,y,n) {
+  var i;
+  if (s0.length!=2*x.length)
+    s0=new Array(2*x.length);
+  copyInt_(s0,0);
+  for (i=0;i<y.length;i++)
+    if (y[i])
+      linCombShift_(s0,x,y[i],i);   //s0=1*s0+y[i]*(x<<(i*bpe))
+  mod_(s0,n);
+  copy_(x,s0);
+}
+
+//do x=x*x mod n for bigInts x,n.
+function squareMod_(x,n) {
+  var i,j,d,c,kx,kn,k;
+  for (kx=x.length; kx>0 && !x[kx-1]; kx--);  //ignore leading zeros in x
+  k=kx>n.length ? 2*kx : 2*n.length; //k=# elements in the product, which is twice the elements in the larger of x and n
+  if (s0.length!=k) 
+    s0=new Array(k);
+  copyInt_(s0,0);
+  for (i=0;i<kx;i++) {
+    c=s0[2*i]+x[i]*x[i];
+    s0[2*i]=c & mask;
+    c>>=bpe;
+    for (j=i+1;j<kx;j++) {
+      c=s0[i+j]+2*x[i]*x[j]+c;
+      s0[i+j]=(c & mask);
+      c>>=bpe;
+    }
+    s0[i+kx]=c;
+  }
+  mod_(s0,n);
+  copy_(x,s0);
+}
+
+//return x with exactly k leading zero elements
+function trim(x,k) {
+  var i,y;
+  for (i=x.length; i>0 && !x[i-1]; i--);
+  y=new Array(i+k);
+  copy_(y,x);
+  return y;
+}
+
+//do x=x**y mod n, where x,y,n are bigInts and ** is exponentiation.  0**0=1.
+//this is faster when n is odd.  x usually needs to have as many elements as n.
+function powMod_(x,y,n) {
+  var k1,k2,kn,np;
+  if(s7.length!=n.length)
+    s7=dup(n);
+
+  //for even modulus, use a simple square-and-multiply algorithm,
+  //rather than using the more complex Montgomery algorithm.
+  if ((n[0]&1)==0) {
+    copy_(s7,x);
+    copyInt_(x,1);
+    while(!equalsInt(y,0)) {
+      if (y[0]&1)
+        multMod_(x,s7,n);
+      divInt_(y,2);
+      squareMod_(s7,n); 
+    }
+    return;
+  }
+
+  //calculate np from n for the Montgomery multiplications
+  copyInt_(s7,0);
+  for (kn=n.length;kn>0 && !n[kn-1];kn--);
+  np=radix-inverseModInt(modInt(n,radix),radix);
+  s7[kn]=1;
+  multMod_(x ,s7,n);   // x = x * 2**(kn*bp) mod n
+
+  if (s3.length!=x.length){
+    s3=dup(x);
+  }
+  else{
+    copy_(s3,x);
+  }
+
+  for (k1=y.length-1;k1>0 & !y[k1]; k1--);  //k1=first nonzero element of y
+  if (y[k1]==0) {  //anything to the 0th power is 1
+    copyInt_(x,1);
+    return;
+  }
+  for (k2=1<<(bpe-1);k2 && !(y[k1] & k2); k2>>=1);  //k2=position of first 1 bit in y[k1]
+  for (;;) {
+    if (!(k2>>=1)) {  //look at next bit of y
+      k1--;
+      if (k1<0) {
+        mont_(x,one,n,np);
+        return;
+      }
+      k2=1<<(bpe-1);
+    }    
+    mont_(x,x,n,np);
+
+    if (k2 & y[k1]) //if next bit is a 1
+      mont_(x,s3,n,np);
+  }
+}
+
+
+//do x=x*y*Ri mod n for bigInts x,y,n, 
+//  where Ri = 2**(-kn*bpe) mod n, and kn is the 
+//  number of elements in the n array, not 
+//  counting leading zeros.  
+//x array must have at least as many elemnts as the n array
+//It's OK if x and y are the same variable.
+//must have:
+//  x,y < n
+//  n is odd
+//  np = -(n^(-1)) mod radix
+function mont_(x,y,n,np) {
+  var i,j,c,ui,t,ks;
+  var kn=n.length;
+  var ky=y.length;
+
+  if (sa.length!=kn)
+    sa=new Array(kn);
+    
+  copyInt_(sa,0);
+
+  for (;kn>0 && n[kn-1]==0;kn--); //ignore leading zeros of n
+  for (;ky>0 && y[ky-1]==0;ky--); //ignore leading zeros of y
+  ks=sa.length-1; //sa will never have more than this many nonzero elements.  
+
+  //the following loop consumes 95% of the runtime for randTruePrime_() and powMod_() for large numbers
+  for (i=0; i<kn; i++) {
+    t=sa[0]+x[i]*y[0];
+    ui=((t & mask) * np) & mask;  //the inner "& mask" was needed on Safari (but not MSIE) at one time
+    c=(t+ui*n[0]) >> bpe;
+    t=x[i];
+    
+    //do sa=(sa+x[i]*y+ui*n)/b   where b=2**bpe.  Loop is unrolled 5-fold for speed
+    j=1;
+    for (;j<ky-4;) { c+=sa[j]+ui*n[j]+t*y[j];   sa[j-1]=c & mask;   c>>=bpe;   j++;
+                     c+=sa[j]+ui*n[j]+t*y[j];   sa[j-1]=c & mask;   c>>=bpe;   j++;
+                     c+=sa[j]+ui*n[j]+t*y[j];   sa[j-1]=c & mask;   c>>=bpe;   j++;
+                     c+=sa[j]+ui*n[j]+t*y[j];   sa[j-1]=c & mask;   c>>=bpe;   j++;
+                     c+=sa[j]+ui*n[j]+t*y[j];   sa[j-1]=c & mask;   c>>=bpe;   j++; }    
+    for (;j<ky;)   { c+=sa[j]+ui*n[j]+t*y[j];   sa[j-1]=c & mask;   c>>=bpe;   j++; }
+    for (;j<kn-4;) { c+=sa[j]+ui*n[j];          sa[j-1]=c & mask;   c>>=bpe;   j++;
+                     c+=sa[j]+ui*n[j];          sa[j-1]=c & mask;   c>>=bpe;   j++;
+                     c+=sa[j]+ui*n[j];          sa[j-1]=c & mask;   c>>=bpe;   j++;
+                     c+=sa[j]+ui*n[j];          sa[j-1]=c & mask;   c>>=bpe;   j++;
+                     c+=sa[j]+ui*n[j];          sa[j-1]=c & mask;   c>>=bpe;   j++; }  
+    for (;j<kn;)   { c+=sa[j]+ui*n[j];          sa[j-1]=c & mask;   c>>=bpe;   j++; }   
+    for (;j<ks;)   { c+=sa[j];                  sa[j-1]=c & mask;   c>>=bpe;   j++; }  
+    sa[j-1]=c & mask;
+  }
+
+  if (!greater(n,sa))
+    sub_(sa,n);
+  copy_(x,sa);
+}
+
+
+
+BigInt = module.exports = {
+  'add': add,
+  'addInt': addInt, 
+  'bigInt2str': bigInt2str, 
+  'bitSize': bitSize,
+  'copy': copy_,
+  'copyInt': copyInt_,
+  'dup': dup,
+  'div': divide_,
+  'equals': equals,
+  'equalsInt': equalsInt,
+  'expand': expand,
+  'findPrimes': findPrimes,
+  'GCD': GCD,
+  'greater': greater,
+  'greaterShift': greaterShift,
+  'int2bigInt': int2bigInt,
+  'inverseMod': inverseMod,
+  'inverseModInt': inverseModInt,
+  'isZero': isZero,
+  'millerRabin': millerRabin,
+  'millerRabinInt': millerRabinInt,
+  'mod': mod,
+  'modInt': modInt,
+  'mult': mult_,
+  'multMod': multMod,
+  'negative': negative,
+  'powMod': powMod,
+  'randBigInt': randBigInt,
+  'randTruePrime': randTruePrime,
+  'randProbPrime': randProbPrime,
+  'leftShift': leftShift_,
+  'rightShift': rightShift_,
+  'str2bigInt': str2bigInt,
+  'sub': sub,
+  'trim': trim
+};
+

+ 655 - 0
buffa.js

@@ -0,0 +1,655 @@
+
+
+
+//require('bufferjs');
+var crypto=require('crypto');
+
+
+var Buffer = require("./buffer").Buffer;
+console.log(typeof(Buffer));
+
+exports.Buffer = Buffer;
+exports.dump = hexdump;
+exports.hexdump = hexdump;
+
+
+
+
+Buffer.prototype.XOR = function(buf){
+	var nn = new Buffer(this.length);
+	var mi = buf.length;
+	var fi = 0;
+	var n = this.length;
+	for(var i=0;i<n;i++){
+		if(i>mi){
+			fi = 0;
+			}
+			nn[i] = this[i] ^ (buf[fi]);
+		fi ++;
+	}
+	return nn;
+}
+Buffer.prototype.AND = function(buf){
+	var nn = new Buffer(this.length);
+	var mi = buf.length;
+	var fi = 0;
+	var n = this.length;
+	for(var i=0;i<n;i++){
+		if(i>mi){
+			fi = 0;
+			}
+			nn[i] = this[i] & (buf[fi]);
+		fi ++;
+	}
+	return nn;
+}
+Buffer.prototype.OR = function(buf){
+	var nn = new Buffer(this.length);
+	var mi = buf.length;
+	var fi = 0;
+	var n = this.length;
+	for(var i=0;i<n;i++){
+		if(i>mi){
+			fi = 0;
+			}
+			nn[i] = this[i] | (buf[fi]);
+		fi ++;
+	}
+	return nn;
+}
+
+Buffer.prototype.clone = function(){
+	var n = new Buffer(this.length);
+		for(var i=0;i<this.length;i++){
+			n[i] = this[i];
+		}
+	return n;
+	}
+
+Buffer.prototype.append = function(buf,baselength){
+	var nlen = this.length + buf.length;
+	if(baselength){
+		nlen = 	Math.ceil( (nlen) / baselength) * baselength;
+	}
+	var tmp = new Buffer( nlen );
+		tmp.fill(0);
+	for(var i=0;i<this.length;i++){
+		tmp[i]=this[i];
+		}
+	for(var i=0;i<buf.length;i++){
+		tmp[this.length+i]=buf[i];
+		}
+ 	return tmp;
+}
+
+
+var BASE = 
+["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","_","=","/","!","#","$","%","&","'","(",")","*","+",",","-",".",":",";","<",">","@","[","]","^","`","{","|","}","~","¡","¢","£","¤","¥","¦","§","¨","©","ª","«","¬","®","¯","°","±","²","³","´","µ","¶","·","¸","¹","º","»","¼","½","¾","¿","À","Á","Â","Ã","Ä","Å","Æ","Ç","È","É","Ê","Ë","Ì","Í","Î","Ï","Ð","Ñ","Ò","Ó","Ô","Õ","Ö","×","Ø","Ù","Ú","Û","Ü","Ý","Þ","ß","à","á","â","ã","ä","å","æ","ç","è","é","ê","ë","ì","í","î","ï","ð","ñ","ò","ó","ô","õ","ö","÷","ø","ù","ú","û","ü","ý","þ"];
+
+function getnum(num,base){
+		var ss = ""
+		while(num > 0){
+			var t = num % base;
+				ss =  BASE[t] + ss;
+				num = Math.floor(num/base);
+		}
+		return ss;
+}
+var bigi = require("../bigint");
+
+Buffer.prototype.toExpand = function(string,base){
+	var asa = bigi.str2bigInt(string,base);
+ 	var ss = bigi.bigInt2str(asa,16);
+ 
+	var re = new Buffer(ss.length%2===0?ss:"0"+ss,'hex');
+	return re;
+}
+
+
+Buffer.prototype.toBase = function(base){
+	var ss = this.toString("hex");
+	var asa = bigi.str2bigInt(ss,16);
+	var s = bigi.bigInt2str(asa,base);
+
+	return  s;
+	console.log(base,"sass",asa,s,ss);
+
+	return ;
+
+	var nn = this.clone();
+		var nwords = Math.floor(nn.length/4);
+		var padding = [0,1,2,3][nn.length % 4];
+		var rest = parseInt(nn.slice(nn.length-padding).toString("hex"),16);
+		var s = "";
+		var at = 0;
+	while(at < nwords){
+		var num = nn.readUInt32BE(at*4);
+
+
+		s += getnum(num,base);
+		s += ss+" ";	 
+		at += 1;
+	}
+	console.log(rest);
+
+	s += getnum(rest,base);
+
+return s;
+
+ 
+}
+
+
+
+Buffer.prototype.prepend = function(buf){
+	var tmp = new Buffer(this.length+buf.length);
+	for(var i=0;i<buf.length;i++){
+		tmp[i]=buf[i];
+		}
+	for(var i=0;i<this.length;i++){
+		tmp[buf.length+i]=this[i];
+		}
+	return tmp;
+}
+Buffer.prototype.SHA1= function(encoding){
+	var encoding = encoding || null;
+	var h=crypto.createHash('sha1');
+		h.update(this);
+		return h.digest(encoding);
+}
+Buffer.prototype.SHA224 = function(encoding){
+	var encoding = encoding || null;
+	var h=crypto.createHash('sha224');
+		h.update(this);
+		return h.digest(encoding);
+}
+Buffer.prototype.SHA256 = function(encoding){
+	var encoding = encoding || null;
+	var h=crypto.createHash('sha256');
+		h.update(this);
+		return h.digest(encoding);
+}
+Buffer.prototype.SHA384 = function(encoding){
+	var encoding = encoding || null;
+	var h=crypto.createHash('sha384');
+		h.update(this);
+		return h.digest(encoding);
+}
+Buffer.prototype.SHA512 = function(encoding){
+	var encoding = encoding || null;
+	var h=crypto.createHash('sha512');
+		h.update(this);
+		return h.digest(encoding);
+}
+
+Buffer.prototype.MD5= function(encoding){
+	var encoding = encoding || null;
+	var h=crypto.createHash('md5');
+		h.update(this);
+		return h.digest(encoding);
+}
+Buffer.prototype.RIPE= function(encoding){
+	var encoding = encoding || null;
+	var h=crypto.createHash('ripemd');
+		h.update(this);
+		return h.digest(encoding);
+}
+Buffer.prototype.RIPE160= function(encoding){
+	var encoding = encoding || null;
+	var h=crypto.createHash('ripemd160');
+		h.update(this);
+		return h.digest(encoding);
+}
+
+Buffer.prototype.WHIRLPOOL= function(encoding){
+	var encoding = encoding || null;
+	var h=crypto.createHash('whirlpool');
+		h.update(this);
+		return h.digest(encoding);
+}
+
+Buffer.prototype.cmp = function(cmp){
+	return !this.cmpNotSame.apply(this,[cmp]);
+	}
+
+Buffer.prototype.cmpNotSame = function(cmp){
+	var f=false;
+	var nmax = this.length > cmp.length ? cmp.length : this.length;
+	var n = 0;
+	while(!f){
+		if(cmp[n]===this[n]){
+			n++
+		}else{
+			f=true;
+		}
+		if(n>nmax){
+			return f;
+			}
+		}
+		return f;
+	}
+
+//console.log(crypto.getHashes());
+
+
+//console.log(new Buffer("10"));
+
+/*
+Buffer.prototype.scan = function(chunksize,each,end){
+	var end = end || function(){};
+	var each = each || function(){};
+	var maxi = this.length;
+	var items = 0;
+	if( maxi % chunksize === 0){
+		items = maxi/chunksize;
+		}
+
+	var indexat = 0;
+	var self = this;
+	var count = 0;
+	function chunk(){
+		var pp = (indexat+chunksize);
+			pp = (pp > maxi ? maxi : pp);
+
+		each.apply(each,[self.slice(indexat,pp),count]);
+		count ++;
+		if(indexat < self.length-chunksize){
+				indexat += chunksize;
+				process.nextTick(chunk);
+			}else{
+				end.apply(end,[count]);
+				}
+		}
+
+	chunk();
+
+	}
+
+*/
+
+
+/*
+Buffer.prototype.extract = function(obj){
+	var o = {};
+	for(var prop in obj){
+
+		if(obj[prop].pos){
+			o[prop] = obj[prop].type(this.slice(obj[prop].pos[0],obj[prop].pos[1]));
+		}else{
+			if(typeof(obj[prop]) === "object"){
+				o[prop] = {};
+				for(var subprop in obj[prop]){
+						if(obj[prop][subprop].pos){
+
+					o[prop][subprop] = obj[prop][subprop].type(this.slice(obj[prop][subprop].pos[0],obj[prop][subprop].pos[1]));
+					}
+
+					}
+
+
+				}
+
+			}
+	}
+
+	return o;
+
+
+	}
+
+
+
+
+
+
+Buffer.prototype.chksum = function(encoding){
+	var encoding = encoding || 'base64';
+	var hash=crypto.createHash('sha256');
+		hash.update(this);
+		var r = hash.digest(encoding);
+		if(encoding==="binary"){
+			var rr = new Buffer(32);
+			for(var i=0;i<32;i++){
+				rr[i] = r.charCodeAt(i);
+				}
+				r = rr;
+			}
+	return r;
+}
+Buffer.prototype.chksuma = function(encoding){
+	var encoding = encoding | 'base64';
+	var hash=crypto.createHash('sha1');
+		hash.update(this);
+	return	hash.digest(encoding);
+}
+
+
+
+Buffer.prototype.toHex = function(){
+	var s = "";
+	for(var i=0;i<this.length;i++){
+		var byte = this[i].toString(16);
+			byte = (byte.length<2) ? '0'+byte : byte;
+			s += byte;
+		}
+	return s;
+	}
+
+
+
+
+Buffer.prototype.toInt = function(){
+	var l=this.length-1;
+	var i=this[l];
+	l--;
+	var b = 256;
+	while(l>-1){
+		i += this[l]*b;
+		l--;
+		b *= 256;
+		}
+	return i;
+	}
+
+
+
+
+
+
+Buffer.prototype.indexOf = function(bytes,start){
+	var i=start||0;
+	var len=this.length-bytes.length,found=false;
+	while(!found && i<len){
+		var a = this.slice(i,i+bytes.length);
+		if(a.toString()===bytes.toString()){
+			return i;
+			}
+
+		i++;
+		}
+	return false;
+
+
+
+	};
+
+Buffer.prototype.fill = function(a){
+	if(typeof(a)==="function"){
+		for(var i=0;i<this.length;i++){
+			 this[i] = a.apply(this,[i]);
+		}
+
+		}else{
+
+		for(var i=0;i<this.length;i++){
+				this[i] = a;
+		}
+	}
+}
+
+Buffer.prototype.filla = function(a,ii,is){
+	if(typeof(a)==="function"){
+		for(var i=ii;i<is;i++){
+			 this[i] = a.apply(this,[i]);
+		}
+
+		}else{
+
+		for(var i=ii;i<is;i++){
+				this[i] = a;
+		}
+	}
+}
+
+function random_byte(){
+	return Math.floor(Math.random()*255);
+	}
+function add_byte(i){
+	this[i] = this[i]+1;
+
+	}
+*/
+
+function hexdump(buf,showascii,perline,space,padit,linenums,showtype){
+	var showtype = showtype || false;
+		var s = "";
+		if(showtype){
+			s += "type: "+typeof(buf)+" "+((buf instanceof Buffer))+"\n";
+		}
+	if(typeof(buf) !== "object"){
+		buf = new Buffer(buf);
+		}
+
+	var usebuf;
+	var perline = (perline===0||perline) ? perline : 32;
+	var space = (space===0||space) ? space : 8;
+	var showascii = showascii || false;
+	var linenums = linenums || false;
+	if(perline === 0){
+		perline = buf.length;
+		}
+	usebuf = buf;
+	if(padit){
+		var shouldbelength = Math.ceil(buf.length/perline)*perline;
+		var nbuf = new Buffer(shouldbelength);
+			nbuf.fill(0);
+			buf.copy(nbuf,0,0,buf.length);
+			usebuf = nbuf;
+		}
+
+	var tl = Math.ceil(buf.length/perline);
+
+
+
+	for(var i=0;i<tl;i++){
+		var mx = (i*perline)+perline;
+			if(mx > usebuf.length){
+				mx = usebuf.length;
+			}
+			if(linenums){
+				s += intToHex(i*perline,3)+" ";
+
+				}
+			var a = "";
+			var t = usebuf.slice(i*perline,mx);
+			for(var y=0;y<t.length;y++){
+				s += int2hex(t[y]);
+					if((t[y] > 31) && (t[y] !== 127)){
+						a += String.fromCharCode(t[y]);
+					}else{
+						a += ".";
+					}
+
+				if(y % space === (space-1)){
+					s += " ";
+					a += " ";
+					}
+
+				}
+
+				if(showascii){
+					s += " | " +a;
+				}
+				if(tl>1){
+					s += "\n";
+
+					}
+
+		}
+
+return s;
+
+}
+
+
+function int2hex(integer) {
+  integer = integer.toString(16);
+  if (integer.length % 2 !== 0) {
+    integer = '0' + integer;
+  }
+  return integer;
+};
+
+function int2word(integer) {
+  integer = integer.toString(16);
+  if (integer.length % 8 !== 0) {
+	  while(integer.length<8){
+		    integer = '0' + integer;
+	  }
+  }
+  return integer;
+};
+function int2longword(integer) {
+  integer = integer.toString(16);
+  if (integer.length % 16 !== 0) {
+	  while(integer.length<16){
+		    integer = '0' + integer;
+	  }
+  }
+  return integer;
+};
+
+
+exports.intToHex = intToHex;
+
+exports.hexToBytes = hexToBytes;
+
+exports.hexToBuffer = hexToBuffer;
+
+function hexToBuffer (hexa) {
+	return new Buffer(hexToBytes(hexa));
+}
+
+
+function hexToBytes (hexa) {
+	for (var bytes = [], c = 0; c < hexa.length/2; c ++)
+		bytes.push(parseInt(hexa.substr(c*2, 2), 16));
+	return bytes;
+};
+
+function intToHex (integera,bytes) {
+	var bytes = bytes || 1;
+	   integera = integera.toString(16);
+	  if (integera.length % (bytes*2) !== 0) {
+		  while(integera.length<bytes*2){
+			    integera = '0' + integera;
+		  }
+	  }
+	  return integera;
+};
+
+exports.bufferToInt = function (arr){
+	var l=arr.length-1;
+	var i=arr[l];
+	l--;
+	var b = 256;
+	while(l>-1){
+		i += arr[l]*b;
+		l--;
+		b *= 256;
+		}
+	return i;
+	}
+exports.intToBuffer = function (integer,bytesa){
+	var hex = intToHex(integer,bytesa);
+	var bb = hexToBytes(hex);
+	return new Buffer(bb);
+	}
+
+
+String.prototype.lpad = function(l,ww){
+var w = ww || " ";
+var s = this;
+while(s.length<l){
+	s = w + s;
+	}
+return s;
+}
+String.prototype.rpad = function(l,ww){
+	var w = ww || " ";
+	var s = this;
+	while(s.length<l){
+		s = s+w;
+		}
+	return s;
+	}
+
+
+
+/*
+
+
+function hexdump(buf,showascii,perline,space,padit,linenums,showtype){
+	var showtype = showtype || false;
+		var s = "";
+		if(showtype){
+			s += "type: "+typeof(buf)+" "+((buf instanceof Buffer))+"\n";
+		}
+	if(typeof(buf) !== "object"){
+		buf = new Buffer(buf);
+		}
+
+	var usebuf;
+	var perline = (perline===0||perline) ? perline : 32;
+	var space = (space===0||space) ? space : 8;
+	var showascii = showascii || false;
+	var linenums = linenums || false;
+	if(perline === 0){
+		perline = buf.length;
+		}
+	usebuf = buf;
+	if(padit){
+		var shouldbelength = Math.ceil(buf.length/perline)*perline;
+		var nbuf = new Buffer(shouldbelength);
+			nbuf.fill(0);
+			buf.copy(nbuf,0,0,buf.length);
+			usebuf = nbuf;
+		}
+
+	var tl = Math.ceil(buf.length/perline);
+
+
+
+	for(var i=0;i<tl;i++){
+		var mx = (i*perline)+perline;
+			if(mx > usebuf.length){
+				mx = usebuf.length;
+			}
+			if(linenums){
+				s += intToHex(i*perline,3)+" ";
+
+				}
+			var a = "";
+			var t = usebuf.slice(i*perline,mx);
+			for(var y=0;y<t.length;y++){
+				s += int2hex(t[y]);
+					if((t[y] > 31) && (t[y] < 127 || t[y] > 127) && (t[y] !== 129 && t[y] !== 143 && t[y] !== 144 && t[y] !== 157  && t[y] !== 160 && t[y] !== 173 ) ){
+						a += String.fromCharCode(t[y]);
+					}else{
+						a += ".";
+					}
+
+				if(y % space === (space-1)){
+					s += " ";
+					a += " ";
+					}
+
+				}
+
+				if(showascii){
+					s += " | " +a;
+				}
+				if(tl>1){
+					s += "\n";
+
+					}
+
+		}
+
+return s;
+
+}
+
+
+
+*/

+ 1118 - 0
buffer.js

@@ -0,0 +1,1118 @@
+/*!
+ * The buffer module from node.js, for the browser.
+ *
+ * @author   Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
+ * @license  MIT
+ */
+
+var base64 = require('base64-js')
+var ieee754 = require('ieee754')
+
+exports.Buffer = Buffer
+exports.SlowBuffer = Buffer
+exports.INSPECT_MAX_BYTES = 50
+Buffer.poolSize = 8192
+
+/**
+ * If `Buffer._useTypedArrays`:
+ *   === true    Use Uint8Array implementation (fastest)
+ *   === false   Use Object implementation (compatible down to IE6)
+ */
+Buffer._useTypedArrays = false; (function () {
+  // Detect if browser supports Typed Arrays. Supported browsers are IE 10+, Firefox 4+,
+  // Chrome 7+, Safari 5.1+, Opera 11.6+, iOS 4.2+. If the browser does not support adding
+  // properties to `Uint8Array` instances, then that's the same as no `Uint8Array` support
+  // because we need to be able to add all the node Buffer API methods. This is an issue
+  // in Firefox 4-29. Now fixed: https://bugzilla.mozilla.org/show_bug.cgi?id=695438
+  try {
+    var buf = new ArrayBuffer(0)
+    var arr = new Uint8Array(buf)
+    arr.foo = function () { return 42 }
+    return 42 === arr.foo() &&
+        typeof arr.subarray === 'function' // Chrome 9-10 lack `subarray`
+  } catch (e) {
+    return false
+  }
+})()
+
+/**
+ * Class: Buffer
+ * =============
+ *
+ * The Buffer constructor returns instances of `Uint8Array` that are augmented
+ * with function properties for all the node `Buffer` API functions. We use
+ * `Uint8Array` so that square bracket notation works as expected -- it returns
+ * a single octet.
+ *
+ * By augmenting the instances, we can avoid modifying the `Uint8Array`
+ * prototype.
+ */
+function Buffer (subject, encoding, noZero) {
+  if (!(this instanceof Buffer))
+    return new Buffer(subject, encoding, noZero)
+
+  var type = typeof subject
+
+  // Workaround: node's base64 implementation allows for non-padded strings
+  // while base64-js does not.
+  if (encoding === 'base64' && type === 'string') {
+    subject = stringtrim(subject)
+    while (subject.length % 4 !== 0) {
+      subject = subject + '='
+    }
+  }
+
+  // Find the length
+  var length
+  if (type === 'number')
+    length = coerce(subject)
+  else if (type === 'string')
+    length = Buffer.byteLength(subject, encoding)
+  else if (type === 'object')
+    length = coerce(subject.length) // assume that object is array-like
+  else
+    throw new Error('First argument needs to be a number, array or string.')
+
+  var buf
+  if (Buffer._useTypedArrays) {
+    // Preferred: Return an augmented `Uint8Array` instance for best performance
+    buf = Buffer._augment(new Uint8Array(length))
+  } else {
+    // Fallback: Return THIS instance of Buffer (created by `new`)
+    buf = this
+    buf.length = length
+    buf._isBuffer = true
+  }
+
+  var i
+  if (Buffer._useTypedArrays && typeof subject.byteLength === 'number') {
+    // Speed optimization -- use set if we're copying from a typed array
+    buf._set(subject)
+  } else if (isArrayish(subject)) {
+    // Treat array-ish objects as a byte array
+    for (i = 0; i < length; i++) {
+      if (Buffer.isBuffer(subject))
+        buf[i] = subject.readUInt8(i)
+      else
+        buf[i] = subject[i]
+    }
+  } else if (type === 'string') {
+    buf.write(subject, 0, encoding)
+  } else if (type === 'number' && !Buffer._useTypedArrays && !noZero) {
+    for (i = 0; i < length; i++) {
+      buf[i] = 0
+    }
+  }
+
+  return buf
+}
+
+// STATIC METHODS
+// ==============
+
+Buffer.isEncoding = function (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.isBuffer = function (b) {
+  return !!(b !== null && b !== undefined && b._isBuffer)
+}
+
+Buffer.byteLength = function (str, encoding) {
+  var ret
+  str = str + ''
+  switch (encoding || 'utf8') {
+    case 'hex':
+      ret = str.length / 2
+      break
+    case 'utf8':
+    case 'utf-8':
+      ret = utf8ToBytes(str).length
+      break
+    case 'ascii':
+    case 'binary':
+    case 'raw':
+      ret = str.length
+      break
+    case 'base64':
+      ret = base64ToBytes(str).length
+      break
+    case 'ucs2':
+    case 'ucs-2':
+    case 'utf16le':
+    case 'utf-16le':
+      ret = str.length * 2
+      break
+    default:
+      throw new Error('Unknown encoding')
+  }
+  return ret
+}
+
+Buffer.concat = function (list, totalLength) {
+  assert(isArray(list), 'Usage: Buffer.concat(list, [totalLength])\n' +
+      'list should be an Array.')
+
+  if (list.length === 0) {
+    return new Buffer(0)
+  } else if (list.length === 1) {
+    return list[0]
+  }
+
+  var i
+  if (typeof totalLength !== 'number') {
+    totalLength = 0
+    for (i = 0; i < list.length; i++) {
+      totalLength += list[i].length
+    }
+  }
+
+  var buf = new Buffer(totalLength)
+  var pos = 0
+  for (i = 0; i < list.length; i++) {
+    var item = list[i]
+    item.copy(buf, pos)
+    pos += item.length
+  }
+  return buf
+}
+
+// BUFFER INSTANCE METHODS
+// =======================
+
+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
+  assert(strLen % 2 === 0, 'Invalid hex string')
+
+  if (length > strLen / 2) {
+    length = strLen / 2
+  }
+  for (var i = 0; i < length; i++) {
+    var byte = parseInt(string.substr(i * 2, 2), 16)
+    assert(!isNaN(byte), 'Invalid hex string')
+    buf[offset + i] = byte
+  }
+  Buffer._charsWritten = i * 2
+  return i
+}
+
+function _utf8Write (buf, string, offset, length) {
+  var charsWritten = Buffer._charsWritten =
+    blitBuffer(utf8ToBytes(string), buf, offset, length)
+  return charsWritten
+}
+
+function _asciiWrite (buf, string, offset, length) {
+  var charsWritten = Buffer._charsWritten =
+    blitBuffer(asciiToBytes(string), buf, offset, length)
+  return charsWritten
+}
+
+function _binaryWrite (buf, string, offset, length) {
+  return _asciiWrite(buf, string, offset, length)
+}
+
+function _base64Write (buf, string, offset, length) {
+  var charsWritten = Buffer._charsWritten =
+    blitBuffer(base64ToBytes(string), buf, offset, length)
+  return charsWritten
+}
+
+function _utf16leWrite (buf, string, offset, length) {
+  var charsWritten = Buffer._charsWritten =
+    blitBuffer(utf16leToBytes(string), buf, offset, length)
+  return charsWritten
+}
+
+Buffer.prototype.write = function (string, offset, length, encoding) {
+  // Support both (string, offset, length, encoding)
+  // and the legacy (string, encoding, offset, length)
+  if (isFinite(offset)) {
+    if (!isFinite(length)) {
+      encoding = length
+      length = undefined
+    }
+  } else {  // legacy
+    var swap = encoding
+    encoding = offset
+    offset = length
+    length = swap
+  }
+
+  offset = Number(offset) || 0
+  var remaining = this.length - offset
+  if (!length) {
+    length = remaining
+  } else {
+    length = Number(length)
+    if (length > remaining) {
+      length = remaining
+    }
+  }
+  encoding = String(encoding || 'utf8').toLowerCase()
+
+  var ret
+  switch (encoding) {
+    case 'hex':
+      ret = _hexWrite(this, string, offset, length)
+      break
+    case 'utf8':
+    case 'utf-8':
+      ret = _utf8Write(this, string, offset, length)
+      break
+    case 'ascii':
+      ret = _asciiWrite(this, string, offset, length)
+      break
+    case 'binary':
+      ret = _binaryWrite(this, string, offset, length)
+      break
+    case 'base64':
+      ret = _base64Write(this, string, offset, length)
+      break
+    case 'ucs2':
+    case 'ucs-2':
+    case 'utf16le':
+    case 'utf-16le':
+      ret = _utf16leWrite(this, string, offset, length)
+      break
+    default:
+      throw new Error('Unknown encoding')
+  }
+  return ret
+}
+
+Buffer.prototype.toString = function (encoding, start, end) {
+  var self = this
+
+  encoding = String(encoding || 'utf8').toLowerCase()
+  start = Number(start) || 0
+  end = (end !== undefined)
+    ? Number(end)
+    : end = self.length
+
+  // Fastpath empty strings
+  if (end === start)
+    return ''
+
+  var ret
+  switch (encoding) {
+    case 'hex':
+      ret = _hexSlice(self, start, end)
+      break
+    case 'utf8':
+    case 'utf-8':
+      ret = _utf8Slice(self, start, end)
+      break
+    case 'ascii':
+      ret = _asciiSlice(self, start, end)
+      break
+    case 'binary':
+      ret = _binarySlice(self, start, end)
+      break
+    case 'base64':
+      ret = _base64Slice(self, start, end)
+      break
+    case 'ucs2':
+    case 'ucs-2':
+    case 'utf16le':
+    case 'utf-16le':
+      ret = _utf16leSlice(self, start, end)
+      break
+    default:
+      throw new Error('Unknown encoding')
+  }
+  return ret
+}
+
+Buffer.prototype.toJSON = function () {
+  return {
+    type: 'Buffer',
+    data: Array.prototype.slice.call(this._arr || this, 0)
+  }
+}
+
+// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
+Buffer.prototype.copy = function (target, target_start, start, end) {
+  var source = this
+
+  if (!start) start = 0
+  if (!end && end !== 0) end = this.length
+  if (!target_start) target_start = 0
+
+  // Copy 0 bytes; we're done
+  if (end === start) return
+  if (target.length === 0 || source.length === 0) return
+
+  // Fatal error conditions
+  assert(end >= start, 'sourceEnd < sourceStart')
+  assert(target_start >= 0 && target_start < target.length,
+      'targetStart out of bounds')
+  assert(start >= 0 && start < source.length, 'sourceStart out of bounds')
+  assert(end >= 0 && end <= source.length, 'sourceEnd out of bounds')
+
+  // Are we oob?
+  if (end > this.length)
+    end = this.length
+  if (target.length - target_start < end - start)
+    end = target.length - target_start + start
+
+  var len = end - start
+
+  if (len < 100 || !Buffer._useTypedArrays) {
+    for (var i = 0; i < len; i++)
+      target[i + target_start] = this[i + start]
+  } else {
+    target._set(this.subarray(start, start + len), target_start)
+  }
+}
+
+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) {
+  var res = ''
+  var tmp = ''
+  end = Math.min(buf.length, end)
+
+  for (var i = start; i < end; i++) {
+    if (buf[i] <= 0x7F) {
+      res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i])
+      tmp = ''
+    } else {
+      tmp += '%' + buf[i].toString(16)
+    }
+  }
+
+  return res + decodeUtf8Char(tmp)
+}
+
+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])
+  return ret
+}
+
+function _binarySlice (buf, start, end) {
+  return _asciiSlice(buf, start, end)
+}
+
+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 (start, end) {
+  var len = this.length
+  start = clamp(start, len, 0)
+  end = clamp(end, len, len)
+
+  if (Buffer._useTypedArrays) {
+    return Buffer._augment(this.subarray(start, end))
+  } else {
+    var sliceLen = end - start
+    var newBuf = new Buffer(sliceLen, undefined, true)
+    for (var i = 0; i < sliceLen; i++) {
+      newBuf[i] = this[i + start]
+    }
+    return newBuf
+  }
+}
+
+// `get` will be removed in Node 0.13+
+Buffer.prototype.get = function (offset) {
+  console.log('.get() is deprecated. Access using array indexes instead.')
+  return this.readUInt8(offset)
+}
+
+// `set` will be removed in Node 0.13+
+Buffer.prototype.set = function (v, offset) {
+  console.log('.set() is deprecated. Access using array indexes instead.')
+  return this.writeUInt8(v, offset)
+}
+
+Buffer.prototype.readUInt8 = function (offset, noAssert) {
+  if (!noAssert) {
+    assert(offset !== undefined && offset !== null, 'missing offset')
+    assert(offset < this.length, 'Trying to read beyond buffer length')
+  }
+
+  if (offset >= this.length)
+    return
+
+  return this[offset]
+}
+
+function _readUInt16 (buf, offset, littleEndian, noAssert) {
+  if (!noAssert) {
+    assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+    assert(offset !== undefined && offset !== null, 'missing offset')
+    assert(offset + 1 < buf.length, 'Trying to read beyond buffer length')
+  }
+
+  var len = buf.length
+  if (offset >= len)
+    return
+
+  var val
+  if (littleEndian) {
+    val = buf[offset]
+    if (offset + 1 < len)
+      val |= buf[offset + 1] << 8
+  } else {
+    val = buf[offset] << 8
+    if (offset + 1 < len)
+      val |= buf[offset + 1]
+  }
+  return val
+}
+
+Buffer.prototype.readUInt16LE = function (offset, noAssert) {
+  return _readUInt16(this, offset, true, noAssert)
+}
+
+Buffer.prototype.readUInt16BE = function (offset, noAssert) {
+  return _readUInt16(this, offset, false, noAssert)
+}
+
+function _readUInt32 (buf, offset, littleEndian, noAssert) {
+  if (!noAssert) {
+    assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+    assert(offset !== undefined && offset !== null, 'missing offset')
+    assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
+  }
+
+  var len = buf.length
+  if (offset >= len)
+    return
+
+  var val
+  if (littleEndian) {
+    if (offset + 2 < len)
+      val = buf[offset + 2] << 16
+    if (offset + 1 < len)
+      val |= buf[offset + 1] << 8
+    val |= buf[offset]
+    if (offset + 3 < len)
+      val = val + (buf[offset + 3] << 24 >>> 0)
+  } else {
+    if (offset + 1 < len)
+      val = buf[offset + 1] << 16
+    if (offset + 2 < len)
+      val |= buf[offset + 2] << 8
+    if (offset + 3 < len)
+      val |= buf[offset + 3]
+    val = val + (buf[offset] << 24 >>> 0)
+  }
+  return val
+}
+
+Buffer.prototype.readUInt32LE = function (offset, noAssert) {
+  return _readUInt32(this, offset, true, noAssert)
+}
+
+Buffer.prototype.readUInt32BE = function (offset, noAssert) {
+  return _readUInt32(this, offset, false, noAssert)
+}
+
+Buffer.prototype.readInt8 = function (offset, noAssert) {
+  if (!noAssert) {
+    assert(offset !== undefined && offset !== null,
+        'missing offset')
+    assert(offset < this.length, 'Trying to read beyond buffer length')
+  }
+
+  if (offset >= this.length)
+    return
+
+  var neg = this[offset] & 0x80
+  if (neg)
+    return (0xff - this[offset] + 1) * -1
+  else
+    return this[offset]
+}
+
+function _readInt16 (buf, offset, littleEndian, noAssert) {
+  if (!noAssert) {
+    assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+    assert(offset !== undefined && offset !== null, 'missing offset')
+    assert(offset + 1 < buf.length, 'Trying to read beyond buffer length')
+  }
+
+  var len = buf.length
+  if (offset >= len)
+    return
+
+  var val = _readUInt16(buf, offset, littleEndian, true)
+  var neg = val & 0x8000
+  if (neg)
+    return (0xffff - val + 1) * -1
+  else
+    return val
+}
+
+Buffer.prototype.readInt16LE = function (offset, noAssert) {
+  return _readInt16(this, offset, true, noAssert)
+}
+
+Buffer.prototype.readInt16BE = function (offset, noAssert) {
+  return _readInt16(this, offset, false, noAssert)
+}
+
+function _readInt32 (buf, offset, littleEndian, noAssert) {
+  if (!noAssert) {
+    assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+    assert(offset !== undefined && offset !== null, 'missing offset')
+    assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
+  }
+
+  var len = buf.length
+  if (offset >= len)
+    return
+
+  var val = _readUInt32(buf, offset, littleEndian, true)
+  var neg = val & 0x80000000
+  if (neg)
+    return (0xffffffff - val + 1) * -1
+  else
+    return val
+}
+
+Buffer.prototype.readInt32LE = function (offset, noAssert) {
+  return _readInt32(this, offset, true, noAssert)
+}
+
+Buffer.prototype.readInt32BE = function (offset, noAssert) {
+  return _readInt32(this, offset, false, noAssert)
+}
+
+function _readFloat (buf, offset, littleEndian, noAssert) {
+  if (!noAssert) {
+    assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+    assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
+  }
+
+  return ieee754.read(buf, offset, littleEndian, 23, 4)
+}
+
+Buffer.prototype.readFloatLE = function (offset, noAssert) {
+  return _readFloat(this, offset, true, noAssert)
+}
+
+Buffer.prototype.readFloatBE = function (offset, noAssert) {
+  return _readFloat(this, offset, false, noAssert)
+}
+
+function _readDouble (buf, offset, littleEndian, noAssert) {
+  if (!noAssert) {
+    assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+    assert(offset + 7 < buf.length, 'Trying to read beyond buffer length')
+  }
+
+  return ieee754.read(buf, offset, littleEndian, 52, 8)
+}
+
+Buffer.prototype.readDoubleLE = function (offset, noAssert) {
+  return _readDouble(this, offset, true, noAssert)
+}
+
+Buffer.prototype.readDoubleBE = function (offset, noAssert) {
+  return _readDouble(this, offset, false, noAssert)
+}
+
+Buffer.prototype.writeUInt8 = function (value, offset, noAssert) {
+  if (!noAssert) {
+    assert(value !== undefined && value !== null, 'missing value')
+    assert(offset !== undefined && offset !== null, 'missing offset')
+    assert(offset < this.length, 'trying to write beyond buffer length')
+    verifuint(value, 0xff)
+  }
+
+  if (offset >= this.length) return
+
+  this[offset] = value
+}
+
+function _writeUInt16 (buf, value, offset, littleEndian, noAssert) {
+  if (!noAssert) {
+    assert(value !== undefined && value !== null, 'missing value')
+    assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+    assert(offset !== undefined && offset !== null, 'missing offset')
+    assert(offset + 1 < buf.length, 'trying to write beyond buffer length')
+    verifuint(value, 0xffff)
+  }
+
+  var len = buf.length
+  if (offset >= len)
+    return
+
+  for (var i = 0, j = Math.min(len - offset, 2); i < j; i++) {
+    buf[offset + i] =
+        (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
+            (littleEndian ? i : 1 - i) * 8
+  }
+}
+
+Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) {
+  _writeUInt16(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) {
+  _writeUInt16(this, value, offset, false, noAssert)
+}
+
+function _writeUInt32 (buf, value, offset, littleEndian, noAssert) {
+  if (!noAssert) {
+    assert(value !== undefined && value !== null, 'missing value')
+    assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+    assert(offset !== undefined && offset !== null, 'missing offset')
+    assert(offset + 3 < buf.length, 'trying to write beyond buffer length')
+    verifuint(value, 0xffffffff)
+  }
+
+  var len = buf.length
+  if (offset >= len)
+    return
+
+  for (var i = 0, j = Math.min(len - offset, 4); i < j; i++) {
+    buf[offset + i] =
+        (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
+  }
+}
+
+Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) {
+  _writeUInt32(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) {
+  _writeUInt32(this, value, offset, false, noAssert)
+}
+
+Buffer.prototype.writeInt8 = function (value, offset, noAssert) {
+  if (!noAssert) {
+    assert(value !== undefined && value !== null, 'missing value')
+    assert(offset !== undefined && offset !== null, 'missing offset')
+    assert(offset < this.length, 'Trying to write beyond buffer length')
+    verifsint(value, 0x7f, -0x80)
+  }
+
+  if (offset >= this.length)
+    return
+
+  if (value >= 0)
+    this.writeUInt8(value, offset, noAssert)
+  else
+    this.writeUInt8(0xff + value + 1, offset, noAssert)
+}
+
+function _writeInt16 (buf, value, offset, littleEndian, noAssert) {
+  if (!noAssert) {
+    assert(value !== undefined && value !== null, 'missing value')
+    assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+    assert(offset !== undefined && offset !== null, 'missing offset')
+    assert(offset + 1 < buf.length, 'Trying to write beyond buffer length')
+    verifsint(value, 0x7fff, -0x8000)
+  }
+
+  var len = buf.length
+  if (offset >= len)
+    return
+
+  if (value >= 0)
+    _writeUInt16(buf, value, offset, littleEndian, noAssert)
+  else
+    _writeUInt16(buf, 0xffff + value + 1, offset, littleEndian, noAssert)
+}
+
+Buffer.prototype.writeInt16LE = function (value, offset, noAssert) {
+  _writeInt16(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeInt16BE = function (value, offset, noAssert) {
+  _writeInt16(this, value, offset, false, noAssert)
+}
+
+function _writeInt32 (buf, value, offset, littleEndian, noAssert) {
+  if (!noAssert) {
+    assert(value !== undefined && value !== null, 'missing value')
+    assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+    assert(offset !== undefined && offset !== null, 'missing offset')
+    assert(offset + 3 < buf.length, 'Trying to write beyond buffer length')
+    verifsint(value, 0x7fffffff, -0x80000000)
+  }
+
+  var len = buf.length
+  if (offset >= len)
+    return
+
+  if (value >= 0)
+    _writeUInt32(buf, value, offset, littleEndian, noAssert)
+  else
+    _writeUInt32(buf, 0xffffffff + value + 1, offset, littleEndian, noAssert)
+}
+
+Buffer.prototype.writeInt32LE = function (value, offset, noAssert) {
+  _writeInt32(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeInt32BE = function (value, offset, noAssert) {
+  _writeInt32(this, value, offset, false, noAssert)
+}
+
+function _writeFloat (buf, value, offset, littleEndian, noAssert) {
+  if (!noAssert) {
+    assert(value !== undefined && value !== null, 'missing value')
+    assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+    assert(offset !== undefined && offset !== null, 'missing offset')
+    assert(offset + 3 < buf.length, 'Trying to write beyond buffer length')
+    verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38)
+  }
+
+  var len = buf.length
+  if (offset >= len)
+    return
+
+  ieee754.write(buf, value, offset, littleEndian, 23, 4)
+}
+
+Buffer.prototype.writeFloatLE = function (value, offset, noAssert) {
+  _writeFloat(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeFloatBE = function (value, offset, noAssert) {
+  _writeFloat(this, value, offset, false, noAssert)
+}
+
+function _writeDouble (buf, value, offset, littleEndian, noAssert) {
+  if (!noAssert) {
+    assert(value !== undefined && value !== null, 'missing value')
+    assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+    assert(offset !== undefined && offset !== null, 'missing offset')
+    assert(offset + 7 < buf.length,
+        'Trying to write beyond buffer length')
+    verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308)
+  }
+
+  var len = buf.length
+  if (offset >= len)
+    return
+
+  ieee754.write(buf, value, offset, littleEndian, 52, 8)
+}
+
+Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) {
+  _writeDouble(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) {
+  _writeDouble(this, value, offset, false, noAssert)
+}
+
+// fill(value, start=0, end=buffer.length)
+Buffer.prototype.fill = function (value, start, end) {
+  if (!value) value = 0
+  if (!start) start = 0
+  if (!end) end = this.length
+
+  if (typeof value === 'string') {
+    value = value.charCodeAt(0)
+  }
+
+  assert(typeof value === 'number' && !isNaN(value), 'value is not a number')
+  assert(end >= start, 'end < start')
+
+  // Fill 0 bytes; we're done
+  if (end === start) return
+  if (this.length === 0) return
+
+  assert(start >= 0 && start < this.length, 'start out of bounds')
+  assert(end >= 0 && end <= this.length, 'end out of bounds')
+
+  for (var i = start; i < end; i++) {
+    this[i] = value
+  }
+}
+
+Buffer.prototype.inspect = function () {
+  var out = []
+  var len = this.length
+  for (var i = 0; i < len; i++) {
+    out[i] = toHex(this[i])
+    if (i === exports.INSPECT_MAX_BYTES) {
+      out[i + 1] = '...'
+      break
+    }
+  }
+  return '<Buffer ' + out.join(' ') + '>'
+}
+
+/**
+ * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
+ * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
+ */
+Buffer.prototype.toArrayBuffer = function () {
+  if (typeof Uint8Array !== 'undefined') {
+    if (Buffer._useTypedArrays) {
+      return (new Buffer(this)).buffer
+    } else {
+      var buf = new Uint8Array(this.length)
+      for (var i = 0, len = buf.length; i < len; i += 1)
+        buf[i] = this[i]
+      return buf.buffer
+    }
+  } else {
+    throw new Error('Buffer.toArrayBuffer not supported in this browser')
+  }
+}
+
+require("./extend")(Buffer.prototype);
+
+
+
+
+
+
+
+// HELPER FUNCTIONS
+// ================
+
+function stringtrim (str) {
+  if (str.trim) return str.trim()
+  return str.replace(/^\s+|\s+$/g, '')
+}
+
+var BP = Buffer.prototype
+
+/**
+ * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
+ */
+Buffer._augment = function (arr) {
+  arr._isBuffer = true
+
+  // save reference to original Uint8Array get/set methods before overwriting
+  arr._get = arr.get
+  arr._set = arr.set
+
+  // deprecated, will be removed in node 0.13+
+  arr.get = BP.get
+  arr.set = BP.set
+
+  arr.write = BP.write
+  arr.toString = BP.toString
+  arr.toLocaleString = BP.toString
+  arr.toJSON = BP.toJSON
+  arr.copy = BP.copy
+  arr.slice = BP.slice
+  arr.readUInt8 = BP.readUInt8
+  arr.readUInt16LE = BP.readUInt16LE
+  arr.readUInt16BE = BP.readUInt16BE
+  arr.readUInt32LE = BP.readUInt32LE
+  arr.readUInt32BE = BP.readUInt32BE
+  arr.readInt8 = BP.readInt8
+  arr.readInt16LE = BP.readInt16LE
+  arr.readInt16BE = BP.readInt16BE
+  arr.readInt32LE = BP.readInt32LE
+  arr.readInt32BE = BP.readInt32BE
+  arr.readFloatLE = BP.readFloatLE
+  arr.readFloatBE = BP.readFloatBE
+  arr.readDoubleLE = BP.readDoubleLE
+  arr.readDoubleBE = BP.readDoubleBE
+  arr.writeUInt8 = BP.writeUInt8
+  arr.writeUInt16LE = BP.writeUInt16LE
+  arr.writeUInt16BE = BP.writeUInt16BE
+  arr.writeUInt32LE = BP.writeUInt32LE
+  arr.writeUInt32BE = BP.writeUInt32BE
+  arr.writeInt8 = BP.writeInt8
+  arr.writeInt16LE = BP.writeInt16LE
+  arr.writeInt16BE = BP.writeInt16BE
+  arr.writeInt32LE = BP.writeInt32LE
+  arr.writeInt32BE = BP.writeInt32BE
+  arr.writeFloatLE = BP.writeFloatLE
+  arr.writeFloatBE = BP.writeFloatBE
+  arr.writeDoubleLE = BP.writeDoubleLE
+  arr.writeDoubleBE = BP.writeDoubleBE
+  arr.fill = BP.fill
+  arr.inspect = BP.inspect
+  arr.toArrayBuffer = BP.toArrayBuffer
+
+
+  return arr
+}
+
+// slice(start, end)
+function clamp (index, len, defaultValue) {
+  if (typeof index !== 'number') return defaultValue
+  index = ~~index;  // Coerce to integer.
+  if (index >= len) return len
+  if (index >= 0) return index
+  index += len
+  if (index >= 0) return index
+  return 0
+}
+
+function coerce (length) {
+  // Coerce length to a number (possibly NaN), round up
+  // in case it's fractional (e.g. 123.456) then do a
+  // double negate to coerce a NaN to 0. Easy, right?
+  length = ~~Math.ceil(+length)
+  return length < 0 ? 0 : length
+}
+
+function isArray (subject) {
+  return (Array.isArray || function (subject) {
+    return Object.prototype.toString.call(subject) === '[object Array]'
+  })(subject)
+}
+
+function isArrayish (subject) {
+  return isArray(subject) || Buffer.isBuffer(subject) ||
+      subject && typeof subject === 'object' &&
+      typeof subject.length === 'number'
+}
+
+function toHex (n) {
+  if (n < 16) return '0' + n.toString(16)
+  return n.toString(16)
+}
+
+function utf8ToBytes (str) {
+  var byteArray = []
+  for (var i = 0; i < str.length; i++) {
+    var b = str.charCodeAt(i)
+    if (b <= 0x7F)
+      byteArray.push(str.charCodeAt(i))
+    else {
+      var start = i
+      if (b >= 0xD800 && b <= 0xDFFF) i++
+      var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%')
+      for (var j = 0; j < h.length; j++)
+        byteArray.push(parseInt(h[j], 16))
+    }
+  }
+  return byteArray
+}
+
+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) {
+  var c, hi, lo
+  var byteArray = []
+  for (var i = 0; i < str.length; i++) {
+    c = str.charCodeAt(i)
+    hi = c >> 8
+    lo = c % 256
+    byteArray.push(lo)
+    byteArray.push(hi)
+  }
+
+  return byteArray
+}
+
+function base64ToBytes (str) {
+  return base64.toByteArray(str)
+}
+
+function blitBuffer (src, dst, offset, length) {
+  var pos
+  for (var i = 0; i < length; i++) {
+    if ((i + offset >= dst.length) || (i >= src.length))
+      break
+    dst[i + offset] = src[i]
+  }
+  return i
+}
+
+function decodeUtf8Char (str) {
+  try {
+    return decodeURIComponent(str)
+  } catch (err) {
+    return String.fromCharCode(0xFFFD) // UTF 8 invalid char
+  }
+}
+
+/*
+ * We have to make sure that the value is a valid integer. This means that it
+ * is non-negative. It has no fractional component and that it does not
+ * exceed the maximum allowed value.
+ */
+function verifuint (value, max) {
+  assert(typeof value === 'number', 'cannot write a non-number as a number')
+  assert(value >= 0, 'specified a negative value for writing an unsigned value')
+  assert(value <= max, 'value is larger than maximum value for type')
+  assert(Math.floor(value) === value, 'value has a fractional component')
+}
+
+function verifsint (value, max, min) {
+  assert(typeof value === 'number', 'cannot write a non-number as a number')
+  assert(value <= max, 'value larger than maximum allowed value')
+  assert(value >= min, 'value smaller than minimum allowed value')
+  assert(Math.floor(value) === value, 'value has a fractional component')
+}
+
+function verifIEEE754 (value, max, min) {
+  assert(typeof value === 'number', 'cannot write a non-number as a number')
+  assert(value <= max, 'value larger than maximum allowed value')
+  assert(value >= min, 'value smaller than minimum allowed value')
+}
+
+function assert (test, message) {
+  if (!test) throw new Error(message || 'Failed assertion')
+}

+ 1323 - 0
bundle.js

@@ -0,0 +1,1323 @@
+require=(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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.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})({"Focm2+":[function(require,module,exports){
+/*!
+ * The buffer module from node.js, for the browser.
+ *
+ * @author   Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
+ * @license  MIT
+ */
+
+var base64 = require('base64-js')
+var ieee754 = require('ieee754')
+
+exports.Buffer = Buffer
+exports.SlowBuffer = Buffer
+exports.INSPECT_MAX_BYTES = 50
+Buffer.poolSize = 8192
+
+/**
+ * If `Buffer._useTypedArrays`:
+ *   === true    Use Uint8Array implementation (fastest)
+ *   === false   Use Object implementation (compatible down to IE6)
+ */
+Buffer._useTypedArrays = (function () {
+  // Detect if browser supports Typed Arrays. Supported browsers are IE 10+, Firefox 4+,
+  // Chrome 7+, Safari 5.1+, Opera 11.6+, iOS 4.2+. If the browser does not support adding
+  // properties to `Uint8Array` instances, then that's the same as no `Uint8Array` support
+  // because we need to be able to add all the node Buffer API methods. This is an issue
+  // in Firefox 4-29. Now fixed: https://bugzilla.mozilla.org/show_bug.cgi?id=695438
+  try {
+    var buf = new ArrayBuffer(0)
+    var arr = new Uint8Array(buf)
+    arr.foo = function () { return 42 }
+    return 42 === arr.foo() &&
+        typeof arr.subarray === 'function' // Chrome 9-10 lack `subarray`
+  } catch (e) {
+    return false
+  }
+})()
+
+/**
+ * Class: Buffer
+ * =============
+ *
+ * The Buffer constructor returns instances of `Uint8Array` that are augmented
+ * with function properties for all the node `Buffer` API functions. We use
+ * `Uint8Array` so that square bracket notation works as expected -- it returns
+ * a single octet.
+ *
+ * By augmenting the instances, we can avoid modifying the `Uint8Array`
+ * prototype.
+ */
+function Buffer (subject, encoding, noZero) {
+  if (!(this instanceof Buffer))
+    return new Buffer(subject, encoding, noZero)
+
+  var type = typeof subject
+
+  // Workaround: node's base64 implementation allows for non-padded strings
+  // while base64-js does not.
+  if (encoding === 'base64' && type === 'string') {
+    subject = stringtrim(subject)
+    while (subject.length % 4 !== 0) {
+      subject = subject + '='
+    }
+  }
+
+  // Find the length
+  var length
+  if (type === 'number')
+    length = coerce(subject)
+  else if (type === 'string')
+    length = Buffer.byteLength(subject, encoding)
+  else if (type === 'object')
+    length = coerce(subject.length) // assume that object is array-like
+  else
+    throw new Error('First argument needs to be a number, array or string.')
+
+  var buf
+  if (Buffer._useTypedArrays) {
+    // Preferred: Return an augmented `Uint8Array` instance for best performance
+    buf = Buffer._augment(new Uint8Array(length))
+  } else {
+    // Fallback: Return THIS instance of Buffer (created by `new`)
+    buf = this
+    buf.length = length
+    buf._isBuffer = true
+  }
+
+  var i
+  if (Buffer._useTypedArrays && typeof subject.byteLength === 'number') {
+    // Speed optimization -- use set if we're copying from a typed array
+    buf._set(subject)
+  } else if (isArrayish(subject)) {
+    // Treat array-ish objects as a byte array
+    for (i = 0; i < length; i++) {
+      if (Buffer.isBuffer(subject))
+        buf[i] = subject.readUInt8(i)
+      else
+        buf[i] = subject[i]
+    }
+  } else if (type === 'string') {
+    buf.write(subject, 0, encoding)
+  } else if (type === 'number' && !Buffer._useTypedArrays && !noZero) {
+    for (i = 0; i < length; i++) {
+      buf[i] = 0
+    }
+  }
+
+  return buf
+}
+
+// STATIC METHODS
+// ==============
+
+Buffer.isEncoding = function (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.isBuffer = function (b) {
+  return !!(b !== null && b !== undefined && b._isBuffer)
+}
+
+Buffer.byteLength = function (str, encoding) {
+  var ret
+  str = str + ''
+  switch (encoding || 'utf8') {
+    case 'hex':
+      ret = str.length / 2
+      break
+    case 'utf8':
+    case 'utf-8':
+      ret = utf8ToBytes(str).length
+      break
+    case 'ascii':
+    case 'binary':
+    case 'raw':
+      ret = str.length
+      break
+    case 'base64':
+      ret = base64ToBytes(str).length
+      break
+    case 'ucs2':
+    case 'ucs-2':
+    case 'utf16le':
+    case 'utf-16le':
+      ret = str.length * 2
+      break
+    default:
+      throw new Error('Unknown encoding')
+  }
+  return ret
+}
+
+Buffer.concat = function (list, totalLength) {
+  assert(isArray(list), 'Usage: Buffer.concat(list, [totalLength])\n' +
+      'list should be an Array.')
+
+  if (list.length === 0) {
+    return new Buffer(0)
+  } else if (list.length === 1) {
+    return list[0]
+  }
+
+  var i
+  if (typeof totalLength !== 'number') {
+    totalLength = 0
+    for (i = 0; i < list.length; i++) {
+      totalLength += list[i].length
+    }
+  }
+
+  var buf = new Buffer(totalLength)
+  var pos = 0
+  for (i = 0; i < list.length; i++) {
+    var item = list[i]
+    item.copy(buf, pos)
+    pos += item.length
+  }
+  return buf
+}
+
+// BUFFER INSTANCE METHODS
+// =======================
+
+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
+  assert(strLen % 2 === 0, 'Invalid hex string')
+
+  if (length > strLen / 2) {
+    length = strLen / 2
+  }
+  for (var i = 0; i < length; i++) {
+    var byte = parseInt(string.substr(i * 2, 2), 16)
+    assert(!isNaN(byte), 'Invalid hex string')
+    buf[offset + i] = byte
+  }
+  Buffer._charsWritten = i * 2
+  return i
+}
+
+function _utf8Write (buf, string, offset, length) {
+  var charsWritten = Buffer._charsWritten =
+    blitBuffer(utf8ToBytes(string), buf, offset, length)
+  return charsWritten
+}
+
+function _asciiWrite (buf, string, offset, length) {
+  var charsWritten = Buffer._charsWritten =
+    blitBuffer(asciiToBytes(string), buf, offset, length)
+  return charsWritten
+}
+
+function _binaryWrite (buf, string, offset, length) {
+  return _asciiWrite(buf, string, offset, length)
+}
+
+function _base64Write (buf, string, offset, length) {
+  var charsWritten = Buffer._charsWritten =
+    blitBuffer(base64ToBytes(string), buf, offset, length)
+  return charsWritten
+}
+
+function _utf16leWrite (buf, string, offset, length) {
+  var charsWritten = Buffer._charsWritten =
+    blitBuffer(utf16leToBytes(string), buf, offset, length)
+  return charsWritten
+}
+
+Buffer.prototype.write = function (string, offset, length, encoding) {
+  // Support both (string, offset, length, encoding)
+  // and the legacy (string, encoding, offset, length)
+  if (isFinite(offset)) {
+    if (!isFinite(length)) {
+      encoding = length
+      length = undefined
+    }
+  } else {  // legacy
+    var swap = encoding
+    encoding = offset
+    offset = length
+    length = swap
+  }
+
+  offset = Number(offset) || 0
+  var remaining = this.length - offset
+  if (!length) {
+    length = remaining
+  } else {
+    length = Number(length)
+    if (length > remaining) {
+      length = remaining
+    }
+  }
+  encoding = String(encoding || 'utf8').toLowerCase()
+
+  var ret
+  switch (encoding) {
+    case 'hex':
+      ret = _hexWrite(this, string, offset, length)
+      break
+    case 'utf8':
+    case 'utf-8':
+      ret = _utf8Write(this, string, offset, length)
+      break
+    case 'ascii':
+      ret = _asciiWrite(this, string, offset, length)
+      break
+    case 'binary':
+      ret = _binaryWrite(this, string, offset, length)
+      break
+    case 'base64':
+      ret = _base64Write(this, string, offset, length)
+      break
+    case 'ucs2':
+    case 'ucs-2':
+    case 'utf16le':
+    case 'utf-16le':
+      ret = _utf16leWrite(this, string, offset, length)
+      break
+    default:
+      throw new Error('Unknown encoding')
+  }
+  return ret
+}
+
+Buffer.prototype.toString = function (encoding, start, end) {
+  var self = this
+
+  encoding = String(encoding || 'utf8').toLowerCase()
+  start = Number(start) || 0
+  end = (end !== undefined)
+    ? Number(end)
+    : end = self.length
+
+  // Fastpath empty strings
+  if (end === start)
+    return ''
+
+  var ret
+  switch (encoding) {
+    case 'hex':
+      ret = _hexSlice(self, start, end)
+      break
+    case 'utf8':
+    case 'utf-8':
+      ret = _utf8Slice(self, start, end)
+      break
+    case 'ascii':
+      ret = _asciiSlice(self, start, end)
+      break
+    case 'binary':
+      ret = _binarySlice(self, start, end)
+      break
+    case 'base64':
+      ret = _base64Slice(self, start, end)
+      break
+    case 'ucs2':
+    case 'ucs-2':
+    case 'utf16le':
+    case 'utf-16le':
+      ret = _utf16leSlice(self, start, end)
+      break
+    default:
+      throw new Error('Unknown encoding')
+  }
+  return ret
+}
+
+Buffer.prototype.toJSON = function () {
+  return {
+    type: 'Buffer',
+    data: Array.prototype.slice.call(this._arr || this, 0)
+  }
+}
+
+// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
+Buffer.prototype.copy = function (target, target_start, start, end) {
+  var source = this
+
+  if (!start) start = 0
+  if (!end && end !== 0) end = this.length
+  if (!target_start) target_start = 0
+
+  // Copy 0 bytes; we're done
+  if (end === start) return
+  if (target.length === 0 || source.length === 0) return
+
+  // Fatal error conditions
+  assert(end >= start, 'sourceEnd < sourceStart')
+  assert(target_start >= 0 && target_start < target.length,
+      'targetStart out of bounds')
+  assert(start >= 0 && start < source.length, 'sourceStart out of bounds')
+  assert(end >= 0 && end <= source.length, 'sourceEnd out of bounds')
+
+  // Are we oob?
+  if (end > this.length)
+    end = this.length
+  if (target.length - target_start < end - start)
+    end = target.length - target_start + start
+
+  var len = end - start
+
+  if (len < 100 || !Buffer._useTypedArrays) {
+    for (var i = 0; i < len; i++)
+      target[i + target_start] = this[i + start]
+  } else {
+    target._set(this.subarray(start, start + len), target_start)
+  }
+}
+
+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) {
+  var res = ''
+  var tmp = ''
+  end = Math.min(buf.length, end)
+
+  for (var i = start; i < end; i++) {
+    if (buf[i] <= 0x7F) {
+      res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i])
+      tmp = ''
+    } else {
+      tmp += '%' + buf[i].toString(16)
+    }
+  }
+
+  return res + decodeUtf8Char(tmp)
+}
+
+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])
+  return ret
+}
+
+function _binarySlice (buf, start, end) {
+  return _asciiSlice(buf, start, end)
+}
+
+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 (start, end) {
+  var len = this.length
+  start = clamp(start, len, 0)
+  end = clamp(end, len, len)
+
+  if (Buffer._useTypedArrays) {
+    return Buffer._augment(this.subarray(start, end))
+  } else {
+    var sliceLen = end - start
+    var newBuf = new Buffer(sliceLen, undefined, true)
+    for (var i = 0; i < sliceLen; i++) {
+      newBuf[i] = this[i + start]
+    }
+    return newBuf
+  }
+}
+
+// `get` will be removed in Node 0.13+
+Buffer.prototype.get = function (offset) {
+  console.log('.get() is deprecated. Access using array indexes instead.')
+  return this.readUInt8(offset)
+}
+
+// `set` will be removed in Node 0.13+
+Buffer.prototype.set = function (v, offset) {
+  console.log('.set() is deprecated. Access using array indexes instead.')
+  return this.writeUInt8(v, offset)
+}
+
+Buffer.prototype.readUInt8 = function (offset, noAssert) {
+  if (!noAssert) {
+    assert(offset !== undefined && offset !== null, 'missing offset')
+    assert(offset < this.length, 'Trying to read beyond buffer length')
+  }
+
+  if (offset >= this.length)
+    return
+
+  return this[offset]
+}
+
+function _readUInt16 (buf, offset, littleEndian, noAssert) {
+  if (!noAssert) {
+    assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+    assert(offset !== undefined && offset !== null, 'missing offset')
+    assert(offset + 1 < buf.length, 'Trying to read beyond buffer length')
+  }
+
+  var len = buf.length
+  if (offset >= len)
+    return
+
+  var val
+  if (littleEndian) {
+    val = buf[offset]
+    if (offset + 1 < len)
+      val |= buf[offset + 1] << 8
+  } else {
+    val = buf[offset] << 8
+    if (offset + 1 < len)
+      val |= buf[offset + 1]
+  }
+  return val
+}
+
+Buffer.prototype.readUInt16LE = function (offset, noAssert) {
+  return _readUInt16(this, offset, true, noAssert)
+}
+
+Buffer.prototype.readUInt16BE = function (offset, noAssert) {
+  return _readUInt16(this, offset, false, noAssert)
+}
+
+function _readUInt32 (buf, offset, littleEndian, noAssert) {
+  if (!noAssert) {
+    assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+    assert(offset !== undefined && offset !== null, 'missing offset')
+    assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
+  }
+
+  var len = buf.length
+  if (offset >= len)
+    return
+
+  var val
+  if (littleEndian) {
+    if (offset + 2 < len)
+      val = buf[offset + 2] << 16
+    if (offset + 1 < len)
+      val |= buf[offset + 1] << 8
+    val |= buf[offset]
+    if (offset + 3 < len)
+      val = val + (buf[offset + 3] << 24 >>> 0)
+  } else {
+    if (offset + 1 < len)
+      val = buf[offset + 1] << 16
+    if (offset + 2 < len)
+      val |= buf[offset + 2] << 8
+    if (offset + 3 < len)
+      val |= buf[offset + 3]
+    val = val + (buf[offset] << 24 >>> 0)
+  }
+  return val
+}
+
+Buffer.prototype.readUInt32LE = function (offset, noAssert) {
+  return _readUInt32(this, offset, true, noAssert)
+}
+
+Buffer.prototype.readUInt32BE = function (offset, noAssert) {
+  return _readUInt32(this, offset, false, noAssert)
+}
+
+Buffer.prototype.readInt8 = function (offset, noAssert) {
+  if (!noAssert) {
+    assert(offset !== undefined && offset !== null,
+        'missing offset')
+    assert(offset < this.length, 'Trying to read beyond buffer length')
+  }
+
+  if (offset >= this.length)
+    return
+
+  var neg = this[offset] & 0x80
+  if (neg)
+    return (0xff - this[offset] + 1) * -1
+  else
+    return this[offset]
+}
+
+function _readInt16 (buf, offset, littleEndian, noAssert) {
+  if (!noAssert) {
+    assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+    assert(offset !== undefined && offset !== null, 'missing offset')
+    assert(offset + 1 < buf.length, 'Trying to read beyond buffer length')
+  }
+
+  var len = buf.length
+  if (offset >= len)
+    return
+
+  var val = _readUInt16(buf, offset, littleEndian, true)
+  var neg = val & 0x8000
+  if (neg)
+    return (0xffff - val + 1) * -1
+  else
+    return val
+}
+
+Buffer.prototype.readInt16LE = function (offset, noAssert) {
+  return _readInt16(this, offset, true, noAssert)
+}
+
+Buffer.prototype.readInt16BE = function (offset, noAssert) {
+  return _readInt16(this, offset, false, noAssert)
+}
+
+function _readInt32 (buf, offset, littleEndian, noAssert) {
+  if (!noAssert) {
+    assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+    assert(offset !== undefined && offset !== null, 'missing offset')
+    assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
+  }
+
+  var len = buf.length
+  if (offset >= len)
+    return
+
+  var val = _readUInt32(buf, offset, littleEndian, true)
+  var neg = val & 0x80000000
+  if (neg)
+    return (0xffffffff - val + 1) * -1
+  else
+    return val
+}
+
+Buffer.prototype.readInt32LE = function (offset, noAssert) {
+  return _readInt32(this, offset, true, noAssert)
+}
+
+Buffer.prototype.readInt32BE = function (offset, noAssert) {
+  return _readInt32(this, offset, false, noAssert)
+}
+
+function _readFloat (buf, offset, littleEndian, noAssert) {
+  if (!noAssert) {
+    assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+    assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
+  }
+
+  return ieee754.read(buf, offset, littleEndian, 23, 4)
+}
+
+Buffer.prototype.readFloatLE = function (offset, noAssert) {
+  return _readFloat(this, offset, true, noAssert)
+}
+
+Buffer.prototype.readFloatBE = function (offset, noAssert) {
+  return _readFloat(this, offset, false, noAssert)
+}
+
+function _readDouble (buf, offset, littleEndian, noAssert) {
+  if (!noAssert) {
+    assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+    assert(offset + 7 < buf.length, 'Trying to read beyond buffer length')
+  }
+
+  return ieee754.read(buf, offset, littleEndian, 52, 8)
+}
+
+Buffer.prototype.readDoubleLE = function (offset, noAssert) {
+  return _readDouble(this, offset, true, noAssert)
+}
+
+Buffer.prototype.readDoubleBE = function (offset, noAssert) {
+  return _readDouble(this, offset, false, noAssert)
+}
+
+Buffer.prototype.writeUInt8 = function (value, offset, noAssert) {
+  if (!noAssert) {
+    assert(value !== undefined && value !== null, 'missing value')
+    assert(offset !== undefined && offset !== null, 'missing offset')
+    assert(offset < this.length, 'trying to write beyond buffer length')
+    verifuint(value, 0xff)
+  }
+
+  if (offset >= this.length) return
+
+  this[offset] = value
+}
+
+function _writeUInt16 (buf, value, offset, littleEndian, noAssert) {
+  if (!noAssert) {
+    assert(value !== undefined && value !== null, 'missing value')
+    assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+    assert(offset !== undefined && offset !== null, 'missing offset')
+    assert(offset + 1 < buf.length, 'trying to write beyond buffer length')
+    verifuint(value, 0xffff)
+  }
+
+  var len = buf.length
+  if (offset >= len)
+    return
+
+  for (var i = 0, j = Math.min(len - offset, 2); i < j; i++) {
+    buf[offset + i] =
+        (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
+            (littleEndian ? i : 1 - i) * 8
+  }
+}
+
+Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) {
+  _writeUInt16(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) {
+  _writeUInt16(this, value, offset, false, noAssert)
+}
+
+function _writeUInt32 (buf, value, offset, littleEndian, noAssert) {
+  if (!noAssert) {
+    assert(value !== undefined && value !== null, 'missing value')
+    assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+    assert(offset !== undefined && offset !== null, 'missing offset')
+    assert(offset + 3 < buf.length, 'trying to write beyond buffer length')
+    verifuint(value, 0xffffffff)
+  }
+
+  var len = buf.length
+  if (offset >= len)
+    return
+
+  for (var i = 0, j = Math.min(len - offset, 4); i < j; i++) {
+    buf[offset + i] =
+        (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
+  }
+}
+
+Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) {
+  _writeUInt32(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) {
+  _writeUInt32(this, value, offset, false, noAssert)
+}
+
+Buffer.prototype.writeInt8 = function (value, offset, noAssert) {
+  if (!noAssert) {
+    assert(value !== undefined && value !== null, 'missing value')
+    assert(offset !== undefined && offset !== null, 'missing offset')
+    assert(offset < this.length, 'Trying to write beyond buffer length')
+    verifsint(value, 0x7f, -0x80)
+  }
+
+  if (offset >= this.length)
+    return
+
+  if (value >= 0)
+    this.writeUInt8(value, offset, noAssert)
+  else
+    this.writeUInt8(0xff + value + 1, offset, noAssert)
+}
+
+function _writeInt16 (buf, value, offset, littleEndian, noAssert) {
+  if (!noAssert) {
+    assert(value !== undefined && value !== null, 'missing value')
+    assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+    assert(offset !== undefined && offset !== null, 'missing offset')
+    assert(offset + 1 < buf.length, 'Trying to write beyond buffer length')
+    verifsint(value, 0x7fff, -0x8000)
+  }
+
+  var len = buf.length
+  if (offset >= len)
+    return
+
+  if (value >= 0)
+    _writeUInt16(buf, value, offset, littleEndian, noAssert)
+  else
+    _writeUInt16(buf, 0xffff + value + 1, offset, littleEndian, noAssert)
+}
+
+Buffer.prototype.writeInt16LE = function (value, offset, noAssert) {
+  _writeInt16(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeInt16BE = function (value, offset, noAssert) {
+  _writeInt16(this, value, offset, false, noAssert)
+}
+
+function _writeInt32 (buf, value, offset, littleEndian, noAssert) {
+  if (!noAssert) {
+    assert(value !== undefined && value !== null, 'missing value')
+    assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+    assert(offset !== undefined && offset !== null, 'missing offset')
+    assert(offset + 3 < buf.length, 'Trying to write beyond buffer length')
+    verifsint(value, 0x7fffffff, -0x80000000)
+  }
+
+  var len = buf.length
+  if (offset >= len)
+    return
+
+  if (value >= 0)
+    _writeUInt32(buf, value, offset, littleEndian, noAssert)
+  else
+    _writeUInt32(buf, 0xffffffff + value + 1, offset, littleEndian, noAssert)
+}
+
+Buffer.prototype.writeInt32LE = function (value, offset, noAssert) {
+  _writeInt32(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeInt32BE = function (value, offset, noAssert) {
+  _writeInt32(this, value, offset, false, noAssert)
+}
+
+function _writeFloat (buf, value, offset, littleEndian, noAssert) {
+  if (!noAssert) {
+    assert(value !== undefined && value !== null, 'missing value')
+    assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+    assert(offset !== undefined && offset !== null, 'missing offset')
+    assert(offset + 3 < buf.length, 'Trying to write beyond buffer length')
+    verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38)
+  }
+
+  var len = buf.length
+  if (offset >= len)
+    return
+
+  ieee754.write(buf, value, offset, littleEndian, 23, 4)
+}
+
+Buffer.prototype.writeFloatLE = function (value, offset, noAssert) {
+  _writeFloat(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeFloatBE = function (value, offset, noAssert) {
+  _writeFloat(this, value, offset, false, noAssert)
+}
+
+function _writeDouble (buf, value, offset, littleEndian, noAssert) {
+  if (!noAssert) {
+    assert(value !== undefined && value !== null, 'missing value')
+    assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+    assert(offset !== undefined && offset !== null, 'missing offset')
+    assert(offset + 7 < buf.length,
+        'Trying to write beyond buffer length')
+    verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308)
+  }
+
+  var len = buf.length
+  if (offset >= len)
+    return
+
+  ieee754.write(buf, value, offset, littleEndian, 52, 8)
+}
+
+Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) {
+  _writeDouble(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) {
+  _writeDouble(this, value, offset, false, noAssert)
+}
+
+// fill(value, start=0, end=buffer.length)
+Buffer.prototype.fill = function (value, start, end) {
+  if (!value) value = 0
+  if (!start) start = 0
+  if (!end) end = this.length
+
+  if (typeof value === 'string') {
+    value = value.charCodeAt(0)
+  }
+
+  assert(typeof value === 'number' && !isNaN(value), 'value is not a number')
+  assert(end >= start, 'end < start')
+
+  // Fill 0 bytes; we're done
+  if (end === start) return
+  if (this.length === 0) return
+
+  assert(start >= 0 && start < this.length, 'start out of bounds')
+  assert(end >= 0 && end <= this.length, 'end out of bounds')
+
+  for (var i = start; i < end; i++) {
+    this[i] = value
+  }
+}
+
+Buffer.prototype.inspect = function () {
+  var out = []
+  var len = this.length
+  for (var i = 0; i < len; i++) {
+    out[i] = toHex(this[i])
+    if (i === exports.INSPECT_MAX_BYTES) {
+      out[i + 1] = '...'
+      break
+    }
+  }
+  return '<Buffer ' + out.join(' ') + '>'
+}
+
+/**
+ * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
+ * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
+ */
+Buffer.prototype.toArrayBuffer = function () {
+  if (typeof Uint8Array !== 'undefined') {
+    if (Buffer._useTypedArrays) {
+      return (new Buffer(this)).buffer
+    } else {
+      var buf = new Uint8Array(this.length)
+      for (var i = 0, len = buf.length; i < len; i += 1)
+        buf[i] = this[i]
+      return buf.buffer
+    }
+  } else {
+    throw new Error('Buffer.toArrayBuffer not supported in this browser')
+  }
+}
+
+// HELPER FUNCTIONS
+// ================
+
+function stringtrim (str) {
+  if (str.trim) return str.trim()
+  return str.replace(/^\s+|\s+$/g, '')
+}
+
+var BP = Buffer.prototype
+
+/**
+ * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
+ */
+Buffer._augment = function (arr) {
+  arr._isBuffer = true
+
+  // save reference to original Uint8Array get/set methods before overwriting
+  arr._get = arr.get
+  arr._set = arr.set
+
+  // deprecated, will be removed in node 0.13+
+  arr.get = BP.get
+  arr.set = BP.set
+
+  arr.write = BP.write
+  arr.toString = BP.toString
+  arr.toLocaleString = BP.toString
+  arr.toJSON = BP.toJSON
+  arr.copy = BP.copy
+  arr.slice = BP.slice
+  arr.readUInt8 = BP.readUInt8
+  arr.readUInt16LE = BP.readUInt16LE
+  arr.readUInt16BE = BP.readUInt16BE
+  arr.readUInt32LE = BP.readUInt32LE
+  arr.readUInt32BE = BP.readUInt32BE
+  arr.readInt8 = BP.readInt8
+  arr.readInt16LE = BP.readInt16LE
+  arr.readInt16BE = BP.readInt16BE
+  arr.readInt32LE = BP.readInt32LE
+  arr.readInt32BE = BP.readInt32BE
+  arr.readFloatLE = BP.readFloatLE
+  arr.readFloatBE = BP.readFloatBE
+  arr.readDoubleLE = BP.readDoubleLE
+  arr.readDoubleBE = BP.readDoubleBE
+  arr.writeUInt8 = BP.writeUInt8
+  arr.writeUInt16LE = BP.writeUInt16LE
+  arr.writeUInt16BE = BP.writeUInt16BE
+  arr.writeUInt32LE = BP.writeUInt32LE
+  arr.writeUInt32BE = BP.writeUInt32BE
+  arr.writeInt8 = BP.writeInt8
+  arr.writeInt16LE = BP.writeInt16LE
+  arr.writeInt16BE = BP.writeInt16BE
+  arr.writeInt32LE = BP.writeInt32LE
+  arr.writeInt32BE = BP.writeInt32BE
+  arr.writeFloatLE = BP.writeFloatLE
+  arr.writeFloatBE = BP.writeFloatBE
+  arr.writeDoubleLE = BP.writeDoubleLE
+  arr.writeDoubleBE = BP.writeDoubleBE
+  arr.fill = BP.fill
+  arr.inspect = BP.inspect
+  arr.toArrayBuffer = BP.toArrayBuffer
+
+  return arr
+}
+
+// slice(start, end)
+function clamp (index, len, defaultValue) {
+  if (typeof index !== 'number') return defaultValue
+  index = ~~index;  // Coerce to integer.
+  if (index >= len) return len
+  if (index >= 0) return index
+  index += len
+  if (index >= 0) return index
+  return 0
+}
+
+function coerce (length) {
+  // Coerce length to a number (possibly NaN), round up
+  // in case it's fractional (e.g. 123.456) then do a
+  // double negate to coerce a NaN to 0. Easy, right?
+  length = ~~Math.ceil(+length)
+  return length < 0 ? 0 : length
+}
+
+function isArray (subject) {
+  return (Array.isArray || function (subject) {
+    return Object.prototype.toString.call(subject) === '[object Array]'
+  })(subject)
+}
+
+function isArrayish (subject) {
+  return isArray(subject) || Buffer.isBuffer(subject) ||
+      subject && typeof subject === 'object' &&
+      typeof subject.length === 'number'
+}
+
+function toHex (n) {
+  if (n < 16) return '0' + n.toString(16)
+  return n.toString(16)
+}
+
+function utf8ToBytes (str) {
+  var byteArray = []
+  for (var i = 0; i < str.length; i++) {
+    var b = str.charCodeAt(i)
+    if (b <= 0x7F)
+      byteArray.push(str.charCodeAt(i))
+    else {
+      var start = i
+      if (b >= 0xD800 && b <= 0xDFFF) i++
+      var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%')
+      for (var j = 0; j < h.length; j++)
+        byteArray.push(parseInt(h[j], 16))
+    }
+  }
+  return byteArray
+}
+
+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) {
+  var c, hi, lo
+  var byteArray = []
+  for (var i = 0; i < str.length; i++) {
+    c = str.charCodeAt(i)
+    hi = c >> 8
+    lo = c % 256
+    byteArray.push(lo)
+    byteArray.push(hi)
+  }
+
+  return byteArray
+}
+
+function base64ToBytes (str) {
+  return base64.toByteArray(str)
+}
+
+function blitBuffer (src, dst, offset, length) {
+  var pos
+  for (var i = 0; i < length; i++) {
+    if ((i + offset >= dst.length) || (i >= src.length))
+      break
+    dst[i + offset] = src[i]
+  }
+  return i
+}
+
+function decodeUtf8Char (str) {
+  try {
+    return decodeURIComponent(str)
+  } catch (err) {
+    return String.fromCharCode(0xFFFD) // UTF 8 invalid char
+  }
+}
+
+/*
+ * We have to make sure that the value is a valid integer. This means that it
+ * is non-negative. It has no fractional component and that it does not
+ * exceed the maximum allowed value.
+ */
+function verifuint (value, max) {
+  assert(typeof value === 'number', 'cannot write a non-number as a number')
+  assert(value >= 0, 'specified a negative value for writing an unsigned value')
+  assert(value <= max, 'value is larger than maximum value for type')
+  assert(Math.floor(value) === value, 'value has a fractional component')
+}
+
+function verifsint (value, max, min) {
+  assert(typeof value === 'number', 'cannot write a non-number as a number')
+  assert(value <= max, 'value larger than maximum allowed value')
+  assert(value >= min, 'value smaller than minimum allowed value')
+  assert(Math.floor(value) === value, 'value has a fractional component')
+}
+
+function verifIEEE754 (value, max, min) {
+  assert(typeof value === 'number', 'cannot write a non-number as a number')
+  assert(value <= max, 'value larger than maximum allowed value')
+  assert(value >= min, 'value smaller than minimum allowed value')
+}
+
+function assert (test, message) {
+  if (!test) throw new Error(message || 'Failed assertion')
+}
+
+},{"base64-js":3,"ieee754":4}],"./":[function(require,module,exports){
+module.exports=require('Focm2+');
+},{}],3:[function(require,module,exports){
+var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
+
+;(function (exports) {
+	'use strict';
+
+  var Arr = (typeof Uint8Array !== 'undefined')
+    ? Uint8Array
+    : Array
+
+	var ZERO   = '0'.charCodeAt(0)
+	var PLUS   = '+'.charCodeAt(0)
+	var SLASH  = '/'.charCodeAt(0)
+	var NUMBER = '0'.charCodeAt(0)
+	var LOWER  = 'a'.charCodeAt(0)
+	var UPPER  = 'A'.charCodeAt(0)
+
+	function decode (elt) {
+		var code = elt.charCodeAt(0)
+		if (code === PLUS)
+			return 62 // '+'
+		if (code === SLASH)
+			return 63 // '/'
+		if (code < NUMBER)
+			return -1 //no match
+		if (code < NUMBER + 10)
+			return code - NUMBER + 26 + 26
+		if (code < UPPER + 26)
+			return code - UPPER
+		if (code < LOWER + 26)
+			return code - LOWER + 26
+	}
+
+	function b64ToByteArray (b64) {
+		var i, j, l, tmp, placeHolders, arr
+
+		if (b64.length % 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
+		var len = b64.length
+		placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
+
+		// base64 is 4/3 + up to two characters of the original data
+		arr = new Arr(b64.length * 3 / 4 - placeHolders)
+
+		// if there are placeholders, only get up to the last complete 4 chars
+		l = placeHolders > 0 ? b64.length - 4 : b64.length
+
+		var L = 0
+
+		function push (v) {
+			arr[L++] = v
+		}
+
+		for (i = 0, j = 0; i < l; i += 4, j += 3) {
+			tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
+			push((tmp & 0xFF0000) >> 16)
+			push((tmp & 0xFF00) >> 8)
+			push(tmp & 0xFF)
+		}
+
+		if (placeHolders === 2) {
+			tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
+			push(tmp & 0xFF)
+		} else if (placeHolders === 1) {
+			tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
+			push((tmp >> 8) & 0xFF)
+			push(tmp & 0xFF)
+		}
+
+		return arr
+	}
+
+	function uint8ToBase64 (uint8) {
+		var i,
+			extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
+			output = "",
+			temp, length
+
+		function encode (num) {
+			return lookup.charAt(num)
+		}
+
+		function tripletToBase64 (num) {
+			return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
+		}
+
+		// go through the array every three bytes, we'll deal with trailing stuff later
+		for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
+			temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
+			output += tripletToBase64(temp)
+		}
+
+		// pad the end with zeros, but make sure to not forget the extra bytes
+		switch (extraBytes) {
+			case 1:
+				temp = uint8[uint8.length - 1]
+				output += encode(temp >> 2)
+				output += encode((temp << 4) & 0x3F)
+				output += '=='
+				break
+			case 2:
+				temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
+				output += encode(temp >> 10)
+				output += encode((temp >> 4) & 0x3F)
+				output += encode((temp << 2) & 0x3F)
+				output += '='
+				break
+		}
+
+		return output
+	}
+
+	module.exports.toByteArray = b64ToByteArray
+	module.exports.fromByteArray = uint8ToBase64
+}())
+
+},{}],4:[function(require,module,exports){
+exports.read = function(buffer, offset, isLE, mLen, nBytes) {
+  var e, m,
+      eLen = nBytes * 8 - mLen - 1,
+      eMax = (1 << eLen) - 1,
+      eBias = eMax >> 1,
+      nBits = -7,
+      i = isLE ? (nBytes - 1) : 0,
+      d = isLE ? -1 : 1,
+      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,
+      eLen = nBytes * 8 - mLen - 1,
+      eMax = (1 << eLen) - 1,
+      eBias = eMax >> 1,
+      rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
+      i = isLE ? 0 : (nBytes - 1),
+      d = isLE ? 1 : -1,
+      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;
+};
+
+},{}]},{},[]);module.exports=require("./").Buffer;

+ 4 - 0
bundle.sh

@@ -0,0 +1,4 @@
+#!/bin/bash
+
+./node_modules/.bin/browserify --no-detect-globals -r ./ > bundle.js
+echo ';module.exports=require("./").Buffer;' >> bundle.js

+ 22 - 0
extend.js

@@ -0,0 +1,22 @@
+
+module.exports = function(PT){
+
+
+
+console.log("HEREHER");
+
+var crypto = require("crypto");
+
+
+PT.SHA256 = function(encoding){
+  var encoding = encoding || null;
+  var h=crypto.createHash('sha256');
+  	console.log(new Buffer(this));
+
+    h.update(new Buffer(this));
+    return h.digest(encoding);
+}
+
+
+
+}

+ 530 - 0
index.js

@@ -0,0 +1,530 @@
+var Buffer = require("buffer").Buffer;
+
+var crypto = require("crypto");
+
+var BP = {};
+
+
+BP.bitSize = function() {
+    return (this.length * 8);
+}
+
+BP.add = function(buf) {
+    var n1 = bigi.str2bigInt(this.toString("hex"), 16, (this.length * 8));
+    var n2 = bigi.str2bigInt(buf.toString("hex"), 16, (buf.length * 8));
+    var res = bigi.add(n1, n2);
+    var tt = bigi.bigInt2str(res, 16);
+    var n = nb(tt.length % 2 === 0 ? tt : "0" + tt, 'hex');
+    return n
+}
+BP.sub = function(buf) {
+    var n1 = bigi.str2bigInt(this.toString("hex"), 16, (this.length * 8));
+    var n2 = bigi.str2bigInt(buf.toString("hex"), 16, (buf.length * 8));
+    var res = bigi.sub(n1, n2);
+    var tt = bigi.bigInt2str(res, 16);
+    var n = nb(tt.length % 2 === 0 ? tt : "0" + tt, 'hex');
+    return n
+}
+BP.mult = function(buf) {
+    var string = this.toString('hex');
+    var asa = bigi.str2bigInt(string, 16, (this.length * 8));
+    var asa2;
+    if (typeof(buf) === "number") {
+        asa2 = bigi.str2bigInt("" + buf, 10);
+    } else {
+        var string2 = buf.toString('hex');
+        asa2 = bigi.str2bigInt(string2, 16, (buf.length * 8));
+    }
+    bigi.mult(asa, asa2);
+    var ss = bigi.bigInt2str(asa, 16);
+    var re = nb(ss.length % 2 === 0 ? ss : "0" + ss, 'hex');
+    return re;
+}
+
+BP.div = function(buf) {
+    var n1 = bigi.str2bigInt(this.toString("hex"), 16, (this.length * 8));
+    var n2 = bigi.str2bigInt(buf.toString("hex"), 16, (buf.length * 8));
+    var q = bigi.str2bigInt("0", 16, n1.length * 8);
+    var r = bigi.str2bigInt("0", 16, n2.length * 8);
+    bigi.div(n1, n2, q, r);
+    var qq = bigi.bigInt2str(q, 16);
+    var rr = bigi.bigInt2str(r, 16);
+    var ret = [nb(qq.length % 2 === 0 ? qq : "0" + qq, 'hex'), nb(rr.length % 2 === 0 ? rr : "0" + rr, 'hex')];
+    return ret;
+}
+
+BP.gcd = function(buf) {
+    var n1 = bigi.str2bigInt(this.toString("hex"), 16, (this.length * 8));
+    var n2 = bigi.str2bigInt(buf.toString("hex"), 16, (buf.length * 8));
+    var gg = bigi.GCD(n1, n2);
+    var qq = bigi.bigInt2str(gg, 16);
+    return nb(qq.length % 2 === 0 ? qq : "0" + qq, 'hex');
+}
+BP.mod = function(buf) {
+    var n1 = bigi.str2bigInt(this.toString("hex"), 16, (this.length * 8));
+    var n2 = bigi.str2bigInt(buf.toString("hex"), 16, (buf.length * 8));
+    var gg = bigi.mod(n1, n2);
+    var qq = bigi.bigInt2str(gg, 16);
+    return nb(qq.length % 2 === 0 ? qq : "0" + qq, 'hex');
+}
+BP.powMod = function(buf, bufn) {
+    var n1 = bigi.str2bigInt(this.toString("hex"), 16, (this.length * 8));
+    var n2 = bigi.str2bigInt(buf.toString("hex"), 16, (buf.length * 8));
+    var n3 = bigi.str2bigInt(bufn.toString("hex"), 16, (bufn.length * 8));
+    var gg = bigi.powMod(n1, n2, n3);
+    var qq = bigi.bigInt2str(gg, 16);
+    return nb(qq.length % 2 === 0 ? qq : "0" + qq, 'hex');
+}
+
+
+BP.leftShift = function(n) {
+    var n1 = bigi.str2bigInt(this.toString("hex"), 16, (this.length * 8));
+    var gg = bigi.leftShift(n1, n);
+    var qq = bigi.bigInt2str(n1, 16);
+    return nb(qq.length % 2 === 0 ? qq : "0" + qq, 'hex');
+}
+BP.rightShift = function(n) {
+    var n1 = bigi.str2bigInt(this.toString("hex"), 16, (this.length * 8));
+    var gg = bigi.rightShift(n1, n);
+    var qq = bigi.bigInt2str(n1, 16);
+    return nb(qq.length % 2 === 0 ? qq : "0" + qq, 'hex');
+}
+
+
+
+
+BP.SHA256 = function(encoding) {
+    var encoding = encoding || null;
+    var h = crypto.createHash('sha256');
+    h.update(new Buffer(this));
+    return nb(h.digest(encoding));
+}
+BP.SHA1 = function(encoding) {
+    var encoding = encoding || null;
+    var h = crypto.createHash('sha1');
+    h.update(this);
+    return nb(h.digest(encoding));
+}
+BP.SHA224 = function(encoding) {
+    var encoding = encoding || null;
+    var h = crypto.createHash('sha224');
+    h.update(this);
+    return nb(h.digest(encoding));
+}
+BP.SHA256 = function(encoding) {
+    var encoding = encoding || null;
+    var h = crypto.createHash('sha256');
+    h.update(this);
+    return nb(h.digest(encoding));
+}
+BP.SHA384 = function(encoding) {
+    var encoding = encoding || null;
+    var h = crypto.createHash('sha384');
+    h.update(this);
+    return nb(h.digest(encoding));
+}
+BP.SHA512 = function(encoding) {
+    var encoding = encoding || null;
+    var h = crypto.createHash('sha512');
+    h.update(this);
+    return nb(h.digest(encoding));
+}
+
+BP.MD5 = function(encoding) {
+    var encoding = encoding || null;
+    var h = crypto.createHash('md5');
+    h.update(this);
+    return h.digest(encoding);
+}
+BP.RIPE = function(encoding) {
+    var encoding = encoding || null;
+    var h = crypto.createHash('ripemd');
+    h.update(this);
+    return nb(h.digest(encoding));
+}
+BP.RIPE160 = function(encoding) {
+    var encoding = encoding || null;
+    var h = crypto.createHash('ripemd160');
+    h.update(this);
+    return nb(h.digest(encoding));
+}
+
+BP.WHIRLPOOL = function(encoding) {
+    var encoding = encoding || null;
+    var h = crypto.createHash('whirlpool');
+    h.update(this);
+    return nb(h.digest(encoding));
+}
+
+BP.prepend = function(buf) {
+    var tmp = nb(this.length + buf.length);
+    for (var i = 0; i < buf.length; i++) {
+        tmp[i] = buf[i];
+    }
+    for (var i = 0; i < this.length; i++) {
+        tmp[buf.length + i] = this[i];
+    }
+    return tmp;
+}
+
+BP.append = function(buf, baselength) {
+    var nlen = this.length + buf.length;
+    if (baselength) {
+        nlen = Math.ceil((nlen) / baselength) * baselength;
+    }
+    var tmp = nb(nlen);
+    tmp.fill(0);
+    for (var i = 0; i < this.length; i++) {
+        tmp[i] = this[i];
+    }
+    for (var i = 0; i < buf.length; i++) {
+        tmp[this.length + i] = buf[i];
+    }
+    return tmp;
+}
+
+
+BP.XOR = function(buf) {
+    var nn = nb(this.length);
+    var mi = buf.length;
+    var fi = 0;
+    var n = this.length;
+    for (var i = 0; i < n; i++) {
+        if (i > mi) {
+            fi = 0;
+        }
+        nn[i] = this[i] ^ (buf[fi]);
+        fi++;
+    }
+    return nn;
+}
+BP.AND = function(buf) {
+    var nn = nb(this.length);
+    var mi = buf.length;
+    var fi = 0;
+    var n = this.length;
+    for (var i = 0; i < n; i++) {
+        if (i > mi) {
+            fi = 0;
+        }
+        nn[i] = this[i] & (buf[fi]);
+        fi++;
+    }
+    return nn;
+}
+BP.OR = function(buf) {
+    var nn = nb(this.length);
+    var mi = buf.length;
+    var fi = 0;
+    var n = this.length;
+    for (var i = 0; i < n; i++) {
+        if (i > mi) {
+            fi = 0;
+        }
+        nn[i] = this[i] | (buf[fi]);
+        fi++;
+    }
+    return nn;
+}
+
+BP.clone = function() {
+    var n = nb(this.length);
+    for (var i = 0; i < this.length; i++) {
+        n[i] = this[i];
+    }
+    return n;
+}
+
+
+var bigi = require("./bigint");
+
+BP.toBase = function(base) {
+    var ss = this.toString("hex");
+    var asa = bigi.str2bigInt(ss, 16);
+    var s = bigi.bigInt2str(asa, base);
+    return s;
+}
+
+
+
+
+BP.fromBase = function(string, base) {
+    var asa = bigi.str2bigInt(string, base);
+    var ss = bigi.bigInt2str(asa, 16);
+
+    var re = nb(ss.length % 2 === 0 ? ss : "0" + ss, 'hex');
+    return re;
+}
+BP.fromBase2 = function(base) {
+    var string = this.toString();
+    var asa = bigi.str2bigInt(string, base);
+    var ss = bigi.bigInt2str(asa, 16);
+    var re = nb(ss.length % 2 === 0 ? ss : "0" + ss, 'hex');
+    return re;
+}
+
+
+var zlib = require('zlib');
+
+BP.zip = function(callback) {
+
+    zlib.deflate(this, function(err, buffer) {
+        callback(err, nb(buffer));
+    });
+}
+
+BP.unzip = function(callback) {
+
+    zlib.unzip(this, function(err, buffer) {
+        callback(err, nb(buffer));
+    });
+}
+
+
+
+
+BP.hexdump = function() {
+    return hexdump.apply(this, arguments);
+}
+
+function hexdump(buf, showascii, perline, space, padit, linenums, showtype, html) {
+    var showtype = showtype || false;
+    var html = html || false;
+    var s = "";
+    if (showtype) {
+        s += "type: " + typeof(buf) + " " + ((buf instanceof Buffer)) + "\n";
+    }
+    if (typeof(buf) !== "object") {
+        buf = new Buffer(buf);
+    }
+
+    var usebuf;
+    var perline = (perline === 0 || perline) ? perline : 32;
+    var space = (space === 0 || space) ? space : 8;
+    var showascii = showascii || false;
+    var linenums = linenums || false;
+    if (perline === 0) {
+        perline = buf.length;
+    }
+    usebuf = buf;
+    if (padit) {
+        var shouldbelength = Math.ceil(buf.length / perline) * perline;
+        var nbuf = new Buffer(shouldbelength);
+        nbuf.fill(0);
+        buf.copy(nbuf, 0, 0, buf.length);
+        usebuf = nbuf;
+    }
+
+    var tl = Math.ceil(buf.length / perline);
+
+    var mask = [127, 129, 141, 143, 144, 157, 160, 173, 184, 185, 186];
+
+    var allow = [];
+
+
+    for (var i = 0; i < tl; i++) {
+        var mx = (i * perline) + perline;
+        if (mx > usebuf.length) {
+            mx = usebuf.length;
+        }
+        if (linenums) {
+            s += intToHex(i * perline, 3) + " ";
+
+        }
+        var a = "";
+        var t = usebuf.slice(i * perline, mx);
+        for (var y = 0; y < t.length; y++) {
+            s += int2hex(t[y]);
+            if (html) {
+                if (((t[y] > 31) && (mask.indexOf(t[y]) === -1))) {
+                    a += "&#" + t[y] + ";";
+                } else {
+                    a += ".";
+                }
+            } else {
+                if (((t[y] > 31) && (t[y] < 127))) {
+                    a += String.fromCharCode(t[y]);
+                } else {
+                    a += ".";
+                }
+            }
+
+
+            if (y % space === (space - 1)) {
+                s += " ";
+                a += " ";
+            }
+
+        }
+
+        if (showascii) {
+            s += " | " + a;
+        }
+        if (tl > 1) {
+            s += "\n";
+
+        }
+
+    }
+
+    return s;
+
+}
+
+function intToHex(integera, bytes) {
+    var bytes = bytes || 1;
+    integera = integera.toString(16);
+    if (integera.length % (bytes * 2) !== 0) {
+        while (integera.length < bytes * 2) {
+            integera = '0' + integera;
+        }
+    }
+    return integera;
+};
+
+function int2hex(integer) {
+    integer = integer.toString(16);
+    if (integer.length % 2 !== 0) {
+        integer = '0' + integer;
+    }
+    return integer;
+};
+
+function int2word(integer) {
+    integer = integer.toString(16);
+    if (integer.length % 8 !== 0) {
+        while (integer.length < 8) {
+            integer = '0' + integer;
+        }
+    }
+    return integer;
+};
+
+function int2longword(integer) {
+    integer = integer.toString(16);
+    if (integer.length % 16 !== 0) {
+        while (integer.length < 16) {
+            integer = '0' + integer;
+        }
+    }
+    return integer;
+};
+
+
+
+var bs58 = require("bs58");
+var decoders = {
+    "base58": function(input) {
+        return bs58.decode(input);
+    }
+}
+var encoders = {
+    "base58": function(input) {
+        return bs58.encode(input);
+    }
+}
+
+BP.toBase58 = function() {
+    return encoders.base58(this);
+}
+BP.toBase64 = function() {
+    return this.toString('base64');
+}
+
+
+
+
+
+
+for (var p in BP) {
+    Buffer.prototype[p] = BP[p];
+}
+
+
+
+
+var encodings = ["ascii", "utf8", "utf16le", "ucs2", "base64", "binary", "hex"];
+var specialencodings = ["base58"];
+
+function nb(a, encoding, minsize) {
+    if (typeof(a) === "object") {
+        if (typeof(a.bitSize) === "function") {
+            return a;
+        }
+    }
+    var holder;
+
+    if (!encoding && !minsize && typeof(a) === "number") {
+        holder = new Buffer(a);
+    } else {
+
+
+        if (!encoding) {
+            encoding = 'utf8';
+        }
+        if (encodings.indexOf(encoding) > -1) {
+            holder = new Buffer(a + "", encoding);
+            if (typeof(a) === "number") {
+                holder.fill(0);
+            }
+            if (minsize) {
+                var hholder = new Buffer(minsize);
+                hholder.fill(0)
+                holder.copy(hholder, hholder.length - holder.length);
+                holder = hholder;
+            }
+
+        } else {
+            if (specialencodings.indexOf(encoding) > -1 && decoders[encoding]) {
+                var tt = decoders[encoding](a);
+                holder = new Buffer(tt);
+            } else {
+
+                var base = parseInt(encoding);
+                var bb = bigi.str2bigInt(a, base);
+                var ss = bigi.bigInt2str(bb, 16);
+
+                holder = new Buffer(ss.length % 2 === 0 ? ss : "0" + ss, 'hex');
+
+                if (minsize) {
+                    var hholder = new Buffer(minsize);
+                    hholder.fill(0)
+                    holder.copy(hholder, hholder.length - holder.length);
+                    holder = hholder;
+                }
+
+            }
+
+
+
+
+
+        }
+
+    }
+
+
+    if (Buffer._useTypedArrays) {
+        for (var p in BP) {
+            holder[p] = BP[p];
+        }
+    }
+    return holder;
+}
+
+
+module.exports = nb;
+
+
+/*
+
+'ascii' - for 7 bit ASCII data only. This encoding method is very fast, and will strip the high bit if set.
+Note that when converting from string to buffer, this encoding converts a null character ('\0' or '\u0000') into 0x20 (character code of a space). If you want to convert a null character into 0x00, you should use 'utf8'.
+
+'utf8' - Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8.
+'utf16le' - 2 or 4 bytes, little endian encoded Unicode characters. Surrogate pairs (U+10000 to U+10FFFF) are supported.
+'ucs2' - Alias of 'utf16le'.
+'base64' - Base64 string encoding.
+'binary' - A way of encoding raw binary data into strings by using only the first 8 bits of each character. This encoding method is deprecated and should be avoided in favor of Buffer objects where possible. This encoding will be removed in future versions of Node.
+'hex' - Encode each byte as two hexadecimal characters.
+*/

+ 37 - 0
perf/bracket-notation.js

@@ -0,0 +1,37 @@
+var benchmark = require('benchmark')
+var suite = new benchmark.Suite()
+
+global.NewBuffer = require('../').Buffer // native-buffer-browserify
+global.OldBuffer = require('buffer-browserify').Buffer // buffer-browserify
+
+var LENGTH = 50
+
+var newTarget = NewBuffer(LENGTH)
+var oldTarget = OldBuffer(LENGTH)
+var nodeTarget = Buffer(LENGTH)
+
+suite.add('NewBuffer#bracket-notation', function () {
+  for (var i = 0; i < LENGTH; i++) {
+    newTarget[i] = i + 97
+  }
+})
+.add('OldBuffer#bracket-notation', function () {
+  for (var i = 0; i < LENGTH; i++) {
+    oldTarget[i] = i + 97
+  }
+})
+.add('Buffer#bracket-notation', function () {
+  for (var i = 0; i < LENGTH; i++) {
+    nodeTarget[i] = i + 97
+  }
+})
+.on('error', function (event) {
+  console.error(event.target.error.stack)
+})
+.on('cycle', function (event) {
+  console.log(String(event.target))
+})
+.on('complete', function () {
+  console.log('Fastest is ' + this.filter('fastest').pluck('name'))
+})
+.run({ 'async': true })

+ 0 - 0
perf/bundle.js


+ 37 - 0
perf/comparison/bracket-notation.js

@@ -0,0 +1,37 @@
+var benchmark = require('benchmark')
+var suite = new benchmark.Suite()
+
+global.NewBuffer = require('../../').Buffer // native-buffer-browserify
+global.OldBuffer = require('buffer-browserify').Buffer // buffer-browserify
+
+var LENGTH = 50
+
+var newTarget = NewBuffer(LENGTH)
+var oldTarget = OldBuffer(LENGTH)
+var nodeTarget = Buffer(LENGTH)
+
+suite.add('NewBuffer#bracket-notation', function () {
+  for (var i = 0; i < LENGTH; i++) {
+    newTarget[i] = i + 97
+  }
+})
+.add('OldBuffer#bracket-notation', function () {
+  for (var i = 0; i < LENGTH; i++) {
+    oldTarget[i] = i + 97
+  }
+})
+.add('Buffer#bracket-notation', function () {
+  for (var i = 0; i < LENGTH; i++) {
+    nodeTarget[i] = i + 97
+  }
+})
+.on('error', function (event) {
+  console.error(event.target.error.stack)
+})
+.on('cycle', function (event) {
+  console.log(String(event.target))
+})
+.on('complete', function () {
+  console.log('Fastest is ' + this.filter('fastest').pluck('name'))
+})
+.run({ 'async': true })

A különbségek nem kerülnek megjelenítésre, a fájl túl nagy
+ 9954 - 0
perf/comparison/bundle.js


+ 40 - 0
perf/comparison/concat.js

@@ -0,0 +1,40 @@
+var benchmark = require('benchmark')
+var suite = new benchmark.Suite()
+
+global.NewBuffer = require('../../').Buffer // native-buffer-browserify
+global.OldBuffer = require('buffer-browserify').Buffer // buffer-browserify
+
+var LENGTH = 16
+
+var newBuf = NewBuffer(LENGTH)
+var newBuf2 = NewBuffer(LENGTH)
+var oldBuf = OldBuffer(LENGTH)
+var oldBuf2 = OldBuffer(LENGTH)
+var nodeBuf = Buffer(LENGTH)
+var nodeBuf2 = Buffer(LENGTH)
+
+;[newBuf, newBuf2, oldBuf, oldBuf2, nodeBuf, nodeBuf2].forEach(function (buf) {
+  for (var i = 0; i < LENGTH; i++) {
+    buf[i] = 42
+  }
+})
+
+suite.add('NewBuffer#concat', function () {
+  var x = Buffer.concat([newBuf, newBuf2])
+})
+.add('OldBuffer#concat', function () {
+  var x = Buffer.concat([oldBuf, oldBuf2])
+})
+.add('Buffer#concat', function () {
+  var x = Buffer.concat([nodeBuf, nodeBuf2])
+})
+.on('error', function (event) {
+  console.error(event.target.error.stack)
+})
+.on('cycle', function (event) {
+  console.log(String(event.target))
+})
+.on('complete', function () {
+  console.log('Fastest is ' + this.filter('fastest').pluck('name'))
+})
+.run({ 'async': true })

+ 35 - 0
perf/comparison/copy-big.js

@@ -0,0 +1,35 @@
+var benchmark = require('benchmark')
+var suite = new benchmark.Suite()
+
+global.NewBuffer = require('../../').Buffer // native-buffer-browserify
+global.OldBuffer = require('buffer-browserify').Buffer // buffer-browserify
+
+var LENGTH = 10000
+
+var newSubject = NewBuffer(LENGTH)
+var oldSubject = OldBuffer(LENGTH)
+var nodeSubject = Buffer(LENGTH)
+
+var newTarget = NewBuffer(LENGTH)
+var oldTarget = OldBuffer(LENGTH)
+var nodeTarget = Buffer(LENGTH)
+
+suite.add('NewBuffer#copy', function () {
+  newSubject.copy(newTarget)
+})
+.add('OldBuffer#copy', function () {
+  oldSubject.copy(oldTarget)
+})
+.add('Buffer#copy', function () {
+  nodeSubject.copy(nodeTarget)
+})
+.on('error', function (event) {
+  console.error(event.target.error.stack)
+})
+.on('cycle', function (event) {
+  console.log(String(event.target))
+})
+.on('complete', function () {
+  console.log('Fastest is ' + this.filter('fastest').pluck('name'))
+})
+.run({ 'async': true })

+ 35 - 0
perf/comparison/copy.js

@@ -0,0 +1,35 @@
+var benchmark = require('benchmark')
+var suite = new benchmark.Suite()
+
+global.NewBuffer = require('../../').Buffer // native-buffer-browserify
+global.OldBuffer = require('buffer-browserify').Buffer // buffer-browserify
+
+var LENGTH = 10
+
+var newSubject = NewBuffer(LENGTH)
+var oldSubject = OldBuffer(LENGTH)
+var nodeSubject = Buffer(LENGTH)
+
+var newTarget = NewBuffer(LENGTH)
+var oldTarget = OldBuffer(LENGTH)
+var nodeTarget = Buffer(LENGTH)
+
+suite.add('NewBuffer#copy', function () {
+  newSubject.copy(newTarget)
+})
+.add('OldBuffer#copy', function () {
+  oldSubject.copy(oldTarget)
+})
+.add('Buffer#copy', function () {
+  nodeSubject.copy(nodeTarget)
+})
+.on('error', function (event) {
+  console.error(event.target.error.stack)
+})
+.on('cycle', function (event) {
+  console.log(String(event.target))
+})
+.on('complete', function () {
+  console.log('Fastest is ' + this.filter('fastest').pluck('name'))
+})
+.run({ 'async': true })

+ 1 - 0
perf/comparison/index.html

@@ -0,0 +1 @@
+<script src='bundle.js'></script>

+ 30 - 0
perf/comparison/new.js

@@ -0,0 +1,30 @@
+var benchmark = require('benchmark')
+var suite = new benchmark.Suite()
+
+global.NewBuffer = require('../../').Buffer // native-buffer-browserify
+global.OldBuffer = require('buffer-browserify').Buffer // buffer-browserify
+
+var LENGTH = 10
+
+suite.add('NewBuffer#new', function () {
+  var buf = NewBuffer(LENGTH)
+})
+.add('Uint8Array#new', function () {
+  var buf = new Uint8Array(LENGTH)
+})
+.add('OldBuffer#new', function () {
+  var buf = OldBuffer(LENGTH)
+})
+.add('Buffer#new', function () {
+  var buf = Buffer(LENGTH)
+})
+.on('error', function (event) {
+  console.error(event.target.error.stack)
+})
+.on('cycle', function (event) {
+  console.log(String(event.target))
+})
+.on('complete', function () {
+  console.log('Fastest is ' + this.filter('fastest').pluck('name'))
+})
+.run({ 'async': true })

+ 43 - 0
perf/comparison/readDoubleBE.js

@@ -0,0 +1,43 @@
+var benchmark = require('benchmark')
+var suite = new benchmark.Suite()
+
+global.NewBuffer = require('../../').Buffer // native-buffer-browserify
+global.OldBuffer = require('buffer-browserify').Buffer // buffer-browserify
+
+var LENGTH = 10
+
+var newTarget = NewBuffer(LENGTH * 8)
+var oldTarget = OldBuffer(LENGTH * 8)
+var nodeTarget = Buffer(LENGTH * 8)
+
+;[newTarget, oldTarget, nodeTarget].forEach(function (buf) {
+  for (var i = 0; i < LENGTH; i++) {
+    buf.writeDoubleBE(97.1919 + i, i * 8)
+  }
+})
+
+suite.add('NewBuffer#readDoubleBE', function () {
+  for (var i = 0; i < LENGTH; i++) {
+    var x = newTarget.readDoubleBE(i * 8)
+  }
+})
+.add('OldBuffer#readDoubleBE', function () {
+  for (var i = 0; i < LENGTH; i++) {
+    var x = oldTarget.readDoubleBE(i * 8)
+  }
+})
+.add('Buffer#readDoubleBE', function () {
+  for (var i = 0; i < LENGTH; i++) {
+    var x = nodeTarget.readDoubleBE(i * 8)
+  }
+})
+.on('error', function (event) {
+  console.error(event.target.error.stack)
+})
+.on('cycle', function (event) {
+  console.log(String(event.target))
+})
+.on('complete', function () {
+  console.log('Fastest is ' + this.filter('fastest').pluck('name'))
+})
+.run({ 'async': true })

+ 43 - 0
perf/comparison/readFloatBE.js

@@ -0,0 +1,43 @@
+var benchmark = require('benchmark')
+var suite = new benchmark.Suite()
+
+global.NewBuffer = require('../../').Buffer // native-buffer-browserify
+global.OldBuffer = require('buffer-browserify').Buffer // buffer-browserify
+
+var LENGTH = 10
+
+var newTarget = NewBuffer(LENGTH * 4)
+var oldTarget = OldBuffer(LENGTH * 4)
+var nodeTarget = Buffer(LENGTH * 4)
+
+;[newTarget, oldTarget, nodeTarget].forEach(function (buf) {
+  for (var i = 0; i < LENGTH; i++) {
+    buf.writeFloatBE(97.1919 + i, i * 4)
+  }
+})
+
+suite.add('NewBuffer#readFloatBE', function () {
+  for (var i = 0; i < LENGTH; i++) {
+    var x = newTarget.readFloatBE(i * 4)
+  }
+})
+.add('OldBuffer#readFloatBE', function () {
+  for (var i = 0; i < LENGTH; i++) {
+    var x = oldTarget.readFloatBE(i * 4)
+  }
+})
+.add('Buffer#readFloatBE', function () {
+  for (var i = 0; i < LENGTH; i++) {
+    var x = nodeTarget.readFloatBE(i * 4)
+  }
+})
+.on('error', function (event) {
+  console.error(event.target.error.stack)
+})
+.on('cycle', function (event) {
+  console.log(String(event.target))
+})
+.on('complete', function () {
+  console.log('Fastest is ' + this.filter('fastest').pluck('name'))
+})
+.run({ 'async': true })

+ 43 - 0
perf/comparison/readUInt32LE.js

@@ -0,0 +1,43 @@
+var benchmark = require('benchmark')
+var suite = new benchmark.Suite()
+
+global.NewBuffer = require('../../').Buffer // native-buffer-browserify
+global.OldBuffer = require('buffer-browserify').Buffer // buffer-browserify
+
+var LENGTH = 20
+
+var newTarget = NewBuffer(LENGTH * 4)
+var oldTarget = OldBuffer(LENGTH * 4)
+var nodeTarget = Buffer(LENGTH * 4)
+
+;[newTarget, oldTarget, nodeTarget].forEach(function (buf) {
+  for (var i = 0; i < LENGTH; i++) {
+    buf.writeUInt32LE(7000 + i, i * 4)
+  }
+})
+
+suite.add('NewBuffer#readUInt32LE', function () {
+  for (var i = 0; i < LENGTH; i++) {
+    var x = newTarget.readUInt32LE(i * 4)
+  }
+})
+.add('OldBuffer#readUInt32LE', function () {
+  for (var i = 0; i < LENGTH; i++) {
+    var x = oldTarget.readUInt32LE(i * 4)
+  }
+})
+.add('Buffer#readUInt32LE', function () {
+  for (var i = 0; i < LENGTH; i++) {
+    var x = nodeTarget.readUInt32LE(i * 4)
+  }
+})
+.on('error', function (event) {
+  console.error(event.target.error.stack)
+})
+.on('cycle', function (event) {
+  console.log(String(event.target))
+})
+.on('complete', function () {
+  console.log('Fastest is ' + this.filter('fastest').pluck('name'))
+})
+.run({ 'async': true })

+ 31 - 0
perf/comparison/slice.js

@@ -0,0 +1,31 @@
+var benchmark = require('benchmark')
+var suite = new benchmark.Suite()
+
+global.NewBuffer = require('../../').Buffer // native-buffer-browserify
+global.OldBuffer = require('buffer-browserify').Buffer // buffer-browserify
+
+var LENGTH = 16
+
+var newBuf = NewBuffer(LENGTH)
+var oldBuf = OldBuffer(LENGTH)
+var nodeBuf = Buffer(LENGTH)
+
+suite.add('NewBuffer#slice', function () {
+  var x = newBuf.slice(4)
+})
+.add('OldBuffer#slice', function () {
+  var x = oldBuf.slice(4)
+})
+.add('Buffer#slice', function () {
+  var x = nodeBuf.slice(4)
+})
+.on('error', function (event) {
+  console.error(event.target.error.stack)
+})
+.on('cycle', function (event) {
+  console.log(String(event.target))
+})
+.on('complete', function () {
+  console.log('Fastest is ' + this.filter('fastest').pluck('name'))
+})
+.run({ 'async': true })

+ 37 - 0
perf/comparison/writeFloatBE.js

@@ -0,0 +1,37 @@
+var benchmark = require('benchmark')
+var suite = new benchmark.Suite()
+
+global.NewBuffer = require('../../').Buffer // native-buffer-browserify
+global.OldBuffer = require('buffer-browserify').Buffer // buffer-browserify
+
+var LENGTH = 10
+
+var newTarget = NewBuffer(LENGTH * 4)
+var oldTarget = OldBuffer(LENGTH * 4)
+var nodeTarget = Buffer(LENGTH * 4)
+
+suite.add('NewBuffer#writeFloatBE', function () {
+  for (var i = 0; i < LENGTH; i++) {
+    newTarget.writeFloatBE(97.1919 + i, i * 4)
+  }
+})
+.add('OldBuffer#writeFloatBE', function () {
+  for (var i = 0; i < LENGTH; i++) {
+    oldTarget.writeFloatBE(97.1919 + i, i * 4)
+  }
+})
+.add('Buffer#writeFloatBE', function () {
+  for (var i = 0; i < LENGTH; i++) {
+    nodeTarget.writeFloatBE(97.1919 + i, i * 4)
+  }
+})
+.on('error', function (event) {
+  console.error(event.target.error.stack)
+})
+.on('cycle', function (event) {
+  console.log(String(event.target))
+})
+.on('complete', function () {
+  console.log('Fastest is ' + this.filter('fastest').pluck('name'))
+})
+.run({ 'async': true })

+ 22 - 0
perf/solo/bracket-notation.js

@@ -0,0 +1,22 @@
+var benchmark = require('benchmark')
+var suite = new benchmark.Suite()
+
+global.NewBuffer = require('../../').Buffer // native-buffer-browserify
+
+var LENGTH = 50
+
+var newTarget = NewBuffer(LENGTH)
+
+suite.add('NewBuffer#bracket-notation', function () {
+  for (var i = 0; i < LENGTH; i++) {
+    newTarget[i] = i + 97
+  }
+})
+.on('error', function (event) {
+  console.error(event.target.error.stack)
+})
+.on('cycle', function (event) {
+  console.log(String(event.target))
+})
+
+.run({ 'async': true })

A különbségek nem kerülnek megjelenítésre, a fájl túl nagy
+ 5320 - 0
perf/solo/bundle.js


+ 27 - 0
perf/solo/concat.js

@@ -0,0 +1,27 @@
+var benchmark = require('benchmark')
+var suite = new benchmark.Suite()
+
+global.NewBuffer = require('../../').Buffer // native-buffer-browserify
+
+var LENGTH = 16
+
+var newBuf = NewBuffer(LENGTH)
+var newBuf2 = NewBuffer(LENGTH)
+
+;[newBuf, newBuf2].forEach(function (buf) {
+  for (var i = 0; i < LENGTH; i++) {
+    buf[i] = 42
+  }
+})
+
+suite.add('NewBuffer#concat', function () {
+  var x = Buffer.concat([newBuf, newBuf2])
+})
+.on('error', function (event) {
+  console.error(event.target.error.stack)
+})
+.on('cycle', function (event) {
+  console.log(String(event.target))
+})
+
+.run({ 'async': true })

+ 21 - 0
perf/solo/copy.js

@@ -0,0 +1,21 @@
+var benchmark = require('benchmark')
+var suite = new benchmark.Suite()
+
+global.NewBuffer = require('../../').Buffer // native-buffer-browserify
+
+var LENGTH = 10
+
+var newSubject = NewBuffer(LENGTH)
+var newTarget = NewBuffer(LENGTH)
+
+suite.add('NewBuffer#copy', function () {
+  newSubject.copy(newTarget)
+})
+.on('error', function (event) {
+  console.error(event.target.error.stack)
+})
+.on('cycle', function (event) {
+  console.log(String(event.target))
+})
+
+.run({ 'async': true })

+ 1 - 0
perf/solo/index.html

@@ -0,0 +1 @@
+<script src='bundle.js'></script>

+ 21 - 0
perf/solo/new.js

@@ -0,0 +1,21 @@
+var benchmark = require('benchmark')
+var suite = new benchmark.Suite()
+
+global.NewBuffer = require('../../').Buffer // native-buffer-browserify
+
+var LENGTH = 10
+
+suite.add('NewBuffer#new', function () {
+  var buf = NewBuffer(LENGTH)
+})
+.add('Uint8Array#new', function () {
+  var buf = new Uint8Array(LENGTH)
+})
+.on('error', function (event) {
+  console.error(event.target.error.stack)
+})
+.on('cycle', function (event) {
+  console.log(String(event.target))
+})
+
+.run({ 'async': true })

+ 26 - 0
perf/solo/readDoubleBE.js

@@ -0,0 +1,26 @@
+var benchmark = require('benchmark')
+var suite = new benchmark.Suite()
+
+global.NewBuffer = require('../../').Buffer // native-buffer-browserify
+
+var LENGTH = 10
+
+var newTarget = NewBuffer(LENGTH * 8)
+
+for (var i = 0; i < LENGTH; i++) {
+  newTarget.writeDoubleBE(97.1919 + i, i * 8)
+}
+
+suite.add('NewBuffer#readDoubleBE', function () {
+  for (var i = 0; i < LENGTH; i++) {
+    var x = newTarget.readDoubleBE(i * 8)
+  }
+})
+.on('error', function (event) {
+  console.error(event.target.error.stack)
+})
+.on('cycle', function (event) {
+  console.log(String(event.target))
+})
+
+.run({ 'async': true })

+ 26 - 0
perf/solo/readFloatBE.js

@@ -0,0 +1,26 @@
+var benchmark = require('benchmark')
+var suite = new benchmark.Suite()
+
+global.NewBuffer = require('../../').Buffer // native-buffer-browserify
+
+var LENGTH = 10
+
+var newTarget = NewBuffer(LENGTH * 4)
+
+for (var i = 0; i < LENGTH; i++) {
+  newTarget.writeFloatBE(97.1919 + i, i * 4)
+}
+
+suite.add('NewBuffer#readFloatBE', function () {
+  for (var i = 0; i < LENGTH; i++) {
+    var x = newTarget.readFloatBE(i * 4)
+  }
+})
+.on('error', function (event) {
+  console.error(event.target.error.stack)
+})
+.on('cycle', function (event) {
+  console.log(String(event.target))
+})
+
+.run({ 'async': true })

+ 26 - 0
perf/solo/readUInt32BE.js

@@ -0,0 +1,26 @@
+var benchmark = require('benchmark')
+var suite = new benchmark.Suite()
+
+global.NewBuffer = require('../../').Buffer // native-buffer-browserify
+
+var LENGTH = 20
+
+var newTarget = NewBuffer(LENGTH * 4)
+
+for (var i = 0; i < LENGTH; i++) {
+  newTarget.writeUInt32LE(7000 + i, i * 4)
+}
+
+suite.add('NewBuffer#readUInt32BE', function () {
+  for (var i = 0; i < LENGTH; i++) {
+    var x = newTarget.readUInt32BE(i * 4)
+  }
+})
+.on('error', function (event) {
+  console.error(event.target.error.stack)
+})
+.on('cycle', function (event) {
+  console.log(String(event.target))
+})
+
+.run({ 'async': true })

+ 26 - 0
perf/solo/readUInt32LE.js

@@ -0,0 +1,26 @@
+var benchmark = require('benchmark')
+var suite = new benchmark.Suite()
+
+global.NewBuffer = require('../../').Buffer // native-buffer-browserify
+
+var LENGTH = 20
+
+var newTarget = NewBuffer(LENGTH * 4)
+
+for (var i = 0; i < LENGTH; i++) {
+  newTarget.writeUInt32LE(7000 + i, i * 4)
+}
+
+suite.add('NewBuffer#readUInt32LE', function () {
+  for (var i = 0; i < LENGTH; i++) {
+    var x = newTarget.readUInt32LE(i * 4)
+  }
+})
+.on('error', function (event) {
+  console.error(event.target.error.stack)
+})
+.on('cycle', function (event) {
+  console.log(String(event.target))
+})
+
+.run({ 'async': true })

+ 20 - 0
perf/solo/slice.js

@@ -0,0 +1,20 @@
+var benchmark = require('benchmark')
+var suite = new benchmark.Suite()
+
+global.NewBuffer = require('../../').Buffer // native-buffer-browserify
+
+var LENGTH = 16
+
+var newBuf = NewBuffer(LENGTH)
+
+suite.add('NewBuffer#slice', function () {
+  var x = newBuf.slice(4)
+})
+.on('error', function (event) {
+  console.error(event.target.error.stack)
+})
+.on('cycle', function (event) {
+  console.log(String(event.target))
+})
+
+.run({ 'async': true })

+ 22 - 0
perf/solo/writeFloatBE.js

@@ -0,0 +1,22 @@
+var benchmark = require('benchmark')
+var suite = new benchmark.Suite()
+
+global.NewBuffer = require('../../').Buffer // native-buffer-browserify
+
+var LENGTH = 10
+
+var newTarget = NewBuffer(LENGTH * 4)
+
+suite.add('NewBuffer#writeFloatBE', function () {
+  for (var i = 0; i < LENGTH; i++) {
+    newTarget.writeFloatBE(97.1919 + i, i * 4)
+  }
+})
+.on('error', function (event) {
+  console.error(event.target.error.stack)
+})
+.on('cycle', function (event) {
+  console.log(String(event.target))
+})
+
+.run({ 'async': true })

+ 164 - 0
test/basic.js

@@ -0,0 +1,164 @@
+var B = require('../').Buffer
+var test = require('tape')
+
+test('new buffer from array', function (t) {
+  t.equal(
+    new B([1, 2, 3]).toString(),
+    '\u0001\u0002\u0003'
+  )
+  t.end()
+})
+
+test('new buffer from string', function (t) {
+  t.equal(
+    new B('hey', 'utf8').toString(),
+    'hey'
+  )
+  t.end()
+})
+
+test('new buffer from buffer', function (t) {
+  var b1 = new B('asdf')
+  var b2 = new B(b1)
+  t.equal(b1.toString('hex'), b2.toString('hex'))
+  t.end()
+})
+
+test('new buffer from uint8array', function (t) {
+  if (typeof Uint8Array !== 'undefined') {
+    var b1 = new Uint8Array([0, 1, 2, 3])
+    var b2 = new B(b1)
+    t.equal(b1.length, b2.length)
+    t.equal(b1[0], 0)
+    t.equal(b1[1], 1)
+    t.equal(b1[2], 2)
+    t.equal(b1[3], 3)
+    t.equal(b1[4], undefined)
+  }
+  t.end()
+})
+
+test('new buffer from uint16array', function (t) {
+  if (typeof Uint16Array !== 'undefined') {
+    var b1 = new Uint16Array([0, 1, 2, 3])
+    var b2 = new B(b1)
+    t.equal(b1.length, b2.length)
+    t.equal(b1[0], 0)
+    t.equal(b1[1], 1)
+    t.equal(b1[2], 2)
+    t.equal(b1[3], 3)
+    t.equal(b1[4], undefined)
+  }
+  t.end()
+})
+
+test('new buffer from uint32array', function (t) {
+  if (typeof Uint32Array !== 'undefined') {
+    var b1 = new Uint32Array([0, 1, 2, 3])
+    var b2 = new B(b1)
+    t.equal(b1.length, b2.length)
+    t.equal(b1[0], 0)
+    t.equal(b1[1], 1)
+    t.equal(b1[2], 2)
+    t.equal(b1[3], 3)
+    t.equal(b1[4], undefined)
+  }
+  t.end()
+})
+
+test('new buffer from int16array', function (t) {
+  if (typeof Int16Array !== 'undefined') {
+    var b1 = new Int16Array([0, 1, 2, 3])
+    var b2 = new B(b1)
+    t.equal(b1.length, b2.length)
+    t.equal(b1[0], 0)
+    t.equal(b1[1], 1)
+    t.equal(b1[2], 2)
+    t.equal(b1[3], 3)
+    t.equal(b1[4], undefined)
+  }
+  t.end()
+})
+
+test('new buffer from int32array', function (t) {
+  if (typeof Int32Array !== 'undefined') {
+    var b1 = new Int32Array([0, 1, 2, 3])
+    var b2 = new B(b1)
+    t.equal(b1.length, b2.length)
+    t.equal(b1[0], 0)
+    t.equal(b1[1], 1)
+    t.equal(b1[2], 2)
+    t.equal(b1[3], 3)
+    t.equal(b1[4], undefined)
+  }
+  t.end()
+})
+
+test('new buffer from float32array', function (t) {
+  if (typeof Float32Array !== 'undefined') {
+    var b1 = new Float32Array([0, 1, 2, 3])
+    var b2 = new B(b1)
+    t.equal(b1.length, b2.length)
+    t.equal(b1[0], 0)
+    t.equal(b1[1], 1)
+    t.equal(b1[2], 2)
+    t.equal(b1[3], 3)
+    t.equal(b1[4], undefined)
+  }
+  t.end()
+})
+
+test('new buffer from float64array', function (t) {
+  if (typeof Float64Array !== 'undefined') {
+    var b1 = new Float64Array([0, 1, 2, 3])
+    var b2 = new B(b1)
+    t.equal(b1.length, b2.length)
+    t.equal(b1[0], 0)
+    t.equal(b1[1], 1)
+    t.equal(b1[2], 2)
+    t.equal(b1[3], 3)
+    t.equal(b1[4], undefined)
+  }
+  t.end()
+})
+
+test('buffer toArrayBuffer()', function (t) {
+  var data = [1, 2, 3, 4, 5, 6, 7, 8]
+  if (typeof Uint8Array !== 'undefined') {
+    var result = new B(data).toArrayBuffer()
+    var expected = new Uint8Array(data).buffer
+    for (var i = 0; i < expected.byteLength; i++) {
+      t.equal(result[i], expected[i])
+    }
+  } else {
+    t.pass('No toArrayBuffer() method provided in old browsers')
+  }
+  t.end()
+})
+
+test('buffer toJSON()', function (t) {
+  var data = [1, 2, 3, 4]
+  t.deepEqual(
+    new B(data).toJSON(),
+    { type: 'Buffer', data: [1,2,3,4] }
+  )
+  t.end()
+})
+
+test('buffer copy example', function (t) {
+  var buf1 = new B(26)
+  var buf2 = new B(26)
+
+  for (var i = 0 ; i < 26 ; i++) {
+    buf1[i] = i + 97; // 97 is ASCII a
+    buf2[i] = 33; // ASCII !
+  }
+
+  buf1.copy(buf2, 8, 16, 20)
+
+  t.equal(
+    buf2.toString('ascii', 0, 25),
+    '!!!!!!!!qrst!!!!!!!!!!!!!'
+  )
+  t.end()
+})

+ 268 - 0
test/buffer.js

@@ -0,0 +1,268 @@
+var B = require('../').Buffer
+var test = require('tape')
+
+test('utf8 buffer to base64', function (t) {
+  t.equal(
+    new B('Ձאab', 'utf8').toString('base64'),
+    '1YHXkGFi'
+  )
+  t.end()
+})
+
+test('utf8 buffer to hex', function (t) {
+  t.equal(
+    new B('Ձאab', 'utf8').toString('hex'),
+    'd581d7906162'
+  )
+  t.end()
+})
+
+test('utf8 to utf8', function (t) {
+  t.equal(
+    new B('öäüõÖÄÜÕ', 'utf8').toString('utf8'),
+    'öäüõÖÄÜÕ'
+  )
+  t.end()
+})
+
+test('utf16le to utf16', function (t) {
+    t.equal(
+        new B(new B('abcd', 'utf8').toString('utf16le'), 'utf16le').toString('utf8'),
+        'abcd'
+    )
+    t.end()
+})
+
+test('utf16le to hex', function (t) {
+    t.equal(
+        new B('abcd', 'utf16le').toString('hex'),
+        '6100620063006400'
+    )
+    t.end()
+})
+
+test('ascii buffer to base64', function (t) {
+  t.equal(
+    new B('123456!@#$%^', 'ascii').toString('base64'),
+    'MTIzNDU2IUAjJCVe'
+  )
+  t.end()
+})
+
+test('ascii buffer to hex', function (t) {
+  t.equal(
+    new B('123456!@#$%^', 'ascii').toString('hex'),
+    '31323334353621402324255e'
+  )
+  t.end()
+})
+
+test('base64 buffer to utf8', function (t) {
+  t.equal(
+    new B('1YHXkGFi', 'base64').toString('utf8'),
+    'Ձאab'
+  )
+  t.end()
+})
+
+test('hex buffer to utf8', function (t) {
+  t.equal(
+    new B('d581d7906162', 'hex').toString('utf8'),
+    'Ձאab'
+  )
+  t.end()
+})
+
+test('base64 buffer to ascii', function (t) {
+  t.equal(
+    new B('MTIzNDU2IUAjJCVe', 'base64').toString('ascii'),
+    '123456!@#$%^'
+  )
+  t.end()
+})
+
+test('hex buffer to ascii', function (t) {
+  t.equal(
+    new B('31323334353621402324255e', 'hex').toString('ascii'),
+    '123456!@#$%^'
+  )
+  t.end()
+})
+
+test('base64 buffer to binary', function (t) {
+  t.equal(
+    new B('MTIzNDU2IUAjJCVe', 'base64').toString('binary'),
+    '123456!@#$%^'
+  )
+  t.end()
+})
+
+test('hex buffer to binary', function (t) {
+  t.equal(
+    new B('31323334353621402324255e', 'hex').toString('binary'),
+    '123456!@#$%^'
+  )
+  t.end()
+})
+
+test('utf8 to binary', function (t) {
+  t.equal(
+    new B('öäüõÖÄÜÕ', 'utf8').toString('binary'),
+    'öäüõÖÄÜÕ'
+  )
+  t.end()
+})
+
+test('hex of write{Uint,Int}{8,16,32}{LE,BE}', function (t) {
+  t.plan(2*(2*2*2+2))
+  var hex = [
+    '03', '0300', '0003', '03000000', '00000003',
+    'fd', 'fdff', 'fffd', 'fdffffff', 'fffffffd'
+  ]
+  var reads = [ 3, 3, 3, 3, 3, -3, -3, -3, -3, -3 ]
+  var xs = ['UInt','Int']
+  var ys = [8,16,32]
+  for (var i = 0; i < xs.length; i++) {
+    var x = xs[i]
+    for (var j = 0; j < ys.length; j++) {
+      var y = ys[j]
+      var endianesses = (y === 8) ? [''] : ['LE','BE']
+      for (var k = 0; k < endianesses.length; k++) {
+        var z = endianesses[k]
+
+        var v1  = new B(y / 8)
+        var writefn  = 'write' + x + y + z
+        var val = (x === 'Int') ? -3 : 3
+        v1[writefn](val, 0)
+        t.equal(
+          v1.toString('hex'),
+          hex.shift()
+        )
+        var readfn = 'read' + x + y + z
+        t.equal(
+          v1[readfn](0),
+          reads.shift()
+        )
+      }
+    }
+  }
+  t.end()
+})
+
+test('hex of write{Uint,Int}{8,16,32}{LE,BE} with overflow', function (t) {
+    t.plan(3*(2*2*2+2))
+    var hex = [
+      '', '03', '00', '030000', '000000',
+      '', 'fd', 'ff', 'fdffff', 'ffffff'
+    ]
+    var reads = [
+      undefined, 3, 0, 3, 0,
+      undefined, 253, -256, 16777213, -256
+    ]
+    var xs = ['UInt','Int']
+    var ys = [8,16,32]
+    for (var i = 0; i < xs.length; i++) {
+      var x = xs[i]
+      for (var j = 0; j < ys.length; j++) {
+        var y = ys[j]
+        var endianesses = (y === 8) ? [''] : ['LE','BE']
+        for (var k = 0; k < endianesses.length; k++) {
+          var z = endianesses[k]
+
+          var v1  = new B(y / 8 - 1)
+          var next = new B(4)
+          next.writeUInt32BE(0, 0)
+          var writefn  = 'write' + x + y + z
+          var val = (x === 'Int') ? -3 : 3
+          v1[writefn](val, 0, true)
+          t.equal(
+            v1.toString('hex'),
+            hex.shift()
+          )
+          // check that nothing leaked to next buffer.
+          t.equal(next.readUInt32BE(0), 0)
+          // check that no bytes are read from next buffer.
+          next.writeInt32BE(~0, 0)
+          var readfn = 'read' + x + y + z
+          t.equal(
+            v1[readfn](0, true),
+            reads.shift()
+          )
+        }
+      }
+    }
+    t.end()
+})
+
+test('concat() a varying number of buffers', function (t) {
+  var zero = []
+  var one  = [ new B('asdf') ]
+  var long = []
+  for (var i = 0; i < 10; i++) long.push(new B('asdf'))
+
+  var flatZero = B.concat(zero)
+  var flatOne = B.concat(one)
+  var flatLong = B.concat(long)
+  var flatLongLen = B.concat(long, 40)
+
+  t.equal(flatZero.length, 0)
+  t.equal(flatOne.toString(), 'asdf')
+  t.equal(flatOne, one[0])
+  t.equal(flatLong.toString(), (new Array(10+1).join('asdf')))
+  t.equal(flatLongLen.toString(), (new Array(10+1).join('asdf')))
+  t.end()
+})
+
+test('fill', function(t) {
+  var b = new B(10)
+  b.fill(2)
+  t.equal(b.toString('hex'), '02020202020202020202')
+  t.end()
+})
+
+test('copy() empty buffer with sourceEnd=0', function (t) {
+  var source = new B([42])
+  var destination = new B([43])
+  source.copy(destination, 0, 0, 0)
+  t.equal(destination.readUInt8(0), 43)
+  t.end()
+})
+
+test('copy() after slice()', function(t) {
+  var source = new B(200)
+  var dest = new B(200)
+  var expected = new B(200)
+  for (var i = 0; i < 200; i++) {
+    source[i] = i
+    dest[i] = 0
+  }
+
+  source.slice(2).copy(dest)
+  source.copy(expected, 0, 2)
+  t.deepEqual(dest, expected)
+  t.end()
+})
+
+test('base64 ignore whitespace', function(t) {
+  var text = '\n   YW9ldQ==  '
+  var buf = new B(text, 'base64')
+  t.equal(buf.toString(), 'aoeu')
+  t.end()
+})
+
+test('buffer.slice sets indexes', function (t) {
+  t.equal((new B('hallo')).slice(0, 5).toString(), 'hallo')
+  t.end()
+})
+
+test('buffer.slice out of range', function (t) {
+  t.plan(2)
+  t.equal((new B('hallo')).slice(0, 10).toString(), 'hallo')
+  t.equal((new B('hallo')).slice(10, 2).toString(), '')
+  t.end()
+})
+
+test('base64 strings without padding', function (t) {
+  t.equal((new B('YW9ldQ', 'base64').toString()), 'aoeu')
+  t.end()
+})

+ 18 - 0
test/deprecated.js

@@ -0,0 +1,18 @@
+var B = require('../').Buffer
+var test = require('tape')
+
+test('.get (deprecated)', function (t) {
+  var b = new B([7, 42])
+  t.equal(b.get(0), 7)
+  t.equal(b.get(1), 42)
+  t.end()
+})
+
+test('.set (deprecated)', function (t) {
+  var b = new B(2)
+  b.set(7, 0)
+  b.set(42, 1)
+  t.equal(b[0], 7)
+  t.equal(b[1], 42)
+  t.end()
+})

+ 29 - 0
test/indexes.js

@@ -0,0 +1,29 @@
+var B = require('../').Buffer
+var test = require('tape')
+
+test('indexes from a string', function(t) {
+  var buf = new B('abc')
+  t.equal(buf[0], 97)
+  t.equal(buf[1], 98)
+  t.equal(buf[2], 99)
+  t.end()
+})
+
+test('indexes from an array', function(t) {
+  var buf = new B([ 97, 98, 99 ])
+  t.equal(buf[0], 97)
+  t.equal(buf[1], 98)
+  t.equal(buf[2], 99)
+  t.end()
+})
+
+test('set then modify indexes from an array', function(t) {
+  var buf = new B([ 97, 98, 99 ])
+  t.equal(buf[2], 99)
+  t.equal(buf.toString(), 'abc')
+
+  buf[2] += 10
+  t.equal(buf[2], 109)
+  t.equal(buf.toString(), 'abm')
+  t.end()
+})

+ 9 - 0
test/is-buffer.js

@@ -0,0 +1,9 @@
+var B = require('../').Buffer
+var test = require('tape')
+
+test('Buffer.isBuffer', function (t) {
+  t.equal(B.isBuffer(new B('hey', 'utf8')), true)
+  t.equal(B.isBuffer(new B([1, 2, 3], 'utf8')), true)
+  t.equal(B.isBuffer('hey'), false)
+  t.end()
+})

+ 9 - 0
test/is-encoding.js

@@ -0,0 +1,9 @@
+var B = require('../').Buffer
+var test = require('tape')
+
+test('Buffer.isEncoding', function (t) {
+  t.equal(B.isEncoding('HEX'), true)
+  t.equal(B.isEncoding('hex'), true)
+  t.equal(B.isEncoding('bad'), false)
+  t.end()
+})

+ 36 - 0
test/slice.js

@@ -0,0 +1,36 @@
+var B = require('../').Buffer
+var test = require('tape')
+
+test('modifying buffer created by .slice() modifies original memory', function (t) {
+  if (!B._useTypedArrays) return t.end()
+
+  var buf1 = new B(26)
+  for (var i = 0 ; i < 26 ; i++) {
+    buf1[i] = i + 97 // 97 is ASCII a
+  }
+
+  var buf2 = buf1.slice(0, 3)
+  t.equal(buf2.toString('ascii', 0, buf2.length), 'abc')
+
+  buf2[0] = '!'.charCodeAt(0)
+  t.equal(buf1.toString('ascii', 0, buf2.length), '!bc')
+
+  t.end()
+})
+
+test('modifying parent buffer modifies .slice() buffer\'s memory', function (t) {
+  if (!B._useTypedArrays) return t.end()
+
+  var buf1 = new B(26)
+  for (var i = 0 ; i < 26 ; i++) {
+    buf1[i] = i + 97 // 97 is ASCII a
+  }
+
+  var buf2 = buf1.slice(0, 3)
+  t.equal(buf2.toString('ascii', 0, buf2.length), 'abc')
+
+  buf1[0] = '!'.charCodeAt(0)
+  t.equal(buf2.toString('ascii', 0, buf2.length), '!bc')
+
+  t.end()
+})

+ 33 - 0
test/utf16.js

@@ -0,0 +1,33 @@
+var B = require('../').Buffer
+var test = require('tape')
+
+test('detect utf16 surrogate pairs', function(t) {
+  var text = '\uD83D\uDE38' + '\uD83D\uDCAD' + '\uD83D\uDC4D'
+  var buf = new B(text)
+  t.equal(text, buf.toString())
+  t.end()
+})
+
+test('throw on orphaned utf16 surrogate lead code point', function(t) {
+  var text = '\uD83D\uDE38' + '\uD83D' + '\uD83D\uDC4D'
+  var err
+  try {
+    var buf = new B(text)
+  } catch (e) {
+    err = e
+  }
+  t.equal(err instanceof URIError, true)
+  t.end()
+})
+
+test('throw on orphaned utf16 surrogate trail code point', function(t) {
+  var text = '\uD83D\uDE38' + '\uDCAD' + '\uD83D\uDC4D'
+  var err
+  try {
+    var buf = new B(text)
+  } catch (e) {
+    err = e
+  }
+  t.equal(err instanceof URIError, true)
+  t.end()
+})

Nem az összes módosított fájl került megjelenítésre, mert túl sok fájl változott