#!/bin/sh
#  $Id$

#  Copyright 2003 Eduardo Sztokbant <du at du.eti.br>
#
#  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 St, Fifth Floor, Boston, MA  02110-1301  USA

shalbum_website="https://github.com/sztokbant/shalbum/releases"
sw_version="1.22"
sw_rev_date='$Date::             $'
software_revision="shalbum $sw_version - $shalbum_website - $sw_rev_date"

# TODO-LIST:
#   - 'shalbumrec -u'
#   - update sample watermark files to $shalbum_website

uname=`uname`

epoch()
{
    if [ $uname != "SunOS" ]; then
	date +%s
    else
	/usr/bin/truss /usr/bin/date 2>&1 | grep '^time' | cut -d '=' -f 2 | cut -d ' ' -f 2
    fi
}

# time
start_time="`epoch`"

#######
# Input
#######

# read options specified in _title, _date and _mhd files (deprecated)
if [ -f _title ]; then
    title="`cat _title`"
else
    title="Album"
fi

if [ -f _date ]; then
    date="`cat _date`"
else
    date=""
fi

if [ -f _mhd ]; then
    mhd="yes"
else
    mhd="no"
fi

# process command-line options
while getopts a:b:c:d:e:hil:mqr:t:uvC:GH:IO:R:S:T:V:W: opt; do
  case $opt in
      # author's name
      a)  cl_author="$OPTARG"
	  ;;

      # link to go back
      b)  cl_back_link="$OPTARG"
	  ;;

      # CSS file
      c)  cl_css="$OPTARG"
	  ;;

      # date/subtitle
      d)  cl_date="$OPTARG"
	  ;;

      # author's e-mail
      e)  cl_email="$OPTARG"
	  ;;

      # index
      i)  cl_only_index="yes"
	  ;;

      # back link label for album list site
      l)  cl_backlink_label="$OPTARG"
	  ;;

      # mhd
      m)  mhd="yes"
	  ;;

      # quiet
      q)  cl_quiet="yes"
	  ;;

      # third title
      r)  cl_third="$OPTARG"
	  ;;

      # title
      t)  cl_title="$OPTARG"
	  ;;

      # update
      u)  cl_update="yes"
	  ;;

      # version
      v)  echo ${software_revision}
	  exit 1
	  ;;

      # number of columns
      C)  cl_n_columns="$OPTARG"
	  ;;

      # choses between ImageMagick and GraphicsMagick
      G)  cl_magick="GM"
	  ;;

      # huge image resolution
      H)  cl_huge_res="$OPTARG"
	  ;;

      # choses between ImageMagick and GraphicsMagick
      I)  cl_magick="IM"
	  ;;

      # order by
      O)  if [ "$OPTARG" = "time" ]; then
	    cl_order_by="time"
	  elif [ "$OPTARG" = "name" ]; then
	    cl_order_by="name"
	  elif [ "$OPTARG" = "file" ]; then
	    cl_order_by="file"
	  else
	    echo "error: unexpected -O input value"
	    echo "valid values: [time|name|file]"
	    exit 1
	  fi
	  ;;

      # number of rows
      R)  cl_n_rows="$OPTARG"
	  ;;

      # slideshow time
      S)  cl_slideshow_time="$OPTARG"
	  ;;

      # thumbnail resolution
      T)  cl_th_res="$OPTARG"
	  ;;

      # vga resolution
      V)  cl_vga_res="$OPTARG"
	  ;;

      # table width
      W)  cl_table_width="$OPTARG"
	  ;;

      # help screen
      *)  echo ${software_revision}
	  echo "Usage: from a directory with image files run"
	  echo "    shalbum [options]"
	  echo ""
	  echo " -h        help screen"
	  echo " -v        show shalbum version and exit"
	  echo ""
	  echo " -t title  specify gallery title"
	  echo " -d date   specify gallery date/subtitle"
	  echo " -r title  specify gallery third title"
	  echo " -a name   specify gallery author's name"
	  echo " -e e-mail specify gallery author's e-mail"
	  echo ""
	  echo " -V num    specify vga resolution"
	  echo " -T num    specify thumbnail resolution"
	  echo " -H num    specify huge image resolution (\"copy\" to keep same)"
	  echo " -W num    specify table width"
	  echo " -R num    specify number of rows"
	  echo " -C num    specify number of columns"
	  echo " -O opt    image sorting option; either \"time\", \"name\" or \"file\""
	  echo " -S secs   seconds per pic in slideshow mode; zero=off"
	  echo ""
	  echo " -G        use GraphicsMagick"
	  echo " -I        use ImageMagick"
	  echo ""
	  echo " -c        specify CSS file path"
	  echo ""
          echo " -u        update existing album"
	  echo ""
	  echo " -b link   link to go back"
	  echo " -l label  back link label for album list site"
	  echo ""
	  echo " -m        selects mhd secondary set of default options"
	  echo " -i        don't resize images, only rebuild the HTML files"
	  echo " -q        quiet mode, suppress output"
	  echo ""
	  echo "More options can be customized by using a .shalbum file."
	  exit 1
	  ;;
  esac
done

