#!/bin/sh

[ -r .conf ] || exit 125

UFRAW='eval ufraw-batch --interpolation=ahd --out-type=tiff --out-depth=16 --overwrite --zip --rotate=no ${UEVARG}'
DCRAW='eval dcraw -v -r 1.225000 1.000000 1.950000 1.000000 -M -H 0 -q 3 -o 1 -n 60 -m 4 -t 0 -4 -T ${DEVARG}'
DCRAW='eval dcraw -v -r 1.387500 1.000000 2.125000 1.000000 -M -H 0 -q 3 -o 1 -n 60 -m 4 -t 0 -4 -T ${DEVARG}'
DCRAW='eval dcraw -v -r 1.387500 1.000000 2.150000 1.000000 -M -H 0 -q 3 -o 1 -n 60 -m 4 -t 0 -4 -T ${DEVARG}'
#DCRAW='eval dcraw -v -r 1.412500 1.000000 2.162500 1.000000 -M -H 0 -q 3 -o 1 -n 60 -m 4 -t 0 -4 -T ${DEVARG}'
#DCRAW='eval dcraw -v -r 1.425000 1.000000 2.162500 1.000000 -M -H 0 -q 3 -o 1 -n 60 -m 4 -t 0 -4 -T ${DEVARG}'
#DCRAW='dcraw -v -w -H 0 -q 3 -n 300 -4 -T'
EXIFTOOL='exiftool -overwrite_original -P'
#EXIFTOOL='true'
EXIFTFF="${EXIFTOOL} -TagsFromFile"
#EXIFTAG='-ImageDescription -Make -Model -Artist -WhitePoint -Copyright -GPS:all -DateTimeOriginal -CreateDate -UserComment -ColorSpace -OwnerName -SerialNumber -ISO -ExposureTime -FNumber -FocalLength -FocalLengthIn35mmFormat -Composite:DigitalZoom -FocalPlaneDiagonal -FocalPlaneXSize -FocalPlaneYSize -FocalPlaneResolutionUnit -FocalPlaneXResolution -FocalPlaneYResolution -ExifImageWidth -ExifImageHeight -ImageWidth -ImageHeight -LensType -LensModel -Lens -Orientation'
EXIFTAG='-EXIF:All -GPS:All'
PMATIC='eval panomatic -n ${CPUS} --fullscale --surfscore 10 --kdtreesteps 100 --kdtreeseconddist 0.3 --ransacdist 100 --minmatches 48'
#PMATIC='eval cpfind -n ${CPUS} --fullscale --kdtreesteps 100 --kdtreeseconddist 0.3 --ransacdist 100 --minmatches 48'
#PMATIC="${PMATIC} --celeste"
FULLA='eval fulla -v -t ${CPUS} -s'
#FFUSE='eval enfuse -v --compression=${ENCOMP} -m ${MEM} -b 16384 --exposure-weight=0.01 --saturation-weight=0.01  --contrast-weight=0.99 --hard-mask'
FFUSE='eval enfuse -v --compression=${ENCOMP} -m ${MEM} -b 16384 --exposure-weight=1.00 --saturation-weight=0.00  --contrast-weight=1.00 --hard-mask --exposure-mu=1.0 --exposure-sigma=0.7'
#CONV='convert -limit memory 512 -limit map 256'
CONV='convert'
#INPNT='greycstoration -alpha 0.9 -sigma 0.2 -p 5 -a 1 -dt 20 -iter 5 -bits 16 -m mask.png -inpaint'
#INPNT='greycstoration -alpha 0.9 -sigma 0.2 -iter 512 -bits 16 -inpaint'
INPNT='greycstoration -iter 1024 -bits 16 -inpaint'

#RGB='-fx (s<=0.03928)?s/12.92:((s+0.055)/1.055)^2.4'
#sRGB='-fx (s<=0.00304)?s*12.92:s^0.416666667*1.055-0.055'

RGBPROFILE='../../tools/profiles/RGB.icc'
sRGBPROFILE='../../tools/profiles/sRGB.icm'
RGB="-profile ${sRGBPROFILE} -profile ${RGBPROFILE}"
sRGB="-profile ${RGBPROFILE} -profile ${sRGBPROFILE}"

LDRREMAP='eval nona -v -t ${CPUS} -m TIFF_m -r ldr -p UINT${DEPTH} -z ${ENCOMP} -o tmp-'
LDRTMPSFX='tif'
LDRMERGE='eval enfuse -v --compression=${ENCOMP} -m ${MEM} -b 16384 --exposure-mu=0.4 --exposure-sigma=0.6'
#LDRMERGE='eval enfuse -v --compression=${ENCOMP} -m ${MEM} -b 16384 --exposure-weight=1.00 --saturation-weight=0.05  --contrast-weight=0.33 --hard-mask --gray-projector=value'
LDRBLEND='eval enblend -v --compression=${ENCOMP} -m ${MEM} -b 16384 --fine-mask'
#LDRBLEND='eval wine ~/.wine/drive_c/bin/enblend.exe -v --compression=${ENCOMP} -m ${MEM} -b 16384 --fine-mask'
#LDRBLEND='eval enfuse -v --compression=${ENCOMP} -m ${MEM} -b 16384 --exposure-weight=0.01  --saturation-weight=0.01  --contrast-weight=0.99 --hard-mask'
#LDRBLEND='sh ../../tools/smartblend'
LDRDEGHOST='deghosting_mask -v -s 60 -c 0.8 -t 150 -i 8 -a mw'

#HDRREMAP='eval nona -v -t ${CPUS} -m EXR_m -r hdr -p FLOAT -z ${ENCOMP} -o tmp-'
#HDRTMPSFX='exr'
HDRREMAP='eval nona -v -t ${CPUS} -m TIFF_m -r hdr -p FLOAT -z ${ENCOMP} -o tmp-'
HDRTMPSFX='tif'
#HDRMERGE='hugin_hdrmerge -vv -m khan -i 4 -a m'
#HDRMERGE='hugin_hdrmerge -v -m khan -i 8 -a di'
#HDRMERGE='hugin_hdrmerge -v -m avg -c -a di'
#HDRMERGE='eval enfuse -v --compression=${ENCOMP} -m ${MEM} -b 16384'
#HDRMERGE='env MERGE=hugin_hdrmerge sh ../../tools/merge-wrapper -vv -m khan -i 4 -a m'
#HDRMERGE='unset EXIFTOOL EXIFTAG; sh ../../tools/pfshdrcalibrate-wrapper -v -r linear -g 7.5 -b 16'
HDRMERGE='unset EXIFTOOL EXIFTAG; eval sh ../../tools/pfshdrcalibrate-wrapper -v -c none -f ${DST}.m -b 16'
HDRBLEND='eval enblend -v --compression=${ENCOMP} -m ${MEM} -b 16384 --fine-mask'
#HDRBLEND='eval wine ~/.wine/drive_c/bin/enblend.exe -v --compression=${ENCOMP} -m ${MEM} -b 16384 --fine-mask'
HDRDEGHOST='deghosting_mask -v -s 60 -c 0.8 -t 150 -i 8 -a mw'

PROCESS=LDR
EPL=1

LANG=C; export LANG

. ./.conf

eval "REMAP=\${${PROCESS}REMAP}"
eval "TMPSFX=\${${PROCESS}TMPSFX}"
eval "MERGE=\${${PROCESS}MERGE}"
eval "BLEND=\${${PROCESS}BLEND}"
eval "DEGHOST=\${${PROCESS}DEGHOST}"

