#!/usr/bin/env bash

# bpgallery.sh - builds a simple 'gallery' from a collection of images
# Copyright (C) 2004-2008 Brett Parker <iDunno@sommitrealweird.co.uk>
#
# This program is free software; you can redistribute it and/or modify 
# it under the terms of the GNU General Public License as published by 
# the Free Software Foundation; either version 2 of the License, or 
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

set -f

VERSION="1.1.5"

function bpgallery_default_head() {
cat <<END
<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
	<title>${TITLE}</title>
	<link rel="stylesheet" href="${BASEURL}style.css" type="text/css" />
</head>
<body>
END
}

declare -rf bpgallery_default_head

function bpgallery_default_description() {
cat <<END
	<h1>${TITLE}</h1>
	${DESCRIPTION}
END
}

declare -rf bpgallery_default_description

function bpgallery_default_thumbsline() {
if [[ -z $caption ]]; then
	caption_alt=Unknown
else
	caption_alt=$caption
fi
cat << END
<div class="thumbnail"><a href="$link"><img src="${ICONSDIRECTORY}/$filename" alt="$caption_alt" /></a><div class="caption">$caption</div></div>
END
}

declare -rf bpgallery_default_thumbsline

function bpgallery_default_tail() {
cat << END
</body>
</html>
END
}

declare -rf bpgallery_default_tail

function bpgallery_default_stylesheet() {
cat <<END
body {
	background: white;
	color: black;
	font-family: sans-serif;
	font-size: 10pt;
}

div.thumbnail {
	float: left;
	padding: 20px;
	border: 0px;
	width: ${MAXWIDTH}px;
	height: ${MAXHEIGHT}px;
	text-align: center;
}

div.caption {
	width: 100%;
	text-align: center;
	font-weight: bold;
}

div.navigation {
	margin: 0;
}

div.navigation ul {
	display: inline;
	margin: 0;
	padding: 0;
	text-align: center;
}

div.navigation ul li {
	display: inline;
	margin: 2em;
}

a {
	border: 0px;
}

img {
	border: 0px;
}
END
}

declare -rf bpgallery_default_stylesheet

function bpgallery_default_page() {
	$BPGALLERY_HEAD_FUNCTION

	linkstart=""
	linkend=""

	if [[ ! -z $linklocation ]]; then
		linkstart="<a href='$linklocation'>"
		linkend="</a>"
	fi
	
	cat <<END
<h1>${caption}</h1>
<div class="navigation">
	<ul>
		<li><a href='${BASEURL}${INDEXDOCUMENT}'>Thumbnails</a></li>
END
	if [[ ! -z $previouspage ]]; then
		$ECHOCOMMAND "<li><a href='${previouspage}'>Previous</a></li>"
	else
		$ECHOCOMMAND "<li>Previous</li>"
	fi

	if [[ ! -z $nextpage ]]; then
		$ECHOCOMMAND "<li><a href='${nextpage}'>Next</a></li>"
	else
		$ECHOCOMMAND "<li>Next</li>"
	fi
cat <<END
	</ul>
</div>
<div class="mainimage">
	${linkstart}<img src="${filename}" alt="${caption}" />${linkend}
</div>
END
	$BPGALLERY_TAIL_FUNCTION
}

declare -rf bpgallery_default_page