# define default-options
if [ $mhd != "yes" ]; then
    # first set of default options
    vga_res=800                     # max width/heigth of final image
    th_res=250                      # max width/height of thumbnail
    huge_res=0                      # max width/height of huge image
    limit_by_height="no"            # if "yes", *_res values will be
                                    # considered 'max height' values
                                    # (this may conflict with watermarks).

    table_width=800                 # width of HTML tables
    n_rows=10                       # number of table rows
    n_columns=3                     # number of table columns
    img_align="optimal"             # if "center", img will be centralized in its
                                    # column on index page; if
                                    # "optimal" img will be aligned
                                    # left on 1st col, right on last
                                    # and center on the rest.
    pic_label_type="conf"           # number, filename, conf, cutatdot, none
    author=""                       # site author's name
    e_mail=''                       # site author's e-mail
    third_title=""                  # string to be added to album's title
    watermark="no"                  # boolean to stamp watermarks
    watermark_th_src="$HOME/.shalbum/watermark_th.png"
                                    # source for thumbnail watermark
    watermark_vga_src="$HOME/.shalbum/watermark_vga.png"
                                    # source for final image watermark
    watermark_dissolve=60           # final image watermark dissolve percent
    thframe="no"                    # enable thumbnail frame
    thframesize=2                   # size of thumbnail frame
    vgaframe="no"                   # enable final image frame
    vgaframesize=3                  # size of final image frame
    hugeframe="no"                  # enable huge image frame
    hugeframesize=3                 # size of huge image frame
    th_quality=75                   # thumbnail percentage quality
    vga_quality=75                  # final image percentage quality
    huge_quality=75                 # huge image percentage quality
    exif_rotate="yes"               # try to rotate image according to exif info
    back_link=""                    # link to go back
    backlink_label=""               # back link label for album list site
    backlink_label_thumbs="&lt;&lt;&lt; thumbnails"
                                    # back link label for thumbnails page
    credits_str=""                  # credit information
    support_shalbum="yes"           # print link to shalbum site
    w3c_ok_banner="yes"             # print "W3C HTML 4.01 compliant" banner
    uname_in_revision="full"        # print OS name in revision comment

    multi_html="yes"                # use one html page per picture?
    th_on_multi="yes"               # show thumbnail for next/last pics?
    long_description="yes"          # attach long description to pic page?
    slideshow_time="5"              # seconds per pic in slideshow mode zero=off
    order_by="time"                 # how to order the images

    magick="AUTO"                   # default: GraphicsMagick, if found

    update="no"                     # do not resize already resized pics
    outdir="album"                  # default output directory

    # CSS
    css_file=""                     # default CSS file

    # HTML layout (deprecated, use CSS instead)
    color_text="#ffffff"
    color_bgcolor="#000000"
    color_link="#ffffff"
    color_vlink="#888888"
    color_alink="#ff0000"
    font_face="Arial, Helvetica, Sans Serif"
else
    # Mostly Harmless Decisions
    # secondary set of default options, selected with "-m" in command-line
    vga_res=500                     # max width/heigth of final image
    th_res=140                      # max width/height of thumbnail
    huge_res=0                      # max width/height of huge image
    limit_by_height="no"            # if "yes", *_res values will be
                                    # considered 'max height' values
                                    # (this may conflict with watermarks).

    table_width=520                 # width of HTML tables
    n_rows=16                       # number of table rows
    n_columns=3                     # number of table columns
    img_align="optimal"             # if "center", img will be centralized in its
                                    # column on index page; if
                                    # "optimal" img will be aligned
                                    # left on 1st col, right on last
                                    # and center on the rest.
    pic_label_type="number"         # number, filename, conf, cutatdot, none
    author="Meia Hora Depois"       # site author's name
    e_mail='banda@meiahoradepois.com'
                                    # site author's e-mail
    third_title="Meia Hora Depois"  # string to be added to album's title
    watermark="yes"                 # boolean to stamp watermarks
    watermark_th_src="$HOME/.shalbum/watermark_th.png"
                                    # source for thumbnail watermark
    watermark_vga_src="$HOME/.shalbum/watermark_vga.png"
                                    # source for final image watermark
    watermark_dissolve=60           # final image watermark dissolve percent
    thframe="yes"                   # enable thumbnail frame
    thframesize=2                   # size of thumbnail frame
    vgaframe="yes"                  # enable final image frame
    vgaframesize=3                  # size of final image frame
    hugeframe="no"                  # enable huge image frame
    hugeframesize=3                 # size of huge image frame
    th_quality=75                   # thumbnail percentage quality
    vga_quality=75                  # final image percentage quality
    huge_quality=75                 # huge image percentage quality
    exif_rotate="yes"               # try to rotate image according to exif info
    back_link="http://www.meiahoradepois.com/fotos.htm"
                                    # link to go back
    backlink_label="&lt;&lt;&lt; &iacute;ndice"
                                    # back link label for album list site
    backlink_label_thumbs="&lt;&lt;&lt; miniaturas"
                                    # back link label for thumbnails page
    credits_str="photos by "        # credit information
    support_shalbum="yes"           # print link to shalbum site
    w3c_ok_banner="yes"             # print "W3C HTML 4.01 compliant" banner
    uname_in_revision="full"        # print OS name in revision comment

    multi_html="yes"                # use one html page per picture?
    th_on_multi="yes"               # show thumbnail for next/last pics?
    long_description="yes"          # attach long description to pic page?
    slideshow_time="5"              # seconds per pic in slideshow mode zero=off
    order_by="name"                 # how to order the images

    magick="AUTO"                   # default: GraphicsMagick, if found

    update="no"                     # do not resize already resized pics
    outdir="album"                  # default output directory

    # CSS
    css_file=""                     # default CSS file

    # HTML layout (deprecated, use CSS instead)
    color_text="#ffffff"
    color_bgcolor="#000000"
    color_link="#ffffff"
    color_vlink="#888888"
    color_alink="#ff0000"
    font_face="Arial, Helvetica, Sans Serif"
fi

quiet="no"                          # suppress output
only_index="no"                     # only create HTML files
tmp_dir="_shalbum.tmp"              # directory for shalbum temporary files
default_input_file=".shalbum-input" # default input file if order_by="file"

css_content=""

# System-wide default options
if [ -f /etc/shalbum/shalbum.conf ]; then
    . /etc/shalbum/shalbum.conf
fi

# User default options
if [ -f $HOME/.shalbum/shalbum.conf ]; then
    . $HOME/.shalbum/shalbum.conf
fi

# read user-defined options

# deprecated
if [ -f ./_options ]; then
    echo "WARNING: '_options' is deprecated. Use '.shalbum' instead."
    . ./_options
fi

if [ -f ./.shalbum ]; then
    . ./.shalbum
fi

# options chosen from command-line if specified
if [ "$cl_title" != "" ]; then
    title="$cl_title"
fi

if [ "$cl_date" != "" ]; then
    date="$cl_date"
fi

if [ "$cl_third" != "" ]; then
    third_title="$cl_third"
fi

if [ "$cl_author" != "" ]; then
    author="$cl_author"
fi

if [ "$cl_email" != "" ]; then
    e_mail="$cl_email"
fi

if [ "$cl_vga_res" != "" ]; then
    vga_res="$cl_vga_res"
fi

if [ "$cl_th_res" != "" ]; then
    th_res="$cl_th_res"
fi

if [ "$cl_huge_res" != "" ]; then
    huge_res="$cl_huge_res"
fi

if [ "$cl_back_link" != "" ]; then
    back_link="$cl_back_link"
fi

if [ "$cl_backlink_label" != "" ]; then
    backlink_label="$cl_backlink_label"
fi

if [ "$cl_table_width" != "" ]; then
    table_width="$cl_table_width"
fi

if [ "$cl_n_rows" != "" ]; then
    n_rows="$cl_n_rows"
fi

