#!/usr/bin/muawk
# rustic sort 
# modified by mawk package

BEGIN	{
	n=split(arg,opts);

	# parse options

	field=0 
	i=1

	while ( i <= n )
	{
	if ( match(opts[i],"-[0-9]") !=0 ) { field=-opts[i]; i++ }

	if ( opts[i] == "-h" )
		{
		print "(rustic) sort: sort lines from stdin"
		print "\tUsage: sort [-field]"
		exit
		}	
	}

	}

	{ line[NR]=$0 "" }

END	{ isort(line,NR);
	for (i=1; i<=NR; i++) print line[i];
	}

function isort(A,n,  i,j,hold) 
{
	for (i=2; i<=n; i++)
	{
	hold=A[j=i];
	while ( compare(A[j-1],hold,field) )  { j--; A[j+1]=A[j] }
	A[j]=hold;
	}

}

function compare(x,y,f)
{
if (f==0 )  return (x>y)
else
	{
	split(x,X); split(y,Y);
	return ( X[f] > Y[f] )
	}
}
