#!/bin/sh

USAGE='
Usage: brewtool [command] [options] <image-files>

  A simple bash shell script for various manipulations of image-files. Sets color 
  profile to sRGB or Adobe. Option to copy all EXIF-metatags from alternative 
  file source if exist. GIMP image format (xcf) as input implies copy EXIF from parent 
  and save to jpeg by default.

  Depends on ImageMagick, exiftool, and awk.

  Copyright © Daniel Ljunggren <foto@demulsion.se>. Version 0.32, 2008 - 2015.

[commands]:
  unsharp              : apply unsharp mask (everything else preserved)
  4K                   : prepare image for UHD 4K at min size 2160 px preserved ratio (unsharp, sRGB, save jpeg)
  web                  : prepare image for web max size 1200 px (unsharp, sRGB, save jpeg)
  thumbS|thumbM|thumbL : prepare thumb at size 150/250/350 px (unsharp, sRGB, save jpeg)
  getty                : prepare image for gettyimages 5017px (tiny unsharp, sRGB, save jpeg)
                       : use no command when applying only options (default)

[options]:
  -profile <value>     : set/convert colorspace to "Adobe" or "sRGB"
  -size <value>        : max image size in pixels (max height or width)
  -height              : size specifies max height
  -width               : size specifies max width
  -sharp <value>       : sharpening value (default 1.0)
  -gray                : convert to gray
  -shadow              : add drop shadow to image
  -signature           : overlay signature on image
  -byline              : overlay byline on image
  -oleft               : overlay in lower-left corner (lower-right default)
  -obn <value>         : overlay brighness variation in percentage (default 50)
  -square              : image or thumb in centered square format
  -q <value>           : jpeg quality in percent (default 98%)
  -jpeg|-tiff|-png     : save as jpeg, tiff or png

  -noexif              : do not save EXIF-tags
  -tagsfile <file>     : copy EXIF-tags from file
  -tagsparent          : copy EXIF-tags from parent file (_r??.xxx) if exists
  -tagsraw             : copy EXIF-tags from raw-file (.cr2) if exists
  -orienttag <value>   : set EXIF-tag Orientation to "normal" (0), "left" (270 CW),
                         "right" (90 CW), or "upside" (180 CW).
  -cameraorienttag     : set EXIF-tag CameraOrientation to Orientation
  -title <string>      : set tags IPTC:ObjectName and XMP:Title
  -descripion <string> : set tags EXIF:ImageDescription and IPTC:Caption-Abstract, and XMP:Description
  -comment <string>    : set tags EXIF:UserComment and Comment
  -o                   : overwrite existing file 
  -nosw                : do not owerwrite tag EXIF:Software
'

CHANGELOG='
Changelog: brewtool
151207: v0.32  # Adapting thumb and web image sizes for 4K monitors by doubling their sizes. 

150201: v0.31  # New command "4K" replacing command "small".

140411: v0.30  # Unsharp and gray is now done in CIELab color space using luminescence channel.
               # Gray is now option instead of command

140404: v0.29  # Fixes with -CameraOrientation and -Orientation

140310: v0.28  # Added tags for title and description for EXIF, IPTC, and XMP.

140111: v0.27  # Fixed GIMP files input color profile. Tags from input file always copied to 
                 output file after copying tags from optional tag file.

131128: v0.26  # Added thumbL

110502: v0.25  # Added option -cameraorienttag (TODO: only if Orientation set)

101215: v0.24  # Added EXIF tag Software containing also command line.

101123: v0.23  # Added option -square

101118: v0.22  # Added option -byline, -oleft, and -obn

101114: v0.21  # Added option -tagsparent

101020: v0.20  # Added option -signature

101012: v0.19  # Added option -shadow

090719: v0.18  # Added option -comment.

090203: v0.17  # Split "thumb" command into "thumbS" and "thumbM".

090116: v0.16  # Added "getty" command.

081206: v0.15  # Added "thumb" command, and png.

081130: v0.14  # Decreased amount of unsharpening for "web"; changed RSBASE from 4.0 to 3.0. 

081104: v0.13  # Changed so that tags are copied from original file on default, and removed 
                 convertion to sRGB for "unsharp", added option -profile.

081019: v0.12  # Added "web" save default to jpeg

