# Makes scenario.txt, rackdata.txt, and module.txt
#!d:\plum\perl\bin\perl.exe

use DBI;
use DBD::mysql;

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

###############################################
# Dump rack data ##############################
###############################################

@rackdata=fetchtable("select racks.acronym,rackdata.* from racks,rackdata where racks.idx=rackdata.racknum order by racks.idx");

open OUT,">..\\rackdata.txt";

print OUT "Acronym\tUpmass\tMiddecks\tKeepalivePower\tPower\tCycles/Inc\tHrs/Cycle\tCrewtime\tCrewtrng\tStowage\tMTL Flow\tKeepalive MTL Flow\n";

foreach $rack (@rackdata)
 {
 $str =$rack->{acronym}."\t";
 $str.=$rack->{upmass_resupply}."\t";
 $str.=$rack->{mid_resupply}."\t";
 $str.=$rack->{keepalive_power}."\t";
 $str.=$rack->{power}."\t";
 $str.=$rack->{cycles_per_increment}."\t";
 $str.=$rack->{hrs_per_cycle}."\t";
 $str.=$rack->{crew_time}."\t";
 $str.=$rack->{crew_training}."\t";
 $str.=$rack->{stowage}."\t";
 $str.=$rack->{MTL_flow}."\t";
 $str.=$rack->{MTL_flow_keepalive}."\n";
 print OUT $str;
 }

close OUT;

###############################################
# Dump run data ###############################
###############################################

open OUT,">..\\scenario.txt";

print OUT "Crew Training\tCrew Time\tMiddecks\tUpmass\tBulk Att\tTrans O'Head\tStowage\tKeepalive\tPower\tCAM O'Head\n";

($run)=fetchtable("select * from runs where idx=".$ARGV[0]);

print OUT $run->{crewtrng}."\t";
print OUT $run->{crewtime}."\t";
print OUT $run->{MLE}."\t";
print OUT $run->{upmass}."\t";
print OUT $run->{bulk}."\t";
print OUT $run->{rack_overhead}."\t";
print OUT $run->{stowage}."\t";
print OUT $run->{keepalive}."\t";
print OUT $run->{power}."\t";
print OUT $run->{hskpg};

close OUT;

###############################################
# Dump module data ############################
###############################################

open OUT,">..\\module.txt";

print OUT "Acronym\tAcoustics\tMax MTL\n";

@modules=fetchtable("select * from modules");

foreach $mod (@modules)
 {
 print OUT $mod->{acronym}."\t";
 print OUT $mod->{acoustics}."\t";
 print OUT $mod->{MTL_total}."\n";
 }

close OUT;

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

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=$_[0];
	my $rst=sql_query($table);
	my @rows;
	my $row;
	while($row=fetchrow($rst))
	 {
	 push @rows,$row;
	 }
	$rst->finish();
	return @rows;
}

$db->disconnect();