var Base58 = Base58Utils = require('../lib/base58')
var Ripple = require('ripple-lib');
var sjcl = Ripple.sjcl;

var RippleWallet = (function () {
  function append_int(a, i) {
    return [].concat(a, i >> 24, (i >> 16) & 0xff, (i >> 8) & 0xff, i & 0xff)
  }

  function firstHalfOfSHA512(bytes) {
    return sjcl.bitArray.bitSlice(
      sjcl.hash.sha512.hash(sjcl.codec.bytes.toBits(bytes)),
      0, 256
    );
  }

  function SHA256_RIPEMD160(bits) {
    return sjcl.hash.ripemd160.hash(sjcl.hash.sha256.hash(bits));
  }

  return function (seed) {
    this.seed = Base58Utils.decode_base_check(33, seed);

    if (!this.seed) {
      throw "Invalid seed."
    }

    this.getAddress = function (seq) {
      seq = seq || 0;

      var private_gen, public_gen, i = 0;
      do {
        private_gen = sjcl.bn.fromBits(firstHalfOfSHA512(append_int(this.seed, i)));
        i++;
      } while (!sjcl.ecc.curves.c256.r.greaterEquals(private_gen));

      public_gen = sjcl.ecc.curves.c256.G.mult(private_gen);

      var sec;
      i = 0;
      do {
        sec = sjcl.bn.fromBits(firstHalfOfSHA512(append_int(append_int(public_gen.toBytesCompressed(), seq), i)));
        i++;
      } while (!sjcl.ecc.curves.c256.r.greaterEquals(sec));

      var pubKey = sjcl.ecc.curves.c256.G.mult(sec).toJac().add(public_gen).toAffine();

      return Base58Utils.encode_base_check(0, sjcl.codec.bytes.fromBits(SHA256_RIPEMD160(sjcl.codec.bytes.toBits(pubKey.toBytesCompressed()))));
    };
  };
})();

RippleWallet.generate = function() {
  for (var i = 0; i < 8; i++) {
    sjcl.random.addEntropy(Math.random(), 32, "Math.random()");
  }

  var masterkey = Base58.encode_base_check(33, sjcl.codec.bytes.fromBits(sjcl.random.randomWords(4)))
  address = new RippleWallet(masterkey)

  return {
    address: address.getAddress(),
    secret: masterkey 
  }
}

Ripple.Wallet = RippleWallet;
exports.Ripple = Ripple;


@@ -768,32 +768,104 @@
 = 0;%0A      do %7B%0A
+        // Compute the hash of the 128-bit seed and the sequence number%0A
         private_
@@ -956,70 +956,267 @@
     
-%7D while (!sjcl.ecc.curves.c256.r.greaterEquals(private_gen));%0A
+  // If the hash is equal to or greater than the SECp256k1 order, increment sequence and try agin%0A      %7D while (!sjcl.ecc.curves.c256.r.greaterEquals(private_gen));%0A%0A      // Compute the public generator using from the private generator on the elliptic curve
 %0A   
@@ -1893,16 +1893,130 @@
 );%0A  %7D%0A%0A
+  // Generate a 128-bit master key that can be used to make any number of private / public key pairs and accounts%0A
   var ma

Add comments to explain ECC key generation