import MapReduce
import sys

mr = MapReduce.MapReduce()

def mapper(record):
    key = record[0]
    i = record[1]
    j = record[2]
    value = record[3]

    if key == 'a':
        for x in range(5):
            mr.emit_intermediate((i,x), ('a', j, value))

    if key == 'b':
        for x in range(5):
            mr.emit_intermediate((x,j), ('b', i, value))

def reducer(key, list_of_values):
    row = []
    col = []
    for e in list_of_values:
        if e[0] == 'a':
            row.append((e[1], e[2]))
        if e[0] == 'b':
            col.append((e[1], e[2]))
    psum = 0
    for v in row:
        for w in col:
            if v[0] == w[0]:
                psum += v[1]*w[1]
    mr.emit((key[0], key[1],psum))

if __name__ == '__main__':
    inputdata = open(sys.argv[1])
    mr.execute(inputdata, mapper, reducer)