#!/bin/sh

[ "$1" = --version ] && exec cl12

output_assembly_file=
output_object_file=
output_executable_file=
flags=
set -e
if [ "$ONLY_STAGE" != E ]; then
	output_object_file="`mktemp -t cl.XXXXXXXX.o`"
	trap 'rm -f "$output_object_file"' EXIT
fi
case "$ONLY_STAGE" in
	E)
		flags=-E
		;;
	S)
		flags=-c
		output_assembly_file="`mktemp -t cl.XXXXXXXX.s`"
		trap 'rm -f "$output_assembly_file" "$output_object_file"' EXIT
		#ln -sf /dev/stdout "$output_assembly_file"
		ln -sf /dev/null "$output_object_file"
		;;
	c)
		flags=-c
		#ln -sf /dev/stdout "$output_object_file"
		;;
	"")
		output_executable_file="`mktemp -t cl.XXXXXXXX.exe`"
		trap 'rm -f "$output_object_file" "$output_executable_file"' EXIT
		#ln -sf /dev/stdout "$output_executable_file"
		;;
esac
[ -n "$DEBUG" ] && flags="$flags -Zi"
[ -n "$OPTIMIZATION" ] && flags="$flags -O$OPTIMIZATION"
for d in $DEFINE; do flags="-D $d $flags"; done
for d in $UNDEFINE; do flags="-U $d $flags"; done
[ -z "$VERBOSE" ] && flags="-nologo $flags"
input_file="`mktemp -t cl.XXXXXXXX.c`" || exit
if ! cat > "$input_file"; then
	rm -f "$input_file"
	exit 1
fi
[ -n "$output_assembly_file" ] && flags="$flags -Faz:$output_assembly_file"
[ -n "$output_object_file" ] && flags="$flags -Foz:$output_object_file"
[ -n "$output_executable_file" ] && flags="$flags -Fez:$output_executable_file"
set +e
/usr/local/bin/cl12 -W4 $flags "$@" "-Tc$input_file" 1>&2
r=$?
rm -f "$input_file"
if [ $r = 0 ]; then case "$ONLY_STAGE" in
	S)
		cat "$output_assembly_file"
		;;
	c)
		cat "$output_object_file"
		;;
	"")
		cat "$output_executable_file"
		;;
esac fi
exit $r
