#! /bin/sh
# -*- tcl -*- \
exec tclsh "$0" ${1+"$@"}

rename source __source 
proc source {path} {
    set f [file join [pwd] $path]
    uplevel 1 __source $path
}


lappend auto_path [file dirname [file dirname [info script]]]
package require doctools::toc

# ---------------------------------------------------------------------
#  1. Handle command line options, input and output
#  2. Initialize a doctools object.
#  3. Run the input through the object.
#  4. Write output.
# ---------------------------------------------------------------------

proc usage {{exitstate 1}} {
    global argv0
    puts "Usage: $argv0\
	    ?-h|--help|-help|-??\
	    ?-help-fmt|--help-fmt?\
	    format in|- ?out|-?"
    exit $exitstate
}

# ---------------------------------------------------------------------

proc fmthelp {} {
    # Tcllib FR #527029: short reference of formatting commands.

    global argv0
    puts "$argv0 [doctools::toc::help]"
    exit 0
}

# ---------------------------------------------------------------------
# 1. Handle command line options, input and output

proc cmdline {} {
    global argv0 argv format in out

    set copyright ""
    set extmodule ""
    set deprecated 0

    while {[string match -* [set opt [lindex $argv 0]]]} {
	switch -exact -- $opt {
	    -help - -h - --help - -? {
		# Tcllib FR #527029
		usage 0
	    }
	    -help-fmt - --help-fmt {
		# Tcllib FR #527029
		fmthelp
	    }
	    default {
		# Unknown option
		usage
	    }
	}
    }

    if {[llength $argv] < 3} {
	usage
    }
    foreach {format in out} $argv break

    if {$format == {} || $in == {}} {
	usage
    }
    if {$out == {}} {set out -}
    return $format
}

# ---------------------------------------------------------------------
#  3. Read input. Also providing the namespace with file information.

proc get_input {} {
    global in
    if {[string equal $in -]} {
	return [read stdin]
    } else {
	set if [open $in r]
	set text [read $if]
	close $if
	return $text
    }
}

# ---------------------------------------------------------------------
# 4. Write output.

proc write_out {text} {
    global out
    if {[string equal $out -]} {
	puts -nonewline stdout $text
    } else {
	set of [open $out w]
	puts -nonewline $of $text
	close $of
    }
}


# ---------------------------------------------------------------------
# Get it all together

proc main {} {
    global format in

    #if {[catch {}
	cmdline

	::doctools::toc::new dt -format $format
	write_out [dt format [get_input]]

	set warnings [dt warnings]
	if {[llength $warnings] > 0} {
	    puts stderr [join $warnings \n]
	}

	#{} msg]} {}
	#puts stderr "Execution error: $msg"
    #{}
    return
}


# ---------------------------------------------------------------------
main
exit