--- a/codesys-ide/codesys
+++ b/codesys-ide/codesys
@@ -84,18 +84,16 @@
 	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
@@ -104,6 +102,8 @@
     # flush output log
     [ -f .codesys.output.txt ] && cat .codesys.output.txt
      sleep 1
+    killall Xvfb
+    rm -rf /tmp/.X91*
     
     if [ "${result}" == "0" ]; then
 	true