#!/usr/perl/perl580/bin/perl

open (IN, "$ARGV[0]");

@matrix = '';
$x = 1;
$y = 1;

while ($line = <IN>) {
	chomp $line;
	if ($line =~ /\@ENTITY ID/) {
#		print ("$line\t$x\n");
		$i = 0;
		$y = 1;
		until (($line =~ /GO:0016209/) || ($line =~ /\@\n/)) {
			if ($line =~ /GO/) {
				($go_id, $value) = split (/\t/, $line);
				$matrix[$x][$y] = $value;
				$go[$i] = $go_id;
#				print ("$x\t$y\t$matrix[$x][$y]\n");
				$y++;
				$i++;
			}
		$line = <IN>;
		chomp $line;
		}
	$x++;
	}
}

close IN;

$loop_control = $y;

#print ("$x\n");
#print ("$y\n");

$i = 0;
$y = 1;
$x = 1;

$first_category_first_element = $ARGV[2];
$first_category_last_element = $ARGV[3];
$matrix_of_elements_from_first_category = ($first_category_last_element - $first_category_first_element);
$matrix_of_elements_from_first_category++;

print ("Working with the first category, ranging from element $first_category_first_element to $first_category_last_element, $matrix_of_elements_from_first_category elements\n");

for $y (1..$loop_control) {
	$soma = 0;
	for $x ($first_category_first_element..$first_category_last_element) {
		print ("$y\t$x\n");
		$soma += $matrix[$x][$y];
	}
	$soma = ($soma/$matrix_of_elements_from_first_category);
	$first_value[$i] = $soma;
#	print ("$soma\n");
	$i++;
}

#print ("$#first_value\n");

$i = 0;
$y = 1;
$x = 1;

$second_category_first_element = $ARGV[4];
$second_category_last_element = $ARGV[5];
$matrix_of_elements_from_second_category = ($second_category_last_element - $second_category_first_element);
$matrix_of_elements_from_second_category++;

print ("Working with the last category, ranging from element $second_category_first_element to $second_category_last_element, $matrix_of_elements_from_second_category elements\n");
print ("\n");
for $y (1..$loop_control) {
	$soma = 0;
	for $x ($second_category_first_element..$second_category_last_element) {
		print ("$y\t$x\n");
		$soma += $matrix[$x][$y];
	}
#	$a = <STDIN>;
	$soma = ($soma/$matrix_of_elements_from_second_category);
	$last_value[$i] = $soma;
	$i++;
}

#print ("$#last_value\n");

$i = 0;
foreach $first_element (@first_value) {
	$difference = ($first_element - $last_value[$i]);
	$difference = $difference**2;
	$difference = $difference**(1/2);
	$final_hash{$go[$i]} = $difference;
	$i++;
}

open (IN, "$ARGV[1]") ||
	die;

while ($line = <IN>) {
	chomp $line;
	($go_id, $name) = split (/\t/, $line);
	$hash{$go_id} = $name;
}

foreach my $key (sort {$final_hash{$b} <=> $final_hash{$a} || $final_hash{$b} cmp $final_hash{$a}} keys %final_hash) {
	print "$key\t$hash{$key}\t$final_hash{$key}\n";
}