#!/bin/sh

SRC='P1000114 P1000115'
CONF='P1000114'
DST='sky-2'

UFRAW='ufraw-batch --interpolation=ahd --out-type=tiff16 --overwrite --zip --wavelet-denoising-threshold=350'
NONA='nona -t 2 -o tmp-'
FULLA='fulla -t 2'
CCM='color_correct -E -c -p.03 -D64 -a-4096:4096+1024 -k24:40/32 -g28:36/32 -otmp.tiff'
ENBL='enblend -w -z -m 896 --fine-mask'
#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'

LANG=C; export LANG

N=0
for n in ${SRC}
do
    o=$(printf '%02d.tiff' ${N})
    N=$((${N}+1))
    [ -r ${o} ] && continue
    [ -r ${n}.RAW.bz2 ] && bzcat ${n}.RAW.bz2 >${n}.RAW
    [ -r ${n}.RAW.gz ] && zcat ${n}.RAW.gz >${n}.RAW
    [ -r ${n}.RAW ] || exit 126
    fl=$(dcraw -i -v ${n}.RAW|awk '/^Focal length: /{print $3}')
    conf=${n}.ufraw
    [ -z "${CONF}" ] || conf=${CONF}.ufraw
    [ -r ${conf} ] || exit 125
    ${UFRAW} --conf=${conf} --output=${n}.tiff ${n}.RAW
    [ -r ${n}.RAW.bz2 -o -r ${n}.RAW.gz ] && rm -f ${n}.RAW
    tca="$( ( cd ../../tools/tca && echo "disp(tca('tca.db','fz50',${fl},1,0))"|octave -q|cat|head -1 ) )"
    ${FULLA} ${tca} -o ${n}.tiff ${n}.tiff
    ${CONV} ${n}.tiff \
        -enhance -unsharp 0x1.25 \
        -compress zip ${o}
    rm -f ${n}.tiff
done
#exit

${NONA} ${DST}.pto \
&& rm [0-9][0-9].tiff \
&& ${ENBL} -f 5776x4332 -o tmp.tiff tmp-0*.tif \
&& rm tmp-0*.tif \
&& ${CONV} tmp.tiff \
    -crop 5344x2080+260+360 +repage \
    -compress zip ${DST}.tiff \
&& rm tmp.tiff \
&& ${CONV} ${DST}.tiff -resize 2048 -unsharp 0x0.5+0.6+0.04 -density 300 -compress zip ${DST}-prn.tiff \
&& ${CONV} ${DST}.tiff -resize x1536 -unsharp 0x0.75+0.6+0.04 -compress zip ${DST}.tiff \
&& ${CONV} ${DST}.tiff -gamma 1.0 -quality 90 ${DST}-big.jpeg \
&& ${CONV} ${DST}.tiff -resize x768 -unsharp 0x0.75+0.6+0.04 -compress zip ${DST}.tiff \
&& ${CONV} ${DST}.tiff -gamma 1.0 -quality 90 ${DST}.jpeg \
&& ${CONV} ${DST}.tiff -resize x384 -unsharp 0x0.65+0.6+0.03 -compress zip ${DST}.tiff \
&& ${CONV} ${DST}.tiff -resize x256 -unsharp 0x0.65+0.6+0.03 -compress zip ${DST}.tiff \
&& ${CONV} ${DST}.tiff -gamma 1.1 -quality 90 ${DST}-small.jpeg \
&& rm ${DST}.tiff \
&& exit
