#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Author: Paweł Kedzia

Created on 2012-01-27

For given pair of files:
  - file with row labels
  - wile with cluto groupping (*.num_of_groups) results (one row is number of group to which belongs)
Makes files (with number equal number of groups) with groupped rows (taken from row labels)
'''

import os, codecs

def make_parser():
	import argparse

	parser = argparse.ArgumentParser()

	parser.add_argument('-r', '--rowlabel', dest = 'rowlabel', required = True)
	parser.add_argument('-g', '--clutogroups', dest = 'clutogroups', required = True, 
			help = 'Path to file (*.num_of_groups) with list of the rows ordered by the Cluto')
	parser.add_argument('-o', '--outdir', dest = 'outdir', required = True,
			help = 'Path to output directory to store groups')
	parser.add_argument('-v', '--verbose', dest = 'verbose', action = 'store_true')
	return parser

def run_splitting(rowlabel, clutogroups, verbose):
	'''
	Params:
	 - rowlabel - path to rows labels
	 - clutogroups - path to file contains list of ordered rows (*.num_of_groups file)
	'''
	if verbose:
		print 'Opening %s file...' % rowlabel
	row_file = open_file_to_read(rowlabel)
	rlabels = read_file_to_list(row_file)
	close_file(row_file)

	if verbose:
		print 'Opening %s file...' % clutogroups
	grp_file = open_file_to_read(clutogroups)
	groups = read_file_to_list(grp_file)
	close_file(grp_file)

	if verbose:
		print 'Making groups...'
	
	gr2words = {}

	for gr_nbr, group in enumerate(groups):
		if not gr2words.has_key(group):
			gr2words[group] = []
		gr2words[group].append(rlabels[gr_nbr])
	return gr2words

def open_file_to_read(filepath):
	return codecs.open(filepath, 'rb', 'utf8')

def open_file_to_write(filepath):
	return codecs.open(filepath, 'wb', 'utf8')

def close_file(file_fp):
	file_fp.close()

def read_file_to_list(file_fp):
	n_lsit = []
	for l in file_fp:
		n_lsit.append(l)
	return n_lsit

def save_groups(gr2words, outdir, verbose):
	if not os.path.exists(outdir):
		if verbose:
			print 'Making output directory %s...' % outdir
		os.makedirs(outdir)
	
	if verbose:
		print 'Saving groups to files...'

	for gr, words in gr2words.iteritems():
		gr_file_path = os.path.join(outdir, 'group__%s.txt' % gr.strip())
		gr_file = open_file_to_write(gr_file_path)

		if verbose:
			print '  Saving words to group file: %s' % gr_file_path

		for w in words:
			gr_file.write(w.strip())
			gr_file.write('\n')
		close_file(gr_file)

def main():
	parser = make_parser()
	args = parser.parse_args()
	gr2words = run_splitting(args.rowlabel, args.clutogroups, args.verbose)
	save_groups(gr2words, args.outdir, args.verbose)

if __name__ == '__main__':
	main()
