--- mythburn_0.24_fixes.git_4.10.2011.py	2011-10-04 15:52:00.000000000 +0200
+++ mythburn_patched backported.py	2011-10-04 16:08:42.000000000 +0200
@@ -1,4 +1,5 @@
 #!/usr/bin/env python
+# -*- coding: utf-8 -*-
 # mythburn.py
 # The ported MythBurn scripts which feature:
 
@@ -31,12 +32,18 @@
 #pyfribidi
 
 #Optional (alternate demuxer)
-#ProjectX - 0.90.4.00
+#ProjectX >= 0.91
 
 #******************************************************************************
 #******************************************************************************
 #******************************************************************************
 
+
+# All strings in this file should be unicode, not byte string!! They get converted to utf-8 only 
+
+
+
+
 # version of script - change after each update
 VERSION="0.1.20101206-1"
 
@@ -239,6 +246,8 @@
 
 def write(text, progress=True):
     """Simple place to channel all text output through"""
+
+    text = text.encode("utf-8", "replace")
     sys.stdout.write(text + "\n")
     sys.stdout.flush()
 
@@ -253,6 +262,7 @@
     """Display an error message and exit app"""
     write("*"*60)
     write("ERROR: " + msg)
+    write("See mythburn.log for more information.")
     write("*"*60)
     write("")
     saveSetting("MythArchiveLastRunResult", "Failed: " + quoteString(msg));
@@ -287,7 +297,7 @@
 # Try to work out how many cpus we have available
 
 def getCPUCount():
-    """return the number of CPU's"""
+    """return the number of CPUs"""
     cpustat = open("/proc/cpuinfo")
     cpudata = cpustat.readlines()
     cpustat.close()
@@ -349,7 +359,7 @@
 
 def getDatabaseConnection():
     """Returns a mySQL connection to mythconverg database."""
-    return MySQLdb.connect(host=mysql_host, user=mysql_user, passwd=mysql_passwd, db=mysql_db, init_command='SET NAMES utf8')
+    return MySQLdb.connect(host=mysql_host, user=mysql_user, passwd=mysql_passwd, db=mysql_db, charset="utf8", use_unicode=True)
 
 #############################################################
 # Returns true/false if a given file or path exists.
@@ -359,12 +369,12 @@
     return os.path.exists( file )
 
 #############################################################
-# Escape quotes in a filename
+# Escape quotes in a command line argument
 
-def quoteFilename(filename):
-    filename = filename.replace('"', '\\"')
-    filename = filename.replace('`', '\\`')
-    return '"%s"' % filename
+def quoteCmdArg(arg):
+    arg = arg.replace('"', '\\"')
+    arg = arg.replace('`', '\\`')
+    return '"%s"' % arg
 
 #############################################################
 # Returns the text contents from a given XML element.
@@ -436,6 +446,19 @@
                 os.remove(os.path.join(root, name))
 
 #############################################################
+# Romoves all the objects from a directory
+
+def deleteEverythingInFolder(folder):
+    for root, dirs, files in os.walk(folder, topdown=False):
+        for name in files:
+                os.remove(os.path.join(root, name))
+        for name in dirs:
+                if os.path.islink(os.path.join(root, name)):
+                    os.remove(os.path.join(root, name))
+                else:
+                    os.rmdir(os.path.join(root, name))
+
+#############################################################
 # Check to see if the user has cancelled the DVD creation process
 
 def checkCancelFlag():
@@ -454,7 +477,14 @@
 def runCommand(command):
     checkCancelFlag()
 
-    result = os.system(command)
+    # mytharchivehelper needes this locale to work correctly
+    try:
+       oldlocale = os.environ["LC_ALL"]
+    except:
+       oldlocale = ""
+    os.putenv("LC_ALL", "en_US.UTF-8")
+    result = os.system(command.encode('utf-8'))
+    os.putenv("LC_ALL", oldlocale)
 
     if os.WIFEXITED(result):
         result = os.WEXITSTATUS(result)
@@ -485,19 +515,19 @@
 
     totalframes=int(musiclength * framespersecond)
 
-    command = path_jpeg2yuv[0] + " -n %s -v0 -I p -f %s -j '%s' | %s -b 5000 -a %s -v 1 -f 8 -o '%s'" \
-              % (totalframes, framespersecond, background, path_mpeg2enc[0], aspectratio, tempvideo)
+    command = quoteCmdArg(path_jpeg2yuv[0]) + " -n %s -v0 -I p -f %s -j %s | %s -b 5000 -a %s -v 1 -f 8 -o %s" \
+              % (totalframes, framespersecond, quoteCmdArg(background), quoteCmdArg(path_mpeg2enc[0]), aspectratio, quoteCmdArg(tempvideo))
     result = runCommand(command)
     if result<>0:
         fatalError("Failed while running jpeg2yuv - %s" % command)
 
-    command = path_mplex[0] + " -f 8 -v 0 -o '%s' '%s' '%s'" % (tempmovie, tempvideo, music)
+    command = quoteCmdArg(path_mplex[0]) + " -f 8 -v 0 -o %s %s %s" % (quoteCmdArg(tempmovie), quoteCmdArg(tempvideo), quoteCmdArg(music))
     result = runCommand(command)
     if result<>0:
         fatalError("Failed while running mplex - %s" % command)
 
     if xmlfile != "":
