#!/bin/bash
# If this script is called with the following
# parametes, a fast conversion from jpeg to ppm is attempted:
#      fconvert -sample <iii>x<iii> <name>.jpg <other-name>.ppm
# Otherwise, convert is called on the given parameters.
# This script can be used as a replacement for convert in tkalbum since it
# is faster than convert on many files.
# Note that you need the following programs to run this script:
#     convert        (ImageMagick)
#     identify       (ImageMagick)
#     djpeg          (jpeg)
#     pnmscalefixed  (netpbm)
if [ $1 != "-sample" ] || [ $# -ne 4 ] ; then
    exec convert $1 $2 "$3" "$4"
fi
case $2 in 
    100x100) size=100;;     
    120x120) size=120;;
    140x140) size=140;;
    160x160) size=160;;
    180x180) size=180;;
    200x200) size=200;;
    220x220) size=220;;
    240x240) size=240;;
    260x260) size=260;;
    280x280) size=280;;
    300x300) size=300;;
    320x320) size=320;;
    340x340) size=340;;
    360x360) size=360;;
    380x380) size=380;;
    400x400) size=400;;
    420x420) size=420;;
    440x440) size=440;;
    460x460) size=460;;
    480x480) size=480;;
    500x500) size=500;;
    *)     exec convert $1 $2 "$3" "$4" ;;
esac

if [ $4 == ${4%%.ppm} ] ; then
    exec convert $1 $2 "$3" "$4"
fi
idval=(`identify -ping -format "%m %w %h" "$3"`)
inputtype=${idval[0]}
width=${idval[1]}
height=${idval[2]}
if  [ $inputtype != "JPEG" ] && [ $inputtype != "jpeg" ] ; then
    exec convert $1 $2 "$3" "$4"
fi
if [ $width -gt $height ] ; then
    max=$width
else
    max=$height
fi
scale=$(($max/$size))
if [ $scale -lt 1 ] ; then
    scale=1
fi
exec djpeg -scale 1/$scale -pnm -fast "$3" | pnmscalefixed -xysize $size $size >$4
