#!/usr/bin/python

import sys, codecs, os.path, os

if len(sys.argv) != 10:
	print "Usage: " + sys.argv[0] + " <crs_1> <weight_1> <crs_2> <weight_2> <crs_3> <weight_3> <crs_4> <weight_4> <output_crs>"
	sys.exit(1)

def getSims(oldline):
	line = oldline.strip()
	if (line ==""):
		return {}
	tokens = line.split(" ")
	sims = {}
	for tok_no in xrange(0, len(tokens), 2):
		col = int(tokens[tok_no])
		val = float(tokens[tok_no+1])
		sims[col] = val
	return sims

crs = []
w = []
for i in range(1,9):
	if (i%2 == 1):
		crs.append(codecs.open(sys.argv[i]))
	else:
		w.append(float(sys.argv[i]))

wsum = 0
for i in xrange(0,len(w)):
	wsum = wsum + w[i]

for i in xrange(0,len(w)):
	w[i] = w[i]/wsum

out = open(sys.argv[9],"w")

eof = False
firstline = True
words = 0
current = 0

while (not eof):
	if firstline:
		firstline = False
		line = crs[0].readline()
		out.write(line)
		for i in range (1,len(crs)):
			crs[i].readline()
		contents = line.split(" ")
		words = int(contents[0])
		continue
	sims = []
	for i in xrange(0,len(crs)):
		sims.append([])
		line = crs[i].readline()
		sims[i] = getSims(line)
	for i in xrange(0,words):
		sim = 0
		for j in xrange(0,len(crs)):
			if (i in sims[j]):
				sim = sim + sims[j][i] * w[j]
		if (sim > 0) :
			out.write(str(i) + " " + str(sim) + " ")
	out.write("\n")
	if (current%10 == 0):
		print "Reading line " + str(current) + " of " + str(words)
	current = current + 1
	if (current == words):
		eof = True
				
	
	
