#!/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_features.pl file_list\n";
	exit;
}

#$feat_count = shift(@ARGV);

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
			
			%features = ();
			
			foreach $feature (@temp) {
				($feat, $value) = split(/:/,$feature);
				$features{$feat} = $value;
			}
			
			push @vectors, { %features };	
		}
		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;

	foreach $key (keys %{$vectors[$i]}) {
		$magi += $vectors[$i]{$key} * $vectors[$i]{$key};
		$sum += $vectors[$i]{$key} * $vectors[$j]{$key};
	}
		
	foreach $key (keys %{$vectors[$j]}) {
		$magj += $vectors[$j]{$key} * $vectors[$j]{$key};
	}
	
	$magi = sqrt($magi);
	$magj = sqrt($magj);
	
	$sum /= ($magi * $magj);
	
	return $sum;
}

sub euclidean { # computes the euclidean distance between two vectors
	$dist = 0;
	
	%keyset = ();
	
	foreach $key (keys %{$vectors[$i]}) { $keyset{$key} = $key; }
	foreach $key (keys %{$vectors[$j]}) { $keyset{$key} = $key; }
	
	foreach $key (keys %keyset)
		{ $dist += ($vectors[$i]{$key} - $vectors[$j]{$key}) * ($vectors[$i]{$key} - $vectors[$j]{$key}); }
	
	$dist = sqrt($dist);

	return $dist;
}