#!/bin/sh  
# \
  exec oagwish "$0" "$@"

#
#

set auto_path [linsert $auto_path 0  /usr/local/oag/apps/lib/$env(HOST_ARCH)]
set auto_path [linsert $auto_path 0 /usr/local/oag/lib_patch/$env(HOST_ARCH)]
APSDebugPath
#lappend auto_path $blt_library
set args $argv
set plane x
set lab 0
set virtual 1
APSStrictParseArguments {plane lab virtual}

set CVSRevisionAuthor "\$Revision: 1.0 $ \$Author: shang $"

wm geometry . +20+20
if $lab {
    set name "Storage Ring [string toupper $plane] plane ID BPLD Position Limit Display (lab)"
} else {
    set name "Storage Ring [string toupper $plane] plane ID BPLD Position Limit Display"
}
APSApplication . -name "$name" -version $CVSRevisionAuthor\
  -overview "SRBPLD Displays the position of the beam in the Storage Ring\
	with axis limits given by the Beam Position Limit Detectors.  A white dot\
	indicates that the beam is in the safe zone.  A yellow dot indicates the\
	beam is between 0.3 mm and 0.1 mm from the trip point.  A red dot indicates the\
	beam is 0.1 mm or closer to the trip point.  A red background indicates the\
   beam is outside the trip limits."

package require BLT 

#need creat new config if the limits changed
if $lab {
    set BPLD(configDir) /home/oxygen/DIAG/apsu/BPLD/BPLD_Config
    set BPLD(sectors) {1 3 5}
} else {
    set BPLD(configDir) /home/helios/oagData/sr/BPLD/BPLD_Config
    for {set i 1} {$i<=35} {incr i} {
	lappend BPLD(sectors) $i
    }
}


proc LoadBPLDConfig {args} {
    set sector ""
    set id ""
    APSParseArguments {sector id}
    set sector [scan $sector %d]
    set sectorf [format %02d $sector]
    global BPLD
    set oldDir [pwd]
    #cd /home/oxygen/DIAG/apsu/BPLD/BPLD_Config
    catch {exec $BPLD(configDir)/scripts/generateIDBPLDConfigPointBySector -sector $sector -id $id -configDir $BPLD(configDir) } result
   # puts $result
    set config $BPLD(configDir)/ID_BPLD_Config.S$sectorf$id.sdds
    set tmpRoot /tmp/[APSTmpString]
    foreach plane {x y} {
	if [catch {exec sddsprocess $config -match=par,plane=$plane $tmpRoot.$plane } result] {
	    return -code error "Error process config file: $result"
	}
	set BPLD(S$sectorf$id.${plane}Limit) [expr 1000.0 * [exec sdds2stream -par=OffsetLimit $tmpRoot.$plane]]
	set BPLD(S$sectorf$id.${plane}pLimit) [expr 1000.0 * [exec sdds2stream -par=AngleLimit $tmpRoot.$plane]]
	APSAddToTmpFileList -ID idbpld -fileList "$tmpRoot.x $tmpRoot.y"
    }
   
    set pointList [exec sdds2stream -col=Point $tmpRoot.$BPLD(plane)]
    foreach nm {P0P0 P1P1 P0P1 P1P0} {
	set ${nm}_x [exec sdds2stream -col=${nm}_x $tmpRoot.$BPLD(plane)]
	set ${nm}_xp [exec sdds2stream -col=${nm}_xp $tmpRoot.$BPLD(plane)]
    }
    set rows [llength $pointList]
  #  puts $rows
    for {set i 0} {$i<$rows} {incr i} {
	set j [expr $i+1]
	foreach nm {P0P0 P1P1 P0P1 P1P0} {
	    set BPLD(S$sectorf$id.$j.$nm.x) [expr 1000.0*[lindex [set ${nm}_x] $i]]
	    set BPLD(S$sectorf$id.$j.$nm.xp) [expr 1000.0 *[lindex [set ${nm}_xp] $i]]
	}
    }
    
}

