import struct
import os

pngSignature = [137, 80, 78, 71, 13, 10, 26, 10]

def Walk( root, recurse=0, pattern="*", returnFolders=False , onlyFolders = False):
	import fnmatch, os, string
	
	# initialize
	result = []

	# must have at least root folder
	try:
		names = os.listdir(root)
	except os.error:
		return result

	# expand pattern
	pattern = pattern or "*"
	pat_list = string.splitfields( pattern , ";" )
	
	# check each file
	for name in names:
		fullname = os.path.normpath(os.path.join(root, name))

		# grab if it matches our pattern and entry type
		for pat in pat_list:
			if fnmatch.fnmatch(name, pat):
				if (os.path.isdir(fullname) and returnFolders == True) or (os.path.isfile(fullname) and onlyFolders == False):
					result.append(fullname)
				continue
				
		# recursively scan other folders, appending results
		if recurse:
			if os.path.isdir(fullname) and not os.path.islink(fullname):
				result = result + Walk( fullname, recurse, pattern, returnFolders, onlyFolders )
			
	return result


def stripPNG(png):
    f = open(png,'rb')
    data=f.read()
    f.close()
    outData = data[:len(pngSignature)]
    if len(data) < 10:
        print "Invalid PNG file, too small",png
        return
    for i in range(len(pngSignature)):
        if ord(data[i]) != pngSignature[i]:
            print "Invalid PNG file, signature incorrect",png
            return
    data = data[len(pngSignature):]
    chunks = {}
    stripped = False
    while len(data) > 0:
        chunkLen = struct.unpack('>L',data[:4])[0]+12 #data plus len plus type plus crc
        chunkType = struct.unpack('>L',data[4:8])[0]
 #       print "Found chunk",chunkType,'|',data[4:8],'|',chunkLen,"remaining data length:",len(data)-chunkLen
        if chunkType == 1766015824:
            profileName = ''
            for c in data[8:]:
                if ord(c) == 0:
                    break
                profileName += c
#            print "Found iCC Profile:",profileName
            stripped = True
            data = data[chunkLen:]
            continue
        outData += data[:chunkLen]
        data = data[chunkLen:]
    if stripped:
#         res = raw_input('Found iCC profile '+profileName+', strip '+png+'? (enter / n)')
#         if res == 'n':
#             return
        print "Removed iCC Profile from",png
        f = open(png,'wb')
        f.write(outData)
        f.close()
           

if __name__ == "__main__":
    files = Walk('.',recurse = True,pattern = '*.png')
    for file in files:
        if file.endswith('.png'):
            print "Verifying",file
            stripPNG(file)
