#!/bin/sh
#| cl-launch.sh -- shell wrapper generator for Common Lisp software.
CL_LAUNCH_VERSION='1.91'
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.sh --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="clisp cmucl sbcl ecl openmcl gclcvs gcl allegro"
DEFAULT_INCLUDE_PATH=/usr/share/common-lisp/source/cl-launch
DEFAULT_USE_CL_LAUNCHRC="t"

### Initialize user configuration 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 \
	EXTRA_CONFIG_VARIABLES \
	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
 -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 FROM 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

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
 -r FUNC	--restart        run FUNC when restarting from dump
 -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 and restart it (option --dump)
* 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'.

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, which will optionally invoke the function
specified with function --restart, if specified. See section DUMPING IMAGES.

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.
You don't have to worry about packages and other nasty read-time issues.
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 system execution happen depend on how
cl-launch is invoked. Any side effect from compiling the system as specified by
options --file and --system will only happen the first time that the
application is compiled with given implementation; changes are automatically
detected and a recompilation happens at every execution unless an image is
dumped, in which case the Lisp world is frozen in the state of its initial
compilation. Side effects from loading the compiled files happen every time
the application is invoked, unless an image is dumped. Side effects from the
restart function only happen if an image was dumped, at every execution.
Finally, side effects from fully evaluating the --init forms happen at every
execution.


Code will be generated into a specified output file (option --output).
The output file itself will be created atomically from complete generated
contents and may thus have the same pathname as the input file.
If '-' (without quotes) is specified, then the standard output is used.
If '!' (without quotes) is specified, then option --execute is assumed.
When the generated software is executed on the spot (option --execute),
command-line arguments may be given to software being executed by putting
them after special marker '--', that ends option processing.

When no output file is specified, immediate execution is assumed
as with option --execute. 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 27KiB.

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::*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 c-l-c cache will take
precedence when detected (tested with common-lisp-controller 4.12 to 4.16).
Hopefully, upstream versions of cl-launch and common-lisp-controller
will synchronize to prevent or quickly fix any possible breakage.

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.


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 only try 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

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.

