#!/bin/bash

# Written by Ivan Toman, 2008
#
# tif2jpg v0.1
#
# please, report any bugs or suggested improvements to:
# ivtoman@inet.hr


#
# Usage:
#
# 1. put this script into your path; eg. /usr/local/bin
# 2. chmod +x /usr/local/bin/tif2jpg
# then....
# cd into directory where your tif images are and issue command
#
# tif2jpg
#
# to auto-process all images in directory, or
#
# tif2jpg -h
#
# to get help with available parameters
#


#
# Script dependencies
######################
#
# For this script to function, you need to install these dependencies:
#
# bash (obviously?)                             http://www.gnu.org/software/bash/
# imagemagick                                   http://www.imagemagick.org/
# exiftool                                      http://www.sno.phy.queensu.ca/~phil/exiftool/
# binomial and/or laplacian scripts             http://www.fmwconcepts.com/imagemagick/
#
#
# Many thanks to Fred Weinhaus for creating great imagemagick scripts that tif2jpg use
# for image sharpening purporses


#                          #
##                        ##
# Start of defaults config #
##                        ##
#                          #

# Set defaults below
#

##############
# PROCESSING #
##############

# Sigmoidal contrast
# Not enabled by default, activate it by giving argument -c when invoking script
# if you wish to get little more "pop". You can customize here how much to boost contrast
# For parameter explanation consult imagemagick manual
SCTRT="2.5x50%"


############
# RESIZING #
############

# Resizing image width in pixels
WIDTH="660"

# Resampling filter:
# Recommended filters are Lanczos, Sinc or Mitchell, for little sharper result you can try Box or Blackman
# and for little softer image try Cubic. These are only examples, there are lot of other filters in imagemagick
# Uncomment only one option
#RFILTER="Lanczos"
RFILTER="Sinc"
#RFILTER="Mitchell"
#RFILTER="Box"
#RFILTER="Blackman"
#RFILTER="Cubic"

# Resampling filter support
# should be normally left on 1. for sharper resizing use less than 1 (say 0.8), for softer
# resizing more than 1 (say 1.2). Do not set extreme values
SUPPORT="1"


##############
# SHARPENING #
##############

# Sharpening method: binomial, laplacian or usm
# Best option is probably binomial; usm is imagemagick's classic unsharp mask and is not good as binomial or laplacian
# methods that are highpass filters and usually give excellent results. Laplacian is not the best for noisy images.
# You MUST have binomial and laplacian scripts in your path to use them! Download them here:
# http://www.fmwconcepts.com/imagemagick/
# Uncomment only one option
SHRPMTD="binomial"
#SHRPMTD="laplacian"
#SHRPMTD="usm"

# Mixing percent with original image: useful values between 40 and 60
# try 50 for starting point, then fine-tune. Larger values give stronger sharpening effect
# but keep in mind that values over 65 cause TOO MUCH artifacts!
MIXIMG="55"

# If sharpening method is "binomial", this parametet is also used for it.
# Here you can define width of square filter that can be 3, 5 or 7
BINWDTH="5"


##############
# CONVERTING #
##############

# jpeg quality:
JQUALITY="96"

# Make also jpegs with borders (frames) around images
# set to 0 to disable
# Functions that create borders are, for now, located at very bottom of this script. If you wish to edit border
# to your liking, you need to make your changes there.
BORDERED="1"


########
# EXIF #
########

# Put YOUR name and copyright information here,
# this is just an example:
ARTIST="Ivan Toman"
COPYRIGHT="(c)2008 Ivan Toman www.meteoadriatic.net"

# End of defaults config
# Usually, no need to change anything below this line
######################################################
######################################################


# Calculations

ADAPTIVE=0
VERBOSE=0
HELP=0
PDEFAULTS=0
SCONTRAST=0
LEAVE=0

