#!/usr/bin/perl -w

use strict;

my %options = (-country=>0,-sects=>1,-eff=>2,-civ=>3,-mil=>4,-shell=>5,
	       -gun=>6,-pet=>7,-iron=>8,-dust=>9,-oil=>10,-pln=>11,-ship=>12,
	       -unit=>13,-money=>14,-score=>15,-help=>100,-version=>101,
	      );
my $option = $ARGV[0];


if (! $option) {
    print "Missing option!\n";
    print "Try 'power.pl -help' for usage information\n";
}
elsif (!defined $options{$option}) {
    print "Invalid option!\n";
    print "Try 'power.pl -help' for usage information\n";
}
elsif ($option eq '-help') {
    &usage(%options);
}
elsif ($option eq '-version') {
    print "power tool Version 1.0 by Roman M. Parparov <romm\@empire.tau.ac.il>\n";
}
elsif ($option eq '-score') {
    while (<STDIN>) {
	print;
    }
}
else {
    my $countries = 0;
    my $tail = '';
    my $restinfo;
    my @tmpgame = ();
    my @game = ();
    my @newgame = ();

    $option =~ s/^\-//;
    while (<STDIN>) {
	if ($countries == 0) {
	    if (/$option/) {
		$countries = 1;
	    }
	    print;
	    next;
	}
	elsif ($countries == 1) {
	    if (/          \-\-\-\-/) {
		$countries = 2;
		$tail .= $_;
	    }
	    else {
		$restinfo = substr($_,9);
		$restinfo =~ s/\s+//;
		@tmpgame = split (/\s+/,$restinfo);
		unshift(@tmpgame,substr($_,0,9));
#		$tmpgame[$options{-country}] = substr($_,0,9);
		$tmpgame[$options{-score}] = $_;
		push(@game,[@tmpgame])
	    }
	}
	else {
	    $tail .= $_;
	}
    }
    $option = '-' . $option;
    @newgame = sort {&tonumber(@$b[$options{$option}]) <=> &tonumber(@$a[$options{$option}])} @game;
    for (@newgame) {
	print @{$_}[$options{-score}];
    }
    print $tail;
}
sub usage {

    my %options = @_;

    print "Usage: power.pl -option < power_output\n";
    print "-option - sort, according to given column of power output:\n";
    print join ", ", sort {$options{$a} <=> $options{$b}} keys %options;
    print "\n";
}
sub tonumber {

    my $string = shift;
    my $number;

    if ($string =~ /(.*)(\D)$/) {
	if ($2 eq 'K') {
	    $number = $1 * 1000;
	}
	elsif ($2 eq 'M') {
	    $number = $1 * 1000000;
	}
	elsif ($2 eq 'G') {
	    $number = $1 * 1000000000;
	}
	elsif ($2 eq '%') {
	    $number = $1;
	}
    }
    else {
	$number = $string;
    }
    return $number;
}
