CXXFLAGS=-Wall -Wextra -std=c++11 -g -O2 -fno-omit-frame-pointer -g -rdynamic
# -ferl -fresume
#CXXFLAGS=-Wall -Wextra -std=c++11 -g -O2
#CXXFLAGS=-Wall -Wextra -std=c++11 -g -O1 -pg -finline
#CXXFLAGS=-Wall -Wextra -std=c++11 -g -O1 -fno-omit-frame-pointer -fsanitize=address

# -rdynamic needs to be used if you want useful backtraces from B_Error_Terminate()
# -ferl, -fresume is not necessary for that

all: cpu cpu-qb64 cpu-qb.bas

cpu: cpu.bas
	~/src/qbc/qb cpu.bas $(CXXFLAGS) -o "$@"

cpu-clang: cpu.bas
	CXX=clang++ ~/src/qbc/qb cpu.bas $(CXXFLAGS) -o "$@"

cpu-qb64: cpu.bas
	export p=`pwd`; sh -c "cd ~/qbexample/sfield/qb64;./qb64 -c $$p/cpu.bas || true"
	mv ~/qbexample/sfield/qb64/cpu "$@"
cpu-bas.s: cpu.bas
	~/src/qbc/qb cpu.bas $(CXXFLAGS) -S -o "$@"

cpu-qb.bas: cpu.bas Makefile
	cp "$<" "$@"
	# UINT -> LONG
	sed -i 's/_UNSIGNED INTEGER/LONG/g' "$@"
	# UNSIGNED anything -> signed
	sed -i 's/_UNSIGNED //g' "$@"
	# BYTE -> integer
	sed -i 's/_BYTE/INTEGER/g' "$@"

	# UBYTE -> INTEGER
	sed -i 's/~%%/%/g' "$@"
	# UINT -> LONG
	sed -i 's/~%/\&/g' "$@"
	# ULONG -> LONG
	sed -i 's/~&/\&/g' "$@"
	# BYTE -> INTEGER
	sed -i 's/%%/%/g' "$@"
	
	# Remove BYVAL
	sed -i 's/BYVAL //g' "$@"
	
	sed -i 's/*&H100+/*\&H100\&+/g' "$@"
	
	# Remove the BYTE trick
	sed -i 's/bytetemp = s/bytetemp = (s AND 127) - (s AND 128)/' "$@"
	
	# Adjust some syntax that BC is unable to handle
	perl -pe 's/(SUB|FUNCTION) +([^ (]*) *\(\).*/\1 \2/'  < "$@" > "$@".tmp
	perl -pe 's/DECLARE (SUB|FUNCTION) +([A-Za-z0-9%]+)$$/DECLARE $$1 $$2 ()/'  < "$@".tmp > "$@"
	
	# Fix some type-mismatch issues by manual substitution
	sed -i 's/CPUops(NextOpcode)/(CPUops(NextOpcode))/g' "$@"
	sed -i 's/WB reg.PC  /WB (reg.PC AND 255)/g' "$@"
	
	# Replace some unsupported tokens with harmless ones
	sed -i 's/_SNDRATE/8000/g' "$@"
	sed -i 's/_DONTBLEND//g' "$@"
	sed -i 's/_NEWIMAGE(.*)/13/g' "$@"
	sed -i 's/_SNDRAWLEN/1/g' "$@"
	sed -i 's/_SNDRAW/REM _SNDRAW/g' "$@"
	sed -i 's/_DISPLAY/REM display/g' "$@"

	# Change some settings
	sed -i 's/CONST *GraphicsSupport *= *./CONST GraphicsSupport=5/' "$@"
	sed -i 's/CONST *ScanlineMultiple *= *./CONST ScanlineMultiple=1/' "$@"
	sed -i 's/CONST *ScreenWidth *= *.*/CONST ScreenWidth=320/' "$@"
	sed -i 's/CONST *ScreenHeight *= *.*/CONST ScreenHeight=240/' "$@"
	sed -i 's/CONST *FrameSkip *= *.*/CONST FrameSkip=1/' "$@"
	sed -i 's/CONST *SwapROMfile *= *.*/CONST SwapROMfile=1/' "$@"

	tr -d '\015' < "$@" | sed 's/$$//' > "$@".tmp
	mv -f "$@".tmp "$@"