proc DrawBoundary {Name args} {
    set sector ""
    set id ""
    APSParseArguments {sector id}
    
    global ID BPLD
    set sector [scan $sector %d]
    set sectorf [format %02d $sector]
    set type $ID(S$sectorf$id.IDtype)
   
   # puts "$sector $type"
    if {$BPLD(plane)=="x"} {
	set xdata1 [list $BPLD(S$sectorf$id.1.$type.x) $BPLD(S$sectorf$id.3.$type.x)]
	set ydata1 [list $BPLD(S$sectorf$id.1.$type.xp) $BPLD(S$sectorf$id.3.$type.xp)]
	set xdata2 [list $BPLD(S$sectorf$id.3.$type.x) $BPLD(S$sectorf$id.5.$type.x)]
	set ydata2 [list $BPLD(S$sectorf$id.3.$type.xp) $BPLD(S$sectorf$id.5.$type.xp)]
	set xdata3 [list $BPLD(S$sectorf$id.5.$type.x) $BPLD(S$sectorf$id.7.$type.x)]
	set ydata3 [list $BPLD(S$sectorf$id.5.$type.xp) $BPLD(S$sectorf$id.7.$type.xp)]
	set xdata4 [list $BPLD(S$sectorf$id.7.$type.x) $BPLD(S$sectorf$id.9.$type.x)]
	set ydata4 [list $BPLD(S$sectorf$id.7.$type.xp) $BPLD(S$sectorf$id.9.$type.xp)]
	set xdata5 [list $BPLD(S$sectorf$id.9.$type.x) $BPLD(S$sectorf$id.11.$type.x)]
	set ydata5 [list $BPLD(S$sectorf$id.9.$type.xp) $BPLD(S$sectorf$id.11.$type.xp)]
	set xdata6 [list $BPLD(S$sectorf$id.11.$type.x) $BPLD(S$sectorf$id.1.$type.x)]
	set ydata6 [list $BPLD(S$sectorf$id.11.$type.xp) $BPLD(S$sectorf$id.1.$type.xp)]
	
	.$Name element create line1 -xdata $xdata1 -ydata $ydata1 -color blue -symbol ""
	.$Name element create line2 -xdata $xdata2 -ydata $ydata2 -color blue -symbol ""
	.$Name element create line3 -xdata $xdata3 -ydata $ydata3 -color blue -symbol ""
	.$Name element create line4 -xdata $xdata4 -ydata $ydata4 -color blue -symbol ""
	.$Name element create line5 -xdata $xdata5 -ydata $ydata5 -color blue -symbol ""
	.$Name element create line6 -xdata $xdata6 -ydata $ydata6 -color blue -symbol ""
    } else {
	#for y plane, only diamond (4 points)
	set xdata1 [list $BPLD(S$sectorf$id.1.$type.x) $BPLD(S$sectorf$id.2.$type.x)]
	set ydata1 [list $BPLD(S$sectorf$id.1.$type.xp) $BPLD(S$sectorf$id.2.$type.xp)]
	set xdata2 [list $BPLD(S$sectorf$id.2.$type.x) $BPLD(S$sectorf$id.3.$type.x)]
	set ydata2 [list $BPLD(S$sectorf$id.2.$type.xp) $BPLD(S$sectorf$id.3.$type.xp)]
	set xdata3 [list $BPLD(S$sectorf$id.3.$type.x) $BPLD(S$sectorf$id.4.$type.x)]
	set ydata3 [list $BPLD(S$sectorf$id.3.$type.xp) $BPLD(S$sectorf$id.4.$type.xp)]
	set xdata4 [list $BPLD(S$sectorf$id.4.$type.x) $BPLD(S$sectorf$id.1.$type.x)]
	set ydata4 [list $BPLD(S$sectorf$id.4.$type.xp) $BPLD(S$sectorf$id.1.$type.xp)]
	.$Name element create line1 -xdata $xdata1 -ydata $ydata1 -color blue -symbol ""
	.$Name element create line2 -xdata $xdata2 -ydata $ydata2 -color blue -symbol ""
	.$Name element create line3 -xdata $xdata3 -ydata $ydata3 -color blue -symbol ""
	.$Name element create line4 -xdata $xdata4 -ydata $ydata4 -color blue -symbol ""
    }
	
}

