#!/usr/bin/env python

import os,traceback,sys
from multiprocessing import Pool

def optimizePNG(filenameAndPath): 
	try:
		os.spawnlp(os.P_WAIT,'optipng','optipng','-o7','-q',filenameAndPath) 
		os.spawnlp(os.P_WAIT,'pngout','pngout','-q', filenameAndPath)
		return (True,filenameAndPath,os.getpid())
	except:
		return (False,filenameAndPath,os.getpid(),traceback.format_exc())
 
def generatePNGListing(directory):
	"run optipng pngout on all png files located in a directory recursively"
	path = os.path.normpath(directory)
	if not os.path.isdir(path):
		raise Error, "Directory %s not found" % path

#we can use a for loop to continually get more data from a walk object until there is none left
	for currPath, currDirs, currFiles in os.walk(path):  
		for file in currFiles:
#no need for us to test and see if the file is a directory as fileGenerator is taking care of that for us. Also no need for recursion.
			if(file.split(".")[-1].lower() == 'png'):
				yield(currPath+"/"+file)

def main(dir):
	pool = Pool() #we'll use the default number of processes
	results = pool.imap_unordered(optimizePNG,generatePNGListing(dir))
	pool.close()
	pool.join()
	successes = []
	failures = []	
	for result in results:
		if result[0] == True:
			successes.append(result)
		else:
			failures.append(result)
	for success in successes:
		print success[1] + " optimized by "+str(success[2])
	for failure in failures:
		print failure[1] + " failed due to exception "+failure[3]+ " in process "+str(failure[2])
		
if __name__ == "__main__":
	main(os.getcwd())
