#!/usr/local/bin/wish -f
#
# get data from pcbridged -t and shows them
#
set i 0
set w(width) 400
set w(height) 180
set w(min_bw) 1000 ; # less than 1KB/s is not worth resolution.
set w(max_bw) 1000000 ; # less than 1KB/s is not worth resolution.

set w(yscale)  [expr $w(height)*1.0/log($w(max_bw)/$w(min_bw))]
set w(bw_10k)  [expr $w(yscale)*log(10000.0/$w(min_bw))]
set w(bw_100k)  [expr $w(yscale)*log(100000.0/$w(min_bw))]

set w(color,1) white
set w(color,2) red
set w(color,3) yellow
set w(color,4) green
set w(color,5) orange

set w(color,bg) black
set w(color,font) fixed

. configure -background $w(color,bg)

proc ini {} {
    global i
    set i 0
}

proc nuovo {nm} {
    global i w
    incr i
    set w($nm) $i
    set w(x,$nm) 0
    # set w(bw,$nm) 0
    frame .f$i -background $w(color,bg)
    pack .f$i -fill x
    frame .f$i.l -background $w(color,bg)
    pack .f$i.l -side left -fill x -expand 1
    canvas .f$i.c -width $w(width) -height $w(height) -background black
    pack .f$i.c -side right -anchor se
    .f$i.c create line 0 0 [expr $w(width) -1] 0 -fill white
    .f$i.c create line 0 $w(bw_10k) [expr $w(width) - 1] $w(bw_10k) -fill green
    .f$i.c create line 0 $w(bw_100k) [expr $w(width) - 1] $w(bw_100k) -fill blue
    label .f$i.l.l -text "***** Bridge $nm *****" \
	-relief raised \
	-font $w(color,font)
    pack .f$i.l.l -side top -anchor nw -fill x
    for {set idx 1} {$idx < 6} {incr idx} {
	set w(prevy,$idx,$nm) $w(height)
	label .f$i.l.l$idx -textvariable w(bw,$idx,$nm) \
	    -background $w(color,bg) -foreground $w(color,$idx) \
	    -font $w(color,font)
	pack .f$i.l.l$idx -side top -anchor nw
    }
}

proc processa {a} {
    global w
    set idx [lindex $a 3] ; # port index
    set nm [lindex $a 4] ; # port name -- index is 3
    set main_nm [lindex $a 5] ; # main port name -- index is 3
    set bw [lindex $a 8] ; # aggregate bandwidth
    set deltat [lindex $a 9] ; # delta t
    if [expr  $deltat < 1 ] {
	set deltat 1 
    }
    set w(bw,$idx,$main_nm) [format "$nm BW: %6d B/s" [expr $bw / $deltat] ]
    if [catch {set w($main_nm)}] {
	nuovo $main_nm
    }
    set c .f$w($main_nm).c ; # canvas id.
    set x $w(x,$main_nm)
    if [expr $idx == 1 ] {
        set w(x,$main_nm) [expr ($w(x,$main_nm) + 1) % $w(width)]
	set x $w(x,$main_nm)
	$c create line $x 0 $x [expr $w(height)-1] -fill black
    }
    set bw [expr $bw / $deltat]
    if [expr $bw < $w(min_bw) ] {
	set bw $w(min_bw)
    }
    set y  [expr $w(height)- $w(yscale)*log(1.0*$bw/$w(min_bw))]
    $c create line $x [expr $y + 1] $x $y -fill $w(color,$idx)
    set w(prevy,$idx,$nm) $y
}

while {[gets stdin a] != -1 } {
    update
    processa "$a"
}