if [ "$cl_n_columns" != "" ]; then
    n_columns="$cl_n_columns"
fi

if [ "$cl_order_by" != "" ]; then
    order_by="$cl_order_by"
fi

if [ "$cl_slideshow_time" != "" ]; then
    slideshow_time="$cl_slideshow_time"
fi

if [ "$cl_quiet" != "" ]; then
    quiet="$cl_quiet"
fi

if [ "$cl_only_index" != "" ]; then
    only_index="$cl_only_index"
fi

if [ "$cl_magick" != "" ]; then
    magick="$cl_magick"
fi

if [ "$cl_update" != "" ]; then
    update="$cl_update"
fi

if [ "$cl_css" != "" ]; then
    css_file="$cl_css"
fi

###############
# Aux functions
###############

println_info()
{
    if [ "$quiet" != "yes" ]; then
	echo "$*"
    fi
}

print_info()
{
    if [ "$quiet" != "yes" ]; then
	printf "$*"
    fi
}

print_err()
{
    echo "$*"
}

create_pages_index()
{
    echo '<!-- pages index begin -->'
    echo '<table width="'$table_width'">'
    echo ' <tr>'
    echo '  <td class="pagesIndex">'
    if [ $n_rows -gt 0 ]; then
	aux=1
	echo '   __LAST_PAGE__'
	while [ $aux -le $idx_counter ]; do
	    last=`expr $aux - 1`
	    next=`expr $aux + 1`

	    echo '   <a href="'"$idx_basename""$aux"".html"'">'"$aux"'</a>'

	    if [ $aux -eq $idx_counter ]; then
		echo '   __NEXT_PAGE__'
	    fi

	    aux=`expr $aux + 1`
	done
    fi

    if [ "$back_link" != "" ]; then
	echo "   <p align='center'><a href=\"$back_link\">$backlink_label</a></p>"
    fi

    echo '  </td>'
    echo ' </tr>'
    echo '</table>'
    echo '<!-- pages index end -->'
}

add_credits_footer()
{
    if  [ "$author" != "" ] ||
	[ "$support_shalbum" = "yes" ] ||
	[ "$w3c_ok_banner" = "yes" ]; then
	
	echo "<!-- credits begin -->"
	echo '<table width="'$table_width'">'
	echo ' <tr>'

	echo '  <td class="footerLeft">'
        # support shalbum!
	if [ "$support_shalbum" = "yes" ]; then
	    echo "   <div>page created with <a href='$shalbum_website' target='shalbum'><u>shalbum</u></a></div><br />"
	fi
	
        # W3C XHTML 1.0 compliant banner
	if [ "$w3c_ok_banner" = "yes" ]; then
	    echo '   <div><a href="http://validator.w3.org/check?uri=referer"><img src="http://www.w3.org/Icons/valid-xhtml10-blue" alt="Valid XHTML 1.0 Transitional" height="31" width="88" /></a></div>'
	fi
	echo "  </td>" 
	
        # Author
	if [ "$author" != "" ]; then
	    echo '  <td class="footerRight">'
	    echo "   <div>${credits_str}${author}</div>"
	    if [ "$e_mail" != "" ]; then
		echo "   <div><a href='mailto:$e_mail'>$e_mail</a></div>"
	    fi
	    echo '  </td>'
	fi
	
	echo ' </tr>'
	echo '</table>'
	echo "<!-- credits end -->"
    fi
}

load_css()
{

    if [ "$css_file" != "" ] && [ -f "$css_file" ]; then
	css_content="`cat $css_file`"
    else
	css_content="a:link {
            text-decoration: none;
            color: $color_link;
          }
          a:visited {
            text-decoration: none;
            color: $color_vlink;
          }
          a:active {
            text-decoration: none;
            color: $color_alink;
          }
          body {
            margin: 0px;
            padding: 0px;
            background: $color_bgcolor;
            color: $color_text;
            font-family: $font_face;
            font-size: 14px;
          }
          img {
            border: 0px solid;
          }
          table
          {
              border-color: #888888;
              border-width: 0px 0px;
              border-style: dotted;
          }
          td
          {
            padding: 0px;
            vertical-align: top;
          }
          td.pagesIndex
          {
            text-align: center;
            font-size: 14px;
            font-weight: bold;
          }
          td.footerLeft
          {
            text-align: left;
            width: 50%;
            font-size: 12px;
            font-weight: bold;
          }
          td.footerRight
          {
            text-align: right;
            width: 50%;
            font-size: 12px;
            font-weight: bold;
          }
          label.currentPage
          {
            color: #ff0000;
          }
          label.playButton
          {
            color: #00ff00;
            font-weight: bold;
          }
          label.stopButton
          {
            color: #ff0000;
            font-weight: bold;
          }
          label.title
          {
            font-size: 22px;
            font-weight: bold;
          }
          label.subtitle
          {
            font-size: 16px;
          }"

	css_file=""
    fi
}

print_css()
{
    echo "<style type='text/css'>"${css_content}"</style>"
}

left_arrow()
{
    LEFT_ARROW="  <td align='left' width='10%'>"
    if [ "$before" != "__NULL__" ]; then
	before_th="thumbnails/th_""${before}"
	html_compliant "${before}.html"
	LEFT_ARROW=${LEFT_ARROW}"<a href='${html_compliant_filename}'>&lt;&lt;</a>"
    fi
    LEFT_ARROW=${LEFT_ARROW}"</td>"

    echo $LEFT_ARROW
}

right_arrow()
{
    # right top arrow
    RIGHT_ARROW="  <td align='right' width='10%'>"
    if [ "$after" != "__NULL__" ]; then
	after_th="thumbnails/th_""${after}"
	html_compliant "${after}.html"
	RIGHT_ARROW=${RIGHT_ARROW}"<a href='${html_compliant_filename}'>&gt;&gt;</a>"
    fi
    RIGHT_ARROW=${RIGHT_ARROW}"</td>"

    echo $RIGHT_ARROW
}