The following releases have been tested, and are supported as follows:
  SBCL 0.9.17 (fully supported)
  CMUCL 19c (fully supported)
  CLISP 2.38 (fully supported) (2.35 known to break)
  OpenMCL 1.1-pre (fully supported) (1.0 known to break)
  Allegro 5 (fully supported) (latter versions completely untested)
  ECL 0.9i (can't dump image of a system)
  GCL 2.7.0-61 ansi mode (can't dump image at all) (earlier versions break)
  GCL 2.6.7-22 ansi mode (can't use systems or dump image).

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
'

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. So be sure to send me what will fit 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.


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
clisp, sbcl, cmucl, allegro and openmcl; ecl supports it with the big
restriction that system dependencies do not currently work; gcl is not
supported yet.

A function may be specified as with option --restart FUNCTION. The function
will be run first thing when restoring the image. It must be a symbol that
will be read after the --file and --system options will have been processed.
This option is only currently supported with clisp, cmucl and sbcl.


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 an optional argument to be used as C exit code.
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_ARGV0
will be set to the process ID and the script invocation filename respectively.


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/header.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_header > ~/src/cl-launch/header.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")


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
	./cl-launch.sh -l 'sbcl cmucl clisp gclcvs' -B tests

Share and Enjoy!
EOF
}

show_help () {
  help_output
  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
        ;;
      -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 ;;
      *=*) # 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 \
	$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
DISCLAIMER= AUTHOR_NOTE= SHORT_LICENSE= LICENSE_COMMENT=
}
include_lisp_header () {
  if [ -z "$INCLUDE_PATH" ] ; then
    print_lisp_header
  else
    load_form "$INCLUDE_PATH/header.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)"
  CL_LAUNCH_ARGV0="$LISP_CONTENT"
  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$IMAGE_ARG" = "xNOT_SUPPORTED_YET" ] ; then
    abort 13 "Image dumping not supported yet with implementation $IMPL.
Try specifying a supported implementation with option --lisp (or \$LISP)"
  fi
  execute_code "$@"
}
do_dump_image () {
  : do_dump_image "$@"
  run_code () {
    do_run_code "$@"
  }
  license_information
  ( do_exec_lisp )
  case "$UPDATE" in
    -) ECHO "$SOFTWARE_CODE" | use_dumped_image "$@" ;;
    *) use_dumped_image "$@" ;;
  esac
}
use_dumped_image () {
  : ddi1 $OUTPUT_FILE
  case "${OUTPUT_FILE}" in
    !) invoke_image "$@" ;;
    *) make_image_invoker ;;
  esac
}
make_image_invoker () {
  WRAPPER_CODE="$ORIG_WRAPPER_CODE"
  compute_image_path
  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 IMAGE_BASE IMAGE_DIR IMAGE"
 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
 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 -o \( $remain = 2 -a "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 \
	"$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 \
	'(asdf:defsystem :clt-asd :components ((:file "clt-sys")))'
  t_create clt-sys.lisp \
	"$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_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 sh $CLOUT
}
t_end_exec () {
  t_args "--execute -- ..."
  t_check t_make "$@" --execute --
}
t_make () {
  XDO $PROG "$@"
}
t_check () {
  echo "cl-launch $ARGS"
  "$@" won | tee clt-out.log >&2
  : RESULTS: "$(cat clt-out.log)"
  if [ -n "$TORIG" -a -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-out.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 $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
}
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
    # gcl wants a suffix for the file it compiles - handled on the lisp side.
    # So does clisp unless you set the custom variables as in header.lisp
    #case $LISP in gcl*) CLOUT=clt-out.sh ;; *) CLOUT=clt-out-sh ;; esac
  for TD in "" "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") ;;
    "dump ":*:gcl*) ;;
    "dump : system":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
  TEUDIFSI="$TO $TUDIFSI"
  do_test $TEUDIFSI
  done ; done ;; esac ; done ;; esac ; done ; done ; done ; done
}
redo_test () {
  export LISPS="$1" LISP="$1" ; shift
  do_test "$@"
}
do_test () {
  if [ $num -ge $MIN -a $num -le $MAX ] ; then
    TCURR="$*"
    if [ -n $num ] ; then
      NUM=$(printf "%02d" $num)
      if [ 0 = $(($num % 4)) ] ; then
        # 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
      fi
    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" -o -z "$OUTPUT_FILE" ] ; then
    ABORT "example usage:
	$PROG -I /usr/share/common-lisp/source/cl-launch \\
	      -l 'sbcl cmucl clisp gcl'
	      -o /usr/bin/cl-launch -B install"
  fi
  install_path
  install_bin
}
print_cl_launch_asd () {
  cat<<END
;;; -*- Lisp -*-
(in-package :cl)
(asdf:defsystem :cl-launch
  :components ((:file "header")))
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 "header.lisp" print_lisp_header &&
  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/header.lisp" print_lisp_header &&
  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
}
print_shell_wrapper_body () {
  cat <<'EOF'
  # Because there must be only one form, we use #. to ensure
  # that the package exists before we attempt to read anything in it.
  # clisp insists on printing every provided form. We avoid this undesired
  # output by ensuring that there is only one form, that quits before clisp
  # prints anything.
  # Note that clisp *does* require the HASH_BANG_FORM.

DO_LISP=do_exec_lisp
IMAGE=
IMAGE_OPT=
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
  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
  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
  EXEC_LISP=exec_lisp
  BIN_ARG=CLISP
  OPTIONS_ARG=CLISP_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
}
implementation_clisp_noarg () {
  implementation_clisp
  EXEC_LISP=exec_lisp_noarg
  # 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 #exec_lisp_noarg
  BIN_ARG=OPENMCL
  OPTIONS_ARG=OPENMCL_OPTIONS
}
implementation_gcl () {
  implementation "${GCL:-gcl}" || return 1
  OPTIONS="${GCL_OPTIONS:- -batch}"
  EVAL=-eval
  ENDARGS=--
  IMAGE_ARG=NOT_SUPPORTED_YET
  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"
  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" -a "/usr/bin/ecl" = "$LISP_BIN" \
       -a -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 "$@"
}
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})"
  exec $LISP_BIN $IMAGE_OPT $IMAGE $OPTIONS $EVAL "$LAUNCH_FORM" $ENDARGS "$@"
}
launch_self () {
  LAUNCH_FORMS="$(load_form "$PROG")"
  try_all_lisps "$@"
}
invoke_image () {
  IMAGE_OPT="$IMAGE_ARG"
  IMAGE="$DUMP"
  PACKAGE_FORM=
  HASH_BANG_FORM=
  LAUNCH_FORMS="(cl-launch::resume)"
  "$EXEC_LISP" "$@"
}

