# tmqjs: shell script to convert text music notation to other format
# using txtmus and quickjs (https://bellard.org/quickjs/)

# search where are the txtmus scripts
p=$0
[ `dirname $p` = . ] && p=`which $p`
[ -L $p ] && p=`realpath $p`
p=`dirname $p`

exec qjs --std -e '

    var	args = scriptArgs,
	path = args.shift() + "/"	// the 1st argument is the script path

// interpreter specific functions
function load(fn) {
	std.loadScript(fn)
}
var tm = {
	print: print,
	printErr: function(s) {
		std.err.printf("%s\n", s)
	},
	quit: function() {
		std.exit(1)
	},
	readFile: std.loadFile,
	get_mtime: function(fn) {
		return new Date(os.stat(fn)[0].mtime)
	},
	loadjs: function(fn, ok, onerror) {
		try {
			load(fn[0] == "/" ? fn : (path + fn))
			if (ok)
				ok()
		} catch(e) {
			if (onerror)
				onerror()
			else
				tm.printErr("Cannot read file " + fn +
					"\n  " + e.name + ": " + e.message)
		}
	} // loadjs()
} // tm

// --- main ---

	console.log = tm.printErr

	if (std.getenv("TMPATH"))
		tm.path =  std.getenv("TMPATH").split(":")

	load(path + "tmcore-2.js")
	load(path + "cmdline.js")

	tmcmd("tmqjs", args, "QuickJS")
' $p "$@"
