#!/usr/bin/env python
import os, sys, re
import string
import socket, threading
import StringIO

_MAX_BUFFER_SIZE_ = 102400 #100KB

pat=re.compile("<fs af='(.*?),(.*)'")

def findPos(str1):
	count=0
	list1=[]
	for ch in str1:
		if(ch=='Z'):
			list1.append(count)
		count+=1
	return list1

def addNukta(str1,list1):
	count=0
	newstr=''
	index=0
#	print str1
#	print list1
	for ch in str1:
#		print count,index
		if(len(list1) > index and count==list1[index] and ch!="Z"):
#			print "here"
			newstr+="Z"
			index+=1
			for i in xrange(index,len(list1),1):
				list1[i]-=1
#				print list1
		elif(ch=="Z"):
			index+=1

		newstr+=ch
		count+=1
	if(len(list1) > index and len(str1)==list1[index]):
		newstr+="Z"
	return newstr

def processInput(f):
        result = ""
        for i in f:
	#	print i.strip("\n")

		arr=i.split("\t")
		if(not len(arr)>=3):
			result += i
			continue
		fss=arr[3].split("|")
		lex=arr[1]
		pos=findPos(lex)
	#	print pos
		final_fs=''
		if(len(pos)):
			for fs in fss:
				lex_root=re.findall(pat,fs)
				rest_fs=lex_root[0][1]
	#			print lex_root
				lex_root=addNukta(lex_root[0][0],pos)
				final_fs+="<fs af='"+lex_root+","+rest_fs+"'>|"
			result += arr[0]+"\t"+arr[1]+"\t"+arr[2]+"\t"+final_fs.rstrip("|")+'\n'
		else:
			result += i
        return result

class ClientThread(threading.Thread):

    def __init__(self,ip,port,clientsocket):
        threading.Thread.__init__(self)
        self.ip = ip
        self.port = port
        self.csocket = clientsocket
        #print "[+] New thread started for "+ip+":"+str(port)

    def run(self):
        #print "Connection from : "+ip+":"+str(port)

        data = self.csocket.recv(_MAX_BUFFER_SIZE_)
        #print "Client(%s:%s) sent : %s"%(self.ip, str(self.port), data)
        fakeFile = StringIO.StringIO(data)
        data = processInput(fakeFile)
        fakeFile.close()
        self.csocket.send(data)
        self.csocket.close()

        #print "Client at "+self.ip+" disconnected..."

host = "0.0.0.0" #Listen on all interfaces
port = eval(sys.argv[1]) #Port number

tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

tcpsock.bind((host,port))

while True:
    tcpsock.listen(4)
    #print "nListening for incoming connections..."
    (clientsock, (ip, port)) = tcpsock.accept()

    #pass clientsock to the ClientThread thread object being created
    newthread = ClientThread(ip, port, clientsock)
    newthread.start()