function bpgallery_escape_url() {
	temp=$1
	temp=${temp//\%/%25}
	temp=${temp//:/%3A}
	temp=${temp//;/%3B}
	temp=${temp// /%20}
	temp=${temp//$/%24}
	temp=${temp//&/%26}
	temp=${temp//+/%2B}
	temp=${temp//,/%2C}
	temp=${temp//\//%2F}
	temp=${temp//=/%3D}
	temp=${temp//\?/%3F}
	temp=${temp//@/%40}
	temp=${temp//\"/%22}
	$ECHOCOMMAND $temp
}

function bpgallery_cleanup_directory_name() {
	temp=$1
	temp=${temp//\%/_}
	temp=${temp//:/_}
	temp=${temp//;/_}
	temp=${temp// /_}
	temp=${temp//$/_}
	temp=${temp//&/_}
	temp=${temp//+/_}
	temp=${temp//,/_}
	temp=${temp//\//_}
	temp=${temp//=/_}
	temp=${temp//\?/_}
	temp=${temp//@/_}
	temp=${temp//\"/_}
	$ECHOCOMMAND $temp
}

declare -rf bpgallery_escape_url

if [[ ! -z ${BPGALLERY_THEME} ]] ; then
	declare -r BPGALLERY_THEME
fi

if [[ ! -z ${TITLE} ]] ; then
	declare -r TITLE
fi

if [[ -e /usr/local/etc/bpgallery/config ]] ; then
	. /usr/local/etc/bpgallery/config 2>/dev/null
fi

if [[ -e /etc/bpgallery/config ]] ; then
	. /etc/bpgallery/config 2>/dev/null
fi

if [[ -e $HOME/.bpgallery.rc ]]; then
	. $HOME/.bpgallery.rc 2>/dev/null
fi

if [[ -e $1 && -d $1 && -e $1/.bpgallery.rc ]]; then
	. $1/.bpgallery.rc 2>/dev/null
fi

if [[ -z ${BPGALLERY_THEME} ]]; then
	BPGALLERY_THEME=default
fi

if [[ ! -z ${BPGALLERY_THEME_DIR} ]] && \
	[[ -e ${BPGALLERY_THEME_DIR}/${BPGALLERY_THEME} ]]; then
	. ${BPGALLERY_THEME_DIR}/${BPGALLERY_THEME} 2>/dev/null
elif [[ -e $HOME/.bpgallery.themes/${BPGALLERY_THEME} ]]; then
	. $HOME/.bpgallery.themes/${BPGALLERY_THEME} 2>/dev/null
elif [[ -e /usr/local/etc/bpgallery/themes/${BPGALLERY_THEME} ]]; then
	. /usr/local/etc/bpgallery/themes/${BPGALLERY_THEME} 2>/dev/null
elif [[ -e /etc/bpgallery/themes/${BPGALLERY_THEME} ]]; then
	. /etc/bpgallery/themes/${BPGALLERY_THEME} 2>/dev/null
fi

if [[ -z $TITLE ]]; then 
	TITLE="Photo Gallery"
fi

if [[ -z $CONVERTTOOL ]]; then
	hash convert
	if [[ $? != 0 ]]; then
		echo "Can't find convert, exiting"
		exit 3
	fi
	CONVERTTOOL=$(hash -t convert)
else
	if [[ ! -x $CONVERTTOOL ]]; then
		echo "Can't find convert at location $CONVERTTOOL, exiting"
		exit 3
	fi
fi

if [[ -z $FINDCOMMAND ]]; then
	hash find
	if [[ $? != 0 ]]; then
		echo "Can't find find, exiting"
		exit 3
	fi
	FINDCOMMAND=$(hash -t find)
else
	if [[ ! -x $FINDCOMMAND ]]; then
		echo "Can't find find at $FINDCOMMAND, exiting"
		exit 3
	fi
fi

if [[ -z $XARGSCOMMAND ]]; then
	hash xargs
	if [[ $? != 0 ]]; then
		echo "Can't find xargs, exiting"
		exit 3
	fi
	XARGSCOMMAND=$(hash -t xargs)
else
	if [[ ! -x $XARGSCOMMAND ]]; then
		echo "Can't find xargs at $XARGSCOMMAND, exiting"
		exit 3
	fi
fi

if [[ -z $ECHOCOMMAND ]]; then
	ECHOCOMMAND=echo
else
	if [[ ! -x $ECHOCOMMAND ]]; then
		echo "Can't find echo at $ECHOCOMMAND, exiting"
		exit 3
	fi
fi

if [[ -z $SORTCOMMAND ]]; then
	hash sort
	if [[ $? != 0 ]]; then
		echo "Can't find sort, exiting"
		exit 3
	fi
	SORTCOMMAND=$(hash -t sort)
else
	if [[ ! -x $SORTCOMMAND ]]; then
		echo "Can't find sort, exiting"
		exit 3
	fi
fi

if [[ -z $IDENTIFYCOMMAND ]]; then
	hash identify
	if [[ $? != 0 ]]; then
		echo "Can't find indentify, exiting"
		exit 3
	fi
	IDENTIFYCOMMAND=$(hash -t identify)
else
	if [[ ! -x $IDENTIFYCOMMAND ]]; then
		echo "Can't find identify at $IDENTIFYCOMMAND, exiting"
		exit 3
	fi
fi

if [[ -z $HEADCOMMAND ]]; then
	hash head
	if [[ $? != 0 ]]; then
		echo "Can't find head, exiting"
		exit 3
	fi
	HEADCOMMAND=$(hash -t head)
else
	if [[ ! -x $HEADCOMMAND ]]; then
		echo "Can't find head at $HEADCOMMAND, exiting"
		exit 3
	fi
fi

if [[ -z $GREPCOMMAND ]]; then
	hash grep
	if [[ $? != 0 ]]; then
		echo "Can't find grep, exiting"
		exit 3
	fi
	GREPCOMMAND=$(hash -t grep)
else
	if [[ ! -x $GREPCOMMAND ]]; then
		echo "Can't find grep at $GREPCOMMAND, exiting"
		exit 3
	fi
fi

if [[ -z $SEDCOMMAND ]]; then
	hash sed
	if [[ $? != 0 ]]; then
		echo "Can't find sed, exiting"
		exit 3
	fi
	SEDCOMMAND=$(hash -t sed)
else
	if [[ ! -x $SEDCOMMAND ]]; then
		echo "Can't find sed at $SEDCOMMAND, exiting"
		exit 3
	fi
fi

if [[ -z $WCCOMMAND ]]; then
	hash wc
	if [[ $? != 0 ]]; then
		echo "Can't find wc, exiting"
		exit 3
	fi
	WCCOMMAND=$(hash -t wc)
	WCCOMMAND="$WCCOMMAND -l"
else
	if [[ ! -x $WCCOMMAND ]]; then
		echo "Can't find wc at $WCCOMMAND, exiting"
		exit 3
	fi
	WCCOMMAND="$WCCOMMAND -l"
fi

if [[ -z $MAXTHREADS ]]; then
	# if there's more than 2G of memory, then do 4 threads, otherwise, just 1
	__total_memory=$(free -t -g | sed -ne '2 { s#Mem:[[:space:]]*\([0-9]*\)[[:space:]]*.*$#\1#; p; }')
	if [[ $__total_memory -ge 2 ]]; then
		MAXTHREADS=4
	else
		MAXTHREADS=1
	fi
fi

if [[ -z $WIDTH ]]; then
	WIDTH=100
fi

if [[ -z $IMAGEEXTENSIONS ]]; then
	IMAGEEXTENSIONS="jpeg jpg gif png";
fi

if [[ -z $CAPTIONHEIGHT ]]; then
	CAPTIONHEIGHT=75
fi

if [[ -z $OUTPUTHTML ]]; then
	OUTPUTHTML=0
fi

if [[ -z $GENERATEPAGESFORFULLSIZE ]]; then
	GENERATEPAGESFORFULLSIZE=0
fi

if [[ -z $GENERATEPAGESFORMEDIUMSIZE ]]; then
	GENERATEPAGESFORMEDIUMSIZE=1
fi

if [[ -z $PAGESDIRECTORY ]]; then
	PAGESDIRECTORY=""
else
	removetrailingslashes=${PAGESDIRECTORY%/}
	temp=$removetrailingslashes
	while [[ $removetrailingslashes != $temp ]]; do
		temp=$removetrailingslashes
		removetrailingslashes=${temp%/}
	done
	PAGESDIRECTORY=$(bpgallery_escape_url "${PAGESDIRECTORY}")
fi

if [[ -z $MEDIUMWIDTH ]]; then
	MEDIUMWIDTH=400
fi

if [[ -z $INDEXDOCUMENT ]]; then
	INDEXDOCUMENT=index.html
fi

if [[ -z $MEDIUMDIRECTORY ]]; then
	MEDIUMDIRECTORY=medium
else
	# Strip out anything that might be broken
	MEDIUMDIRECTORY=$(bpgallery_cleanup_directory_name "$MEDIUMDIRECTORY")
fi

if [[ -z $ICONSDIRECTORY ]]; then
	ICONSDIRECTORY=icons
else
	# Strip out anything that might be broken
	ICONSDIRECTORY=$(bpgallery_cleanup_directory_name "$ICONSDIRECTORY")
fi

if declare -F "bpgallery_${BPGALLERY_THEME}_page" > /dev/null ; then
	BPGALLERY_PAGE_FUNCTION="bpgallery_${BPGALLERY_THEME}_page"
else
	BPGALLERY_PAGE_FUNCTION="bpgallery_default_page"
fi

if declare -F "bpgallery_${BPGALLERY_THEME}_head" > /dev/null ; then
	BPGALLERY_HEAD_FUNCTION="bpgallery_${BPGALLERY_THEME}_head"
else
	BPGALLERY_HEAD_FUNCTION="bpgallery_default_head"
fi

if declare -F "bpgallery_${BPGALLERY_THEME}_description" > /dev/null ; then
	BPGALLERY_DESCRIPTION_FUNCTION="bpgallery_${BPGALLERY_THEME}_description"
else
	BPGALLERY_DESCRIPTION_FUNCTION="bpgallery_default_description"
fi

if declare -F "bpgallery_${BPGALLERY_THEME}_thumbsline" > /dev/null ; then
	BPGALLERY_THUMBSLINE_FUNCTION="bpgallery_${BPGALLERY_THEME}_thumbsline"
else
	BPGALLERY_THUMBSLINE_FUNCTION="bpgallery_default_thumbsline"
fi

if declare -F "bpgallery_${BPGALLERY_THEME}_tail" > /dev/null ; then
	BPGALLERY_TAIL_FUNCTION="bpgallery_${BPGALLERY_THEME}_tail"
else
	BPGALLERY_TAIL_FUNCTION="bpgallery_default_tail"
fi

if declare -F "bpgallery_${BPGALLERY_THEME}_stylesheet" > /dev/null ; then
	BPGALLERY_STYLESHEET_FUNCTION="bpgallery_${BPGALLERY_THEME}_stylesheet"
else
	BPGALLERY_STYLESHEET_FUNCTION="bpgallery_default_stylesheet"
fi

FINDIMAGESOPTIONS=""

for imageext in $IMAGEEXTENSIONS; do
	FINDIMAGESOPTIONS=$FINDIMAGESOPTIONS' -o -type f -iname '*.$imageext' -print0'
done

FINDIMAGESOPTIONS=${FINDIMAGESOPTIONS## -o }
FINDIMAGESOPTIONS='-maxdepth 1 '${FINDIMAGESOPTIONS}

function usage() {
cat <<END
Usage:
  $0 [--help|--version|<path to images>]

    --help
        displays this help screen
    --version
        displays the version and exits

This can also takes some environment variables, these will use defaults if not
set.

        TITLE
            the title of the gallery

        WIDTH
            the width to make the icons

        HEIGHT
            the height to make the icons (sets up a bounding box with WIDTH)

        MEDIUMWIDTH
            set the width of images in the medium size pages

        MEDIUMHEIGHT
            the height to make images in the medium size pages (sets up a
            bounding box with MEDIUMWIDTH)

        BPGALLERY_THEME
            set the theme to use (described below)

        BPGALLERY_THEME_DIR
            set an extra location to look for themes

        OUTPUTHTML
            sets the script output to be wrapped in a <pre> block

        GENERATEPAGESFORMEDIUMSIZE
            generate medium sized images and pages

        GENERATEPAGESFORFULLSIZE
            decide wether to generate pages for the full size images or not

        INDEXDOCUMENT
            name of the index page (e.g. index.html)

Example:
	TITLE="My Funky Gallery" WIDTH=200 INDEXDOCUMENT="welcome.html" GENERATEPAGESFORFULLSIZE=1 GENERATEPAGESFORMEDIUMSIZE=1 MEDIUMWIDTH=400 $0 /path/to/image/folder
END
}

function version() {
cat <<END
Version: $VERSION
END
}

function check_dimensions() {
	wantedwidth=$1
	wantedheight=$2
	dir=$3
	filename=$4
	if [ ! -e "$dir/$filename" ]; then
		echo 0
		return
	fi
	iconwidth=$($IDENTIFYCOMMAND -format "%wx%h" "$dir/$filename")
	iconheight=${iconwidth//*x}
	iconwidth=${iconwidth//x*}
	# are the dimensions correctish?
	imagesizeright=1
	if [ ! -z $wantedheight ]; then
		if [ $wantedwidth -ne $iconwidth ] && [ $wantedheight -ne $iconheight ]; then
			imagesizeright=0
		else
			# make sure that both of the dimensions are smaller than they
			# should be
			if [ $iconwidth -gt $wantedwidth ] || [ $iconheight -gt $wantedheight ]; then
				imagesizeright=0
			fi
		fi
	else
		if [ $wantedwidth -ne $iconwidth ]; then
			imagesizeright=0
		fi
	fi
	echo $imagesizeright
}

function generate_resized_images() {
	$ECHOCOMMAND "Generating $2"
	width=$1
	height=${width//*x}
	if [ $width != $height ]; then
		width=${width//x*}
	else
		height=""
	fi
	currentimage=0
	totalimages=$($FINDCOMMAND . $FINDIMAGESOPTIONS | $XARGSCOMMAND -0 -I {} $ECHOCOMMAND {} | $WCCOMMAND);
	imagestoupdate=$($FINDCOMMAND . $FINDIMAGESOPTIONS |
		$XARGSCOMMAND -0 -I {} $ECHOCOMMAND {} |
		while read filename; do
			filename=${filename//\"/\\\"}
			imagesizeright=$(check_dimensions "$width" "$height" "$2" "$filename")
			if [ ! -r "$2/$filename" ] ||
				[ "$filename" -nt "$2/$filename" ] ||
				[ $imagesizeright -ne 1 ]; then
				$ECHOCOMMAND $filename
			fi
		done |
		$WCCOMMAND)
	
	if [ $totalimages -eq 0 ]; then
		# might as well exit at this point - there are no pictures
		$ECHOCOMMAND "No images for the gallery - exiting."
		exit 64
	else
		# check if the directory exists and create it other wise
		if [ ! -d $2 ]; then
			mkdir $2
		fi

		if [ ! -w $2 ]; then
			$ECHOCOMMAND "Can't write to $2 directory, exiting"
			exit 16
		fi
	fi

	if [ $totalimages -eq $imagestoupdate ]; then
		$ECHOCOMMAND "Regenerating all $2"
	elif [ $imagestoupdate -eq 0 ]; then
		$ECHOCOMMAND "No Updated $2, not regenerating"
		return
	else
		$ECHOCOMMAND "Generating $imagestoupdate of $totalimages $2"
	fi
	
	$FINDCOMMAND . $FINDIMAGESOPTIONS | \
		$XARGSCOMMAND -0 -I {} $ECHOCOMMAND {} | \
		while read filename; do 
			tempfilename=${filename//\"/\\\"/}; 
			imagesizeright=$(check_dimensions "$width" "$height" "$2" "$filename")
			if [ ! -r "$2/$tempfilename" ] \
				|| [ "$tempfilename" -nt "$2/$tempfilename" ] \
				|| [ $imagesizeright -ne 1 ]; then 
					$ECHOCOMMAND -n $filename
					$ECHOCOMMAND -n -e "\000"
			fi
		done | \
		$XARGSCOMMAND -0 --verbose --max-procs=$MAXTHREADS -I {} $CONVERTTOOL -resize $1 '{}' $2/'{}' 2>&1 | \
			while read throwout; do
				$ECHOCOMMAND done: $currentimage/$imagestoupdate images
				currentimage=$((currentimage+1))
			done
	$ECHOCOMMAND done: $imagestoupdate/$imagestoupdate images
	$ECHOCOMMAND "Completed generating $2 for $totalimages images"
}

function generate_thumbs() {
	if [ ! -z $HEIGHT ]; then
		generate_resized_images "${WIDTH}x${HEIGHT}" $ICONSDIRECTORY
	else
    	generate_resized_images $WIDTH $ICONSDIRECTORY
	fi
}

function generate_medium() {
	if [ ! -z $MEDIUMHEIGHT ]; then
		generate_resized_images "${MEDIUMWIDTH}x${MEDIUMHEIGHT}" $MEDIUMDIRECTORY
	else
		generate_resized_images $MEDIUMWIDTH $MEDIUMDIRECTORY
	fi
}

function generate_pages() {
	$ECHOCOMMAND "Generating Pages"
	previouspage=""
	currentpage=""
	nextpage=""
	previousimage=""
	currentimage=""
	nextimage=""
	extra=""
	extradir=""
	addlinks=0
	
	if [ ! -z $1 ]; then
		extra=$1
	fi

	if [ ! -z $2 ]; then
		extradir=$2/
		addlinks=1
	fi

	if [ -z $2 ] && [[ $GENERATEPAGESFORMEDIUMSIZE != 0 ]]; then
		addlinks=2
	fi
	
	$FINDCOMMAND . $FINDIMAGESOPTIONS | \
	$XARGSCOMMAND -0 -I {} $ECHOCOMMAND {} | \
	$SORTCOMMAND -g | \
	while read imagefilename; do
		previousimage=$currentimage
		currentimage=$nextimage
		nextimage=${imagefilename#./}
		addlink=""
		
		if [[ $GENERATEPAGESFORFULLSIZE != 0 ]]; then
			if [[ $addlinks == 1 ]]; then
				addlink=${currentimage}.html
			else
				addlink=${currentimage}${extra}.html
			fi
		else
			addlink=${currentimage}
		fi

		previouspage=$currentpage
		currentpage=$nextpage
		if [[ $addlinks == 1 ]]; then
			nextpage=${nextimage}${extra}.html
		else
			nextpage=${nextimage}.html
		fi

		if [[ "x$PAGESDIRECTORY" != "x" ]]; then
			filename=../${extradir}${currentimage}
		else
			filename=${extradir}${currentimage}
		fi
		if [ "x$currentpage" != "x" ]; then
			generate_general_page "$previouspage" "$currentpage" "$nextpage" $addlink
		fi
		$ECHOCOMMAND $nextimage
	done | tail -n 2 | (
		read previouspage
		read currentpage
		addlink=""

		if [[ $GENERATEPAGESFORFULLSIZE != 0 ]]; then
			if [[ $addlinks == 1 ]]; then
				addlink=${currentpage}.html
			else
				addlink=${currentpage}${extra}.html
			fi
		else
			addlink=${currentpage}
		fi
		
		if [[ "x$PAGESDIRECTORY" != "x" ]]; then
			filename=../${extradir}${currentpage}
		else
			filename=${extradir}${currentpage}
		fi
		if [[ $addlinks == 1 ]]; then
			currentpage=${currentpage}${extra}.html
			previouspage=${previouspage}${extra}.html
		else
			currentpage=${currentpage}.html
			previouspage=${previouspage}.html
		fi
		nextpage=""
		generate_general_page "$previouspage" "$currentpage" "" $addlink
	)
}

function generate_medium_pages() {
	generate_pages __${MEDIUMDIRECTORY} ${MEDIUMDIRECTORY}
}

function generate_general_page() {

	if [[ -z $1 ]]; then
		previouspage=""
	fi

	if [[ -z $2 ]]; then
		currentpage=""
		return
	fi

	if [[ -z $3 ]]; then
		nextpage=""
	fi

	if [[ ! -z $4 ]]; then
		linklocation=$4
	fi

	if [ -r captions.txt ]; then
		imagefilename=${filename##*/}
		caption=$($GREPCOMMAND -E "^${imagefilename}	" captions.txt); caption=${caption#*	}
	else
		caption=""
	fi
	
	$BPGALLERY_PAGE_FUNCTION > "${UNIXPAGESDIRECTORY}$currentpage"
}

if [[ $OUTPUTHTML != 0 ]]; then
	$ECHOCOMMAND "<pre>"
fi

if [[ -z $1 ]]; then
	$ECHOCOMMAND "No path given"
	usage
	exit 1
fi

if [[ "$1" == "--help" || "$1" == "-h" ]]; then
	usage
	exit 0
fi

if [[ "$1" == "--version" || "$1" == "-v" ]]; then
	version
	exit 0
fi

if [[ ! -d $1 ]]; then
	$ECHOCOMMAND "$1 is not a directory"
	usage
	exit 2
fi

cd "$1"

if ( ! $FINDCOMMAND . $FINDIMAGESOPTIONS > /dev/null 2>/dev/null ); then
	$ECHOCOMMAND "$1 does not contain any images. Quitting."
	exit 4
fi

if [ ! -w . ]; then
	$ECHOCOMMAND "Can't write to images directory, exiting"
	exit 8
fi

if [ -e ${INDEXDOCUMENT} ] && [ ! -w ${INDEXDOCUMENT} ]; then
	$ECHOCOMMAND "Can't write ${INDEXDOCUMENT}, exiting"
	exit 8
fi

if [ -e style.css ] && [ ! -w style.css ]; then
	$ECHOCOMMAND "Can't write style.css, exiting"
	exit 8
fi

generate_thumbs

if [[ "x$PAGESDIRECTORY" != "x" ]]; then
	if [ ! -d $PAGESDIRECTORY ]; then
		mkdir -p $PAGESDIRECTORY
	fi

	if [ ! -w $PAGESDIRECTORY ]; then
		$ECHOCOMMAND "Can't write to $PAGESDIRECTORY directory, exiting"
		exit 16
	fi
	UNIXPAGESDIRECTORY=$PAGESDIRECTORY/	
	PAGESDIRECTORY=$(bpgallery_escape_url $PAGESDIRECTORY)/

	BASEURL="../"
else
	BASEURL=""
	UNIXPAGESDIRECTORY=""
fi

if [ $GENERATEPAGESFORMEDIUMSIZE != 0 ]; then
	generate_medium
	generate_medium_pages
fi

if [ $GENERATEPAGESFORFULLSIZE != 0 ]; then
	if [ $GENERATEPAGESFORMEDIUMSIZE != 0 ]; then
		generate_pages __${MEDIUMDIRECTORY}
	else
		generate_pages
	fi
fi

if [ -r description.txt ] ; then
	DESCRIPTION=$($SEDCOMMAND -e '1 { s/^/<p>/; }; /^$/ { s,$,</p><p>,; }; $ { s,$,</p>, };' description.txt)
else
	DESCRIPTION=""
fi

BASEURL=""

$ECHOCOMMAND "Starting to generate page"

$BPGALLERY_HEAD_FUNCTION > ${INDEXDOCUMENT}
$BPGALLERY_DESCRIPTION_FUNCTION >> ${INDEXDOCUMENT}

$ECHOCOMMAND "Adding Captions"

extra=""
if [ $GENERATEPAGESFORMEDIUMSIZE != 0 ]; then
	extra=__${MEDIUMDIRECTORY}
fi

$FINDCOMMAND . $FINDIMAGESOPTIONS | $XARGSCOMMAND -0 -I {} $ECHOCOMMAND {} | $SORTCOMMAND -g | while read filename; do filename=${filename#./}; if [ -r captions.txt ]; then caption=$($GREPCOMMAND -E "^$filename	" captions.txt); caption=${caption#*	}; else caption=""; fi; if [ $GENERATEPAGESFORMEDIUMSIZE != 0 ]; then link=${PAGESDIRECTORY}$(bpgallery_escape_url "${filename}${extra}.html"); elif [ $GENERATEPAGESFORFULLSIZE != 0 ]; then link=${PAGESDIRECTORY}$(bpgallery_escape_url "${filename}.html"); else link=$(bpgallery_escape_url "$filename"); fi; filename=$(bpgallery_escape_url "$filename"); $BPGALLERY_THUMBSLINE_FUNCTION; done >> ${INDEXDOCUMENT}

$BPGALLERY_TAIL_FUNCTION >> ${INDEXDOCUMENT}

$ECHOCOMMAND "Finished generating the page"
$ECHOCOMMAND "Generating stylesheet"
cd $ICONSDIRECTORY

MAXHEIGHT=$($FINDCOMMAND . $FINDIMAGESOPTIONS | $XARGSCOMMAND -0 $IDENTIFYCOMMAND -format "%h\n" | $GREPCOMMAND -v "^$" | $SORTCOMMAND -g -r | $HEADCOMMAND -n 1)
MAXWIDTH=$($FINDCOMMAND . $FINDIMAGESOPTIONS | $XARGSCOMMAND -0 $IDENTIFYCOMMAND -format "%w\n" | $GREPCOMMAND -v "^$" | $SORTCOMMAND -g -r | $HEADCOMMAND -n 1)

cd ..

# add a bit to the maxheight for the size of the caption
MAXHEIGHT=$((MAXHEIGHT+$CAPTIONHEIGHT))

$BPGALLERY_STYLESHEET_FUNCTION > style.css

$ECHOCOMMAND "All done"

if [[ $OUTPUTHTML != 0 ]]; then
	$ECHOCOMMAND "</pre>"
fi