create_page_for_pic()
{
    pic="$1"
    before="$2"
    after="$3"
    pic_subtitle="$4"
    index_page="$5"
    refresh="$6"

    if [ "${refresh}" != "" ]; then
	html_file=${tmp_dir}/${pic}"_r.html"
    else
	html_file=${tmp_dir}/${pic}".html"
    fi

    echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' > $html_file

    echo "<html xmlns='http://www.w3.org/1999/xhtml'>" >> $html_file

    # <head>
    echo "<!-- head -->" >> $html_file
    echo "<head>" >> $html_file

    # slideshow
    if [ "${refresh}" != "" ]; then
	if [ "$after" != "__NULL__" ]; then
	    html_compliant "${after}_r.html"
	    echo " <meta http-equiv='refresh' content='${refresh};url=${html_compliant_filename}#picture' />" >> $html_file
	fi
    fi

    echo " <meta http-equiv=\"Content-Type\" content=\"application/xhtml+xml; charset=ISO-8859-1\" />" >> $html_file
    printf " " >> $html_file
    print_css >> $html_file
    if [ "$pic_subtitle" != "" ]; then
	pic_title="$pic_subtitle"
    else
	pic_title="$pic"
    fi
    echo " <title>$pic_title</title>" >> $html_file
    echo "</head>" >> $html_file
    # </head>

    # <body>
    echo "<!-- body -->" >> $html_file
    echo "<body>" >> $html_file
    echo "<div align='center'>" >> $html_file

    # reference to index
    echo "<!-- header -->" >> $html_file
    echo "<table width='$table_width'>" >> $html_file
    echo " <tr>" >> $html_file
    echo "  <td align='left' colspan='3'>" >> $html_file
    printf "   <a href='index" >> $html_file
    if [ "$index_page" != "1" ]; then
	printf "${index_page}" >> $html_file
    fi
    echo ".html'><b>${backlink_label_thumbs}</b></a>" >> $html_file
    echo "  </td>" >> $html_file
    echo " </tr>" >> $html_file

    echo " <tr>" >> $html_file
    left_arrow >> $html_file

    # slideshow
    SLIDESHOW="  <td align='center' width='80%'>"
    if [ "$after" != "__NULL__" ]; then
	if [ "${refresh}" != "" ]; then
	    html_compliant "${pic}.html"
	    SLIDESHOW=${SLIDESHOW}"<a href='${html_compliant_filename}'>STOP <label class='stopButton'>X</label></a>"
	else
	    if [ "${slideshow_time}" != "0" ]; then
		html_compliant "${pic}_r.html"
		SLIDESHOW=${SLIDESHOW}"<a href='${html_compliant_filename}#picture'>PLAY <label class='playButton'>&gt;</label></a>"
	    fi
	fi
    fi
    SLIDESHOW=${SLIDESHOW}"</td>"
    echo $SLIDESHOW >> $html_file

    right_arrow >> $html_file

    echo " </tr>" >> $html_file
    echo "</table>" >> $html_file

    # pic
    echo "<!-- the picture itself -->" >> $html_file
    echo "<a name='picture'></a>" >> $html_file
    echo "<table width='$table_width'>" >> $html_file
    echo " <tr>" >> $html_file
    echo "  <td valign='middle' width='$vga_res' align='center'>" >> $html_file

    # link to huge image
    HUGE_REF=""
    if [ "$huge_res" != "0" ]; then
	html_compliant "huge/huge_${pic}"
	HUGE_REF=${HUGE_REF}"   <a href='huge/huge_${pic}'>"
    fi

    html_compliant "vga/vga_${pic}"
    HUGE_REF=${HUGE_REF}"<img src='${html_compliant_filename}' alt='' />"

    if [ "$huge_res" != "0" ]; then
	HUGE_REF=${HUGE_REF}"</a>"
    fi

    echo $HUGE_REF >> $html_file

    echo "  </td>" >> $html_file
    echo " </tr>" >> $html_file
    echo "</table>" >> $html_file

    # bottom arrows and pic subtitle
    echo "<!-- bottom arrows and subtitle -->" >> $html_file
    echo "<table width='$table_width'>" >> $html_file
    echo " <tr>" >> $html_file

    left_arrow >> $html_file
    echo "  <td align='center' width='80%'><b>$pic_subtitle</b></td>" >> $html_file
    right_arrow >> $html_file

    echo " </tr>" >> $html_file
    echo "</table>" >> $html_file

    # long description if appropriate
    if [ "$long_description" = "yes" ]; then
        long_description_file="$1""-description.html"
	if [ -f $long_description_file ]; then
	    echo "<table width='$table_width'><tr><td align='left'>" >> $html_file
	    cat $long_description_file >> $html_file
	    echo "</td></tr></table>" >> $html_file
	fi
    fi

    # thumbnails with links
    if [ "$th_on_multi" = yes ]; then
	echo "<!-- thumbnails for adjacent pictures -->" >> $html_file
	echo "<table width='$table_width'>" >> $html_file
	echo " <tr>" >> $html_file
        # before
	echo "  <td align='left'>" >> $html_file
	if [ "$before" != "__NULL__" ]; then
	    html_compliant "${before}.html"
	    BEFORE_REF="   <a href='${html_compliant_filename}'>"
	    html_compliant "${before_th}"
	    BEFORE_REF=${BEFORE_REF}"<img src='${html_compliant_filename}' alt='' />"
	    BEFORE_REF=${BEFORE_REF}"</a>"

	    echo $BEFORE_REF >> $html_file
	fi
	echo "  </td>" >> $html_file
	
	echo "  <td align='center' width='100%'></td>" >> $html_file
	
        # after
	echo "  <td align='right'>" >> $html_file
	if [ "$after" != "__NULL__" ]; then
	    html_compliant "${after}.html"
	    AFTER_REF="   <a href='${html_compliant_filename}'>"
	    html_compliant "${after_th}"
	    AFTER_REF=${AFTER_REF}"<img src='${html_compliant_filename}' alt='' />"
	    AFTER_REF=${AFTER_REF}"</a>"

	    echo $AFTER_REF >> $html_file
	fi
	echo "  </td>" >> $html_file
	
	echo " </tr>" >> $html_file
	echo "</table>" >> $html_file
    fi

    echo "<br />" >> $html_file

    add_credits_footer >> $html_file

    echo "</div>" >> $html_file
    echo "</body>" >> $html_file
    echo "</html>" >> $html_file
    echo '<!-- created with '$software_revision' -->' >> $html_file
}

html_compliant()
{
    # input:  a file name
    # output: ${html_compliant_filename}, this filename with some
    #         chars replaced by "%XX" for HTML compliancy

    html_compliant_filename="$1"

    # '%'
    html_compliant_filename=`echo $html_compliant_filename | sed -e s/'%'/'%25'/g`

    # '?'
    html_compliant_filename=`echo $html_compliant_filename | sed -e s/'?'/'%3f'/g`
}