-        command = path_spumux[0] + " -m dvd -s 0 '%s' < '%s' > '%s'" % (xmlfile, tempmovie, finaloutput)
+        command = quoteCmdArg(path_spumux[0]) + " -m dvd -s 0 %s < %s > %s" % (quoteCmdArg(xmlfile), quoteCmdArg(tempmovie), quoteCmdArg(finaloutput))
         result = runCommand(command)
         if result<>0:
             fatalError("Failed while running spumux - %s" % command)
@@ -1509,7 +1539,7 @@
             top_element.appendChild(node)   
 
             node = infoDOM.createElement("title")
-            node.appendChild(infoDOM.createTextNode(unicode(record[6], "UTF-8")))
+            node.appendChild(infoDOM.createTextNode(record[6]))
             top_element.appendChild(node)
 
             #date time is returned as 2005-12-19 00:15:00            
@@ -1523,11 +1553,13 @@
             top_element.appendChild(node)   
 
             node = infoDOM.createElement("subtitle")
-            node.appendChild(infoDOM.createTextNode(unicode(record[5], "UTF-8")))
+            node.appendChild(infoDOM.createTextNode(record[5]))
+
             top_element.appendChild(node)   
 
             node = infoDOM.createElement("description")
-            node.appendChild(infoDOM.createTextNode(unicode(record[4], "UTF-8")))
+            node.appendChild(infoDOM.createTextNode(record[4]))
+
             top_element.appendChild(node)   
 
             node = infoDOM.createElement("rating")
@@ -1630,7 +1662,7 @@
             top_element.appendChild(node)   
 
             node = infoDOM.createElement("title")
-            node.appendChild(infoDOM.createTextNode(unicode(record[0], "UTF-8")))
+            node.appendChild(infoDOM.createTextNode(record[0]))
             top_element.appendChild(node)   
 
             node = infoDOM.createElement("recordingdate")
@@ -1647,12 +1679,12 @@
             top_element.appendChild(node)   
 
             node = infoDOM.createElement("subtitle")
-            node.appendChild(infoDOM.createTextNode(unicode(record[9], "UTF-8")))
+            node.appendChild(infoDOM.createTextNode(record[9]))
             top_element.appendChild(node)   
 
             node = infoDOM.createElement("description")
             if record[2] != None:
-                desc = unicode(record[2], "UTF-8")
+                desc = record[2]
                 if desc != "None":
                     node.appendChild(infoDOM.createTextNode(desc))
                 else:
@@ -1805,12 +1837,12 @@
 def encodeAudio(format, sourcefile, destinationfile, deletesourceafterencode):
     write( "Encoding audio to "+format)
     if format == "ac3":
-        cmd = path_ffmpeg[0] + " -v 0 -y "
+        cmd = quoteCmdArg(path_ffmpeg[0]) + " -v 0 -y "
 
         if cpuCount > 1:
             cmd += "-threads %d " % cpuCount
 
-        cmd += "-i '%s' -f ac3 -ab 192k -ar 48000 '%s'" % (sourcefile, destinationfile)
+        cmd += "-i %s -f ac3 -ab 192k -ar 48000 %s" % (quoteCmdArg(sourcefile), quoteCmdArg(destinationfile))
         result = runCommand(cmd)
 
         if result != 0:
@@ -1904,13 +1936,13 @@
     # run spumux to add subtitles if they exist
     if os.path.exists(os.path.dirname(destination) + "/stream.d/spumux.xml"):
         write("Checking integrity of subtitle pngs")
-        command = os.path.join(scriptpath, "testsubtitlepngs.sh") + " %s/stream.d/spumux.xml" % (os.path.dirname(destination))
+        command = quoteCmdArg(os.path.join(scriptpath, "testsubtitlepngs.sh")) + " " + quoteCmdArg(os.path.dirname(destination) + "/stream.d/spumux.xml")
         result = runCommand(command)
         if result<>0:
             fatalError("Failed while running testsubtitlepngs.sh - %s" % command)
 
         write("Running spumux to add subtitles")