while getopts ":acdhlM:Q:P:vW:" options; do
  case $options in
    a ) ADAPTIVE=1;;
    c ) SCONTRAST=1;;
    d ) PDEFAULTS=1;;
    h ) HELP=1;;
    l ) LEAVE=1;;
    M ) MIXIMG=$OPTARG;;
    P ) APPENDIX=$OPTARG;;
    Q ) JQUALITY=$OPTARG;;
    v ) VERBOSE=1;;
    W ) WIDTH=$OPTARG;;
  esac
done

if [ "$HELP" = '1' ]
then
echo
echo "USAGE:"
echo "First cd into directory that contains tif images, then execute: "
echo 
echo "tif2jpg (-adhlv) (-M mix) (-P appendix) (-W width)"
echo 
echo "where options are:"
echo "a : turn on adaptive resize"
echo "c : turn on sigmoidal contrast enhancing"
echo "d : print default parameters and exit"
echo "h : print this help message"
echo "l : do not delete finalized tif images"
echo "v : verbose mode"
echo
echo "M mix        : set mixing percent with original image"
echo "               when highpass sharpening (usable range 40-60)"
echo "Q quality    : set jpg quality"
echo "P appendix   : set directory appendix (eg: jpg4web_800_somestring)"
echo "               if you give '-P _somestring'"
echo "W width      : set image width in pixels"
echo
echo "You don't have to give any argument to script,"
echo "in that case all defaults will be used"
echo
echo "Read script itself for deeper explanations"
echo
exit 1
fi

if [ "$SHRPMTD" = 'binomial' ]
then
SHRPCMD="$SHRPMTD -w $BINWDTH -m $MIXIMG"
else
if [ "$SHRPMTD" = 'laplacian' ]
then
SHRPCMD="$SHRPMTD -m $MIXIMG"
else
SHRPCMD="convert -unsharp 0x1.5+0.7"
fi
fi

if [ "$SCONTRAST" = '0' ]; then SCTRT="not activated"; fi


echo
echo "Starting automated image converter script for web"
echo "--------------------------------------------------"
echo
echo "May take lot of time, depending on number of images"
echo "and your system speed"
if [ "$VERBOSE" = '1' ]
then
echo
echo "Verbose output activated"
echo 
echo "Version tif2jpg 0.1"
fi
echo
echo

if [ "$VERBOSE" = '1' ] || [ "$PDEFAULTS" = '1' ]
then
echo "Parameters"
echo ":::::::::::"
echo 
echo "sigmoidal-contrast:               " $SCTRT
echo "Image width in pixels:            " $WIDTH
echo "adaptive-resize flag:             " $ADAPTIVE
echo "Resampling filter:                " $RFILTER
echo "Resampling filter support:        " $SUPPORT
echo "Sharpening method:                " $SHRPMTD
echo "Sharpening mixing percent:        " $MIXIMG
echo "jpeg quality:                     " $JQUALITY
echo "Leave tif flag:           " $LEAVE
echo "Directory appendix:               " $APPENDIX
echo
echo
echo
fi

if [ "$PDEFAULTS" = '1' ]; then exit 1; fi;

# process tif files

if [ ! -d ./tmp ]; then mkdir ./tmp; fi;

if [ "$VERBOSE" = '1' ]
then
echo
echo "Image processing and resizing... be patient..."
echo "-----------------------------------------------"
echo 
fi

for f in *.tif;
do
        echo "Processing $f"
if [ "$ADAPTIVE" = '0' ]
then
        if [ "$SCONTRAST" = '0' ]
        then
        convert $f \
                -enhance \
                -filter $RFILTER \
                -support $SUPPORT \
                -resize $WIDTH \
                tmp/$f
        else
        convert $f \
                -enhance \
                -sigmoidal-contrast $SCTRT \
                -filter $RFILTER \
                -support $SUPPORT \
                -resize $WIDTH \
                tmp/$f
        fi
        
