#!/bin/sh
#------------------------->  Bourne shell - script  <-------------------------#
#- Copyright (C) 199x by International Computer Science Institute            -#
#- This file is part of the GNU Sather package. It is free software; you may -#
#- redistribute  and/or modify it under the terms of the  GNU General Public -#
#- License (GPL)  as  published  by the  Free  Software  Foundation;  either -#
#- version 3 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 Doc/GPL for more details.        -#
#- The license text is also available from:  Free Software Foundation, Inc., -#
#- 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA                     -#
#------------->  Please email comments to <bug-sather@gnu.org>  <-------------#

# - Cameron Simpson <cameron@dap.csiro.au>

usage="Usage: $0 [-f] [-r] [files...]
	-f	Force overwrite.
	-r	Recurse."

badopts=
flags=
fflag=
recurse=
while :
do  case "$1" in
	-f)	fflag=1; flags="$flags $1" ;;
	-r)	recurse=1 ;;
	-?*)	echo "$0: unrecognised option: $1" >&2; badopts=1 ;;
	*)	break ;;
    esac
    shift
done

[ $badopts ] && { echo "$usage" >&2; exit 2; }

if [ $recurse ]
then
    xit=0
    for dir in `find ${1+"$@"} ${1-.} -type d -print|sort`
    do  ( cd "$dir" || exit $?
	  echo "$dir ..."
	  exec "$0" $flags
	) || xit=$?
    done

    exit $xit
fi

[ $# = 0 ] && { case $0 in
		    *bmp2jpg)	set x *.bmp ;;
		    *pnm2jpg)	set x *.pnm ;;
		    *jpg2pnm)	set x *.jpg ;;	# implemented through a hack
		    *tif2jpg)	set x *.tif *.tiff ;;
		    *gif2jpg)	set x *.gif ;;
		esac
		shift
	      }

tmp=/tmp/t$$
xit=0

for i
do
    case "$i" in
	\*.gif|\*.tif|\*.tiff|\*.pnm|\*.jpg)
		     continue ;;	# unmatched pattern, ignore
	*-small.gif) continue ;;	# thumbnail, ignore
	*.gif)	j=`exec expr "$i" : '\(.*\).gif'`.jpg ;;
	*.tif)	j=`exec expr "$i" : '\(.*\).tif'`.jpg ;;
	*.tiff)	j=`exec expr "$i" : '\(.*\).tiff'`.jpg ;;
	*.pnm)	j=`exec expr "$i" : '\(.*\).pnm'`.jpg ;;
	*.jpg)	j=`exec expr "$i" : '\(.*\).jpg'`.pnm ;;
	*.bmp)	j=`exec expr "$i" : '\(.*\).bmp'`.jpg ;;
	*)	j=$i.jpg ;;
    esac
    echo "$i -> $tmp" >&2
    case "$i" in
	*.bmp)	bmptoppm < "$i" | cjpeg >"$tmp" ;;
	*.tiff|*.tif)	tifftopnm < "$i" | cjpeg >"$tmp" ;;
	*.pnm)	cjpeg < "$i" > "$tmp" ;;
	*.jpg)	djpeg -pnm < "$i" > "$tmp" ;;
	*)	cjpeg < "$i" > "$tmp" ;;
    esac
    if [ $? != 0 ]
    then
	rm -f "$tmp"
	xit=1
    else
	if [ -n "$fflag" -o ! -s "$j" ]
	then
	    echo " -> $j" >&2
	    cat "$tmp" > "$j" && rm -f "$tmp" "$i" && echo >&2 \
		|| xit=$?
	else
	    if cmp "$tmp" "$j"
	    then
		echo ", same as $j; $i removed" >&2
		rm -f "$tmp" "$i" && echo >&2 || xit=$?
	    else
		echo "$tmp and $j differ, discarding $tmp, $i remains" >&2
		rm -f "$tmp" && echo >&2
		xit=1
	    fi
	fi
    fi
done

exit $xit
