'''
Created on Aug 7, 2011
@author: Dilum Bandara
@contact: dilumb@engr.colostate.edu
@version: 0.1
@copyright: Copyright(c) 2011, Dilum Bandara
@license: GPL
'''

'''
Extract data from file & save community information & messages separately
Also extract routing and AS information
'''
import sys;

fIn1 = 'dumpQueries_' + sys.argv[1] + '.txt'
fIn2 = 'dumpRoutingTable' + sys.argv[1] + '.txt'
fIn3 = 'dumpTopology' + sys.argv[1] + '.brite'
fOut1 = 'QueryTrace_' + sys.argv[1] + '.txt'
fOut2 = 'Nodes' + sys.argv[1] + '.txt'
fOut3 = 'RoutingTable' + sys.argv[1] + '.txt'
fOut4 = 'ASTable' + sys.argv[1] + '.txt'

#Extract query message data
'''
fdIn = open(fIn1, 'r')
fdOut1 = open(fOut1, 'w')
fdOut2 = open(fOut2, 'w')
for line in fdIn: #Extract information
    tmp = line.split()
    if len(tmp) == 0: continue #Skip blank lines
    if tmp[0] == 'PATH':
        if ((len(tmp) - 4) != (int(tmp[-1]) + 1)) and (tmp[3] != tmp[4]):
            print 'Path length & no of intermediate nodes don\'t match'
            print tmp
            sys.exit(0)
        elif len(tmp) == 5: #Query resolved at same node
            tmp.insert(4, tmp[3])
        for i in range(len(tmp) - 1):
            fdOut1.write(tmp[i + 1] + '\t')
        fdOut1.write('\n')
    elif tmp[0] == 'GID':
        fdOut2.write(tmp[1] + '\t' + tmp[2] + '\n')
fdIn.close()
fdOut1.close()
fdOut2.close()
'''

#Extract Routing data
fdIn = open(fIn2, 'r')
fdOut3 = open(fOut3, 'w')
fdOut4 = open(fOut4, 'w')
for line in fdIn: #Extract information
    tmp = line.split()
    if len(tmp) == 0: continue #Skip blank lines
    if tmp[0] == 'ROUTE':        
        for i in range(len(tmp) - 1):
            fdOut3.write(tmp[i + 1] + '\t')
        fdOut3.write('\n')
    elif tmp[0] == 'ASNO':
        fdOut4.write(tmp[1] + '\t' + tmp[2] + '\n')
fdIn.close()
fdOut3.close()
fdOut4.close()

#Extract latency of transit link latency
nodeData = False
topologyData = False
borderRouters = []
latency = []
fdIn = open(fIn3, 'r')
for line in fdIn: #Extract information
    tmp = line.split()
    if len(tmp) == 0: continue #Skip blank lines
    if tmp[0] == 'Nodes:': 
       nodeData = True #Start reading node data
       continue
    if tmp[0] == 'Edges:': 
       topologyData = True #Start reading node data
       continue
    if nodeData == True:
        if len(tmp) == 0: nodeData = False
        else:
            if tmp[-1] == 'RT_BORDER': borderRouters.append(tmp[0])
    if topologyData == True:
        if len(tmp) == 0: topologyData = False
        else: #If both src & dest is border routers
            #if tmp[1] in borderRouters and tmp[2] in borderRouters:
            #    latency.append(float(tmp[4]))
            latency.append(float(tmp[4]))
            #print float(tmp[3])/float(tmp[4])
fdIn.close()
#print latency
print 'Ave. transit link latency', sum(latency)/len(latency)