export CL_LAUNCH_PID=$$
export CL_LAUNCH_ARGV0="$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)
'
print_lisp_header () {
  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 file. 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.
|# #-cl-launch
(eval-when (:load-toplevel :execute :compile-toplevel)
  (declaim (optimize (speed 1) (safety 2) (compilation-speed 3)
       	   #+sbcl (sb-ext:inhibit-warnings 3)
	   #+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)

  ;;;; 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))

#-cl-launch
(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)))))

#-cl-launch (eval-when (:load-toplevel :execute :compile-toplevel)

  ;;; define getenv and quit in ways that minimize package conflicts
  ;;; (use-package :cl-launch) while in cl-user.
  #+common-lisp-controller
    (progn
      (import 'common-lisp-controller::*source-root*)
      (import 'common-lisp-controller::*fasl-root*)
      (import 'common-lisp-controller::calculate-fasl-root)
      (import 'common-lisp-controller::source-root-path-to-fasl-path)
      (import 'common-lisp-controller::alternative-root-path-to-fasl-path))
  #+(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)
    (defun getenv (x)
      #+sbcl (sb-ext:posix-getenv x)
      #+cmu (cdr (assoc (intern x :keyword) ext:*environment-list*)))
  (defun quit (&optional (code 0))
    #+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)
    #-(or cmu clisp sbcl openmcl gcl allegro ecl)
    (error "Quitting not implemented")))

#-cl-launch (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.
  (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")))
  (unless (and (find-package :asdf) (find-symbol "OUTPUT-FILES" :asdf))
    (when *asdf-path*
      (ignore-errors (load *asdf-path* :verbose nil :print nil)))))

#-cl-launch (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)))

;;#-cl-launch (eval-when (:load-toplevel :execute :compile-toplevel)
;;  (ignore-errors (asdf::oos 'asdf::load-op :cl-launch)))

#-cl-launch (eval-when (:load-toplevel :execute :compile-toplevel)
  ;;; Try to share this with asdf, in case we get asdf to support it one day.
  (import 'asdf::*output-pathname-translations*))

;;;; CL-Launch Initialization code
#-cl-launch (progn ;;;

;;We provide cl-launch, no need to go looking for it further!
#+asdf
(unless (asdf:find-system :cl-launch)
  (asdf:defsystem :cl-launch))


;;#+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))

(defvar *cl-launch-file* (getenv "CL_LAUNCH_ARGV0"))
(defvar *cl-launch-preamble*
  (or #-gcl-pre2.7 (or *compile-file-pathname* *load-pathname*)
      *cl-launch-file*))

(defvar *arguments* nil
  "command-line parameters")

(defvar *verbose* nil)

(defun compute-arguments ()
  (when (getenv "CL_LAUNCH_VERBOSE") (setf *verbose* t))
  (setf *arguments*
   (or *arguments*
       #+(or gcl ecl) ; (or cmu gcl ecl)
         (cdr (member "--"
		      #+gcl si:*command-args*
                      #+ecl (loop for i from 1 below (si:argc) collect (si:argv i))
		      #+cmu extensions:*command-line-strings*
		      :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*))
    #+(or gcl openmcl allegro)
      (do ((eof '#:eof) (x t (read s nil eof))) ((eq x eof)) (eval x))
    #-(or gcl openmcl 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 %quit (&optional (code 0))
  (finish-outputs) ;;; essential, for openmcl, and for standard compliance.
  (quit code))

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

(defvar *restart* nil)
(defvar *init-forms* nil)
(defvar *quit* t)

(defun resume ()
  (compute-arguments)
  (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 *arguments* nil)
  #+clisp
  (ext:saveinitmem filename
   #|:init-function #'resume|#
   #|:executable executable|#
   :start-package package
   :keep-global-handlers nil
   :norc t)
  #+sbcl
  (progn
   (setf sb-ext::*gc-run-time* 0)
   (sb-ext:save-lisp-and-die filename #|:executable executable :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))
  #-(or clisp sbcl cmu openmcl allegro)
  (%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*)
  (when restart
    (setf restart `(function ,(read-from-string restart))))
  (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 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 restart))
        *init-forms* init
        *quit* quit))

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

#-ecl
(defun build-and-dump (dump load system restart init quit)
  (build-and-load load system restart init quit)
  (dump-image dump)
  (%quit))

#+ecl
(defun build-and-dump (dump load system restart init quit)
  (setf *compile-verbose* nil
        c::*suppress-compiler-warnings* t
        c::*suppress-compiler-notes* t)
  (let* ((cl-launch-objects
	  (let ((*features* (remove :cl-launch *features*)))
	    (list
	     (compile-and-load-file *cl-launch-preamble* :verbose nil :load nil :system-p t))))
	 (file-objects
	  (when load
	    (list
             (labels ((x (file)
                        (compile-and-load-file file :verbose nil :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 (asdf:find-system system))
                   (build (make-instance 'asdf:build-op :type :library))
                   (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)))))
	 (init-code
	  `(setf
	    *load-verbose* nil
	    ,@(when restart
		    `(*restart* ,restart))
	    ,@(when init
		    `(*init-forms* ,init))
	    ,@(unless quit
		      `(*quit* nil))))
	 (fasl
	  (c::build-fasl dump
			 :lisp-files
			 (append cl-launch-objects file-objects system-objects)
			 :epilogue-code init-code)))
  (unless (equal (parse-namestring dump) fasl)
    (rename-file fasl dump))
  (%quit)))

;;;; Interfaces for the fasl cache

(defun dirname->pathname (dn)
  (parse-namestring
   (if (eql #\/ (char dn (1- (length dn)))) dn
      (concatenate 'string dn "/"))))

(defvar *fasl-cache*
  (let ((cache-env (getenv "LISP_FASL_CACHE")))
    (cond
     ((null cache-env)
     (merge-pathnames (make-pathname :directory
                                     (list :relative ".cache" "lisp-fasl"))
                      (user-homedir-pathname)))
     ((equal cache-env "NIL") nil)
     (t (parse-namestring cache-env))))
  "lisp fasl cache hierarchy")

;;;; 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"
                      ccl::*openmcl-major-version*
                      ccl::*openmcl-minor-version*)
  #+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 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

(defvar *fasl-root*
  (or
   (when (getenv "LISP")
     (let ((r (getenv "LISP_FASL_ROOT")))
       (when r (if (equal r "NIL") :disabled (dirname->pathname r)))))
   (when *fasl-cache*
    (merge-pathnames (make-pathname
		      :directory (list :relative *implementation-name*))
                     *fasl-cache*)))
  "top path for the fasl cache for current implementation")

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

(defvar *output-pathname-translations*
   `(#+common-lisp-controller
     ,@(progn
         (calculate-fasl-root)
         (let ((sp (wilden (asdf::resolve-symlinks *source-root*)))
	       (fp (wilden (asdf::resolve-symlinks *fasl-root*))))
           `((,sp ,fp)
             (,fp ,fp)
             (,(wilden "/")
              ,(wilden (merge-pathnames
                        (make-pathname :directory '(:relative "local")) fp))))))
     ,@(when (and *fasl-root* (not (eq *fasl-root* :disabled)))
	 `((,(wilden "/") ,(wilden *fasl-root*)))))
  "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)
    (let* ((p (if (pathnamep dir) dir (dirname->pathname dir)))
           (n (truename p))
           (w (wilden n)))
      (pushnew (list w w)
	       cl-launch::*output-pathname-translations*
	       :test #'equal))))

#+(or clisp sbcl cmucl gcl) ; no need for ECL: no source/fasl couples there.
(exclude-from-cache
 #+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))))
)

(defun apply-output-pathname-translations (path)
  #+common-lisp-controller
  (progn
    (calculate-fasl-root)
    (let ((root-dir (pathname-directory (asdf::resolve-symlinks *source-root*)))
          (src-dir (pathname-directory path)))
      (if (and (>= (length src-dir) (length root-dir))
               (equalp root-dir (subseq src-dir 0 (length root-dir))))
        (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 (and (equal fasl path)
                           (not failures))
                (error "failed to compile ~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 (and ecl (not dlopen)))
  (compile-and-load-file source :verbose *verbose*)
  #+gcl
  (let* ((pn (parse-namestring source)))
    (if (pathname-type pn) ; gcl will always 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*))

(pushnew :cl-launch *features*)

#+ecl (require 'cmp)
;#+ecl (trace c::builder load)
;#+gcl-pre2.7 (trace compile-file compiler::compile-file1)
;#+clisp (trace compile-and-load-file compile-file)
;#+clisp (trace file-newer-p compile-file load)

;;;;; Return to the default package.
(in-package :cl-user))

;;; 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
