#!/usr/bin/ruby

DATA_DIR = "/path/to/mirrored/dir/"
OUTFILE = 'ncaa_results.txt'

#{'1234'=>'Texas A&M'}
$teams = Hash.new();

def get_data_from_html(content,home_id)

	#strip newlines to make regex's more effective
	content.gsub!(/\s/,'')
	
	#get rid of classes that will mess things up
	content.gsub!(/class="smtext"/,'')

	#split on table rows
	content.gsub!(/<\/tr>/,'')
	content.gsub!(/<\/table>/,'<tr>')
	lines = content.split('<tr>')

	results = []
	lines.each do |line|

		#throw out everything but table rows
		next if( line[0..2] != '<td')

		#don't need closing cells; we'll split on opening cells to get our good data
		line.gsub!(/<\/td>/,'')
		elements = line.split('<td>')

		#take of empty string and date at start
		elements.shift(2)

		#these aren't the scores you're looking for
		next if (elements.length != 2)
		
		next unless match = /.*org_id=(?<opponent_id>\d+).*/.match(elements[0])

		elements[0] = match['opponent_id']

		#we're calling overtime a tie.
		if( /OT/.match(elements[1]) )
			elements[1] = 'T'
		elsif ( /W/.match(elements[1]) )
			elements[1] = 'W'
		elsif( /L/.match(elements[1]) )
			elements[1] = 'L'
		end

		elements.unshift(home_id)

		results << elements
	end	

	results
end

def create_team_hash()
	index_file = '/home/audioman/Desktop/ncaa/index.html'
	content = File.open(index_file)
	content.each do |line|
		next unless match = /<a.*?org_id=(?<team_id>\d+)" onclick.*?>(?<team_name>.*?)<\/a>/.match(line)

		$teams[match['team_id']] = match['team_name']
	end
end

def write_results(fh, lines)
	puts "Writing " + lines.length.to_s + " lines to total..."

	lines.each do |line|
		begin
			fh << $teams[line[0]] + "\t" + $teams[line[1]] + "\t" + line[2] + "\n"
		rescue
			print "Game against unlisted team encountered "
			puts line.to_s
		end
	end
end


create_team_hash

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

files = Dir.entries DATA_DIR
files.each{ |file|
	next if file[0] == '.'

	puts "Parsing file #{file}..."

	content = File.read(DATA_DIR + file)

	next unless match = /.*org_id=(?<team_id>\d+)$/.match(file)

	lines = get_data_from_html(content,match['team_id'])

	write_results(fh, lines)

}

fh.close

