## sort [-r] [-i] [-u] file...
#
var stdout = "/dev/stdout"
var stderr = "/dev/stderr"
val list = new ArrayList()
BEGIN {
	reverse = ignoreCase = unique = ""; option(1); option(2); option(3)
}
	{
	var key = $0; gsub("[\n\t]", "\r", key)
	if (ignoreCase != "") key = tolower(key)
	list.add(key "\n" $0)
}
END {
	Collections.sort(list)
	z = "\t"
	if (reverse == "") {
	  for (x in list)
	    printList(x)
	} else {
	  for (i = list.size() - 1; i >= 0; i--)
	    printList(list.get(i))
	}
	print ".sort", ignoreCase, unique, reverse, "processed I/O", NR ",", output, "lines." >stderr
}
function printList(x) {
	if (x != z || unique == "") {
	  var w = x; sub(/^[^\n]*\n/, "", w)
	  print w >stdout
	  output += 1
	}
	z = x
}
function option(i) {
	if (ARGV[i] == "-r") {
	  reverse = ARGV[i]; ARGV[i] = ""
	} else if (ARGV[i] == "-i") {
	  ignoreCase = ARGV[i]; ARGV[i] = ""
	} else if (ARGV[i] == "-u") {
	  unique = ARGV[i]; ARGV[i] = ""
	}
}