/*
 * Use ARC4 to generate large random numbers
 *
 * Bart 1999/2
 */

namespace PRNG {

  global int setkey = 0;

  public void function srandom(int s) {
    ARC4::nsetkey(10, s);
    setkey = 1;
  }

  /* returns an n-*bit* random number in 0..(2**n)-1 */
  public int function randbits(int n) {
    int q = n >> 3;
    int r = n & 7;
    if (!setkey)
      srandom(0);
    int acc = ARC4::streambyte() >> (8 - r);
    while (q > 0) {
      --q;
      acc += ARC4::streambyte() << (8 * q + r);
    }
    return acc;
  }

  /* returns a random integer in the range 0..n-1 */
  public int function randint(int n) {
    return randbits(32 + bit_width (n)) % n;
  }

}
