import struct, binascii

class Chunk:
  def __init__(self, f):
    cl = f.read(4)
    self.len = struct.unpack("!L", cl)[0]
    ch = f.read(self.len+8)
    (self.type, self.data, self.crc) = struct.unpack("!4s%ssL" % self.len, ch)

  def write(self, f):
    cl = struct.pack("!L", len(self.data))
    f.write(cl)
    ch = struct.pack("!4s%ssL" % len(self.data),
                     self.type,
                     self.data,
                     self.calccrc())
    f.write(ch)

  def calccrc(self):
    return crc(self.type + self.data)
    
class Header(Chunk):
  def __init__(self, f):
    Chunk.__init__(self, f)
    (self.width,
     self.height,
     self.depth,
     self.colortype,
     self.compressiontype,
     self.filtertype,
     self.interlace) = struct.unpack("!llccccc", self.data)

  def write(self, f):
    self.data = struct.pack("!llccccc", self.width,
                            self.height,
                            self.depth,
                            self.colortype,
                            self.compressiontype,
                            self.filtertype,
                            self.interlace)
    Chunk.write(self, f)

crc_table = {}

def make_crc_table():
  for n in range(256):
    c = n
    for k in range(8):
      if c & 1:
        c = 0xedb88320L ^ (c >> 1)
      else:
        c = c >> 1
    crc_table[n] = c

def update_crc(crc, buf):
  c = crc
  for n in buf:
    c = crc_table[(c ^ ord(n)) & 0xff] ^ (c >> 8)
  return c

def crc(buf):
  return update_crc(0xffffffffL, buf) ^ 0xffffffffL

def set_height(filename, height):

    f = open(filename, "r+b")

    sig = f.read(8)

    if sig != "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a":
      print "Not a PNG file:", filename

    hpos = f.tell()

    header = Header(f)

    f.seek(hpos)

    if header.height != height:
      header.height = height
      header.write(f)

    f.close()

make_crc_table()