080914: v0.11  # Added option orienttag, and corrected bugs.

080526: v0.10  # Started combining several different scripts into one.

'

#######################################
# SYSTEM DEPENDENT FILES
ICCCATALOG="/usr/share/color/icc/"
SRGB_PROFILE="${ICCCATALOG}/sRGB.icc"
ARGB_PROFILE="${ICCCATALOG}/AdobeRGB1998.icc"
GRAY_PROFILE="${ICCCATALOG}/CaptureOne/PhaseOneEffects-B&W.icm"
CIELAB_PROFILE="${ICCCATALOG}/lcms/Lab.icc"
SIGNATUREFILE="/home/daniellj/Foto/signature/signature.png" #"/data/FotoBanken/signature/signature.png"
BYLINEFILE="/home/daniellj/Foto/signature/byline.png"       #"/data/FotoBanken/signature/byline.png"
#######################################

# Default values:
SOFTWARE="brewtool v0.32 [brewtool $@]"
COMMAND=""
OVRWRT=false
NOSW=false
QUALITY=98
NEWSIZE=""
SHARP=1.0
RSBASE=1.5
ABASE=1.0
NOEXIF=""
SUFFIX=""
ORIENTTAG=""
TITLETAG=""
DESCRIPTIONTAG=""
COMMENTTAG=""
COPYRIGHTSWITCH="-v0" # Needs to use dummy command here, otherwise exiftool treats empty space as 'file not found' (!)
ARTISTSWITCH="-v0"    # Needs to use dummy command here, otherwise exiftool treats empty space as 'file not found' (!)
AUTHORSWITCH="-v0"    # Needs to use dummy command here, otherwise exiftool treats empty space as 'file not found' (!)
SIZEDIM="max"
COLORPROFILE=""
INPROFILE_SWITCH=""
OUTPROFILE_SWITCH=""
COLORSPACETAG="--InteropIndex --ColorSpace"
RESIZE=""
UNSHARP=""
TAGS="orig"
GRAY=""
RAWFILE=false
SHADOW=false
SIGNATURE=false
BYLINE=false
GRAVITY=southeast
BRIGHTNESS=50
SQUARE=false


while [ $# -gt 0 ]
do
    case "$1" in
	web)
	    COMMAND="web"
	    EXTENSION=JPEG
	    RSBASE=4.5
	    ABASE=1.0
	    NEWSIZE=1200
	    COLORPROFILE=sRGB
	    #SIGNATURE=true
	    ;;
	thumbS)
	    COMMAND="thumb"
	    EXTENSION=JPEG
	    RSBASE=7.5
            ABASE=2.0
	    NEWSIZE=150 # old 75
	    COLORPROFILE=sRGB
            SUFFIX="_thb"
	    ;;
	thumbM)
	    COMMAND="thumb"
	    EXTENSION=JPEG
	    RSBASE=7.5
            ABASE=2.0
	    NEWSIZE=250 # old 125
	    COLORPROFILE=sRGB
            SUFFIX="_thb"
	    ;;
	thumbL)
	    COMMAND="thumb"
	    EXTENSION=JPEG
	    RSBASE=7.5
            ABASE=2.0
	    NEWSIZE=350 # old 175
	    COLORPROFILE=sRGB
            SUFFIX="_thb"
	    ;;
	4K)
	    COMMAND="uhd4k"
	    EXTENSION=JPEG
	    RSBASE=3
	    ABASE=1.0
	    NEWSIZE=2160
	    COLORPROFILE=sRGB
	    SIZEDIM=min
	    ;;
	unsharp)
	    COMMAND="unsharp"
	    SUFFIX="_usm"
	    ;;
        getty)
            COMMAND="getty"
	    EXTENSION=JPEG
	    RSBASE=1.5
	    ABASE=0.5
	    NEWSIZE=5017
	    COLORPROFILE=sRGB
            SUFFIX="_getty"
	    ;;
	-gray)
	    # Best is to use CIELab color space using luminescence channel
	    GRAY="-profile ${CIELAB_PROFILE} -channel R -separate +channel -type truecolor"
	    #GRAY="-profile ${GRAY_PROFILE} -type truecolor"
	    #GRAY="-type Grayscale -type truecolor"
	    ;;
	-profile)
	    COLORPROFILE=$2
	    shift 1
	    ;;
        -o)
  	    OVRWRT="true"
            ;;
	-nosw)
  	    NOSW="true"
            ;;
	-sharp)	  
            SHARP=$2	
	    shift 1	
            ;;	
	-tiff)	
            EXTENSION=TIFF
            ;;
	-jpeg)
            EXTENSION=JPEG
            ;;
        -png)
            EXTENSION=PNG
            ;;
	-q)
	    QUALITY=$2
	    shift 1
	    ;;
	-shadow)
	    SHADOW=true
	    ;;
	-signature)
	    SIGNATURE=true
	    ;;
	-byline)
	    BYLINE=true
	    ;;
	-obn)
	    BRIGHTNESS=$2
	    shift 1
	    ;;
	-square)
	    SQUARE=true
	    ;;
	-oleft)
	    GRAVITY=southwest
	    ;;
	-size)
	    NEWSIZE=$2
	    shift 1
	    ;;
	-height)
	    SIZEDIM=height
	  ;;
	-width)
	    SIZEDIM=width
	  ;;
	-noexif)
	    NOEXIF="-All="
	    ;;
	-tagsfile)
	    TAGFILENAME=$2
	    TAGS="file"
	    shift 1
	    ;;
	-tagsraw)
	    TAGS="raw"
	    ;;
	-tagsparent)
	    TAGS="parent"
	    ;;
	-orienttag)
	    ORIENTTAG=$2
	    shift 1
	    ;;
	-cameraorienttag)
	    CAMORIENTTAG=true
	    ;;
	-title)
	    TITLETAG=$2
	    shift 1
	    ;;
	-description)
	    DESCRIPTIONTAG=$2
	    shift 1
	    ;;
	-comment)
	    COMMENTTAG=$2
	    shift 1
	    ;;
	-*)
	    echo "$USAGE" 1>&2
	    exit 1
	    ;;
	*)
            break
	    ;;
    esac
    shift 1