find_image_type()
{
    type="$1"

    if [ "$CAT_COMMAND" != "" ]; then
	INPUT="$CAT_COMMAND"
    else
	INPUT="ls"
    fi

    if [ "`$INPUT | grep -i \"\\.$type\$\" 2>/dev/null`" != "" ]; then
	image_types=$image_types" $type"
    fi
}

set_images_to_grep()
{
    rx_all_image_types=""
    for type in $image_types; do
	if [ "$rx_all_image_types" = "" ]; then
	    rx_all_image_types="("$type"\$"
	else
	    rx_all_image_types=${rx_all_image_types}"|"$type"\$"
	fi
    done

    if [ "$rx_all_image_types" != "" ]; then
	rx_all_image_types=${rx_all_image_types}")"
    fi
}

##########################################
# Part 0: init (look for images, load css)
##########################################

# handle file names with white spaces and order by modify time
if [ "$order_by" = "name" ]; then
    LS_COMMAND="ls"
elif [ "$order_by" = "time" ]; then
    LS_COMMAND="ls -t -r"
elif [ "$order_by" = "file" ]; then
    if [ -f "$default_input_file" ]; then
	CAT_COMMAND="cat $default_input_file"
    else
	println_info "$default_input_file not found, assuming default input."
    fi
fi

if [ "$LS_COMMAND" = "" ] && [ "$CAT_COMMAND" = "" ]; then
    LS_COMMAND="ls -t -r"
fi

find_image_type jpg
find_image_type gif
find_image_type png
find_image_type bmp
find_image_type tiff

set_images_to_grep

if [ "$rx_all_image_types" = "" ]; then
    print_err "No pictures specified"
    exit 2
fi

if [ "$LS_COMMAND" != "" ]; then
    all_files="`$LS_COMMAND | egrep -i $rx_all_image_types`"
    input_from="current dir: `pwd`"
else
    all_files="`$CAT_COMMAND | egrep -i $rx_all_image_types`"
    input_from="$default_input_file file"
fi

IFS='\
'

total_files=`ls $all_files | wc -l | sed -e s/"[^0-9]"//g`

# load CSS file
load_css

println_info "$software_revision"
println_info "Creating album"
println_info "  title:    \"$title\""
println_info "  subtitle: \"$date\""
println_info "  third:    \"$third_title\""
println_info "  author:   \"$author\""
println_info "  e-mail:   \"$e_mail\""
println_info "  input:    $input_from"
print_info   "  config:   "
if [ -f _options ] || [ -f .shalbum ]; then
    println_info "found, using custom options"
else
    println_info "not found, using default options"
fi
print_info   "  css:      "
if [ "$css_file" != "" ]; then
    println_info "found, using custom CSS"
else
    println_info "not found, using default CSS"
fi
println_info "  mhd:      $mhd"
println_info "  images:   $total_files"
println_info "  type(s): $image_types"


#############################
# Part I: process image files
#############################

# delete previous temporary files
if [ -d ${tmp_dir} ]; then
    rm -rf ${tmp_dir}
fi
mkdir ${tmp_dir}

