#!/usr/bin/env python
import argparse
from configparser import SafeConfigParser
from contextlib import closing
from os.path import basename, dirname, join, normpath, realpath
import sys
from urllib2 import urlopen

def generic_open(arg):
    try:
        return urlopen(arg), None
    except ValueError:
        arg = normpath(realpath(arg))
        return open(arg, "r"), dirname(arg)

def playlist_files(config):
    n = config.getint("playlist", "NumberOfEntries")
    for i in xrange(1, n+1):
        yield config.get("playlist", "File%d" % i)

parser = argparse.ArgumentParser(description = "dfsdfsdf")
parser.add_argument("--mpc", dest = "mpc", action = "store_const", const = True, default = False)
parser.add_argument("paths", metavar = "path-or-URL", nargs = "+")
args = parser.parse_args()

config = SafeConfigParser()
for path in args.paths:
    raw_handle, directory = generic_open(path)
    with closing(raw_handle) as handle:
        try:
            config.readfp(handle)
            for raw_fn in playlist_files(config):
                fn = join(directory, raw_fn) if directory != None else raw_fn
                if args.mpc and directory != None:
                    fn = "file://" + fn
                print fn
        except Exception, e:
            print >> sys.stderr, "%s\n    [%s] %s" % (path, type(e).__name__, e)

@@ -56,20 +56,16 @@
  import 
-Safe
 ConfigPa
@@ -123,18 +123,8 @@
 port
- basename,
  dir
@@ -198,66 +198,148 @@
 en%0A%0A
-def generic_open(arg):%0A    try:%0A        return urlopen(arg
+ENCODINGS = (%22utf-8%22, %22iso-8859-1%22)%0A%0Adef read_pls(path):%0A    try:%0A        with closing(urlopen(path)) as resp:%0A            return resp.read(
 ), N
@@ -373,19 +373,24 @@
         
-arg
+the_path
  = normp
@@ -402,19 +402,20 @@
 ealpath(
-arg
+path
 ))%0A     
@@ -421,43 +421,289 @@
     
-return open(arg, %22r%22), dirname(arg)
+with open(the_path, %22r%22) as fh:%0A            return fh.read(), dirname(the_path)%0A%0Adef decode(text):%0A    result = None%0A    for enc in ENCODINGS:%0A        try:%0A            result = text.decode(enc)%0A            break%0A        except UnicodeDecodeError:%0A            pass%0A    return result
 %0A%0Ade
@@ -1127,12 +1127,8 @@
 g = 
-Safe
 Conf
@@ -1166,26 +1166,38 @@
 hs:%0A    
-raw_handle
+try:%0A        pls_bytes
 , direct
@@ -1206,20 +1206,16 @@
 y = 
-generic_open
+read_pls
 (pat
@@ -1225,55 +1225,58 @@
     
+   
-with closing(raw_handle) as handle:%0A        try
+ pls = decode(pls_bytes)%0A        if pls != None
 :%0A  
@@ -1300,17 +1300,19 @@
 read
-fp(handle
+_string(pls
 )%0A  
@@ -1553,24 +1553,141 @@
 rint fn%0A    
+    else:%0A            print %3E%3E sys.stderr, %22%25s%5Cn    Failed to decode file (tried %25s)%22 %25 (path, %22, %22.join(ENCODINGS))%0A
     except E
@@ -1699,20 +1699,16 @@
 ion, e:%0A
-    
         

support utf-8, iso-8859-1