#!/bin/sh

source ./parameters

# get first picture name
read filename

# for each picture
# restrict the possible colors (downsizing often increases the number of colors)
# determine quality/compression
# copy the image while resizing it
# find big files and try to pngcrush them (ImageMagick is bad in compressing png)
while [[ "$filename" != "XXendXX" ]]; do
    #echo "Img_compressor handling $filename"
    filenamearg=$filename
    newtype=""
    ispng=0
    tryjpg=0
    if [[ "$filename" == *.png  || "$filename" == *.PNG || "$filename" == *.gif || "$filename" = *.GIF || "$filename" = *.bmp ]]; then
       colorcount=`identify -verbose $filename | awk -- 'BEGIN { FS=" *|=|\n" }; /Colors:/  { print $3 }'`
       if [[ $colorcount != "" ]]; then
           imagecount=`echo "$colorcount" | wc -l`  # animated GIFs seem to have many Colors: lines
           if [[ $imagecount -gt 1 ]]; then
               if [[ $unanimate -eq 1 ]] ; then
                   filenamearg="${filename}[0]"
               fi
               colorcount=`echo "$colorcount" | head -n 1 `
           fi
           if [[ $colorcount -gt 200 ]]; then
               tryjpg=1              # maybe the image will be smaller as jpeg
           fi
           colorcount=$(($colorcount * 3 ))  # allow for some increase due to scaling
           if [[ $colorcount -gt 256 ]]; then
               colorcount=256              # no truecolor with png!
           fi
       else
           colorcount=256
       fi
       colors="-colors $colorcount -depth 8 -colorspace YUV -type Palette"
    else
       colors=""
    fi
    if [[ "$filename" == *.png  || "$filename" == *.PNG ]]; then
        quality="-quality 95"
    else
         quality="-quality ${jpgquality}"
    fi
    if [[ "$filename" = *.bmp ]]; then # get rid of these unwieldy bmps
       newtype="png:"
       quality="-quality 95"
       ispng=1
    fi
    convert "$filenamearg" -strip +matte $quality -filter bessel -resize "${xsize}x${ysize}>" $colors ${newtype}${filename}.conv >/dev/null
    if [[ -e $filename.conv ]]; then
        size=`wc -c ${filename}.conv | awk -- "{ print \\$1 }"`
        if [[ "$filename" == *.jpg || "$filename" == *.jpeg ]] ; then
           # maybe a png with 256 colors would be smaller? (especially since some *.jpgs are really .bmps
	   convert "$filenamearg" -strip +matte -filter bessel -resize "${xsize}x${ysize}>" -colors 256 -depth 8 -colorspace YUV -type Palette -quality 95 png:${filename}.conv2
           size2=`wc -c ${filename}.conv2 | awk -- "{ print \\$1 }"`
           #echo "PNG version is of size $size2"
           if [[ (-e $filename.conv2 ) && ( $(( $size2 + $pngbetterjpeg )) -lt $size) ]]; then
               echo "Converting $filename from jpg to png since it saves $(( $size - $size2 )) bytes"
               mv -f ${filename}.conv2 ${filename}.conv
               ispng=1
               size=$size2
           else
               rm -f ${filename}.conv2
           fi
        fi
        if [[ ($pngcrush != "") && ($size -gt $crushlimit) && ("$filename" == *.png  || "$filename" == *.PNG || $ispng -gt 0 ) ]]; then
           $pngcrush -o 5 -i 0 ${filename}.conv >/dev/null
           #mv ${filename}.crs ${filename}.conv
           sizeold=$size
           size=`wc -c $filename.conv | awk -- "{ print \\$1 }" `
           echo crushed $filename gained $(($sizeold - $size))
        fi
        if [[ $tryjpg -gt 0 ]]; then
           # we have png/bmp file which might be better as jpeg
	   convert "$filenamearg" -strip +matte -quality ${jpgquality} -filter bessel -resize "${xsize}x${ysize}>" jpg:${filename}.conv2
           size2=`wc -c ${filename}.conv2 | awk -- "{ print \\$1 }"`
           #echo "JPG version is of size $size2"
           if [[ (-e $filename.conv2 ) && ( $(( $size2 + $jpegbetterpng )) -lt $size) ]]; then
               echo "Converting $filename from png/bmp to jpg since it saves $(( $size - $size2 )) bytes"
               mv -f ${filename}.conv2 ${filename}.conv
               size=$size2
           else
               rm -f ${filename}.conv2
           fi            
        fi
        if [[ (-e $filename.conv ) && ( $size -lt `wc -c $filename | awk -- "{ print \\$1 }"`) ]]; then
            mv -f $filename.conv $filename
            echo "Overwriting" $filename "with new version of size " $size
        else
            rm -f $filename.conv
        fi
    fi
    ## get next picture to compress
    read filename;
    if [[ $filename == "" ]] ; then
      echo "Unexpected end of filename stream!"
      exit 5
    fi
done

