#!/bin/sh
#Script to reduce quality on a jpeg and therefore reduce size
#You can usually set quality to around 50-75 without noticable loss of
#image quality.

PATH="/usr/local/bin:/bin:/usr/bin"

QUALITY=60
NOSAVE=
TEMP=/tmp/temp.jpg
VERBOSE="YES"

usage()
{	cat - <<EOF
$0: Script to process jpg images to reduce size.  It does this by reducing
the jpeg image quality, but this can usually be set to around 50-75 without
noticable degradation of the image, with significant size savings.

Usage:
$0 [ -q QUALITY ] [ --nosave ] image1.jpg image2.jpg image3.jpg ...

QUALITY is the jpeg quality to use, defaults to $QUALITY

If nosave is set, the original image will not be saved.
Normally, the original image is renamed and the new, smaller(?) image is
named after the original.

In the example above, if the --nosave option is not given, 
the original image1.jpg, image2.jpg, and image3.jpg will be renamed to
orig-image1.jpg, orig-image2.jpg, orig-image3.jpg, and the reduced versions
put into image1.jpg, image2.jpg, image3.jpg

EOF
}

reduce_image()
{	orig=$1
	tmp=$TEMP
	if [ "x$NOSAVE" = "xYES" ]
	then
		rm -f $TEMP 2>&1 > /dev/null
	else
		tmp="orig-$1"
	fi

	
	if [ "x$VERBOSE" = "xYES" ]
	then
		echo "Renaming original $orig to $tmp"
	fi
	
	if [ -f $tmp ]
	then
		echo "Backup file $tmp already exists, refuse to clobber" 2>&1
		echo "Aborting." 2>&1
		exit 1
	fi

	mv $orig $tmp

	if [ "x$VERBOSE" = "xYES" ]
	then
		echo "Changing quality to $QUALITY"
	fi
	djpeg $tmp | cjpeg -quality $QUALITY > $orig

	if [ "x$NOSAVE" = "xYES" ]
	then
		if [ "x$VERBOSE" = "xYES" ]
		then
			echo "Deleting backup file $tmp"
			rm $tmp
		fi
	fi
}
	
	
	

if [ $# -eq 0 ]
then
	usage
	exit 0
fi

while [ $# -gt 0 ]
do
	arg=$1
	shift

	if [ $arg = "-h" -o $arg = "--help" ]
	then
		usage
		exit 0
	fi

	if [ $arg = "-q" -o $arg = "--quality" ]
	then
		if [ "x$1" = "x" ]
		then
			usage
			echo "Must supply argument to quality arg" 1>&2
			exit 1
		fi

		if [ $1 -gt 0 ]
		then
			QUALITY=$1
			shift
			continue
		else
			usage
			echo "Illegal value $1 given for quality" 1>&2
			exit 1
		fi
	fi


	if [ $arg = "-n" -o $arg = "--nosave" ]
	then
		NOSAVE="YES"
		continue
	fi

	if [ $arg = "-s" -o $arg = "--save" ]
	then
		NOSAVE=
		TEMP=/tmp/temp.jpg
		continue
	fi

	reduce_image $arg
done


