#!/usr/bin/perl -w
use strict;
use DBI;
use lib qw(/home/jeremy/Documents/scripts/);
use tools;

my $file = "postout.tex";
open IN,"$file";
my @data = <IN>;
close IN;

sub noEndMatter {
	my $str = $_[0];
	substr($str,index($str,"\\\\"),length($str)-index($str,"\\\\")) = '';
	return($str);
}

sub getEqn {
	my ($eq,$null) = @_;
	my $r = substr($eq,1,length($eq) - 2);

	if( defined($null) ){
		substr($r,rindex($r," + "),length($r) - rindex($r," + ")) = '';
	}

	return($r);
}

my $eqn_index = 2;

open OUT,">fcalcout.tex";

my $eqn = '';

for( my $i=0;$i<@data;$i++ ){
	my @info = split(/\&/,noEndMatter($data[$i]));

	my $eqn_null = getEqn($info[$eqn_index],'n');

	my $match = -1;
	for(my $j=$i + 1;$j<(@data);$j++){
		my @c = split(/\&/,noEndMatter($data[$j]));
		if( $eqn_null eq getEqn($c[$eqn_index]) ){
			$match = $j;
		}
	}

	my @denom = split(/\&/,noEndMatter($data[$match]));

	my $Ftest = "MS(" . substr($info[0],1,index($info[0],"_")-1) . ")/";
	$Ftest .= "MS(" . substr($denom[0],1,index($denom[0],"_")-1) . ")";

	if( $match == -1 ){
		$Ftest = "- -";
	}

	my ($er,$df,$eq) = split(/\&/,noEndMatter($data[scalar(@data) - 1])); 
	if(( index($Ftest,"varepsilon") > -1 )&&( $df == 0 )){
		$Ftest = "- -";
	}

	my $pstr = StringTools::linetostr("&","\\\\",@info,"\$$Ftest\$");
	#my $pstr = StringTools::linetostr("&","\\\\",$info[0],$info[2],"\$$Ftest\$");
	#print "$info[0]\t$info[1]\t$info[2]\t$Ftest\n";
	print OUT $pstr;

	$eqn .= $info[0] . " + ";

}
#print OUT "$eqn\n";

close OUT;

FileTools::addTabs("fcalcout.tex");
