@@ -41,11 +41,10 @@
 # Coupling to main window
 #
 main = None
 
 
-
 # Streamlink/listformat mapping
 listfmt_t = {
     "audio/x-scpls":        "pls",
     "audio/x-mpegurl":      "m3u",
     "audio/mpegurl":        "m3u",
@@ -248,11 +247,11 @@
         return urls
 
     # Otherwise convert to local file
     if local_file:
         fn, is_unique = tmp_fn(cnt, dest)
-        with open(fn, "wb") as f:
+        with open(fn, "w") as f:
             debug(dbg.DATA, "exporting with format:", dest, " into filename:", fn)
             f.write( save_playlist(source="srv", multiply=True).export(urls, row, dest) )
         return [fn]
     else:
         return urls
@@ -374,11 +373,11 @@
         converter = getattr(self, dest) or self.pls
         return converter(rows)
 
     # save directly
     def file(self, rows, dest, fn):
-        with open(fn, "wb") as f:
+        with open(fn, "w") as f:
             f.write(self.store(rows, dest))
     
     
 
     # M3U
@@ -451,18 +450,28 @@
     from xml.sax.saxutils import escape as xmlentities
     return xmlentities(s)
 
 
 
-# generate filename for temporary .m3u, if possible with unique id
+# Generate filename for temporary .m3u, if possible with unique id
 def tmp_fn(pls, ext="m3u"):
     # use shoutcast unique stream id if available
     stream_id = re.search("http://.+?/.*?(\d+)", pls, re.M)
     stream_id = stream_id and stream_id.group(1) or "XXXXXX"
     try:
         channelname = main.current_channel
     except:
         channelname = "unknown"
-    return (str(conf.tmp) + os.sep + "streamtuner2."+channelname+"."+stream_id+"."+ext, len(stream_id) > 3 and stream_id != "XXXXXX")
+    # return temp filename
+    fn = "%s/streamtuner2.%s.%s.%s" % (str(conf.tmp), channelname, stream_id, ext)
+    is_unique = len(stream_id) > 3 and stream_id != "XXXXXX"
+    tmp_files.append(fn)
+    return fn, is_unique
+
+# Collect generated filenames
+tmp_files = []
 
-    
+# Callback from main / after gtk_main_quit
+def cleanup_tmp_files():
+    if not int(conf.reuse_m3u):
+        [os.remove(fn) for fn in set(tmp_files)]