#!/bin/sh
#| cl-launch.sh -- shell wrapper generator for Common Lisp software -*- Lisp -*-
CL_LAUNCH_VERSION='2.07'
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"

### Initialize cl-launch variables
unset \
	SOFTWARE_FILE SOFTWARE_SYSTEM SOFTWARE_INIT_FORMS \
	SYSTEMS_PATHS INCLUDE_PATH LISPS WRAPPER_CODE \
	OUTPUT_FILE UPDATE \
	LINE LINE1 LINE2 NO_QUIT CONTENT_FILE \
        TRIED_CONFIGURATION HAS_CONFIGURATION \
	SH_SCRIPT_ARGUMENT_WORKAROUND \
	EXEC_LISP DO_LISP DUMP RESTART IMAGE IMAGE_OPT \
	EXTRA_CONFIG_VARIABLES \
	EXECUTABLE_IMAGE DIRECT_EXECUTABLE CL_LAUNCH_EXECUTABLE \
        TEST_SHELLS TORIG

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

UNREAD_DEPTH=0
OUTPUT_FILE="!"

### Other constants
MAGIC_MD5SUM="65bcc57c2179aad145614ec328ce5ba8"
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:
 -f FILE	--file FILE	 FILE to be embedded or loaded
 -s SYSTEM	--system SYSTEM	 asdf SYSTEM to be loaded
 -r FUNC	--restart        restart FUNC to funcall before initializations
 -i FORM	--init FORM	 initialization FORM to evaluate after loading
 -ip FORM	--print FORM	 evaluate and princ FORM after loading
 -iw FORM	--write FORM	 evaluate and write FORM after loading
 -p PATH	--path PATH	 register asdf systems search PATH
 -pc		--path-current	 register current directory to asdf (default)
 +p		--no-path	 do not register any asdf system PATH
 -l LISP...	--lisp LISP...	 specify list of supported LISP implementations
 -w CODE	--wrap CODE      specify shell CODE to run in the wrapper
 -I PATH        --include PATH   specify runtime PATH to cl-launch installation
 +I             --no-include     disable cl-launch installation feature
 -R             --rc             try read /etc/cl-launchrc and ~/.cl-launchrc
 +R             --no-rc          skip /etc/cl-launchrc and ~/.cl-launchrc
 -v             --verbose        be very noisy while building software
 -q             --quiet          be quiet while building software (default)

Output options:
 -x      -o !   --execute	 no file creation, run the thing NOW (default)
 -o FILE	--output FILE	 specify FILE name of output script
 -d DUMP	--dump DUMP      dump an image of the world for faster startup
 -X ... --	(see more help)	 use #!/path/to/cl-launch as script interpreter
 --		--		 end of cl-launch 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).

The software is specified as the execution, in this order, of:
* 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 Lisp header manages compilation of Lisp code into a fasl cache
and provides uniform access to the invocation context. It defines a package
:cl-launch that exports the following symbols:
   *arguments* getenv quit
   load-system compile-and-load-file compile-file-pathname*
   apply-pathname-translations *output-pathname-translations*
   apply-output-pathname-translations
See below section 'CL-LAUNCH RUNTIME API'.

The cl-launch header will try to load ASDF. It will first try to (require ...)
it from your Lisp implementation, then will try a path provided through
environment variable \$ASDF_PATH if available, then it will look in your
home directory under ~src/asdf/asdf.lisp and finally it will search for
the default common-lisp-controller installation of it in
   /usr/share/common-lisp/source/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.


Multiple paths may be supplied that will be added to asdf:*central-registry*
before any software is loaded, so that asdf may find the required systems.
Each instance of option --path will specify one such path. The paths will
be added in reverse order, so that the those specified earlier have priority
over those specified later. You may also withhold any modification to asdf's
central registry by specifying option --no-path. Or you may specify the current
directory (at the time cl-launch is run) with option --path-current. The
default if none of these options have been specified is --no-path.
At each specification, an argument containing only alphanumerics and characters
-+_,.:=%/ will be considered as a pathname; any other specification will be
considered as an arbitrary Lisp expression (that will not be evaluated).
You can also add things to asdf:*central-registry* in your system-wide
or user configuration files for the startup of your Lisp implementation,
but note that the default arguments used by cl-launch when invoking those
implementations will disable system and user configuration files.
See below how to change these arguments.


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 openmcl 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,
cl-launch sets up a fasl cache to hold fasl files in a proper place.
It will also modify asdf so that it too will put files in the same cache.
This caching mechanism will be disabled if common-lisp-controller is present,
since c-l-c version 6.0 and later already do a similar caching.

The fasl cache is a per-user, per-Lisp-implementation, per-source-pathname,
mapping of source files to compiled files fasl.
The fasl for a file \$DIR/\$FILE with be stored in directory
	\$HOME/.cache/lisp-fasl/\$IMPL/\$DIR/
Here, \$IMPL is a unique string generated by cl-launch in a way similar
to what SLIME does, and stored in cl-launch::*implementation-name*.

You may specify an alternate cache directory instead of the default
\$HOME/.cache/lisp-fasl/ by setting and exporting the environment variable
	\$LISP_FASL_CACHE
You may also disable the cache altogether, by using the value NIL (uppercase).
This path is stored in variable cl-launch::*lisp-fasl-cache*.

Because the cache reserves a separate directory for every Lisp implementation,
it prevents common problems due to a same pathname being used by several
different and incompatible implementations or versions of a same implementation
to store their fasl files, resulting in conflict. This makes it easy to
share source code hierarchy among users, machines, implementations.

As a variant, if you know for sure which implementation you're using and
have set the variable \$LISP, you can override the whole path with variable
	\$LISP_FASL_ROOT
so that fasls for code under \$DIR with be stored under \$LISP_FASL_ROOT/\$DIR.

This feature plays well with common-lisp-controller: the clc cache will take
precedence when detected (tested with common-lisp-controller 4.12 to 6.6).
Hopefully, upstream versions of cl-launch and common-lisp-controller
will synchronize to prevent or quickly fix any possible breakage.
Due to outstanding bugs as of clc 6.6, ecl 0.9i-2 and gcl 2.7.0-61,
the clc cache is disabled for ECL and GCL.

Note that you may use symlinks to move ~/.cache/lisp-fasl/ to the place of your
choice, and to equate NFS paths that vary across machines for a same directory.
To distinguish paths between machines that share a common home directory but
with varying directory contents mounted on given identical pathnames, you can
use distinct values of \$LISP_FASL_CACHE depending on the machine, and merge
back whatever can be merged with symlinks.


SUPPORTED LISP IMPLEMENTATIONS

The implementations supported by current version of cl-launch are
	sbcl cmucl clisp openmcl allegro ecl gcl
Also defined are
	gclcvs lisp
which are name variations for gcl and cmucl respectively.
Finally, defined but completely untested is
	lispworks

The following releases have been tested.
They are fully supported unless specified otherwise.
  sbcl:  SBCL 1.0
  cmucl:  CMUCL 19b
  clisp:  GNU CLISP 2.38  (known breakage before version 2.36)
  openmcl:  OpenMCL 1.1-pre  (known breakage at version 1.0 and earlier)
  gclcvs:  GCL 2.7 ansi mode  (known breakage before debian release 2.7.0-62)
  allegro:  Allegro 5  (other versions completely untested)
  ecl:  ECL 0.9i
  gcl:  GCL 2.6.7 ansi mode  (--system not supported)