#
# Creates a new graph
#
proc displayGraph {args} {
    set minX -1000
    set maxX 1000
    set minY -250
    set maxY 250
    set Xpos 0
    set Ypos 0
    set Title "No Title"
    set Name [APSUniqueName a]
    set width 190
    set width 250
    set height 150
    set height 160
    set sector ""
    set id ID1
    APSStrictParseArguments {minX maxX minY maxY Title Name Xpos Ypos Frame sector id}
    
    blt::graph .$Name -cursor crosshair -width $width -height $height -bg black \
      -title $Title -topmargin 15 -rightmargin 5 -bottommargin 25 \
      -leftmargin 35 -fg white -plotbackground #737373
    .$Name xaxis configure -color white -background black -max $maxX -min $minX 
    .$Name yaxis configure -color white -background black -max $maxY -min $minY 
    
    .$Name element create dot -xdata $Xpos -ydata $Ypos \
      -symbol circle -color white -pixels 0.5 -linewidth 0.5
    #.$Name element create line1 -xdata {-1000 0} -ydata {0 250} -color 
    DrawBoundary $Name -sector $sector -id $id
    
    .$Name legend configure -hide yes
    pack .$Name -in $Frame -side left
    return
}

#
# Changes the plot of an existing graph
#
proc modifyGraph {Name Xpos Ypos minX maxX minY maxY args} {
  #  set ID ID1
    set sector ""
    set id ""
    APSParseArguments {sector id}
    .$Name element delete dot
    .$Name element create dot -xdata $Xpos -ydata $Ypos
    
    set bottomY [expr $Ypos - $minY]
    set topY [expr $maxY - $Ypos]
    set background black
    set warning white

    global BPLD ID virtual
    
    set sector [scan $sector %d]
    set sectorf [format %02d $sector]
    global ID1P1$sectorf ID1P2$sectorf ID2P1$sectorf ID2P2$sectorf
    set statusVar BPLD(S${sectorf}${id}Status)
    
    set plane $BPLD(plane)
    set xLimit $BPLD(S$sectorf$id.${plane}Limit)
    set yLimit $BPLD(S$sectorf$id.${plane}pLimit)
    set P1pos [set ${id}P1$sectorf]
    set P2pos [set ${id}P2$sectorf]
    if {[expr abs($P1pos)]>[expr abs($P1pos)]} {
	set pPos $P1pos
    } else {
	set pPos $P2pos
    }
    set leftX [expr $pPos - $minX]
    set rightX [expr $maxX - $pPos]
    set type $ID(S$sectorf$id.IDtype)
    set refAngle 0
    set angle 0
    #y plane has only diaomond boundary, simpler
    set status 0
    set warning white
    set background black
    if !$virtual {
	if {$pPos<$minX || $pPos>$maxX || $Ypos<$minY || $Ypos>$maxY} {
	    set warning green
	    set background red
	    set status 3
	} else {
	    if {$pPos>0} {
		if {$topY<=[expr 0.3*$maxY]} {
		    set warning red
		    set status 2
		} elseif {$topY<=[expr 0.6*$maxY]} {
		    set warning yellow
		    set status 1
		}
	    } else {
		if {$bottomY<=[expr 0.3*$maxY]} {
		    set warning red
		    set status 2
		} elseif {$bottomY<=[expr 0.6*$maxY]} {
		    set warning yellow
		    set status 1
		}
	    }
	    if {$pPos>0} {
		if {$rightX<=[expr 0.3*$maxX]} {
		    set warning red
		    set status 2
		} elseif {$rightX<=[expr 0.6*$maxX]} {
		    set warning yellow
		    set status 1
		}
	    } else {
		if {$leftX<=[expr 0.3*$maxX]} {
		    set warning red
		    set status 2
		} elseif {$leftX<=[expr 0.6*$maxX]} {
		    set warning yellow
		    set status 1
		}
	    }
	}
	set $statusVar $status
	pv putw $statusVar
	.$Name element configure dot -color $warning
	.$Name configure -fg $warning -bg $background
	return
    }
    if {$BPLD(plane)=="y"} {
	if {$Xpos<$minX || $Xpos>$maxX || $Ypos<$minY || $Ypos>$maxY} {
	    set warning green
	    set background red
	    set status 3
	} elseif {$Ypos>=0} {
	    if {$Xpos<0} {
		set angle [expr abs($Ypos)/($xLimit+$Xpos)]
		set refAngle $ID(S$sectorf$id.trig1)
	    } else {
		set angle [expr abs($Ypos)/($xLimit-$Xpos)]
		set refAngle $ID(S$sectorf$id.trig2)
	    }
	} else {
	    if {$Xpos<=0} {
		set angle [expr abs($Ypos)/($xLimit+$Xpos)]
		set refAngle $ID(S$sectorf$id.trig4)
	    } else {
		set angle [expr abs($Ypos)/($xLimit-$Xpos)]
		set refAngle $ID(S$sectorf$id.trig3)
	    }
	}
    } else {
	if {$Xpos<$minX || $Xpos>$maxX || $Ypos<$minY || $Ypos>$maxY} {
	    set warning green
	    set background red
	    set status 3
	} elseif {$Ypos>=0} {
	    #if {$Xpos!=0} {
		set angle [expr abs($Ypos)/(abs($minX)-abs($Xpos))]
	    #}
	    if {$Xpos<$BPLD(S$sectorf$id.3.$type.x)} {
		#trig1
		set refAngle $ID(S$sectorf$id.trig1)
	    } elseif {$Xpos<$BPLD(S$sectorf$id.5.$type.x)} {
		#top rectangle, only need check the Ypos
		if {$topY < [expr .1*$maxY]} {
		    set warning red
		} elseif {$topY < [expr .3*$maxY]} {
		    set warning yellow
		}
	    } else {
		#trig2
		set refAngle $ID(S$sectorf$id.trig2)
	    }
	} else {
	    #Ypos<0
	   # if {$Xpos!=0} {
		set angle [expr abs($Ypos)/(abs($minX)-abs($Xpos))]
	   # }
	    if {$Xpos<$BPLD(S$sectorf$id.11.$type.x)} {
		#trig4
		set refAngle $ID(S$sectorf$id.trig4)
	    } elseif {$Xpos<$BPLD(S$sectorf$id.9.$type.x)} {
		#bottom rectangular
		if {$bottomY < [expr .1 * $maxY]} {
		    set warning red
		} elseif {$bottomY < [expr .3 * $maxY]} {
		    set warning yellow
		}
	    } else {
		#trig3
		set refAngle $ID(S$sectorf$id.trig3)
	    }
	}
    }
    set angle [format %0.3f $angle]
    set refAngle [format %0.3f $refAngle]
    if $refAngle>0 {
	set delta [expr abs($angle-$refAngle)]
	if {$angle>$refAngle} {
	    set background red
	    set warning green
	    set status 3
	} elseif {$delta<[expr 0.05*$refAngle]} {
	    set warning red
	    set status 2
	} elseif {$delta<[expr 0.2*$refAngle]} {
	    set warning yellow
	    set status 1
	}
    }
    set $statusVar $status
    pv putw $statusVar
    .$Name element configure dot -color $warning
    .$Name configure -fg $warning -bg $background

    return
   
}


