#!tclsh

proc get_km_status { km_control } {
set file [open "$km_control" "w+"]
puts $file "STATUS"
flush $file
set r [list ]
set s ""
while { "$s" != "+END_STATUS" } {
	set s [gets $file]
	set i [string first "=" "$s"]
	if { $i > 0 } {
		lappend r [string range "$s" 0 [expr $i-1]] [string range "$s" [expr $i+1] end]
		}
	}
puts "$r"
}

proc find_km_device { location_id } {
puts "Looking for km device that corresponds to $location_id"
if { ! [file exists /proc/km ] } {
	global km_warning warn_about_missing_km
	if { !$warn_about_missing_km || [info exists km_warning ] } { return }
	tk_dialog .controlwin.b "KM is not loaded" "It does not appear that KM driver has been loaded.\nThis driver is required for snapshot and video capture and for closed captioning.\nSee README for more details\n" "" 0 "Acknowledged"
	set km_warning 1
	return
	}
set km_devs [list ]
catch {
	set km_devs [split [exec ls -1 /proc/km] "\n"]
	}
puts "km_devs=$km_devs"
set LOCATION_ID ""
foreach file $km_devs {
	if { ! [regexp {^control} $file] } { continue }
	set attrs [list ]
	catch {
		set FILE [open /proc/km/$file "w+"]
		fconfigure $FILE -buffersize 65536
		puts -nonewline $FILE "STATUS\n"
		flush $FILE
		while {1} {
			gets $FILE line
			puts "read line=$line"
			if { [regexp {^(.*)=(.*)} $line {} var value] } { 
				set $var $value
				lappend attrs $var $value
				}
			if { [regexp {END_STATUS} $line] } { break }
			}
		close $FILE
		}
	if { $LOCATION_ID == $location_id } {
		return [list file $file attrs $attrs]
		}
	}
}

proc update_primary_globals {} {
global LOCATION_ID
foreach var { primary_v4l_device primary_vbi_device } {
	global $var
	set $var ""
	}
if { ! [info exists LOCATION_ID] } { return }
catch {
	foreach {var value } [find_km_device $LOCATION_ID] {
		set $var $value
		}
	foreach {var value} $attrs {
		set $var $value
		}
	set primary_v4l_device "/dev/video$V4L_DEVICE"
	set primary_vbi_device "/dev/vbi[expr $VBI_DEVICE-224]"
	}
}
