short mask[] = {
	01, 02, 04, 010, 020, 040, 0100, 0200, 0400,
	01000, 02000, 04000, 010000, 020000, 040000,
	0100000
};

struct {
	char is, os, er, ki;
	short tmode;
} tty, otty;

short dir, way;
int intr();
short count = 0;

main(c, argv)
char **argv;
{
	register short v;
	long i;
	long sleeper;


	if(c != 2)sleeper = 10000;
	else sleeper = (long)(atoi(*++argv));
	v = 0;
	signal(2, intr);
	gtty(0, &otty);
	gtty(0, &tty);
	while(1){
		v = next(v);
		tty.tmode = v;
		for(i = 0; i < sleeper; i++,i--,i++);
		stty(0, &tty);
		count++;
	}
}

intr()
{
	stty(0, &otty);
	printf("Final count = %u\n", count);
	exit();
}


next(v)
register short v;
{
	register short i;

	if(v == -1){
		dir = 1;
		way = 0;
		return(077777);
	}

	if(v == 0){
		dir = 0;
		way = 1;
		return(1);
	}

	if(dir){
		i = getr(v);
		v |= mask[i];
		if(way){
			if(i == 15){
				way = 0;
				return(v & ~mask[15]);
			}
			return(v & ~mask[i+1]);
		}
		if(i == 0 || (v & mask[i-1]) == 0){
			way = 1;
			if(i < 15)
				return((v & ~(mask[i] | mask[i+1])));
			printf("can't happen 1\n");
			intr();
		}
		return(v & ~mask[i-1]);
	}
	i = getl(v);
	v &= ~mask[i];
	if(way){
		if(i == 15){
			way = 0;
			return(v | mask[i] | mask[14]);
		}
		if(v & mask[i+1]){
			way = 0;
			if(i)return(v | mask[i] | mask[i-1]);
			printf("can't happen 2\n");
			intr();
		}
		return(v | mask[i+1]);
	}
	if(i) return(v | mask[i-1]);
	way = 1;
	return(v | 1);
}


getl(v)
register short v;
{
	register short i;

	for(i = 0; i < 16; i++)
		if(v & mask[i])return(i);
	printf("getl bug\n");
	intr();
}

getr(v)
register short v;
{
	register short i;

	for(i = 15; i >= 0; i--)
		if((v & mask[i]) == 0)return(i);
	printf("getr bug\n");
	intr();
}


output(v)
register short v;
{
	register short i;

	for(i = 15; i >= 0; i--)
		printf("%c", v & mask[i] ? '1' : '0');
	printf("\n");
}

