#!/bin/sh
#| cl-launch.sh -- shell wrapper generator for Common Lisp software -*- Lisp -*-
CL_LAUNCH_VERSION='3.22.1'
license_information () {
AUTHOR_NOTE="\
# Please send your improvements to the author:
# fare at tunes dot org < http://www.cliki.net/Fare%20Rideau >.
"
SHORT_LICENSE="\
# CL-Launch is available under the terms of the bugroff license.
#	http://www.geocities.com/SoHo/Cafe/5947/bugroff.html
# You may at your leisure use the LLGPL instead < http://www.cliki.net/LLGPL >
"
WEB_SITE="# For the latest version of CL-Launch, see its web page at:
#	http://www.cliki.net/cl-launch
"
LICENSE_COMMENT="\
# This software can be used in conjunction with any other software:
# the result may consist in pieces of the two software glued together in
# a same file, but even then these pieces remain well distinguished, and are
# each available under its own copyright and licensing terms, as applicable.
# The parts that come from the other software are subject to the terms of use
# and distribution relative to said software, which may well be
# more restrictive than the terms of this software (according to lawyers
# and the armed henchmen they got the taxpayers to pay to enforce their laws).
# The bits of code generated by cl-launch, however, remain available
# under the terms of their own license, and you may service them as you wish:
# manually, using cl-launch --update or whichever means you prefer.
# That said, if you believe in any of that intellectual property scam,
# you may be subject to the terms of my End-Seller License:
#	http://www.livejournal.com/users/fare/21806.html
"
DISCLAIMER="\
# This file was automatically generated and contains parts of CL-Launch
"
}
license_information

### Settings for the current installation -- adjust to your convenience
### Or see documentation for using commands -B install and -B install_bin.
DEFAULT_LISPS="cmucl sbcl clisp ecl openmcl gclcvs allegro lisp gcl"
DEFAULT_INCLUDE_PATH=/usr/share/common-lisp/source/cl-launch
DEFAULT_USE_CL_LAUNCHRC="t"
DEFAULT_USE_CLBUILD=""

### Initialize cl-launch variables
unset \
	SOFTWARE_FILE SOFTWARE_SYSTEM \
	SOFTWARE_FINAL_FORMS SOFTWARE_INIT_FORMS \
	SOURCE_REGISTRY INCLUDE_PATH LISPS WRAPPER_CODE \
	OUTPUT_FILE UPDATE \
	LINE LINE1 LINE2 NO_QUIT CONTENT_FILE \
        TRIED_CONFIGURATION HAS_CONFIGURATION \
	EXEC_LISP DO_LISP DUMP LOAD_IMAGE RESTART IMAGE IMAGE_OPT \
	EXTRA_CONFIG_VARIABLES \
	EXECUTABLE_IMAGE STANDALONE_EXECUTABLE CL_LAUNCH_STANDALONE \
        TEST_SHELLS TORIG IMPL

LISPS="$DEFAULT_LISPS"
INCLUDE_PATH="$DEFAULT_INCLUDE_PATH"
USE_CL_LAUNCHRC="$DEFAULT_USE_CL_LAUNCHRC"
USE_CLBUILD="$DEFAULT_USE_CLBUILD"

UNREAD_DEPTH=0
OUTPUT_FILE="!"

### Other constants
MAGIC_MD5SUM="65bcc57c2179aad145614ec328ce5ba8" # Greenspun's Tenth Rule...
CONTENT_DISCLAIMER="\
;;; THE SOFTWARE AFTER THIS MARKER AND TO THE END OF THE FILE IS NOT PART OF
;;; CL-LAUNCH BUT A PIECE OF SOFTWARE DISTINCT FROM CL-LAUNCH. IT IS OWNED BY
;;; BY ITS OWNERS AND IS SUBJECT ITS OWN INDEPENDENT TERMS OF AVAILABILITY."
CONTENT_BEGIN_MARKER="\
;;; ${MAGIC_MD5SUM} SOFTWARE WRAPPED BY CL-LAUNCH BEGINS HERE:"

### Help
## setup a few environment variables for the program
BASIC_ENV_CODE='PROG="$0"'
eval "$BASIC_ENV_CODE"

PROGBASE="${0##*/}" # "$(basename "$0")"

CL_LAUNCH_URL="http://fare.tunes.org/files/cl-launch/cl-launch.sh"

HELP_HEADER="cl-launch.sh $CL_LAUNCH_VERSION -- shell wrapper generator for Common Lisp software"
print_help_header () {
  ECHO "$HELP_HEADER"
}
print_help () {
cat <<EOF
Usage:
	$PROGBASE '(lisp (form) to evaluate)'
	    evaluate specified Lisp form, print the results followed by newline
	$PROGBASE --execute [...] [-- arguments...]
	    run the specified software without generating a script (default)
	$PROGBASE --output SCRIPT [--file LISP_FILE] [--init LISP_FORM] [...]
	    generate a runnable shell script FILE from a software specification
	$PROGBASE --update FILE [...]
	    same as above, but reuse software specification from previous FILE
	$PROGBASE [ --version | --help | --more-help ]
	    display information (might be long, you may pipe it into a pager)

Special modes:
 -h  or  -?	--help		 display a short help message
 -H		--more-help	 display a longer help message
 -V		--version	 display cl-launch version and configuration
 -u FILE	--update FILE	 update a cl-launch script to current version

Software specification:
 -w CODE	--wrap CODE          shell wrapper CODE to run in cl-launch
 -l LISP...	--lisp LISP...	     try use these LISP implementation(s)
 -m IMAGE       --image IMAGE        build from Lisp image IMAGE
 -f FILE	--file FILE	     load FILE first when building
 -S X		--source-registry X  override source registry of asdf systems
 -s SYSTEM	--system SYSTEM	     load asdf SYSTEM when building
 -r FUNC	--restart            restart from build by funcalling FUNC
 -i FORM	--init FORM	     evaluate initialization FORM after restart
 -ip FORM	--print FORM	     evaluate and princ FORM after restart
 -iw FORM	--write FORM	     evaluate and write FORM after restart
 -I PATH        --include PATH       runtime PATH to cl-launch installation
 +I             --no-include         disable cl-launch installation feature
 -R             --rc                 try read /etc/cl-launchrc, ~/.cl-launchrc
 +R             --no-rc              skip /etc/cl-launchrc, ~/.cl-launchrc
 -b             --clbuild            use clbuild (with limitations, read docs)
 +b             --no-clbuild         do not use clbuild
 -v             --verbose            be very noisy while building software
 -q             --quiet              be quiet while building software (default)

Output options:
 -x      -o !   --execute	     run the thing NOW (default)
 -o FILE	--output FILE	     create executable FILE
 -d IMAGE	--dump IMAGE         dump IMAGE for faster startup
 -X ... --	(see more help)	     use #!/.../cl-launch as script interpreter
 --		--		     end of arguments when using -x or -X
EOF
}
print_help_footer () {
  cat<<EOF
See our web page on
	http://www.cliki.net/cl-launch

Note: if this help is too long for you, you may scroll back, or use
	$PROG --more-help | less

EOF
}
print_more_help () {
cat<<EOF
INVOCATION OF CL-LAUNCH

CL-Launch will create a shell script that, when invoked, will evaluate
the specified Lisp software with an appropriate Common Lisp implementation.

A suggested short-hand name for cl-launch is cl (you may create a symlink
if it isn't included in your operating system's cl-launch package).

To work properly, CL-Launch 3.21 depends on ASDF 3 or later,
or else at least ASDF 2.015 and ASDF-DRIVER configured in your source-registry.

The software is specified as the execution, in this order, of:
* optionally having your Lisp start from a Lisp IMAGE (option --image)
* loading a small header of code that provides common cl-launch functionality
* optionally loading the contents of a FILE (option --file)
* optionally having ASDF load a SYSTEM (option --system)
* optionally having your Lisp DUMP an image to restart from (option --dump)
* optionally having your Lisp execute a RESTART function (option --restart)
* optionally evaluating a series of initialization FORMS (option --init)

General note on cl-launch invocation: options are processed from left to right;
in case of conflicting or redundant options, the latter override the former.


The cl-launch 3.21 relies on ASDF 3 and its ASDF-DRIVER
to manage compilation and image life cycle.

cl-launch defines a package :cl-launch that exports the following symbols:
   *arguments* getenv quit compile-and-load-file load-system
See below section 'CL-LAUNCH RUNTIME API'.

The cl-launch header will try to load ASDF from various sources until
a satisfactorily recent enough version is found. It will first look for
an ASDF that is already loaded. Then, it will try a path provided through
environment variable \$ASDF_PATH if specified. Then, it will try to
(require ...) it from your Lisp implementation, and if an ASDF is present
but not recent enough, it will try to load a more recent version
with ASDF itself. Failing the above, it will look in various places
according to the XDG standard, which by default will include
   /usr/share/common-lisp/source/asdf/asdf.lisp
and
   /usr/share/common-lisp/source/cl-asdf/asdf.lisp
and finally it will look in your
home directory under ~/cl/asdf/asdf.lisp.
If asdf is not found, cl-launch will proceed but you won't be able to use it
and the --system option will be unavailable.

Only one input files may be specified with option --file. Now, if the specified
filename is '-' (without the quotes), then the standard input is used. You may
thus concatenate several files and feed them to cl-launch through a pipe. Or
you may write Lisp code that loads the files you need in order.

Only one system may be specified with option --system, because the right thing
to do if your software depends upon multiple systems is to write a system
definition that :depends-on several other systems. It may still be useful to
combine options --file and --system, since you may want to prepare your Lisp
system with proper settings and proclamations before you load your system.

You may specify that a snapshot image of the Lisp world be dumped at this point
with option --dump. Execution of the program will consist in restarting the Lisp
implementation from that dumped image. See section DUMPING IMAGES.

You may optionally specify a restart function with option --restart,
to be called every time the software is invoked. If you are dumping an image,
this function will be called right after execution resumes from the dumped
image. If you are not dumping an image, it will merely be executed after
loading the system from source or fasl. Only one restart function may be
specified with option --restart. If you want several functions to be called,
you may DEFUN one that calls them and use it as a restart, or you may use
init forms below.

Several instances of option --init FORMS may specify as many series of forms
that will be read and evaluated sequentially as top-level forms, as loaded
from a string stream after the rest of the software has been loaded.
Loading from a stream means you don't have to worry about packages and other
nasty read-time issues; however it also means that if you care a lot about
the very last drop of startup delay when invoking a dumped image,
you'll be using option --restart only and avoiding --init.
Option --print (or -ip) specifies FORMS where the result of the last form
is to be printed as if by PRINC, followed by a newline. Option --write
(or -iw) is similar to --print, using WRITE instead of PRINC.


When the various side effects from software invocation happen depend on how
cl-launch is invoked. For the purpose of side effects, software invocation
may be divided in two phases: software preparation and software execution.
Software preparation consists in compiling and loading the software as
specified by options --file and --system. During software preparation, object
files are cached and will be loaded without being recompiled if a previous
version exists that does not depend upon any modified sources. If no image is
dumped, then software preparation happens at each invocation of the generated
script. If an image is dumped then the preparation only happens at invocation
of cl-launch, and the generated script will use the prepared software directly;
with ECL, the load-time (but not compile-time) side-effects of software
preparation are evaluated every time a dumped image is invoked.
Software execution happens at every invocation, after the prepared software
has been suitably loaded. First the --restart function, if provided, is called.
Then, the --init forms, if provided, are evaluated.


When option --execute is specified, the specified software is executed.
Command-line arguments may be given to software being executed by putting
them after a special marker '--', that ends cl-launch option processing.

When option --output FILE is used, code will be generated into the specified
FILE. The output file itself will be created atomically from complete
generated contents and may thus have the same pathname as the input file.
The restart function and init forms will not be evaluated, but kept for
when the output file is executed.
If '-' (without quotes) is specified, then the standard output is used.
If '!' (without quotes) is specified, then option --execute is assumed.

When no --output file is specified, option --execute is implicitly assumed.
The last --output or --execute option takes precedence over the previous ones.

If only one argument exists and it doesn't start with '-' then the argument is
considered as if given to option -ip, to be evaluated and printed immediately.


The ASDF 2 source-registry configuration can be overridden with option
--source-registry SOURCE_REGISTRY. The provided configuration will take
priority over anything provided by the environment or configuration files,
though it may inherit from them as usual. See the ASDF 2 manual about that.


Options --lisp and --wrap may be used to control the way that a Common Lisp
implementation is found when the software is run. Option --lisp specifies the
list of Common Lisp implementations to try to use; the list is
whitespace-separated, and consists in nicknames recognized by cl-launch.
Option --wrap supplies arbitrary code to be evaluated by the shell wrapper,
after it has read its configuration and defined its internal functions, but
before it tries to find and run a Lisp implementation. Such wrapper code is
typically used to modify the variables that control the run-time behaviour
of generated scripts, as documented below. Use of other internals of cl-launch
is possible, but not supported, which means that it is your responsibility to
keep a copy of the specific version of cl-launch with which your code works and
to update your code if you later make an upgrade to an incompatible cl-launch.
For instance, --lisp "foo bar" is equivalent to --wrap 'LISPS="foo bar"'.
See below the documentation section on 'LISP IMPLEMENTATION INVOCATION'.


Option --no-include specifies that cl-launch should generate a standalone
script that includes the configuration, shell wrapper, Lisp header, and
user-provided Lisp code (from --file). If the software doesn't use asdf, or
if the asdf systems remain well located at runtime, then the script is pretty
much standalone indeed an may be moved around the filesystem and still used.
However the size of the output will be the size of the user Lisp code
plus about 43KiB.

Option --include PATH specifies that cl-launch should generate a very small
script (typically under 1KiB) that when run will read the cl-launch shell
wrapper and Lisp header from a specified installation directory PATH.
Also, if option --include is used, and Lisp code is specified with --file
and an absolute pathname starting with / as opposed to a relative pathname
or to the standard input, then Lisp code will also be loaded from the specified
location at runtime rather than embedded into the script at generation time.
This option generates leaner scripts, but may not be applicable when
the very same script is to used in a variety of situations
that lack common coherent filesystem management.

Which of --include or --no-include is the default may depend on your cl-launch
installation. The version of cl-launch distributed by the author uses
--no-include by default, but the version of cl-launch available in your
operating system distribution may rely on a well-managed include path (this is
the case with debian for instance). You may query the configuration of an
instance of cl-launch with option --version.

For instance, one may expect a debian version of cl-launch to use
	/usr/share/common-lisp/source/cl-launch/
as a system-managed include path. One may also expect that Lisp implementations
managed by the system would come with cl-launch precompiled in Lisp images.
Since the cl-launch provides feature :cl-launch, and since the cl-launch Lisp
header is conditionalized to not be read with this feature, this would make
cl-launch startup faster, while still allowing non-system-managed Lisp
implementations to run fine.

You may create an installation of cl-launch with such a command as
	cl-launch --include /usr/share/common-lisp/source/cl-launch \\
		--lisp 'sbcl ccl clisp' \\
                --rc \\
		--output /usr/bin/cl-launch -B install
You can use command -B install_bin if you only want to configure cl-launch
(with a different default for --lisp but no --include, for instance), and
command -B install_path if you only want to create support files.
Note that the --backdoor option -B must come last in your invocation.


Option --no-rc or +R specifies that cl-launch should not try to read resource
files /etc/cl-launchrc and ~/.cl-launchrc.

Option --rc or -R specifies that cl-launch should try to read resource
files /etc/cl-launchrc and ~/.cl-launchrc. These files are notably useful
to define override the value of \$LISP depending on \$SOFTWARE_SYSTEM.
A function system_preferred_lisps is provided so that your cl-launchrc might
contain lines as follows:
	system_preferred_lisps stumpwm cmucl sbcl clisp
	system_preferred_lisps exscribe clisp cmucl sbcl
Beware that for the sake of parsing option --no-rc, the resource files are run
*after* options are processed, and that any overriding of internal variables
will thus preempt user-specified options. A warning will be printed on the
standard error output when such an override happens.
Note that such overrides only happen at script-creation time. A script created
by cl-launch will not try to read the cl-launch resource files.


Files generated by cl-launch are made of several well-identifiable sections.
These sections may thus be considered as distinct software, each available
under its own regime of intellectual property (if any). In case of an accident,
you may still retrieve the exact original code provided with option --file
by stripping the wrapper, as delimited by well-identified markers.
Search for the marker string "BEGINS HERE:". Every after it is not cl-launch.
This can be done automatically with backdoor option -B extract_lisp_content.
cl-launch uses this functionality implicitly when embedding a file specified
with the option --file, so that you may process a script previously generated
by cl-launch and change the options with which it wraps the embedded Lisp code
into runnable software.

As an alternative, you may also upgrade a previously generated script to use
the current version of cl-launch while preserving its original wrapping options
with option --update. In this case, software specification options are ignored.
Output options still apply. Specifying '-' (without quotes) as the file to
update means to read the contents to be read from the standard input.
This feature might not work with scripts generated by very early versions
of the cl-launch utility. It should work with versions later than 1.47.


COMPILATION AND FASL CACHING

A cl-launch generated program will compile the contents of the file supplied
with --file the first time it is invoked. Note that this happens even when
the file contents were embedded in the script, since compiling or loading
the wrapped file is equivalent to compiling or loading the original file
supplied.

So as to avoid problems with badly interfering fasl files everywhere,
ASDF is usually configured to set up a fasl cache
to hold fasl files in a proper place, by default under ~/.cache/common-lisp/
See your ASDF documentation about ASDF-Output-Translations.


SUPPORTED LISP IMPLEMENTATIONS

The implementations supported by current version of cl-launch are
	abcl allegro ccl clisp cmucl ecl gcl lispworks sbcl scl xcl
Also defined are aliases
	clozurecl gclcvs lisp openmcl
which are name variations for ccl, gcl, cmucl and ccl again respectively.

Fully supported, including standalone executables:
  sbcl:  SBCL 1.0.34
  clisp:  GNU CLISP 2.49
  ecl:  ECL 11.1.1
  cmucl:  CMUCL 20B
  ccl:  ClozureCL 1.6
  lispworks:  LispWorks Professional 6.0.0  (no personal ed, banner)

Fully supported, but no standalone executables:
  gclcvs (GCL 2.7):  GCL 2.7.0 ansi mode  (get a recent release)
  allegro:  Allegro 8.2  (also used to work with 5)
  scl:  Scieneer CL 1.3.9

Incomplete support:
  abcl:  ABCL 0.27.0 (no image dumping support at this time)
  gcl (GCL 2.6):  GCL 2.6.7 ansi mode  (no ASDF so --system not supported)
  xcl:  XCL 0.0.0.291 (cannot dump an image) (get a recent checkout)


GCL is only supported in ANSI mode. cl-launch does export GCL_ANSI=t in the
hope that the gcl wrapper script does the right thing as it does in Debian.
Also ASDF requires GCL 2.7 so --system won't work with an old gcl 2.6.
Note that GCL seems to not be maintained anymore.
A bug in the (years old) latest Debian package prevents ASDF from running,
and though it is fixed upstream, the upstream GCL itself
fails to compile unmodified on Debian. RIP.

There are some issues regarding standalone executables on CLISP.
See below in the section regarding STANDALONE EXECUTABLES.

LispWorks requires the Professional Edition. Personal edition isn't supported
as it won't let you control the command line or dump images.
Dumped Images will print a banner, unless you dump a standalone executable.
To dump an image, make sure you have a license file in your target directory
(or use a trampoline shell script to exec /path/to/lispworks "\$@"),
create a build script with
       echo '(hcl:save-image "lispworks" :environment nil)' > si.lisp
       lispworks-6-1-0-x86-linux -siteinit - -init - -build si.lisp

Similarly, a mlisp image for allegro can be created as follows:
	alisp -e '(progn
                   (build-lisp-image "sys:mlisp.dxl"
                    :case-mode :case-sensitive-lower
		    :include-ide nil :restart-app-function nil)
                   (when (probe-file "sys:mlisp") (delete-file "sys:mlisp"))
                   (sys:copy-file "sys:alisp" "sys:mlisp"))'

