#! /bin/env tclsh

::proc cmd args {
	::set args [::lassign $args[::set args {}] pkg]
	::lappend pkgpath {*}$pkg
	::while 1 {
		::set copts {}
		::set cres {}
		::package require [::list ycl {*}$pkgpath]
		::try {
			return [[::yclprefix] {*}${pkgpath} {*}$args]
		} on error {cres copts} {
			::dict with copts {}
			if {[llength ${-errorstack}] < 5} {
				::if {[::lrange ${-errorcode} 0 2] eq [
					::list TCL LOOKUP SUBCOMMAND]} {

					::lappend pkgpath [::lindex $args 0]
					::set args [::lrange $args[::set args {}] 1 end]
					::continue
				}
			}
			::break
		}
	}
	::if {$copts ne {}} {
		::return -code [::dict get $copts -code] -options $copts
	}
}


proc puts args {
	::package require {ycl interp process}
	::set res [[::yclprefix] interp process new config [
		::list ::set auto_path $::auto_path
	] cmd [::list ::source {*}$args]]
	::puts $res
}



### compatibility ###

variable yclpath [file normalize [file dirname [info script]]] 

if {[::namespace which ::tailcall] eq {}} {
	::namespace eval [yclprefix]::tailcall {
		::source [file join $yclpath/../../tailcall/lib/tailcall.tcl]
		::namespace export {[a-z]*}
	}
	::namespace eval :: {
		::namespace import [yclprefix]::tailcall::tailcall
	}
}