ECL is the only implementation to support creating a standalone executable
that works without the need of a shell wrapper. To use this feature,
give the same output file name as argument to both --dump and --output.

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.


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"
LISP_FASL_CACHE=/var/cache/lisp-fasl # 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.


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 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 given directory instead of the
directory where you dumped it. This option is currently supported with all of
clisp, sbcl, cmucl, allegro, openmcl, gcl and ecl.

Specifying a dump image of '!' or a giving a --dump argument identical to the
--output argument means that you want cl-launch to create a directly executable
file instead of script. This is currently only supported with ECL.


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 cl-launch:compile-file-pathname* to determine the fasl pathname.

Function cl-launch:compile-file-pathname* is a variant of the similarly named
ANSI CL function cl:compile-file-pathname that takes into account the
fasl cache and also common-lisp-controller (if present).
It works by calling cl-launch:apply-output-pathname-translations with the truename
of the given source file. The specified source file must exist.

Function cl-launch:apply-pathname-translations takes a pathname as an argument,
and an optional list of translations (by default, it will use those from
cl-launch:*output-pathname-translations*). It will scan the list of
translations, where every translation is a list of a source pathname
and a destination pathname. If the source pathname matches, then the file
is translated to the destination pathname.

Function cl-launch:apply-output-pathname-translations takes a pathname as an
argument translates it into a pathname in the cache. If common-lisp-controller
is present then the c-l-c cache is used. Otherwise, the cl-launch cache as
specified by cl-launch:*output-pathname-translations* is used.

Variable cl-launch:*output-pathname-translations* is the list of translations
that apply-pathname-translations will use by default.
asdf, if present, will have been configured to make use of this mechanism.

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 openmcl 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 fasl cache architecture.

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:oos 'asdf:load-op :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*)" \\
	--path \${PREFIX}/cl-foo/systems \\
	--lisp "openmcl 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 openmcl ; 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, gcl (gclcvs), openmcl, allegro

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"
  else
    echo "\
  will generate scripts 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
  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
    case "$1" in
      -h|"-?"|--help)
        show_help
        ;;
      -H|--more-help)
        show_more_help
        ;;
      -V|--version)
        show_version
        ;;
      -v|--verbose)
        export CL_LAUNCH_VERBOSE=t
	shift
        ;;
      -q|--quiet)
        unset CL_LAUNCH_VERBOSE
	shift
        ;;
      -f|--file)
	SOFTWARE_FILE="$2"
	shift 2 ;;
      -s|--system)
	SOFTWARE_SYSTEM="$2"
	shift 2 ;;
      -i|--init)
        add_init_form "$2"
	shift 2 ;;
      -ip|--print)
        add_init_form "(princ(progn $2))(terpri)"
	shift 2 ;;
      -iw|--write)
        add_init_form "(write(progn $2))(terpri)"
	shift 2 ;;
      -p|--path)
        register_system_path "$2"
	shift 2 ;;
      -pc|--path-current)
        path_current
	shift 1 ;;
      +p|--no-path)
        no_paths
	shift 1 ;;
      -l|--lisp) LISPS="$2"
	shift 2 ;;
      -w|--wrap) WRAPPER_CODE="$2" ;
        shift 2 ;;
      -I|--include)
        INCLUDE_PATH="$2"
	shift 2 ;;
      +I|--no-include)
        INCLUDE_PATH=""
	shift 1 ;;
      -R|--rc)
        USE_CL_LAUNCHRC=t
	shift 1 ;;
      +R|--no-rc)
        USE_CL_LAUNCHRC=
	shift 1 ;;
      -o|--output)
	OUTPUT_FILE="$2"
	shift 2 ;;
      -x|--execute)
        OUTPUT_FILE="!"
	shift ;;
      --)
        if [ "x${OUTPUT_FILE}" = "x!" ] ; then
	  shift
          do_it "$@"
	else
	  ABORT "Extra arguments given but not in --execute mode"
        fi
	;;
      -X) OPTION -x
        OPTION -i "(cl-launch::compile-and-load-file (pop cl-launch::*arguments*))"
        #OPTION -i "$(load_form_0 "(pop cl-launch::*arguments*)")"
        shift ;
        ;;
      -X' '*)
        # DBG "Working around sh script script limitation..."
	SH_SCRIPT_ARGUMENT_WORKAROUND=t ;
	# The below gets the script arguments from the kernel-given argument:
	#	OPTS="$1" ; shift ; 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 "$2")" ; shift
	eval "OPTION $OPTS \$@"
	ABORT "The cl-launch script $1 failed to use -X ... --"
	;;
      -u|--update)
	UPDATE="$2"
	shift 2 ;;
      -d|--dump)
	DUMP="$2"
        shift 2 ;;
      -r|--restart)
	RESTART="$2"
        shift 2 ;;
      -B|--backdoor) shift ; "$@" ; exit ;;
      -*=*)
	 DBG "Invalid command line argument '$1'" ; mini_help_abort ;;
      *=*) # explicit variable definition
	eval "$(kwote "$1")" ; shift 1 ;;
      *) DBG "Unrecognized command line argument '$1'" ; mini_help_abort ;;
    esac
  done
}
add_init_form () {
        SOFTWARE_INIT_FORMS="$SOFTWARE_INIT_FORMS${SOFTWARE_INIT_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
}
no_paths () {
  SYSTEMS_PATHS=
}
path_current () {
  register_system_path $PWD
}
register_system_path () {
  NEW_PATH="$(make_system_path "$1")"
  SYSTEMS_PATHS="$NEW_PATH $SYSTEMS_PATHS"
}
make_system_path () {
  if simple_term_p "$1" ; then
    ECHOn "#P\"$(kwote "${1%/}/")\""
  else
    ECHOn "$1"
  fi
}

