#!/bin/sh

USAGE='Usage: brewpreview [-o (overwrite)] <raw-image-files>

  Extract preview images from camera RAW-files.

  Depends on brewraw.

  Copyright © Daniel Ljunggren <foto@demulsion.se>. April 2009.

[options]:
  -slidecopy  : Set option -slidecopy in brewraw (assume film copy image)
  -negative   : Set option -negative in brewraw (use with -slidecopy to assume film copy image)
'

# 080826: Use brewraw (method 2) to get previews as in-camera processed images are too fuzzy.

OVERWRITE=false
BREWRAW_SWITCH=""

while [ $# -gt 0 ] 
do
    case "$1" in
	-o)	
	    OVERWRITE=true
	    ;;
	-slidecopy)
	    BREWRAW_SWITCH="${BREWRAW_SWITCH} -slidecopy"
	    ;;
	-negative)
	    BREWRAW_SWITCH="${BREWRAW_SWITCH} -negative"
	    ;;
	-*)	
	    echo "$USAGE" 1>&2
	    exit 2
	    ;;
	*)
	    break
	    ;;
    esac
    shift 1
done

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

for FILE 
do
    if [ -w "$FILE" ]; then
	case "$FILE" in
	    *.CR2)
		ORIG_EXT=CR2
		;;
	    *.cr2)
		ORIG_EXT=cr2
		;;
	    *.CRW)
		ORIG_EXT=CRW
		;;
	    *.crw)
		ORIG_EXT=crw
		;;
	    *.RAW)
		ORIG_EXT=RAW
		;;
	    *.raw)
		ORIG_EXT=raw
		;;
	    *)
		echo "brewpreview: Can't handle file '$FILE', skipping" 1>&2
		continue
		;;
	esac

	DIR=`dirname $FILE`
	BASE=`basename $FILE .$ORIG_EXT`
	PREVIEW_FILE="${DIR}/${BASE}.jpg"

	if [ ! -e "${PREVIEW_FILE}" ] || [ "${OVERWRITE}" == "true" ]; then
	    # Method 1:
            #dcraw -e -c "${FILE}" > "${PREVIEW_FILE}"
	    #echo -n "brewpreview: ${PREVIEW_FILE} extracted..."
	    #exiftool -TagsFromFile ${FILE} -XMP:all= -overwrite_original "${PREVIEW_FILE}"

	    # Method 2:
	    echo "brewpreview: ${PREVIEW_FILE} extracting..."
	    #brewraw -s "" -copyorient ${BREWRAW_SWITCH} -o -h "${FILE}"  # 17 sec.
	    brewraw -s "" -copyorient ${BREWRAW_SWITCH} -o -preview "${FILE}"  # 24 sec.

	else
	    echo "brewpreview: Warning: ${PREVIEW_FILE} already exist, skipping..."
	fi
    fi

done