set BPLD(plane) $plane
#LoadBPLDConfig 
#read BPLD bpm configuration
set configFile $BPLD(configDir)/config.sdds
set tmpRoot /tmp/[APSTmpString]
set sectors 40
#set xLimit $BPLD(${plane}Limit)
#set yLimit $BPLD(${plane}pLimit)
# (only 1,3,5 available now)
if $lab {
    set BPLD(sectors) {1 3 5}
} else {
    set BPLD(sectors)  [exec sdds2stream -col=Sector /home/helios/oagData/sr/BPLD/doubleSectors.sdds]
}

set tmpRoot /tmp/[APSTmpString]

foreach sector $BPLD(sectors) {
    set sectorf [format %02d $sector]
    lappend sectorList [format %02d $sector]
    APSAddToTmpFileList -ID idbpld -fileList $tmpRoot.S$sectorf
    if [catch {exec sddsprocess $configFile $tmpRoot.S$sectorf \
		   -filter=col,BPLDSector,$sector,$sector} bpmList] {
	puts stderr "Error getting ID BPLD bpms: $bpmList"
	exit 1
    }
    set indexList [exec sdds2stream -col=BPLDIndex $tmpRoot.S$sectorf]
    set bpmList [exec sdds2stream -col=DeviceName $tmpRoot.S$sectorf]
    
    #load bpld config
   # puts $sector
    LoadBPLDConfig -sector $sector -id ID1
    LoadBPLDConfig -sector $sector -id ID2
    
    #read bpm index from ioc
    if [catch {exec cavget -list=S${sectorf}-LMPS:BPLD:ID1:BPM-XY -list=1,2 -list=_idx-SP -pend=10 } ID1Index] {
	return -code error "Error reading S$sectorf ID1 index: $ID1Index"
    }
    if [catch {exec cavget -list=S${sectorf}-LMPS:BPLD:ID2:BPM-XY -list=1,2 -list=_idx-SP -pend=10 } ID2Index] {
	return -code error "Error reading S$sectorf ID1 index: $ID1Index"
    }
    
    set sectorf [format %02d $sector]
    set ID(S${sectorf}ID1.bpm1) [lindex $bpmList [lsearch -exact $indexList [lindex $ID1Index 0]]]
    set ID(S${sectorf}ID1.bpm2) [lindex $bpmList [lsearch -exact $indexList [lindex $ID1Index 1]]]
    
    set sector1 [expr $sector+1]
    set sector1f [format %02d $sector1]
    set ID(S${sectorf}ID2.bpm1) [lindex $bpmList [lsearch -exact $indexList [lindex $ID2Index 0]]]
    set ID(S${sectorf}ID2.bpm2) [lindex $bpmList [lsearch -exact $indexList [lindex $ID2Index 1]]]

    if [regexp {P0} $ID(S${sectorf}ID1.bpm1)] {
	set up P0
    } elseif [regexp {P1} $ID(S${sectorf}ID1.bpm1)] {
	set up P1
    } else {
	puts stderr "Error: invalid bpm ($ID(S${sectorf}ID1.bpm1) is used for S$sectorf ID1 upstream"
	exit 1
    }
    if [regexp {P0} $ID(S${sectorf}ID1.bpm2)] {
	set down P0
    } elseif [regexp {P1} $ID(S${sectorf}ID1.bpm2)] {
	set down P1
    } else {
	puts stderr "Error: invalid bpm ($ID(S${sectorf}ID1.bpm2) is used for S$sectorf ID1 downstream"
	exit 1
    }
    
    set ID(S${sectorf}ID1.IDtype) $up$down
    set xLimit $BPLD(S${sectorf}ID1.xLimit)
    if {$BPLD(plane)=="x"} {
	#first  x<0 xp>0
	set ID(S${sectorf}ID1.trig1) [expr abs($BPLD(S${sectorf}ID1.3.$up$down.xp))/($xLimit - abs($BPLD(S${sectorf}ID1.3.$up$down.x)))]
	#second x>0 xp>0
	set ID(S${sectorf}ID1.trig2) [expr abs($BPLD(S${sectorf}ID1.5.$up$down.xp))/($xLimit - abs($BPLD(S${sectorf}ID1.5.$up$down.x)))]
	#third x>0 xp<0
	set ID(S${sectorf}ID1.trig3) [expr abs($BPLD(S${sectorf}ID1.9.$up$down.xp))/($xLimit - abs($BPLD(S${sectorf}ID1.9.$up$down.x)))]
	#forth x>0 xp<0
	set ID(S${sectorf}ID1.trig4) [expr abs($BPLD(S${sectorf}ID1.11.$up$down.xp))/($xLimit - abs($BPLD(S${sectorf}ID1.11.$up$down.x)))]
    } else {
	#first  x<0 xp>0
	set ID(S${sectorf}ID1.trig1) [expr abs($BPLD(S${sectorf}ID1.2.$up$down.xp))/($xLimit +$BPLD(S${sectorf}ID1.2.$up$down.x))]
	#second x>0 xp>0
	set ID(S${sectorf}ID1.trig2) [expr abs($BPLD(S${sectorf}ID1.2.$up$down.xp))/($xLimit - $BPLD(S${sectorf}ID1.2.$up$down.x))]
	#third x>0 xp<0
	set ID(S${sectorf}ID1.trig3) [expr abs($BPLD(S${sectorf}ID1.4.$up$down.xp))/($xLimit - $BPLD(S${sectorf}ID1.4.$up$down.x))]
	#forth x>0 xp<0
	set ID(S${sectorf}ID1.trig4) [expr abs($BPLD(S${sectorf}ID1.4.$up$down.xp))/($xLimit + $BPLD(S${sectorf}ID1.4.$up$down.x))]
    }
    
    if [regexp {P0} $ID(S${sectorf}ID2.bpm1)] {
	set ID(S${sectorf}ID2.type) P0
	set up P0
    } elseif [regexp {P1} $ID(S${sectorf}ID2.bpm1)] {
	set ID(S${sectorf}ID2.type) P1
	set up P1
    } else {
	puts stderr "Error: invalid bpm ($ID(S${sectorf}ID2.bpm1) is used for S$sectorf ID2 upstream"
	exit 1	
    }
    if [regexp {P0} $ID(S${sectorf}ID2.bpm2)] {
	append ID(S${sectorf}ID2.type) P0
	set down P0
    } elseif [regexp {P1} $ID(S${sectorf}ID2.bpm2)] {
	append ID(S${sectorf}ID2.type) P1
	set down P1
    } else {
	puts stderr "Error: invalid bpm ($ID(S${sectorf}ID2.bpm2) is used for S$sectorf ID2 downstream"
	exit 1	
    }
			     
    set xLimit $BPLD(S${sectorf}ID2.xLimit)
    set ID(S${sectorf}ID2.IDtype) $up$down
    if {$BPLD(plane)=="x"} {
	#first  x<0 xp>0
	set ID(S${sectorf}ID2.trig1) [expr $BPLD(S${sectorf}ID2.3.$up$down.xp)/($xLimit-abs($BPLD(S${sectorf}ID2.3.$up$down.x)))]
	#second x>0 xp>0
	set ID(S${sectorf}ID2.trig2) [expr $BPLD(S${sectorf}ID2.5.$up$down.xp)/($xLimit-abs($BPLD(S${sectorf}ID2.5.$up$down.x)))]
	#third x>0 xp<0
	set ID(S${sectorf}ID2.trig3) [expr abs($BPLD(S${sectorf}ID2.9.$up$down.xp))/($xLimit-abs($BPLD(S${sectorf}ID2.9.$up$down.x)))]
	#forth x>0 xp<0
	set ID(S${sectorf}ID2.trig4) [expr abs($BPLD(S${sectorf}ID2.11.$up$down.xp))/($xLimit-abs($BPLD(S${sectorf}ID2.11.$up$down.x)))] 
    } else {
	#first  x<0 xp>0
	set ID(S${sectorf}ID2.trig1) [expr abs($BPLD(S${sectorf}ID2.2.$up$down.xp))/($xLimit +$BPLD(S${sectorf}ID2.2.$up$down.x))]
	#second x>0 xp>0
	set ID(S${sectorf}ID2.trig2) [expr abs($BPLD(S${sectorf}ID2.2.$up$down.xp))/($xLimit - $BPLD(S${sectorf}ID2.2.$up$down.x))]
	#third x>0 xp<0
	set ID(S${sectorf}ID2.trig3) [expr abs($BPLD(S${sectorf}ID2.4.$up$down.xp))/($xLimit - $BPLD(S${sectorf}ID2.4.$up$down.x))]
	#forth x>0 xp<0
	set ID(S${sectorf}ID2.trig4) [expr abs($BPLD(S${sectorf}ID2.4.$up$down.xp))/($xLimit + $BPLD(S${sectorf}ID2.4.$up$down.x))]
    }
}