### 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 \
	SYSTEMS_PATHS 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
    load_form "$INCLUDE_PATH/launcher.lisp"
  fi
}
LAUNCH_FUN=cl-launch::run
print_lisp_launch () {
  echo -n "($LAUNCH_FUN"
  if [ -n "${SYSTEMS_PATHS}" ] ; then
    echo -n " :paths '(${SYSTEMS_PATHS})"
  fi
  case "${SOFTWARE_FILE}" in
    /dev/null|"") : ;;
    -) ECHOn " :load t" ;;
    .) ECHOn " :load :self" ;;
    *) ECHOn " :load \"$(kwote "$SOFTWARE_FILE")\""
  esac
  if [ -n "${SOFTWARE_SYSTEM}" ] ; then
    echo -n " :system :${SOFTWARE_SYSTEM}"
  fi
  if [ -n "${SOFTWARE_INIT_FORMS}" ] ; then
    echo -n " :init \"$(kwote "${SOFTWARE_INIT_FORMS}")\""
  fi
  if [ -n "${NO_QUIT}" ] ; then
    echo -n " :quit nil"
  fi
  if [ -n "${DUMP}" ] ; then
    echo -n " :dump \"$(kwote "${DUMP}")\""
  fi
  if [ -n "${RESTART}" ] ; then
    echo -n " :restart \"$(kwote "${RESTART}")\""
  fi
  echo -n ")"
}
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 () {
  echo -n "\
#!/bin/sh
#| CL-LAUNCH ${CL_LAUNCH_VERSION} CONFIGURATION
" ; include_configuration ; echo -n "\
# 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
 echo -n '

launch_self "$@"
ABORT
# |#
' ; include_lisp_stuff
}
include_lisp_stuff () {
  include_lisp_header ; echo -n '

;;;; CL-LAUNCH LISP INITIALIZATION CODE

' ; print_lisp_initialization ; echo -n '

;;;; 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 () {
  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 "$DIRECT_EXECUTABLE" ] ; then
    if [ "x$DUMP" = "x$OUTPUT_FILE" ] || [ "x$OUTPUT_FILE" = "x!" ] ; then
      export CL_LAUNCH_EXECUTABLE=t
    fi
  else
    if [ "x$DUMP" = "x$OUTPUT_FILE" ] ; then
      abort 15 "This implementation does not support dumping a directly executable image"
    fi
  fi
  license_information
  ( 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 () {
  : ddi1 $OUTPUT_FILE
  compute_image_path
  case "${CL_LAUNCH_EXECUTABLE}:${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 () {
 IMAGE_BASE="$(basename "$DUMP")"
 IMAGE_DIR="${INCLUDE_PATH:-$(dirname "$DUMP")}"
 IMAGE=${IMAGE_DIR}/${IMAGE_BASE}
}
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 () {
  # 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='(defvar *f* ())(defvar *err* 0)(defvar *begin* 0)(defvar *n*)
(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.~%" cl-launch::*implementation-name*))
'
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, ")))
(if (equal "doh" (cl-launch::getenv "DOH"))
(format t "getenv worked, ")
(progn (incf *err*) (format t "getenv failed failed, ")))
(if (zerop *err*) (format t "all tests ~a~a.~%" :o :k) (format t "~a ~a.~%" :error :detected)))'
CLOUT="$PWD/clt-out-sh"
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 --path-current
}
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_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=.:$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 -ci error < 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 () {
  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
  for TEST_SHELL in ${TEST_SHELLS:-${TEST_SHELL:-sh}} ; do
  echo "Using test shell $TEST_SHELL"
  for TD in "" "dump " "dump_ " ; do
  for IF in "noinc" "noinc file" "inc" "inc1 file" "inc2 file" ; do
  TDIF="$TD$IF"
  for TS in "" " system" ; do
  TDIFS="$TDIF$TS"
  case "$TD:$TS:$LISP" in
    *:" system:gcl") ;; # no ASDF for GCL 2.6
    dump_*:sbcl*|dump_*:cmucl*|dump_*:gcl*|dump_*:allegro|dump_*:openmcl|dump_*:clisp)
      : invalid or unsupported combo ;; # actually only available for ecl
    *)
  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 ; 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/lisp-fasl/*/$(pwd)/clt* >&2
}
fakeopenmcl () {
  DO export LISP=openmcl OPENMCL=sbcl OPENMCL_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 -*-
(in-package :cl-user)

#-cl-launch
(load (make-pathname :name "launcher" :type "lisp" :defaults *load-truename*))
(cl-launch::compute-arguments)

(asdf:defsystem :cl-launch
  :components ((:file "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
}
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
}
configure_launcher () {
  sed -e \
      's,^\(DEFAULT_LISPS\)=.*$,\1="'"${1}"'",
       s,^\(DEFAULT_INCLUDE_PATH\)=.*$,\1='"${2%/}"',
       s,^\(DEFAULT_USE_CL_LAUNCHRC\)=.*$,\1="'"${3}"'",'
}
print_configured_launcher () {
  configure_launcher "$LISPS" "$INCLUDE_PATH" "$USE_CL_LAUNCHRC" < "$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=

implementation_cmucl () {
  implementation "${CMUCL:-cmucl}" || return 1
  OPTIONS="${CMUCL_OPTIONS:- -quiet -batch -noinit}"
  EVAL=-eval
  ENDARGS=--
  IMAGE_ARG=-core
  EXEC_LISP=exec_lisp_noarg
  # exec_lisp works fine, except in the corner case when the program's user
  # would use arguments that cmucl would process as its own arguments, even
  # though they are meant for the Lisp program. cmucl provides no way to
  # specify that arguments after "--" don't really matter.
  # And so we use exec_lisp_noarg.
  BIN_ARG=CMUCL
  OPTIONS_ARG=CMUCL_OPTIONS
}
implementation_lisp () {
  implementation ${CMULISP:=lisp} || return 1
  CMUCL=$CMULISP
  implementation_cmucl "$@"
}
implementation_sbcl () {
  implementation "${SBCL:-sbcl}" || return 1
  OPTIONS="${SBCL_OPTIONS:- --noinform --userinit /dev/null --disable-debugger}"
  # 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=--core
  #! IMAGE_ARG=EXECUTABLE_IMAGE # not appropriate: only executable if specified as such
  #! DIRECT_EXECUTABLE=t # won't work as of sbcl 0.9.17: we need to modify sbcl
  #! so it leaves all argument parsing to the software.
  EXEC_LISP=exec_lisp
  BIN_ARG=SBCL
  OPTIONS_ARG=SBCL_OPTIONS
}
implementation_clisp () {
  implementation "${CLISP:-clisp}" || return 1
  OPTIONS="${CLISP_OPTIONS:- -norc --quiet --quiet}"
  EVAL=-x
  LOAD=-i
  ENDARGS="-- foo"
  # 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
  #! DIRECT_EXECUTABLE=t # won't work as of unpatched 2.41: we need to modify clisp
  #! so it leaves all argument parsing to the software. See for instance
  #! http://article.gmane.org/gmane.lisp.clisp.devel/15476
  EXEC_LISP=exec_lisp
  BIN_ARG=CLISP
  OPTIONS_ARG=CLISP_OPTIONS
}
implementation_lispworks () { ### NEVER TESTED
  implementation "${LISPWORKS:-lispworks}" || return 1
  OPTIONS="${LISPWORKS_OPTIONS:- -siteinit -}" # -init -
  LOAD=-init #### No such thing found in the online documentation.
  #! EVAL=-eval # No such thing found in the online documentation.
  #! ENDARGS="--"
  IMAGE_ARG="EXECUTABLE_IMAGE" # we don't use this by default
  EXEC_LISP=exec_lisp_file
  BIN_ARG=LISPWORKS
  OPTIONS_ARG=LISPWORKS_OPTIONS
}
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}"
}
exec_lisp_noarg () {
  prepare_arg_form "$@"
  exec_lisp
}
exec_lisp_file () {
  prepare_arg_form "$@"
  LOADFILE=${TMP:-/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_openmcl () {
  implementation "${OPENMCL:-openmcl}" || return 1
  OPTIONS="${OPENMCL_OPTIONS:- --no-init --batch}"
  EVAL=--eval # -e
  IMAGE_ARG=--image-name # -I
  ENDARGS=--
  # (finish-output) is essential for openmcl, that won't do it by default,
  # unlike the other lisp implementations tested.
  EXEC_LISP=exec_lisp_noarg
  # exec_lisp will work great for 1.1, but 1.1 isn't there yet,
  # 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.
  BIN_ARG=OPENMCL
  OPTIONS_ARG=OPENMCL_OPTIONS
}
implementation_gcl () {
  implementation "${GCL:-gcl}" || return 1
  OPTIONS="${GCL_OPTIONS:- -batch}"
  EVAL=-eval
  ENDARGS=--
  IMAGE_ARG=EXECUTABLE_IMAGE
  BIN_ARG=GCL
  OPTIONS_ARG=GCL_OPTIONS
  export GCL_ANSI=t
  EXEC_LISP=exec_lisp
}
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
  DIRECT_EXECUTABLE=t
  BIN_ARG=ECL
  OPTIONS_ARG=ECL_OPTIONS
  EXEC_LISP=exec_lisp

  # work around brokenness in c-l-c packaging of ECL,
  # at least as of ecl 0.9i-2 and c-l-c 6.2
  if [ -z "$ECL" ] &&
     [ "/usr/bin/ecl" = "$LISP_BIN" ] &&
     [ -x "/usr/lib/ecl/ecl-original" ] ; then
    LISP_BIN=/usr/lib/ecl/ecl-original
  fi
}
implementation_gclcvs () {
  implementation "${GCLCVS:=gclcvs}" || return 1
  GCL="$GCLCVS"
  implementation_gcl "$@" && BIN_ARG=GCLCVS
}
implementation_allegro () {
  implementation "${ALLEGRO:-acl}" || return 1
  OPTIONS="${ALLEGRO_OPTIONS:- -QQ -qq -batch}"
  EVAL=-e
  ENDARGS=--
  IMAGE_ARG=-I
  EXEC_LISP=exec_lisp
  BIN_ARG=ALLEGRO
  OPTIONS_ARG=ALLEGRO_OPTIONS
}
implementation () {
  if [ -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 () {
  $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})"
  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="(cl-launch::resume)"
  "$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 -n "#-cl-launch "
  fi
  cat
}

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 "(compute-arguments)"
  print_lisp_code_bottom
}

print_lisp_code () {
  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
":" ; cl_fragment<<'NIL'
(eval-when (:load-toplevel :execute :compile-toplevel)
  (declaim (optimize (speed 1) (safety 2) (compilation-speed 3) #-gcl (debug 1)
       	   #+sbcl (sb-ext:inhibit-warnings 3)
           #+sbcl (sb-c::merge-tail-calls 3) ;-- this plus debug 1 (or sb-c::insert-debug-catch 0 ???) should ensure all tail calls are optimized, says jsnell
	   #+cmu (ext:inhibit-warnings 3)))
  #+gcl ;;; If using GCL, do some safety checks
  (when (or #-ansi-cl t)
    (format *error-output*
     "CL-Launch only supports GCL in ANSI mode. Aborting.~%")
    (lisp:quit))
  #+gcl
  (when (or (< system::*gcl-major-version* 2)
            (and (= system::*gcl-major-version* 2)
                 (< system::*gcl-minor-version* 7)))
    (pushnew :gcl-pre2.7 *features*))
  (setf *print-readably* nil ; allegro 5.0 notably will bork without this
        *load-verbose* nil *compile-verbose* nil *compile-print* nil)
  #+cmu (setf ext:*gc-verbose* nil)
  #+clisp (setf custom:*source-file-types* nil custom:*compiled-file-types* nil)
  #+gcl (setf compiler::*compiler-default-type* (pathname "")
              compiler::*lsp-ext* "")
  #+ecl (require 'cmp)

  ;;;; Ensure package hygiene
  (unless (find-package :cl-launch)
    (if (find-package :common-lisp)
       (defpackage :cl-launch (:use :common-lisp))
       (make-package :cl-launch :use '(:lisp))))
  (in-package :cl-launch))
NIL
":" ; cl_fragment<<'NIL'
(defmacro dbg (tag &rest exprs)
  "simple debug statement macro:
outputs a tag plus a list of source expressions and their resulting values, returns the last values"
  (let ((res (gensym))(f (gensym)))
  `(let ((,res))
    (flet ((,f (fmt &rest args) (apply #'format *error-output* fmt args)))
      (,f "~&~A~%" ,tag)
      ,@(mapcan
         #'(lambda (x)
            `((,f "~&  ~S => " ',x)
              (,f "~{~S~^ ~}~%" (setf ,res (multiple-value-list ,x)))))
         exprs)
      (apply 'values ,res)))))
NIL
":" ; cl_fragment<<'NIL'
(eval-when (:load-toplevel :execute :compile-toplevel)
  ;; Import a few symbols if needed
  #+common-lisp-controller
  (map () #'import
       '(clc::*source-root*
         clc::*fasl-root*
         clc::calculate-fasl-root
         clc::source-root-path-to-fasl-path
         clc::alternative-root-path-to-fasl-path
         clc::*redirect-fasl-files-to-cache*))
  #+ecl
  (map () #'import
       '(c::system-ld-flag
         c::library-type-p
         c::built-type-p
         c::builder
         c::build-fasl
         c::wt-filtered-data
         c::init-function-name
         c::data-init
         c::compiler-cc
         c::linker-cc
         c::shared-cc
         c::bundle-cc
         c::safe-system
         c::cmp-delete-file
         c::+lisp-program-header+
         c::+lisp-program-init+
         c::+lisp-program-main+
         c::+static-library-prefix+
         c::+lisp-program-init+
         ))
  ;;; define getenv and quit in ways that minimize package conflicts
  ;;; (use-package :cl-launch) while in cl-user.
  #+(or openmcl allegro gcl clisp ecl)
    (import '#+openmcl ccl::getenv
             #+allegro sys:getenv
             #+gcl system:getenv
             #+clisp ext:getenv
             #+ecl si:getenv
      :cl-launch)
  #+(or cmu sbcl lispworks)
    (defun getenv (x)
      #+sbcl (sb-ext:posix-getenv x)
      #+lispworks (lispworks:environment-variable x)
      #+cmu (cdr (assoc (intern x :keyword) ext:*environment-list*)))
  (defun quit (&optional (code 0) (finish-output t))
    (when finish-output ;; essential, for openmcl, and for standard compliance.
      (finish-outputs))
    #+cmu (unix:unix-exit code)
    #+clisp (ext:quit code)
    #+sbcl (sb-unix:unix-exit code)
    #+openmcl (ccl:quit code)
    #+gcl (lisp:quit code)
    #+allegro (excl:exit code :quiet t)
    #+ecl (si:quit code)
    #+lispworks (lispworks:quit :status code :confirm nil :return nil :ignore-errors-p t)
    #-(or cmu clisp sbcl openmcl gcl allegro ecl lispworks)
    (error "Quitting not implemented")))
NIL
":" ; cl_fragment<<'NIL'
(eval-when (:load-toplevel :execute :compile-toplevel)
  ;;;; Load ASDF
  (ignore-errors (require :asdf))
  ;;; Here is a fallback plan in case the lisp implementation isn't asdf-aware.
  (unless (and (find-package :asdf) (find-symbol "OUTPUT-FILES" :asdf))
    (defvar *asdf-path*
      (or (and (getenv "ASDF_PATH") (probe-file (getenv "ASDF_PATH")))
          (probe-file (merge-pathnames "src/asdf/asdf.lisp"
                                       (user-homedir-pathname)))
          (probe-file "/usr/share/common-lisp/source/asdf/asdf.lisp")))
    (when *asdf-path*
      (ignore-errors (load *asdf-path* :verbose nil :print nil)))))
NIL
":" ; cl_fragment<<'NIL'
(eval-when (:load-toplevel :execute :compile-toplevel)
  ;;; Even in absence of asdf, at least create a package asdf.
  (unless (find-package :asdf)
    (make-package :asdf)))
NIL
":" ; cl_fragment<<'NIL'
(eval-when (:load-toplevel :execute :compile-toplevel)
  ;;; Try to share this with asdf, in case we get asdf to support it one day.
  (map () #'import
       '(asdf::*output-pathname-translations*
         asdf::resolve-symlinks
         asdf::oos asdf::load-op asdf::find-system)))

;;;; CL-Launch Initialization code
NIL
":" ; cl_fragment<<'NIL'
(progn

(pushnew :cl-launch *features*)

;;#+ecl (require 'cmp) ; ensure we use the compiler (we use e.g. *ecl-library-directory*)

(dolist (s '(*arguments* getenv quit compile-and-load-file
             compile-file-pathname* apply-pathname-translations
	     *output-pathname-translations*
             apply-output-pathname-translations))
  (export s))

;; To dynamically recompute from the environment at each invocation
(defvar *cl-launch-file* nil)
(defvar *verbose* nil)
(defvar *lisp-fasl-cache* nil "lisp fasl cache hierarchy")
(defvar *lisp-fasl-root* nil "top path for the fasl cache for current implementation")
;; To dynamically recompute from the command-line at each invocation
(defvar *arguments* nil "command-line parameters")

;; Variables that define the current system
(defvar *dumped* nil)
(defvar *restart* nil)
(defvar *init-forms* nil)
(defvar *quit* t)

;; Provide compatibility with clc 6.2
(defvar *redirect-fasl-files-to-cache* t)

#+ecl
(defun command-line-arguments ()
  (loop for i from 1 below (si:argc) collect (si:argv i)))

(defun compute-arguments ()
  #+gcl (setf system::*tmp-dir* (ensure-directory-name (or (getenv "TMP") "/tmp"))) ; basic lack fixed after gcl 2.7.0-61, but ending / required still on 2.7.0-64.1
  (setf *cl-launch-file* (getenv "CL_LAUNCH_FILE")
        *verbose* (when (getenv "CL_LAUNCH_VERBOSE") t)
        *lisp-fasl-cache* (let* ((cache-env (getenv "LISP_FASL_CACHE"))
                            (cache-spec
                             (cond
                               ((null cache-env)
                                (merge-pathnames
                                 #p".cache/lisp-fasl/"
                                 ;;(make-pathname :directory (list :relative ".cache" "lisp-fasl"))
                                 (user-homedir-pathname)))
                               ((equal cache-env "NIL") nil)
                               (t (dirname->pathname cache-env)))))
                       #+gcl-pre2.7 cache-spec #-gcl-pre2.7
		       (when cache-spec
                         (ensure-directories-exist cache-spec)
                         (resolve-symlinks cache-spec)))
        *lisp-fasl-root* (let* ((root-env
                                 (when (getenv "LISP")
                                   (let ((r (getenv "LISP_FASL_ROOT")))
                                     (when r (if (equal r "NIL") :disabled
                                                 (dirname->pathname r))))))
                                (root-spec
                                 (or root-env
                                     (when *lisp-fasl-cache*
                                       (merge-pathnames
                                        (make-pathname
                                         :directory (list :relative *implementation-name*))
                                        *lisp-fasl-cache*)))))
			   #+gcl-pre2.7 root-spec #-gcl-pre2.7
                           (when root-spec
                             (ensure-directories-exist root-spec)
                             (resolve-symlinks root-spec))))
  (calculate-output-pathname-translations)
  (setf *arguments*
   (or *arguments*
       #+(or cmu gcl ecl lispworks)
         (cdr (member "--"
		      #+gcl si:*command-args*
                      #+ecl (command-line-arguments)
		      #+cmu extensions:*command-line-strings*
                      #+lispworks system:*line-arguments-list*
		      :test 'equal))
       #+openmcl ccl:*unprocessed-command-line-arguments*
       #+sbcl (cdr sb-ext:*posix-argv*)
       #+allegro (cdr (sys:command-line-arguments))
       #+clisp (cdr ext:*args*))))

(defun register-paths (paths)
  #-asdf (declare (ignore paths))
  #+asdf
  (dolist (p (reverse paths))
    (pushnew p asdf::*central-registry* :test 'equal)))

(defun load-stream (&optional (s #-clisp *standard-input*
				 #+clisp *terminal-io*))
  ;; GCL 2.6 can't load from a string-input-stream
  ;; OpenMCL 1.1-pre cannot load from either *standard-input* or *terminal-io*
  ;; Allegro 5, I don't remember but it must have been broken when I tested.
  #+(or gcl-pre2.7 allegro)
  (do ((eof '#:eof) (x t (read s nil eof))) ((eq x eof)) (eval x))
  #-(or gcl-pre2.7 allegro)
  (load s :verbose nil :print nil))

(defun load-string (string)
  (with-input-from-string (s string) (load-stream s)))

(defun finish-outputs ()
  (finish-output *error-output*)
  (finish-output))

(defun %abort (code fmt &rest args)
  (apply #'format *error-output* fmt args)
  (quit code))

(defun resume ()
  (compute-arguments)
  (do-resume))

(defun do-resume ()
  (when *restart* (funcall *restart*))
  (when *init-forms* (load-string *init-forms*))
  (finish-outputs)
  (when *quit* (quit 0)))

(defun dump-image (filename &key executable (package :cl-user))
  (declare (ignorable filename executable package))
  (setf *dumped* (if executable :executable t)
        *arguments* nil)
  #+clisp
  (ext:saveinitmem filename
   :executable executable
   :init-function (when executable #'resume)
   ;; :parse-options (not executable) ;--- requires a patch to clisp
   :script t
   :quiet t
   :norc t
   :start-package package
   :keep-global-handlers nil)
  #+sbcl
  (progn
    ;;(sb-pcl::precompile-random-code-segments) ;--- it is ugly slow at compile-time (!) when the initial core is a big CLOS program. If you want it, do it yourself
   (setf sb-ext::*gc-run-time* 0)
   (apply 'sb-ext:save-lisp-and-die filename
    :executable executable
    (when executable (list :toplevel #'resume))))
  #+cmu
  (progn
   (ext:gc :full t)
   (setf ext:*batch-mode* nil)
   (setf ext::*gc-run-time* 0)
   (extensions:save-lisp filename))
  #+openmcl
  (ccl:save-application filename)
  #+allegro
  (progn
   (sys:resize-areas :global-gc t :pack-heap t :sift-old-areas t :tenure t) ; :new 5000000
   (excl:dumplisp :name filename :suppress-allegro-cl-banner t))
  #+lispworks
  (save-image filename :environment nil) ; XXXXX
  #+gcl
  (progn
   (si::set-hole-size 500) (si::gbc nil) (si::sgc-on t)
   (si::save-system filename))
  #-(or clisp sbcl cmu openmcl allegro gcl lispworks)
  (%abort 11 "CL-Launch doesn't supports image dumping with this Lisp implementation.~%"))

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

(defun read-function (string)
  `(function ,(read-from-string string)))

(defun build-and-load (load system restart init quit)
  (when load
    (cond
     ((eq load t) (load-stream))
     ((streamp load) (load-stream load))
     ((eq load :self) (load-file *cl-launch-file*))
     (t (load-file load))))
  (when system
    #+asdf
    (load-system system :verbose *verbose*)
    #-asdf
    (%abort 10 "ERROR: asdf requested, but not found~%"))
  (setf *restart* (when restart (eval (read-function restart)))
        *init-forms* init
        *quit* quit))

(defun build-and-run (load system restart init quit)
  (build-and-load load system restart init quit)
  (do-resume))

#-ecl
(defun build-and-dump (dump load system restart init quit)
  (build-and-load load system restart init quit)
  (dump-image dump :executable (getenv "CL_LAUNCH_EXECUTABLE"))
  (quit))

#+ecl (progn ;;; ECL PATCH: modifies and adds functions into ecl*/src/cmp/cmpmain.lsp
;;; necessary for ecl 0.9i. The patch since made it to the development branch and so
;;; will have to be removed from here when new ecl releases make it to our target
;;; linux distributions.

