#!/bin/csh -f
#
# Eric A. Brewer  8-19-92
#
# setparam: read or set a single Proteus parameter
#
# setparam  [-v <param>]  [<param> <value>] [file]
#	either	1) read a value: "setparam -v NO_OF_PROCESSORS"
#	or	2) set a value:  "setparam NO_OF_PROCESSORS 64"
#	file defaults to *.param
#

unset error
unset valueonly
unset bool
set argmin = 2

while ($#argv > 0)
	switch ($argv[1])
	  case "-v":
		set valueonly = true
		set argmin = 1
		set value = 0
	  	breaksw
	  case -*:
		echo 'Unknown option:' $argv[1]
		set error = true
	  default:
		breaksw ; break
	endsw
	shift argv
end

if ($?error || $#argv < $argmin  || $#argv > $argmin + 1) then
	echo 'Usage: setparam -v <param> [<file>]'
	echo '  or   setparam <param> <value> [<file>]'
	echo '           -v <param>       =>  show value of <param>'
	echo '           <param> <value>  =>  set <param> to <value>'
	echo '           <file>           defaults to *.param'
	exit 1
endif

if ($#argv == 3) then
	set file = "$3"
else
	set file = "*.param"
endif

if ($?valueonly && $#argv == 2)	set file = "$2"

set param = $1
set bools =(t f T F true false TRUE FALSE)

if (! $?valueonly) then # check for boolean value
	set value = $2
	foreach i ($bools)
		if ($value == $i) then
			set bool = true
			break
		endif
	end
	if ($?bool) then
		echo 'Checking for boolean parameter...'
	 	if ($value =~ t* || $value =~ T*) then
			set value = TRUE
		else
			set value = FALSE
		endif
	endif
endif

set context = "#define *$param|#undef *$param"

foreach i ($file)
	set output = (`egrep {"$context"} $i`)
	if ($#output > 1) goto update
end

echo Error: '"'"$param"'"' 'not found in file(s):' $file
exit 2


# update the parameter file

update:
	if ($#output < 2 || $#output > 3) then
		echo Bad parameter format in "$i"
		exit 4
	endif
	if ($#output == 2) then
		if ($?bool || $?valueonly) then
			if ($output[1] =~ *"#undef") then
				set oldval = FALSE
			else
				set oldval = TRUE
			endif
		else
			echo 'Cannot set boolean param to' $value
			exit 4
		endif
	else # $#output == 3
		if ($?bool) then
			echo 'Cannot set integer param to' $value
			exit 4
		else
			set oldval = $output[3]
		endif
	endif

	echo Found "$param" in "$i", value = "$oldval"

	if ($?valueonly) exit 0

	if ($oldval == $value) then
		echo 'Warning: value unchanged, not updating' "$i"
		exit 0
	endif
	if ($?bool) then
		if ($oldval == FALSE) then
			sed -e '/#undef *'"$param"/s/undef/define/ < $i > tmp
		else
			sed -e '/#define *'"$param"/s/define/undef/ < $i > tmp
		endif
	else
		set search = '/#define *'"$param"'/s/[0-9.e-]* *$/'"$value/"
		sed -e "$search" < $i > tmp
	endif
	mv -f tmp $i
	if ($status) then
		echo Warning: file "$i" not updated
	else
		echo Set value to $value
	endif
	exit 0




