#!PERL
#       sortdb.pl - sort the database, based on the unique keys
#			uses the SORT field in the object from the
#			config file
#
#	$RCSfile: sortdb.pl,v $
#	$Revision: 0.17 $
#	$Author: marten $
#	$Date: 1994/09/20 12:35:25 $
#

@INC = ("LIBDIR", @INC);

require "dbopen.pl";
require "dbclose.pl";
require "enread.pl";
require "enwrite.pl";
require "dbmatch.pl";
require "rconf.pl";
require "misc.pl";

sub mysort {
    if ($a =~ /[0-9]+\.[0-9]+\./) {
	&quad2int($a) <=> &quad2int($b);
    }
    elsif ($a =~ /as[0-9]+/) {
	substr($a, 2) <=> substr($b,2);
    }
    else {
	$a cmp $b;
    }
}

# Read config file from RIPEDBCNF, or set to default.

$conffile=$ENV{"RIPEDBCNF"};
$conffile= "DEFCONFIG" unless $conffile;
&rconf($conffile);

local(*a) = 'boe';
%nothing = ();
&dbopen(a, *nothing, 1, $ARGV[0]) || die "Cannot open $ARGV[0]";

while (($k, $v) = each %a) {
    if ($k =~ s/^%([0-9])//) {
	local($first, $second) = split(/\t/, $k);
	$new = join("", reverse split(/(\S+)/, $first));
	$new .= "\t".$second;
	eval "\$array$1[\$index$1] = \"$new\";";
	eval "\$index$1++;";
	$seen{"$1"} = 1;
    }
}

@keys = sort keys(%seen);

# Print generation date to STDOUT

local($s,$m,$h,$md,$mo,$y,$wd,$yd,$is) = localtime(time);

$mo+=1;

$mo = "0".$mo unless $mo > 9;
$md = "0".$md unless $md > 9;
$s = "0".$s unless $s > 9;
$m = "0".$m unless $m > 9;
$h = "0".$h unless $h > 9;

print "#\n# $y$mo$md $h:$m:$s\n#\n";

# Print the copyright notice to STDOUT

local(@rights) = split(/\n/, $RIGHTS);
foreach $m (@rights) {
    print "# ".$m."\n";
}
print "\n";


for $i (0..$#keys) {
    eval "\@aap = sort mysort \@array$keys[$i];";
    for $j (0..$#aap) {
	local($first, $second) = split(/\t/, $aap[$j],2);
	$new = join("", reverse split(/(\S+)/, $first));
	if ($second) {
	    $new .= "\t".$second;
	}
	$yo[0] = "%$keys[$i]".$new;
	local(@matches) = &dbmatch(*a, @yo);
	%en = &enread(a, $matches[0]);
	&enwrite(*en);
	print "\n";
    }
}


&dbclose(*a);
