#!/usr/bin/perl
#set q=1 in various atlas output files
#jda@math.umd.edu

use strict;

use Getopt::Long qw(:config no_ignore_case);

use vars qw($help $outputFile $quiet $sort $original $force $reverse);
    
my %options=('h' => \$help,  
	     'o' => \$outputFile,
	     'O' => \$original,
	     's'=> \$sort,
	     'r'=> \$reverse,
	     'f' => \$force,
	     'q' => \$quiet);

	     
GetOptions(\%options,qw(h! o=s s! q! O! f! r!));
my $file=$ARGV[0];			   
&help if (!$file or $help);

open(IN,"<$file")||die("Can't open $file for input\n");

if ($outputFile){
    !$quiet and print "Sending output to file $outputFile\n";
    open(OUT,">$outputFile")||die("Can't open $outputFile for output");
    select(OUT);
}
if (!$quiet){
    print "Setting q=1 in $file\n";
    $original and print "Showing original values\n";
    if ($sort){
        print "Sorted numerically, ";
	print $reverse?"smallest first\n":"largest first\n";
    }
}

my @lines;
foreach my $line (<IN>){
    chomp($line);
    my ($prefix,$value);
    if ($line =~ /[a-p]/){
	push @lines, $line;
	next;
    }
    if  ($line =~ /:/){
	($prefix,$value) =  $line =~ /(.*):(.*)/;
	if ($sort and !$force){
	    print "You probably don't want to use -s (sort numerically) in klbasis file. Use -f to force this\n";
	    exit;
	}
    }else{
	$value=$line;
    }
    $value =~ s/([0-9]+)q/\1*q/g;
    $value =~ s/q/1/g;
    $value =~ s/\^/**/g;
    $value=eval($value);
    my $outputLine=$prefix.": ".$value if ($prefix);
    if ($original){
	$outputLine = $line."  ".$outputLine;
    }
    if ($sort){
	push @lines, $outputLine;
    }else{
	print  $outputLine,"\n";
    }
}
close(IN);
if ($sort){
    if ($original){
	my @sort= sort {
	    my ($qa,$na)=split /\s+/, $a;
	    my ($qb,$nb)=split /\s+/, $b;
	    $reverse?$nb<=>$na:$na <=> $nb;
	} @lines;
	@lines=@sort;
    }else{
	my @sort = sort {$a <=> $b} @lines;
	@lines=@sort;
    }
}

print join "\n", @lines;
print "\n";


sub help{
print "Set q=1 in output of klbasis or kllist

Usage: q=1 [-o output] [-s sort [-r]] [-q] $file

Examples:

q=1 klbasis 
q=1 -O klbasis   <-- show original line also
q=1 -s kllist    <-- sort output numerically, smallest first
q=1 -s -r kllist | more   <-- capture the largest one

Options:
-q        quiet output
-o output send output to file instead of terminal
-s sort   sort (numerically) - only use with kllist
-r        reverse sort (biggest to smallest)
-O        show Original line also
-f        force sort of klbasis (you probably don't want to do this)
-h        this help file

";
exit; 
}












