
# **************************** addfilebuttons **************************
proc addfilebuttons {parent args} {
# Adds buttons to an APSLabeledEntry to find a new file or
#   increment numbers in a name
    set types "F-+"
    set variable ""     ;# Required
    set path ""
    set pattern "*"
    set trim 0

    APSParseArguments {types variable path pattern checkValidity trim}

    if {![string compare $variable ""]} {
	APSAlertBox .alert -errorMessage \
	  "No variable given for addfilebuttons"
	return
    }

    if {[string first F $types] != -1} {
	set fargs [list -path $path -pattern $pattern]
	APSButton .findbutton -parent $parent -text "F" \
	  -packOption "-side right" -command "findfile $variable $trim $fargs $args" \
	  -contextHelp \
	  "Bring up a file selection dialog box to choose the file."
    }
    if {[string first - $types] != -1} {
	APSButton .decrbutton -parent $parent -text "-" \
	  -packOption "-side right" \
	  -command "incrementname $variable -1" \
	  -contextHelp "If the filename is of the form *.nn.* and\
           nn is an integer, then decrement nn in the name."
    }
    if {[string first + $types] != -1} {
	APSButton .incrbutton -parent $parent -text "+" \
	  -packOption "-side right" \
	  -command "incrementname $variable 1" \
	  -contextHelp "If the filename is of the form *.nn.* and\
           nn is an integer, then increment nn in the name."
    }
}
# **************************** findfile ********************************
proc findfile {filenamevariable trim args} {
# General purpose file selection
# args is passed to APSFileSelectDialog
    global $filenamevariable

    set response [eval APSFileSelectDialog .findfiledialog $args]
    if {[string compare $response ""]} {
	# Trim the current working directory from the name
	if {$trim} {
            set response [file tail $response]
	}
	set $filenamevariable $response
    }
}
# **************************** incrementname ***************************
proc incrementname {filenamevariable increment} {
# If $namevar is of the form *.[0-9][0-9].* and nn is an integer,
# or if $namevar is of the form *.[0-9][0-9]$ and nn is an integer,
#   then increments nn
# Assumes namevar is global
    upvar \#0 $filenamevariable namevar 

    set name [set namevar]
    set result [regexp {(^.*\.)([0-9][0-9])(\..*$)} $name match prefix number ext]
    if {!$result} {
	set result [regexp {(^.*\.)([0-9][0-9])($)} $name match prefix number ext]
    }
    if {$result} {
	# Strip leading zero so not octal
	if {[string first 0 $number] == 0} {
	    set number [string range $number 1 1]
	}
	incr number $increment
	if {$number > 99} {set number 99}
	if {$number < 0} {set number 00}
	set number [format "%02d" $number]
	set namevar ${prefix}${number}${ext}
    } else {
	APSAlertBox .alert -errorMessage \
	  "$name\n  is not of the proper form (*.nn.* or *.nn) to be incremented"
    }
}