else
        if [ "$SCONTRAST" = '0' ]
        then
        convert $f \
                -enhance \
                -filter $RFILTER \
                -support $SUPPORT \
                -adaptive-resize $WIDTH \
                tmp/$f
        else
        convert $f \
                -enhance \
                -sigmoidal-contrast $SCTRT \
                -filter $RFILTER \
                -support $SUPPORT \
                -adaptive-resize $WIDTH \
                tmp/$f
        fi
fi
done
echo

# sharpening

if [ ! -d ./tmp2 ]; then mkdir ./tmp2; fi;

if [ "$VERBOSE" = '1' ]
then
echo
echo "Sharpening resized images with command: "
echo $SHRPCMD
echo "-----------------------------------------"
echo
fi

cd tmp

for f in *.tif;
do
        echo "Sharpening $f"
if [ "$SHRPMTD" = 'usm' ]
then
        $SHRPCMD $f \
                ../tmp2/$f > /dev/null 2>&1
                rm ../tmp2/*tif-1* > /dev/null 2>&1
else
        $SHRPCMD \
                -m $MIXIMG \
                $f \
                ../tmp2/$f > /dev/null 2>&1
                rm ../tmp2/*tif-1* > /dev/null 2>&1
fi
done
echo
cd ..


# convert to jpg without adding frame

if [ ! -d ./jpg4web_$WIDTH$APPENDIX ]; then mkdir ./jpg4web_$WIDTH$APPENDIX; fi;

if [ "$VERBOSE" = '1' ]
then
echo
echo "Converting and saving images to jpg"
echo "------------------------------------"
echo 
fi

cd tmp2

for f in *.tif;
do
        echo "Converting $f to jpg"
        convert $f \
                -quality $JQUALITY \
                -sampling-factor 1x1 \
                -interlace line \
                ../jpg4web_$WIDTH$APPENDIX/$f.jpg
                rm ../jpg4web_$WIDTH$APPENDIX/*tif-1* > /dev/null 2>&1
        if [ "$VERBOSE" = '1' ]
        then
        echo "Updating $f exif information"
        fi
                exiftool \
                        -overwrite_original \
                        -artist="$ARTIST" \
                        -copyright="$COPYRIGHT" \
                        ../jpg4web_$WIDTH$APPENDIX/$f.jpg  > /dev/null 2>&1
done
echo
cd ..

#
# Make frames around images
#
#############################
# convert to jpg with frame

if [ "$BORDERED" = '1' ]
then

if [ ! -d ./jpg4web_$WIDTH$APPENDIX/bordered ]; then mkdir ./jpg4web_$WIDTH$APPENDIX/bordered; fi;

cd tmp2

for f in *.tif;
do
        echo "Converting $f to jpg with border"
        convert $f \
                -border 2x2 -bordercolor "rgb(255,255,255)" \
                -border 2x2 -bordercolor "rgb(0,0,0)" \
                -border 2x2 -bordercolor "rgb(255,255,255)" \
                -quality $JQUALITY \
                -sampling-factor 1x1 \
                -interlace line \
                ../jpg4web_$WIDTH$APPENDIX/bordered/$f.jpg
                rm ../jpg4web_$WIDTH$APPENDIX/bordered/*tif-1* > /dev/null 2>&1
        if [ "$VERBOSE" = '1' ]
        then
        echo "Updating $f exif information"
        fi
                exiftool \
                        -overwrite_original \
                        -artist="$ARTIST" \
                        -copyright="$COPYRIGHT" \
                        ../jpg4web_$WIDTH$APPENDIX/bordered/$f.jpg  > /dev/null 2>&1
done
cd ..

fi

echo
echo

if [ "$VERBOSE" = '1' ]
then
echo "Clearing temporary files..."
fi
rm -fR tmp
        if [ "$LEAVE" = '1' ]
        then
        mv tmp2 tif_$WIDTH$APPENDIX
        else
        rm -fR tmp2
        fi

echo "All jobs finished"
echo