-        command = path_spumux[0] + " -P %s/stream.d/spumux.xml <%s >%s" % (os.path.dirname(destination), destination, os.path.splitext(destination)[0] + "-sub.mpg")
+        command = quoteCmdArg(path_spumux[0]) + " -P %s <%s >%s" % (quoteCmdArg(os.path.dirname(destination) + "/stream.d/spumux.xml"), quoteCmdArg(destination), quoteCmdArg(os.path.splitext(destination)[0] + "-sub.mpg"))
         result = runCommand(command)
         if result<>0:
             nonfatalError("Failed while running spumux.\n"
@@ -1928,8 +1960,9 @@
 
 def getStreamInformation(filename, xmlFilename, lenMethod):
     """create a stream.xml file for filename"""
-    filename = quoteFilename(filename)
-    command = "mytharchivehelper -i %s %s %d" % (filename, xmlFilename, lenMethod)
+
+    command = "mytharchivehelper -i %s %s %d" % (quoteCmdArg(filename), quoteCmdArg(xmlFilename), lenMethod)
+    write(command)
 
     result = runCommand(command)
 
@@ -1938,7 +1971,7 @@
 
     # print out the streaminfo.xml file to the log
     infoDOM = xml.dom.minidom.parse(xmlFilename)
-    write("streaminfo.xml :-\n" + infoDOM.toprettyxml("    ", ""), False)
+    write(xmlFilename + ":-\n" + infoDOM.toprettyxml("    ", ""), False)
 
 #############################################################
 # Gets the video width and height from a file's stream xml file
@@ -1971,16 +2004,15 @@
     """Use mythtranscode to cut commercials and/or clean up an mpeg2 file"""
 
     if localfile != "":
-        localfile = quoteFilename(localfile)
         if usecutlist == True:
-            command = "mythtranscode --mpeg2 --honorcutlist -i %s -o %s" % (localfile, destination)
+            command = "mythtranscode --mpeg2 --honorcutlist -i %s -o %s" % (quoteCmdArg(localfile), quoteCmdArg(destination))
         else:
-            command = "mythtranscode --mpeg2 -i %s -o %s" % (localfile, destination)
+            command = "mythtranscode --mpeg2 -i %s -o %s" % (quoteCmdArg(localfile), quoteCmdArg(destination))
     else:
         if usecutlist == True:
-            command = "mythtranscode --mpeg2 --honorcutlist -c %s -s %s -o %s" % (chanid, starttime, destination)
+            command = "mythtranscode --mpeg2 --honorcutlist -c %s -s %s -o %s" % (chanid, starttime, quoteCmdArg(destination))
         else:
-            command = "mythtranscode --mpeg2 -c %s -s %s -o %s" % (chanid, starttime, destination)
+            command = "mythtranscode --mpeg2 -c %s -s %s -o %s" % (chanid, starttime, quoteCmdArg(destination))
 
     result = runCommand(command)
 
@@ -2043,24 +2075,13 @@
             write("Failed to generate Project-X cutlist.")
             return False
 
-    pxbasename = os.path.splitext(os.path.basename(file))[0]
-
     if os.path.exists(file) != True:
         write("Error: input file doesn't exist on local filesystem")
         return False
 
-
-    qdestdir = quoteFilename(folder)
-    qpxbasename = quoteFilename(pxbasename)
-    qfile = quoteFilename(file)
-    qcutlist = os.path.join(folder, "cutlist_x.txt")
-
-    command = path_projectx[0] + " -id %s" % getStreamList(folder)
+    command = quoteCmdArg(path_projectx[0]) + " %s -id '%s' -set ExternPanel.appendPidToFileName=1 -out %s -name stream" % (quoteCmdArg(file), getStreamList(folder), quoteCmdArg(folder))
     if usecutlist == True:
-        command += " -cut %s -out %s -name %s %s" % (qcutlist, qdestdir, qpxbasename, qfile)
-    else:
-        command += " -out %s -name %s %s" % (qdestdir, qpxbasename, qfile)
-
+        command += " -cut %s" % quoteCmdArg(os.path.join(folder, "cutlist_x.txt"))
     write(command)
 
     result = runCommand(command)
@@ -2072,7 +2093,63 @@
 
 
     # workout which files we need and rename them
-    renameProjectXFiles(folder, pxbasename)
+    video, audio1, audio2 = selectStreams(folder)
+    if addSubtitles:
+        subtitles = selectSubtitleStream(folder)
+
+    videoID_hex = "0x%x" % video[VIDEO_ID]
+    if audio1[AUDIO_ID] != -1:
+        audio1ID_hex = "0x%x" % audio1[AUDIO_ID]
+    else:
+        audio1ID_hex = ""
+    if audio2[AUDIO_ID] != -1:
+        audio2ID_hex = "0x%x" % audio2[AUDIO_ID]
+    else:
+        audio2ID_hex = ""
+    if addSubtitles and subtitles[SUBTITLE_ID] != -1:
+        subtitlesID_hex = "0x%x" % subtitles[SUBTITLE_ID]
+    else:
+        subtitlesID_hex = ""
+
+
+    files = os.listdir(folder)
+    for file in files:
+        if file[0:9] == "stream{0x": # don't rename files that have already been renamed
+            PID = file[7:13]
+            SubID = file[19:23]
+            if PID == videoID_hex or SubID == videoID_hex:
+                os.rename(os.path.join(folder, file), os.path.join(folder, "stream.mv2"))
+            elif PID == audio1ID_hex or SubID == audio1ID_hex:
+                os.rename(os.path.join(folder, file), os.path.join(folder, "stream0." + file[-3:]))
+            elif PID == audio2ID_hex or SubID == audio2ID_hex:
+                os.rename(os.path.join(folder, file), os.path.join(folder, "stream1." + file[-3:]))
+            elif PID == subtitlesID_hex or SubID == subtitlesID_hex:
+                if file[-3:] == "sup":
+                    os.rename(os.path.join(folder, file), os.path.join(folder, "stream.sup"))
+                else:
+                    os.rename(os.path.join(folder, file), os.path.join(folder, "stream.sup.IFO"))
+
+
+    # Fallback if assignment and renaming by ID failed
+    
+    files = os.listdir(folder)
+    for file in files:
+        if file[0:9] == "stream{0x": # don't rename files that have already been renamed
+            if not os.path.exists(os.path.join(folder, "stream.mv2")) and file[-3:] == "m2v":
+                os.rename(os.path.join(folder, file), os.path.join(folder, "stream.mv2"))
+            elif not (os.path.exists(os.path.join(folder, "stream0.ac3")) or os.path.exists(os.path.join(folder, "stream0.mp2"))) and file[-3:] == "ac3":
+                os.rename(os.path.join(folder, file), os.path.join(folder, "stream0.ac3"))
+            elif not (os.path.exists(os.path.join(folder, "stream0.ac3")) or os.path.exists(os.path.join(folder, "stream0.mp2"))) and file[-3:] == "mp2":
+                os.rename(os.path.join(folder, file), os.path.join(folder, "stream0.mp2"))
+            elif not (os.path.exists(os.path.join(folder, "stream1.ac3")) or os.path.exists(os.path.join(folder, "stream1.mp2"))) and file[-3:] == "ac3":
+                os.rename(os.path.join(folder, file), os.path.join(folder, "stream1.ac3"))
+            elif not (os.path.exists(os.path.join(folder, "stream1.ac3")) or os.path.exists(os.path.join(folder, "stream1.mp2"))) and file[-3:] == "mp2":
+                os.rename(os.path.join(folder, file), os.path.join(folder, "stream1.mp2"))
+            elif not os.path.exists(os.path.join(folder, "stream.sup")) and file[-3:] == "sup":
+                os.rename(os.path.join(folder, file), os.path.join(folder, "stream.sup"))
+            elif not os.path.exists(os.path.join(folder, "stream.sup.IFO")) and file[-3:] == "IFO":
+                os.rename(os.path.join(folder, file), os.path.join(folder, "stream.sup.IFO"))
+
 
     # if we have some dvb subtitles and the user wants to add them to the DVD
     # convert them to pngs and create the spumux xml file
@@ -2081,7 +2158,7 @@
             os.path.exists(os.path.join(folder, "stream.sup.IFO"))):
             write("Found DVB subtitles converting to DVD subtitles")
             command = "mytharchivehelper --sup2dast "
