# -*- coding: utf-8 -*-
import sys
################## Read various files ###################################################
unigram = open('filteredcorpus.txt').read().decode('utf-8').strip().split('\n')
alpha = open('alphabets').read().translate(None,'\n').decode('utf-8')


#####################    Replace alphabet by Phonemes   ############################################################
def r_phoneme(phone, a, b, word):
	index = 0;
	for i in word:
		for j in range(len(a)):
			if(i.encode('utf-8') == a[j]):
				if(b[j]  != "_"):
					w = word[0:index]+b[j].decode('utf-8')+word[index+1:]
					phone.append(w)
				else:
					w = word[0:index]+word[index+1:]
					phone.append(w)
		index = index + 1;
	index =0;
	for i in word:
		for j in range(len(b)):
			if(i.encode('utf-8') == b[j]):
				if(b[j]  != "_"):
					w = word[0:index]+a[j].decode('utf-8')+word[index+1:]
					phone.append(w)
		index = index + 1;

#############################  Construct UniGram Dictionary ###########################################################
unigramdict = {}
for line in unigram:					
	ele=line.split()
	ele[1] = ele[1].strip();
	unigramdict[ele[1]] = int(ele[0].decode('utf-8'))


##########################    Find unigrams in dictionary #######################################################
def check(lwords, x):
	for w in lwords:
		try:
			fr = unigramdict[w];
			x.append([fr, w]);
		except:
			continue;

############################  Check existence of unigram ##########################################################
def check2(word):
	x=0
	try:
		x = unigramdict[word.decode('utf-8')]
	except:
		x=0
	if(x!=0):
		return 1
	else:
		return 0
	
##############################  Find Edit1-Distance  ###############################################################
def edits1(word):
   splits     = [(word[:i], word[i:]) for i in range(len(word) + 1)]
   deletes    = [a + b[1:] for a, b in splits if b]
   transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1]
   replaces   = [a + c + b[1:] for a, b in splits for c in alpha if b]
   inserts    = [a + c + b for a, b in splits for c in alpha]
   return set(deletes + transposes + replaces + inserts)



########## Suggestions(Unigram) #############################
spell = open("hi-spell1.txt")
prev_word = "";
for line in spell:
	prev_word = ""
	#print "----------------------------------------------------------------------------------"
	el=line.split(":")
	#print el[0].strip()
	x=el[1]
	x=x.strip();
	if(check2(x) == 1):
		x=x.decode('utf-8').strip()
		prev_word = x
		print x.encode('utf-8').strip()
		continue;
	else:
		x=x.decode('utf-8').strip()
		edits = edits1(x)
		uni=[]	
		check(edits, uni)
		uni.sort(key = lambda t:t[0], reverse=True)
		#print "\nUnigram suggestions for word: ", x.encode('utf-8')
		if(len(uni)==0):
			print x.encode('utf-8').strip()
		for j in range(1):
			if (uni and j<len(uni)):
				print uni[j][1].encode('utf-8')
				
		prev_word = x
