#!/usr/bin/env python

import os,traceback,sys
 
def optimizeImages(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):  
		print currPath
		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.
			try:
				if(file.split(".")[-1] == 'png'):
						print "optipnging "+ currPath + '/'+ file 
#we need to append the filename to the path as we haven't changed the current working directory this time
						os.spawnlp(os.P_WAIT,'optipng','optipng','-o7','-q',currPath+'/'+file) 
						print "pngouting" + currPath + '/'+file
						os.spawnlp(os.P_WAIT,'pngout','pngout','-q', currPath +'/'+ file)
			except:
				traceback.print_exc()
				
optimizeImages(os.getcwd())
sys.exit(0)
