#!/usr/bin/env python

import sys
import pstats
import cProfile
from cStringIO import StringIO
def profile(fn):
	def wrapper(*args, **kwargs):
		profiler = cProfile.Profile()
		stream = StringIO()
		profiler.enable()
		try:
			res = fn(*args, **kwargs)
		finally:
			profiler.disable()
			stats = pstats.Stats(profiler, stream=stream)
			stats.sort_stats('time')
			print >>stream, ""
			print >>stream, "=" * 100
			print >>stream, "Stats:"
			stats.print_stats()

			print >>stream, "=" * 100
			print >>stream, "Callers:"
			stats.print_callers()

			print >>stream, "=" * 100
			print >>stream, "Callees:"
			stats.print_callees()
			print >>sys.stderr, stream.getvalue()
			stream.close()
		return res
	return wrapper


import getopt
from os.path import dirname, join

sys.path.append(join(dirname(__file__), '..'))

import mmseg
def process_tokens(stdin, separator,ttype):
	algor = mmseg.Algorithm(stdin)
	wlist = list();
	for tk in algor:
		if ttype is None or ttype == 'n':
			wlist.append(tk.text);
		else:
			wlist.append(tk.text + '/' + tk.pos.strip('\0'));
	return separator.join(wlist);

@profile
def split_file(ifile,ofile,ttype):
	try:
		fp = open(ifile,'r');
		fo = open(ofile,'w+');
		for line in fp.readlines():
			if len(line) == 0 or line[0] == '#': continue;
			line = line.strip('\r').strip('\n');
			out = process_tokens(line,' ',ttype);
			fo.write(out + '\n');
		fp.close();
		fo.close();
	except Exception as e:
		fp.close();
		fo.close();
		raise e;

def print_usage():
	print """
mmseg  Segment Chinese text. Read from ifile and print to ofile.

Options:
	-h
	--help       Print this message
	-i           input file
	-o           output file
	-t           print type[p|n] print the characteristic of a certain word if select p
	-s
	--separator  Select the separator of the segmented text. Default is space.
"""
	sys.exit(0)

separator = " "
ifile = ofile = ttype = None;

optlst, args = getopt.getopt(sys.argv[1:], 'hs:i:o:t:')

for opt, val in optlst:
	if opt == '-h':
		print_usage();
	elif opt == '-i':
		ifile = val;
	elif opt == '-o':
		ofile = val;
	elif opt == '-t':
		ttype = val;
	elif opt == '-s':
		separator = val
if ifile is None or ofile is None:
	print_usage();

# load default dictionaries
mmseg.dict_load_defaults();
split_file(ifile,ofile,ttype);
