'''
Build WStattions file
'''


fdIn = open('SReadings_final.txt', 'r')
fdOut = open('WStations.txt', 'w')

sTime = {} #Times that sensor readings are available
sensors = {}
for line in fdIn:
    l = line.split()
    sID = int(l[0])
    t = int(l[1])
    if sID in sTime:
        td = t - sTime[sID][0]
        if td not in sTime[sID][1]: sTime[sID][1][td] = 1
        else: sTime[sID][1][td] += 1
        sTime[sID][0] = t
    else: sTime[sID] = [t, {}, [l[3], l[5], l[7]]]
    if 'DD' in l:
        if sID in sensors and 'DD' not in sensors[sID]: sensors[sID].append('DD')
        else: sensors[sID] = ['DD']
    if 'FF' in l:
        if sID in sensors and 'FF' not in sensors[sID]: sensors[sID].append('FF')
        else: sensors[sID] = ['FF']
    if 'P' in l:
        if sID in sensors and 'P' not in sensors[sID]: sensors[sID].append('P')
        else: sensors[sID] = ['P']
    if 'T' in l:
        if sID in sensors and 'T' not in sensors[sID]: sensors[sID].append('T')
        else: sensors[sID] = ['T']
    if 'RH' in l:
        if sID in sensors and 'RH' not in sensors[sID]: sensors[sID].append('RH')
        else: sensors[sID] = ['RH']
fdIn.close()

maxInterval = -1
for id in sorted(sTime.keys()):
    maxTime = -1
    maxCount = -1
    for j in sTime[id][1]:
        if sTime[id][1][j] > maxCount: 
            maxTime = j
            maxCount = sTime[id][1][j]
    if maxTime == -1: 
        print 'Few samples at', id
        continue
    if maxTime > maxInterval: maxInterval = maxTime
    tmpStr = str(id) + '\t' + sTime[id][2][0] + '\t' + sTime[id][2][1] + '\t' + sTime[id][2][2] + '\t' + str(maxTime)
    for att in sensors[id]: tmpStr += '\t' + att
    fdOut.write(tmpStr + '\n')
print maxInterval
fdOut.close()