Additionally, cl-launch supports the use of clbuild as a wrapper to invoke
the Lisp implementation, with the --clbuild option.


LISP IMPLEMENTATION INVOCATION

When a cl-launch generated script is invoked, the cl-launch shell wrapper will
try to execute the Lisp code with the first Common Lisp implementation it finds
in a given list, which can be specified through option --lisp. The runtime
behaviour of the cl-launch shell wrapper is very configurable through a series
of environment variables. These variables can be controlled by the user by
exporting them in his environment, or they can be restricted at the time of
script generation by using cl-launch option --wrap.

If variable LISP is defined, the shell wrapper will first try the implementation
named by variable LISP. If that fails, it will try the list of implementations
provided at script generation time. The list of implementations generated will
be the argument to option --lisp if specified. Otherwise, cl-launch will supply
its default value. This default value for the current instance of cl-launch is:
	$DEFAULT_LISPS
This LISP selection only happens at system preparation time. If you dump an
image then the script will always use the Lisp implementation for which an
image was dumped. If you don't then the user may override the implementation.


Note that these are nicknames built into the cl-launch shell wrapper, and not
necessarily names of actual binary. You may control the mapping of
implementation nickname to actual binary pathname to call with an environment
variable. For a given implementation nickname, the environment variable will be
the capitalization of the given nickname. Hence, variable \$SBCL controls where
to look for a sbcl implementation, and variable \$CMUCL controls where to look
for a cmucl implementation. If a binary is found with a matching pathname
(using the standard unix \$PATH as required), then said implementation will be
used, using proper command line options, that may be overriden with an
environment variable similar to the previous but with _OPTIONS appended to its
name. Hence, \$CMUCL_OPTIONS for cmucl, \$CLISP_OPTIONS for clisp, etc.
Sensible defaults are provided for each implementation, so as to execute the
software in non-interactive mode, with debugger disabled, without reading
user-specific configuration files, etc.

If you want to insist on using a given implementation with given options,
you may use option --lisp and --wrap, as follows:
	--lisp 'sbcl clisp' wrap '
LISP= # do not allow the user to specify his implementation
SBCL=/usr/bin/sbcl # not any experimental thing by the user
SBCL_OPTIONS="--noinform --sysinit /dev/null --userinit /dev/null \\
	--disable-debugger" # predictable Lisp state
CLISP=/usr/bin/clisp # fall back on machines that lack SBCL
CLISP_OPTIONS=" -norc --quiet --quiet"
CL_SOURCE_REGISTRY=/usr/local/share/common-lisp/source//: # configure ASDF
ASDF_OUTPUT_TRANSLATIONS=/my/cl/src:/my/fasl/cache: # assuming precompiled fasls there
'

If you dump an image, you need not unset the LISP variable, but you
might still want to override any user-specified SBCL and SBCL_OPTIONS
(or corresponding variables for your selected implementation) from what
the user may specify.

Note that you can use option --wrap "\$(cat your_script)"
to embed into your program a full fledged script from a file.
Your script may do arbitrary computations before the shell wrapper is run.
It may make some consistency checks and abort before to run Lisp.
Or it may analyze invocation arguments and make according adjustments
to Lisp implementation options. This can be useful for setting options
that cannot be set from the Lisp code, such the path to a runtime image,
interactive or non-interactive execution, size of heaps,
locale settings for source file encoding, etc.

Reading the source code of cl-launch can be completely crazy. You may have
great fun understanding why things are how they are and adding features
without breaking anything! However, adding support for a new CL implementation
should be straightforward enough: just search the sources for "clisp" or "sbcl"
and mimic what I did for them. Be sure to send me what will get your favorite
Lisp flavor of the month rolling.


LIMITED CLBUILD SUPPORT

cl-launch 2.12 and later support using clbuild as a wrapper to configure your
Lisp implementation, with option --clbuild (which can be disabled with option
--no-clbuild if it was enabled by default in your cl-launch installation).

Note that when you use clbuild, you can no longer override implementation
options with say SBCL_OPTIONS, as clbuild takes care of the options for you.
Any implementation banner will not be removed unless you instruct clbuild
to do so. Also, you cannot use clbuild with a non-executable image different
from clbuild's, which precludes image dumping with cmucl or allegro (allegro
could probably be updated, but I don't have a recent licence to test and
develop).

clbuild support is not fully tested at this point. Please report any bug.


SIMPLE CL-LAUNCH SCRIPTS

In simple cases, you may create a Common Lisp shell script with CL-Launch
without a script generation step, just because you'll spend a lot of time
editing the script and distributing it, and little time waiting for script
startup time anyway. This notably is a good idea if you're not spawning many
instances of the same version of a script on a given computer. If that's
what you want, you may use cl-launch as a script interpret the following way
(stripping leading spaces):
  #!/path/to/cl-launch -X ...options... --
For instance, you may write the following script (stripping leading spaces):
  #!/usr/bin/cl-launch -X --init '(format t "foo~%")' --
  (format t "hello, world~%")
  (write cl-launch:*arguments*) (terpri)
The limitation is that the first argument MUST be '-X' (upper case matters,
and so does the following space actually), the last one MUST be '--' and all
your other arguments (if any) must fit on the first line, although said line
can be as long as you want: the kernel has a limit of 127 characters or so
for this first line, but cl-launch will read the first line directly from
the Lisp script, anyway.

Note that if you don't need Lisp code to be loaded from your script,
with everything happening in the --file --system and --init software
specification, then you may instead use a simple #!/bin/sh shell script
from which you exec /path/to/cl-launch -x ... -- "\$@".

Also, in case you can't rely on cl-launch being at a fixed path, or if your
shell and/or kernel combination doesn't support using cl-launch as a script
interpreter, then you may instead start your script with the following lines
(stripping leading spaces):
  #!/bin/sh
  ":" ; exec cl-launch -X -- "\$0" "\$@" || exit 42
  (format t "It works!~%")
In practice, I've found that machines with custom-compiled Linux kernels
2.6.15 and later supported #!/usr/bin/cl-launch fine with a wide variety of
shells (I tried all of posh 0.4.7, bash 2.05, bash 3.1, zsh 4.3.2, dash 0.5.3
and busybox 1.01 ash), whereas other machines with a standard Linux
kernel 2.6.11 from debian would not support it with any shell.
Maybe an issue with kernel binfmt_misc configuration?


DUMPING IMAGES

You can dump an image (for static compilation and fast startup) with option
--dump IMAGE where IMAGE specifies the path where the image will be dumped.

If you use option --include PATH then the image will be loaded back from
that specified directory instead of the directory where you dumped it. This
is useful if you're preparing a script to be installed at another place maybe
on another computer.

This option is currently supported on all CL implementations available
with cl-launch.

