#get some information and print out the table (in LaTex)
#for algorithm 2

open(FACTORS,"factors");
my @data = <FACTORS>;
close(FACTORS);

my $n = scalar(@data);

my @factors;
my @types;
my @levels;
my %values;
for(my $i=0;$i<$n-1;$i++){
	chomp $data[$i];
	my @this = split(/\t/,$data[$i]);
	push @factors,$this[0];
	push @types,$this[1];
	$values{$this[0]} = $this[2];
	push @levels,$this[3];
}

my %error;
chomp $data[$n-1];
my @v = split(/\t/,$data[$n-1]);
$error{"value"} = $v[2];
$error{"level"} = $v[3];
$error{"type"}  = $v[1];

sub df {
	my $int = $_[0];
	#my %val = $_[1];
	my $n = length($int);
	my $dfn = 1;
	my $dfs = '';

	for(my $i = 0;$i<$n;$i++){
		my $l = substr($int,$i,1);

		if($values{$l} !~ m/\D/){
			$dfn *= $values{ substr($int,$i,1) } - 1;
		}else{
			$dfs .= "($values{$l}-1)";
		}
	}

	my $df = $dfn . $dfs;
	if(substr($df,0,1) == 1){
		substr($df,0,1) = '';
	}

	return $df;
}

my @interactions = ();
foreach my $i (@factors){
	push @interactions,$i;
	my @temp = ();
	for(my $j=scalar(@interactions)-1;$j>0;$j--){
		#push @interactions,($i . $interactions[$j-1]);
		push @temp,($i . $interactions[$j-1]);
	}
	push @interactions,reverse @temp;
}

my @subscripts = ();
foreach my $i (@interactions){
	my $temp;
	for(my $j=0;$j<@factors;$j++){
		if( index($i,$factors[$j]) >= 0 ){
			$temp .= $levels[$j];
		}
	}
	push @subscripts,$temp;
}

my $header = "& df ";
for(my $i=0;$i<@types;$i++){
	$header .= "& $types[$i]/$levels[$i]";
}
$header .= "&" . $error{"type"}. "/" . $error{"level"} . "&EMS\\\\ \\hline \n";

my $amp = '&' x ($n);
my $col = 'l' x ($n+4);

open(OUT,">outtable.tex");
print OUT "\\begin{center}\n";
print OUT "\\begin{tabular}{$col}\n";
print OUT "$header";

my $c = 0;
foreach my $i (@interactions){
	$interactions[$c] = reverse($i);
	print OUT "\$$interactions[$c]_{$subscripts[$c]}\$ &" . df($interactions[$c]);
	for(my $j=0;$j<@levels;$j++){
		if( index($subscripts[$c],$levels[$j]) >= 0 ){
			if( $types[$j] eq 'F' ){
				print OUT "& 0";
			}elsif( $types[$j] eq 'R' ){
				print OUT "& 1";
			}
		}else{
			print OUT "&$values{$factors[$j]}";
		}
	}
	print OUT "&",$error{"value"};
	print OUT "\\\\\n";
	$c++;
}

print OUT "\$\\varepsilon_{",$error{"level"},"(@levels)}\$&";
for(my $j=0;$j<@levels;$j++){
	print OUT "& 1";
}
print OUT "&",$error{"value"} - 1,"\n";

print OUT "\\end{tabular}\n";
print OUT "\\end{center}\n";
close OUT;

