#!/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)]

set args $argv
set pvaName ""
set label 0
set outputFile ""
set printValue 0
set usage "pvaput -pvaName <name> -valuesOnly <1|0> -outputFile <filename>\n
-pvaName     required, provide the PVA channel name.\n
-label       print values with pv names. \n
-outputFile  provide the filename for writing the values and PVs in the pva channel\n"

APSParseArguments {pvaName label outputFile printValue}

if ![string length $argv] {
    puts $usage
    exit 0
}

if ![string length $pvaName] {
    puts stderr "Error1 (pvaget): pvaName not provided"
    exit 1
}

if [catch {exec pvinfo $pvaName} result] {
    puts stderr "Error2 (pvaget) pvinfo $pvaName: $result!"
    exit 1
}

if [catch {exec pvget $pvaName } values] {
    puts stderr "Error3 (pvaget): Error reading values of $pvaName"
    exit 1
}
set valList [split $values "\n"]
set items [llength $valList]
set nameList ""
set valueList ""
for {set i 0} {$i<$items} {incr i} {
    set val [lindex $valList $i]
    set chan [scan [string trim $val] "structure channel%d"]
    if [catch {expr $chan/2} result] {
	#not a number
	continue
    }
    if [string match "*structure channel*" $val] {
	incr i
	set name [lindex [split [lindex $valList $i] " "] end]
	while {1} {
	    incr i
	    set val [lindex $valList $i]
	    set nm [lindex [split $val " "] end-1]
	    if {$nm=="value"} {
		set val [lindex [split $val " "] end]
		break
	    }
	}
	set value  [lindex [split [lindex $valList $i] " "] end]
	lappend nameList $name
	lappend valueList $value
    }
}

if [string length $outputFile] {
    if [catch {exec sddsmakedataset $outputFile -par=PVAName,type=string -data=$pvaName \
		   -col=ControlName,type=string -data=[join $nameList ,] \
		   -col=Value,type=string -data=[join $valueList ,] } result] {
	puts stderr "Error4 (pvaget): error writting output file: $result"
	exit 1
    }
} 
if $label {
    foreach name $nameList value $valueList {
	puts "$name $value"
    }
} elseif {$printValue || ![string length $outputFile]} {
    puts [join $valueList]
} 


exit 0