done

if [ $# -eq 0 ]; then echo "${USAGE}"; fi

case "${COLORPROFILE}" in
    Adobe)
	COLORSPACETAG="-InteropIndex=R03 -ColorSpace=Uncalibrated"
	OUTPROFILE_SWITCH="-profile ${ARGB_PROFILE}"
	;;
    sRGB)
	COLORSPACETAG="-InteropIndex=R98 -ColorSpace=sRGB"
	OUTPROFILE_SWITCH="-profile ${SRGB_PROFILE}"
	;;
esac

case "$COMMAND" in
    web)
	SUFFIX="_www_${NEWSIZE}"
	;;
    uhd4k)
	SUFFIX="_4K"
	#SUFFIX="_${NEWSIZE}"
	;;
esac

# Define a calculator with max() and min() based on awk 
function calc () {
    awk "function max(a, b) { if (a > b) {return a} else {return b} };
               function min(a, b) { if (a < b) {return a} else {return b} };
               BEGIN { print $* ; }"
}
MAX="define max(x,y){if (x > y) return(x); return(y);}"
MIN="define min(x,y){if (x > y) return(y); return(x);}"

# Returns OK if $1 contains $2
strstr() {
    [ "${1#*$2*}" = "$1" ] && return 1
    return 0
}

for FILE 
do
    if [ -e "$FILE" ]; then
	case "$FILE" in
	    *.jpg)
		ORIG_EXT=jpg
		NEW_EXT=jpg
	    	;;
	    *.jpeg)
		ORIG_EXT=jpeg
		NEW_EXT=jpg
	    ;;
	    *.JPG)
		ORIG_EXT=JPG
		NEW_EXT=jpg
	    ;;
	    *.JPEG)
		ORIG_EXT=JPEG
		NEW_EXT=jpg
	    ;;
	    *.tif)
		ORIG_EXT=tif
		NEW_EXT=tif
		;;
	    *.tiff)
		ORIG_EXT=tiff
		NEW_EXT=tif
		;;
	    *.TIF)
		ORIG_EXT=TIF
		NEW_EXT=tif
		;;
	    *.TIFF)
		ORIG_EXT=TIFF
		NEW_EXT=tif
		;;
            *.PNG)
		ORIG_EXT=PNG
		NEW_EXT=png
		;;
            *.png)
		ORIG_EXT=png
		NEW_EXT=png
		;;
	    *.xcf)
		ORIG_EXT=xcf
		NEW_EXT=xcf
		;;
            *.XCF)
		ORIG_EXT=XCF
		NEW_EXT=xcf
		;;
	    *.raw)
		ORIG_EXT=raw
		RAWFILE=true
		;;
	    *.RAW)
		ORIG_EXT=RAW
		RAWFILE=true
		;;
	    *.crw)
		ORIG_EXT=crw
		RAWFILE=true
		;;
	    *.CRW)
		ORIG_EXT=CRW
		RAWFILE=true
		;;
	    *.cr2)
		ORIG_EXT=cr2
		RAWFILE=true
		;;
	    *.CR2)
		ORIG_EXT=CR2
		RAWFILE=true
		;;
	    *.DNG)
		ORIG_EXT=DNG
		RAWFILE=true
		;;
	    *.dng)
		ORIG_EXT=dng
		RAWFILE=true
		;;
	    *.pef)
		ORIG_EXT=pef
		RAWFILE=true
		;;
	    *.PEF)
		ORIG_EXT=PEF
		RAWFILE=true
		;;
	    *)
		echo "brewtool ${COMMAND}: Can't handle file '$FILE', only JPEG, TIFF, PNG, XCF, and raw-formats are valid files, skipping" 1>&2
		continue
	    ;;
	esac

	PROFILE=`exiftool -ProfileDescription ${FILE} | cut -b35-`
	XCFTOOL="";

	# Set default output color profile same as input profile
	if [ -z ${COLORPROFILE} ]; then
	    if [ "${PROFILE}" == "Adobe RGB (1998)" ]; then
		COLORSPACETAG="-InteropIndex=R03 -ColorSpace=Uncalibrated"
		OUTPROFILE_SWITCH="-profile ${ARGB_PROFILE}"
	    else
		COLORSPACETAG="-InteropIndex=R98 -ColorSpace=sRGB"
		OUTPROFILE_SWITCH="-profile ${SRGB_PROFILE}"
	    fi
	fi

	# Set input color profile for GIMP images
	if [ "${ORIG_EXT}" == "XCF" ] || [ "${ORIG_EXT}" == "xcf" ]; then
	    if [ "${PROFILE}" == "Adobe RGB (1998)" ]; then
		INPROFILE_SWITCH="-profile ${ARGB_PROFILE}"
	    else #elif [ "${PROFILE}" == "sRGB" ] || [ "${PROFILE}" == "sRGB IEC61966-2.1" ]; then
		INPROFILE_SWITCH="-profile ${SRGB_PROFILE}"
	    fi
	    if [ $TAGS == "orig" ]; then
		TAGS="parent"  # GIMP doesnt keep EXIF information, so copy from parent
	    fi
	    if [ -z "${EXTENSION}" ]; then
		NEW_EXT=jpg  # Set default save format as imagemagick cannot save to xcf
	    fi
	    # WORKAROUND for bug in ImageMagick 6.7.8-9 reading XCF file format and giving dark image, fixed in version after 6.8.7-5. 
	    #XCFTOOL="xcf2pnm -a /dev/null ${FILE} " 
	    XCFTOOL="xcf2pnm ${FILE} "
	fi
	
	# Force output file format.
        case "${EXTENSION}" in
	    "");;
	    JPEG) NEW_EXT=jpg;;
	    TIFF) NEW_EXT=tif;;
            PNG)  NEW_EXT=png;;
	esac

	# Add dropshadow
	if [ ${SHADOW} == "true" ]; then
	    DROPSHADOW="( +clone -background black -shadow 80x3+6+6% ) +swap -background none -layers merge +repage"
	else
	    DROPSHADOW=""
	fi
	
	# Add overlay signature
	if [ ${SIGNATURE} == "true" ]; then
	    SIGNATURESWITCH="( ${SIGNATUREFILE} -modulate ${BRIGHTNESS} ) -gravity ${GRAVITY} -composite"
	   #SIGNATURESWITCH="-stroke white -pointsize 12  -gravity southeast -annotate 0 daniel"
	   #SIGNATURESWITCH="-compose hardlight -gravity SouthEast ${SIGNATUREFILE} -composite"
	else
	    SIGNATURESWITCH=""
	fi

	# Add overlay byline
	if [ ${BYLINE} == "true" ]; then
	    BYLINESWITCH="( ${BYLINEFILE} -modulate ${BRIGHTNESS} ) -gravity ${GRAVITY} -composite"
	else
	    BYLINESWITCH=""
	fi

	# Find original image size (-CanonImageXXXXX is always landscape size!)
	#WIDTH=`exiftool -CanonImageWidth ${FILE} | cut -b35-`
	#if [ "${WIDTH}" == "" ]; then
	WIDTH=`exiftool -ImageWidth ${FILE} | cut -b35-`
	#fi
	#HEIGHT=`exiftool -CanonImageHeight ${FILE} | cut -b35-`
	#if [ "${HEIGHT}" == "" ]; then
	HEIGHT=`exiftool -ImageHeight ${FILE} | cut -b35-`
	#fi

	RATIO=$(echo "scale=6; ${WIDTH}/${HEIGHT}" | bc -l)
	MIN_SIZE=$(echo "${MIN}; min(${WIDTH},${HEIGHT})" | bc -l)

	# Set image to square format of size MIN_SIZE
	if [ ${SQUARE} == "true" ]; then
	    SHAVE_WIDTH=$(echo "scale=0; (${WIDTH} - ${MIN_SIZE})/2" | bc -l)
	    SHAVE_HEIGHT=$(echo "scale=0; (${HEIGHT} - ${MIN_SIZE})/2" | bc -l)
	    WIDTH=${MIN_SIZE}
	    HEIGHT=${MIN_SIZE}
	    SQUARESWITCH="-shave ${SHAVE_WIDTH}x${SHAVE_HEIGHT}!"
	else
	    SQUARESWITCH=""
	fi

	# Calculate new max and min size.
	MAX_SIZE=$(echo "${MAX}; max(${WIDTH},${HEIGHT})" | bc -l)
	MIN_SIZE=$(echo "${MIN}; min(${WIDTH},${HEIGHT})" | bc -l)

	# Set new image size, and calculate new min size.
	if [ ! -z ${NEWSIZE} ]; then
	    if [ ${SIZEDIM} == "height" ]; then
		RESIZE="-filter Lanczos -resize x${NEWSIZE}"
		MAX_SIZE=$(echo "${MAX}; scale=0; max(${NEWSIZE},${NEWSIZE}*${RATIO})" | bc -l)
		MIN_SIZE=$(echo "${MIN}; scale=0; min(${MAX_SIZE}*${RATIO},${MAX_SIZE}/${RATIO})" | bc -l)
	    elif [ ${SIZEDIM} == "width" ]; then
		RESIZE="-filter Lanczos -resize ${NEWSIZE}"
	        MAX_SIZE=$(echo "${MAX}; scale=0; max(${NEWSIZE},${NEWSIZE}/${RATIO})" | bc -l)
		MIN_SIZE=$(echo "${MIN}; scale=0; min(${MAX_SIZE}*${RATIO},${MAX_SIZE}/${RATIO})" | bc -l)
	    elif [ ${SIZEDIM} == "min" ]; then
		RESIZE="-filter Lanczos -resize ${NEWSIZE}x${NEWSIZE}^"
		MAX_SIZE=$(echo "${MAX}; scale=0; max(${NEWSIZE}*${RATIO},${NEWSIZE}/${RATIO})" | bc -l)
		MIN_SIZE="${NEWSIZE}"
	    else # sizedim = max
		RESIZE="-filter Lanczos -resize ${NEWSIZE}x${NEWSIZE}"
		MAX_SIZE="${NEWSIZE}"
		MIN_SIZE=$(echo "${MIN}; scale=0; min(${MAX_SIZE}*${RATIO},${MAX_SIZE}/${RATIO})" | bc -l)
	    fi
	fi

	# Unsharp parameters.
	RADIUS=$(echo "scale=2; ${MIN_SIZE}*${RSBASE}/4368" | bc -l)
	SIGMA=$(echo "scale=2; ${MIN_SIZE}*${RSBASE}/4368" | bc -l)
	AMOUNT=$(calc "${SHARP}*${ABASE}")
	THRESHOLD=0.0
	UNSHARP_VALUE="${RADIUS}x${SIGMA}+${AMOUNT}+${THRESHOLD}"
	
	if [ ! -z ${COMMAND} ]; then 
	    if [ ${COMMAND} == "web" ] || [ ${COMMAND} == "uhd4k" ] || [ ${COMMAND} == "unsharp" ] || [ ${COMMAND} == "getty" ]; then
		echo "brewtool ${COMMAND}: Unsharp filtering: radius=$RADIUS x sigma=$SIGMA" \
		    "+amount=${AMOUNT} +threshold=${THRESHOLD}"
		#UNSHARP="-unsharp ${UNSHARP_VALUE}"
		UNSHARP="-profile ${CIELAB_PROFILE} -channel R -unsharp ${UNSHARP_VALUE} +channel"
	    fi
	elif [ ! -z ${COLORPROFILE} ]; then
	    COMMAND="convert" # Must run convert to change color profile
	else
	    NEW_EXT=${ORIG_EXT}  # We only manipulate exif-info on original file.
	fi

	if [ ! -z ${COMMAND} ] && [ ${RAWFILE} == "true" ]; then
	    echo "brewtool: Can't perform operation on image raw-file, skipping..." 1>&2
	    exit 1  # Should only exit 'for FILE do'-loop and jump to next FILE, howto?
	fi

	# Force 8-bit output for 8-bit input bit-depth.
	DEPTH=""
	if [ ${RAWFILE} != "true" ]; then
	    MATCH=`identify -quiet $FILE`
	    BIT8=`expr "${MATCH}" : ".*\(8-bit\).*"`
	    if [ ! -z ${BIT8} ] && [ ${BIT8} == "8-bit" ]; then
		DEPTH="-depth 8"
	    fi
	fi

	DIR=`dirname $FILE`
	BASE=`basename $FILE .$ORIG_EXT`
	NEW_FILE="${BASE}${SUFFIX}.${NEW_EXT}"
	#NEW_FILE="${DIR}/${BASE}${SUFFIX}.${NEW_EXT}"

	# Set file for EXIF-tag information.
	case "${ORIENTTAG}" in
	    "")
		ORIENTSWITCH="";;
	    right)
		ORIENTSWITCH="-Orientation#=6";;
	    left)
		ORIENTSWITCH="-Orientation#=8";;
	    normal)
		ORIENTSWITCH="-Orientation#=1";;
	    upside)
		ORIENTSWITCH="-Orientation#=3";;
	esac

	# Exclude EXIF tags from being copied
	EXIFEXCLUDESWITCH="--XResolution --YResolution --InteropIndex --ColorSpace" # -XMP:all=
	[[ -z ${ORIENTTAG} ]] && EXIFEXCLUDESWITCH="--Orientation ${EXIFEXCLUDESWITCH}"
	EXIFTOOLSWITCH="${COLORSPACETAG} -DocumentName=${NEW_FILE}" #-XMP:all=

	# Set file for EXIF-tag CameraOrientation from Orientation.
	if [ "${CAMORIENTTAG}" == "true" ]; then 
	    echo "brewtool: Resetting CameraOrientation..."
	    CAMORIENTSWITCH="-CameraOrientation < Orientation"
	else
	    CAMORIENTSWITCH="-CameraOrientation"
	    EXIFEXCLUDESWITCH="--CameraOrientation ${EXIFEXCLUDESWITCH}"
	fi
	
	# Handle title, description, and comments field tags.
	if [ -z "${TITLETAG}" ]; then
	    # TITLESWITCH1="--DocumentName"
	    TITLESWITCH2="--IPTC:ObjectName"
	    TITLESWITCH3="--XMP:Title"
	else
	    # TITLESWITCH1="-DocumentName=${TITLETAG}" # -DocumentName is used by 'brewraw' for file name.
	    TITLESWITCH2="-IPTC:ObjectName=${TITLETAG}"
	    TITLESWITCH3="-XMP:Title=${TITLETAG}"
	fi

	if [ -z "${DESCRIPTIONTAG}" ]; then 
	    DESCRIPTIONSWITCH1="--ImageDescription"
	    DESCRIPTIONSWITCH2="--IPTC:Caption-Abstract"
	    DESCRIPTIONSWITCH3="--XMP:Description"
	else
	    DESCRIPTIONSWITCH1="-ImageDescription=${DESCRIPTIONTAG}"
	    DESCRIPTIONSWITCH2="-IPTC:Caption-Abstract=${DESCRIPTIONTAG}"
	    DESCRIPTIONSWITCH3="-XMP:Description=${DESCRIPTIONTAG}"
	fi

	if [ -z "${COMMENTTAG}" ]; then 
	    COMMENTSWITCH1="--UserComment"
	    COMMENTSWITCH2="--Comment"
	else
	    COMMENTSWITCH1="-UserComment=${COMMENTTAG}" # DigiKam calls this 'Caption' and optionally syncs it with Description tags
	    COMMENTSWITCH2="-Comment=${COMMENTTAG}"
	fi

	# Copy author and copyright information from EXIF to XMP fields 
	COPYRIGHT=`exiftool -Copyright $FILE | cut -b35-`
	OWNERNAME=`exiftool -OwnerName $FILE | cut -b35-`

	COPYRIGHT_XMP=`exiftool -XMP:Copyright $FILE | cut -b35-`
	if [ -z "${COPYRIGHT_XMP}" ]; then
	    COPYRIGHTSWITCH="-XMP:Copyright=${COPYRIGHT}"
	fi

	ARTIST=`exiftool -Artist $FILE | cut -b35-`
	if [ -z "${ARTIST}" ]; then
	    ARTISTSWITCH="-Artist=${COPYRIGHT}"
	fi

	AUTHOR_XMP=`exiftool -XMP:Author $FILE | cut -b35-`
	if [ -z "${AUTHOR_XMP}" ]; then
	    AUTHORSWITCH="-XMP:Author=${OWNERNAME}"
	fi

	if [ -z "${COMMAND}" ] || [ "${NOSW}" == "true" ]; then 
	    SOFTWARESWITCH="--Software"
	else
	    SOFTWARESWITCH="-Software=${SOFTWARE}"
	fi

	PREFILENAME=`expr $BASE : '\(.*[0-9][0-9][0-9][0-9][0-9][0-9]_[a-z][0-9][0-9][0-9][0-9]\).*$'`
	TAGFILENAMERAW="${DIR}/${PREFILENAME}.cr2"
	# Find parent filename for GIMP file format
	if [ "${ORIG_EXT}" == "XCF" ] || [ "${ORIG_EXT}" == "xcf" ]; then
	    if [ -r ${DIR}/${PREFILENAME}_r??.tif ]; then
		TAGFILENAMEPARENT="${DIR}/${PREFILENAME}_r??.tif"
	    elif [ -r ${DIR}/${PREFILENAME}_r??.jpg ]; then
		TAGFILENAMEPARENT="${DIR}/${PREFILENAME}_r??.jpg"
	    fi
	else
	    TAGFILENAMEPARENT="${DIR}/${PREFILENAME}_r??.${ORIG_EXT}"
	fi
	
	TAGSWITCH="" # Fallback when TAGS == "orig"
	MODEL=`exiftool -Model $FILE | cut -b35-`
	if [ $TAGS == "orig" ] && [ -z "${MODEL}" ]; then # Check if original file seems empty force parent
	    TAGS="parent"
	fi

	if [ $TAGS == "raw" ] && TAGFILENAME="${TAGFILENAMERAW}" && [ ! -z ${TAGFILENAMERAW} ] && [ -r ${TAGFILENAMERAW} ]; then
	    TAGSWITCH="-TagsFromFile ${TAGFILENAMERAW}"
	elif [ $TAGS == "parent" ] && TAGFILENAME="${TAGFILENAMEPARENT}" && [ ! -z ${TAGFILENAMEPARENT} ] && [ -r ${TAGFILENAMEPARENT} ]; then
            TAGSWITCH="-TagsFromFile ${TAGFILENAMEPARENT}"
        elif [ $TAGS == "parent" ] && [ ! -r ${TAGFILENAMEPARENT} ] && [ ! -z ${TAGFILENAMERAW} ] && [ -r ${TAGFILENAMERAW} ]; then
            TAGSWITCH="-TagsFromFile ${TAGFILENAMERAW}"
            TAGFILENAME="${TAGFILENAMERAW}"
	    echo "brewtool ${COMMAND}: WARNING! EXIF-tag source file '${TAGFILENAMEPARENT}' does not exist or is not readable! Falling back to '${TAGFILENAME}'..." 1>&2
	elif [ $TAGS == "file" ] && [ -r ${TAGFILENAME} ]; then
	    TAGSWITCH="-TagsFromFile ${TAGFILENAME}"
	#else
	#    TAGSWITCH="-TagsFromFile ${FILE}"
	#    if [ ! -z ${TAGFILENAME} ]; then
	#	echo "brewtool ${COMMAND}: WARNING! EXIF-tag source file '${TAGFILENAME}' does not exist! Falling back to ${FILE}..." 1>&2
	#    fi
	fi
	TAGSWITCH2="-TagsFromFile ${FILE} " # Always copy tags from input file to output file as a last step.

	#if [ ! -e ${TAGFILENAME} ]; then
	#    echo "brewtool ${COMMAND}: WARNING! EXIF-tag source file '${TAGSFILENAME}' does not exist! Skipping..." 1>&2
	#    break;
	#fi

	# Ask user for overwrite permissions.
	if [ -e ${NEW_FILE} ]; then
	    if [ $OVRWRT == "true" ]; then
		echo "brewtool ${COMMAND}: Warning: Overwriting ${NEW_FILE}..." 1>&2
		answer=y
	    else
		echo -n "brewtool ${COMMAND}: Warning: Overwrite ${NEW_FILE} ? [Y/n] " 1>&2
		read answer
	    fi
	else
	    answer=""
	    NEW="true"
	fi

	if [ -z "${XCFTOOL}" ]; then
	    XCFTOOL="false"
	else
	    FILE="-"
	    [ -z "${COMMENTTAG}" ] && COMMENTSWITCH2="-Comment=" # To avoid 'Converted by xcf2pnm'
	fi
	
	# Check overwrite status and convert file.
	if strstr $"yY" "$answer" || [ "$answer" = "" ]; then
	    if [ -w ${NEW_FILE} ] || [ $NEW == "true" ]; then
		if [ ! -z ${COMMAND} ]; then 
		    #echo "Running '" ${XCFTOOL} '|' convert -quiet ${FILE} ${INPROFILE_SWITCH} $GRAY ${SQUARESWITCH} ${RESIZE} \
		    #${UNSHARP} ${OUTPROFILE_SWITCH} ${SIGNATURESWITCH} ${BYLINESWITCH} ${DROPSHADOW} \
		    #-quality $QUALITY ${DEPTH} ${NEW_FILE} "'"
		    ${XCFTOOL} | convert -quiet ${FILE} ${INPROFILE_SWITCH} $GRAY ${SQUARESWITCH} ${RESIZE} ${UNSHARP} ${OUTPROFILE_SWITCH} \
			${SIGNATURESWITCH} ${BYLINESWITCH} ${DROPSHADOW} -quality $QUALITY ${DEPTH} ${NEW_FILE}
		fi
		exiftool ${TAGSWITCH} ${EXIFEXCLUDESWITCH} ${TAGSWITCH2} ${EXIFTOOLSWITCH} ${ORIENTSWITCH} \
		    "${TITLESWITCH2}" "${TITLESWITCH3}" \
		    "${DESCRIPTIONSWITCH1}" "${DESCRIPTIONSWITCH2}" "${DESCRIPTIONSWITCH3}" \
		    "${COMMENTSWITCH1}" "${COMMENTSWITCH2}" \
		    "${COPYRIGHTSWITCH}" "${ARTISTSWITCH}" "${AUTHORSWITCH}" "${SOFTWARESWITCH}" \
		    ${NOEXIF} -overwrite_original -P ${NEW_FILE}
		exiftool "${CAMORIENTSWITCH}" -overwrite_original -P ${NEW_FILE}
	    else
		echo "brewtool ${COMMAND}: Target file ${NEW_FILE} does not exist or has no write permissions! Skipping..." 1>&2
	    fi
	else
	    echo "brewtool ${COMMAND}: Skipping..." 1>&2
	fi
    else
	echo "brewtool ${COMMAND}: Original file '${FILE}' has no write permissions!, skipping" 1>&2
    fi
done
