#!/perl -w
# numsort.pl
# AIM: Sort a file, taking the first columns as numbers ...
use strict;
use warnings;
require 'logfile.pl' or die "Unable to load logfile.pl ...\n";
# log file stuff
my ($LF);
my $outfile = 'temp.'.$0.'.txt';
open_log($outfile);
my $in_file = 'C:\dtemp\temp4.txt';
my $out_file = 'temp4s.txt';
my $line = '';
my $lncnt = 0;
# debug
my $verb3 = 0;

if (@ARGV) {
	$in_file = pop @ARGV;
}
if (@ARGV) {
	$out_file = pop @ARGV;
}
prt( "$0 - \$in_file = $in_file, \$out_file = $out_file ...\n" );

open INF, "<$in_file" or mydie( "ERROR: Can not open [$in_file]! ... $! ... check name, location ...\n" );
my @lines = <INF>;	# slurp it all in ...
close INF;
$lncnt = scalar @lines;
prt( "Processing $lncnt lines from [$in_file] ...\n" );
sortlines();
$lncnt = scalar @lines;
prt( "Outputting $lncnt lines to [$out_file] ...\n" );
open OUTF, ">$out_file" or mydie( "ERROR: Can not create out [$out_file]! ... $! ... check location ...\n" );
foreach $line (@lines) {
	print OUTF $line;
}
close OUTF;

close_log($outfile,1);
exit(0);

######################

sub sortlines {
	my @newlns = ();
	my ($len, $i, $ch, $num);
	foreach $line (@lines) {
		$len = length($line);
		$num = 0;
		for ($i = 0; $i < $len; $i++) {
			$ch = substr($line,$i,1);
			if ($ch =~ /\d/) {
				$num = ($num * 10) + $ch;
			} else {
				last;
			}
		}
		push(@newlns, [$num, $line]);
	}
	my @sarr = sort mycmp_ascend @newlns;
	$len = scalar @sarr;
	@lines = ();
	for ($i = 0; $i < $len; $i++) {
		$line = $sarr[$i][1];
		push(@lines, $line);
	}
}


# put least first
sub mycmp_ascend {
	if (${$a}[0] < ${$b}[0]) {
		prt( "-[".${$a}[0]."] < [".${$b}[0]."]\n" ) if $verb3;
		return -1;
	}
	if (${$a}[0] > ${$b}[0]) {
		prt( "+[".${$a}[0]."] < [".${$b}[0]."]\n" ) if $verb3;
		return 1;
	}
	prt( "=[".${$a}[0]."] < [".${$b}[0]."]\n" ) if $verb3;
	return 0;
}

# eof