#
# For each detector set up the variables
#
set pl [string toupper $plane]
switch $plane {
    x {
	set pl0 H
    }
    y {
	set pl0 V
    }
}


foreach sector $sectorList {
    lappend pvList S${sector}-LMPS:BPLD:ID1_${pl}_mm_Cal-I  \
	S${sector}-LMPS:BPLD:ID1_${pl}_mrad_Cal-I \
	S${sector}-LMPS:BPLD:ID2_${pl}_mm_Cal-I  \
	S${sector}-LMPS:BPLD:ID2_${pl}_mrad_Cal-I \
	S${sector}-LMPS:BPLD:ID1_${pl}1-I \
	S${sector}-LMPS:BPLD:ID1_${pl}2-I \
	S${sector}-LMPS:BPLD:ID2_${pl}1-I \
	S${sector}-LMPS:BPLD:ID2_${pl}2-I 
	
    lappend tclVarList X1$sector Xp1$sector X2$sector Xp2$sector ID1P1$sector ID1P2$sector ID2P1$sector ID2P2$sector
    #BPLD status pvs
    lappend pvList S${sector}-MPS:BPLD:ID1:${pl0}LimitStatus S${sector}-MPS:BPLD:ID2:${pl0}LimitStatus
    lappend tclVarList  BPLD(S${sector}ID1Status)  BPLD(S${sector}ID2Status)
}

