#!/usr/bin/ruby

#should be in three column tab-delimited format
#team1, team2, team1 result
DATA_FILE = 'ncaa_results.txt'

#will be a two column file
#team, elo score
OUTFILE = 'elos.txt'
BASE_ELO = 1000
K_FACTOR = 30.0
Q_CONST = 400.0

#{'team1'=>1000}
$elo = Hash.new(BASE_ELO);

results = File.open(DATA_FILE)

results.each do |line|
	(team1, team2, result) = line.split("\t");
	result.chomp!;

	#for variable explanations and more:
	#http://en.wikipedia.org/wiki/Elo_rating_system#Mathematical_details
	q1 = 10.0 ** ($elo[team1] / Q_CONST)
	q2 = 10.0 ** ($elo[team2] / Q_CONST)
	e1 = q1 / (q1 + q2)

	if( result == 'W' )
		s1 = 1.0
	elsif (result == 'L')
		s1 = 0.0
	elsif (result == 'T')
		s1 = 0.5
	else
		puts "Invalid result encountered"
		next;
	end

	diff = s1 - e1
	delta = K_FACTOR * (s1 - e1);
	delta = delta.to_int

	print "R1: #{$elo[team1].to_s}, R2: #{$elo[team2].to_s}, E1: #{e1}, Result: #{result}, Delta: #{delta}, "

	$elo[team1] += delta
	$elo[team2] -= delta
	
	puts "R1': #{$elo[team1].to_s}, R2': #{$elo[team2].to_s}"

end


fh = File.open(OUTFILE,'w')

#sort in descending, write to file
$elo.sort_by{|k,v| v}.reverse.each do |team,elo|
	fh << team + "\t" + elo.to_s + "\n"
end

fh.close


