/* compile with diet -Os gcc -W -Wall -s random.c -o random -lowfat
 * usage:
 * random <high>
 *      prints a random integer between 0 and <high> (exclusive)
 * random <low> <high>
 *      prints a random integer between <low> (inclusive) and <high> (exclusive)
 *      here <high> needs to be bigger than <low>
 *
 * returns non-zero on error.
 */

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
void err(char *s);

int main(int argc, char **argv)
{
	unsigned long low=0, high, rand;
	char *phigh=argv[1];
	char buf[50];
	char *p=buf;
	int fd;

	if(argc != 2 && argc != 3){
		err("error: one or two arguments required\n");
		return 1;
	}
	
	fd = open("/dev/urandom", O_RDONLY);
	if(fd <= 0){
		err("error: open() failed for /dev/urandom\n");
		return 2;
	}

	if( read(fd, &rand, sizeof(rand)) != sizeof(rand) ){
		err("error: read() failed\n");
		return 3;
	}
	

	if(argc == 3){
		scan_ulong(argv[1], &low);
		phigh = argv[2];
	}
	scan_ulong(phigh, &high);

	if(high <= low){
		err("error: high has to be bigger than low\nusage: \
random <low> [high]\n");
		return 4;
	}

	rand = rand % (high-low) + low;

	//p=buf already
	p+=fmt_ulong(buf, rand);
	*p++='\n';
	write(1, buf, p-buf);
	
	return 0;
}


void err(char *s)
{
	char *p=s;
	while(*p != '\0') p++;
	write(2, s, p-s);
}