#
# Link all the variables
#
if [pv linkw $tclVarList $pvList]!=0 {
    APSAlertBox [APSUniqueName .] -errorMessage "Problem with connection: $errorInfo"
    exit 
}

# For each detector call displayGraph to make a new graph
#
set limit 4
set GraphNumber $limit
set GraphFrame firstRow

set IDList [exec sddsprocess $BPLD(configDir)/BPLD_ID_Limits.sdds -filter=col,IDExist,1,1 -pipe=out | sdds2stream -pipe=in -col=ID]
set idSectorList [exec sddsprocess $BPLD(configDir)/BPLD_ID_Limits.sdds -filter=col,IDExist,1,1 -pipe=out | sdds2stream -pipe=in -col=BPLDSector]

foreach sector $BPLD(sectors) {
    set sectorf [format %02d $sector]
    if {$sector==1} {
	set id1 40
	set id2 1
    } else {
	set id1 [expr $sector-1]
	set id2 $sector
    }
    set sectorf [format %02d $sector]
    
    if {$GraphNumber == $limit} {
        set GraphFrame [APSUniqueName .]
        frame $GraphFrame -bg black
        pack $GraphFrame -in .userFrame -side top -expand true -fill x
        set GraphNumber 1
    }
    incr GraphNumber
    
    if [lsearch -exact $IDList $id1]>=0 {
	set sectorf [format %02d $sector]
	set minX -$BPLD(S${sectorf}ID1.${plane}Limit)
	set maxX $BPLD(S${sectorf}ID1.${plane}Limit)
	set minY -$BPLD(S${sectorf}ID1.${plane}pLimit)
	set maxY $BPLD(S${sectorf}ID1.${plane}pLimit)
	
	
	displayGraph -minX $minX -maxX $maxX -minY $minY \
	    -maxY $maxY -Title "ID$id1 ($ID(S${sectorf}ID1.IDtype)) $plane" \
	    -Xpos [set X1$sectorf] -Ypos [set Xp1$sectorf]\
	    -Name graph1$sectorf -Frame $GraphFrame -sector $sectorf -id ID1
	modifyGraph graph1$sectorf [set X1$sectorf] [set Xp1$sectorf] $minX $maxX $minY $maxY  -sector $sector -id ID1
    }
    if [lsearch -exact $IDList $id2]>=0 {
	set minX -$BPLD(S${sectorf}ID2.${plane}Limit)
	set maxX $BPLD(S${sectorf}ID2.${plane}Limit)
	set minY -$BPLD(S${sectorf}ID2.${plane}pLimit)
	set maxY $BPLD(S${sectorf}ID2.${plane}pLimit)
	displayGraph -minX $minX -maxX $maxX -minY $minY\
	    -maxY $maxY -Title "ID$id2 ($ID(S${sectorf}ID2.IDtype)) $plane" \
	    -Xpos [set X2$sectorf] -Ypos [set Xp2$sectorf]\
	    -Name graph2$sectorf -Frame $GraphFrame  -sector $sector -id ID2
	modifyGraph graph2$sectorf [set X2$sectorf] [set Xp2$sectorf] $minX $maxX $minY $maxY  -sector $sector -id ID2
    }
}

