#!/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.387500 1.000000 2.125000 1.000000 -M -H 0 -q 3 -o 1 -n 40 -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"
REMAPLDR='eval nona -v -t ${CPUS} -m TIFF_m -r ldr -p UINT${DEPTH} -z DEFLATE -o tmp-'
LDRSFX='tif'
#REMAPHDR='eval nona -v -t ${CPUS} -m EXR_m -r hdr -p FLOAT -z DEFLATE -o tmp-'
#HDRSFX='exr'
REMAPHDR='eval nona -v -t ${CPUS} -m TIFF_m -r hdr -p FLOAT -z DEFLATE -o tmp-'
#REMAPHDR="${REMAPLDR}"
HDRSFX='tif'
FULLA='eval fulla -v -t ${CPUS} -s'
CCM='color_correct -E -c -p.03 -D64 -a-4096:4096+1024 -k24:40/32 -g28:36/32'
BLEND='eval enblend -v --compression=${ENCOMP} -m ${MEM} -b 16384 --fine-mask'
#BLEND='eval wine ~/.wine/drive_c/bin/enblend.exe -v --compression=${ENCOMP} -m ${MEM} -b 16384 --fine-mask'
#BLEND='eval enfuse -v --compression=${ENCOMP} -m ${MEM} -b 16384 --wExposure=0.01  --wSaturation=0.01  --wContrast=0.99 --HardMask'
#BLEND='sh ../../tools/smartblend'
EFUSE='eval enfuse -v --compression=${ENCOMP} -m ${MEM} -b 16384 --exposure-mu=0.4 --exposure-sigma=0.6'
#EFUSE='eval enfuse -v --compression=${ENCOMP} -m ${MEM} -b 16384 --wExposure=1.00  --wSaturation=0.05  --wContrast=0.33 --HardMask --GrayProjector=value'
FFUSE='eval enfuse -v --compression=${ENCOMP} -m ${MEM} -b 16384 --wExposure=0.01  --wSaturation=0.01  --wContrast=0.99 --HardMask'
MERGE='hugin_hdrmerge -vv -m khan -i 4 -a m'
MERGE='env MERGE=hugin_hdrmerge sh ../../tools/merge-wrapper -vv -m khan -i 4 -a m'
MERGE='unset EXIFTOOL EXIFTAG; sh ../../tools/pfshdrcalibrate-wrapper -v -r linear -g 7.5 -b 16'
MERGE='unset EXIFTOOL EXIFTAG; eval sh ../../tools/pfshdrcalibrate-wrapper -v -c none -f ${DST}.m -b 16'
#MERGE='hugin_hdrmerge -v -m khan -i 8 -a di'
#MERGE='hugin_hdrmerge -v -m avg -c -a di'
#MERGE='eval enfuse -v --compression=${ENCOMP} -m ${MEM} -b 16384'
#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'
DEGHOST='deghosting_mask -v -s 60 -c 0.8 -t 150 -i 16 -a mw'

#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.icm'
sRGBPROFILE='../../tools/profiles/sRGB.icm'
RGB="-profile ${sRGBPROFILE} -profile ${RGBPROFILE}"
sRGB="-profile ${RGBPROFILE} -profile ${sRGBPROFILE}"

PFSMAX=75013120
PFSMAX=$((12*1024*3*1024*12))
PFSHOST=192.168.0.55

LANG=C; export LANG

. ./.conf

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

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

