#!/usr/bin/env python3

# (c) 2017-2020 Simon Budig <simon@budig.de>
# placed in the public domain.

import sys, struct

blacklist = [b'oFFs', b'pHYs', b'caNv', b'vpAg',
             b'gAMA', b'sRGB', b'cHRM', b'tIME']

PNGHeader = b'\x89PNG\r\n\x1a\n'

if __name__=='__main__':
   if len (sys.argv) < 1 or len (sys.argv) > 3:
      print ("usage: %s [<infile> [<outfile>]]\n", file=sys.stderr)
      sys.exit (1)

   infile = sys.stdin.buffer
   outfile = sys.stdout.buffer

   # some magic: if no 2nd arg is there, use the 1st.
   args = [sys.argv[1:2], sys.argv[2:0:-1][:1]]

   if args[0] and args[0][0] != '-':
      infile = open (args[0][0], "rb")

   pngfile = infile.read ()
   if infile != sys.stdin:
      infile.close()

   if pngfile[:8] != PNGHeader:
      print ("invalid PNG file signature", file=sys.stderr)
      sys.exit (1)

   if args[1] and args[1][0] != '-':
      outfile = open (args[1][0], 'wb')

   outfile.write (PNGHeader)

   pngfile = pngfile[8:]
   while pngfile:
      l = struct.unpack (">L", pngfile[:4])[0] + 12
      t = pngfile[4:8]

      print ("%s: %d bytes%s" % (t, l, [""," (filtered)"][t in blacklist]),
             file=sys.stderr)
      if not t in blacklist:
         outfile.write (pngfile[:l])

      pngfile = pngfile[l:]

   if outfile != sys.stdout:
      outfile.close()