#!/bin/bash

clear

# write date in the format 2023.05.09
date -I | tr "-" . > /tmp/date.txt

c_compile() {

START=$(date +%s)

sdcc --peep-file Source/Z80/Code/Game/GameLogic/c-optim.def -mz80 --no-std-crt0 --disable-warning 59 --disable-warning 85 --disable-warning 110 --disable-warning 230 --disable-warning 283 --vc ./Source/Z80/Code/Game/GameLogic/c/$1.c -I ./Source/Z80/Code/Game/GameLogic/_Config -I ./Source/Z80/Code/Game/GameLogic/_AnimSequences -c --opt-code-speed --reserve-regs-iy --max-allocs-per-node 2000000

mv $1.asm Source/Z80/.$1.asm

if [[ $? -ne 0 ]] ; then
    echo "Error while compiling with SDCC !!!"
    exit 1
fi
rm ./$1.lst
rm ./$1.rel
rm ./$1.sym

./Tools/sdcc2rasm_src/sdcc2rasm . Source/Z80/.$1.asm ./Source/Z80/Code/Game/GameLogic/asm/_$1.asm

#rm Source/Z80/.$1.asm


END=$(date +%s)
DIFF=$(( $END - $START ))
echo "It took $DIFF seconds to compile $1.c"
}

do_c_compile=false
for FILE in `find ./Source/Z80/Code/Game/GameLogic/c/*.c`
do
    if [ $FILE -nt Source/Z80/.GameLogic.asm ] ; then
    	echo "Need compile for" $FILE
    	do_c_compile=true
    fi
done
for FILE in `find ./Source/Z80/Code/Game/GameLogic/c/*.h`
do
    if [ $FILE -nt Source/Z80/.GameLogic.asm ] ; then
    	echo "Need compile for" $FILE
    	do_c_compile=true
    fi
done
for FILE in `find ./Source/Z80/Code/Game/GameLogic/_AnimSequences/*.h`
do
    if [ $FILE -nt Source/Z80/.GameLogic.asm ] ; then
    	echo "Need compile for" $FILE
    	do_c_compile=true
    fi
done

for FILE in `find ./Source/Z80/Code/Game/GameLogic/_Config/*.h`
do
    if [ $FILE -nt Source/Z80/.GameLogic.asm ] ; then
    	echo "Need compile for" $FILE
    	do_c_compile=true
    fi
done

if [ "$do_c_compile" = true ] ; then
	echo "C file(s) updated, compiling with SDCC..."
	c_compile GameLogic
fi

./Tools/rasm/rasm.exe -ISource/Z80 Source/Z80/Code/CPR.asm -o game -mml -er -sz -cprquiet -w -wc
if [[ $? -ne 0 ]] ; then
    exit 1
fi

exit 0
