#!/bin/bash

srcdir=$1

set `cat $srcdir/centers|awk '{
  if (($2<xmin)||(xmin==0)) xmin=$2; 
  if ($2>xmax) xmax=$2;
  if (($3<ymin)||(ymin==0)) ymin=$3;
  if ($3>ymax) ymax=$3;
  xtot+=$2;
  ytot+=$3;
  ++count;
} 
END {
  printf "%d %d %d %d %d %d",xmin,xmax,ymin,ymax,xtot/count,ytot/count 
}'`

cx=$5
cy=$6

dx1=`expr $2 - $cx`
dx2=`expr $cx - $1`
if [ $dx1 -lt $dx2 ]; then
	dx=`expr $dx1 \* 2`
else
	dx=`expr $dx2 \* 2`
fi

dy1=`expr $4 - $cy`
dy2=`expr $cy - $3`
if [ $dy1 -lt $dy2 ]; then
	dy=`expr $dy1 \* 2`
else
	dy=`expr $dy2 \* 2`
fi

odx=`expr $dx / 8`
ody=`expr $dy / 6`
if [ $ody -gt $odx ]; then
	odx=$ody
fi
dx=`expr $odx \* 8`
dy=`expr $odx \* 6`
sx=`expr 640 - $dx`
sy=`expr 480 - $dy`

echo "cropping 640x480 to $sx"x"$sy"

for i in $srcdir/*.jpg; do
	image=`basename $i`
	set `grep $image $srcdir/centers`
	ix=$2
	iy=$3
	ox=`expr $dx / 2 + $ix - $cx`
	oy=`expr $dy / 2 + $iy - $cy`
	if [ $ox -lt 0 ]; then ox=0; fi
	if [ $oy -lt 0 ]; then oy=0; fi
	if [ $ox -gt $dx ]; then ox=$dx; fi
	if [ $oy -gt $dy ]; then oy=$dy; fi
	convert -crop ${sx}x${sy}+${ox}+${oy} -compress none $i $i.tif
done

convert -delay $DELAY -gamma $GAMMA -sample $SIZE -compress lzw $srcdir/*.tif $OUTPUT
rm $srcdir/*.tif
