#!/usr/bin/perl

if (@ARGV < 1) { # print a warning if we didn't get the right number of features
	print "Correct syntax is:\n\tfind_distances.pl file_list\n";
	exit;
}

foreach $file (@ARGV) {
	if (-e $file) {
	
		# slurp in the file
		open(FH, $file);
		@vectors;
		@author_ids;
		@author_picked;
		$author_count;
		
		while (<FH>) {
			@temp = split;
			push (@author_ids, shift @temp); # get the real author ID of the file, and store it
			push (@author_picked, pop @temp); # get the assigned author id
			$author_count = @temp; # get a count on the number of entries in the vector
			push @vectors, [ @temp ];	
		}
		close(FH);
		
		open(FH, ">$file.pair_data");
		print FH "same_auth\tdoc_#\tauthor\tdoc_#\tauthor\tdot_product\teuclidean_distance\n";
		
		for($i = 0; $i < $#vectors + 1; $i++) {
			for($j = $i + 1; $j < $#vectors + 1; $j++) {
				$dot = &dp();
				$distance = &euclidean();
				$same_auth = 0; 
				if ($author_ids[$i] == $author_ids[$j]) { $same_auth = 1; }
				print FH "$same_auth\t$i\t$author_ids[$i]\t$j\t$author_ids[$j]\t$dot\t$distance\n";
			}
		}
	}
}

exit;

sub dp { # computes the dot product of two vectors
	$magi = 0;
	$magj = 0;
	$sum = 0;

	for ($index = 0; $index < $author_count; $index++) {
		$magi += $vectors[$i][$index] * $vectors[$i][$index];
		$magj += $vectors[$j][$index] * $vectors[$j][$index];
		$sum += $vectors[$i][$index] * $vectors[$j][$index];
	}
	
	$magi = sqrt($magi);
	$magj = sqrt($magj);
	
	$sum /= ($magi * $magj);
	
	return $sum;
}

sub euclidean { # computes the euclidean distance between two vectors
	$dist = 0;
	
	for ($index = 0; $index < $author_count; $index++) 
		{ $dist += ($vectors[$i][$index] - $vectors[$j][$index]) * ($vectors[$i][$index] - $vectors[$j][$index]); }
	
	$dist = sqrt($dist);

	return $dist;
}