#!/bin/csh -f

# This simple script spins Yarn files...

# Feed it .pyy files, and it spits out
#  matched .py files.

set magic="#This file was automatically generated by spin from a .pyy file."

foreach src ($argv:q)

	set dst="$src:r.py"

	if (-e "$dst") then
		set line2=`head -2 "$dst" | tail -1`
		if ("$line2" != "$magic") then
			echo "$dst exists and was not automatically generated.  Skipping\!"
			continue
		endif
	endif

	echo '#\!/usr/bin/python' > "$dst"
	echo "$magic" >> "$dst"

#		-e "s/\([ 	]*\)waitfor[ 	]\([^#]*\)/\1yield (2, Yarn.Yarn(\2))/" \
	sed \
		-e "s/^\([ 	]*\)\([^	 ].*\)[ 	]*=[ 	]*waitfor[ 	]\([^#]*\)/\1SPINTMP=Yarn.Yarn(\3)\\
\1yield (2, SPINTMP)\\
\1if SPINTMP.resumeWhen:\\
\1	raise SPINTMP.resumeWhen\\
\1\2 = SPINTMP.returnTo/" \
		-e "s/^\([ 	]*\)waitfor[ 	]\([^#]*\)/\1SPINTMP=Yarn.Yarn(\2)\\
\1yield (2, SPINTMP)\\
\1if SPINTMP.resumeWhen:\\
\1	raise SPINTMP.resumeWhen/" \
		-e "s/^\([ 	]*\)exit[ 	][	 ]*\([^	 #][^#]*\)/\1yield (0, \2)/" \
		-e "s/^\([ 	]*\)exit[ 	]/\1return/" \
		-e "s/^\([ 	]*\)spawn[ 	]\([^#]*\)[ 	]at[ 	]\([^#]*\)/\1Yarn.spawnAt(\3,\2)/" \
		-e "s/^\([ 	]*\)spawn[ 	]\([^#]*\)/\1Yarn.spawn(\2)/" \
			< "$src" >> "$dst"

	chmod u+x "$dst"
end

