file="$1.bat"
test -r "$file" ||
	{ file="$1.BAT"
	test -r "$file" ||
		{ echo "Error: $0 cannot find $1.bat" >&2
		exit 2; }; }
sed '
1i\
_label=::top\
while true\
do case $_label in\
::top)

	s/~/\
/g
	s/\\\\/~/g
	s:\\:/:g
	s/~/\\/g

	:p1
		s/%/~/
		t p2
		b p3
	:p2
		s/~\([0-9]\)/$\1/
		t p1
		s/~\([^~% 	][^% 	]*\)%/${\1}/
		t p1
		s/~%/~/
		b p1
	:p3
		s/~/%/g

	s/^\([ 	]*\)\(.*\)/	\1~\2 /

	s/~for\([ 	][ 	]*\)/~FOR\1/
		s/\(~FOR[^~]*[ 	]\)[([]/\1[ /g
		s/\(~FOR[^~]*\)[ 	]*[])]\([ 	]\)/\1 ]\2/g
		s/~FOR[^~]*[	 ]][ 	][ 	]*[Dd][Oo][ 	][ 	]*/&~/g
	s/~if\([ 	][ 	]*\)/~IF\1/
	/~IF\([ 	][ 	]*\)/{
		s/\([ 	][ 	]*\)if\([ 	][ 	]*\)/\1~IF\2/g
		s/\([ 	][ 	]*\)break\([ 	][ 	]*\)/\1~BREAK\2/g
		s/\([ 	][ 	]*\)echo[ 	][ 	]*off\([ 	][ 	]*\)/\1~ECHO OFF\2/g
		s/\([ 	][ 	]*\)echo[ 	][ 	]*on\([ 	][ 	]*\)/\1~ECHO ON\2/g
		s/\([ 	][ 	]*\)for\([ 	][ 	]*\)/\1~FOR\2/g
		s/\([ 	][ 	]*\)FOR\([ 	][ 	]*\)/\1~FOR\2/g
			s/\(~FOR[^~]*[ 	]\)(/\1[ /g
			s/\(~FOR[^~]*\)[ 	]*)\([ 	]\)/\1 ]\2/g
			s/~FOR[^~]*[	 ]][ 	][ 	]*[Dd][Oo][ 	][ 	]*/&~/g
		s/\([ 	][ 	]*\)goto\([ 	][ 	]*\)/\1~GOTO\2/g
		s/\([ 	][ 	]*\)GOTO\([ 	][ 	]*\)/\1~GOTO\2/g
		s/~GOTO[ 	]*$/~GOTO : /g
		s/~GOTO[ 	]*\(.*\)/_label=:\1\\; else false \&\& continue/
		s/\([ 	][ 	]*\)set\([ 	][ 	]*\)/\1~SET\2/g
		s/\([ 	][ 	]*\)time\([ 	][ 	]*\)/\1~TIME\2/g
		}
	s/~break\([ 	][ 	]*\)/~BREAK\1/g
	s/~echo[ 	][ 	]*off\([ 	][ 	]*\)$/~ECHO OFF\1/g
	s/~echo[ 	][ 	]*on\([ 	][ 	]*\)$/~ECHO ON\1/g
	s/~goto\([ 	][ 	]*\)/~GOTO\1/g
	s/~set\([ 	][ 	]*\)/~SET\1/g
	s/~time\([ 	][ 	]*\)/~TIME\1/g
	s/~GOTO[ 	]*$/~GOTO : /g
	/~GOTO\([ 	][ 	]*\)/{
		s/~GOTO[ 	]*\(.*\)/_label=:\1; continue/
		h
		}
	s/~ECHO ON[ 	]*$/set -x/
	s/~ECHO OFF[ 	]*$/set +x/

	s/~//g
	s/[ 	][ 	]*$//
	s/\n/~/g

	/^[ 	]*:/{s/^[ 	]*\(:.*\)[ 	]*$/	_label=\1; continue;;\
\1)/
		x
		G
		s/^[ 	]*_.*ue;;/	;;/
		s/^\n//
		x
		s/.*//
		x
		}
$a\
	exit;;\
*)	exit;;\
esac\
done
	' <$file  |
	case $0 in
		*batcg)	file=$1; shift
			{ echo set -- "$@"; tee $file; } | $SHELL;;
		*)	cat >$1
			chmod +rx $1;;
		esac
