#!/usr/bin/python

import sys
import os
import re


pattern = None
rtt_arr = []
snd_cwnd_arr = []



def analyseLine(line):
   match = pattern.match(line)

   #print line
   
   if match:
       #print "Matched!"
       #print match.groups()
       
       rtt = match.group(1)
       rtt_arr.append(float(rtt))
       
       rttvar = match.group(2)
       
       snd_cwnd = match.group(3)
       snd_cwnd_arr.append(float(snd_cwnd))
       
       send = match.group(4)
       
   else:
       #print "Not Matched!"
       pass


def printMeanValue(title, arr):
    print title

    print arr

    length = len(arr)
    print "length: %d" % length
    print "25th Percentile: " + str(arr[int(length*0.25)])
    print "50th Percentile: " + str(arr[int(length*0.50)])
    print "75th Percentile: " + str(arr[int(length*0.75)])
    print "95th Percentile: " + str(arr[int(length*0.95)])

    # average value
    sum = 0.0
    for a in arr:
        sum += a
    print "* Average Value: " + str(sum/length)




def doStatistic():
    printMeanValue("RTT:", rtt_arr)
    printMeanValue("snd_cwnd:", snd_cwnd_arr)


def usage():
    print "Usage:"
    print "   ss -t -i | ./analyse_ss.py"
    print "Or"
    print "   echo \"xxxxxxx\" | ./analyse_ss.py"


if __name__ == "__main__":
    if len(sys.argv) != 1:
        usage()
        os._exit(2)

    '''
    cubic wscale:7,7 rto:204 rtt:0.079/0.118 ato:40 mss:24576 cwnd:10 send 24887.1Mbps rcv_space:43690
    '''
    pattern = re.compile(r'.*rtt:([0-9\.]+)/([0-9\.]+).*cwnd:([0-9\.]+).*send ([0-9\.MK]+)')

    try:
        while True:
            line = sys.stdin.readline()
            if line:
                analyseLine(line)
            else:
                break
    except Exception as e:
        print e


    doStatistic()

    os._exit(0)

@@ -412,20 +412,18 @@
 .append(
-floa
+in
 t(snd_cw
@@ -556,16 +556,57 @@
 , arr):%0A
+    print %22###########################%22 %0A
     prin
@@ -647,24 +647,40 @@
  = len(arr)%0A
+    arr.sort()%0A%0A
     print %22l
@@ -685,16 +685,20 @@
 %22length:
+    
  %25d%22 %25 l
@@ -722,32 +722,35 @@
 25th Percentile:
+   
  %22 + str(arr%5Bint
@@ -784,32 +784,35 @@
 50th Percentile:
+   
  %22 + str(arr%5Bint
@@ -826,16 +826,24 @@
 *0.50)%5D)
+ + %22  *%22
 %0A    pri
@@ -854,32 +854,35 @@
 75th Percentile:
+   
  %22 + str(arr%5Bint
@@ -924,16 +924,19 @@
 centile:
+   
  %22 + str
@@ -1040,17 +1040,16 @@
  print %22
-*
  Average
@@ -1056,23 +1056,31 @@
  Value: 
-%22 + str
+    %25.3f  *%22 %25 
 (sum/len

fix bug: forget to sort.