require 'net/http'
require 'cgi'

def google_hits_for query
	response = Net::HTTP.get('www.google.com', "/search?q=#{CGI.escape query}")
	response[/of about <b>([\d,]+)<\/b>/,1].tr(',','').to_i
rescue
	1
end

def love_hate_index_for lang
	if lang['&']
		love, hate = lang.split('&').inject([0,0]) do |sum,lang|
			love, hate, = love_hate_index_for lang
			sum[0] += love
			sum[1] += hate
			sum
		end
	else
		restriction = "programming"
		love = google_hits_for("\"love #{lang}\"+" + restriction)
		hate = google_hits_for("\"hate #{lang}\"+" + restriction)
	end
	rating = (love - hate).to_f / hate
	return love, hate, rating
end

LANGS = DATA.read.scan(/[\t*]\t.*?\t/).map { |l| l.strip }

def calculate
	rating = {}
	for lang in LANGS
		rating[lang] = love_hate_index_for(lang)
	end
	rating
end

CACHE = 'love_hate.yaml'
require 'yaml'
if File.exist? CACHE
	rating = YAML.load File.read(CACHE)
else
	rating = calculate
	File.open CACHE, 'w' do |f|
		f.write rating.to_yaml
	end
end

for lang, (love, hate, index) in rating.sort_by { |k,(love, hate, rating)| -rating }
	puts '<tr><td><b>%s</b></td><td>%d</td><td>%d</td><td>%5.2f</td><td>%s</td></tr>' % [
		lang,
		love, hate, index,
		'&hearts;' * (index/10).to_i
	]
end

__END__
1 	2 		Java 	21.275% 	+4.29% 	A
2 	1 		C 	17.688% 	-0.95% 	A
3 	4 		C++ 	10.900% 	+0.71% 	A
4 	5 		PHP 	10.880% 	+2.15% 	A
5 	6 		Basic 	10.109% 	+3.32% 	A
6 	3 		Perl 	5.847% 	-4.35% 	A
7 	8 		C# 	3.948% 	+1.13% 	A
8 	9 		Python 	2.759% 	+0.06% 	A
9 	11 		JavaScript 	1.567% 	-0.07% 	A
10 	7 		Delphi&Kylix 	1.443% 	-2.23% 	A
11 	12 		SAS 	1.428% 	+0.07% 	A
12 	10 		PL/SQL 	1.009% 	-0.74% 	A
13 	43 		Visual FoxPro 	0.834% 	+0.74% 	A--
14 	15 		Lisp&Scheme 	0.721% 	-0.09% 	A--
15 	24 		ColdFusion 	0.542% 	+0.16% 	B
16 	26 		VB.NET 	0.541% 	+0.18% 	B
17 	14 		COBOL 	0.517% 	-0.47% 	A--
18 	32 		Ruby 	0.493% 	+0.20% 	B
19 	18 		Ada 	0.490% 	-0.15% 	B
20 	30 		D 	0.484% 	+0.16% 	B