-            command += " %s %s 0" % (os.path.join(folder, "stream.sup"), os.path.join(folder, "stream.sup.IFO"))
+            command += " %s %s 0" % (quoteCmdArg(os.path.join(folder, "stream.sup")), quoteCmdArg(os.path.join(folder, "stream.sup.IFO")))
 
             result = runCommand(command)
 
@@ -2096,127 +2173,6 @@
     return True
 
 #############################################################
-# find the required stream files and rename them
-
-def renameProjectXFiles(folder, pxbasename):
-
-    write("renameProjectXFiles start -----------------------------------------", False)
-    logf = open(os.path.join(folder, pxbasename + "_log.txt"))
-    logdata = logf.readlines()
-    logf.close()
-
-    # find stream PIDs and Files
-    streamIds = []
-    streamFiles = []    
-    for line in logdata:
-         tokens = line.split()
-         if len(tokens) > 0:
-            if tokens[0] == "++>":
-              # From ProjectX/resources/pjxresources_en.properties:
-              if tokens[1] == "Mpg":
-                if tokens[2] == "Video:":
-                  write("found MPEG video stream %s" % tokens[4], False)
-                  streamIds.append(int(tokens[4], 16))
-                if tokens[2] == "Audio:":
-                  write("found MPEG audio stream %s" % tokens[4], False)
-                  streamIds.append(int(tokens[4], 16))
-              if tokens[1] == "AC3/DTS":
-                write("found AC3/DTS audio stream %s" % tokens[4], False)
-                streamIds.append(int(tokens[4], 16))              
-              if tokens[1] == "LPCM":
-                write("found LPCM audio stream %s" % tokens[4], False)
-                streamIds.append(int(tokens[4], 16))             
-              if tokens[1] == "Teletext:":
-                write("found Teletext stream %s" % tokens[3], False)
-                streamIds.append(int(tokens[3], 16))              
-              if tokens[1] == "Subpicture:":
-                write("found Subpicture stream %s" % tokens[3], False)
-                streamIds.append(int(tokens[3], 16))
-              if tokens[1] == "Generic_VBI:":
-                write("found Generic_VBI stream %s" % tokens[3], False)
-                streamIds.append(int(tokens[3], 16))                                            
-            if tokens[0] == "--->":
-              if tokens[1] == "new":
-                if tokens[2] == "File:":
-                  write("found file for stream 0x%x, %s" % (streamIds[len(streamIds)-1], tokens[3]), False)
-                  streamFiles.append(tokens[3].replace("'","")) # let's hope the path never has a space in it
-            if tokens[0] == "-->":
-              if tokens[1] == "stream":
-                if tokens[2] == "omitted":
-                  write("stream 0x%x omitted" % streamIds[len(streamIds)-1], False)
-                  streamFiles.append("")
-                  
-    write("streadmIds=%s" % streamIds)
-    write("streamFiles=%s" % streamFiles)
-
-    # choose which streams we need
-    video, audio1, audio2 = selectStreams(folder)
-
-    if getFileType(folder) == "mpeg":
-        videoID  = video[VIDEO_ID] & 255
-        audio1ID = audio1[AUDIO_ID] & 255
-        audio2ID = audio2[AUDIO_ID] & 255
-    else:
-        videoID  = video[VIDEO_ID]
-        audio1ID = audio1[AUDIO_ID]
-        audio2ID = audio2[AUDIO_ID]
-
-    # sanity check - we should have a file for each ID
-    if len(streamIds) == len(streamFiles):
-        # loop thought the available streams looking for the ones we want
-        for stream in streamIds:
-            write("got stream: %d" % stream, False)
-            if stream == videoID:
-                write("found video streamID", False)
-                if os.path.exists(streamFiles[streamIds.index(stream)]):
-                    write("found video stream file", False)
-                    os.rename(streamFiles[streamIds.index(stream)], os.path.join(folder, "stream.mv2"))
-
-            if stream == audio1ID:
-                write("found audio1 streamID", False)
-                if os.path.exists(streamFiles[streamIds.index(stream)]):
-                    write("found audio1 stream file", False)
-                    if audio1[AUDIO_CODEC] == "AC3":
-                        os.rename(streamFiles[streamIds.index(stream)], os.path.join(folder, "stream0.ac3"))
-                    else:
-                        os.rename(streamFiles[streamIds.index(stream)], os.path.join(folder, "stream0.mp2"))
-
-            if stream == audio2ID:
-                write("found audio2 streamID", False)
-                if os.path.exists(streamFiles[streamIds.index(stream)]):
-                    write("found audio2 stream file", False)
-                    if audio2[AUDIO_CODEC] == "AC3":
-                        os.rename(streamFiles[streamIds.index(stream)], os.path.join(folder, "stream1.ac3"))
-                    else:
-                        os.rename(streamFiles[streamIds.index(stream)], os.path.join(folder, "stream1.mp2"))
-
-    # final chance to find the correct stream files
-    if not os.path.exists(os.path.join(folder, "stream.mv2")):
-        if os.path.exists(os.path.join(folder, pxbasename + ".m2v")):
-            os.rename(os.path.join(folder, pxbasename + ".m2v"), os.path.join(folder, "stream.mv2"))
-
-    if not os.path.exists(os.path.join(folder, "stream0.mp2")) or not os.path.exists(os.path.join(folder, "stream0.ac3")):
-        if os.path.exists(os.path.join(folder, pxbasename + ".mp2")):
-            os.rename(os.path.join(folder, pxbasename + ".mp2"), os.path.join(folder, "stream0.mp2"))
-        if os.path.exists(os.path.join(folder, pxbasename + ".ac3")):
-            os.rename(os.path.join(folder, pxbasename + ".ac3"), os.path.join(folder, "stream0.ac3"))
-
-    if not os.path.exists(os.path.join(folder, "stream1.mp2")) or not os.path.exists(os.path.join(folder, "stream1.ac3")):
-        if os.path.exists(os.path.join(folder, pxbasename + "[1].mp2")):
-            os.rename(os.path.join(folder, pxbasename + "[1].mp2"), os.path.join(folder, "stream1.mp2"))
-        if os.path.exists(os.path.join(folder, pxbasename + "[1].ac3")):
-            os.rename(os.path.join(folder, pxbasename + "[1].ac3"), os.path.join(folder, "stream1.ac3"))
-
-    # do we have any subtitle files
-    if os.path.exists(os.path.join(folder, pxbasename + ".sup")):
-        os.rename(os.path.join(folder, pxbasename + ".sup"), os.path.join(folder, "stream.sup"))
-
-    if os.path.exists(os.path.join(folder, pxbasename + ".sup.IFO")):
-        os.rename(os.path.join(folder, pxbasename + ".sup.IFO"), os.path.join(folder, "stream.sup.IFO"))
-
-    write("renameProjectXFiles end -----------------------------------------", False)
-
-#############################################################
 # convert time stamp to pts
 
 def ts2pts(time):