if [ "$only_index" != "yes" ]; then

    # check for GraphicsMagick or ImageMagick's binaries (Default: GM)
    if [ "$magick" = "GM" ] || [ "$magick" = "AUTO" ]; then
        WHICH_GM=`which gm | cut -d ' ' -f 1`
	if [ "$WHICH_GM" != "" ] && [ "$WHICH_GM" != "no" ]; then
	    gm="gm"
	    magick="GM"
	elif [ "$magick" = "GM" ]; then
	    echo "GraphicsMagick not found. Exiting."
	    exit 1
	fi
    fi

    if [ "$magick" = "IM" ] || [ "$magick" = "AUTO" ]; then
	gm=""
	magick="IM"
        WHICH_CONVERT=`which convert | cut -d ' ' -f 1`
	if [ "$WHICH_CONVERT" = "" ] || [ "$WHICH_CONVERT" = "no" ]; then
	    echo "ImageMagick's 'convert' not found. Exiting."
	    exit 1
	fi

        WHICH_MONTAGE=`which montage | cut -d ' ' -f 1`
        if [ "$WHICH_MONTAGE" = "" ] || [ "$WHICH_MONTAGE" = "" ]; then
	    echo "ImageMagick's 'montage' not found. Exiting."
	    exit 1
	fi

        WHICH_IDENTIFY=`which identify | cut -d ' ' -f 1`
        if [ "$WHICH_IDENTIFY" = "" ] || [ "$WHICH_IDENTIFY" = "" ]; then
	    echo "ImageMagick's 'identify' not found. Exiting."
	    exit 1
	fi
    fi

    if [ "$magick" = "IM" ]; then
	println_info "  magick:   ImageMagick"
    elif [ "$magick" = "GM" ]; then
	println_info "  magick:   GraphicsMagick"
    fi

    mkdir ${tmp_dir}/thumbnails
    mkdir ${tmp_dir}/vga

    if [ "$huge_res" != "0" ]; then
	mkdir ${tmp_dir}/huge
    fi
    
    # time elapsed
    img_start_time="`epoch`"

    # generate watermarks
    if [ $watermark = "yes" ]; then
	print_info "Creating watermarks: "
	# temporary resized watermarks
	watermark_th="${tmp_dir}/watermark_${th_res}.png"
	watermark_vga="${tmp_dir}/watermark_${vga_res}.png"

	if [ "$huge_res" != "0" ] && [ "$huge_res" != "copy" ]; then
	    watermark_huge="${tmp_dir}/watermark_${huge_res}.png"
	fi
	
	if [ $limit_by_height = "yes" ]; then
	    th_resize="x${th_res}"
	    vga_resize="x${vga_res}"
	    huge_resize="x${huge_res}"
	else
	    th_resize="${th_res}x${th_res}"
	    vga_resize="${vga_res}x${vga_res}"
	    huge_resize="${huge_res}x${huge_res}"
	fi

	# thumbnail watermark
	print_info "[t${th_res}]"
	$gm convert -sharpen 3 $watermark_th_src -resize ${th_resize} +profile "*" $watermark_th
	
	# vga watermark
	print_info "[v${vga_res}]"
	$gm convert -sharpen 3 $watermark_vga_src -resize ${vga_resize} +profile "*" $watermark_vga

	# huge watermark (same as vga)
	if [ "$huge_res" != "0" ] && [ "$huge_res" != "copy" ]; then
	    print_info "[h${huge_res}]"
	    $gm convert -sharpen 3 $watermark_vga_src -resize ${huge_resize} +profile "*" $watermark_huge
	fi
	    
	println_info " ok!"
    fi # $watermark = yes
    
    println_info "Creating pictures: "
    processed=0
    for file in $all_files; do
	processed100=`expr $processed \* 100`
	percent=`expr $processed100 \/ $total_files`
	processed=`expr $processed + 1`

        if [ "$quiet" != "yes" ]; then
	    printf "%4d/%4d [%2.0f%%] %s: " "$processed" "$total_files" "$percent" "$file"
        fi

        #   1       2      3     4       5           6          7         8
        #
        # 888888 888888     88 88    8888888888 88                 88 8888888888
        # 88         88     88 88    88  88     88  88         88  88     88  88
        # 8888     8888   8888 8888  88         8888888888 8888888888         88
        # 88         88     88 88
        # 88         88 888888 888888

	# Rotate image according to JPEG EXIF orientation information
	# based on http://jpegclub.org/exif_orientation.html
	if [ ${exif_rotate} = "yes" ]; then
	    case `$gm identify -format "%[EXIF:Orientation]" "$file"` in
		2) rotate="180"
		   flip="-flip"
		   ;;
		3) rotate="180"
		   ;;
		4) flip="-flip"
		   ;;
		5) rotate="90"
		   flip="-flip"
		   ;;
		6) rotate="90"
		   ;;
		7) rotate="270"
		   flip="-flip"
		   ;;
		8) rotate="270"
		   ;;
		*) rotate="0"
		   ;;
	    esac
	else
	    rotate="0"
	fi

	# output files
	huge_file="${tmp_dir}/huge/huge_${file}"
	vga_file="${tmp_dir}/vga/vga_${file}"
	th_file="${tmp_dir}/thumbnails/th_${file}"

	# huge
	if [ "$huge_res" != 0 ]; then
	    if [ "$huge_res" = "copy" ]; then
		print_info "[hcp]"
		cp "$file" "$huge_file"
	    else
		print_info "[h${huge_res}]"

		if [ "$limit_by_height" = "yes" ]; then
		    huge_resize="x${huge_res}"
		else
		    huge_resize="${huge_res}x${huge_res}"
		fi

                if [ ${update} != "yes" ] || [ ! -f ${outdir}/huge/`basename ${huge_file}` ]; then
		    if [ $hugeframe = "yes" ]; then
		        $gm convert "$file" -rotate $rotate $flip -resize ${huge_resize} "$huge_file"
		    else
		        $gm convert "$file" -rotate $rotate $flip -resize ${huge_resize} -quality ${huge_quality} "$huge_file"
		    fi
                else
                    print_info "*"
                fi

		# prevent "child" pictures from rotating
		rotate="0"
		flip=""
	    fi
	fi

	# vga	
	print_info "[v${vga_res}]"

	if [ "$huge_res" != 0 ]; then
	    file="${huge_file}"
	fi

	if [ "$limit_by_height" = "yes" ]; then
	    vga_resize="x${vga_res}"
	else
	    vga_resize="${vga_res}x${vga_res}"
	fi

        if [ ${update} != "yes" ] || [ ! -f ${outdir}/vga/`basename ${vga_file}` ] && [ -f ${file} ]; then
	    if [ $vgaframe = "yes" ]; then
	        $gm convert "$file" -rotate $rotate $flip -resize ${vga_resize} "$vga_file"
	    else
	        $gm convert "$file" -rotate $rotate $flip -resize ${vga_resize} -quality ${vga_quality} "$vga_file"
	    fi
        else
            print_info "*"
        fi
	
	# thumbnail
	print_info "[t${th_res}]"

	if [ "$limit_by_height" = "yes" ]; then
	    th_resize="x${th_res}"
	else
	    th_resize="${th_res}x${th_res}"
	fi

        if [ ${update} != "yes" ] || [ ! -f ${outdir}/thumbnails/`basename ${th_file}` ] && [ -f ${vga_file} ]; then
	    if [ $thframe = "yes" ]; then
	        $gm convert "${vga_file}" -resize ${th_resize} "${th_file}"
	    else
	        $gm convert "${vga_file}" -resize ${th_resize} -quality ${th_quality} "${th_file}"
	    fi
        else
            print_info "*"
        fi

	# watermarks
	if [ $watermark = "yes" ]; then
	    print_info "[wm]"
	    if [ "$huge_res" != 0 ] && [ "$huge_res" != "copy" ] && [ -f ${huge_file} ]; then
		composite -dissolve ${watermark_dissolve} -gravity SouthEast $watermark_huge "${huge_file}" "${huge_file}"
	    fi

            if [ -f ${vga_file} ]; then
	        composite -dissolve ${watermark_dissolve} -gravity SouthEast $watermark_vga "${vga_file}" "${vga_file}"
            fi

            if [ -f ${th_file} ]; then
	        composite -dissolve ${watermark_dissolve} -gravity SouthEast $watermark_th "${th_file}" "${th_file}"
            fi
	fi

	# frames
	if [ "$huge_res" != 0 ] && [ $hugeframe = "yes" ] && [ "$huge_res" != "copy" ] && [ -f ${huge_file} ]; then
	    print_info "[hf]"
	    $gm montage "${huge_file}" -mode concatenate -frame $hugeframesize -quality ${huge_quality} "${huge_file}"
	fi

	if [ $vgaframe = "yes" ] && [ -f ${vga_file} ]; then
	    print_info "[vf]"
	    $gm montage "${vga_file}" -mode concatenate -frame $vgaframesize -quality ${vga_quality} "${vga_file}"
	fi
	
	if [ $thframe = "yes" ] && [ -f ${th_file} ]; then
	    print_info "[tf]"
	    $gm montage "${th_file}" -mode concatenate -frame $thframesize -quality ${th_quality} "${th_file}"
	fi

	println_info " ok!"
    done

    # time
    img_end_time="`epoch`"

    if [ $watermark = "yes" ]; then
	rm $watermark_vga $watermark_th $watermark_huge
    fi
fi # !only_index

##########################
# Part II: the index files
##########################

# time
idx_start_time="`epoch`"

print_info "Generating indexes..."

idx_basename='index'
idx_counter=1
idx_filename="${tmp_dir}/$idx_basename""$idx_counter"".html"

############################## CONTENTS ##############################
echo '<table width="'$table_width'">' >> $idx_filename

col_counter=1
lin_counter=1

if [ $multi_html = "yes" ]; then
    cur_counter=1
    b4_file="__NULL__"
fi

col_percentage=`expr 100 \/ $n_columns`

