#! /bin/tcsh -f
# Last edited on 2008-02-04 20:30:59 by stolfi

set cmd = "$0"; set cmd = "${cmd:t}"
set usage = "${cmd} IMG DXA DYA MGA  DXB DYB MGB  DXC DYC MGC"

# Aligns three photometric stereo images 
# ${indir}/${IMG}a.jpg, ${indir}/${IMG}b.jpg, ${indir}/${IMG}c.jpg
# (same camera, different lights), by applying a translation (-DX,-DY)
# and a uniform scaling by a factor MG to each image.
# Output goes to align/${IMG}{a,b,c}-L.png

if ( $#argv != 10 ) then
  echo "usage: ${usage}"; exit 1
endif

set img = "$1"; shift;

set dxa = "$1"; shift;
set dya = "$1"; shift;
set mga = "$1"; shift;

set dxb = "$1"; shift;
set dyb = "$1"; shift;
set mgb = "$1"; shift;

set dxc = "$1"; shift;
set dyc = "$1"; shift;
set mgc = "$1"; shift;

set indir = ${STOLFIHOME}/projects/fragments/IAB-2002/raw-sorted
set otdir = ${STOLFIHOME}/projects/fragments/IAB-2002/raw-aligns

(cd ${indir}/. )

set imgin = "${indir}/${img}"
set imgot = "${otdir}/${img}"
set tmp = /tmp/$$

echo "aligning ${imgin}{a,b,c}.jpg -> ${imgot}{a,b,c}-L.png"

if ( ! ( -d ${imgot:h} ) ) then
  mkdir -p ${imgot:h}
endif

gawk \
  -v dxa=${dxa} -v dxb=${dxb} -v dxc=${dxc} \
  -v dya=${dya} -v dyb=${dyb} -v dyc=${dyc} \
  -v mga=${mga} -v mgb=${mgb} -v mgc=${mgc} \
    ' BEGIN{ \
        wxa=2048*mga-dxa; wxb=2048*mgb-dxb; wxc=2048*mgc-dxc; \
        wxm=(wxa<wxb ? wxa : wxb); wxm=(wxm<wxc ? wxm : wxc); \
        wya=1536*mga-dya; wyb=1536*mgb-dyb; wyc=1536*mgc-dyc; \
        wym=(wya<wyb ? wya : wyb); wym=(wym<wyc ? wym : wyc); \
        printf "%d %d\n", wxm-1, wym-1; \
      } ' \
  > ${imgot}.size

set sz = ( `cat ${imgot}.size` )

echo "aligned image size = ${sz}"

cat ${imgin}a.jpg \
  | convert jpg:- ppm:- \
  | pnmscale ${mga} \
  | pnmcut ${dxa} ${dya} ${sz[1]} ${sz[2]} \
  | convert ppm:- png:- \
  > ${imgot}a-L.png

cat ${imgin}b.jpg \
  | convert jpg:- ppm:- \
  | pnmscale ${mgb} \
  | pnmcut ${dxb} ${dyb} ${sz[1]} ${sz[2]} \
  | convert ppm:- png:- \
  > ${imgot}b-L.png

cat ${imgin}c.jpg \
  | convert jpg:- ppm:- \
  | pnmscale ${mgc} \
  | pnmcut ${dxc} ${dyc} ${sz[1]} ${sz[2]} \
  | convert ppm:- png:- \
  > ${imgot}c-L.png
