#!/usr/bin/wish -f

set sockid [socket localhost 9600]

set size 200  
set base 200 
set index 0
set scale 50
set start 1
set step 3
set cwidth [expr $size * $step + $start]
set cheight [expr $base * 2]
set sregion [list 0 -1000 $cwidth 1000]
set maxwidth 800
set wwidth [expr ($cwidth > $maxwidth) ? $maxwidth : $cwidth]
set wheight [expr $base * 2]

	     
set colors { #00f #01e #02d #03c #04b #05a #069 #078 #087 #096 #0a5 #0b4 #0c3 #0d2 #0e1 #0f0
	     #0f0 #1e0 #2d0 #3c0 #4b0 #5a0 #690 #780 #870 #960 #a50 #b40 #c30 #d20 #e10 #f00}


set numcolors [llength $colors]

canvas .c -scrollregion $sregion -width $wwidth -height $wheight -xscrollincrement 1 -xscrollcommand ".s set"
scrollbar .s -orient horizontal -command ".c xview"
pack .s -side bottom -fill x
pack .c -side top -expand yes -fill both

set xmax 400
set ymax 400
set average 0
set total 0
set x 1
set y 1
while { 1 } { 
    gets $sockid inputString

    #puts "Input String :$inputString:"

    if {[string match *FFT_Result* $inputString]} {

	#puts "Found start of record" 

	# calculate average level
	set average [expr int($total/$x)]
	set total 0

	# start a new line
	set y [expr $y+1]

	# Flush the output to the screen
	update idletasks
    
    } else {

	scan $inputString " %d %f " a b

	if { $a > 10 } {

	    set c [expr int($b)] 
	    set x $a

	    set aveDiv [expr 1+($average/100)] 

	    set colorIndex [expr ((($c - $average)/($aveDiv))+($numcolors/2))]

	    #puts "$inputString $a $b $c $average $colorIndex "	

	    if {  ( $colorIndex < 0 ) } {
		set colorIndex 0
	    } elseif { ( $colorIndex > $numcolors ) } {
		set colorIndex [expr $numcolors-1]
	    }
	    

	    
	    .c create line $x $y [expr $x + 1] [expr $y + 1] -fill [lindex $colors $colorIndex ]
	    
	    # accumulate values for next average 
	    set total [expr $total+$b]

	}    
    }
}


