(defun system-ld-flag (library)
  (let ((asdf (find-package "ASDF"))
        system)
    (labels ((asdfsym (x) (find-symbol (string x) asdf))
             (asdfcall (fun &rest rest) (apply (asdfsym fun) rest))
             (system-output (system type)
               (let ((build (make-instance (asdfsym :build-op) :type type)))
                 (first (asdfcall :output-files build system))))
             (existing-system-output (system type)
               (let ((o (system-output system type)))
                 (and o (probe-file o))))
             (find-archive (system)
                 (or (existing-system-output system :library)
                     (existing-system-output system :shared-library)))
             (fallback () (format nil #-msvc "-l~A" #+msvc "~A.lib" (string-downcase library))))
      (or (and asdf
               (setf system (asdfcall :find-system library nil))
               (find-archive system))
        (fallback)))))

(defun library-type-p (type)
  (member type
          #-msvc '("a" "so")
          #+msvc '("lib" "dll")
          :test #'equal))

(defun built-type-p (type)
  (or (equal type #-msvc "o" #+msvc "obj")
      (library-type-p type)))

(defun builder (target output-name &key lisp-files ld-flags shared-data-file
		(init-name nil)
		(prologue-code "")
		(epilogue-code (when (eq target :program) '(SI::TOP-LEVEL)))
		#+:win32 (system :console))
  ;;
  ;; The epilogue-code can be either a string made of C code, or a
  ;; lisp form.  In the latter case we add some additional C code to
  ;; clean up, and the lisp form is stored in a text representation,
  ;; to avoid using the compiler.
  ;;
  (cond ((null epilogue-code)
	 (setf epilogue-code ""))
	((stringp epilogue-code)
	 )
	(t
	 (with-standard-io-syntax
	   (setq epilogue-code
		 (with-output-to-string (stream)
		   (princ "{ const char *lisp_code = " stream)
		   (wt-filtered-data (write-to-string epilogue-code) stream)
		   (princ ";
cl_object output;
si_select_package(make_simple_base_string(\"CL-USER\"));
output = cl_safe_eval(c_string_to_object(lisp_code), Cnil, OBJNULL);
" stream)
		   (when (eq target :program)
		     (princ "cl_shutdown(); return (output != OBJNULL);" stream))
		   (princ #\} stream)
		   )))))
  ;;
  ;; When a module is built out of several object files, we have to
  ;; create an additional object file that initializes those ones.
  ;; This routine is responsible for creating this file.
  ;;
  ;; To avoid name clashes, this object file will have a temporary
  ;; file name (tmp-name).
  ;;
  (let* ((tmp-name (si::mkstemp #P"TMP:ECLINIT"))
	 (c-name (si::coerce-to-filename
		  (compile-file-pathname tmp-name :type :c)))
	 (o-name (si::coerce-to-filename
		  (compile-file-pathname tmp-name :type :object)))
	 submodules
	 c-file)
    (dolist (item (reverse lisp-files))
      (etypecase item
        (symbol
         (push (system-ld-flag item) ld-flags)
         ;;---*** NOTE: reduce clashes by having a system prefix in the init-name
         (push (init-function-name item "system") submodules))
        ((or string pathname)
         (let* ((pn (parse-namestring item))
                (type (pathname-type pn))
                (module (pathname-name pn))
                (init-fn
                 ;;---*** NOTE: it would reduce clashes to keep/add a
                 ;;---*** system/library prefix in/to the init-name
                 (if (library-type-p type)
                   (let ((name
                          (if (equal (subseq module 0 (length +static-library-prefix+))
                                     +static-library-prefix+)
                           (subseq module (length +static-library-prefix+))
                           module)))
                     (init-function-name name "system"))
                   (init-function-name module)))
                (built-pn
                 (if (built-type-p type) pn
                   (compile-file-pathname pn :type :object)))
                (filename (si::coerce-to-filename built-pn)))
           (push filename ld-flags)
           (push init-fn submodules)))))
    (setq c-file (open c-name :direction :output))
    (format c-file +lisp-program-header+
            #-(or :win32 :mingw32 :darwin) (if (eq :fasl target) nil submodules)
            #+(or :win32 :mingw32 :darwin) submodules)
    (cond (shared-data-file
	   (data-init shared-data-file)
	   (format c-file "
#define VM ~A
#ifdef ECL_DYNAMIC_VV
static cl_object *VV;
#else
static cl_object VV[VM];
#endif
#define ECL_SHARED_DATA_FILE 1
" (data-permanent-storage-size))
	   (data-dump c-file))
	  (t
	   (format c-file "
#define compiler_data_text NULL
#define compiler_data_text_size 0
#define VV NULL
#define VM 0" c-file)))
    (ecase target
      (:program
       (when (or (symbolp output-name) (stringp output-name))
	 (setf output-name (compile-file-pathname output-name :type :program)))
       (unless init-name
	 (setf init-name (init-function-name (pathname-name output-name) nil)))
       (format c-file +lisp-program-init+ init-name "" shared-data-file
	       submodules "")
       (format c-file #+:win32 (ecase system (:console +lisp-program-main+)
				             (:windows +lisp-program-winmain+))
	              #-:win32 +lisp-program-main+
		      prologue-code init-name epilogue-code)
       (close c-file)
       (compiler-cc c-name o-name)
       (apply #'linker-cc output-name (namestring o-name) ld-flags))
      ((:library :static-library :lib)
       (when (or (symbolp output-name) (stringp output-name))
	 (setf output-name (compile-file-pathname output-name :type :lib)))
       (unless init-name
	 ;; Remove the leading "lib"
	 (setf init-name (subseq (pathname-name output-name) (length +static-library-prefix+)))
	 (setf init-name (init-function-name init-name "system")))
       (format c-file +lisp-program-init+ init-name prologue-code
	       shared-data-file submodules epilogue-code)
       (close c-file)
       (compiler-cc c-name o-name)
       #-msvc
       (progn
       (safe-system (format nil "ar cr ~A ~A ~{~A ~}"
			    output-name o-name ld-flags))
       (safe-system (format nil "ranlib ~A" output-name)))
       #+msvc
       (unwind-protect
         (progn
           (with-open-file (f "static_lib.tmp" :direction :output :if-does-not-exist :create :if-exists :supersede)
             (format f "/DEBUGTYPE:CV /OUT:~A ~A ~{~&\"~A\"~}"
                     output-name o-name ld-flags))
           (safe-system "link -lib @static_lib.tmp"))
         (when (probe-file "static_lib.tmp")
           (cmp-delete-file "static_lib.tmp")))
       )
      #+dlopen
      ((:shared-library :dll)
       (when (or (symbolp output-name) (stringp output-name))
	 (setf output-name (compile-file-pathname output-name :type :dll)))
       (unless init-name
	 ;; Remove the leading "lib"
	 (setf init-name (subseq (pathname-name output-name)
				 (length +static-library-prefix+)))
	 (setf init-name (init-function-name init-name nil)))
       (format c-file +lisp-program-init+ init-name prologue-code
	       shared-data-file submodules epilogue-code)
       (close c-file)
       (compiler-cc c-name o-name)
       (apply #'shared-cc output-name o-name ld-flags))
      #+dlopen
      (:fasl
       (when (or (symbolp output-name) (stringp output-name))
	 (setf output-name (compile-file-pathname output-name :type :fasl)))
       (unless init-name
	 (setf init-name (init-function-name "CODE" nil)))
       #-(or :win32 :mingw32 :darwin)
       (setf submodules
	     (mapcar #'(lambda (sm)
			 (format nil "((ecl_init_function_t) ecl_library_symbol(Cblock, \"~A\", 0))" sm))
		     submodules))
       (format c-file +lisp-program-init+ init-name prologue-code shared-data-file
	       submodules epilogue-code)
       (close c-file)
       (compiler-cc c-name o-name)
       (apply #'bundle-cc output-name o-name ld-flags)))
    (cmp-delete-file tmp-name)
    (cmp-delete-file c-name)
    (cmp-delete-file o-name)
    output-name))
);END OF ECL PATCH

#+ecl
(defun build-and-dump (dump load system restart init quit)
  (setf *compile-verbose* *verbose*
        c::*suppress-compiler-warnings* (not *verbose*)
        c::*suppress-compiler-notes* (not *verbose*))
  (let* ((library-type :library) ; :library :shared-library
         (program-type :program) ; :program :fasl
         (cl-launch-objects
	  (let ((*features* (remove :cl-launch *features*))
                (header (or *compile-file-pathname* *load-pathname* (getenv "CL_LAUNCH_HEADER"))))
	    (list
	     (compile-and-load-file header :verbose *verbose* :load nil :system-p t))))
	 (file-objects
	  (when load
	    (list
             (labels ((x (file)
                        (compile-and-load-file file :verbose *verbose* :system-p t :load t))
                      (xwt (s)
                        (error "dumping image from a stream is unsupported")
                        ;; should be dumping the stream to a temporary file then compiling
                        ))
               (cond
                 ((eq load t) (xwt *standard-input*))
                 ((streamp load) (xwt load))
                 ((eq load :self) (x *cl-launch-file*))
                 (t (x load)))))))
	 (system-objects
	  (when system
	    (let* ((target (find-system system))
                   (build (make-instance 'asdf:build-op :type library-type))
                   (sysdep ()))
              (loop for (op . component) in (asdf::traverse build target)
                    when (typep component 'asdf:system)
                    do (pushnew component sysdep)
                    finally (setf sysdep (nreverse sysdep)))
              (loop for system in sysdep
                    nconc (asdf:output-files build system)
                    do (asdf:oos 'asdf:compile-op system)
                    do (asdf:oos 'asdf:build-op system :type library-type)))))
         (executable (getenv "CL_LAUNCH_EXECUTABLE"))
	 (init-code
	  `(setf
	    *load-verbose* nil
            *dumped* ,(if executable :executable t)
            ,@(when executable
                '(*arguments* (command-line-arguments)))
	    ,@(when restart
		    `(*restart* ,(read-function restart)))
	    ,@(when init
		    `(*init-forms* ,init))
	    ,@(unless quit
		      `(*quit* nil))))
         (epilogue-code
          (ecase program-type
            (:fasl init-code)
            (:program `(progn ,init-code (resume)))))
	 (fasl
	  (builder program-type (parse-namestring dump)
                   :lisp-files
                   (append cl-launch-objects file-objects system-objects)
                   :epilogue-code epilogue-code)))
  (quit)))

;;;; Find a unique directory name for current implementation for the fasl cache
;;; (modified from SLIME's swank-loader.lisp)

(defparameter *implementation-features*
  '(:allegro :lispworks :sbcl :openmcl :cmu :clisp :ccl :corman :cormanlisp
    :armedbear :gcl :ecl :scl))

(defparameter *os-features*
  '(:macosx :linux :windows :mswindows :win32
    :solaris :darwin :sunos :hpux :unix))

(defparameter *architecture-features*
  '(:powerpc :ppc
    :x86-64 :amd64 :x86 :i686 :i586 :i486 :pc386 :iapx386
    :sparc64 :sparc :hppa64 :hppa))

(defun lisp-version-string ()
  #+cmu       (substitute-if #\_ (lambda (x) (find x " /"))
                             (lisp-implementation-version))
  #+scl       (lisp-implementation-version)
  #+sbcl      (lisp-implementation-version)
  #+ecl       (lisp-implementation-version)
  #+openmcl   (format nil "~d.~d.fasl~d"
                      ccl::*openmcl-major-version*
                      ccl::*openmcl-minor-version*
                      (logand ccl::fasl-version #xFF))
  #+lispworks (lisp-implementation-version)
  #+allegro   (format nil
                      "~A~A~A"
                      excl::*common-lisp-version-number*
                      (if (eq 'h 'H) "A" "M")     ; ANSI vs MoDeRn
                      (if (member :64bit *features*) "-64bit" ""))
  #+clisp     (let ((s (lisp-implementation-version)))
                (subseq s 0 (position #\space s)))
  #+armedbear (lisp-implementation-version)
  #+cormanlisp (lisp-implementation-version)
  #+gcl       (let ((s (lisp-implementation-version))) (subseq s 4)))

(defun ensure-directory-name (dn)
   (if (eql #\/ (char dn (1- (length dn)))) dn
      (concatenate 'string dn "/")))

(defun dirname->pathname (dn)
  (parse-namestring (ensure-directory-name dn)))

(defun unique-directory-name (&optional warn)
  "Return a name that can be used as a directory name that is
unique to a Lisp implementation, Lisp implementation version,
operating system, and hardware architecture."
  (flet ((first-of (features)
           (find-if #'(lambda (f) (find f *features*)) features))
         (maybe-warn (value fstring &rest args)
           (cond (value)
                 (t (when warn (apply #'warn fstring args))
                    "unknown"))))
    (let ((lisp (maybe-warn (first-of *implementation-features*)
                            "No implementation feature found in ~a."
                            *implementation-features*))
          (os   (maybe-warn (first-of *os-features*)
                            "No os feature found in ~a." *os-features*))
          (arch	(maybe-warn (first-of *architecture-features*)
                            "No architecture feature found in ~a."
                            *architecture-features*))
          (version (maybe-warn (lisp-version-string)
                               "Don't know how to get Lisp ~
                                implementation version.")))
      (format nil "~(~@{~a~^-~}~)" lisp version os arch))))

(defvar *implementation-name* (unique-directory-name *verbose*)
  "The name of the implementation, used to make a directory hierarchy for fasl files")

;;;; Redefine the ASDF output-files method to put fasl's under the fasl cache.
;;; (taken from common-lisp-controller's post-sysdef-install.lisp)

;;#-common-lisp-controller (progn ; BEGIN of progn to disable caching when clc is detected

(defparameter *wild-path*
   (make-pathname :directory '(:relative :wild-inferiors)
		  :name :wild :type :wild :version nil))

(defun wilden (path)
   (merge-pathnames *wild-path* path))

#-asdf
(defun resolve-symlinks (x)
  #+allegro (excl:pathname-resolve-symbolic-links x)
  #+gcl-pre2.7 (truename (merge-pathnames x *default-pathname-defaults*))
  #-(or allegro gcl-pre2.7)
  (truename x))

(defvar *output-pathname-translations* nil
  "a list of pathname translations, where every translation is a list
of a source pathname and destination pathname.")

(defun exclude-from-cache (&rest dirs)
  (dolist (dir dirs)
    (when dir
      (let* ((p (if (pathnamep dir) dir (dirname->pathname dir)))
             (n #+asdf (resolve-symlinks p) #-asdf p)
             (w (wilden n)))
        (pushnew (list w w)
                 cl-launch::*output-pathname-translations*
                 :test #'equal)))))

(defun calculate-output-pathname-translations ()
  (setf *output-pathname-translations*
        `(#+(and common-lisp-controller (not gcl))
          ,@(progn
              #-gcl-pre2.7 (ensure-directories-exist (calculate-fasl-root))
              (let* ((sr (resolve-symlinks *source-root*))
                     (fr (resolve-symlinks *fasl-root*))
                     (sp (wilden sr))
                     (fp (wilden fr)))
                `((,sp ,fp)
                  (,fp ,fp)
                  ,@(when *redirect-fasl-files-to-cache*
                      `((,(wilden "/")
                          ,(wilden (merge-pathnames
                                    (make-pathname :directory '(:relative "local")) fr))))))))
          #-(and common-lisp-controller (not gcl))
          ,@(when (and *lisp-fasl-root* (not (eq *lisp-fasl-root* :disabled)))
              `((,(wilden "/") ,(wilden *lisp-fasl-root*))))))

  ;; Do not recompile in private cache system-installed sources
  ;; that already have their accompanying precompiled fasls.
  #+(or clisp sbcl cmucl gcl) ; no need for ECL: no source/fasl couples there.
  (exclude-from-cache
   #p"/usr/lib/"
   #+clisp ext:*lib-directory*
   #+gcl system::*lib-directory*
   #+ecl c::*ecl-library-directory*
   #+sbcl (getenv "SBCL_HOME")
   #+cmu (truename #p"library:")))


(defun apply-pathname-translations
  (path &optional (translations *output-pathname-translations*))
#+gcl-pre2.7 path ;;; gcl 2.6 lacks pathname-match-p, anyway
#-gcl-pre2.7
  (loop
    for (source destination) in translations
    when (pathname-match-p path source)
    do (return (translate-pathname path source destination))
    finally (return path)))

#+asdf
(handler-bind ((warning #'muffle-warning))
  (defmethod asdf:output-files :around ((op asdf:operation) (c asdf:component))
    "Method to rewrite output files to fasl-path"
    (let ((orig (call-next-method)))
       (mapcar #'apply-pathname-translations orig))))

;; We provide cl-launch, no need to go looking for it further!
#+asdf
(unless (find-system :cl-launch nil)
  (asdf:defsystem :cl-launch
      #+gcl :pathname #+gcl "/dev/null"
      :depends-on () :serial t :components ()))

;);;END of progn to disable caching when clc is detected

#|
#+common-lisp-controller
(defun beneath-clc-source-root? (pn)
  "Returns T if pn's directory below *source-root*"
  (when pn
    (let ((root-dir (pathname-directory (resolve-symlinks *source-root*)))
          (comp-dir (pathname-directory pn)))
      (and (>= (length comp-dir)
               (length root-dir))
           (equalp root-dir (subseq comp-dir 0 (length root-dir)))))))
|#

(defun apply-output-pathname-translations (path)
#|  #+common-lisp-controller
  (progn
    (if (beneath-clc-source-root? path)
      (source-root-path-to-fasl-path path)
      (alternative-root-path-to-fasl-path path)))
  #-common-lisp-controller |#
  (apply-pathname-translations path))

#+asdf
(defun load-system (system &key verbose)
  (asdf:oos 'asdf:load-op system :verbose verbose))

#+asdf
(defun load-systems (&rest systems)
  (dolist (s systems) (load-system s :verbose *verbose*)))

(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-file-pathname* (source &rest args)
  #-(or gcl ecl)
  (apply-output-pathname-translations
   (apply #'compile-file-pathname source args))
  #+(or gcl ecl) ;; ECL BUG: compile-file-pathname doesn't accept system-p
  (let* ((system-p (getf args :system-p))
         (args (loop for (x y . z) on args by #'cddr nconc
                     (unless (eq x :system-p)
                       (list x y))))
         (path (apply-output-pathname-translations
                (apply #'compile-file-pathname source args))))
    (if system-p
        (make-pathname :type "o" :defaults path)
        path)))

#-(or cormanlisp)
(defun compile-and-load-file (source &key force-recompile verbose (load t)
                                     #+(or ecl gcl) system-p)
  "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"
  (let* ((truesource (truename source))
         (fasl
          (compile-file-pathname* truesource
                                  #+(or ecl gcl) :system-p #+(or ecl gcl) system-p))
         (compiled-p
          (when (or force-recompile
                    (not (probe-file fasl))
                    (not (file-newer-p fasl source)))
            ;; When in doubt, don't trust and recompile, even though there are 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.
            #-gcl-pre2.7 (ensure-directories-exist fasl)
            (multiple-value-bind (path warnings failures)
                (compile-file truesource
                              :output-file fasl
                              #+ecl :system-p #+ecl system-p
                              #-gcl-pre2.7 :print #-gcl-pre2.7 verbose
                              #-gcl-pre2.7 :verbose #-gcl-pre2.7 verbose)
              (declare (ignore warnings))
              (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 #-(and ecl (not dlopen)) fasl
            #+(and ecl (not dlopen)) (if system-p source fasl)
            :verbose verbose))
    (values fasl compiled-p)))

#+(or cormanlisp)
(defun compile-and-load-file (source &key force-recompile verbose load)
  "Corman Lisp has trouble with compiled files (says SLIME)."
  (declare (ignore force-recompile))
  (when load
    (load source :verbose verbose))
  (force-output)
  (values nil t))

(defun load-file (source)
  #-(or gcl-pre2.7 (and ecl (not dlopen)))
  (compile-and-load-file source :verbose *verbose*)
  #+gcl-pre2.7
  (let* ((pn (parse-namestring source))) ; when compiling, gcl 2.6 will always
    (if (pathname-type pn) ; add a type .lsp if type is missing, so avoid compilation
      (compile-and-load-file source :verbose *verbose*)
      (load source :verbose *verbose*)))
  #+(and ecl (not dlopen))
  (load source :verbose *verbose*)))
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