#
# Update graph values every two seconds
#
foreach var $tclVarList {
    set old($var) [set $var]
}

while 1 {
    update
    eval global $tclVarList 
    if [pv getw $tclVarList]!=0 {
        APSAlertBox [APSUniqueName .] -errorMessage "Problem with connection: $errorInfo"
        exit
    }
    update
    foreach sector $BPLD(sectors) {
	set sectorf [format %02d $sector]
	if {$sector==1} {
	    set id1 40
	    set id2 1
	} else {
	    set id1 [expr $sector-1]
	    set id2 $sector
	}
	if [lsearch -exact $IDList $id1]>=0 {
	    set changed 0
	    foreach var [list X1$sectorf Xp1$sectorf] name {Xpos Ypos} {
		if [expr abs($old($var) - [set $var])]>0.5 {
		    set changed 1
		}
		set $name [set $var]
	    }
	    if $changed {
		modifyGraph graph1$sectorf $Xpos $Ypos $minX $maxX $minY $maxY  -sector $sector -id ID1
	    }
	       
	}
	if [lsearch -exact $IDList $id2]>=0 {
	    set changed 0
	    foreach var [list X2$sectorf Xp2$sectorf] name {Xpos Ypos} {
		if [expr abs($old($var) - [set $var])]>0.5 {
		    set changed 1
		}
		set $name [set $var]
	    }
	    if $changed {
		modifyGraph graph2$sectorf $Xpos $Ypos $minX $maxX $minY $maxY  -sector $sector -id ID2
	    }
	}
    }
    foreach var $tclVarList {
	set old($var) [set $var]
    }
    APSWaitWithUpdate -waitSeconds 1
}