if [ "$uname_in_revision" = "full" ]; then
    software_revision="${software_revision} (`uname -srm`)"
elif [ "$uname_in_revision" = "short" ]; then
    software_revision="${software_revision} (${uname})"
fi

for file in $all_files; do

    # rows & columns
    if [ $col_counter -eq 1 ]; then
	echo "<!-- row begins -->" >> $idx_filename
	echo " <tr>" >> $idx_filename
    fi
    echo "  <td align='left' width='${col_percentage}%'>" >> $idx_filename

    th_file="thumbnails/th_""$file"
    vga_file="vga/vga_""$file"

    if [ "$img_align" = "center" ]; then
	center_str="align='center'"
    else
	if [ "$img_align" = "optimal" ]; then
	    if [ $col_counter -eq 1 ]; then
		center_str="align='left'"
	    elif [ $col_counter -eq $n_columns ]; then
		center_str="align='right'"
	    else
		center_str="align='center'"
	    fi
	fi
    fi

    if [ "$pic_label_type" != "none" ]; then
        if [ "$pic_label_type" = "number" ]; then
            # try to guess pic number
            # following IMG_####.JPG or DSC#####.JPG (Sony) pattern
	    if [ "`echo $file | grep _`" = "$file" ]; then
		num_sep="_"
	    elif [ "`echo $file | grep c`" = "$file" ]; then
		num_sep="c"
	    else
		num_sep="C"
	    fi
	    number=`echo $file | cut -d "." -f 1 | cut -d "$num_sep" -f 2`
	    pic_subtitle=$number
	elif [ "$pic_label_type" = "filename" ]; then
	    pic_subtitle=$file
	elif [ "$pic_label_type" = "conf" ]; then
	    if [ -f _subtitles ]; then
		pic_subtitle="`grep \"${file}=\" _subtitles | cut -d '=' -f 2-`"
	    fi
	elif [ "$pic_label_type" = "cutatdot" ]; then
	    pic_subtitle="`echo $file | cut -d '.' -f 1`"
	fi
    fi

    alt=""
    if [ "${pic_subtitle}" != "" ]; then
	alt="${pic_subtitle}"
    else
	alt="${file}"
    fi

    echo "   <table width='100%'>" >> $idx_filename
    echo "    <tr>" >> $idx_filename

    PIC_LINK=""
    if [ $multi_html = "yes" ]; then
	html_compliant "${file}.html"
	PIC_LINK=${PIC_LINK}"     <td width='100%' $center_str><a href='${html_compliant_filename}'>"
	html_compliant "${th_file}"
	PIC_LINK=${PIC_LINK}'<img src="'${html_compliant_filename}'" alt="'${alt}'" /></a>'
    else
	html_compliant "${vga_file}"
	PIC_LINK=${PIC_LINK}"     <td width='100%' $center_str><a href='${html_compliant_filename}' target='${file}'><img "
	html_compliant "${th_file}"
	PIC_LINK=${PIC_LINK}'src="'${html_compliant_filename}'" alt="'${alt}'" /></a>'
    fi
    echo $PIC_LINK >> $idx_filename

    if [ "$pic_label_type" != "none" ]; then
	echo "     </td>" >> $idx_filename
	echo "    </tr>" >> $idx_filename
	echo "    <tr>" >> $idx_filename
	echo "     <td align='left' width='100%'><b>$pic_subtitle</b>" >> $idx_filename
    fi

    echo '     </td>' >> $idx_filename
    echo '    </tr>' >> $idx_filename
    echo '   </table>' >> $idx_filename
    echo '  </td>' >> $idx_filename

    # multi-pages
    if [ $multi_html = "yes" ]; then
        # finds next file!
	if [ "$total_files" -gt "$cur_counter" ]; then
	    next_counter=0
	    for f_find in $all_files; do
		next_file=$f_find
		if [ "$next_counter" = "$cur_counter" ]; then
		    break
		fi
		next_counter=`expr $next_counter + 1`
	    done
	else
	    next_file="__NULL__"
	fi

	# finds out index page
	index_page=`expr \( $cur_counter - 1 \) \/ \( $n_rows \* $n_columns \) + 1`

	create_page_for_pic "$file" "$b4_file" "$next_file" "$pic_subtitle" "$index_page"

	if [ "$slideshow_time" != "0" ]; then
	    create_page_for_pic "$file" "$b4_file" "$next_file" "$pic_subtitle" "$index_page" "$slideshow_time"
	fi
    fi

    col_counter=`expr $col_counter + 1`

    if [ $col_counter -gt $n_columns ]; then
	echo '</tr>' >> $idx_filename
	col_counter=1
	lin_counter=`expr $lin_counter + 1`
    fi

    if [ $n_rows -gt 0 ]; then
	if [ $lin_counter -gt $n_rows ]; then
	    # this 'if' avoids creation of an empty index.html in the end
	    if [ ! `expr $n_rows \* $n_columns \* $idx_counter` -eq $total_files ]; then
		idx_counter=`expr $idx_counter + 1`
		idx_filename="${tmp_dir}/$idx_basename""$idx_counter"".html"
		
		echo '<table width="'$table_width'">' >> $idx_filename
		lin_counter=1
	    fi
	fi
    fi

    if [ $multi_html = "yes" ]; then
	b4_file="$file"
	cur_counter=`expr $cur_counter + 1`
    fi
done

# Fill empty columns
while [ $col_counter -gt 1 ]; do
    echo "  <td align='left' width='${col_percentage}%'></td>" >> $idx_filename

    col_counter=`expr $col_counter + 1`

    if [ $col_counter -gt $n_columns ]; then
	echo ' </tr>' >> $idx_filename
	col_counter=1
    fi
done
############################## /CONTENTS ##############################

############################## HEADER ##############################
idx_header="header.html"

echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' > $idx_header
echo "<html xmlns='http://www.w3.org/1999/xhtml'>" >> $idx_header

# shalbumrec stuff
echo "<!-- shalbumrec:title ^${title}^ -->" >> $idx_header
if [ "$date" != "" ]; then
    echo "<!-- shalbumrec:date ^${date}^ -->" >> $idx_header
fi

# <head>
echo "<!-- head -->" >> $idx_header
echo "<head>" >> $idx_header

# meta
echo " <meta http-equiv=\"Content-Type\" content=\"application/xhtml+xml; charset=ISO-8859-1\" />" >> $idx_header

# style
printf " " >> $idx_header
print_css >> $idx_header

