#! /usr/bin/env tclsh

# @(#) $Id: wishx 1.6 2007/08/29 17:50:05 EAL $

# At this point, the legal command-line options for wish have already been 
# removed from argv: argv only contains the filename and/or script options.
# Depending on what arguments are left, we may have to adjust the argc value.
# Remark that the "--" will have been removed, which makes it difficult
# to distinguish between a first argument intended as the script-file
# or as a filename to be passed to an interactive script. E.g. 
#    wishx test.tcl -- -a -b -c
#    wishx -- test.tcl -a -b -c
# will be seen by this shell as
#    wishx test.tcl -a -b -c
# i.e. the sript-file test.tcl will be executed, which is not what was
# wanted in the latter case. The only way out of this would be to exec tclsh
# instead of wish, do a "package require Tk" and deal with the wish options
# in a different way - but not all options have corresponding commands.

package require Tclx

# Parse command line options
if {$argc != 0} {
    # possible first arguments:
    #   -c <script>   : if given, must come as first arg!
    #   <otherOption> : options must be identified by a leading -
    #   <scriptFile>  : name of script to execute; must come as first arg!
    switch -glob -- [lindex $argv 0] {
        -c	{
            incr argc -2
            lvarpop argv
            if {[catch {eval [lvarpop argv]}]} {
                puts stderr $errorInfo
                exit 1
            } else {
		exit 0
            }
        }
        -*      {}
        default	{
            incr argc -1
            if {[catch {source [lvarpop argv]}]} {
                puts stderr $errorInfo
                exit 1
            } else {
		vwait ::TclX::forever
            }
        }
    }
}

# If we get here, there are either no args passed, or the arg-list
# does not start with a script-filename nor the -c option; in other
# words, we have an interactive session.
# Remark that [fstat stdin] will not indicate a tty if the input
# is piped into stdin (e.g. via a "echo" cmd). As "mainloop"
# will not read from stdin if tcl_interactive is 0, we need to
# force it to 1.
set tcl_prompt1 "puts -nonewline stdout [file tail $argv0]>"
set tcl_prompt2 {puts -nonewline stdout =>}
if {[catch {fconfigure stdin}]} {
     # stdin is closed - cannot go "interactive"
     exit 0
} 
##if {[fstat stdin tty]} {set tcl_interactive 1}
set tcl_interactive 1
mainloop
