import sys

#In put arguments should follow event ID, bucket size, file name, run number
eventId = sys.argv[1]
#eventId = '9'
bucketSize = float(sys.argv[2])
genDistribution = 1

vecFile = "MyDHTTestApp-" + sys.argv[4] + ".vec"
dataFile1 = "data_" + sys.argv[3] + "_all-" + sys.argv[4] + ".txt"
dataFile2 = "data_" + sys.argv[3] + "_bucket-" + sys.argv[4] + ".txt"
dataFile3 = "data_" + sys.argv[3] + "_distri-" + sys.argv[4] + ".txt"

timeList = []
valueList = [] 

#Extract data
fVec = open(vecFile, "r")
#fData1 = open(dataFile1, "w")
for line in fVec:
    tmp = line.split()
    if len(tmp) == 0:
        continue
    if tmp[0] == eventId:
        timeList.append(float(tmp[2]))
        valueList.append(float(tmp[3]))
#        fData1.write(tmp[2] + '\t' + tmp[3] + '\n')
fVec.close()
#fData1.close()

#Extract data
if bucketSize > 0.0:
    fData2 = open(dataFile2, "w")
    beginTime = timeList[0]
    total = 0
    tmpValList = []
    i = 0

    for i in range(len(timeList)):
        if timeList[i] < (beginTime + bucketSize) :
            tmpValList.append(valueList[i])
        else:
            for k in range(len(tmpValList)):
                total = total + tmpValList[k]
            
            fData2.write(str(timeList[i-1]) + '\t' +  str(total/len(tmpValList))+ '\n')
            total = 0
            tmpValList = []
            tmpValList.append(valueList[i])  
            beginTime = timeList[i]

    for j in range(len(tmpValList)):
        total = total + tmpValList[j]
    fData2.write(str(timeList[i]) + '\t' +  str(total/len(tmpValList))+ '\n')
    fData2.close()

#Get the distribution
if genDistribution == 1:
    fData3 = open(dataFile3, "w")
    tmpList = {}
    for i in range(len(timeList)):
        if valueList[i] in tmpList:
            tmpList[valueList[i]] = tmpList[valueList[i]] + 1
        else:
            tmpList[valueList[i]] = 1

    for k in tmpList:
        fData3.write(str(k) + '\t' +  str(tmpList[k])+ '\n')
    fData3.close()
