#!/bin/ksh

# wpic - Prepare a picture scanned to a TIFF file for use on a Web Page
#
# This script normalizes (color corrects) the original scan then makes
# jpeg format copies at the original size and at SCALE (0.4) of the
# original size. The jpeg files are left in DESTDIR and are tagged
# with the ICC profile used in the normalization step.

# This script has to work around a number of bugs.

DESTDIR=${DESTDIR:-/d2/voyage/pictures}
# Profile to use for normalization
NORM_PROFILE=genrgb.pf
QUALITY=90
SCALE=0.4
TMPDIR=${TMPDIR:-/var/tmp}
USAGE="Usage: $0 [-d destdir] [-n norm_profile] [-q quality] [-s scale] file ..."

while getopts d:n:q:s: f
do
    case $f in
        d) DESTDIR=$OPTARG;;
        n) NORM_PROFILE=$OPTARG;;
        q) QUALITY=$OPTARG;;
        s) SCALE=$OPTARG;;
        -) break;;
        \?) echo $USAGE; exit 2;; 
    esac
done
shift `expr $OPTIND - 1`

if [ $# = "0" ]
then
    echo $USAGE
    exit 2
fi

for i in $*
do
    head=${i##*/}
    head=${head%.*}
    # Color correct the tiff file
    cocostiff -d $NORM_PROFILE -o $head.coco.tif $i
    mv $head.coco.tif $i
    # Make the full size jpeg image
    # Redirect the stiff file warnings from the 6.2 imgcopy to /dev/null.
    imgcopy -q ${QUALITY} $i ${DESTDIR}/$head.jpg > /dev/null 2>&1
    # Make small image
    # Redirect the stiff file warnings from imgscale to /dev/null.
    imgscale 0.4 $i ${TMPDIR}/${head}-sm.tif > /dev/null 2>&1
    # Convert to jpeg
    # Redirect the imgcopy warning about converting to a jpeg file
    # to /dev/null.
    imgcopy -q ${QUALITY} ${TMPDIR}/${head}-sm.tif ${DESTDIR}/${head}-sm.jpg > /dev/null 2>&1
    rm ${TMPDIR}/${head}-sm.tif
    # tag output files with color profile since imgcopy is clueless
    # about color management.
    # cmstagjpeg crashes (IRIX 6.[23]) when given a long file name in a
    # different filesystem from where it is running; cd to reduce the risk. 
    cd $DESTDIR
    cmstagjpeg -s $NORM_PROFILE $head.jpg
    cmstagjpeg -s $NORM_PROFILE $head-sm.jpg
done