[ -r "${DST}${3}.pto" ] && DST=${DST}${3}

[ -r "${DST}.pto" ] && [ "$(ptoget -p v "${DST}.pto")" != 360 ] \
|| BLEND="${BLEND} -w"

[ -z "${LIN}" ] || {
    [ "${PROCESS}" = HDR ] \
    || MERGE="${MERGE} --fallback-profile='${RGBPROFILE}' --ciecam"
    FFUSE="${FFUSE} --fallback-profile='${RGBPROFILE}' --ciecam"
}

[ -n "${TMPDIR}" ] || TMPDIR=.

[ -n "${DEPTH}" ] || DEPTH="${2}"
[ -n "${DEPTH}" ] || DEPTH=16

[ -z "${KEEPHDR}" ] || KEEPHDR="tee ${DST}.pfs"
[ -n "${KEEPHDR}" ] || KEEPHDR=cat

[ -n "${CPUS}" ] || CPUS=$(sysctl -n kern.smp.cpus)
[ -n "${CPUS}" ] || CPUS=1

#[ -n "${MEM}" ] || MEM="$(($(ulimit -d)/1024))"
#[ -n "${MEM}" ] || MEM=512
[ -n "${MEM}" ] || MEM=1536
[ ${MEM} -le 2560 ] || MEM=2560

[ -n "${IMCOMP}" ] || IMCOMP=zip
[ -n "${ENCOMP}" ] || ENCOMP=DEFLATE

[ -n "${FQ}" ] || FQ=90
[ -n "${QKF}" ] || QKF=95
[ -n "${WKF}" ] || WKF=760

extractsrc () {
    n="${SRC}"
    o="${NAM}${ESF}${FSF}"
    [ -z "${n}" -o "${n}" = SKIP -o "${n}" = SSKIP ] && continue
    [ -r ${o}.tiff ] && continue
    l="$(expr "${n}" : 'LINK:\(.*\)')" && {
        ln -s "${l}" ${o}.tiff
        continue
    }
    n="${n%.RAW.bz2}"
    n="${n%.RAW.gz}"
    n="${n%.RAW}"
    n="${n%.CR2}"
    n="${n%.JPG}"
    [ -r ${n}.RAW.bz2 ] && bzcat ${n}.RAW.bz2 >${n}.RAW
    [ -r ${n}.RAW.gz ] && zcat ${n}.RAW.gz >${n}.RAW
    [ -r ${n}.CR2 ] && ln -s ${n}.CR2 ${n}.RAW
    if [ -r ${n}.RAW ]
    then
        if [ -n "${BASELV}" -o -n "${EVCOMP}" ]
        then
            eval "$(
                ${EXIFTOOL} -LightValue -n ${n}.RAW \
                | awk '
                    BEGIN {
                        EV=0;
                    }
                    {
                        if (BASELV != "") {
                            EV = $4 - BASELV;
                        }
                        print "UEVARG=\"--exposure=" (EV+EVCOMP) "\"; DEVARG=\"-b " (2^(EV+EVCOMP)) "\"";
                    }
                  ' BASELV="${BASELV}" EVCOMP="${EVCOMP:-0}"
            )"
            echo "UEVARG='${UEVARG}'; DEVARG='${DEVARG}'"
        fi
        if [ -z "${LIN}" ]
        then
            conf=${n}.ufraw
            [ -z "${UCONF}" ] || conf=${UCONF}.ufraw
            [ -z "${UCF}" ] || conf=${UCF}.ufraw
            [ -r ${conf} ] || exit 125
            [ -z "${BASELV}" ] || UEVARG="${UEVARG} --create-id=no"
            ${UFRAW} --conf=${conf} --output=${n}.tiff ${n}.RAW
            ${CONV} ${n}.tiff \
                -flop \
                -compress ${IMCOMP} ${o}.tiff
        else
            ${DCRAW} ${n}.RAW
        fi
        tca=''
        if [ -z "${TCA}" -a -n "${LENS}" ]
        then
            fl="$(dcraw -i -v ${n}.RAW|awk '/^Focal length: /{print $3}')"
            #fl="$(exiftool -n -e -FocalLength ${n}.RAW |awk '{print $NF}')"
            tca="$( ( cd ../../tools/tca && echo "disp(tca('tca.db','${LENS}',${fl},1,0))"|octave -qf|cat|head -1 ) )"
            echo "Focal length: ${fl}; TCA correction: ${tca}"
        else
            tca="${TCA}"
        fi
        [ -z "${tca}" ] || ${FULLA} ${tca} -o ${n}.tiff ${n}.tiff
        eval "$(identify -format 'w=%w; h=%h' ${n}.tiff)"
        ${CONV} ${n}.tiff \
            -crop $((${w}-16))x$((${h}-16))+8+8 +repage \
            -compress ${IMCOMP} ${o}.tiff
        rm -f ${n}.tiff
        if [ -n "${LIN}" -a "${1}" = prep -a "${DEPTH}" = 8 ]
        then
            m='-modulate 100,50'
            ${CONV} ${o}.tiff \
                ${m} \
                -strip ${sRGB} \
                -compress ${IMCOMP} ${o}.tiff
        fi
        [ "${DEPTH}" = 16 ] \
        || ${CONV} ${o}.tiff -gamma 1.5 -depth 8 -compress ${IMCOMP} ${o}.tiff
    elif [ -r ${n}.JPG ]
    then
        # sRGB => RGB
        [ -z "${LIN}" ] || rgb="${RGB}"
        ${CONV} ${n}.JPG \
            -noise 3 -unsharp 0x0.3 \
            ${rgb} \
            -depth ${DEPTH} \
            -compress ${IMCOMP} ${o}.tiff
    else
        exit 126
    fi
    [ -r mask-${o}.png -a \( "${1}" != prep -o "${DEPTH}" != 8 \) ] \
    && ${CONV} ${o}.tiff -matte \
        mask-${o}.png -compose copyopacity -composite \
        -compress ${IMCOMP} ${o}.tiff
    #    mask-${o}.png -compose multiply -composite \
    [ -r ${n}.RAW ] && ${EXIFTFF} ${n}.RAW ${EXIFTAG} ${o}.tiff
    [ -r ${n}.RAW -a \( -r ${n}.RAW.bz2 -o -r ${n}.RAW.gz -o -r ${n}.CR2 \) ] \
    && rm -f ${n}.RAW
    [ -r ${n}.JPG ] && ${EXIFTFF} ${n}.JPG ${EXIFTAG} ${o}.tiff
}

prep () {
    for s in ${SEC}
    do
        eval "NAM=\${NAM${s}}"
        eval "EXP=\${EXP${s}}"
        if [ -z "${EXP}" ]
        then
            # no exposures stack for current sector
            ESF=''
            UCF=''
            eval "FOC=\${FOC${s}}"
            if [ -z "${FOC}" ]
            then
                # no focuses stack for current sector
                FSF=''
                eval "SRC=\${SRC${s}}"
                extractsrc
                continue
            fi
            for f in ${FOC}
            do
                eval "FSF=\${FSF${f}}"
                eval "SRC=\${SRC${s}F${f}}"
                extractsrc
            done
            continue
        fi
        for e in ${EXP}
        do
            eval "ESF=\${ESF${e}}"
            eval "UCF=\${UCF${e}}"
            eval "FOC=\${FOC${s}E${e}}"
            if [ -z "${FOC}" ]
            then
                # no focuses stack for current exposure and sector
                FSF=''
                eval "SRC=\${SRC${s}E${e}}"
                extractsrc
                continue
            fi
            for f in ${FOC}
            do
                eval "FSF=\${FSF${f}}"
                eval "SRC=\${SRC${s}E${e}F${f}}"
                extractsrc
            done
        done
    done
}

