#include <stdlib.h>

#define SIZE 256
#define PSIZ 8

int main() {
  char data[SIZE + 1];
  long xptr = 0;
  long cptr;
  long c, i = 1000;
  unsigned long test = 0, pattern;
  long unchanged = 0;
  unsigned maxfound = 0;

  /*  printf("Code-- %d bits: ", SIZE);
      scanf("%s", data); 
      for (c = 0; c < SIZE; c++) {
      if (data[c] == '1')
      data[c] = 1;
      else
      data[c] = 0;
      }*/

  srand(UNIQUE);

  while (test < 2147483648L) {
    /* pattern = 2147483648L; */
    for (c = 0; c < SIZE; c++) {
      data[c] = rand() % 2; /* (test % pattern) / (pattern / 2);
			       pattern /= 2; */
    }
    for (c = 0; c < SIZE; c++)
      printf("%d", data[c]);
    printf(" ->\n");

    i = 1000;
    unchanged = 0;
    while (i--) {
      /* Jump to *xptr (if last command was 1, jump is to next command) */
      cptr = 0;
      for (c = 0; c < PSIZ; c++)
	cptr = cptr * 2 + data[(xptr + c) % SIZE];
      
      if (data[cptr]) { /* 1: *xptr++ */
	c = xptr + PSIZ - 1;
	data[c % SIZE]++;
	while (data[c % SIZE] == 2) {
	  data[c % SIZE] = 0;
	  c--;
	  if (c < 0)
	    c = SIZE - 1;
	  data[c % SIZE]++;
	}
	unchanged = 0;
      } else { /* 0: xptr = cptr + 1 */
	xptr = (cptr + 1) % SIZE;
	unchanged++;
      }
      
      if (unchanged > SIZE)
	break;
    }

    for (c = 0; c < SIZE; c++)
      printf("%d", data[c]);
    printf(" (%d)\n", 1000 - i - unchanged);
    if (1000 - i - unchanged > maxfound)
      maxfound = 1000 - i - unchanged;
    
    printf("     - - - - %d - - - -     - - - - %d - - - - \n", maxfound, test);

    if (1000 - i - unchanged > 500)
      getchar();

    test++;
  }
}
    
/* 
.       .
0000 - 0000
^      ^
*/
/*
.       .       .      .      .     .        .    
0010 - 0010 - 0010 - 0011 - 0100 - 0100 - 0100 - done
^       ^       ^       ^   ^        ^    ^
*/
/*
.       .       .      .
0011 - 0011 - 0011 - 0100 - done
^       ^        ^   ^
*/
/*
.      .         .     .      .
0100 - 1000 - 1000 - 1000 - 1001 - done
 ^       ^     ^     ^       ^
*/
/*
.      .         .      .    .       .      .      .     .        .
0101 - 1001 - 1001 - 0010 - 0010 - 0010 - 0011 - 0100 - 0100 - 0100 - done
 ^       ^       ^   ^       ^       ^       ^   ^        ^    ^
*/
/*
.      .      .
0110 - 1010 - 1110 - done
 ^       ^       ^
*/

/*
0000xxxx, 00010000, 00010001, 00010010 - unchanged
00010011 -> 00010100
00010100 -> 01000000
00010101 -> 01011001
00010110 -> 01011000
00010111 -> 01001001
00011000 -> 01000000
00011001 -> 00100001
00011010 -> 00100011
*/
