#! /bin/sh
echo $1
set -e

do_remove_chunks() {
  IN=$1
  TMP=$(tempfile)
  pngcrush -q -f 0 -l 0 -m 1 \
      -rem iTXt -rem tEXt -rem zTXt \
      -rem bKGD -rem hIST -rem pHYs \
      -rem sPLT -rem sTER -rem tIME -rem tRNS \
      $IN $TMP
  touch -r $IN $TMP
  mv $TMP $IN
}

do_optimize_filters() {
  IN=$1
  TMP=$(tempfile)
  cp $IN $TMP
  optipng -quiet -o1 -f0-5 $TMP
  touch -r $IN $TMP
  mv $TMP $IN
}

do_optimize_deflate() {
  IN=$1
  TMP=$(tempfile)
  cp $IN $TMP
  advdef -z -3 $TMP
  touch -r $IN $TMP
  mv $TMP $IN
}

get_size() {
  du -b $1 | cut -f1
}

# do stuff

for OLD in "$@"; do
    NEW=$(tempfile)
    cp $OLD $NEW
    do_remove_chunks $NEW
    do_optimize_filters $NEW
    do_optimize_deflate $NEW > /dev/null
    touch -r $OLD $NEW
    if [ $(get_size $NEW) -lt $(get_size $OLD) ]; then
	mv $NEW $OLD
    else
	rm $NEW
    fi;
done

echo traitee