auto () {
    mkpto () {
        return 0
        for n in ${SRC}
        do
            eval "$(
                ${EXIFTOOL} -n -FOV -LightValue -ImageWidth -ImageHeight ${n} \
                | awk '
                    /^Field Of View/ {
                        print "FOV="$NF
                    }
                    /^Light Value/ {
                        print "LV="$NF
                    }
                    /^Image Width/ {
                        print "W="$NF
                    }
                    /^Image Height/ {
                        print "H="$NF
                    }
                '
            )"
            echo "i f0 w${W} h${H} v${FOV} Eev${LV} d0 e0 a0 b0 c0 p0 r0 y0 n\"${n}\""
        done \
        > "${1}"
        SRC="${1}"
    }
    autoexp () {
        x=${1}; shift
        e=${1}; shift
        eval "ESF=\${ESF${e}}"
        [ -r ${DST}${ESF}${x}-ao.pto ] && return
        [ ${#} -lt 2 ] && return
        SRC=''
        for s
        do
            eval "NAM=\${NAM${s}}"
            FSF=''
            eval "FOC=\${FOC${s}E${e}}"
            [ -n "${FOC}" ] || eval "FOC=\${FOC${s}}"
            [ -z "${FOC}" ] || eval "FSF=\${FSF${FOC%% *}}"
            src="${NAM}${ESF}${FSF}.tiff"
            [ -r "${src}" ] && SRC="${SRC} ${src}"
        done
        printf 'e=%s; S=%s\n' ${e} "${SRC}"
        mkpto ${DST}${ESF}${x}-pm.pto
        ${PMATIC} \
            --linearmatch --linearmatchlen 8 \
            --sieve1width 64 --sieve1height 48 --sieve1size 8 \
            --sieve2width 16 --sieve2height 16 --sieve2size 4 \
            -o ${DST}${ESF}${x}-pm.pto ${SRC}
        autooptimiser -a -l -s -o ${DST}${ESF}${x}-ao.pto ${DST}${ESF}${x}-pm.pto
    }
    autoexpex () {
        e="${1}"; shift
        eval "ESF=\${ESF${e}}"
        [ -r ${DST}${ESF}-ao.pto ] && return
        if [ -z "${ROWS}" ]
        then
            autoexp '' "${e}" "${@}"
            return ${?}
        fi
        eval "${ROWS}"
        eval "RROWS=\${ROWS${e}}"
        if [ -n "${RROWS}" ]
        then
            for r in ${RROWS}
            do
                eval "RSF=\${RSF${e}R${r}}"
                eval "RSC=\${RSC${e}R${r}}"
                autoexp "${RSF}" "${e}" ${RSC}
            done
            ptomerge ${DST}${ESF}[^-]*-ao.pto ${DST}${ESF}-ao.pto
            ptosort -i n ${DST}${ESF}-ao.pto ${DST}${ESF}-ao.pto
            autooptimiser -a -l -s -o ${DST}${ESF}-ao.pto ${DST}${ESF}-ao.pto
            return ${?}
        fi
        autoexp '' "${e}" "${@}"
    }
    autosec () {
        s=${1}; shift
        eval "NAM=\${NAM${s}}"
        [ -r ${DST}-${NAM}-ao.pto ] && return
        echo "${DST}-${NAM}-ao.pto: ${#}"
        [ ${#} -lt 2 ] && return
        SRC=''
        for e
        do
            eval "ESF=\${ESF${e}}"
            FSF=''
            eval "FOC=\${FOC${s}E${e}}"
            [ -n "${FOC}" ] || eval "FOC=\${FOC${s}}"
            [ -z "${FOC}" ] || eval "FSF=\${FSF${FOC%% *}}"
            src="${NAM}${ESF}${FSF}.tiff"
            [ -r "${src}" ] && SRC="${SRC} ${src}"
        done
        printf 's=%s; SRC=%s\n' ${s} "${SRC}"
        mkpto ${DST}-${NAM}-pm.pto
        ${PMATIC} \
            --sieve1width 64 --sieve1height 48 --sieve1size 8 \
            --sieve2width 32 --sieve2height 24 --sieve2size 4 \
            -o ${DST}-${NAM}-pm.pto ${SRC}
        autooptimiser -a -o ${DST}-${NAM}-ao.pto ${DST}-${NAM}-pm.pto
    }
    autofoc () {
        s=${1}; shift
        eval "NAM=\${NAM${s}}"
        ESF=''
        e="${1}"; shift
        [ -z "${e}" ] || eval "ESF=\${ESF${e}}"
        [ -r ${DST}-${NAM}${ESF}-ao.pto ] && return
        echo "${DST}-${NAM}${ESF}-ao.pto: ${#}"
        [ ${#} -lt 2 ] && return
        SRC=''
        for f
        do
            eval "FSF=\${FSF${f}}"
            src="${NAM}${ESF}${FSF}.tiff"
            [ -r "${src}" ] && SRC="${SRC} ${src}"
        done
        printf 's=%s; e=%s; SRC=%s\n' ${s} ${e} "${SRC}"
        mkpto ${DST}-${NAM}${ESF}-pm.pto
        ${PMATIC} \
            --linearmatch --linearmatchlen 8 \
            --sieve1width 64 --sieve1height 48 --sieve1size 8 \
            --sieve2width 32 --sieve2height 24 --sieve2size 4 \
            -o ${DST}-${NAM}${ESF}-pm.pto ${SRC}
        autooptimiser -a -o ${DST}-${NAM}${ESF}-ao.pto ${DST}-${NAM}${ESF}-pm.pto
    }
    E=''
    for s in ${SEC}
    do
        eval "EXP=\${EXP${s}}"
        for e in ${EXP}
        do
            echo "${E}" | grep -q "\<${e}\>" && continue
            E="${E} ${e}"
        done
    done
    for e in ${E}
    do
        S=''
        for s in ${SEC}
        do
            eval "echo \"\$EXP${s}\" | grep -q '\<${e}\>'" || continue
            S="${S} ${s}"
        done
        autoexpex "${e}" ${S}
    done
    for s in ${SEC}
    do
        eval "EXP=\${EXP${s}}"
        autosec ${s} ${EXP}
        eval "FOC=\${FOC${s}}"
        if [ -n "${FOC}" ]
        then
            autofoc "${s}" '' ${FOC}
            continue
        fi
        for e in ${EXP}
        do
            eval "FOC=\${FOC${s}E${e}}"
            [ -n "${FOC}" ] || continue
            autofoc "${s}" "${e}" ${FOC}
        done
    done
}

cluster () {
    clexp () {
        e=${1}
        eval "ESF=\${ESF${e}}"
        [ -r ${DST}${ESF}-ao.pto ] || return
        [ -z "${2}" ] || D="-D${2}"
        [ -z "${3}" ] || d="-d${3}"
        yrp=y,r,p/0-
        #[ -z "${4}" ] || yrp="y,r,p/0-$((${4}-1)),$((${4}+1))-:r,p/${4}"
        [ -z "${4}" ] || yrp="y,r,p/0-$((${4}-1)),$((${4}+1))-"
        echo "yrp: ${yrp}"
        [ -r ${DST}${ESF}.pto ] && return
        perl ../../tools/ptsed -O0x80ff \
            -s -Vb,v/0:a,c,d,e/0-:${yrp} \
            -o ${DST}${ESF}-ao.txt ${DST}${ESF}-ao.pto
        PToptimizer ${DST}${ESF}-ao.txt
        perl ../../tools/ptscluster -O0xff \
            -x48 -y36 ${D} ${d} \
            -o ${DST}${ESF}-ao.txt ${DST}${ESF}-ao.txt \
        && perl ../../tools/ptsed -O0xff \
            -s -r \
            -o ${DST}${ESF}-ao.txt ${DST}${ESF}-ao.txt
        PToptimizer ${DST}${ESF}-ao.txt
        perl ../../tools/ptscluster -O0xff \
            -x24 -y18 ${D} ${d} \
            -o ${DST}${ESF}-ao.txt ${DST}${ESF}-ao.txt \
        && perl ../../tools/ptsed -O0xff \
            -s -r \
            -o ${DST}${ESF}-ao.txt ${DST}${ESF}-ao.txt
        PToptimizer ${DST}${ESF}-ao.txt
        perl ../../tools/ptscluster -O0xff \
            ${D} ${d} \
            -o ${DST}${ESF}-ao.txt ${DST}${ESF}-ao.txt \
        && perl ../../tools/ptsed -O0xff \
            -s -r \
            -o ${DST}${ESF}-ao.txt ${DST}${ESF}-ao.txt
        PToptimizer ${DST}${ESF}-ao.txt
        perl ../../tools/ptsed -O0xff \
            -i \
            -o ${DST}${ESF}.pto ${DST}${ESF}-ao.txt
    }
    clsec () {
        s=${1}
        eval "NAM=\${NAM${s}}"
        ESF=''
        e=${2}
        [ -z "${e}" ] || eval "ESF=\${ESF${e}}"
        [ -r ${DST}-${NAM}${ESF}-ao.pto ] || return
        #[ -r ${DST}-${NAM}${ESF}.pto ] && return
        #    -Ib,v/1-:=0:a,c,d,e/0-:0 \
        perl ../../tools/ptsed -O0xff \
            -Vy,r,p/1- \
            -s -o ${DST}-${NAM}${ESF}-ao.txt ${DST}-${NAM}${ESF}-ao.pto
        PToptimizer ${DST}-${NAM}${ESF}-ao.txt
        perl ../../tools/ptscluster -O0xff \
            -r0x21 -x48 -y36 -d12 -D24 \
            -o ${DST}-${NAM}${ESF}-ao.txt ${DST}-${NAM}${ESF}-ao.txt \
        && perl ../../tools/ptsed -O0xff \
            -s -r \
            -o ${DST}-${NAM}${ESF}-ao.txt ${DST}-${NAM}${ESF}-ao.txt
        PToptimizer ${DST}-${NAM}${ESF}-ao.txt
        perl ../../tools/ptscluster -O0xff \
            -r0x21 -x48 -y36 -d8 -D16 \
            -o ${DST}-${NAM}${ESF}-ao.txt ${DST}-${NAM}${ESF}-ao.txt \
        && perl ../../tools/ptsed -O0xff \
            -s -r \
            -o ${DST}-${NAM}${ESF}-ao.txt ${DST}-${NAM}${ESF}-ao.txt
        PToptimizer ${DST}-${NAM}${ESF}-ao.txt
        perl ../../tools/ptscluster -O0xff \
            -r0x21 -x48 -y36 -D10 \
            -o ${DST}-${NAM}${ESF}-ao.txt ${DST}-${NAM}${ESF}-ao.txt \
        && perl ../../tools/ptsed -O0xff \
            -s -r \
            -Vy,r,p/1- \
            -o ${DST}-${NAM}${ESF}-ao.txt ${DST}-${NAM}${ESF}-ao.txt
            #-Va,c,d,e/1-:y,r,p/1- \
        PToptimizer ${DST}-${NAM}${ESF}-ao.txt
        perl ../../tools/ptscluster -O0xff \
            -r0x21 -x24 -y18 -D7 \
            -o ${DST}-${NAM}${ESF}-ao.txt ${DST}-${NAM}${ESF}-ao.txt \
        && perl ../../tools/ptsed -O0xff \
            -s -r \
            -o ${DST}-${NAM}${ESF}-ao.txt ${DST}-${NAM}${ESF}-ao.txt
        PToptimizer ${DST}-${NAM}${ESF}-ao.txt
        perl ../../tools/ptscluster -O0xff \
            -r0x21 -D5 \
            -o ${DST}-${NAM}${ESF}-ao.txt ${DST}-${NAM}${ESF}-ao.txt \
        && perl ../../tools/ptsed -O0xff \
            -s -r \
            -o ${DST}-${NAM}${ESF}-ao.txt ${DST}-${NAM}${ESF}-ao.txt
        #PToptimizer ${DST}-${NAM}${ESF}-ao.txt
        #perl ../../tools/ptscluster -O0xff \
        #    -r0x21 -D3 \
        #    -o ${DST}-${NAM}${ESF}-ao.txt ${DST}-${NAM}${ESF}-ao.txt \
        #&& perl ../../tools/ptsed -O0xff \
        #    -s -r \
        #    -o ${DST}-${NAM}${ESF}-ao.txt ${DST}-${NAM}${ESF}-ao.txt
        PToptimizer ${DST}-${NAM}${ESF}-ao.txt
        perl ../../tools/ptsed -O0xff \
            -i \
            -o ${DST}-${NAM}${ESF}.pto ${DST}-${NAM}${ESF}-ao.txt
    }
    E=''
    for s in ${SEC}
    do
        eval "EXP=\${EXP${s}}"
        for e in ${EXP}
        do
            echo "${E}" | grep -q "\<${e}\>" && continue
            E="${E} ${e}"
        done
    done
    for e in ${E}
    do
        eval "anc=\${ANC${e}}"
        [ -n "${anc}" ] || anc="${ANC}"
        echo "ANC: ${ANC}; anc: ${anc}"
        clexp ${e} "${DMAX}" "${DMIN}" "${anc}"
    done
    for s in ${SEC}
    do
        clsec ${s}
        eval "EXP=\${EXP${s}}"
        for e in ${EXP}
        do
            clsec ${s} ${e}
        done
    done
}

mkprocessrmf () {
    srcdef () {
        awk '
            BEGIN {
                i=0;
            }
            /^p / {
                if (match($0,/ E[^ ]+/))
                    print "EPAN="substr($0,RSTART+2,RLENGTH-2);
            }
            /^i / {
                if (match($0," n\"?"SRC"\"?")) {
                    print "ISRC="i;
                    if (match($0,/ Eev[^ ]+/))
                        print "ESRC="substr($0,RSTART+4,RLENGTH-4);
                    nextfile
                }
                ++i;
            }
        ' SRC=${SRC} ${DST}.pto
    }
    prologue () {
        cat <<EOT
DST?=${DST}

CPUS?=${CPUS}
MEM?=${MEM}
DEPTH?=${DEPTH}
IMCOMP?=${IMCOMP}
ENCOMP?=${ENCOMP}
RGBPROFILE?=${RGBPROFILE}
sRGBPROFILE?=${sRGBPROFILE}

CONV?=${CONV}
REMAP?=${REMAP}
FFUSE?=${FFUSE}
MERGE?=${MERGE}
DEGHOST?=${DEGHOST}
BLEND?=${BLEND} ${f}

EXIFTFF?=${EXIFTFF}
EXIFTAG?=-EXIF:ShutterSpeedValue -EXIF:ApertureValue -EXIF:ISO

RM=${RM}
MV=mv
LN=ln -f

all: \${DST}.tiff

EOT
    }
    epilogue () {
        cat <<EOT

tmp.tiff: ${BLIN}
	@\${RM} ${RMIN}
	@\${BLEND} -o tmp.tiff ${BLIN}
	@\${RM} ${BLIN}
EOT
    }
    epilogueLDR1 () {
        cat <<EOT
\${DST}.tiff: tmp.tiff
	@\${CONV} tmp.tiff \\
		+matte +repage ${DARG} \\
		-compress \${IMCOMP} \${DST}.tiff
	@\${RM} tmp.tiff
EOT
    }
    epilogueHDR1 () {
        bright=-1.67
        light=0.35
        chrom=0.95
        r=0.9500
        g=0.7000
        b=1.2000
        cat <<EOT
\${DST}.tiff: tmp.tiff
	@pfsin tmp.tiff \\
	 | pfsclamp --min 1e-20: --max 1e+20 \\
	 | pfswb -v -r ${r} -g ${g} -b ${b} \\
	 | pfstmo_reinhard05 -v -b ${bright} -c ${chrom} -l ${light} \\
	 | pfsoutimgmagick -s -b 16 \${DST}.tiff
	@\${RM} tmp.tiff
	@\${CONV} \${DST}.tiff \\
		+matte +repage ${DARG} \\
		-compress \${IMCOMP} \${DST}.tiff
EOT
    }
    epilogueHDR2 () {
        bright=1.33
        light=0.50
        chrom=0.95
        #[ "${K}" = a ] && {
        #    bright=1.33
        #}
        #[ "${K}" = b ] && {
        #    bright=-5.00
        #    light=0.30
        #}
        #[ "${K}" = b ] && bright=-1.50
        #[ "${K}" = b ] && light=0.9625
        cat <<EOT

\${DST}.tiff: tmp.tiff
	@pfsin tmp.tiff \\
	 | pfsclamp --min 4 --max 65536 \\
	 | pfswb -v -r 1.0500 -g 1.0000 -b 0.9750 \\
	 | pfstmo_mantiuk08 -v -d pd=crt -c 0.9 -e 0.75 \\
	 | pfsoutimgmagick -b 16 \${DST}.0.tiff
	@pfsin tmp.tiff \\
	 | pfsclamp --min 4 --max 65536 \\
	 | pfswb -v -r 1.0500e-04 -g 1.0000e-04 -b 0.9750e-04 \\
	 | pfstmo_reinhard05 -v -b ${bright} -c ${chrom} -l ${light} \\
	 | pfsoutimgmagick -s -b 16 \${DST}.1.tiff
	@\${RM} tmp.tiff
	@\${CONV} \${DST}.0.tiff \\
		-colorspace HSL -channel B -separate \\
		-compress \${IMCOMP} \${DST}.2.tiff
	@\${CONV} \${DST}.2.tiff \\
		-negate \\
		+level 0%,90%,1.0 \\
		-compress \${IMCOMP} \${DST}.3.tiff
	@\${CONV} \${DST}.2.tiff \${DST}.3.tiff \\
		-compose lighten -composite \\
		-level 49%,100%,1.2 \\
		+level 0%,98%,1.0 \\
		-compress \${IMCOMP} \${DST}.4.tiff
	@\${CONV} \${DST}.1.tiff \${DST}.4.tiff \\
		-compose copy-opacity -composite \\
		-compress \${IMCOMP} \${DST}.5.tiff
	@\${CONV} \${DST}.0.tiff \${DST}.5.tiff \\
		-compose src-over -composite \\
		+matte +repage ${DARG} \\
		-compress \${IMCOMP} \${DST}.tiff
	@\${RM} \${DST}.0.tiff \${DST}.1.tiff \\
		\${DST}.2.tiff \${DST}.3.tiff \\
		\${DST}.4.tiff \${DST}.5.tiff
EOT
    }
    remap () {
        SRC="${NAM}${ESF}${FSF}.tiff"
        eval "EV=\${EV${e}}; SEV=\${EV${e}S${s}}"
        eval "$(srcdef)"
        [ -n "${ISRC}" ] || return 1
        [ ${nexp} -gt 1 ] || ESRC="${EPAN}"
        [ -z "${EV}" ] || ESRC="${EV}"
        [ -z "${SEV}" ] || ESRC="${SEV}"
        [ -z "${ESRC}" ] || ESRC="-e ${ESRC}"
        t=$(printf 'tmp-%04d.%s' ${ISRC} ${TMPSFX})
        m=''
        [ "${PROCESS}" = HDR ] \
        && m=$(printf ' tmp-%04d_gray.pgm' ${ISRC})
        cat <<EOT
${t}: \${DST}.pto ${SRC}
	@\${REMAP} -i ${ISRC} ${ESRC} \${DST}.pto
EOT
        RMIN="${RMIN} ${SRC}${m}"
        n="${SRC}"
        SRC="tmpf${NAM}${ESF}${FSF}.tiff"
        cat <<EOT
${SRC}: ${t}
EOT
        eval "TARGE=\${TARGE${e}F}; TARGSE=\${TARG${s}E${e}F}; TARGSEF=\${TARG${s}E${e}F${f}}"
        XTARG=''
        #[ -z "${LIN}" ] \
        #|| XTARG="${XTARG} ${sRGB}"
        [ -z "${TARGE}" ] \
        || XTARG="${XTARG} ${TARGE}"
        [ -z "${TARGSE}" ] \
        || XTARG="${XTARG} ${TARGSE}"
        [ -z "${TARGSEF}" ] \
        || XTARG="${XTARG} ${TARGSEF}"
        if [ -n "${XTARG}" ]
        then
            cat <<EOT
	@\${CONV} ${t} \\
		${XTARG} \\
		-compress \${IMCOMP} ${SRC}
EOT
        else
            cat <<EOT
	@\${LN} ${t} ${SRC}
EOT
        fi
        [ "${PROCESS}" = HDR ] && cat <<EOT
	@\${EXIFTFF} ${n} \${EXIFTAG} ${SRC}
EOT
        cat <<EOT
	@\${RM} ${t}
EOT
        FFIN="${FFIN} ${SRC}"
    }
    fstack () {
        t="${FFIN}"
        if [ "$(echo "${t}" | wc -w)" -gt 1 ]
        then
            t="tmpet${NAM}${ESF}.tiff"
            cat <<EOT
${t}: ${FFIN}
	@\${FFUSE} -o ${t} ${FFIN}
EOT
            [ "${PROCESS}" = HDR ] && cat <<EOT
	@\${EXIFTFF} ${FFIN%% *} \${EXIFTAG} ${t}
EOT
            cat <<EOT
	@\${RM} ${FFIN}
EOT
        fi
        SRC="tmpe${NAM}${ESF}.tiff"
        eval "PATCH=\${PATCH${s}E${e}}"
        ifs="${IFS}"; IFS=:
        set -- ${PATCH}
        IFS=${ifs}; unset ifs
        ps=''
        ap=''
        for p
        do
            eval "$(echo "${p}" | { read n p g a; echo "n='${n}';p='${p}';g='${g}';a='${a}'"; })"
            [ -n "${p}" ] || continue
            eval "p=tmpe${NAM}\${ESF${p}}.tiff"
            ps="${ps} ${p}"
            ap="$(printf '%s\n\t%s' "${ap}" "@env RGBPROFILE='\${RGBPROFILE}' sRGBPROFILE='\${sRGBPROFILE}' CONV='\${CONV}' IMCOMP='\${IMCOMP}' RM='\${RM}' sh ../../tools/applypatch ${g} ${p} ${SRC} ${n} ${LIN} ${a}")"
        done
        cat <<EOT
${SRC}: ${t}${ps}
EOT
        eval "TARGS=\${TARG${s}E}; TARGE=\${TARGE${e}}; TARGSE=\${TARG${s}E${e}}"
        XTARG=''
        [ -z "${TARGS}" ] \
        || XTARG="${XTARG} ${TARGS}"
        [ -z "${TARGE}" ] \
        || XTARG="${XTARG} ${TARGE}"
        [ -z "${TARGSE}" ] \
        || XTARG="${XTARG} ${TARGSE}"
        if [ -n "${XTARG}" ]
        then
            cat <<EOT
	@\${CONV} ${t} \\
		${XTARG} \\
		-compress \${IMCOMP} ${SRC}
EOT
        else
            cat <<EOT
	@\${LN} ${t} ${SRC}
EOT
        fi
        [ -z "${ap}" ] || echo "${ap}" | tail +2
        [ "${PROCESS}" = HDR ] && cat <<EOT
	@\${EXIFTFF} ${t} \${EXIFTAG} ${SRC}
EOT
        cat <<EOT
	@\${RM} ${t}
EOT
        EFIN="${EFIN} ${SRC}"
    }
    estack () {
        t="tmpt${NAM}.tiff"
        cat <<EOT
${t}: ${EFIN}
EOT
        if [ "$(echo "${EFIN}" | wc -w)" -gt 1 ]
        then
            [ -z "${STK}" ] \
            || cat <<EOT
	@env CONV='\${CONV}' RM='\${RM}' sh ../../tools/stackmask ${EFIN}
EOT
            [ -z "${DGH}" ] \
            || cat <<EOT
	@\${DEGHOST} ${EFIN}
	@for n in ${EFIN}; \\
	 do \\
		\${CONV} \$\${n} \\( +clone -fx '1-s.o' +matte \$\${n%.tif}_mask.tif -compose multiply -composite \\) -compose copy-opacity -composite \$\${n}; \\
		\${RM} \$\${n%.tif}_mask.tif; \\
	 done
EOT
        fi
        cat <<EOT
	@\${MERGE} -o ${t} ${EFIN}
	@\${RM} ${EFIN}
EOT
        SRC="tmp${NAM}.tiff"
        cat <<EOT
${SRC}: ${t}
EOT
        eval "TARGS=\${TARG${s}}"
        XTARG=''
        [ -z "${TARG}" ] \
        || XTARG="${XTARG} ${TARG}"
        [ -z "${TARGS}" ] \
        || XTARG="${XTARG} ${TARGS}"
        if [ -n "${XTARG}" ]
        then
            cat <<EOT
	@\${CONV} ${t} \\
		${XTARG} \\
		-compress \${IMCOMP} ${SRC}
EOT
        else
            cat <<EOT
	@\${LN} ${t} ${SRC}
EOT
        fi
        cat <<EOT
	@\${RM} ${t}
EOT
        BLIN="${BLIN} ${SRC}"
    }
    K="${3}"
    RM='rm -f'
    [ -z "${K}" ] || RM='echo'
    f=$(awk '/^p /{if(match($0,/ w[0-9]+/)){w=substr($0,RSTART+2,RLENGTH-2);match($0,/ h[0-9]+/);h=substr($0,RSTART+2,RLENGTH-2);print w"x"h}nextfile}' ${DST}.pto)
    [ -z "${f}" ] || f="-f ${f}"
    c=$(awk '/^p /{if(match($0,/ S[0-9]+,[0-9]+,[0-9]+,[0-9]+/)){split(substr($0,RSTART+2,RLENGTH-2),a,/,/);print(a[2]-a[1])"x"(a[4]-a[3])"+"a[1]"+"a[3]}nextfile}' ${DST}.pto)
    [ -z "${c}" ] || f="-f ${c}"
    #expr "${BLEND}" : '.*smartblend' >/dev/null && f=''
    prologue
    RMIN=''
    BLIN=''
    for s in ${SEC}
    do
        eval "NAM=\${NAM${s}}"
        eval "EXP=\${EXP${s}}"
        nexp=$(echo "${EXP}" | wc -w)
        EFIN=''
        if [ -z "${EXP}" ]
        then
            # no exposures stack for current sector
            e=0
            ESF=''
            FFIN=''
            eval "FOC=\${FOC${s}}"
            if [ -z "${FOC}" ]
            then
                # no focuses stack for current sector
                f=0
                FSF=''
                remap || return 1
            fi
            for f in ${FOC}
            do
                eval "FSF=\${FSF${f}}"
                remap || return 1
            done
            fstack
        fi
        for e in ${EXP}
        do
            eval "ESF=\${ESF${e}}"
            eval "FOC=\${FOC${s}E${e}}"
            FFIN=''
            if [ -z "${FOC}" ]
            then
                # no focuses stack for current exposure and sector
                f=0
                FSF=''
                remap || return 1
            fi
            for f in ${FOC}
            do
                eval "FSF=\${FSF${f}}"
                remap || return 1
            done
            fstack
        done
        estack
    done
    epilogue
    "epilogue${PROCESS}${EPL}"
}

inpaint () {
    g=${1}
    n=${2}
    [ -r mask-${DST}.${n}.png ] || return
    ${CONV} ${DST}.tiff \
        -crop ${g} \
        -compress ${IMCOMP} ${DST}.${n}.tiff 
    mv ${DST}.tiff ${DST}.0.tiff
    greycstoration -inpaint ${DST}.${n}.tiff \
        -iter 1024 -bits 16 \
        -m mask-${DST}.${n}.png \
        -o ${DST}.${n}.tiff
    ${CONV} ${DST}.0.tiff ${DST}.${n}.tiff \
        -geometry ${g} \
        -compose src-over -composite \
        -compress ${IMCOMP} ${DST}.tiff
    rm ${DST}.0.tiff ${DST}.${n}.tiff
}

apply_patch () {
    g=${1}; shift
    se=${1}; shift
    de=${1}; shift
    n=${1}; shift
    [ -n ${n} ] || n=1
    rgb=''; srgb=''
    [ -n ${LIN} ] || { rgb="${RGB}"; srgb="${sRGB}"; }
    ${CONV} ${DST}-e${se}.tiff \
        -crop ${g} +repage \
        ${rgb} "${@}" ${srgb} \
        -compress ${IMCOMP} ${DST}-e${de}.${n}.tiff 
    [ -r mask-${DST}-e${de}.${n}.png ] \
    && ${CONV} ${DST}-e${de}.${n}.tiff \
        mask-${DST}-e${de}.${n}.png -compose copyopacity -composite \
        -compress ${IMCOMP} ${DST}-e${de}.${n}.tiff
    mv ${DST}-e${de}.tiff ${DST}-e${de}.0.tiff
    ${CONV} ${DST}-e${de}.0.tiff ${DST}-e${de}.${n}.tiff \
        -geometry ${g} \
        -compose src-over -composite \
        -compress ${IMCOMP} ${DST}-e${de}.tiff
    rm ${DST}-e${de}.0.tiff ${DST}-e${de}.${n}.tiff
}

apply_patch2 () 
{
    dg=${1}; shift
    sg=${1}; shift
    n=${1}; shift
    [ -n ${n} ] || n=1
    rgb=''; srgb=''
    [ -n ${LIN} ] || { rgb="${RGB}"; srgb="${sRGB}"; }
    ${CONV} ${DST}.tiff \
        -crop ${sg} +repage \
        ${rgb} "${@}" ${srgb} \
        -compress ${IMCOMP} ${DST}.${n}.tiff 
    [ -r mask-${DST}.${n}.png ] \
    && ${CONV} ${DST}.${n}.tiff \
        mask-${DST}.${n}.png -compose copyopacity -composite \
        -compress ${IMCOMP} ${DST}.${n}.tiff
    mv ${DST}.tiff ${DST}.0.tiff
    ${CONV} ${DST}.0.tiff ${DST}.${n}.tiff \
        -geometry ${dg} \
        -compose src-over -composite \
        -compress ${IMCOMP} ${DST}.tiff
    rm ${DST}.0.tiff ${DST}.${n}.tiff
}

apply_patch3 () 
{
    dst=${1}; shift
    dg=${1}; shift
    src=${1}; shift
    sg=${1}; shift
    n=${1}; shift
    [ -n ${n} ] || n=1
    rgb=''; srgb=''
    [ -n ${LIN} ] || { rgb="${RGB}"; srgb="${sRGB}"; }
    ${CONV} ${src}.tiff \
        -crop ${sg} +repage \
        ${rgb} "${@}" ${srgb} \
        -compress ${IMCOMP} ${dst}.${n}.tiff 
    [ -r mask-${dst}.${n}.png ] \
    && ${CONV} ${dst}.${n}.tiff \
        mask-${dst}.${n}.png -compose copyopacity -composite \
        -compress ${IMCOMP} ${dst}.${n}.tiff
    mv ${dst}.tiff ${dst}.0.tiff
    ${CONV} ${dst}.0.tiff ${dst}.${n}.tiff \
        -geometry ${dg} \
        -compose src-over -composite \
        -compress ${IMCOMP} ${dst}.tiff
    rm ${dst}.0.tiff ${dst}.${n}.tiff
}

qtvr () {
    mkdir -p ${TMPDIR}/${DST}
    eval "${CONV} ${DST}.tiff ${FINAL} ${*} -compress ${IMCOMP} '${TMPDIR}/${DST}/${DST}.tiff'"
    n=''
    [ -z "${NAME}" ] || n="--name='${NAME}'"
    yaw=''
    [ -z "${YAW}" ] || yaw="--yaw='${YAW}'"
    BASEDIR="$(pwd)" \
    && cd "${TMPDIR}/${DST}" \
    && eval "erect2cubic --erect=${DST}.tiff \
        ${yaw} \
        --ptofile=cubic.pto" \
    && ptsed -Pw,h:2048 -o cubic.pto cubic.pto \
    && ${LDRREMAP} -o face- cubic.pto \
    && for n in 0 1 2 3 4 5
       do
        ${CONV} face-000${n}.tif \
            -sharpen 0x1.16331 \
            -quality 90 -write face-big-${n}.jpg \
            -resize 1024 -sharpen 0x0.76105 \
            -quality 90 -write face-${n}.jpg \
            -resize 512 -sharpen 0x0.51848 \
            -quality 92 -write face-small-${n}.jpg \
            -resize 256 -sharpen 0x0.42410 \
            -quality 80 preview-${n}.jpg \
        && rm face-000${n}.tif
        #${CONV} face-000${n}.tif \
        #    -unsharp 0x0.75+0.5+0.05 \
        #    -quality 90 -write face-${n}.jpg \
        #    -resize 1024 -unsharp 0x0.75+0.5+0.04 \
        #    -quality 90 -write face-small-${n}.jpg \
        #    -resize 512 -unsharp 0x0.65+0.5+0.04 \
        #    -resize 256 -unsharp 0x0.45+0.4+0.03 \
        #    -quality 80 preview-${n}.jpg \
       done \
    && eval "jpeg2qtvr \
        --prefix=face-small- --preview=preview- ${n} \
        --width=400 --height=300 \
        --outfile='${BASEDIR}/${DST}-small.mov'" \
    && eval "jpeg2qtvr \
        --prefix=face- --preview=preview- ${n} \
        --width=768 --height=576 \
        --outfile='${BASEDIR}/${DST}.mov'" \
    && eval "jpeg2qtvr \
        --prefix=face-big- --preview=preview- ${n} \
        --width=1280 --height=960 \
        --outfile='${BASEDIR}/${DST}-big.mov'"
    cd "${BASEDIR}"
    rm -rf ${TMPDIR}/${DST}
    test -r ${DST}.mov
}

globe () {
    true || {
    h=$(identify -format '%h' ${DST}.tiff)
    y=$((${h}/2))
    r=$((${h}/64))
    s=$((${r}/3))
    echo "globe: h=${h}; y=${y}; blur ${r}x${s}"
    true || ${CONV} ${DST}.tiff \
        \(  -size ${h}x${h} xc:'rgba(44.314%,49.020%,55.294%,1.0)' \
            \(  -colorspace gray -virtual-pixel white \
                -size ${h}x${h} xc:white \
                -fill black -box black -draw "circle ${y},${y} ${y},1" \
                -blur ${r}x${s} +matte \
            \) \
            -compose copyopacity -composite \
        \) \
        -compose src-over -composite \
        -compress ${IMCOMP} ${DST}.tiff
    }
    #${FULLA} -g 0.09:0.03:-0.9:1.75 -o ${DST}.tiff ${DST}.tiff
    #${FULLA} -g 0.09:0.03:-0.9:1.78 -o ${DST}.tiff ${DST}.tiff
    #${FULLA} -g 0.09:0.03:-0.925:1.805 -o ${DST}.tiff ${DST}.tiff
    #${FULLA} -g 0.095:0.035:-0.950:1.820 -o ${DST}.tiff ${DST}.tiff
    ${FULLA} -g 0.100:0.040:-0.960:1.820 -o ${DST}.tiff ${DST}.tiff
    #${FULLA} -g 0.09:0.03:-0.9:1.60 -o ${DST}.tiff ${DST}.tiff
}

final_fe () {
    SFX=${1}
    shift
    h=$(identify -format '%h' ${DST}.tiff)
    y=$((${h}/2))
    r=$((${h}/64))
    s=$((${r}/3))
    echo "h=${h}; y=${y}; blur ${r}x${s}"
    eval "${CONV} \
        \( ${DST}.tiff \
            ${FINAL} \
        \) \
        \(  -colorspace gray -virtual-pixel black -size ${h}x${h} xc:black \
            -fill white -box white -draw 'circle ${y},${y} ${y},1' \
            -blur ${r}x${s} \
        \) \
        -compose multiply -composite \
        ${@} \
        -quality 90 ${DST}${SFX}.jpeg"
    r=${?}
    return ${r}
}

final () {
    SFX=${1}
    shift
    echo "${SFX}: ${FQ}%"
    eval "${CONV} ${DST}.tiff ${FINAL} ${@} -quality 90 \
        -compress zip ${DST}${SFX}.tiff" \
    && ${CONV} ${DST}${SFX}.tiff -quality ${FQ} ${DST}${SFX}.jpeg
    r=${?}
    rm ${DST}${SFX}.tiff
    return ${r}
}

[ "${1}" = cluster -o "${1}" = mkldrmf -o "${1}" = mkhdrmf ] \
|| prep "${@}"
[ "${1}" = prep ] && exit
[ "${1}" = auto ] && { auto "${@}"; exit; }
[ "${1}" = cluster ] && { cluster "${@}"; exit; }
[ "${1}" = mkprocessrmf ] && { mkprocessrmf "${@}"; exit; }
{
    mkprocessrmf "${@}" >Makefile \
    && make \
    && { [ -n "${3}" ] || rm Makefile; }
} || exit ${?}
#if [ "${3}" = a ]
#then
#    inpaint 480x480+4224+5056 1
#    inpaint 64x128+4832+4576 2
#else
#    inpaint 320x64+64+2720 1
#    inpaint 128x64+7840+2688 2
#fi
#[ "${3}" = a ] || {
#    apply_patch2 64x96+1536+1952 64x96+1546+1952 1
#    apply_patch2 96x320+1504+2032 96x320+1568+2032 2
#}
inpaint 480x480+2976+2592 1
[ "${1}" = pano ] && exit
#[ -n "${3}" -a "${3}" != 1 ] || qtvr 
#[ "${3}" = b ] && globe
#resize='-resize x3072'
#[ "${3}" = d ] && resize=''
#[ "${3}" = b ] && resize="-crop 3584x3584+0+0 +repage ${resize}"
#[ "${3}" = e ] && resize="-rotate 90 ${resize}"
final=final
#[ "${3}" = a ] && final='final_fe'
echo ${final}
${CONV} ${DST}.tiff    ${resize}     -sharpen 0x0.85000 -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -huge -adaptive-sharpen 1x0.33 -sharpen 0x0.8 \
&& ${CONV} ${DST}.tiff -resize x1536 -sharpen 0x0.64418 -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -big -adaptive-sharpen 1x0.33 -sharpen 0x0.45 \
&& ${CONV} ${DST}.tiff -resize x768  -sharpen 0x0.48820 -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -middle -adaptive-sharpen 1x0.33 -sharpen 0x0.55 \
&& { SFQ=${FQ}; FQ=${QKF}; ${final} -kf -resize ${WKF} -sharpen 0x0.40 -adaptive-sharpen 1x0.33 -sharpen 0x0.67 -gamma 1.025; FQ=${SFQ}; } \
&& ${CONV} ${DST}.tiff -resize x384  -sharpen 0x0.36998 -compress ${IMCOMP} ${DST}.tiff \
&& ${CONV} ${DST}.tiff -resize x256  -sharpen 0x0.31459 -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -small -adaptive-sharpen 1x0.33 -sharpen 0x0.75 -gamma 1.05 \
&& rm ${DST}.tiff
exit
${CONV} ${DST}.tiff    ${resize}     -unsharp 0x0.75+0.6+0.05 -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -huge -adaptive-sharpen 1x0.33 -sharpen 0x0.80 \
&& ${CONV} ${DST}.tiff -resize x1536 -unsharp 0x0.70+0.6+0.04 -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -big -adaptive-sharpen 1x0.33 -sharpen 0x0.45 \
&& ${CONV} ${DST}.tiff -resize x768  -unsharp 0x0.65+0.5+0.04 -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -middle -adaptive-sharpen 1x0.33 -sharpen 0x0.55 \
&& { SFQ=${FQ}; FQ=${QKF}; ${final} -kf -resize ${WKF} -unsharp 0x0.65+0.5+0.04 -adaptive-sharpen 1x0.33 -sharpen 0x0.55 -gamma 1.025; FQ=${SFQ}; } \
&& ${CONV} ${DST}.tiff -resize x384  -unsharp 0x0.55+0.5+0.04 -compress ${IMCOMP} ${DST}.tiff \
&& ${CONV} ${DST}.tiff -resize x256  -unsharp 0x0.45+0.4+0.03 -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -small -gamma 1.10 -adaptive-sharpen 1x0.33 -sharpen 0x0.75 \
&& rm ${DST}.tiff
exit
${CONV} ${DST}.tiff    ${resize}     -sharpen 0x0.85000 -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -huge -sharpen 0x1.50000 \
&& ${CONV} ${DST}.tiff -resize x1536 -sharpen 0x0.64418 -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -big -sharpen 0x1.06070 \
&& ${CONV} ${DST}.tiff -resize x768  -sharpen 0x0.48820 -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -middle -sharpen 0x0.75000 \
&& ${CONV} ${DST}.tiff -resize x384  -sharpen 0x0.36998 -compress ${IMCOMP} ${DST}.tiff \
&& ${CONV} ${DST}.tiff -resize x256  -sharpen 0x0.31459 -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -small -sharpen 0x0.53033 -gamma 1.05 \
&& rm ${DST}.tiff
exit
${CONV} ${DST}.tiff    ${resize}     -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -huge -sharpen 0x1.41420 \
&& ${CONV} ${DST}.tiff -resize x1536 -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -big -sharpen 0x1.09590 \
&& ${CONV} ${DST}.tiff -resize x768  -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -middle -sharpen 0x0.84924 \
&& ${CONV} ${DST}.tiff -resize x384  -sharpen 0x0.65809 -compress ${IMCOMP} ${DST}.tiff \
&& ${CONV} ${DST}.tiff -resize x256  -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -small -sharpen 0x0.50997 -gamma 1.05 \
&& rm ${DST}.tiff
exit
${CONV} ${DST}.tiff    ${resize}     -sharpen 0x1.41420 -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -huge \
&& ${CONV} ${DST}.tiff -resize x1536 -sharpen 0x1.09590 -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -big \
&& ${CONV} ${DST}.tiff -resize x768  -sharpen 0x0.84924 -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -middle \
&& ${CONV} ${DST}.tiff -resize x384  -sharpen 0x0.65809 -compress ${IMCOMP} ${DST}.tiff \
&& ${CONV} ${DST}.tiff -resize x256  -sharpen 0x0.50997 -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -small -gamma 1.05 \
&& rm ${DST}.tiff
exit
${CONV} ${DST}.tiff    ${resize}     -sharpen 0x1.83038 -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -huge \
&& ${CONV} ${DST}.tiff -resize x1536 -sharpen 0x1.16331 -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -big \
&& ${CONV} ${DST}.tiff -resize x768  -sharpen 0x0.76105 -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -middle \
&& ${CONV} ${DST}.tiff -resize x384  -sharpen 0x0.51848 -compress ${IMCOMP} ${DST}.tiff \
&& ${CONV} ${DST}.tiff -resize x256  -sharpen 0x0.42410 -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -small -gamma 1.05 \
&& rm ${DST}.tiff
exit
${CONV} ${DST}.tiff    ${resize}     -sharpen 0x1.37500 -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -huge \
&& ${CONV} ${DST}.tiff -resize x1536 -sharpen 0x1.09130 -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -big \
&& ${CONV} ${DST}.tiff -resize x768  -sharpen 0x0.86620 -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -middle \
&& ${CONV} ${DST}.tiff -resize x384  -sharpen 0x0.68750 -compress ${IMCOMP} ${DST}.tiff \
&& ${CONV} ${DST}.tiff -resize x256  -sharpen 0x0.54567 -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -small -gamma 1.10 \
&& rm ${DST}.tiff
exit
${CONV} ${DST}.tiff    ${resize}     -sharpen 0x1.25000 -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -huge \
&& ${CONV} ${DST}.tiff -resize x1536 -sharpen 0x1.05110 -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -big \
&& ${CONV} ${DST}.tiff -resize x768  -sharpen 0x0.88388 -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -middle \
&& ${CONV} ${DST}.tiff -resize x384  -sharpen 0x0.74325 -compress ${IMCOMP} ${DST}.tiff \
&& ${CONV} ${DST}.tiff -resize x256  -sharpen 0x0.62500 -compress ${IMCOMP} ${DST}.tiff \
&& ${final} -small -gamma 1.10 \
&& rm ${DST}.tiff
exit
