#!/usr/bin/env python
import os, sys,shutil
import id3reader

def readInfo(mp3Name):
	curMp3 = {}
	id3r = id3reader.Reader(mp3Name)
	curMp3['album'] = id3r.getValue('album')
	curMp3['performer'] = id3r.getValue('performer')
	curMp3['title'] = id3r.getValue('title')
	curMp3['track'] = id3r.getValue('track')
	curMp3['year'] = id3r.getValue('year')
	return curMp3

def mkdir(dst):
	if dst == 'unknown':
		try:
			os.mkdir('unknown')
		except OSError:
			out = 'unknown'
		return 'unknown'
	out = dst
	try:
		os.mkdir(dst)
	except OSError:
		out = 'unknown'
		return mkdir(out)
	return out

def cpyMp3(fileIn, destFolder):
	try:
		info = readInfo(fileIn)
		artist = info['performer']
		if not artist:
			artist = 'Unknown_Artist'
		newName = artist + ' - '
		
		album = info['album']
		if not album:
			album = 'Unknown_Album'

		if info['title']:
			newName += info['title']
		else:
			if info['track']:
				newName += 'track_' + info['track']
		newName += '.mp3'
		# you can dump one artist...
		if selective and selective != artist:
			return
		# copy into 'destFolder/artist/album/newName'
		mkdir(destFolder)
		mkdir(destFolder + '/' + artist)
		mkdir(destFolder + '/' + artist +'/' + album)
		srcname = fileIn
		dstname = os.path.join(destFolder + '/' + artist +'/' + album, newName).encode('latin-1')
		try:
			shutil.copy2(srcname, dstname)
			print dstname
		except (IOError, os.error), why:
			return
	except IOError:
		return

def process(inURI, outURI):
	print inURI, outURI
	all = [f for f in os.listdir(inURI)]
	for f in all:
		if os.path.isdir(os.path.join(inURI,f)):
			process(os.path.join(inURI,f), outURI)
		else:
			cpyMp3(os.path.join(inURI,f), outURI)

outURI = '/tmp'
if os.name=='nt':
	outURI = 'C:\\iPodDump'
	mkdir(outURI)
selective = None
entryURI = '../iPod_Control/Music'

inURI = os.path.join('./',entryURI)
process(inURI, outURI)
