#!/bin/bash
### rejpeg - try to save disc space by re-coding JPEGs with quality set to 80
### Copyright (C) 1999  Arne Zellentin <arne@unix-ag.org>

### This program is free software; you can redistribute it and/or modify
### it under the terms of the GNU General Public License as published by
### the Free Software Foundation; either version 2 of the License, or
### (at your option) any later version.

### This program is distributed in the hope that it will be useful,
### but WITHOUT ANY WARRANTY; without even the implied warranty of
### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
### GNU General Public License for more details.

### You should have received a copy of the GNU General Public License
### along with this program; if not, write to the Free Software
### Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

### see http://www.home.unix-ag.org/arne/scripToys/ for details.

# usage: rejpeg [-f] <file1> [<, ...,> <filen>]
# use option -f if you want the new files even if less than 5% are saved
# (this is good for corrupted JPEGs)

if [ "$1" = "-f" ] ; then
  force=1
  shift
else
  force=0
fi

sum1=0
sum2=0
while [ $# -gt 0 ] ; do
	size1=`ls --size "$1" | awk '{ print $1 }'`
	echo -n "$1 $size1 --> "
	ok=0
	( djpeg -pnm "$1" | cjpeg -quality 80 -optimize > "$1.jj" ) && ok=1
	size2=`ls --size "$1.jj" | awk '{ print $1 }'`
	save=`expr $size2 \* 100 / $size1`
	echo -n "$size2 ($save%)"
	if [ $ok = 1 -a "$save" -le 95 ] ; then
		mv "$1.jj" "$1"
		echo .
		sum1=`expr $sum1 + $size1`
		sum2=`expr $sum2 + $size2`
	else
		if [ $force = 1 ] ; then
			mv "$1.jj" "$1"
			echo " (forced)."
	                sum1=`expr $sum1 + $size1`
	                sum2=`expr $sum2 + $size2`
		else
			rm "$1.jj"
			echo " - not replaced."
		fi
        fi
	shift
done
if [ $sum1 -gt 0 ] ; then
	echo "total: $sum1 --> $sum2 (`expr $sum2 \* 100 / $sum1`%)"
fi
