#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys, codecs
import pymatrices

def main():
	mdir = sys.argv[1]
	mname = sys.argv[2]
	out = sys.argv[3]
	print "Mdir: %s\nMname: %s\n" % (mdir, mname)

	matrix = pymatrices.LoadSuperMatrix(mdir, mname, False, True)
	rows = matrix.NumberOfRows()
	rfeatures = matrix.GetRowFeatures()
	row_words = set();
	for row_no in xrange(rows):
		rlabel = rfeatures[row_no].GetLabel()
		try:
			rlabel = rlabel.decode('utf8')
		except:
			pass
		rlabel = rlabel[6:]
		row_words.add(rlabel)
		
	cfeatures = matrix.GetColumnFeatures()

	data = []
	for row_no in xrange(rows):
		rlabel = rfeatures[row_no].GetLabel()
		try:
			rlabel = rlabel.decode('utf8')
		except:
			pass
		rlabel = rlabel[6:]
		v = matrix.GetRow(row_no).GetValues()
		for column_no in v:
			clabel = cfeatures[column_no].GetLabel()
			try:
				clabel = clabel.decode('utf8')
			except:
				pass
			clabel = clabel[6:]
			if not clabel in row_words:
				continue
			if rlabel == clabel:
				continue
			#line = u'%s;%s;%d' % ( rlabel, clabel, int( v[column_no] ) )
			data.append(  ( int(v[column_no]), rlabel, clabel ) )
	
	with codecs.open(out, 'w', 'utf8') as fi:
		for (f, r, c) in reversed(sorted(data)):
			fi.write('%s;%s;%d\n' % (r,c,f))





if __name__ == '__main__':
	main()
