#!/bin/sh

USAGE='Usage: brewrenamebias [-raw (directly from camera)] [-b <+-NNNN>] <image-files>

  Subtracts or adds sequence nr in image filenames.

  Depends on awk.

  Copyright © Daniel Ljunggren <foto@demulsion.se>. Feb 2008.

'

BIAS_NR=0
RAW=false

while [ $# -gt 0 ] 
do
    case "$1" in
	-b)
	    if [[ $2 == [+-][0-9][0-9][0-9][0-9] ]]; then
		BIAS_NR="$2"
	    else
		echo "BIAS_NR needs +- proceeding four digits ..."
		echo "$USAGE" 1>&2
		exit 2
	    fi
	    shift 1
	    ;;
	-raw)
	    RAW=true
	    ;;
	-*)	
	    echo "$USAGE" 1>&2
	    exit 2
	    ;;
	*)
	    break
	    ;;
    esac
    shift 1
done


if [ $# -eq 0 ]; then echo "${USAGE}"; exit 0 1>&2; fi

# 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 $* ; }"
}

for FILE 
do
    if [ -f "$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
		;;
	    *.jpg)
		ORIG_EXT=jpg
		;;
	    *.jpeg)
		ORIG_EXT=jpeg
		;;
	    *.JPG)
		ORIG_EXT=JPG
		;;
	    *.JPEG)
		ORIG_EXT=JPEG
		;;
	    *.avi)
		ORIG_EXT=avi
		;;
	    *.AVI)
		ORIG_EXT=AVI
		;;
	    *.tif)
		ORIG_EXT=tif
		;;
	    *.tiff)
		ORIG_EXT=tiff
		;;
	    *.TIF)
		ORIG_EXT=TIF
		;;
	    *.TIFF)
		ORIG_EXT=TIFF
		;;
	    *.PNG)
		ORIG_EXT=PNG
		;;
	    *.png)
		ORIG_EXT=png
		;;
	    *)
		echo "Can't handle file '$FILE', skipping" 1>&2
		continue
		;;
	esac

        # Find image sequence number:
	if [ $RAW == "true" ]; then
	    BASE=`basename $FILE .$ORIG_EXT`
	    SERIES=''
            SEQNR=`expr $BASE : '.*\([0-9][0-9][0-9][0-9]\).*$'`
	    
	else
	    BASE=`basename $FILE .$ORIG_EXT`
	    SERIES=`expr $BASE : '.*\([a-z]\)[0-9][0-9][0-9][0-9].*$'`
            SEQNR=`expr $BASE : '.*[a-z]\([0-9][0-9][0-9][0-9]\).*$'`
	fi

	NEW_SEQNR=`echo "${SEQNR}${BIAS_NR}" | bc`
	
	if [[ $NEW_SEQNR == [0-9] ]]; then
	    NEW_SEQNR=000$NEW_SEQNR
	fi
	if [[ $NEW_SEQNR == [0-9][0-9] ]]; then
	    NEW_SEQNR=00$NEW_SEQNR
	fi    
	if [[ $NEW_SEQNR == [0-9][0-9][0-9] ]]; then
	    NEW_SEQNR=0$NEW_SEQNR
	fi

	echo "Replacing sequencenr '${SERIES}${SEQNR}' with '${SERIES}${NEW_SEQNR}' in old filename $FILE"
	rename ${SERIES}${SEQNR} ${SERIES}${NEW_SEQNR} $FILE

    else
	echo "brewrenamebias: Warning: $FILE is not a regular file, skipping..."
    fi

done