As a limitation, LispWorks will print a banner on standard output,
unless you use the standalone executable option below.

As another limitation, ECL will not be able to dump an image when running
from a previously dumped image (with --image). This is because with the
link model of ECL, you'll need to be able to locate which object files were
used in linking the original image, keep track of these files, and prepend
the list of them to to the object files linked into the dump. Doing this
is unhappily out of the scope of cl-launch;
however, we hope to support that someday with a real build system such as XCVB.


STANDALONE EXECUTABLES

You can create standalone executables with the option --dump '!'
(or by giving a --dump argument identical to the --output argument).

This option is currently only supported with
SBCL, ECL, CLISP, CMUCL, CCL and LispWorks Professional.
Moreover CLISP has the issues below.

CLISP standalone executables will react magically if invoked with options
such as --clisp-help or --clisp-x '(sys::main-loop)'.
That's a pretty far-fetched thing to hit by mistake, and
the CLISP maintainers consider it a feature (I don't).
Don't use such executables as setuid, and don't let untrusted users
control arguments given to such executables that are run with extra privileges.


CL-LAUNCH RUNTIME API

cl-launch provides the following Lisp functions:

Variable cl-launch:*arguments* contains the command-line arguments
used to invoke the software.

Function cl-launch:getenv allows to query (but not modify) the environment
variables, as in (getenv "HOME"), returning nil when the variable is unbound.

Function cl-launch:load-system takes as an argument the name of an asdf system
and the keyword argument verbose, and loads specified system with specified
verbosity.

Function cl-launch:compile-and-load-file takes as an argument a source pathname
designator, and keyword arguments force-recompile (default NIL) and verbose
(default NIL). It will arrange to compile the specified source file if it is
explicitly requested, or if the file doesn't exist, or if the fasl is not
up-to-date. It will compile and load with the specified verbosity. It will
take use asdf:compile-file-pathname* to determine the fasl pathname.

Function cl-launch:quit will cause the current Lisp application to exit.
It takes two optional arguments code with default value 0, and finish-output
with default value t. The first is to be used as the process exit code, the
second specifies whether to call finish-output on *standard-output* and
*error-output*. Note that you should use (finish-output) and otherwise flush
buffers as applicable before you quit, not just to be standard-compliant, but
also to support ccl and any other Lisp implementation that do buffering.

Additionally, environment variables CL_LAUNCH_PID and CL_LAUNCH_FILE
will be set to the process ID and the script invocation filename respectively.


VERBOSE OUTPUT MODE

If the shell variable CL_LAUNCH_VERBOSE is exported and non-nil, then
cl-launch and the scripts it generates will produce an abundance of output,
display such things as the Lisp invocation command, compiling and loading
files with :verbose t and :print t, etc. This is only useful for debugging
cl-launch and/or your build process. Option --verbose sets this variable,
whereas option --quiet resets it.


USING CL-LAUNCH FUNCTIONALITY IN YOUR LISP DEVELOPMENT ENVIRONMENT

When you develop programs that you will use with cl-launch, you may as well use
cl-launch during development, and benefit from its functionality.

To this end, you may explicitly include the cl-launch Lisp header from your
Lisp source code or from the Lisp initialization file for your favorite
implementation  (~/.sbclrc, ~/.cmucl-init, ~/.clisprc, etc.):
  #-cl-launch (load "/usr/share/common-lisp/source/cl-launch/launcher.lisp")
If cl-launch is not installed at a fixed system location, you may create
a copy in your own directory with such a command as
	cl-launch -B print_lisp_launcher > ~/src/cl-launch/launcher.lisp

Alternatively, you may include cl-launch itself instead of an extracted header,
if only you tell your Lisp reader consider #! as introducing a line comment:

    (set-dispatch-macro-character #\\# #\\!
      #'(lambda (stream char arg)
	   (declare (ignore char arg)) (values (read-line stream))))
    #-cl-launch (load "/path/to/cl-launch.sh")

Finally, if you use cl-launch from debian, or it was otherwise installed with
	cl-launch -B install
or if you create the asd in addition to the header and declare it to asdf
	cl-launch -B print_cl_launch_asd > ~/src/cl-launch/cl-launch.asd
then if your installed cl-launch.asd is properly symlinked from a directory
in your asdf:*central-registry*, you may just have your software depend on
the system :cl-launch
	(asdf:load-system :cl-launch)
which in some implementations (sbcl) can be simplified into
	(require :cl-launch)
You may also declare in the asdf:defsystem for your software that it
	:depends-on (:cl-launch ...)


MAKEFILE EXAMPLES:

### Automatically download of the current version of cl-launch if not present
cl-launch.sh:
	wget -O cl-launch.sh ${CL_LAUNCH_URL}
	chmod a+x cl-launch.sh

### Making a shell script executable from a simple Lisp file named foo.lisp
foo.sh: cl-launch.sh foo.lisp
	./cl-launch.sh --output foo.sh --file foo.lisp

### A more complex example using all options.
run-foo.sh: cl-launch.sh preamble.lisp
	./cl-launch.sh --output run-foo.sh --file preamble.lisp --system foo \\
	--init "(foo:main cl-launch:*arguments*)" \\
	--source-registry \${PREFIX}/cl-foo/systems: \\
	--lisp "ccl sbcl" --wrap 'SBCL=/usr/local/bin/sbcl-no-unicode' \\
	--no-include

### An example with horrible nested makefile, shell and Lisp quoting
hello:
	opera=wORlD ; ./cl-launch.sh --execute --init \\
	"(format t \\"~25R~A~A~%\\" 6873049 #\\\\space '\$\$opera)"


CAVEAT LISPOR

cl-launch begins evaluation of your Lisp software in the CL-USER package.
By the time your initialization forms are evaluated, the package may or may
not have changed, depending on the fine-grained semantics of load.
Be sure to use in-package if these things matter.

There are lots of ways of making mistakes by improperly quoting things when
you write shell commands. cl-launch does the right thing, but you still must
be careful with the nested quoting mechanisms of make, shell, and Lisp.

Here is a simple example use of cl-launch to quickly compare the result of
a same computation on a variety of systems:

  for l in sbcl cmucl clisp gcl ccl ; do
    ./cl-launch.sh --lisp \$l --execute --init \\
      '(format t "'\$l' ~A~%" most-positive-fixnum)' ; done

Internally, cl-launch includes many self-test functions.
You may for instance try (from a directory where it may create junk)
	./cl-launch.sh -l 'sbcl cmucl clisp gclcvs' -B tests

Share and Enjoy!
EOF
}

show_help () {
  print_help_header
  echo
  print_help
  echo
  print_help_footer
  exit "${1:-0}"
}
show_more_help () {
  print_help_header
  echo
  print_help
  echo
  print_more_help
  echo
  print_help_footer
  exit "${1:-0}"
}
error_help () {
  show_help "${1:-2}" >& 2
}
show_version () {
  echo "cl-launch ${CL_LAUNCH_VERSION}

Supported implementations:
    sbcl, cmucl (lisp), clisp, ecl, ccl (openmcl), abcl,
    xcl, gcl (gclcvs), allegro (alisp), lispworks, scl

Local defaults for generated scripts:
  will search in this order these supported implementations:
      ${DEFAULT_LISPS}"
  if [ -z "$DEFAULT_INCLUDE_PATH" ] ; then
    echo "\
  will generate self-contained scripts using option --no-include by default"
  else
    echo "\
  will generate scripts by default with runtime dependencies using option
    --include ${DEFAULT_INCLUDE_PATH}"
  fi
  if [ -n "$DEFAULT_USE_CL_LAUNCHRC" ] ; then
    echo "\
  will use /etc/cl-launchrc and ~/.cl-launchrc by default"
  else
    echo "\
  will not use /etc/cl-launchrc and ~/.cl-launchrc by default"
  fi
  if [ -z "$DEFAULT_USE_CLBUILD" ] ; then
    echo "\
  will generate scripts that do not use clbuild by default"
  else
    echo "\
  will generate scripts that use clbuild"
  fi
  echo
  exit
}

### Generic debugging library excerpted from ~fare/etc/zsh/aliases.debug

print_basic_functions () {
  cat <<'EOF'
ECHOn () { printf '%s' "$*" ;}
simple_term_p () {
  case "$1" in *[!a-zA-Z0-9-+_,.:=%/]*) return 1 ;; *) return 0 ;; esac
}
kwote0 () { ECHOn "$1" | sed -e "s/\([\\\\\"\$\`]\)/\\\\\\1/g" ;}
kwote () { if simple_term_p "$1" ; then ECHOn "$1" ; else kwote0 "$1" ; fi ;}
load_form_0 () { echo "(load $1 :verbose nil :print nil)" ;}
load_form () { load_form_0 "\"$(kwote "$1")\"" ;}
ECHO () { printf '%s\n' "$*" ;}
DBG () { ECHO "$*" >& 2 ;}
abort () { ERR="$1" ; shift ; DBG "$*" ; exit "$ERR" ;}
ABORT () { abort 42 "$*" ;}
EOF
}

eval "$(print_basic_functions)"

kwote1 () { if simple_term_p "$1" ; then ECHOn "$1"
  else ECHOn "\"$(kwote0 "$1")\"" ; fi ;}
