#!/usr/bin/perl -w
# Compute topological distances between ORFs based on distances between classes

open(CDIS, "go_process_dist.txt");
while (<CDIS>) {
	chomp;
	@d = split;
	push @D, [@d];
}
close(CDIS);

open(NODE, "go_process_node.txt");
while (<NODE>) {
	chomp;
	($line, $node) = split;
	$line{$node} = $line;
}
close(NODE);

# open(ORF, "process_terms_for_orf.txt");
open(ORF, "go_process_orf.txt");
while (<ORF>) {
	chomp;
	($orf, $term) = split /\s+/, $_, 2;
	
	$orf =~ s/-//;
	$term{$orf} = $term;
}
close(ORF);

@orf = sort(keys %term);

for $i (0 .. $#orf) {
	$term1 = $term{$orf[$i]};
	@term1 = split /\s+/, $term1;
	for $j ($i + 1 .. $#orf) {
		$term2 = $term{$orf[$j]};
		@term2 = split /\s+/, $term2;
		# print "$orf[$i]\t$orf[$j]\t$term1\t$term2\t";
		print "$orf[$i]\t$orf[$j]\t";

		$d_min = 1000000000;
		for $term1 (@term1) {
			$line1 = $line{$term1};
			for $term2 (@term2) {
				$line2 = $line{$term2};
				unless (defined $line1 && defined $line2) {
					# print "NA ";
					# print "\tline1 = $line1\tline2 = $line2\n";
					# print "\tterm1 = $term1\tterm2 = $term2\n";
				} else {
					$d = $D[$line1][$line2];
					if ($d < $d_min) {
						$d_min = $d;
					}
					# printf("%d ", $d);
				}
			}
		}
		# print "\n";
		printf("\t%d\n", $d_min);
	}
}
