#----------------------------------------------------------------------------
# A simple scan command for DMC. This allows scanning a motor against the
# monitors. This is useful for adjusting DMC. No fancy file writing is done.
# This code relies on (and checks for) the LogBook being active.
#
# Mark Koennecke, Juli 1997
#---------------------------------------------------------------------------

#----- internal: check LogBook is on.
proc scan:CheckLog { } {
     set text [LogBook]
     if { [string match Log*:*on $text] } {
        return 1
     } else {
        return 0
     }
}
#------ internal: get Monitor value 
proc scan:monitor { num } {
     set reply [counter GetMonitor $num]
     set l [split $reply =]
     return [lindex $l 1]
}

#------ actual scan command
proc scan { motor start step n {mode NULL } { preset NULL } } {
#----- check for existence of LogBook
#     set ret [scan:CheckLog]
#     if { $ret != 1 } {
#        ClientPut "ERROR: logging must be active for scan"
#        ClientPut $ret
#        return 
#     }
#----- is motor reallly countable ?
     set ret [SICSType $motor]
     if { [string compare $ret "DRIV"] != 0 } {
        ClientPut [format "ERROR: %s not drivable" $motor]
        return
     }
#----- deal with mode
     set mode2 [string toupper $mode]
     set mode3 [string trim $mode2]
     set mc    [string index $mode2 0]
     if { [string compare $mc T] == 0 } {
       banana CountMode Timer
     } elseif { [string compare $mc M] == 0 } {
       banana CountMode Monitor
     }
#------ deal with preset
     if { [string compare $preset NULL] != 0 } {
       banana preset $preset
     }
#------- write output header
     ClientPut [format "%10.10s    Monitor0     Monitor1" $motor] 

#------ the scan loop
     for { set i 0} { $i < $n } { incr i } {
#--------- drive
       set pos [expr $start + $i * $step]
       set ret [catch "drive $motor $pos" msg]
       if { $ret != 0 } {
         ClientPut "ERROR: driving motor"
         ClientPut $msg
       }
#---------- count
       banana count
       Success
#---------- create output
       set m0 [scan:monitor 0]
       set m1 [scan:monitor 1]  
       ClientPut [format "%10.2f %11.11d %11.11d" $pos $m0 $m1]
     }        
     ClientPut "Scan finished !"
}