@@ -2286,10 +2242,7 @@
             fr=frameratePAL
         else:
             fr=framerateNTSC
-
-        source = quoteFilename(source)
-
-        command = "mytharchivehelper -t  %s '%s' %s" % (source, seconds, destination)
+        command = "mytharchivehelper -t %s '%s' %s" % (quoteCmdArg(source), seconds, quoteCmdArg(destination))
         result = runCommand(command)
         if result <> 0:
             fatalError("Failed while running mytharchivehelper to get thumbnails.\n"
@@ -2312,9 +2265,8 @@
     write("Extracting thumbnail images from: %s - at %s" % (source, thumbList))
     write("Destination file %s" % destination)
 
-    source = quoteFilename(source)
-
-    command = "mytharchivehelper -v important -t %s '%s' %s" % (source, thumbList, destination)
+    command = "mytharchivehelper -v important -t %s '%s' %s" % (quoteCmdArg(source), thumbList, quoteCmdArg(destination))
+    write(command)
     result = runCommand(command)
     if result <> 0:
         fatalError("Failed while running mytharchivehelper to get thumbnails")
@@ -2329,7 +2281,7 @@
 
     passes = int(getText(profileNode.getElementsByTagName("passes")[0]))
 
-    command = path_ffmpeg[0]
+    command = quoteCmdArg(path_ffmpeg[0])
 
     if cpuCount > 1:
         command += " -threads %d" % cpuCount
@@ -2342,9 +2294,9 @@
 
         # do some parameter substitution
         if value == "%inputfile":
-            value = quoteFilename(source)
+            value = quoteCmdArg(source)
         if value == "%outputfile":
-            value = quoteFilename(destvideofile)
+            value = quoteCmdArg(destvideofile)
         if value == "%aspect":
             value = aspectratio
 
@@ -2398,7 +2350,7 @@
         passLog = os.path.join(getTempPath(), 'pass')
 
         pass1 = string.replace(command, "%passno","1")
-        pass1 = string.replace(pass1, "%passlogfile", passLog)
+        pass1 = string.replace(pass1, "%passlogfile", quoteCmdArg(passLog))
         write("Pass 1 - " + pass1)
         result = runCommand(pass1)
 
@@ -2410,7 +2362,7 @@
             os.remove(destvideofile)
 
         pass2 = string.replace(command, "%passno","2")
-        pass2 = string.replace(pass2, "%passlogfile", passLog)
+        pass2 = string.replace(pass2, "%passlogfile", quoteCmdArg(passLog))
         write("Pass 2 - " + pass2)
         result = runCommand(pass2)
 
@@ -2515,14 +2467,14 @@
     samplerate, channels = getAudioParams(folder)
     videores, fps, aspectratio = getVideoParams(folder)
 
-    command =  path_ffmpeg[0] + " -y "
+    command =  quoteCmdArg(path_ffmpeg[0]) + " -y "
 
     if cpuCount > 1:
         command += "-threads %d " % cpuCount
 
-    command += "-f s16le -ar %s -ac %s -i %s " % (samplerate, channels, os.path.join(folder, "audout")) 
+    command += "-f s16le -ar %s -ac %s -i %s " % (samplerate, channels, quoteCmdArg(os.path.join(folder, "audout"))) 
     command += "-f rawvideo -pix_fmt yuv420p -s %s -aspect %s -r %s " % (videores, aspectratio, fps)
-    command += "-i %s " % os.path.join(folder, "vidout")
+    command += "-i %s " % quoteCmdArg(os.path.join(folder, "vidout"))
     command += "-aspect %s -r %s " % (aspectratio, fps)
     if (deinterlace == 1):
         command += "-deinterlace "
@@ -2530,7 +2482,7 @@
     command += "-s %s -b %s -vcodec mpeg2video " % (outvideores, outvideobitrate)
     command += "-qmin %s -qmax %s -qdiff %s " % (qmin, qmax, qdiff)
     command += "-ab %s -ar %s -acodec %s " % (outaudiobitrate, outaudiosamplerate, outaudiocodec)
-    command += "-f dvd %s" % quoteFilename(destvideofile)
+    command += "-f dvd %s" % quoteCmdArg(destvideofile)
 
     #wait for mythtranscode to create the fifos
     tries = 30
@@ -2567,10 +2519,10 @@
 def CreateDVDISO(title):
     write("Creating ISO image")
     checkCancelFlag()
-    command = path_mkisofs[0] + ' -dvd-video '
-    command += ' -V ' + quoteFilename(title)
-    command += ' -o ' + os.path.join(getTempPath(), 'mythburn.iso')
-    command += " " + os.path.join(getTempPath(),'dvd')
+    command = quoteCmdArg(path_mkisofs[0]) + ' -dvd-video '
+    command += ' -V ' + quoteCmdArg(title)
+    command += ' -o ' + quoteCmdArg(os.path.join(getTempPath(), 'mythburn.iso'))
+    command += " " + quoteCmdArg(os.path.join(getTempPath(),'dvd'))
 
     result = runCommand(command)
 
@@ -2585,20 +2537,28 @@
 
 def BurnDVDISO(title):
     write( "Burning ISO image to %s" % dvddrivepath)
-    checkCancelFlag()
 
     finished = False
-    tries = 0
-    while not finished and tries < 10:
-        f = os.open(dvddrivepath, os.O_RDONLY | os.O_NONBLOCK)
-        drivestatus = ioctl(f,CDROM.CDROM_DRIVE_STATUS, 0)
-        os.close(f);
+    while not finished:
+        # Maybe the user has no appropriate medium or something alike. Give her the chance to cancel.
+        checkCancelFlag()
 
-        if drivestatus == CDROM.CDS_DISC_OK or drivestatus == CDROM.CDS_NO_INFO:
+        def drivestatus():
+            f = os.open(dvddrivepath, os.O_RDONLY | os.O_NONBLOCK)
+            return ioctl(f,CDROM.CDROM_DRIVE_STATUS, 0)
+            os.close(f);
+
+        # I drive needs some time (for example to close the tray) give it to it
+        tries = 0
+        while drivestatus() == CDROM.CDS_DRIVE_NOT_READY and tries < 6:
+            time.sleep(5)
+            tries += 1
+
+        if drivestatus() == CDROM.CDS_DISC_OK or drivestatus() == CDROM.CDS_NO_INFO:
 
             # If the frontend has a previously burnt DVD+RW mounted,
             # growisofs will fail to burn it, so try to pumount it first...
-            runCommand("pumount " + dvddrivepath);
+            runCommand("pumount " + quoteCmdArg(dvddrivepath));
 
             if mediatype == DVD_RW and erasedvdrw == True:
                 command = path_growisofs[0] + " -dvd-compat "
@@ -2618,18 +2578,31 @@
             write("Running growisofs to burn DVD")
 
             result = runCommand(command)
-            if result != 0:
+            if result == 0:
+                finished = True
+            elif result == 252:
+                write("-"*60)
+                write("You probably inserted a medium of wrong type.")
+                if mediatype == DVD_SL:
+                  write("Please insert an empty single-layer disc (DVD+R or DVD-R).")
+                if mediatype == DVD_DL:
+                  write("Please insert an empty double-layer disc (DVD+R DL or DVD-R DL).")
+                if mediatype == DVD_RW:
+                  write("Please insert a rewritable disc (DVD+RW or DVD-RW).")
+            else:
                 write("-"*60)
                 write("ERROR: Failed while running growisofs.")
                 write("Result %d, Command was: %s" % (result, command))
                 write("Please check the troubleshooting section of the README for ways to fix this error")
                 write("-"*60)
                 write("")
-                sys.exit(1)
-            finished = True
+                write("Going to try it again until canceled by user:")
+                write("-"*60)
+                write("")
 
             try:
                 # eject the burned disc
+                runCommand("pumount " + quoteCmdArg(dvddrivepath));
                 f = os.open(dvddrivepath, os.O_RDONLY | os.O_NONBLOCK)
                 r = ioctl(f,CDROM.CDROMEJECT, 0)
                 os.close(f)
@@ -2637,28 +2610,25 @@
                 write("Failed to eject the disc! "
                       "Maybe the media monitor has mounted it")
 
-        elif drivestatus == CDROM.CDS_TRAY_OPEN:
-            # Give the user 10secs to close the Tray
+        elif drivestatus() == CDROM.CDS_TRAY_OPEN:
             write("Waiting for tray to close.")
-            time.sleep(10)
-        elif drivestatus == CDROM.CDS_NO_DISC:
+            # Wait until user closes tray or cancels
+            while drivestatus() == CDROM.CDS_TRAY_OPEN:
+                checkCancelFlag()
+                time.sleep(5)
+        elif drivestatus() == CDROM.CDS_NO_DISC:
             # Open the Tray, if there is one.
             write("Opening tray to get it fed with a DVD.")
             f = os.open(dvddrivepath, os.O_RDONLY | os.O_NONBLOCK)
             ioctl(f,CDROM.CDROMEJECT, 0)
             os.close(f);
-        elif drivestatus == CDROM.CDS_DRIVE_NOT_READY:
-            # Try a hard reset
+        elif drivestatus() == CDROM.CDS_DRIVE_NOT_READY:
+            # Try a hard reset if the device is still not ready
             write("Trying a hard-reset of the device")
             f = os.open(dvddrivepath, os.O_RDONLY | os.O_NONBLOCK)
             ioctl(f,CDROM.CDROMEJECT, 0)
             os.close(f);
 
-        time.sleep(1)
-        tries += 1
-
-    if not finished:
-        fatalError("Tried 10 times to get a good status from DVD drive - Giving up!")
 
     write("Finished burning ISO image")
 
@@ -2669,7 +2639,7 @@
 def deMultiplexMPEG2File(folder, mediafile, video, audio1, audio2):
 
     if getFileType(folder) == "mpegts":
-        command = "mythreplex --demux --fix_sync -t TS -o %s " % (folder + "/stream")
+        command = "mythreplex --demux --fix_sync -t TS -o %s " % quoteCmdArg(folder + "/stream")
         command += "-v %d " % (video[VIDEO_ID])
 
         if audio1[AUDIO_ID] != -1: 
@@ -2689,7 +2659,7 @@
                 command += "-c %d " % (audio2[AUDIO_ID])
 
     else:
-        command = "mythreplex --demux --fix_sync -o %s " % (folder + "/stream")
+        command = "mythreplex --demux --fix_sync -o %s " % quoteCmdArg(folder + "/stream")
         command += "-v %d " % (video[VIDEO_ID] & 255)
 
         if audio1[AUDIO_ID] != -1: 
@@ -2709,7 +2679,7 @@
             elif audio2[AUDIO_CODEC] == 'EAC3':
                 command += "-c %d " % (audio2[AUDIO_ID] & 255)
 
-    mediafile = quoteFilename(mediafile)
+    mediafile = quoteCmdArg(mediafile)
     command += mediafile
     write("Running: " + command)
 
@@ -2726,23 +2696,22 @@
     M2Vsize0 = os.path.getsize(source)
     write("Initial M2Vsize is %.2f Mb , target is %.2f Mb" % ( (float(M2Vsize0)/mega), (float(M2Vsize0)/(factor*mega)) ))
 
-    command = path_M2VRequantiser[0]   
+    command = quoteCmdArg(path_M2VRequantiser[0])   
     command += " %.5f "  % factor
     command += " %s "  % M2Vsize0
-    command += " <  %s " % source
-    command += " >  %s " % destination
+    command += " <  %s " % quoteCmdArg(source)
+    command += " >  %s " % quoteCmdArg(destination)
  
     write("Running: " + command)
     result = runCommand(command)
+    if result<>0:
+        fatalError("Failed while running M2VRequantiser. Command was %s" % command)
 
     M2Vsize1 = os.path.getsize(destination)
        
     write("M2Vsize after requant is  %.2f Mb " % (float(M2Vsize1)/mega))
     fac1=float(M2Vsize0) / float(M2Vsize1)
     write("Factor demanded %.5f, achieved %.5f, ratio %.5f " % ( factor, fac1, fac1/factor))
-            
-    if result<>0:
-        fatalError("Failed while running M2VRequantiser. Command was %s" % command)
 
 #############################################################
 # Calculates the total size of all the video, audio and menu files 
@@ -3501,7 +3470,7 @@
                 height = getScaledAttribute(node, "h")
                 frames = int(secondsToFrames(menulength))
 
-                command = "mytharchivehelper -t  %s '%s' '%s' %d" % (inputfile, starttime, outputfile, frames)
+                command = "mytharchivehelper -t %s '%s' '%s' %d" % (quoteCmdArg(inputfile), starttime, quoteCmdArg(outputfile), frames)
                 result = runCommand(command)
                 if (result != 0):
                     write( "mytharchivehelper failed with code %d. Command = %s" % (result, command) )
@@ -4367,7 +4336,7 @@
     # 2. if there is one or more stream(s) using the 2nd preferred language we use that
     # 3. if we still haven't found a stream we use the stream with the lowest PID
     # 4. we prefer ac3 over mp2
-    # 5. if there are more that one stream with the chosen language we use the one with the lowest PID
+    # 5. if there are more than one stream with the chosen language we use the one with the lowest PID
 
     write("Preferred audio languages %s and %s" % (preferredlang1, preferredlang2))
 
@@ -5091,7 +5060,8 @@
         tmpfile = node.attributes["filename"].value
         filename = os.path.basename(tmpfile)
 
-        res = runCommand("mytharchivehelper -r " + quoteFilename(tmpfile))
+        res = runCommand("mytharchivehelper -r " + quoteCmdArg(tmpfile))
+
         if res == 2:
             # file is on a remote filesystem so copy it to a local file
             write("Copying file from " + tmpfile)
@@ -5156,9 +5126,6 @@
 
         write( "Final DVD Video format will be " + videomode)
 
-        #Ensure the destination dvd folder is empty
-        if doesFileExist(os.path.join(getTempPath(),"dvd")):
-            deleteAllFilesInFolder(os.path.join(getTempPath(),"dvd"))
 
         #Loop through all the files
         files=media[0].getElementsByTagName("file")
@@ -5168,18 +5135,12 @@
 
             if debug_secondrunthrough==False:
                 #Delete all the temporary files that currently exist
-                deleteAllFilesInFolder(getTempPath())
+                deleteEverythingInFolder(getTempPath())
 
             #If User wants to, copy remote files to a tmp dir
             if copyremoteFiles==True:
                 if debug_secondrunthrough==False:
                     localCopyFolder=os.path.join(getTempPath(),"localcopy")
-                    #If it already exists destroy it to remove previous debris
-                    if os.path.exists(localCopyFolder):
-                        #Remove all the files first
-                        deleteAllFilesInFolder(localCopyFolder)
-                        #Remove the folder
-                        os.rmdir (localCopyFolder)
                     os.makedirs(localCopyFolder)
                 files=copyRemote(files,getTempPath())
 
@@ -5193,20 +5154,6 @@
                 folder=getItemTempPath(filecount)
 
                 if debug_secondrunthrough==False:
-                    #If it already exists destroy it to remove previous debris
-                    if os.path.exists(folder):
-                        #Remove all the files first
-                        deleteAllFilesInFolder(folder)
-                        subtitlefolder = os.path.join(folder, "stream.d")
-                        if os.path.exists(subtitlefolder):
-                            deleteAllFilesInFolder(subtitlefolder)
-                            os.rmdir(subtitlefolder)
-                        previewfolder = os.path.join(folder, "preview")
-                        if os.path.exists(previewfolder):
-                            deleteAllFilesInFolder(previewfolder)
-                            os.rmdir(previewfolder)
-                        #Remove the folder
-                        os.rmdir (folder)
                     os.makedirs(folder)
                 #Do the pre-process work
                 preProcessFile(node,folder,filecount)
