#!/bin/sh

INDEXDAT="index.dat"
IMGNUM="`echo ${QUERY_STRING} | sed s/[^0-9]//g`"
TOTALIMG="`egrep -v '(^#|^$)' $INDEXDAT | wc -l | awk '{print $1}'`"
HEADER="${DOCUMENT_ROOT}/Stuff/gallery-header-noflash.html"
FOOTER="${DOCUMENT_ROOT}/Stuff/gallery-footer.html"
VIEWER="${DOCUMENT_ROOT}/Stuff/gallery-viewer-noflash.html"

if [ -f "title.dat" ] ; then
  TITLE=" - `cat title.dat`"
fi

if [ -z "${IMGNUM}" ] ; then
  IMGNUM=1
fi

echo "Content-type: text/html" ; echo


showIndex() {
pagewidth=`expr \( ${TOTALIMG} / 6 + 1 \) \* 64`

sed "s~%%TITLE%%~${TITLE}~; \
     s~%%DEFAULTIMAGE%%~${IMGNUM}~; \
     s~%%WIDTH%%~${pagewidth}~;" < ${HEADER}

egrep -v '(^#|^$)' $INDEXDAT \
  | awk '(NR%6 == 1) { printf("    <div class=\"thumbsCol\">\n") } 
    { printf("      <div><a href=\"?%d\" target=\"view\"><img src=\"thumbs/%s\" alt=\"\" /></a></div>\n",NR,$1) }
    (NR%6 == 0) { printf("      <p class=\"index\">%d</p>\n    </div>\n\n", NR) }
    END { if ( NR%6 ) printf("    </div>\n\n")}'

cat ${FOOTER}
}


showImage() {

this="${IMGNUM}"

if [ ${this} -le 1 ] ; then
  this=1
elif [ ${this} -ge ${TOTALIMG} ] ; then
  this=${TOTALIMG}
fi

prev=`expr ${this} - 1`
next=`expr ${this} + 1`

egrep -v '(^#|^$)' $INDEXDAT | awk -v line=${this} '(NR == line)' | while read img width height caption ; do
  margin=`expr \( 470 - $height - 20 \) / 2`
  prevurl=`printf ?%d $prev`
  nexturl=`printf ?%d $next`
if [ -z "${caption}" ] ; then
  caption=`printf '(%03d)' ${this}`
else
  caption=`printf '(%03d) ' ${this} ; echo $caption`
fi

#echo '<pre>'
#env
#echo '</pre>'

  sed "s~%%TITLE%%~${TITLE}~; \
       s~%%IMAGEPATH%%~images/${img}~; \
       s~%%IMAGEWIDTH%%~${width}~; \
       s~%%IMAGEHEIGHT%%~${height}~; \
       s~%%IMAGEMARGIN%%~${margin}~; \
       s~%%PREVURL%%~${prevurl}~; \
       s~%%NEXTURL%%~${nexturl}~; \
       s~%%CAPTION%%~${caption}~;" < ${VIEWER}
done
}

if [ -z "${QUERY_STRING}" ] ; then
  showIndex
else
  showImage
fi