/*
 * Copyright © 1999 Bart Massey.
 * All Rights Reserved.  See the file COPYING in this directory
 * for licensing information.
 */

/*
 * Implementation of Alleged RC4
 *
 * Bart 1999/2
 * 
 * Used primarily for PRNG, so interface is not too fancy
 */

namespace ARC4 {

  global int[256] state = {};
  global int p1, p2;

  public void nsetkey(int nn, int k) 
    /*
     * First argument is number of times to iterate the
     * initial scramble.  10 seems good for most apps.
     * Second argument is integer key: largest useful key is
     * 8 * 62 bits.
     */
  {
    int i, j, n, ii;
    int[64] key = {};

    key[0] = 13;
    key[1] = 17;
    for (n = 2; n < 64 && k > 0; n++) {
      key[n] = k & 0xff;
      k = k >> 8;
    }

    for (i = 0; i < 256; i++)
      state[i] = i;

    for (ii = 0; ii < nn; ii++) {
      j = 0;
      for (i = 0; i < 256; i++) {
        j = (j + state[i] + key[i % n]) & 0xff;
	int tmp = state[i];
	state[i] = state[j];
	state[j] = tmp;
      }
    }
    p1 = p2 = 0;
  }

  public int streambyte() 
    /*
     * Get the next byte from the stream 
     */
  {
    p1 = (p1 + 1) & 0xff;
    p2 = (p2 + state[p1]) & 0xff;
    int tmp = state[p1];
    state[p1] = state[p2];
    state[p2] = tmp;
    int n = (state[p1] + state[p2]) & 0xff;
    return state[n];
  }
  
}
