#!/usr/bin/python
#encoding:utf8

import argparse
import sys

def make_parser():
	desc = 'Statystyki kolumnowe'
	parser = argparse.ArgumentParser(description = desc)
	parser.add_argument('-i', '--in-file', dest = 'in_file', required = True)
	parser.add_argument('-n', '--column_name', dest = 'column_name', required = True)
	parser.add_argument('-o', '--out_file', dest = 'out_file', required = False)
	return parser

def read_file(filename):
	"""Wczytuje plik"""
	lines = []
	with open(filename, 'rt') as fin:
		for line in fin:
			line = line.strip()
			if line.find('synset_str_plwn') != -1:
				continue
			lines.append(line)
	return lines

def str_to_nr(column_name, filename):
	""" Zamienia nazwe kolumny na jej numer"""
	with open(filename, 'rt') as fin:
		for line in fin:
			line = line.strip()
			head = line.split(';')
			if column_name in head:
				return int(head.index(column_name))
			else:
				print "Not Found!"
				return None

def make_stats(lines, column):
	"""Tworzy statystyki dla podanej kolumny"""
	statistic = {}

	for line in lines:
		li = line.split(';')
		

		if li[-1] not in statistic.keys():
			statistic[li[-1]] = {}

		if li[column] not in statistic[li[-1]].keys():
			statistic[li[-1]][li[column]] = 1
		else:
			statistic[li[-1]][li[column]] += 1
	return statistic

def write_stats(statistic):
	for key in statistic.keys():
		for s in statistic[key].keys():
			print "%s;%s;%d"	%	(key, s, statistic[key][s]) 

def save_to_file(statistic, out_file):
    saveout = sys.stdout                                                        
    fsock = open(out_file, 'w') 
    sys.stdout = fsock 
    write_stats(statistic)
    sys.stdout = saveout

def main(argv = None):
	parser = make_parser()
	args = parser.parse_args()

	lines = read_file(args.in_file)
	stats = make_stats(lines, str_to_nr(args.column_name, args.in_file))
	try:
		save_to_file(stats, args.out_file)
	except:
		write_stats(stats)

if __name__ == '__main__':
	main()
