#!/bin/bash

patchsize=64
marginsize=8
tmp=./tmp
source=./final
dest=~web/html/jade-warrior/covers

titles=$(cat filelist)

count=0
rm -f $tmp/text.txt

for foo in $titles ; do
  cat $source/$foo.ttl >> $tmp/text.txt
  count=$[count+1]
done

pbmtext < $tmp/text.txt > $tmp/text.pbm

textwidth=$(pnmfile $tmp/text.pbm | awk '{print $4}')

horiz=5

hsize=$[horiz*patchsize+(horiz+3)*marginsize+textwidth]
vsize=$[count*patchsize+(count+2)*marginsize]

echo "base http://feghoot.ml.org/jade-warrior/covers/" > $tmp/composite.map

echo Making background, $hsize by $vsize

ppmmake rgb:0/0/0 $hsize $vsize > $tmp/composite.ppm

voffset=$marginsize

for foo in $titles ; do
  hoffset=$[textwidth+2*marginsize]
  pbmtext < $source/$foo.ttl | pnminvert > $tmp/text.pbm
  textheight=$(pnmfile $tmp/text.pbm | awk '{print $6}')
  insertvert=$[voffset+(patchsize-textheight)/2]
  pnmpaste -replace $tmp/text.pbm $marginsize $insertvert $tmp/composite.ppm > $tmp/newcomposite.ppm
  mv $tmp/newcomposite.ppm $tmp/composite.ppm
  for bar in A B C D E; do
    echo Processing $foo-$bar
    hlimit=$[hoffset+patchsize]
    vlimit=$[voffset+patchsize]
    if [ -f $source/$foo-$bar.tif ] ; then
      tifftopnm $source/$foo-$bar.tif | \
        pnmscale -xysize $patchsize $patchsize > $tmp/patch.pnm
      pnmpaste -replace $tmp/patch.pnm $hoffset $voffset $tmp/composite.ppm > \
        $tmp/newcomposite.ppm
      mv $tmp/newcomposite.ppm $tmp/composite.ppm
      if [ -f $dest/$foo-$bar.jpg -a $dest/$foo-$bar.jpg -nt $source/$foo-$bar.tif ] ; then
	 echo $dest/$foo-$bar.jpg exists, no need to rebuild
      else
         echo Building $dest/$foo-$bar.jpg
         tifftopnm $source/$foo-$bar.tif | \
           cjpeg -quality 90 > $dest/$foo-$bar.jpg
      fi
      echo "rect $foo-$bar.jpg $hoffset,$voffset $hlimit,$vlimit" >> $tmp/composite.map
    elif [ -f $source/$foo-$bar.gif ] ; then
      giftoppm $source/$foo-$bar.gif | \
        pnmscale -xysize $patchsize $patchsize > $tmp/patch.pnm
      pnmpaste -replace $tmp/patch.pnm $hoffset $voffset $tmp/composite.ppm > \
        $tmp/newcomposite.ppm
      mv $tmp/newcomposite.ppm $tmp/composite.ppm
      cp $source/$foo-$bar.gif $dest
      echo "rect $foo-$bar.gif $hoffset,$voffset $hlimit,$vlimit" >> $tmp/composite.map
    elif [ -f $source/$foo-$bar.jpg ] ; then
    	djpeg $source/$foo-$bar.jpg |  \
        pnmscale -xysize $patchsize $patchsize > $tmp/patch.pnm
      pnmpaste -replace $tmp/patch.pnm $hoffset $voffset $tmp/composite.ppm > \
        $tmp/newcomposite.ppm
      mv $tmp/newcomposite.ppm $tmp/composite.ppm
      cp $source/$foo-$bar.jpg $dest
      echo "rect $foo-$bar.jpg $hoffset,$voffset $hlimit,$vlimit" >> $tmp/composite.map
    else
      echo "No file available"
    fi
    hoffset=$[hoffset+patchsize+marginsize]
  done
  voffset=$[voffset+patchsize+marginsize]
done

cjpeg < $tmp/composite.ppm > $dest/composite.jpg
cp $tmp/composite.map $dest/composite.map