# echo title
TITLE=" <title>"
if [ "$third_title" != "" ]; then
    TITLE=${TITLE}"${third_title} - "
fi
TITLE=${TITLE}"$title"
if [ "$date" != "" ]; then
    TITLE=${TITLE}" - $date"
fi
TITLE=${TITLE}'</title>'
echo $TITLE >> $idx_header

echo "</head>" >> $idx_header
# </head>

# <body>
echo "<!-- body -->" >> $idx_header
echo "<body>" >> $idx_header
echo "<div align='center'>" >> $idx_header

# body title
echo "<!-- body title -->" >> $idx_header
echo '<table width="'$table_width'">' >> $idx_header
echo ' <tr>' >> $idx_header
echo '  <td align="left">' >> $idx_header
if [ "$third_title" != "" ]; then
    echo "   <label class='subtitle'><b>${third_title}</b></label><br />" >> $idx_header
fi
echo "   <label class='title'><b>$title</b></label>" >> $idx_header
if [ "$date" != "" ]; then
    echo "   <br />" >> $idx_header
    echo "   <label class='subtitle'>$date</label>" >> $idx_header
fi
echo '  </td>' >> $idx_header
echo ' </tr>' >> $idx_header
echo '</table>' >> $idx_header

# page index
create_pages_index >> $idx_header
############################## /HEADER ##############################

############################## FOOTER ##############################
idx_footer="footer.html"

echo '</table>' >> $idx_footer
echo '<br />' >> $idx_footer

# page index
create_pages_index >> $idx_footer

# credits footer
add_credits_footer >> $idx_footer

echo '</div>' >> $idx_footer
echo '</body>' >> $idx_footer
echo '</html>' >> $idx_footer
echo '<!-- created with '$software_revision' -->' >> $idx_footer
############################## /FOOTER ##############################

################################### CREATION #################################
aux=1
while [ $aux -le $idx_counter ]; do
    idx_filename="${tmp_dir}/$idx_basename""$aux"".html"

    cat $idx_header $idx_filename $idx_footer > ${tmp_dir}/tmp_idx.html
    mv ${tmp_dir}/tmp_idx.html $idx_filename

    if [ $idx_filename = "${tmp_dir}/${idx_basename}1.html" ]; then
	mv $idx_filename "${tmp_dir}/$idx_basename".html
	idx_filename="${tmp_dir}/$idx_basename".html
    fi

    next=`expr $aux + 1`
    last=`expr $aux - 1`

    neighbors=0
    # last page
    if [ $aux -eq 1 ]; then
	cat $idx_filename | sed s/"__LAST_PAGE__"/""/g > ${tmp_dir}/tmp_idx.html
    else
	neighbors=`expr $neighbors + 1`
	cat $idx_filename | sed s/"__LAST_PAGE__"/'<a href="'"$idx_basename""$last"".html"'">\&lt;\&lt;<\/a> '/g > ${tmp_dir}/tmp_idx.html
    fi
    mv ${tmp_dir}/tmp_idx.html $idx_filename

    # next page
    if [ $aux -eq $idx_counter ]; then
	cat $idx_filename | sed s/"__NEXT_PAGE__"/""/g > ${tmp_dir}/tmp_idx.html
    else
	neighbors=`expr $neighbors + 1`
	cat $idx_filename | sed s/"__NEXT_PAGE__"/'<a href="'"$idx_basename""$next"".html"'">\&gt;\&gt;<\/a>'/g > ${tmp_dir}/tmp_idx.html
    fi
    mv ${tmp_dir}/tmp_idx.html $idx_filename

    # link to current file
    cat $idx_filename | sed s/'<a href="'"${idx_basename}${aux}.html"'">'"$aux"'<\/a>'/'<label class="currentPage">'"$aux"'<\/label>'/g > ${tmp_dir}/tmp_idx.html
    mv ${tmp_dir}/tmp_idx.html $idx_filename

    # ${idx_basename}1.html
    cat $idx_filename | sed s/"${idx_basename}1.html"/"${idx_basename}.html"/g > ${tmp_dir}/tmp_idx.html
    mv ${tmp_dir}/tmp_idx.html $idx_filename

    aux=`expr $aux + 1`
done
rm $idx_header $idx_footer

# if there's only one index file, remove page number.
if [ $neighbors -eq 0 ]; then
    cat $idx_filename | sed s/'<label class="currentPage">1<\/label>'/""/g > ${tmp_dir}/tmp_idx.html
    mv ${tmp_dir}/tmp_idx.html $idx_filename
fi
################################### /CREATION #################################

# time
idx_end_time="`epoch`"

println_info " ok!"

##################
# Part III: export
##################

print_info "Exporting: "

if [ "$only_index" != yes ]; then

    if [ ${update} != "yes" ]; then
      # remove previous backup and backup existing album
      rm -rf ${outdir}.bak

      if [ -d ${outdir} ]; then
        mv ${outdir} ${outdir}.bak
      fi
    fi

    mkdir -p ${outdir}/thumbnails
    mkdir -p ${outdir}/vga
    mkdir -p ${outdir}/huge

    print_info "[tnails]"
    mv ${tmp_dir}/thumbnails/* ${outdir}/thumbnails/ 2>/dev/null
    print_info "[pics]"
    mv ${tmp_dir}/vga/* ${outdir}/vga/ 2>/dev/null
    if [ "$huge_res" != "0" ]; then
	print_info "[huge]"
	mv ${tmp_dir}/huge/* ${outdir}/huge/ 2>/dev/null
    fi

fi # !only_index

print_info "[idx]"
mkdir -p ${outdir}
rm "${outdir}/""$idx_basename"*.html 2>/dev/null
mv "${tmp_dir}/$idx_basename"*.html ${outdir}

if [ $multi_html = "yes" ]; then
    print_info '[multi-idx]'
    for file in $all_files; do
	mv "${tmp_dir}/${file}.html" ${outdir}
	if [ "${slideshow_time}" != "0" ]; then
	    mv "${tmp_dir}/${file}_r.html" ${outdir}
	fi
    done
fi

# cleanup
rm -rf ${tmp_dir}

println_info " ok!"

# time
end_time="`epoch`"

if [ "$only_index" != "yes" ]; then
    img_time=`expr $img_end_time - $img_start_time`
fi
idx_time=`expr $idx_end_time - $idx_start_time`
total_time=`expr $end_time - $start_time`

print_info "Elapsed:  "
print_info "img ${img_time}s, "
print_info "idx ${idx_time}s, "
println_info "total ${total_time}s"

exit 0
