#! /bin/sh
# This is a script to break a gif photo into pieces.
# Flydraw is used to do it.

cd `dirname $0`
pics=`ls photos/*.gif | sed 's!photos/!!g;s!\.gif!!g'`
fly=../../../../../other/bin/flydraw
levels="2x2 2x3 3x3 3x4 4x5"

p=`echo $pics`
echo !set photos=$p >photindex
echo !set levels=!words2items $levels >>photindex

for name in $pics
do
if [ ! -e pieces/$name ] || [ pieces/$name -ot photos/$name.gif ]; then
photo=photos/$name.gif
echo Cutting $photo...

siz=`identify -verbose '%x:%y' $photo 2>/dev/null | grep -i 'geometry:' | grep -iv page |
	awk '{print $2}'`
if [ -z "$siz" ]; then
 echo ImageMagick missing in your system. Impossible to cut photos.
 echo Program aborted.
 exit
fi
sizex=`echo $siz | awk -F x '{print $1}'`
sizey=`echo $siz | awk -F x '{print $2}'`

if [ ! -e pieces/$name ]; then mkdir -m 755 pieces/$name; fi
touch pieces/$name

for q in $levels
do
 echo q=$q
 qy=`echo $q | awk -F x '{print $1}'`
 qx=`echo $q | awk -F x '{print $2}'`
 if [ ! -e pieces/$name/$q ]; then mkdir -m 755 pieces/$name/$q; fi
 xp=$(($sizex/$qx))
 yp=$(($sizey/$qy))
 xpp=$(($xp-1))
 ypp=$(($yp-1))
 x=0
 while [ $x -lt $qx ]; do
  xstart=$(($xp*$x))
  xend=$(($xstart+$xp-2))
  y=0
  while [ $y -lt $qy ]; do
   ystart=$(($yp*$y))
   yend=$(($ystart+$yp-2))
   $fly pieces/$name/$q/p.$x.$y.gif <<@
new
size $xpp,$ypp
fill 0,0,192,192,192
copy 0,0,$xstart,$ystart,$xend,$yend,$photo
@
   y=$(($y+1))
  done
  x=$(($x+1))
 done
# fly -o pieces/$name/$q/p.bad.gif <<@ &>/dev/null
#new
#size $xp,$yp
#fill 0,0,0,0,0
#@
 chmod a+r pieces/$name/$q/*.gif
done

fi
done

