     i = ms_random_word() % pvec.length
     p = pvec[i]
     return p if (ft = fermat2_test(p)) and miller_rabin(p, iters)
-    l = pvec.length - 1
-    pvec[i] = pvec.pop()
+    tmp = pvec.pop()
+    pvec[i] = tmp if pvec.length
 
   return nbv(0)
 

fta = new Avg()
fermat2_test = (n) ->
  fta.start()
  t = nbv(1)
  bl = n.bitLength()
  bl--
  for i in [bl..0]
    t = t.modPowInt(2,n)
    #t = t.square()

    # .t in jsbn is equivalent to _mp_size in GNU bigint.  _mp_size
    # is the "number of limbs" in the bigint
    #if t.t > n.t

exports.miller_rabin = miller_rabin
exports.random_prime = random_prime

await random_prime 4096, 20, defer p
console.log p.toString()
console.log "avg -> #{fta.avg()}"
process.exit -1
