#!d:\plum\perl\bin\perl.exe

### sel_success.txt
### Usage: perl sel_success.txt <idx>
### idx is the index of the run to calculate selection successes for, num is the number of selected racks.
### Makes bars.txt and combos.txt
### Last updated 17 Aug 2002

use DBI;
use DBD::mysql;

$db=DBI->connect("DBI:mysql:plum_data");

###############################################
# Grab data ###################################
###############################################

$runidx=$ARGV[0];
($run)=fetchtable('select * from runs where idx='.$runidx);
($racks)=fetchtable('select count(idx) as num from racks');
$racks=$racks->{num};
@names=fetchtable('select racks.acronym,rackdata.partner from racks,rackdata where racks.idx=rackdata.racknum order by racks.idx');
$tblname=$run->{tblname};
$order=$run->{numcombos}/2;

@rackdata=fetchtable("select rackdata.*,selection.status from rackdata,selection where selection.run=$runidx and rackdata.racknum=selection.rack order by rackdata.racknum");

###
# Build constraint table
###

@cons=fetchtable('select * from runcons where run='.$runidx);
$j=0;
foreach(@cons)
{
    %c=%{$_};
    @con=fetchtable('select * from constraints where name="'.$c{'cons'}.'"');
    $n=0;
    foreach(@con)
    {
	%row=%{$_};
	$constraints[$j]->[$n]->{'rack'}=$row{'rack'};
	$constraints[$j]->[$n]->{'trigger'}=$row{'trigger'};
	$n++;
    }
    $j++;
}

$db->disconnect();
$db=DBI->connect("DBI:mysql:plum_output"); # Reconnect to output database


@percents=fetchtable("select selectednum,count(idx) as percent from $tblname where any_exceeded_inc=0 group by selectednum");

$temp=shift(@percents);
$best=$temp->{percent}-$order;
$target=$temp->{selectednum};

foreach(@percents)
{
    if(abs($_->{percent}-$order) < abs($best))
    {
	$best=$_->{percent}-$order;
	$target=$_->{selectednum};
    }
}


###change number of combos selected####

$target = $target-1;
######


$query="select selects from ".$tblname.' where selectednum='.$target.' and any_exceeded_inc=0';

@data=fetchtable($query);

$numsucceeds=@data;



###############################################
# Figure succeeds #############################
###############################################

for($n=1;$n!=$racks+1;$n++)
{
    $succeeds[$n]=0;
}

foreach(@data)
{
    $n=1;
    @selects=split(//,$_->{selects});
    foreach(@selects)
    {
	if($_==1)
	{
	    $succeeds[$n]++;
	}
	$n++;
    }
}

if(!$run->{'oldcons'})
{
    foreach(@names)
    {
	if(!available($_->{'acronym'}))
	{
	    $notavail{$_->{'acronym'}}=1;
	}       
    }      
}     

open BARS,">bars.txt";
open COMBOS,">combos.txt";
open NEVER,">never.txt";
open FOOTER,">footer.txt";

@newnames=@names;

shift @succeeds; # I bet that if you remove this line, it will fix the problems involving rack column naming.
foreach(@succeeds)
{
    $_=0 if $_ eq '';
    $name=shift @names;
    if($name->{partner} ne 'Unknown')
    {
	$value=$_/$numsucceeds*100;
	if($run->{'oldcons'} or !$notavail{$name->{'acronym'}})
	{
	    print BARS $name->{partner}."\t".$name->{acronym}."\t".$value."\n";
	}
    }
}

$num=keys(%notavail);
print NEVER $num."\n";

foreach(keys(%notavail))
{
    print NEVER $_."\n";
}     

foreach(@newnames)
{
    print COMBOS $_->{acronym}."\t";
}
print COMBOS "\n";
foreach(@newnames)
{
    print COMBOS $_->{partner}."\t";
}
print COMBOS "\n";


foreach(@data)
{
    @selects=split //,$_->{selects};
    foreach(@selects)
    {
	print COMBOS $_."\t";
    }
    print COMBOS "\n";
}


print FOOTER $run->{'name'}."\n";
print FOOTER "Upmass (kg)\t".$run->{'upmass'}."\n";
print FOOTER "Att P/Ls (kg)\t".$run->{'bulk'}."\n";
print FOOTER "Middecks (MDLs)\t".$run->{'MLE'}."\n";
print FOOTER "Crew Time (hrs per week)\t".$run->{'crewtime'}."\n";
print FOOTER "Crew Trng (hrs)\t".$run->{'crewtrng'}."\n";
print FOOTER "Stowage (racks)\t".$run->{'stowage'}."\n";
print FOOTER "Power (kW)\t".$run->{'power'}."\n";
print FOOTER "K/A Power (kW)\t".$run->{'keepalive'}."\n";
print FOOTER "CAM Hskpg (kW)\t".$run->{'hskpg'}."\n";

close BARS;
close COMBOS;
close NEVER;
close FOOTER;

###############################################
# Begin library funcs #########################
###############################################


sub available{
    my $name;
    my $r;
    my @r2;
    my $triggers;
    my $included;
    my $thistrigger;
    my $possibletrigger;
    my $totalincluded;
    
    $name=$_[0];
    $idx=0;
    foreach(@names)
    {
	if($name eq $_->{acronym})
	{
	    $racknum=$idx+1;
	}
	$idx++;
    }

    if($rackdata[$racknum-1]->{'status'}!=3){return 1;}
    $r=0;
    $totalincluded=0;
    foreach(@constraints)
    {
	$triggers=0;
	$included=0;
	$thistrigger=0;
	$possibletrigger=0;
	@r2=@{$_};
	foreach(@r2)
	{
	    if($_->{'trigger'}==1)
	    {
		if($rackdata[$_->{'rack'}-1]->{'status'}!=3){$possibletrigger=1;}
		$triggers++;
	    }
	    if($_->{'rack'}==$racknum){$included=1;$totalincluded++;}
	    if($_->{'trigger'}==1 and $_->{'rack'}==$racknum){$thistrigger=1;}
	}
	if($included==0 or $possibletrigger==1)
	{
	    $r++;
	}	  
    }
    if($totalincluded==0){return 0;}
    if($r!=0){return 1;}
    return 0;
}    


sub sql_query{
    if($_[0] eq '')
    {
	return;
    }
    if($_[1] eq '')
    {
	$_[1]=$db;
    }
    my $rst=$_[1]->prepare($_[0]);
    $rst->execute();
    return $rst;
}

sub fetchrow{
    my $row=$_[0]->fetchrow_hashref();
    return $row;
}

sub fetch_hash{
    my $row=$_[0]->fetchrow_hashref();
    return %{$row};
}

sub fetchtable{
    my $table;my $rst;my @rows;my $row;
    $table=$_[0];
    $rst=sql_query($table);
    while($row=fetchrow($rst))
    {
	push @rows,$row;
    }
    return @rows;
}

$db->disconnect();