[ -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 () {
        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
}

mkldrmf () {
    RM='rm -f'
    [ -z "${3}" ] || 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=''
    cat <<EOT
DST?=${DST}

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

CONV?=${CONV}
REMAP?=${REMAPLDR}
FFUSE?=${FFUSE}
EFUSE?=${EFUSE}
DEGHOST?=${DEGHOST}
BLEND?=${BLEND} ${f}

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

all: \${DST}.tiff

EOT
    SRC=''
    BLIN=''
    for s in ${SEC}
    do
        FUIN=''
        t=''
        eval "NAM=\${NAM${s}}"
        eval "EXP=\${EXP${s}}"
        nexp=$(echo "${EXP}" | wc -w)
        for e in ${EXP}
        do
            eval "ESF=\${ESF${e}}"
            eval "EV=\${EV${e}}; SEV=\${EV${e}S${s}}"
            eval "STARG=\${TARG${s}}; ETARG=\${TARGE${e}}; ESTARG=\${TARG${s}E${e}}"
            n="${NAM}${ESF}${FSF}.tiff"
            SRC="${SRC} ${n}"
            eval "$(awk '
                BEGIN {
                    i=0;
                }
                /^p / {
                    if (match($0,/ E[^ ]+/))
                        print "EP="substr($0,RSTART+2,RLENGTH-2);
                }
                /^i / {
                    if (match($0," n\"?"n"\"?")) {
                        print "I="i;
                        if (match($0,/ Eev[^ ]+/))
                            print "E="substr($0,RSTART+4,RLENGTH-4);
                        nextfile
                    }
                    ++i;
                }
            ' n=${n} ${DST}.pto)"
            [ -n "${I}" ] || return 1
            t=$(printf 'tmp-%04d.%s' ${I} ${LDRSFX})
            [ ${nexp} -gt 1 ] || E="${EP}"
            [ -z "${EV}" ] || E="${EV}"
            [ -z "${SEV}" ] || E="${SEV}"
            [ -z "${E}" ] || E="-e ${E}"
            cat <<EOT
${t}: \${DST}.pto ${n}
	@\${REMAP} -i ${I} ${E} \${DST}.pto
EOT
            FARG="${t}"
            [ -z "${LIN}" ] \
            || FARG="${FARG} ${sRGB}"
            [ -z "${STARG}" ] \
            || FARG="${FARG} ${STARG}"
            [ -z "${ETARG}" ] \
            || FARG="${FARG} ${ETARG}"
            [ -z "${ESTARG}" ] \
            || FARG="${FARG} ${ESTARG}"
            cat <<EOT
f${t}: ${t}
EOT
            if [ "${FARG}" = "${t}" ]
            then
                cat <<EOT
	@\${LN} ${t} f${t}
EOT
            else
                cat <<EOT
	@\${CONV} \\
		${FARG} \\
		-compress \${IMCOMP} f${t}
EOT
            fi
            cat <<EOT
	@\${RM} ${t}
EOT
            FUIN="${FUIN} f${t}"
        done
        FOUT="etmp-${NAM}.${LDRSFX}"
        cat <<EOT
${FOUT}: ${FUIN}
EOT
        if [ ${nexp} -gt 1 ]
        then
            [ -z "${STK}" ] \
            || cat <<EOT
	@env CONV='\${CONV}' RM='\${RM}' sh ../../tools/stackmask ${FUIN}
EOT
            [ -z "${DGH}" ] \
            || cat <<EOT
	@\${DEGHOST} ${FUIN}
	@for n in ${FUIN}; \\
	 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
            cat <<EOT
	@\${EFUSE} -o ${FOUT} ${FUIN}
EOT
        else
            cat <<EOT
	@\${LN} ${FUIN} ${FOUT}
EOT
        fi
        cat <<EOT
	@\${RM} ${FUIN}
EOT
        BLIN="${BLIN} ${FOUT}"
    done
    SRC="$(echo "${SRC}"|sed -e 's/^ *\(.*\) *$/\1/')"
    BLIN="$(echo "${BLIN}"|sed -e 's/^ *\(.*\) *$/\1/')"
    cat <<EOT

SRC=${SRC}
BLIN=${BLIN}

tmp.tiff: \${BLIN}
	@\${RM} \${SRC}
	@\${BLEND} -o tmp.tiff \${BLIN}
	@\${RM} \${BLIN}
\${DST}.tiff: tmp.tiff
	@\${CONV} tmp.tiff \\
		+matte +repage \\
		-compress \${IMCOMP} \${DST}.tiff
	@\${RM} tmp.tiff
EOT
#		-sharpen 0x0.25 \\
#		-rotate 90 \\
#		-unsharp 0x0.20 \\
#	@pfsin tmp.tiff \\
#	 | pfstmo_reinhard02 -v -k 0.09 \\
#	 | pfsgamma -m 0.9 -g 2.2 \\
#	 | pfsoutimgmagick \${DST}.tiff
#	@\${RM} tmp.tiff
#	@\${CONV} \${DST}.tiff \\
#		+matte +repage \\
#		-unsharp 0x0.3 \\
#		-compress \${IMCOMP} \${DST}.tiff
#		-unsharp 0x0.80+0.6+0.05 \\
}

mkhdrmf () {
    RM='rm -f'
    [ -z "${3}" ] || 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=''
    cat <<EOT
DST?=${DST}

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

CONV?=${CONV}
REMAP?=${REMAPHDR}
BLEND?=${BLEND} ${f}
MERGE?=${MERGE}
EXIFTFF?=${EXIFTFF}
EXIFTAG?=-EXIF:ShutterSpeedValue -EXIF:ApertureValue -EXIF:ISO

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

all: \${DST}.tiff

EOT
    SRC=''
    BLIN=''
    for a in ${SECT}
    do
        FUIN=''
        t=''
        eval "AEXP=\${EXP${a}}"
        nexp=$(echo "${AEXP}" | wc -w)
        for e in ${AEXP}
        do
            eval "$(echo ${e} | awk 'BEGIN{FS=":"}{print "e="$1"; aa="$2}')"
            eval "SFX=\${SFX${e}}"
            eval "EV=\${EV${e}}; AEV=\${EV${e}_${a}}"
            eval "ATARG=\${TARG_${a}}; ETARG=\${TARG${e}}; EATARG=\${TARG${e}_${a}}"
            [ -n "${aa}" ] || aa=${a}
            n="$(printf '%02d%s.tiff' ${aa} ${SFX})"
            SRC="${SRC} ${n}"
            eval "$(awk '
                BEGIN {
                    i=0;
                }
                /^p / {
                    if (match($0,/ E[^ ]+/))
                        print "EP="substr($0,RSTART+2,RLENGTH-2);
                }
                /^i / {
                    if (match($0," n\"?"n"\"?")) {
                        print "I="i;
                        if (match($0,/ Eev[^ ]+/))
                            print "E="substr($0,RSTART+4,RLENGTH-4);
                        nextfile
                    }
                    ++i;
                }
            ' n=${n} ${DST}.pto)"
            [ -n "${I}" ] || return 1
            t=$(printf 'tmp-%04d.%s' ${I} ${HDRSFX})
            [ ${nexp} -gt 1 ] || E="${EP}"
            [ -z "${EV}" ] || E="${EV}"
            [ -z "${AEV}" ] || E="${AEV}"
            [ -z "${E}" ] || E="-e ${E}"
            [ ${a} -ne ${aa} ] \
            || cat <<EOT
${t}: \${DST}.pto ${n}
	@\${REMAP} -i ${I} ${E} \${DST}.pto
EOT
            FARG="${t}"
            [ -z "${ATARG}" ] \
            || FARG="${FARG} ${ATARG}"
            [ -z "${ETARG}" ] \
            || FARG="${FARG} ${ETARG}"
            [ -z "${EATARG}" ] \
            || FARG="${FARG} ${EATARG}"
            cat <<EOT
f${t}: ${t}
EOT
            if [ "${FARG}" = "${t}" ]
            then
                cat <<EOT
	@\${LN} ${t} f${t}
EOT
            else
                cat <<EOT
	@\${CONV} \\
		${FARG} \\
		-compress \${IMCOMP} f${t}
EOT
            fi
            cat <<EOT
	@\${EXIFTFF} ${n} \${EXIFTAG} f${t}
	@\${RM} ${t}
EOT
            FUIN="${FUIN} f${t}"
        done
        FOUT=$(printf 'etmp-%02d.%s' ${a} ${HDRSFX})
        cat <<EOT
${FOUT}: ${FUIN}
EOT
        if [ ${nexp} -gt 1 ]
        then
            cat <<EOT
	@\${MERGE} -o ${FOUT} ${FUIN}
EOT
        else
            cat <<EOT
	@\${LN} ${FUIN} ${FOUT}
EOT
        fi
        cat <<EOT
	@\${RM} ${FUIN}
EOT
        BLIN="${BLIN} ${FOUT}"
    done
    SRC="$(echo "${SRC}"|sed -e 's/^ *\(.*\) *$/\1/')"
    BLIN="$(echo "${BLIN}"|sed -e 's/^ *\(.*\) *$/\1/')"
    resize=''
    #resize='-sharpen 0x0.75'
    #[ "${3}" = a ] \
    #|| resize='-unsharp 0x0.3 -resize x4096 -unsharp 0x0.75+0.6+0.05'
    #[ "${3}" = b ] \
    #|| resize='-unsharp 0x0.75+0.6+0.05'
    bright=1.33
    light=0.50
    chrom=0.95
    [ "${3}" = a ] && {
        bright=1.33
    }
    #[ "${3}" = b ] && {
    #    bright=-5.00
    #    light=0.30
    #}
    #[ "${3}" = b ] && bright=-1.50
    #[ "${3}" = b ] && light=0.9625
    cat <<EOT

SRC=${SRC}
BLIN=${BLIN}

tmp.tiff: \${BLIN}
	@\${RM} \${SRC}
	@\${BLEND} -o tmp.tiff \${BLIN}
	@\${RM} \${BLIN}
\${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 \\
		${resize} \\
		-compress \${IMCOMP} \${DST}.tiff
	@\${RM} \${DST}.0.tiff \${DST}.1.tiff \\
		\${DST}.2.tiff \${DST}.3.tiff \\
		\${DST}.4.tiff \${DST}.5.tiff
EOT
#	@\${CONV} \${DST}.0.tiff \${DST}.1.tiff \\
#		-compose overlay -composite \\
#		+matte +repage \\
#		${resize} \\
#		-compress \${IMCOMP} \${DST}.tiff
#	 | pfstmo_reinhard05 -v -b ${bright} -c ${chrom} -l ${light} \\
#	 | pfsoutimgmagick -s -b 16 \${DST}.tiff
#	 | pfsclamp --min 1e-20 --max 1e+20 \\
}

mkhdrmf-old () {
    RM='rm -f'
    [ -z "${3}" ] || 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)
    #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])}nextfile}' ${DST}.pto)
    [ -z "${c}" ] || f="-f ${c}"
    cat <<EOT
DST?=${DST}

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

CONV?=${CONV}
REMAP?=${REMAPHDR}
BLEND?=${BLEND} ${f}
MERGE?=${MERGE}
EXIFTFF?=${EXIFTFF}
EXIFTAG?=${EXIFTAG}

RM=${RM}
MV=mv

all: \${DST}.tiff

EOT
    SRC=''
    BLIN=''
    for a in ${SECT}
    do
        FUIN=''
        MASK=''
        t=''
        eval "AEXP=\${EXP${a}}"
        for e in ${AEXP}
        do
            DEP=${t}
            eval "$(echo ${e} | awk 'BEGIN{FS=":"}{print "e="$1"; aa="$2}')"
            eval "SFX=\${SFX${e}}"
            eval "EV=\${EV${e}}; AEV=\${EV${e}_${a}}"
            [ -n "${aa}" ] || aa=${a}
            n="$(printf '%02d%s.tiff' ${aa} ${SFX})"
            SRC="${SRC} ${n}"
            eval "$(awk '
                BEGIN {
                    i=0;
                }
                /^p / {
                    if (match($0,/ E[^ ]+/))
                        print "EP="substr($0,RSTART+2,RLENGTH-2);
                }
                /^i / {
                    if (match($0," n\"?"n"\"?")) {
                        print "I="i;
                        if (match($0,/ Eev[^ ]+/))
                            print "E="substr($0,RSTART+4,RLENGTH-4);
                        nextfile
                    }
                    ++i;
                }
            ' n=${n} ${DST}.pto)"
            [ -n "${I}" ] || return 1
            t=$(printf 'tmp-%04d.%s' ${I} ${HDRSFX})
            m=$(printf 'tmp-%04d_gray.pgm' ${I})
            FUIN="${FUIN} ${t}"
            MASK="${MASK} ${m}"
            #[ ${a} -eq ${aa} ] || continue
            FOUT=${t}
            #[ ${nexp} -gt 1 ] || E="${EP}"
            [ -z "${EV}" ] || E="${EV}"
            [ -z "${AEV}" ] || E="${AEV}"
            [ -z "${E}" ] || E="-e ${E}"
            cat <<EOT
${t}: \${DST}.pto ${n} ${DEP}
	@\${REMAP} -i ${I} ${E} \${DST}.pto
	@\${EXIFTFF} ${n} \${EXIFTAG} ${t}
EOT
        done
        FUIN="$(echo "${FUIN}"|sed -e 's/^ *\(.*\) *$/\1/')"
        MASK="$(echo "${MASK}"|sed -e 's/^ *\(.*\) *$/\1/')"
        [ "${FUIN}" = "${FOUT}" ] || \
        cat <<EOT
	@\${MERGE} -o .${FOUT} ${FUIN}
	@\${RM} ${FUIN}
	@\${MV} .${FOUT} ${FOUT}
EOT
        cat <<EOT
	@\${RM} ${MASK}
EOT
        BLIN="${BLIN} ${FOUT}"
    done
    SRC="$(echo "${SRC}"|sed -e 's/^ *\(.*\) *$/\1/')"
    BLIN="$(echo "${BLIN}"|sed -e 's/^ *\(.*\) *$/\1/')"
    resize=''
    #resize='-sharpen 0x0.75'
    #[ "${3}" = a ] \
    #|| resize='-unsharp 0x0.3 -resize x4096 -unsharp 0x0.75+0.6+0.05'
    #[ "${3}" = b ] \
    #|| resize='-unsharp 0x0.75+0.6+0.05'
    bright=0
    light=0.45
    chrom=0.80
    [ "${3}" = b ] && bright=-1.50
    [ "${3}" = b ] && light=0.9625
    cat <<EOT

SRC=${SRC}
BLIN=${BLIN}

tmp.tiff: \${BLIN}
	@\${RM} \${SRC}
	@\${BLEND} -o tmp.tiff \${BLIN}
	@\${RM} \${BLIN}
\${DST}.tiff: tmp.tiff
	@pfsin tmp.tiff \\
	 | pfsclamp --min 1e-20: --max 1e+20 \\
	 | pfswb -v -r 1.2500 -g 1.0000 -b 0.5500 \\
	 | pfstmo_reinhard05 -v -b ${bright} -c ${chrom} -l ${light} \\
	 | pfsoutimgmagick -s -b 16 \${DST}.tiff
	@\${RM} tmp.tiff
	@\${CONV} \${DST}.tiff \\
		+matte +repage \\
		${resize} \\
		-compress \${IMCOMP} \${DST}.tiff
EOT
#	 | pfstmo_mantiuk06 -v -f 0.45 -s 0.75 \\
#	 | pfsgamma -m 0.825 -g 2.2 \\
#	 | pfstmo_mantiuk08 -v -d pd=crt -c 0.40 -e 1.00 \\
#	 | pfsgamma -m 0.65 -g 1.00 \\
#	 | pfstmo_reinhard02 -v -k 0.090 \\
#	 | pfsgamma -m 0.825 -g 2.185 \\
#	 | pfstmo_reinhard02 -v -k 0.0225 \\
#	 | pfsgamma -m 0.750 -g 2.300 \\
#	 | pfsoutimgmagick \${DST}.tiff
}

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 \
    && ${REMAPLDR} -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}" = mkldrmf ] && { mkldrmf "${@}"; exit; }
[ "${1}" = mkhdrmf ] && { mkhdrmf "${@}"; exit; }
#mkpano "${@}" || exit ${?}
#mkpanohdr "${@}" || exit ${?}
#mkpanofuse "${@}" || exit ${?}
#{ mkldrmf "${@}" >Makefile && make && { [ -n "${3}" ] || rm Makefile; } } || exit ${?}
{ mkhdrmf "${@}" >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
#}
[ "${1}" = pano ] && exit
#mkhdr "${@}" || exit ${?}
#[ "${1}" = hdr ] && 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