SHOW () { ( set +x
  k="" ; for i ; do ECHOn "$k" ; kwote1 "$i" ; k=" " ; done ; echo
) }
XDO () { SHOW "$@" >&2 ; "$@" ;}
DO () { SHOW "$@" ; "$@" ;}
EVAL () { ECHO "$*" ; eval "$*" ;}
fullpath () {
 # If we were sure readlink is here, we could: for i ; do readlink -f "$i" ; done
 for i ; do case "$i" in /*) ECHO "$i" ;; *) ECHO "$PWD/$i" ;; esac ; done
}
print_var () {
  for var ; do eval "ECHO \"$var=\$(kwote1 \"\${$var}\")\"" ; done ;}
create_file () {
  MOD="$1" OUT="$2" ; shift 2; TMPFILE="$OUT.tmp$$~"
  if "${@:-cat}" > "$TMPFILE" &&
     chmod "$MOD" "$TMPFILE" &&
     mv -f "$TMPFILE" "$OUT" ;
  then return 0 ; else rm -f "$TMPFILE" ; return 1 ; fi
}

### Process options
OPTION () { process_options "$@" ;}
process_options () {
  case "$#:$1" in
    "1:-"*)
      : ;;
    "1:"*)
      add_init_form "(princ(progn $1))(terpri)"
      shift ;;
  esac
  while [ $# -gt 0 ] ; do
    x="$1" ; shift
    case "$x" in
      -h|"-?"|--help)
        show_help ;;
      -H|--more-help)
        show_more_help ;;
      -V|--version)
        show_version ;;
      -v|--verbose)
        export CL_LAUNCH_VERBOSE=t ;;
      -q|--quiet)
        unset CL_LAUNCH_VERBOSE ;;
      -f|--file)
	SOFTWARE_FILE="$1" ; shift ;;
      -s|--system)
	SOFTWARE_SYSTEM="$1" ; shift ;;
      -F|--final)
        add_final_form "$1" ; shift ;;
      -i|--init)
        add_init_form "$1" ; shift ;;
      -ip|--print)
        add_init_form "(princ(progn $1))(terpri)" ; shift ;;
      -iw|--write)
        add_init_form "(write(progn $1))(terpri)" ; shift ;;
      -p|-pc|+p)
        ABORT "option $x is not supported anymore." \
		"Use option -S instead." ;;
      --path|--path-current|--no-path)
        ABORT "option $x is not supported anymore." \
		"Use option --source-registry instead." ;;
      -S|--source-registry)
	SOURCE_REGISTRY="$1" ; shift ;;
      -l|--lisp)
	LISPS="$1" ; shift ;;
      -w|--wrap)
	WRAPPER_CODE="$1" ; shift ;;
      -I|--include)
        INCLUDE_PATH="$1" ; shift ;;
      +I|--no-include)
        INCLUDE_PATH="" ;;
      -R|--rc)
        USE_CL_LAUNCHRC=t ;;
      +R|--no-rc)
        USE_CL_LAUNCHRC= ;;
      -b|--clbuild)
        USE_CLBUILD=t ;;
      +b|--no-clbuild)
        USE_CLBUILD= ;;
      -o|--output)
	OUTPUT_FILE="$1" ; shift ;;
      -x|--execute)
        OUTPUT_FILE="!" ;;
      --)
        if [ "x${OUTPUT_FILE}" = "x!" ] ; then
          do_it "$@"
	else
	  ABORT "Extra arguments given but not in --execute mode"
        fi
	;;
      -X) OPTION -x
        #OPTION -iw "cl-launch::*arguments*"
        OPTION -i "(cl-launch::compile-and-load-file (pop cl-launch::*arguments*))"
        #OPTION -i "$(load_form_0 "(pop cl-launch::*arguments*)")"
        ;;
      -X' '*)
        # DBG "Working around sh script script limitation..."
	# The below gets the script arguments from the kernel-given argument:
	#	OPTS="$x" ; eval "OPTION $OPTS \"\$@\""
	# The kernel lumps everything after the interpreter name in the #! line
	# into one (optional) argument. The line is limited to 127 characters,
	# as defined in linux/{fs/binfmt_script.c,include/linux/binfmts.h}.
	# If we want to allow for a longer in-script command line argument,
	# and we do if we want to accomodate for inline Lisp code using -i
	# then we'd need to go fetch the full line and parse it. Here it is:
	OPTS="$(get_hashbang_arguments "$1")"
	eval "OPTION $OPTS \"\$@\""
	ABORT "The cl-launch script $1 failed to use -X ... --" ;;
      -u|--update)
	UPDATE="$1" ; shift ;;
      -m|--image)
        LOAD_IMAGE="$1" ; shift ;;
      -d|--dump)
	DUMP="$1" ; shift ;;
      -r|--restart)
	RESTART="$1" ; shift ;;
      -B|--backdoor)
	"$@" ; exit ;;
      -*=*)
	 DBG "Invalid command line argument '$x'" ; mini_help_abort ;;
      *=*) # explicit variable definition
	eval "$(kwote "$x")" ;;
      *)
	DBG "Unrecognized command line argument '$x'" ; mini_help_abort ;;
    esac
  done
}
add_init_form () {
        SOFTWARE_INIT_FORMS="$SOFTWARE_INIT_FORMS${SOFTWARE_INIT_FORMS+
}$1"
}
add_final_form () {
        SOFTWARE_FINAL_FORMS="$SOFTWARE_FINAL_FORMS${SOFTWARE_FINAL_FORMS+
}$1"
}
get_hashbang_arguments () {
  cut -c3- < "$1" | { read INTERP ARGUMENTS ; ECHO "$ARGUMENTS" ;}
}
mini_help_abort () {
  DBG "$HELP_HEADER

For help, invoke script with help argument:
	$PROG -h" ; ABORT
}

### Do the job
guess_defaults () {
  if [ -n "$UPDATE" ] ; then
    SOFTWARE_FILE=
    : "${OUTPUT_FILE:=$UPDATE}"
  fi
  LISP_CONTENT="$SOFTWARE_FILE"
}
# Configuration
system_preferred_lisps () {
  if [ "x${SOFTWARE_SYSTEM}" = "x$1" ] ; then
    shift
    LISPS="$*"
    DBG "User configuration for system ${SOFTWARE_SYSTEM} overrides LISPS with $(kwote1 "$LISPS")"
  fi
}
try_resource_file () {
  if [ -f "$1" ] ; then
    . "$1"
  fi
}
try_resource_files () {
  if [ -n "$USE_CL_LAUNCHRC" ] ; then
    try_resource_file /etc/cl-launchrc
    try_resource_file "$HOME/.cl-launchrc"
  fi
}
print_configuration () {
  print_var \
	SOFTWARE_FILE SOFTWARE_SYSTEM SOFTWARE_INIT_FORMS SOFTWARE_FINAL_FORMS \
	SOURCE_REGISTRY INCLUDE_PATH LISPS WRAPPER_CODE \
        DUMP RESTART IMAGE_BASE IMAGE_DIR IMAGE \
	$EXTRA_CONFIG_VARIABLES
}
include_configuration () {
  if [ -n "$UPDATE" ] ; then
    extract_configuration
    ECHO "$CONFIGURATION"
    eval "$CONFIGURATION"
  else
    extract_configuration
    print_configuration
  fi
}
ensure_configuration () {
  extract_configuration
  if [ -n "$UPDATE" ] ; then
    eval "$CONFIGURATION"
    adjust_configuration
  fi
}
adjust_configuration () {
  : INCLUDE_PATH="$INCLUDE_PATH" SOFTWARE_FILE="$SOFTWARE_FILE"
  if [ -n "$INCLUDE_PATH" ] ; then
    AUTHOR_NOTE= SHORT_LICENSE= LICENSE_COMMENT=
  fi
  case "$SOFTWARE_FILE" in
    ""|/dev/null) LISP_CONTENT= ;;
    /*) if [ -n "$INCLUDE_PATH" ] ; then
          LISP_CONTENT=
        else
          LISP_CONTENT="$SOFTWARE_FILE" SOFTWARE_FILE="."
        fi ;;
    .) LISP_CONTENT= SOFTWARE_FILE="." ;;
    -) LISP_CONTENT= SOFTWARE_FILE="-" ;;
    *) LISP_CONTENT="$SOFTWARE_FILE" SOFTWARE_FILE="." ;;
  esac
  : LISP_CONTENT="$LISP_CONTENT" SOFTWARE_FILE="$SOFTWARE_FILE"
}
include_license () {
  if [ -n "$DISCLAIMER" ] ; then
    l=
    for i in "$DISCLAIMER" "$AUTHOR_NOTE" "$SHORT_LICENSE" "$LICENSE_COMMENT"
    do l="$l$i${i:+#
}" ;  done
  ECHOn "$l"
  fi
  hide_license
}
hide_license () {
  DISCLAIMER= AUTHOR_NOTE= SHORT_LICENSE= LICENSE_COMMENT= CONTENT_DISCLAIMER=
}
include_lisp_header () {
  if [ -z "$INCLUDE_PATH" ] ; then
    print_lisp_header
  else
    echo "#-cl-launch"
    load_form "$INCLUDE_PATH/launcher.lisp"
  fi
}
LAUNCH_FUN=cl-launch::run
print_lisp_launch () {
  ECHOn "($LAUNCH_FUN"
  if [ -n "${SOURCE_REGISTRY}" ] ; then
    ECHOn " :source-registry \"$(kwote "$SOURCE_REGISTRY")\""
  fi
  case "${SOFTWARE_FILE}" in
    /dev/null|"") : ;;
    -) ECHOn " :load t" ;;
    .) ECHOn " :load :self" ;;
    *) ECHOn " :load \"$(kwote "$SOFTWARE_FILE")\""
  esac
  if [ -n "${SOFTWARE_SYSTEM}" ] ; then
    ECHOn " :system :${SOFTWARE_SYSTEM}"
  fi
  if [ -n "${SOFTWARE_FINAL_FORMS}" ] ; then
    ECHOn " :final \"$(kwote "${SOFTWARE_FINAL_FORMS}")\""
  fi
  if [ -n "${SOFTWARE_INIT_FORMS}" ] ; then
    ECHOn " :init \"$(kwote "${SOFTWARE_INIT_FORMS}")\""
  fi
  if [ -n "${NO_QUIT}" ] ; then
    ECHOn " :quit nil"
  fi
  if [ -n "${DUMP}" ] ; then
    ECHOn " :dump \"$(kwote "${DUMP}")\""
  fi
  if [ -n "${RESTART}" ] ; then
    ECHOn " :restart \"$(kwote "${RESTART}")\""
  fi
  ECHOn ")"
}
print_lisp_initialization () {
  echo "#-cl-launched"
  print_lisp_launch
}
print_lisp_content () {
  ECHO "$CONTENT_DISCLAIMER"
  ECHO "$CONTENT_BEGIN_MARKER"
  extract_lisp_content
}
include_lisp_content () {
  if [ "$SOFTWARE_FILE" = . ] ; then print_lisp_content ; fi
}
include_shell_wrapper () {
  ECHO "$BASIC_ENV_CODE"
  if [ -z "$INCLUDE_PATH" ] ; then
    print_shell_wrapper
  else
    ECHO ". $(kwote1 "$INCLUDE_PATH/wrapper.sh")"
  fi
}
include_script_configuration_and_headers () {
  ECHOn "\
#!/bin/sh
#| CL-LAUNCH ${CL_LAUNCH_VERSION} CONFIGURATION
" ; include_configuration ; ECHOn "\
# END OF CL-LAUNCH CONFIGURATION

# This file was generated by CL-Launch ${CL_LAUNCH_VERSION}
" ; include_license
}
make_loader () {
 include_script_configuration_and_headers
 include_shell_wrapper
 ECHOn '

launch_self "$@"
ABORT
# |#
' ; include_lisp_stuff
}
include_lisp_stuff () {
  include_lisp_header ; ECHOn '

;;;; CL-LAUNCH LISP INITIALIZATION CODE

' ; print_lisp_initialization ; ECHOn '

;;;; END OF CL-LAUNCH LISP INITIALIZATION CODE

' ; include_lisp_content
}
READ () {
  if [ $UNREAD_DEPTH = 0 ] ; then
    read -r LINE
  elif [ $UNREAD_DEPTH = 1 ] ; then
    UNREAD_DEPTH=0
    LINE="$LINE1"
  elif [ $UNREAD_DEPTH = 2 ] ; then
    UNREAD_DEPTH=1
    LINE="$LINE1"
    LINE1="$LINE2"
  else
    ABORT "error: UNREAD_DEPTH=$UNREAD_DEPTH"
  fi
}
UNREAD () {
  if [ $UNREAD_DEPTH = 0 ] ; then
    UNREAD_DEPTH=1
    LINE1="$1"
  elif [ $UNREAD_DEPTH = 1 ] ; then
    UNREAD_DEPTH=2
    LINE2="$LINE1"
    LINE1="$1"
  else
    ABORT "error: UNREAD_DEPTH=$UNREAD_DEPTH"
  fi
}
extract_configuration () {
  TRIED_CONFIGURATION=t
  CONFIGURATION=
  READ || return
  : "READ => $LINE"
  L1="#!/bin/sh"
  case "$LINE" in
    "$L1") : "read the SHEBANG" ;;
    *) : "Not a shell script" ; UNREAD "$LINE" ; return 2 ;;
  esac
  if ! READ ; then UNREAD "$L1" ; return 2 ; fi
  : "READ => $LINE"
  case "$LINE" in
    "#| CL-LAUNCH"*" CONFIGURATION") : "read the CL comment start" ;;
    *) : "Not a CL-Launch script" ; UNREAD "$LINE" ; UNREAD "$L1" ; return 2 ;;
  esac
  while READ &&
    #: "READ => $LINE" &&
    case "$LINE" in
      "# END OF CL-LAUNCH CONFIGURATION") ! : ;;
      *) : ;;
    esac
  do CONFIGURATION="$CONFIGURATION${CONFIGURATION:+
}$LINE" ; done
  HAS_CONFIGURATION=t
}
extract_lisp_content () {
  if [ -z "$TRIED_CONFIGURATION" ] ; then
    extract_configuration
  fi
  if [ -n "$HAS_CONFIGURATION" ] ; then
    skip_to_marker
  fi
  cat_with_unread
}
cat_with_unread () {
  while [ $UNREAD_DEPTH != 0 ] ; do
    READ
    : "READ => $LINE"
    ECHO "$LINE"
  done
  cat
}
skip_to_marker () {
  while READ &&
  #: "READ => $LINE" &&
    case "$LINE" in
      "$CONTENT_BEGIN_MARKER") ! : ;;
      *) : ;;
    esac
  do : ; done
}
create_output () {
  create_file 755 "$OUTPUT_FILE" "$@"
}
with_input_from () {
  IN="$1" ; shift
  case "$IN" in
    ""|/dev/null) : from null ; "$@" < /dev/null ;;
    -) : from stdin ; "$@" ;;
    *) : from file "$IN" ; "$@" < "$IN" ;;
  esac
}
with_input () {
  with_input_from "${UPDATE:-$LISP_CONTENT}" "$@"
}
with_output () {
  case "${OUTPUT_FILE}" in
    "") ABORT "output file not specified" ;;
    /dev/null) : ;;
    -) "$@" ;;
    *) create_output "$@" ;;
  esac
}
make_output_file () {
  if [ -n "$DUMP" ] ; then
    dump_image_and_continue
  else
    do_make_output_file
  fi
}
do_make_output_file () {
  with_output with_input make_loader
}

execute_code () {
  run_code "$@"
}
do_run_code () {
  eval "$(print_shell_wrapper_body)"
  if [ -n "$LISP_CONTENT" ] ; then
    export CL_LAUNCH_FILE="$LISP_CONTENT"
  else
    unset CL_LAUNCH_FILE
  fi
  LAUNCH_FUN='funcall(intern(string :run):cl-launch)'
  LAUNCH_FORMS="$(load_form "$PROG";print_lisp_launch)"
  try_all_lisps "$@"
}
run_code () {
  ### Note: when dumping an image, run_code gets locally redefined
  ### by do_dump_image_and_continue, and restored by do_dump_image
  do_run_code "$@"
}
dump_image_and_continue () {
  case "$UPDATE" in
    -) SOFTWARE_CODE="$(cat)"
       ECHO "$SOFTWARE_CODE" | do_dump_image_and_continue "$@" ;;
    *) do_dump_image_and_continue "$@" ;;
  esac
}
do_dump_image_and_continue () {
  ORIG_WRAPPER_CODE="$WRAPPER_CODE"
  run_code () {
    WRAPPER_CODE="$WRAPPER_CODE
DO_LISP=do_dump_image"
    do_run_code "$@"
  }
  if [ "x$DUMP" = "x!" ] ; then
    if [ "x$OUTPUT_FILE" = "x!" ] ; then
      abort 14 "Image dump required but neither dump file nor output file specified"
    else
      DUMP="$OUTPUT_FILE"
    fi
  fi
  IMAGE=
  execute_code "$@"
}
do_dump_image () {
  : do_dump_image "$@"
  run_code () {
    do_run_code "$@"
  }
  if [ -n "$INCLUDE_PATH" ] ; then
    export CL_LAUNCH_HEADER="$INCLUDE_PATH/launcher.lisp"
  else
    export CL_LAUNCH_HEADER="$PROG"
  fi
  if [ "x$IMAGE_ARG" = "xNOT_SUPPORTED_YET" ] ; then
      abort 13 "Image dumping not supported with implementation $IMPL.
Try specifying a supported implementation with option --lisp (or \$LISP)"
  fi
  if [ -n "$STANDALONE_EXECUTABLE" ] ; then
    if [ "x$DUMP" = "x$OUTPUT_FILE" ] ; then
      # disabled optimization: also for || [ "x$OUTPUT_FILE" = "x!" ]
      # as it doesn't play nice with older versions of SBCL, ECL, etc.,
      # that do not support standalone executables.
      export CL_LAUNCH_STANDALONE=t
    fi
  else
    if [ "x$DUMP" = "x$OUTPUT_FILE" ] ; then
      abort 15 "This implementation does not support dumping a standalone executable image"
    fi
  fi
  license_information
  # Use LOAD_IMAGE if it exists
  compute_image_path "$LOAD_IMAGE"
  ( do_exec_lisp ) || abort 22 "Failed to dump an image"
  case "$UPDATE" in
    -) ECHO "$SOFTWARE_CODE" | use_dumped_image "$@" ;;
    *) use_dumped_image "$@" ;;
  esac
}
use_dumped_image () {
  : use_dumped_image $OUTPUT_FILE
  compute_image_path "$DUMP"
  case "${CL_LAUNCH_STANDALONE}:${OUTPUT_FILE}" in
    :!) invoke_image "$@" ;;
    :*) make_image_invoker ;;
    t:!) if [ -n "$CL_LAUNCH_VERBOSE" ] ; then set -x ; fi ;
	${IMAGE} "$@" ;;
    t:*) ;;
  esac
}
make_image_invoker () {
  WRAPPER_CODE="$ORIG_WRAPPER_CODE"
  with_output with_input make_image_invocation_script
}
compute_image_path () {
  if [ -n "$1" ] ; then
    IMAGE_BASE="$(basename "$1")"
    IMAGE_DIR="${INCLUDE_PATH:-$(dirname "$1")}"
    IMAGE=${IMAGE_DIR}/${IMAGE_BASE}
  else
    IMAGE_BASE=
    IMAGE_DIR=
    IMAGE=
  fi
}

prepare_invocation_configuration () {
 LISP=$IMPL
 EXTRA_CONFIG_VARIABLES="LISP $OPTIONS_ARG"
 if eval "[ -n \"\$$BIN_ARG\" ]" ; then
   EXTRA_CONFIG_VARIABLES="$EXTRA_CONFIG_VARIABLES $BIN_ARG"
 fi
}
make_image_invocation_script () {
 prepare_invocation_configuration
 include_script_configuration_and_headers
 make_image_invocation
 include_lisp_content
}
make_image_invocation () {
 include_shell_wrapper
 if [ "x$IMAGE_ARG" = xEXECUTABLE_IMAGE ] ; then
   echo "$BIN_ARG=$IMAGE"
 fi
 cat<<END
ensure_implementation $IMPL
invoke_image "\$@"
ABORT
# |#
END
}
do_it () {
  guess_defaults
  try_resource_files
  process_software_1 "$@"
  exit
}
process_software_1 () {
  # Stage 1: extract the configuration (if required)
  if [ -n "$UPDATE" ] ; then
    extract_and_process_software_2 "$@"
  else
    adjust_configuration
    process_software_2 "$@"
  fi
}
extract_and_process_software_2 () {
  with_input ensure_configuration
  if [ "." = "$SOFTWARE_FILE" ] ; then
    SOFTWARE_FILE="${UPDATE}"
  fi
  if [ "x-" = "x$UPDATE" ] ; then
    extract_lisp_content | process_software_2 "$@"
  else
    process_software_2 "$@"
  fi
}
process_software_2 () {
  compute_image_path "$LOAD_IMAGE"
  # we have a configuration, now, ensure we have an image if needed
  if [ -n "$DUMP" ] ; then
    dump_image_and_continue "$@"
  else
    process_software_3 "$@"
  fi
}
process_software_3 () {
  # we have a configuration and no dump, now either execute or create script
  case "${OUTPUT_FILE}" in
    !) execute_code "$@" ;;
    *) make_output_file ;;
  esac
}
all () {
  process_options "$@"
  do_it
}

### Testing
foo_provide () {
  echo "(tst \"$1\"(defparameter *$2* 0)(defvar *err* 0)(format t \"--$2 worked, \"))"
}
foo_require () {
  echo "(tst \"$1\"(defvar *$2* 1)(defvar *err* 0)(incf *err* *$2*)
(unless (zerop *$2*) (format t \"--$2 ~A, \" :failed)))"
}
t_env () {
[ -n "$BEGIN_TESTS" ] && return
export DOH=doh
TCURR=
BEGIN_TESTS='(in-package :cl-user)(defvar *f* ())(defvar *err* 0)(defvar *begin* 0)(defvar *n*)
;;(eval-when (:compile-toplevel) (format *trace-output* "~&Prologue compiled~%"))
;;(eval-when (:load-toplevel) (format *trace-output* "~&Prologue loaded~%"))
;;(eval-when (:execute) (format *trace-output* "~&Prologue executed~%"))
(defmacro tst (x &body body) `(progn (setf *n* ,x) (push (quote(progn ,@body)) *f*)))

(defun tt () (dolist (x (reverse *f*)) (eval x)))
(tst()(format t "Hello, world, ~A speaking.~%"
#+asdf2 (cl-launch::call :asdf :implementation-type) #-asdf2 (lisp-implementation-type)))
'
END_TESTS="$(foo_require t begin)"'
(tst t(if (equal "won" (first cl-launch::*arguments*))
(format t "argument passing worked, ")
(progn (incf *err*) (format t "argument passing failed (got ~S), " (cl-launch::raw-command-line-arguments))))
(if (equal "doh" (cl-launch::getenv "DOH"))
(format t "getenv worked, ")
(progn (incf *err*) (format t "getenv failed, ")))
(if (zerop *err*) (format t "all tests ~a~a.~%" :o :k) (format t "~a ~a.~%" :error :detected)))'
case "$LISP" in
  ecl) CLOUT="$PWD/clt-out-sh" ;;
  *) CLOUT="$PWD/clt-out.sh" ;;
esac
TFILE="clt-src.lisp"
}
t_begin () {
  remain="$#" ARGS= TORIG= TOUT= TINC2=
  HELLO="$BEGIN_TESTS" GOODBYE= TESTS="" BEGUN= ENDING="$END_TESTS"
  t_lisp "$@" t_end ;}
t_lisp () { if [ -n "$LISP" ] ; then
  ARGS="--lisp $LISP" ; "$@" --lisp $LISP ; else "$@" ; fi ;}
t_end () { if [ -n "$TEXEC" ] ; then t_end_exec "$@" ;
  else t_end_out "$@" ; fi ;}
t_register () {
  # SHOW t_register "$@" ; print_var remain HELLO GOODBYE
  BEGUN=t
  HELLO="$HELLO$TESTS"
  if [ $remain = 1 ] || { [ $remain = 2 ] && [ "t_noinit" = "$2" ]; } ; then
    GOODBYE="$1$ENDING" TESTS= ENDING=
    #foo=1
  else
    GOODBYE="" TESTS="$1"
    #foo=2
  fi
  # print_var HELLO GOODBYE foo
}
t_next () { remain=$(($remain-1)) ; [ -n "$BEGUN" ] && HELLO= ; "$@" ;}
t_args () { ARGS="$ARGS $1" ;}
t_create () {
  create_file 644 "$1" echo "$2"
  TFILES="$TFILES $1" ;}
t_cleanup () { rm $TFILES ;}
t_file () {
  t_register "$(foo_require "$NUM:file" file)" $1
  t_create $TFILE \
	"(in-package :cl-user)
$HELLO
$(foo_provide "$NUM:file" file)
$GOODBYE"
  if [ -n "$TINC2" ] ; then t_args "--file /..." ;
    else t_args "--file ..." ; fi
  t_next "$@" --file "$TFILE"
}
t_system () {
  t_register "$(foo_require "$NUM:system" system)" $1
  t_create clt-asd.asd \
	'(in-package :cl-user)(asdf:defsystem :clt-asd :components ((:file "clt-sys")))'
  t_create clt-sys.lisp \
	"(in-package :cl-user)$HELLO$(foo_provide "$NUM:system" system)$GOODBYE"
  t_args "--system ..."
  t_next "$@" --system clt-asd --source-registry \
  "(:source-registry \
     (:directory \"${PWD}\") (:directory \"${ASDF_DIR}\") \
     :ignore-inherited-configuration)"
}
t_init () {
  t_register "$(foo_require "$NUM:init" init)" xxx_t_init
  t_args "--init ..."
  t_next "$@" --init "$HELLO$(foo_provide "$NUM:init" init)$GOODBYE(tt)"
}
t_noinit () {
  t_args "--restart ..."
  t_next "$@" --restart tt
}
t_image () {
 t_args "--image ..."
 t_register "$(foo_require "$NUM:image" image)" $1
 t_create clt-preimage.lisp \
       "(in-package :cl-user)$HELLO$(foo_provide "$NUM:image" image)$GOODBYE"
 if ! [ -f clt.preimage ] ; then
   t_make --dump clt.preimage --file clt-preimage.lisp --output clt-preimage.sh
 fi
 t_next "$@" --image "$PWD/clt.preimage"
}
t_dump () {
  t_args "--dump ..."
  t_next "$@" --dump "$PWD/clt.image"
}
t_dump_ () {
  t_args "--dump !"
  t_next "$@" --dump "!"
}
t_inc () {
  ( OPTION --include "$PWD" -B install_path ) >&2
  t_args "--include ..."
  t_next "$@" --include "$PWD"
}
t_inc1 () {
  TFILE=clt-src.lisp ; t_inc "$@"
}
t_inc2 () {
  TINC2=t TFILE="$PWD/clt-src.lisp" ; t_inc "$@"
}
t_noinc () {
  t_args "--no-include"
  t_next "$@" --no-include
}
t_update () {
  t_args "--update ..."
  TORIG=$CLOUT.orig ; cp -f $CLOUT $TORIG
  t_next "$@" --update $CLOUT
}
t_noupdate () {
  TORIG=
  t_next "$@"
}
t_end_out () {
  t_args "--output ... ; out.sh ..."
  TOUT=$CLOUT
  t_make "$@" --output $CLOUT
  t_check $CLOUT
}
t_end_exec () {
  t_args "--execute -- ..."
  t_check t_make "$@" --execute --
}
t_make () {
  XDO t_$TEST_SHELL -x $PROG "$@"
}
t_check () {
  echo "cl-launch $ARGS"
  PATH=${PWD}:$PATH "$@" "won" | tee clt.log >&2
  : RESULTS: "$(cat clt.log)"
  if [ -n "$TORIG" ] && [ -n "$TOUT" ] && ! cmp --quiet $TOUT $TORIG ; then
    echo "the updated file differs from the original one, although execution might not show the difference. Double check that with:
	diff -uN $TORIG $TOUT | less - $TORIG
"
    t_check_failed
  elif [ 0 = "$(grep -c OK < clt.log)" ] || [ 0 != "$(grep -c 'ERROR\(:\| DETECTED\)' < clt.log)" ] ; then
    t_check_failed
  else
    t_check_success
  fi
}
t_check_success () {
  echo "success with test $NUM :-)"
  return 0
}
t_check_failed () {
  echo "FAILURE with test $NUM :-("
  [ -n "$NUM" ] && echo "You may restart from this test with:
	$PROG -l $(kwote1 "$LISPS") -B tests $NUM
or
	$PROG -l $(kwote1 "$LISPS") -B tests $(printf %02d $(( ( $num / 4 ) * 4 )) )"
  [ -n "$TCURR" ] && echo "You may re-run just this test with:
	$PROG -B redo_test $TEST_SHELL $LISP $TCURR"
  [ -n "$NO_STOP" ] || ABORT "FIX THAT BUG!"
}
t_out () {
  t_env ; TEXEC= ; t_begin "$@"
}
t_exec () {
  t_env ; TEXEC=t ; t_begin "$@"
}
clisp_tests () { LISPS=clisp ; tests "$@" ;}
all_tests () { NO_STOP=t ; tests "$@" ;}
tests () {
  do_tests "$@" 2> tests.log
}
detect_program () {
  which "$1" 2>&1 > /dev/null
}
detect_shells () {
  # add something wrt ksh, pdksh ?
  TEST_SHELLS=
  for i in sh posh dash zsh pdksh bash busybox ; do
    if detect_program $i ; then
      TEST_SHELLS="$TEST_SHELLS $i"
    fi
  done
}
t_sh () { sh "$@" ;}
t_bash () { bash "$@" ;}
t_posh () { posh "$@" ;}
t_pdksh () { pdksh "$@" ;}
t_dash () { dash "$@" ;}
t_zsh () { zsh -fy "$@" ;}
t_busybox () { busybox sh "$@" ;}
shell_tests () {
  detect_shells
  tests "$@"
}

do_tests () {
  if [ -n "$TEST_SHELLS" ] ; then
    echo "Using test shells $TEST_SHELLS"
  fi
  t_env
  num=0 MIN=${1:-0} MAX=${2:-999999}
  export LISP
  # Use this with
  #    cl-launch.sh -B test
  # beware, it will clobber then remove a lot of file clt-*
  # and exercise your Lisp fasl cache
  for LISP in $LISPS ; do
  case $LISP in
    gcl) ;; # doesn't support asdf.
    *) export ASDF_DIR="$(case "$LISP" in xcl) LISP=sbcl ;; esac ; $PROG --lisp "$LISP" --quiet --system asdf --init '(cl-launch::finish-outputs)(format t "~%~A-~A: ~A~%" "SOURCE" "REGISTRY" (asdf:system-source-directory :asdf))' | grep ^SOURCE-REGISTRY: | tail -1 | cut -d' ' -f2- )" ;;
  esac
  for TEST_SHELL in ${TEST_SHELLS:-${TEST_SHELL:-sh}} ; do
  echo "Using lisp implementation $LISP with test shell $TEST_SHELL"
  for TM in "" "image " ; do
  for TD in "" "dump " "dump_ " ; do
  case "$TM:$TD:$LISP" in
    # we don't know how to dump from a dump with ECL
    image*:dump*:ecl) ;;
    # we don't know how to dump at all with ABCL, XCL
    *:dump*:abcl|image*:*:abcl|*:dump*:xcl|image*:*:xcl) ;;
    # Actually, even dumping is largely broken on ECL as of 3.010 + ASDF 2.015
    *:dump*:ecl|image*:*:ecl) ;;
    *)
  for IF in "noinc" "noinc file" "inc" "inc1 file" "inc2 file" ; do
  TDIF="$TM$TD$IF"
  for TS in "" " system" ; do
  TDIFS="$TDIF$TS"
  case "$TD:$TS:$LISP" in
    *:" system:gcl") ;; # no ASDF for GCL 2.6
    dump_*:cmucl*|dump_*:gcl*|dump_*:allegro|dump_*:ccl|dump_*:clisp|dump_*:scl)
      : invalid or unsupported combo ;; # actually only available for ecl and sbcl
    *)
  for TI in "noinit" "init" ; do
  TDIFSI="$TDIFS $TI"
  case "$TDIFSI" in
    *"inc noinit") : skipping invalid combination ;;
    *)
  for TU in "noupdate" "update" ; do
  TUDIFSI="$TU $TDIFSI"
  for TO in "exec" "out" ; do
  case "$TU:$TO:$TD" in
    update:*:dump_*) : invalid combo ;;
    *:exec:dump_*) : invalid combo ;;
    *)
  TEUDIFSI="$TO $TUDIFSI"
  do_test $TEUDIFSI
  ;; esac ; done ; done ;; esac ; done ;; esac ; done ; done ; esac ; done ; done ; done ; done
}
redo_test () {
  export TEST_SHELL="$1" LISPS="$2" LISP="$2" ; shift 2
  do_test "$@"
}
do_test () {
  if [ $MIN -le $num ] && [ $num -le $MAX ] ; then
    TCURR="$*"
    if [ -n "$num" ] ; then
      NUM=$(printf "%02d" $num)
      case "$*" in
        *out*noupdate*)
        # If we don't clean between runs of test/update, then
        # we have bizarre transient failures at test 12 or 40 when we e.g.
        #        DEBUG_RACE_CONDITION=t cl-launch -l clisp -B tests 8 12
        # There is some race condition somewhere in the cacheing layer,
        # and even though (trace ...) shows that cl-launch does try to
        # recompile then file, when it loads, it still find the old version in the cache.
        [ -n "$DEBUG_RACE_CONDITION" ] || test_clean
	;;
      esac
    fi
    eval "$(for i ; do ECHOn " t_$i" ; done)"
  fi
  num=$(($num+1))
}
test () {
  tests $@ && test_clean
}
test_clean () {
  rm -rfv clt* ~/.cache/common-lisp/*/$(pwd)/clt* >&2
}
fakeccl () {
  DO export LISP=ccl CCL=sbcl CCL_OPTIONS="--noinform --sysinit /dev/null --userinit /dev/null --eval (make-package':ccl) --eval (setf(symbol-function'ccl::quit)(symbol-function'sb-ext:quit)) --eval (setf(symbol-function'ccl::getenv)(symbol-function'sb-ext:posix-getenv))"
  OPTION "$@"
}
update () {
  wget -O cl-launch.sh "${CL_LAUNCH_URL}"
  chmod a+x cl-launch.sh
}
install () {
  if [ -z "$INCLUDE_PATH" ] || [ -z "$OUTPUT_FILE" ] ; then
    ABORT "example usage:
	$PROG -I /usr/share/common-lisp/source/cl-launch \\
	      -l '$DEFAULT_LISPS' \\
	      -o /usr/bin/cl-launch -B install"
  fi
  install_path
  install_bin
}
print_cl_launch_asd () {
  cat<<END
;;; -*- Lisp -*-
;; This file is for the sake of building systems that depend on cl-launch,
;; and/or binaries from implementations that link instead of dump (i.e. ECL).
;; cl-launch also used to be used as a way to redirect fasls, like
;; asdf-binary-locations or common-lisp-controller, in times before ASDF 2.
;;
;; It is only safe to upgrade asdf itself as part of an asdf operation
;; if the initial ASDF is more recent than 2.014.8.
;; If the initial ASDF isn't, you're likely in trouble.
;;
(asdf:defsystem :cl-launch
  :depends-on (#-asdf3 :asdf-driver) ; we need asdf-driver, included in asdf 3 and later
  :components ((:file "launcher")))
END
}
print_build_xcvb () {
  cat<<END
#+xcvb
(module
  (:fullname "cl-launch"
   :supersedes-asdf ("cl-launch")
   :build-depends-on ((:asdf "/asdf-driver"))
   :depends-on ("launcher")))
END
}
generate_install_files () {
  DO create_file 755 "cl-launch" print_configured_launcher &&
  DO create_file 644 "wrapper.sh" print_shell_wrapper &&
  DO create_file 644 "launcher.lisp" print_lisp_launcher &&
  DO create_file 644 "cl-launch.asd" print_cl_launch_asd
  DO create_file 644 "build.xcvb" print_build_xcvb
}
install_path () {
  DO mkdir -p "$INCLUDE_PATH" &&
  DO create_file 644 "$INCLUDE_PATH/wrapper.sh" print_shell_wrapper &&
  DO create_file 644 "$INCLUDE_PATH/launcher.lisp" print_lisp_launcher &&
  DO create_file 644 "$INCLUDE_PATH/cl-launch.asd" print_cl_launch_asd
  DO create_file 644 "$INCLUDE_PATH/build.xcvb" print_build_xcvb
}
configure_launcher () {
  sed -e \
      's,^\(DEFAULT_LISPS\)=.*$,\1="'"${1}"'",
       s,^\(DEFAULT_INCLUDE_PATH\)=.*$,\1='"${2%/}"',
       s,^\(DEFAULT_USE_CL_LAUNCHRC\)=.*$,\1="'"${3}"'",
       s,^\(DEFAULT_USE_CLBUILD\)=.*$,\1="'"${4}"'",'
}
print_configured_launcher () {
  configure_launcher "$LISPS" "$INCLUDE_PATH" "$USE_CL_LAUNCHRC" "$USE_CLBUILD" < "$PROG"
}
install_bin () {
  DO create_file 755 "$OUTPUT_FILE" print_configured_launcher
}

### The meaty stuff: shell wrapper and Lisp loader
### That's where you want to add support for new Lisp implementations
print_shell_wrapper () {
  echo "# cl-launch ${CL_LAUNCH_VERSION} shell wrapper
#   Find and execute the most appropriate supported Lisp implementation
#   to evaluate software prepared with CL-Launch.
#"
  include_license
  print_basic_functions
  print_shell_wrapper_body
}

# We must evaluate everything we need in only one form, because
# (1) SBCL (and other lisps?) refuses to execute several forms per --eval, and
# (2) clisp insists on printing every provided form, and we want to avoid that.
# We avoid this undesired output by ensuring that there is only one form,
# that quits before clisp prints anything, and that cause a SBCL error.
# Inside this form, we use #. to evaluate things before other things are read.
# Thus we may ensure that the CL-LAUNCH package exists before we attempt
# to read anything in it. Note that clisp *does* require the HASH_BANG_FORM,
# because we're not invoking our script using the clisp syntax.

print_shell_wrapper_body () {
  cat <<'EOF'
DO_LISP=do_exec_lisp
HASH_BANG_FORM='(set-dispatch-macro-character #\# #\! (lambda(stream char arg)(declare(ignore char arg))(values(read-line stream))))'
PACKAGE_FORM=" #.(progn(defpackage :cl-launch (:use :cl))())"
MAYBE_PACKAGE_FORM=
PROGN="(progn"
NGORP=")"

#implementation_foo () {
#  implementation "${foo:-foo}" || return 1
#  OPTIONS=${FOO_OPTIONS:- --option-to-hush-the-banner --option-to-avoid-user-init-script}
#  EVAL=--option-to-pass-a-form-to-Lisp
#  ENDARGS="--option-to-end-Lisp-arguments-and-start-user-arguments"
#  IMAGE_ARG="--option-to-specify-an-image" # "EXECUTABLE_IMAGE" if instead of foo --core x.core you just ./x.core
#  EXEC_LISP=exec_lisp # or some other thing
#  BIN_ARG=FOO # name of the variable with which to override Lisp binary location
#  OPTIONS_ARG=FOO_OPTIONS # name of the variable used above
#  [ -z "$CL_LAUNCH_DEBUG" ] && OPTIONS="${OPTIONS} --option-to-disable-debugger"
#}
implementation_abcl () {
  implementation "${ABCL:-abcl}" || return 1
  OPTIONS="${ABCL_OPTIONS:- --noinform --noinit}" # --nosystem
  EVAL=--eval
  ENDARGS="--"
  IMAGE_ARG=NOT_SUPPORTED_YET
  EXEC_LISP=exec_lisp
  BIN_ARG=ABCL
  OPTIONS_ARG=ABCL_OPTIONS
  if [ -z "$CL_LAUNCH_DEBUG" ] ; then
    OPTIONS="${OPTIONS} --batch" # -backtrace-on-error ???
  fi
}
__implementation_allegro () {
  OPTIONS="${ALLEGRO_OPTIONS:- -QQ -qq}"
  EVAL=-e
  ENDARGS=--
  IMAGE_ARG=-I
  EXEC_LISP=exec_lisp
  BIN_ARG=ALLEGRO
  OPTIONS_ARG=ALLEGRO_OPTIONS
  if [ -z "$CL_LAUNCH_DEBUG" ] ; then
    OPTIONS="${OPTIONS} -batch -backtrace-on-error"
  fi
  HASH_BANG_FORM="(setf *readtable* (copy-readtable))${HASH_BANG_FORM}"
}
implementation_allegro () {
  implementation "${ALLEGRO:-alisp}" || return 1
  __implementation_allegro
}
implementation_allegromodern () {
  implementation "${ALLEGROMODERN:-mlisp}" || return 1
  __implementation_allegro
}

implementation_ccl () {
  # ClozureCL, nee OpenMCL, forked from MCL, formerly Macintosh Common Lisp, nee Coral Common Lisp
  implementation "${CCL:-ccl}" || return 1
  OPTIONS="${CCL_OPTIONS:- --no-init --quiet}"
  EVAL=--eval # -e
  # IMAGE_ARG=--image-name # -I
  IMAGE_ARG=EXECUTABLE_IMAGE # depends on our using :prepend-kernel t
  ENDARGS=--
  # (finish-output) is essential for ccl, that won't do it by default,
  # unlike the other lisp implementations tested.
  EXEC_LISP=exec_lisp
  # exec_lisp will work great for 1.1 and later.
  # For earlier versions, use exec_lisp_arg instead:
  # 1.0 doesn't support --, and the latest 1.1-pre060826 snapshot has a bug
  # whereby it doesn't stop at -- when looking for a -I or --image-file argument.
  STANDALONE_EXECUTABLE=t
  BIN_ARG=CCL
  OPTIONS_ARG=CCL_OPTIONS
  if [ -z "$CL_LAUNCH_DEBUG" ] ; then
    OPTIONS="${OPTIONS} --batch"
  fi
}
implementation_clisp () {
  implementation "${CLISP:-clisp}" || return 1
  OPTIONS="${CLISP_OPTIONS:- -norc --quiet --quiet}"
  EVAL=-x
  LOAD=-i
  ENDARGS="--"
  # if the first argument begins with - there might be problems,
  # so we avoid that and take the cdr or ext:*args*
  # IMAGE_ARG=-M # for use without :executable t
  IMAGE_ARG="EXECUTABLE_IMAGE" # we don't use this by default
  STANDALONE_EXECUTABLE=t # will mostly work as of clisp 2.48, but with a (in)security backdoor.
  # For details, see the thread at http://sourceforge.net/forum/message.php?msg_id=5532730
  EXEC_LISP=exec_lisp
  BIN_ARG=CLISP
  OPTIONS_ARG=CLISP_OPTIONS
  if [ -z "$CL_LAUNCH_DEBUG" ] ; then
    OPTIONS="${OPTIONS} -on-error exit"
  else
    OPTIONS="${OPTIONS} -on-error debug"
  fi
}
implementation_cmucl () {
  implementation "${CMUCL:-cmucl}" || return 1
  OPTIONS="${CMUCL_OPTIONS:- -quiet -noinit}"
  EVAL=-eval
  ENDARGS=--
  #IMAGE_ARG=-core
  IMAGE_ARG="EXECUTABLE_IMAGE"
  STANDALONE_EXECUTABLE=t
  EXEC_LISP=exec_lisp # depends on a recent CMUCL. Works with 20B.
  BIN_ARG=CMUCL
  OPTIONS_ARG=CMUCL_OPTIONS
  if [ -z "$CL_LAUNCH_DEBUG" ] ; then
    OPTIONS="${OPTIONS} -batch"
  fi
}
implementation_ecl () {
  implementation "${ECL:-ecl}" || return 1
  OPTIONS="${ECL_OPTIONS:- -q -norc}"
  EVAL=-eval
  ENDARGS=--
  #IMAGE_ARG="-q -load" # for :fasl
  IMAGE_ARG="EXECUTABLE_IMAGE" # for :program
  STANDALONE_EXECUTABLE=t
  BIN_ARG=ECL
  OPTIONS_ARG=ECL_OPTIONS
  EXEC_LISP=exec_lisp
  if [ -n "$CL_LAUNCH_DEBUG" ] ; then
    PROGN="(handler-bind((error'invoke-debugger))(progn(set'si::*break-enable*'t)"
    NGORP="))"
  fi
}
implementation_ecl_bytecodes () {
  implementation_ecl
  OPTIONS="${OPTIONS} -eval (ext::install-bytecodes-compiler)"
  "${ECL:-ecl}" || return 1
  OPTIONS="${ECL_OPTIONS:- -q -norc}"
  EVAL=-eval
  ENDARGS=--
  #IMAGE_ARG="-q -load" # for :fasl
  IMAGE_ARG="EXECUTABLE_IMAGE" # for :program
  STANDALONE_EXECUTABLE=t
  BIN_ARG=ECL
  OPTIONS_ARG=ECL_OPTIONS
  EXEC_LISP=exec_lisp
  if [ -n "$CL_LAUNCH_DEBUG" ] ; then
    PROGN="(handler-bind((error'invoke-debugger))(progn(set'si::*break-enable*'t)"
    NGORP="))"
  fi
}
implementation_mkcl () { ### Untested
  implementation "${MKCL:-mkcl}" || return 1
  OPTIONS="${MKCL_OPTIONS:- -q -norc}"
  EVAL=-eval
  ENDARGS=--
  #IMAGE_ARG="-q -load" # for :fasl
  IMAGE_ARG="EXECUTABLE_IMAGE" # for :program
  STANDALONE_EXECUTABLE=t
  BIN_ARG=ECL
  OPTIONS_ARG=ECL_OPTIONS
  EXEC_LISP=exec_lisp
  if [ -n "$CL_LAUNCH_DEBUG" ] ; then
    PROGN="(handler-bind((error'invoke-debugger))(progn(set'si::*break-enable*'t)" ## Check this one!
    NGORP="))"
  fi
}
implementation_gcl () {
  implementation "${GCL:-gcl}" || return 1
  OPTIONS="${GCL_OPTIONS}"
  EVAL=-eval
  ENDARGS=-- # -f ?n
  IMAGE_ARG=EXECUTABLE_IMAGE
  BIN_ARG=GCL
  OPTIONS_ARG=GCL_OPTIONS
  export GCL_ANSI=t
  EXEC_LISP=exec_lisp
  if [ -z "$CL_LAUNCH_DEBUG" ] ; then
    OPTIONS="${OPTIONS} -batch"
  fi
}
implementation_lispworks () { ### NOT EXTENSIVELY TESTED
  # http://www.lispworks.com/documentation/lw60/LW/html/lw-484.htm#pgfId-891723
  USE_CLBUILD= implementation "${LISPWORKS:-lispworks}" || return 1
  OPTIONS="${LISPWORKS_OPTIONS:- -siteinit - -init -}" #
  LOAD=-build #### way to avoid splash screen (?) and dump executable
  # LOAD=-load
  EVAL=-eval # Exists in LW 6.0,
  #! ENDARGS="--"
  IMAGE_ARG="EXECUTABLE_IMAGE" # we don't use this by default
  EXEC_LISP=exec_lisp_file # for use with -build
  STANDALONE_EXECUTABLE=t
  BIN_ARG=LISPWORKS
  OPTIONS_ARG=LISPWORKS_OPTIONS
  if [ -z "$CL_LAUNCH_DEBUG" ] ; then
    : # OPTIONS="${OPTIONS} ..."
  else
    : # OPTIONS="${OPTIONS} ..."
  fi
  export LWLICENSE=$(dirname $LISP_BIN)/lwlicense
}
implementation_sbcl () {
  implementation "${SBCL:-sbcl}" || return 1
  OPTIONS="${SBCL_OPTIONS:- --noinform --userinit /dev/null}"
  # We purposefully specify --userinit /dev/null but NOT --sysinit /dev/null
  EVAL=--eval # SBCL's eval can only handle one form per argument.
  ENDARGS=--end-toplevel-options
  IMAGE_ARG="EXECUTABLE_IMAGE" # we use executable images
  # if you want to test non-executable images, uncomment the one below,
  # and comment out the :executable t in (defun dump-image ...)
  # -IMAGE_ARG=--core
  STANDALONE_EXECUTABLE=t # requires sbcl 1.0.21.24 or later.
  EXEC_LISP=exec_lisp
  BIN_ARG=SBCL
  OPTIONS_ARG=SBCL_OPTIONS
  if [ -z "$CL_LAUNCH_DEBUG" ] ; then
    OPTIONS="${OPTIONS} --disable-debugger"
  fi
}
implementation_scl () {
  implementation ${SCL:=scl} || return 1
  OPTIONS="${SCL_OPTIONS:- -quiet -noinit}"
  EVAL=-eval
  ENDARGS=--
  IMAGE_ARG=-core
  EXEC_LISP=exec_lisp
  BIN_ARG=SCL
  OPTIONS_ARG=SCL_OPTIONS
  if [ -z "$CL_LAUNCH_DEBUG" ] ; then
    OPTIONS="${OPTIONS} -batch"
  fi
}
implementation_xcl () {
  implementation "${XCL:-xcl}" || return 1
  OPTIONS="${XCL_OPTIONS:- --noinform --no-userinit}" # --no-siteinit
  EVAL=--eval
  ENDARGS="--"
  IMAGE_ARG=NOT_SUPPORTED_YET
  EXEC_LISP=exec_lisp
  BIN_ARG=XCL
  OPTIONS_ARG=XCL_OPTIONS
  if [ -z "$CL_LAUNCH_DEBUG" ] ; then
    : # Not supported yet
  fi
}
prepare_arg_form () {
  ENDARGS= F=
  for arg ; do
    F="$F\"$(kwote "$arg")\""
  done
  MAYBE_PACKAGE_FORM="$PACKAGE_FORM"
  LAUNCH_FORMS="(defparameter cl-launch::*arguments*'($F))${LAUNCH_FORMS}"
}
# Aliases
implementation_alisp () {
  implementation_allegro "$@"
}
implementation_mlisp () {
  implementation_allegromodern "$@"
}
implementation_gclcvs () {
  implementation "${GCLCVS:=gclcvs}" || return 1
  GCL="$GCLCVS"
  implementation_gcl "$@" && BIN_ARG=GCLCVS
}
implementation_lisp () {
  implementation ${CMULISP:=lisp} || return 1
  CMUCL=$CMULISP
  implementation_cmucl "$@"
}
implementation_openmcl () {
  implementation "${OPENMCL:=openmcl}" || return 1
  CCL="$OPENMCL"
  CCL_OPTIONS="$OPENMCL_OPTIONS"
  implementation_ccl "$@" && BIN_ARG=OPENMCL
}

exec_lisp_noarg () {
  prepare_arg_form "$@"
  exec_lisp
}
exec_lisp_file () {
  prepare_arg_form "$@"
  LOADFILE=${TMPDIR:-/tmp}/cl-load-file-$(date +%s)-$$
  cat > $LOADFILE <<END
${MAYBE_PACKAGE_FORM}
${HASH_BANG_FORM}
${LAUNCH_FORMS}
END
  $LISP_BIN $IMAGE_OPT $IMAGE $OPTIONS $LOAD "$LOADFILE"
  RET=$?
  rm -f $LOADFILE
  exit $RET
}
implementation_clisp_noarg () {
  implementation_clisp
  EXEC_LISP=exec_lisp_noarg
  # For testing purposes
}
implementation_clisp_file () {
  implementation_clisp
  EXEC_LISP=exec_lisp_file
  # For testing purposes
}
implementation () {
  if [ -n "$USE_CLBUILD" ] ; then
    if CLBUILD_BIN="`which clbuild 2> /dev/null`" ; then
      LISP_BIN="$CLBUILD_BIN --implementation $IMPL lisp"
      return 0
    else
      return 1
    fi
  elif [ -x "$1" ] ; then
    LISP_BIN="$1"
    return 0
  elif LISP_BIN="`which "$1" 2> /dev/null`" ; then
    return 0
  else
    return 1
  fi
}
trylisp () {
  IMPL="$1" ; shift
  implementation_${IMPL} "$@"
}
do_exec_lisp () {
  if [ -n "$IMAGE" ] ; then
    if [ "x$IMAGE_ARG" = xEXECUTABLE_IMAGE ] ; then
      LISP_BIN= IMAGE_OPT=
    else
      IMAGE_OPT="$IMAGE_ARG"
    fi
  fi
  $EXEC_LISP "$@"
}
no_implementation_found () {
  ABORT "$PROG: Cannot find a supported lisp implementation.
Tried the following: $*"
}
ensure_implementation () {
  trylisp "$1" || no_implementation_found "$1"
}
try_all_lisps () {
  for l in $LISP $LISPS ; do
    if trylisp $l ; then
      $DO_LISP "$@"
      return 0
    fi
  done
  no_implementation_found "$LISP $LISPS"
}
exec_lisp () {
  # SBCL wants only one form per --eval so we need put everything in one progn.
  # However we also want any in-package form to be evaluated before any of the
  # remaining forms is read, so we get it to be evaluated at read-time as the
  # first thing in the main progn.
  # GNU clisp allows multiple forms per -x but prints the result of every form
  # evaluated and so we also need put everything in a single progn, and that progn
  # must quit before it may return to the clisp frame that would print its value.
  # CMUCL allows multiple forms per -eval and won't print values, so is ok anyway.
  # I don't know about other Lisps, but they will all work this way.
  LAUNCH_FORM="${PROGN}${MAYBE_PACKAGE_FORM}${HASH_BANG_FORM}${LAUNCH_FORMS}${NGORP}"
  ### This is partial support for CLBUILD.
  if [ -n "$USE_CLBUILD" ] ; then
    if [ -z "$IMAGE_OPT" ] ; then
      OPTIONS=
    else
      ABORT "Cannot use clbuild with a non-executable image different from clbuild's"
    fi
  fi
  if [ -n "$CL_LAUNCH_VERBOSE" ] ; then set -x ; fi
  exec $LISP_BIN $IMAGE_OPT $IMAGE $OPTIONS $EVAL "$LAUNCH_FORM" $ENDARGS "$@"
}
launch_self () {
  LAUNCH_FORMS="$(load_form "$PROG")"
  try_all_lisps "$@"
}
invoke_image () {
  if [ "x$IMAGE_ARG" = xEXECUTABLE_IMAGE ] ; then
    LISP_BIN= IMAGE_OPT=
  else
    IMAGE_OPT="$IMAGE_ARG"
  fi
  PACKAGE_FORM=
  HASH_BANG_FORM=
  LAUNCH_FORMS="(asdf/image:restore-image)"
  "$EXEC_LISP" "$@"
}

export CL_LAUNCH_PID=$$
export CL_LAUNCH_FILE="$PROG"

## execute configuration-provided code
eval "$WRAPPER_CODE"

### END OF CL-LAUNCH SHELL WRAPPER
EOF
}
: ' Useful tidbit for dichotomy-debugging Lisp code:
(defvar *x* 0) (defun xx () (format t "*x* ~D~%" (incf *x*) (finish-output))) (xx)
(xx)
'
cl_fragment () {
  if [ -n "$CL_HEADER" ] ; then
    ECHO "#-cl-launch"
  fi
  cat
}
do_print_lisp_implementation () {
  ECHO "$IMPL"
}
print_lisp_implementation () {
  eval "$(print_shell_wrapper_body)"
  DO_LISP=do_print_lisp_implementation
  try_all_lisps
}
do_print_lisp_binary_path () {
  ECHO "$LISP_BIN"
}
print_lisp_binary_path () {
  eval "$(print_shell_wrapper_body)"
  DO_LISP=do_print_lisp_binary_path
  try_all_lisps
}
print_lisp_header () {
  CL_HEADER=t
  print_lisp_code
  echo ";;;;; Return to the default package."
  echo "(in-package :cl-user)"
  print_lisp_code_bottom
}
print_lisp_launcher () {
  CL_HEADER=
  print_lisp_code
  echo ; echo "(cl-launch::compute-arguments)"
  print_lisp_code_bottom
}
print_lisp_setup () {
  OPTION -q
  print_lisp_launcher
  OPTION -x -s asdf -i "(let ((*package* (find-package :cl-launch))) (format t \"(cl-launch::initialize-asdf ~S)~%\" \"$(kwote $SOURCE_REGISTRY)\"))" --
}

print_lisp_code () {
  echo "#+xcvb (module (:build-depends-on () :depends-on (\"/asdf\")))"
  echo "#| ;;; cl-launch ${CL_LAUNCH_VERSION} lisp header"
  include_license
# HACK: this whole file is itself readable as Lisp code, and its meaning
# is then that of the cl-launch lisp header code enclosed herein.
# |# Last bit of Karma
cat<<'NIL'

|# ;;;; Silence our lisp implementation for quiet batch use...

#| We'd like to evaluate as little as possible of the code without compilation.
 This poses a typical bootstrapping problem: the more sophistication we want
 to distinguish what to put where in what dynamic environment, the more code
 we have to evaluate before we may actually load compiled files. And, then,
 it is a waste of time to try to compile said code into a file. Moving things
 to the shell can only help so much, and reduces flexibility. Our best bet is
 to tell sbcl or cmucl to not try to optimize too hard.
|#
NIL
":" 't #-cl-launch ;'; cl_fragment<<'NIL'
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *print-readably* nil ; allegro 5.0 notably will bork without this
      *print-level* nil
      *load-verbose* nil *compile-verbose* nil *compile-print* nil *load-print* nil)
(defvar cl-user::*asdf-directory-pathname*
  (merge-pathnames #p"cl/asdf/" (user-homedir-pathname))
  "directory where ASDF is installed, if not provided by your implementation.")

(unless (member :asdf *features*)
  (ignore-errors (funcall 'require "asdf")))
(unless (member :asdf *features*)
  (ignore-errors (load (merge-pathnames "build/asdf.lisp" cl-user::*asdf-directory-pathname*))))
(unless (member :asdf *features*)
  (error "Could not load ASDF."))

(in-package :asdf))
NIL
":" 't #-cl-launch ;'; cl_fragment<<'NIL'
;; Make sure we use the latest ASDF available.
(eval-when (:compile-toplevel :load-toplevel :execute)

(ignore-errors
 (pushnew cl-user::*asdf-directory-pathname* *central-registry*)
 (defparameter asdf::*asdf-verbose* nil) ;; for old versions of ASDF 2
 (setf *load-verbose* nil asdf:*verbose-out* nil)
   (handler-bind ((warning #'muffle-warning))
     (operate 'load-op :asdf :verbose nil)))

(unless (member :asdf3 *features*)
  (unless (asdf::version-satisfies (asdf::asdf-version) "2.15")
    (error "CL-Launch requires ASDF 2.015 or later")) ; fallback feature
  (asdf:load-system :asdf-driver))

;;;; Ensure package hygiene
#+gcl2.6
(unless (find-package :cl-launch) (make-package :cl-launch :use '(:lisp)))
#-gcl2.6
(defpackage :cl-launch
  (:use :common-lisp :asdf/driver :asdf)
  (:export #:compile-and-load-file))

(in-package :cl-launch))
NIL
":" 't #-cl-launch ;'; cl_fragment<<'NIL'
;;;; CL-Launch Initialization code
(progn
(defvar *cl-launch-file* nil) ;; name of this very file
(defvar *verbose* nil)
(progn
  (defun call-with-new-file (n f)
    (with-open-file (o n :direction :output :if-exists :error :if-does-not-exist :create)
      (funcall f o)))
  (defun dump-stream-to-file (i n)
    (call-with-new-file n (lambda (o) (copy-stream-to-stream i o))))
  (defun dump-sexp-to-file (x n)
    (call-with-new-file
     n
     (lambda (o) (write x :stream o :pretty t :readably t))))
  (defvar *temporary-filenames* nil)
  (defvar *temporary-file-prefix*
    (format nil "~Acl-launch-~A-" asdf/driver:*temporary-directory* (getenvp "CL_LAUNCH_PID")))
  (defun make-temporary-filename (x)
    (concatenate 'string *temporary-file-prefix* x))
  (defun register-temporary-filename (n)
    (push n *temporary-filenames*)
    n)
  (defun temporary-filename (x)
    (register-temporary-filename (make-temporary-filename x)))
  (defun temporary-file-from-foo (dumper arg x)
    (let ((n (temporary-filename x)))
      (funcall dumper arg n)
      n))
  (defun temporary-file-from-stream (i x)
    (temporary-file-from-foo #'dump-stream-to-file i x))
  (defun temporary-file-from-string (i x)
    (temporary-file-from-foo #'princ i x))
  (defun temporary-file-from-sexp (i x)
    (temporary-file-from-foo #'dump-sexp-to-file i x))
  (defun temporary-file-from-file (f x)
    (with-open-file (i f :direction :input :if-does-not-exist :error)
      (temporary-file-from-stream i x)))
  (defun ensure-lisp-file-name (x &optional (name "load.lisp"))
    (let ((p (pathname x)))
      (if (equal (pathname-type p) "lisp")
          p
          (temporary-file-from-file p name))))
  (defun ensure-lisp-file (x &optional (name "load.lisp"))
    (cond
      ((eq x t) (temporary-file-from-stream *standard-input* "load.lisp"))
      ((streamp x) (temporary-file-from-stream x "load.lisp"))
      ((eq x :self) (ensure-lisp-file-name *cl-launch-file* name))
      (t (ensure-lisp-file-name x name))))
  (defun cleanup-temporary-files ()
    (loop :for n = (pop *temporary-filenames*)
          :while n :do
          (ignore-errors (delete-file n)))))
(defun file-newer-p (new-file old-file)
  "Returns true if NEW-FILE is strictly newer than OLD-FILE."
  (> (file-write-date new-file) (file-write-date old-file)))
(defun compile-and-load-file (source &key force-recompile
                              (verbose *verbose*) (load t)
                              output-file)
  "compiles and load specified SOURCE file, if either required by keyword
argument FORCE-RECOMPILE, or not yet existing, or not up-to-date.
Keyword argument VERBOSE specifies whether to be verbose.
Returns two values: the fasl path, and T if the file was (re)compiled"

  ;; When in doubt, don't trust - recompile. Indeed, there are
  ;; edge cases cases when on the first time of compiling a simple
  ;; auto-generated file (e.g. from the automated test suite), the
  ;; fasl ends up being written to disk within the same second as the
  ;; source was produced, which cannot be distinguished from the
  ;; reverse case where the source code was produced in the same split
  ;; second as the previous version was done compiling. Could be
  ;; tricky if a big system needs be recompiled as a dependency on an
  ;; automatically generated file, but for cl-launch those
  ;; dependencies are not detected anyway (BAD). If/when they are, and
  ;; lacking better timestamps than the filesystem provides, you
  ;; should sleep after you generate your source code.
  #+(and gcl (not gcl2.6))
  (setf source (ensure-lisp-file-name source (concatenate 'string (pathname-name source) ".lisp")))
  (let* ((truesource (truename source))
         (fasl (or output-file (compile-file-pathname* truesource)))
         (compiled-p
          (when (or force-recompile
                    (not (probe-file fasl))
                    (not (file-newer-p fasl source)))
            (ensure-directories-exist fasl)
            (multiple-value-bind (path warnings failures)
                (compile-file* truesource :output-file fasl)
              (declare (ignorable warnings failures))
              (unless (equal (truename fasl) (truename path))
                (error "CL-Launch: file compiled to ~A, expected ~A" path fasl))
              (when failures
                (error "CL-Launch: failures while compiling ~A" source)))
            t)))
    (when load
      (load* fasl :verbose verbose))
    (values fasl compiled-p)))
(defun load-file (source &key output-file)
  (declare (ignorable output-file))
  #-(or gcl2.6 (and ecl (not dlopen)))
  (compile-and-load-file source :verbose *verbose* :output-file output-file)
  #+gcl2.6
  (let* ((pn (parse-namestring source))) ; when compiling, gcl 2.6 will always
    (if (pathname-type pn) ; add a type .lsp if type is missing, to avoid compilation
      (compile-and-load-file source :verbose *verbose* :output-file output-file)
      (load source :verbose *verbose*)))
  #+(and ecl (not dlopen))
  (load source :verbose *verbose*))

(defun compute-arguments ()
  (setf *cl-launch-file* (getenvp "CL_LAUNCH_FILE")
        *verbose* (when (getenvp "CL_LAUNCH_VERBOSE") t)))

;; We provide cl-launch, no need to go looking for it further!
(unless (fboundp 'asdf::register-preloaded-system)
  (eval
   '(progn
      (defvar asdf::*preloaded-systems* (make-hash-table :test 'equal))
      (defun asdf::sysdef-preloaded-system-search (requested)
        (let ((name (coerce-name requested)))
          (multiple-value-bind (keys foundp) (gethash name asdf::*preloaded-systems*)
            (when foundp
              (apply 'make-instance 'system :name name :source-file (getf keys :source-file) keys)))))
      (defun asdf::register-preloaded-system (system-name &rest keys)
        (setf (gethash (coerce-name system-name) asdf::*preloaded-systems*) keys))
      (asdf::appendf asdf:*system-definition-search-functions* '(asdf::sysdef-preloaded-system-search)))))

(asdf::register-preloaded-system "cl-launch")

(defun do-build-and-load (load system restart final init quit)
  (etypecase load
    (null nil)
    ((eql t) (load* nil))
    (stream (load* load))
    ((eql :self) (load-file *cl-launch-file*))
    ((or pathname string) (load-file load)))
  (when system
    (load-systems system))
  (when final
    (load-from-string final))
  (setf *image-prelude* init
        *image-entry-point* (when restart (ensure-function restart))
        *lisp-interaction* (not quit)))

(defun build-and-load (load system restart final init quit)
  (unwind-protect
       (do-build-and-load load system restart final init quit)
    #+(and gcl (not gcl2.6))
    (cleanup-temporary-files)))


(defun build-and-run (load system restart final init quit)
  (build-and-load load system restart final init quit)
  (restore-image))

#-ecl
(defun build-and-dump (dump load system restart final init quit)
  (build-and-load load system restart final init quit)
  (dump-image dump :executable (getenvp "CL_LAUNCH_STANDALONE"))
  (quit 0))

;;; Attempt at compiling directly with ECL's make-build and temporary wrapper asd's
#+ecl (defvar *in-compile* nil)
#+ecl
(defun build-and-dump (dump load system restart final init quit)
  (unwind-protect
       (let* ((*compile-verbose* *verbose*)
              (*in-compile* t)
              (c::*suppress-compiler-warnings* (not *verbose*))
              (c::*suppress-compiler-notes* (not *verbose*))
              (*features* (remove :cl-launch *features*))
              (header (or *compile-file-pathname* *load-pathname* (getenvp "CL_LAUNCH_HEADER")))
              (header-file (ensure-lisp-file header "header.lisp"))
              (load-file (when load (ensure-lisp-file load "load.lisp")))
              (standalone (getenvp "CL_LAUNCH_STANDALONE"))
              (init-code
               `(progn
                  (unless *in-compile*
                    (setf
                     *package* (find-package :cl-user)
                     *load-verbose* nil
                     *dumped* ,(if standalone :standalone :wrapped)
                     *arguments* nil
                     ;;,(symbol* :asdf :*source-registry*) nil
                     ;;,(symbol* :asdf :*output-translations*) nil
                     ,@(when restart `(*restart* (read-function ,restart)))
                     *init-forms* ,init)
                    ,@(unless quit `(*quit* nil)))
                 ,(if standalone '(asdf/image:restore-image) '(si::top-level))))
              (final-file (temporary-file-from-string final "final.lisp"))
              (init-file (temporary-file-from-sexp init-code "init.lisp"))
              (prefix-sys (pathname-name (temporary-filename "prefix")))
              (program-sys (pathname-name (temporary-filename "program")))
              (prefix-sysdef
               `(,(symbol* :asdf :defsystem) ,prefix-sys
                 :depends-on () :serial t
                 :components ((:file "header" :pathname ,(truename header-file))
                              ,@(when load-file `((:file "load" :pathname ,(truename load-file)))))))
              (program-sysdef
               `(,(symbol* :asdf :defsystem) ,program-sys
                 :serial t
                 :depends-on (,prefix-sys
                              ,@(when system `(,system))
                              ,prefix-sys) ;; have the prefix first, whichever order asdf traverses
                 :components ((:file "final" :pathname ,(truename final-file))
                              (:file "init" :pathname ,(truename init-file)))))
              (prefix-asd (temporary-file-from-sexp prefix-sysdef "prefix.asd"))
              (program-asd (temporary-file-from-sexp program-sysdef "program.asd")))
         (load prefix-asd)
         (load program-asd)
         (call :asdf :make-build program-sys :type :program)
         (si:system (format nil "cp -p ~S ~S"
                            (namestring (first (call :asdf :output-files
                                                     (make-instance (symbol* :asdf :program-op))
                                                     (call :asdf :find-system program-sys))))
                            dump)))
    (cleanup-temporary-files))
  (quit))

;;(handler-bind (#+ecl (si::simple-package-error (lambda (x) (declare (ignore x)) (invoke-restart 'continue)))) (format *trace-output* "Enabling some debugging~%") #+ecl (trace c::builder c::build-fasl c:build-static-library c:build-program ensure-lisp-file-name ensure-lisp-file cleanup-temporary-files delete-package) #+ecl (setf c::*compiler-break-enable* t) (trace load-file load-systems build-and-dump build-and-run run compile-and-load-file load compile-file) (setf *verbose* t *load-verbose* t *compile-verbose* t))

(defun run (&key source-registry load system dump restart final init (quit 0))
  (pushnew :cl-launched *features*)
  (compute-arguments)
  (when source-registry (initialize-source-registry source-registry))
  (if dump
      (build-and-dump dump load system restart final init quit)
      (build-and-run load system restart final init quit)))

(pushnew :cl-launch *features*))
NIL
#|
}
print_lisp_code_bottom () {
# |#
":" ; cat<<'NIL'

;;; END OF CL-LAUNCH LISP HEADER
NIL
#|
}

### There we are. Now do the job
[ $# -gt 0 ] || mini_help_abort
all "$@" ; exit

# |# ; What follows is Lisp code available when loading this file
