use math::random;
use fmt;
use time;
use getopt;
use os;
use strconv;
use sort;
use sort::cmp;

export fn main() void = {
	const cmd = getopt::parse(os::args,
		"Random Number Generator",
		('n', "number", "Number of random numbers to print (default: 6)"),
		('m', "max", "Max number than can be generated (default: 110)"),
		('s', "Sort the numbers"),
		('d', "Avoid duplicates"));
	defer getopt::finish(&cmd);

	let nb = 6z;
	let max = 110u32;
	let dosort = false;
	let nodups = false;
	for (let opt .. cmd.opts) {
		switch (opt.0) {
		case 'n' =>
			nb = strconv::stoz(opt.1)!;
		case 'm' =>
			max = strconv::stou32(opt.1)!;
		case 's' =>
			dosort = true;
		case 'd' =>
			nodups = true;
		case => abort();
		};
	};

	if (nodups && max < nb) {
		fmt::fatal("Can't generate the desired number of randoms without duplicates");
	};

	let seed = time::unix(time::now(time::clock::MONOTONIC));
	let r = random::init(seed: u32);
	let rngs: []u32 = [];
	defer free(rngs);
	for (let i = 0z; i < nb; i+= 1) {
		let a = random::u32n(&r, max) + 1;
		for (nodups && contains(rngs, a)) {
			a = random::u32n(&r, max) + 1;
		};
		append(rngs, a);
	};

	if (dosort) {
		sort::sort(rngs: []opaque, size(u32), &cmp::u32s);
	};

	for (let rng .. rngs) {
		fmt::printfln("{}", rng)!;
	};
};

fn contains(a: []u32, b: u32) bool = {
	for (const l .. a) {
		if (l == b) {
			return true;
		};
	};
	return false;
};
