--- a/codesys-ide/codesys
+++ b/codesys-ide/codesys
@@ -4,8 +4,8 @@
 
 if [ -d /usr/local/share/codesys ]; then
     BASEPATH=/usr/local/share/codesys
-else    
-    BASEPATH=$(pwd)/scripts
+else
+    BASEPATH=$(dirname ${0})/scripts
 fi
 
 # get first CODESYS profile and start the script with it
@@ -84,16 +84,18 @@
 	exit -1
     fi
     
-    export DISPLAY=:91
-    Xvfb :91 &> /dev/zero &
-    sleep 1
     export WINEPREFIX=~/.wine.cds
     ${WINE} ~/.wine.cds/drive_c/CODESYS/CODESYS/Common/CODESYS.exe --culture=en --profile="'"${profile}"'" --runscript="z:${BASEPATH}/noop.py" --noUI 2> /dev/zero
     # remove output log
     [ -f .codesys.output.txt ] && rm -f .codesys.output.txt
     # check if script runs with or without UI
     if grep '# CODESYS with UI' "${BASEPATH}/${1}.py" 2>&1 > /dev/zero; then
+	export DISPLAY=:91
+	Xvfb :91 &> /dev/zero &
+	sleep 1
 	${WINE} ~/.wine.cds/drive_c/CODESYS/CODESYS/Common/CODESYS.exe --culture=en --profile="'"${profile}"'" --runscript="z:${BASEPATH}/${1}.py" 2> /dev/zero
+	killall Xvfb
+	rm -rf /tmp/.X91*
     else
 	${WINE} ~/.wine.cds/drive_c/CODESYS/CODESYS/Common/CODESYS.exe --culture=en --profile="'"${profile}"'" --runscript="z:${BASEPATH}/${1}.py" --noUI 2> /dev/zero
     fi
@@ -102,8 +104,6 @@
     # flush output log
     [ -f .codesys.output.txt ] && cat .codesys.output.txt
      sleep 1
-    killall Xvfb
-    rm -rf /tmp/.X91*
     
     if [ "${result}" == "0" ]; then
 	true