#@package: prompts prompt prompt_yn prompt_choices

#
# Copyright (C) 1992-1997 NeoSoft.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted, provided
# that the above copyright notice appear in all copies.  NeoSoft makes no 
# representations about the suitability of this software for any purpose.
# It is provided "as is" without express or implied warranty.

#
# prompt - given some prompt text, the name of a variable, and a possible
# default value, emit the text, read a line into the named variable and,
# if an empty string is entered, use the default instead, and set the
# result into the named variable.
#
proc prompt {promptText varName {default ""}} {
    upvar $varName line
    set line ""

    if {$default == ""} {
        puts stdout "$promptText: " nonewline
    } else {
        puts stdout "$promptText \[$default\]: " nonewline
    }
    if {[gets stdin line] < 0} return
    if {$line == ""} {
        set line $default
    }
}

#
# prompt_yn - emit some prompt text and get a yes or no response,
# returning 1 for yes and 0 for no.
#
proc prompt_yn {promptText {default ""}} {
    while 1 {
        if {$default == ""} {
            puts stdout "$promptText (y/n): " nonewline
        } else {
            puts stdout "$promptText (y/n) \[$default\]: " nonewline
        }
        if {[gets stdin line] < 0} return
        if {$line == ""} {set line $default}
        set char [string tolower [cindex $line 0]]
        if {$char == "n"} {return 0}
        if {$char == "y"} {return 1}
        echo "Please answer y)es or n)o"
    }
}

#
# prompt_choices - emit some prompt text and get a selection of one
# of a number of responses.
#
proc prompt_choices {promptText choiceList {default ""}} {
    while 1 {
	set nChoices 0
	echo $promptText
	foreach element $choiceList {
	    echo "  $nChoices $element"
	    incr nChoices
	}
	prompt "Your selection?" input $default
	if {([catch {set choice [lindex $choiceList $input]} result] == 1) || \
	    ($choice == "" && $default != "")} {
	    echo "Please enter a number between 1 and $nChoices."
	    continue
	}
	if {$choice == ""} {return $default}
	return $choice
    }
}

