#!/bin/bash

len=$(expr length $0)
len=$(expr $len - 3 )
dir=$(expr substr $0 1 $len )
dir=$(echo "$dir.")

cd $dir

ficha=$(expr substr $0 1 1)
if ( expr "$ficha" = "/" )
then
	kvt -e ./run
	exit 0
fi

clear

if !(test -f ./makefile.sub) #makefile.sub should only be found in ./source
then
	kdialog --msgbox "\"run\" is stored in a wrong directory" \
		|| xmessage "\"run\" is stored in a wrong directory" \
		|| dialog --msgbox "\"run\" is stored in a wrong directory"

	exit 1
fi

kdialog --msgbox "Please note: This may take some time." \
	|| xmessage "Please note: This may take some time." \
	|| dialog --msgbox "Please note: This may take some time."

clear

echo "TRANSLATING TO C++ CODE"
make -s VK_files || ( kdialog --msgbox "Couldn't translate:\nSee terminal output for details." \
	|| xmessage "Couldn't translate:\nSee terminal output for details." \
	|| dialog --msgbox "Couldn't translate:\nSee terminal output for details."
	echo -e "\t\t\t[ PRESS ENTER TO EXIT ]"
	read
	exit 1 ) || exit 1

echo "COMPILING C++ CODE AND RUNNING THE PROGRAM"
make -s KDE || ( kdialog --msgbox "Couldn't compile:\nSee terminal output for details." \
	|| xmessage "Couldn't compile:\nSee terminal output for details." \
	|| dialog --msgbox "Couldn't compile:\nSee terminal output for details."
	rbltStr=$( echo -e "Sometimes these errors occour, as something hasn't been rebuilt.\nI will run 'make clean' now, to force EVERYTHING to be rebuilt, when you\nstart 'run' next time.\nMay I?" )
	kdialog --yesno "$rbltStr" \
	&& make -s clean && kdialog --msgbox "Cleaned."
	echo -e "\t\t\t[ PRESS ENTER TO EXIT ]"
	read
	exit 1 ) || exit 1

exit 0