echo "RetroForth, Release 7"
echo "Forth -> Assembly Conversion"
echo "*** Experimental, Build 4 ***"
echo "=================================="

echo "Preparing source code for conversion"
echo "  Removing comments"
grep -v "(" $1 >/tmp/forth-prefilter
echo "  Locating definitions"
grep ":" /tmp/forth-prefilter >/tmp/forth-words
echo "  Locating startup code"
grep -v ":" /tmp/forth-prefilter >/tmp/forth-init

echo "Threading definitions"
sed -f /retro/src/forth/compiler/forth2asm /tmp/forth-words >/tmp/forth-code

echo "Threading startup code"
sed -f /retro/src/forth/compiler/forth2asm /tmp/forth-init >/tmp/forth-init2


echo "Generating assembly code"

echo "  Linux startup"
cat >$1.asm <<start.1
%include "/retro/src/forth/macros"
SECTION .text
	global _start
_start:
	mov TOS, 07dh              ;sys mprotect (pinched from IsForth :-)
	mov ebx, 08048000h
	mov C, 00100000h
	mov edx, 7
	int 080h                   ;make the entire program space rwx
start.1

cat /tmp/forth-init2 >>$1.asm

echo "  Linux termination"
cat >>$1.asm <<end.1
	lea PSP, [esp-0x200]	;Initialize data stack
	sub ebx,ebx	;Return exit status 0
	mov TOS,ebx
	inc TOS		;1 = sys_exit
	int 80h
end.1

echo "  Words & Primitives"
echo "; ( User Words )" >>$1.asm
cat /tmp/forth-code >>$1.asm
echo "; ( RetroForth Primitives )" >>$1.asm
cat /retro/src/forth/primitives >>$1.asm

echo "Conversion to assembly is complete"

echo "Cleaning up..."
rm -f /tmp/forth-*
