#!/bin/bash
# ---------------------------------------------------------------
# Copyright (C) 2007, 2008 Kristoffer Sederlof
#
# 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., 59 Temple Place - Suite 330, Boston, 
# MA 02111-1307, USA. 
#
#                   (t)humb(n)ail (maker)
#              http://penti.org/~sederlok/tn/
# 
# Requirements:
# ---------------------------------------------------------------
# - bash    [ Any reasonable version should do                ]
# - awk     [ Likewise...                                     ] 
# - convert [ At least verison 5.4.6.                         ]
#
# Well, it also uses "ls", "wc" and "mv", but since they are
# rudimentary "Unix" I'll just assume that you have them ;)
#
# ---------------------------------------------------------------
# File History / Changelog:
#  o http://penti.org/~sederlok/tn/changelog
# ---------------------------------------------------------------
#
# FYI: If you want to make bunch of pictures a bit more brighter,
# Image magic's "convert" program plus the -modulate switch might come
# in handy.
#
# -modulate takes three args: brightness, saturation, and hue.
#
# For example, to increase the color brightness by 30% and decrease the
# color saturation by 10% and leave the hue unchanged,
# use: 
#
#  for i in *.jpg; do echo $i ; convert -modulate 130,90 $i $i; done 
#
#################################################################
# Activate These To Turn Debugging On...
#################################################################
#set -x
#export PS4='$LINENO '
#################################################################
# Booting up some vars...
#################################################################
VERSION="3.0.7"
TOT_STEPS="6"
ONLY_CLEAN=""
SKIP_TN_CREATION=""               
SKIP_HTML_INDEX_CREATION=""
SKIP_HTML_INDEX_ALL_CREATION=""
SKIP_HTML_MULTI_CREATION=""
SKIP_TN_HTML_CREATION=""
SKIP_PICTURE_NAME=""
SKIP_RC_SOURCING=""
SKIP_PICTURE_CREATION_DATA=""
SKIP_MAX_CHARACTERS=""
FORCE=""
GIVEN_ARGS=""
FAKE_PICTURE_WIDTH_SWITCH=""
FORCE_FAKE_PICTURE_WIDTH_SWITCH=""
TO_ROOT="../.."
TN_RC_FILE=".tnrc"
TN_CSS_FILE="$HOME/.tn.css"

# "Hide" these dirs under the dots
PIC_BASE=".tn"
PIC_HTML_DIR="$PIC_BASE/html"
PIC_HTML_SLIDES_DIR="$PIC_BASE/slides"
PIC_TN_DIR="$PIC_BASE/thumbs"
PIC_DIR_BASE=`pwd | awk 'BEGIN { FS = "/" } {print $NF}'`
PIC_IDENT_DATA_FILE="$PIC_BASE/identify_data.txt"

TMP="/tmp/tn_tmp"
CSS_FILE="$PIC_BASE/style.css"

#################################################################
# BEGIN :: PERSONAL RC DATA ::
#################################################################
# If you feel like giving it a more personal touch, edit these...
#################################################################
# (if you copy-paste these into a ~/.tnrc file then you can always
#  safely upgrade without loosing your own color settings, zen do a 
#  " chmod 755 ~/.tnrc " and nirvana is around the corner... ;)
#################################################################
# Who is the author if these pics...
AUTHOR="Kristoffer Sederl&ouml;f"

# Amount of wait time between slides...
REFRESH="5"

# Change to your wanted thumbnail size
TN_RESO="170x170"

# Where to fallback when user clicks on the "Picture Album Name"
FALLBACKDIR="../"

# Here you can change the name of the default index page.
INDEXFILE="A_index.html"
INDEXFILE_TYPE="all"
INDEXFILE_CURRENT_COLOR="#ffff33"
INDEXFILE_NR_PIC_PER_PAGE="12"

# Your wanted _fake_ image size goes here
# This is placed in the PIC:age tag as width=xxx. I.e. people with
# puju resolution can also see your images. The images them selves
# remain the original size.  
#
# This value will also be used if you have any avi files in your
# current working dir...
FAKE_PICTURE_WIDTH="800"
FAKE_PICTURE_HEIGHT="600"

# Am I the owner of these files??? (show $AUTHOR as copywrite owner)
SKIP_COPYRIGHT=""

# as ENV says...
USE_ORIGINAL_PICTURE_WIDTH=""

# Start chopping filenames which are longer than...
MAX_CHAR_AMOUNT="15"

TABLE_BORDER="0"
TABLE_CELLPADDING="5"
TABLE_CELLSPACING="5"
TABLE_CELLPADDING_TITLE="0"
TABLE_CELLSPACING_TITLE="0"

TABLE_ROW_PICTURE_AMOUNT="4"

#################################################################
# END :: PERSONAL RC DATA ::
#################################################################

# ----------------- [ Start of functions ] ----------------------

#################################################################
function _greeting()
{
    echo -e " -= Welcome to (t)humb(n)ail maker version $VERSION =-"
}

#################################################################
function _html_generate_css_file()
{
    if [ -e "$TN_CSS_FILE" ]; then
        echo -e " [0/$TOT_STEPS] => Using User's own CSS instead of tn's version"
        cp $TN_CSS_FILE $CSS_FILE
    else
        cat <<EOF > $CSS_FILE
/* tn css */
body{ 
        background-color: grey; 
        color: white;
}

/* Make "hovering titles" look a bit less uggly, when clicking... ;-) */
A:link.header{color:black; text-decoration:none}
A:visited.header{color:black; text-decoration:none}
A:active.header{color:black;; text-decoration:none}
A:hover.header{color:#black; text-decoration:none}

A:link{
        text-decoration: none;
        text-decoration: underline;
        color: white;
}

A:visited{
        text-decoration: underline;
        font-weight: bold;
        color: #adff2f;
}

A:active{
        text-decoration: none;
        color: gray;
}

A:hover{
        text-decoration: underline;
        color: blue;
}

.shadow,
.content{
        position: relative;
        bottom: 2px;
        right: 2px;
}

.shadow{
        background-color: #666;
        color: inherit;
}

.content{
        background-color: beige;
        color: #000;
        border: 1px solid #000;
        padding: .1cm;
}

.content h1{
        margin: 0;
}

#text,#head{
        font-weight: bold;
        font-size: 2.2em;
        display: block;
        line-height: 1.1em;
        color: #666666;
        background-color: transparent;
        white-space: nowrap;
}

#head:before,
#head:after{
        content: ": $PIC_DIR_BASE :";
        display: block;
}

#text:before,
#head:before{
        margin-bottom: -1.05em;
        margin-left: 0.1ex;
        color: #aaaaaa;
        background-color: transparent;
}

#text:after,
#head:after{
        margin-top: -1.05em;
        margin-left: -0.1ex;
        color: #fff;
        background-color: transparent;
}
EOF
    fi
}

#################################################################
function _html_generate_title()
{
    local TMP
    TMP=$(_count_index_page_nr $1)
    echo "<title>: ${2} : $PIC_DIR_BASE : [$1/$TOT] :</title>"
}

#################################################################
function _html_insert_one_br_if_we_got_one_index()
{
    if [ -z "`_html_generate_indexfile_list`" ]; then
        echo "<br>"
    else
        echo "<br><br>"
    fi
}

#################################################################
function _html_generate_avi_text()
{
    if [ -n "`echo $1|grep -i \.avi`" ]; then 
        cat <<EOF
    <div align="center">
      <a href="../../${1}">This picture is in fact a <b>AVI-file</b> (Moving Picture), <br>
      click on this text to <b>view/save it</b>.</a><br><br>
    </div>
EOF
    fi
}

#################################################################
# _html_generate_arrows(where_to_link, linkname)
function _html_generate_arrows()
{
    local FILE=$1
    local LINK_NAME=$2

    IDENT=$(_return_picture_data $FILE)
    FILENAME=$(_adjust_filename_if_other_than_normal_pic ${FILE})
    cat <<EOF
<a href="`echo ${FILE} | _extension_remove`.html">${LINK_NAME}</a>
EOF

}

#################################################################
#_html_generate_meta_header(index/picture)
function _html_generate_meta_header()
{
    local REGION=$1

    cat <<EOF
<!--                                                                            -->
<!-- ThumbNail maker (tn) Version $VERSION                                        -->
<!--                                                                            -->
<!-- This File Is Automatically Generated. All Modifications Which Are Made     -->
<!-- To This File Will Be Lost Upon Next Run!!                                  -->
<!--                                                                            -->
<!-- For the GPLed source goto: http://penti.org/~sederlok/tn/                  -->
<!--                                                                            -->
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<meta name="author" content="$AUTHOR">
<meta name="generator" content="yes I have a generator.">
<meta http-equiv="keywords" content="tn,thumbnail,awk,bash,convert,
                  unix,picture gallery,pictures,kristoffer sederlöf,sederlok">
EOF
    # Print right path to CSS depending on where this header goes...
    if [ $REGION = "index" ]; then
        cat <<EOF
<link rel="stylesheet" type="text/css" href=".tn/style.css">
EOF
    else
        cat <<EOF
<link rel="stylesheet" type="text/css" href="../style.css">
EOF
    fi
}

#################################################################
function _html_generate_copyright_text()
{
    if [ -z $SKIP_COPYRIGHT ]; then
        echo -e "<font size="-1"> &copy; $AUTHOR </font>"
    fi
}

#################################################################
#_html_generate_first_pic_link(pic_first,pic_previous)
function _html_generate_first_pic_link()
{
    echo "<a href="${1}.html">&lt;&lt;</a>"
}

#################################################################
#_html_generate_last_pic_link(pic_last,pic_next)
function _html_generate_last_pic_link()
{
    echo "<a href="${1}.html">&gt;&gt;</a>"
}

#################################################################
#_html_generate_fake_picture_width(ident)
function _html_generate_fake_picture_width()
{
    # Check if user wants us to fake picture width
    if [ -z $USE_ORIGINAL_PICTURE_WIDTH ]; then

        IDENT_PIC_WIDTH=$(echo $* | awk '{ print $2 }' | sed 's/x.*//g')
        IDENT_PIC_HEIGHT=$(echo $* | awk '{ print $2 }' | sed 's/.*x//g')
        
        # make sure that we didnt get fed crap..
        if [ -n $IDENT_PIC_WIDTH ]; then  
            
            # tests for integer variable.
            case $IDENT_PIC_WIDTH in
                *[!0-9]*|"") IDENT_PIC_WIDTH=0;;
            esac
            
        # default to zero...
        else
            IDENT_PIC_WIDTH=0
        fi

        # FORCE give FAKE image Size...(fake all images sizes)
        if [ $FORCE_FAKE_PICTURE_WIDTH_SWITCH ]; then
            echo "width=\"$FAKE_PICTURE_WIDTH\""

        # Give FAKE image Size...(images size must be bigger than fake)
        elif [ $IDENT_PIC_WIDTH -gt $FAKE_PICTURE_WIDTH -o $IDENT_PIC_HEIGHT -gt $FAKE_PICTURE_HEIGHT ]; then

            if [ $IDENT_PIC_HEIGHT -gt $IDENT_PIC_WIDTH ]; then
                echo "height=\"$FAKE_PICTURE_HEIGHT\""
            else
                echo "width=\"$FAKE_PICTURE_WIDTH\""
            fi

        # Report to user that we are NOT FAKING this images reso...
        else
            cat <<EOF  > $TMP1

 NOTE! NOTE! NOTE! NOTE!

 TN did _not_ fake the image size for the following images since the
 original image size was smaller than faked, which inturn would have
 resulted in a pixeled image... Ie. the following images are shown
 with their original size.

 if you _want_ all images to be shown with the specified width
 regardless of the original images size, just use the -W <RESO> 
 switch instead:

EOF
            echo "  $*" >> $TMP2
        fi
    fi
}

#################################################################
function _html_generate_table_code_for_tn_et_link()
{
    local FILENAME=$1
    local FILENAME_CLEAN=$2
    local MESSAGE=$3

    IDENT=$(_return_picture_data $FILENAME)

    FILENAME=$(_adjust_filename_if_other_than_normal_pic $FILENAME)

    cat <<EOF
 <td>
  <div align="center">
   <a href="${FILENAME_CLEAN}.html">$MESSAGE</a>
   <br><br>
   <div class="shadow">
    <div class="content">
     <a href="${FILENAME_CLEAN}.html"><img src="$TO_ROOT/$PIC_TN_DIR/${FILENAME_CLEAN}.png"
          alt="$IDENT"
        title="$IDENT"></a>
    </div>
   </div>
  </div>
 </td>
EOF

}

#################################################################
function _html_generate_indexfile_list()
{
    local DOTDOT="" TMP="" i=""

    # if called from the pic html:
    # - add dotdot to INDEX link
    # - count current index page from given pic number
    if [ "$1" = "stepback" ]; then
        DOTDOT="$TO_ROOT/"
        TMP=$(_count_index_page_nr $2)
    fi

    # Do not show any links if all pages can fit on one page
    if [ $INDEX_NR_TOT -gt 1 ]; then

        echo -e "\n"

        # Generate the A_index_<NR>.html page links...
        for (( i = 1 ; i <= INDEX_NR_TOT ; i++ )); do

            INDEXFILE="${INDEXFILE_BASENAME}_$i.html"
            
            # We ARE NOW on the GIVEN index file, no link, just text + color.
            if [ "$1" = "$i" -o "$TMP" = "$i" ]; then
                cat <<EOF
<font color="$INDEXFILE_CURRENT_COLOR">$i</font>
EOF
            # We are NOT our index page, create working link...
            else
                cat <<EOF 
<a href="${DOTDOT}${INDEXFILE}">$i</a>
EOF
            fi
            
        done

        # Generate the ALL links...
        if [ "$1" = "all" ]; then
            # We ARE NOW on the GIVEN index file, no link, just text + color.
            cat<<EOF
<font color="$INDEXFILE_CURRENT_COLOR">All</font>
EOF
        else
            # We are NOT our index page, create working link...
            cat<<EOF
<a href="${DOTDOT}${INDEXFILE_BASENAME}_all.html">All</a> 
EOF
        fi

        echo -e "\n"
    fi

}

#################################################################
function _html_generate_index_next_and_previous_link()
{
    local NR="$1" INDEXFILE_PREV="" INDEXFILE_NEXT="" 

    if [ "$NR" = "all" ]; then
        _html_generate_indexfile_list $1
    else
        #  FIRST index-page, only NEXT link please
        if [ "$1" = 1 ]; then
            let "NR += 1"
            INDEXFILE_NEXT="${INDEXFILE_BASENAME}_$NR.html"
            cat <<EOF 
[ <a href="${INDEXFILE_NEXT}">Next</a> ]
EOF

        # LAST index-page, only PREVIOUS link please
        elif [ "$1" = "$INDEX_NR_TOT" ]; then
            let "NR -= 1"
            INDEXFILE_PREV="${INDEXFILE_BASENAME}_$NR.html"

            cat <<EOF 
[ <a href="${INDEXFILE_PREV}">Prev</a> ]
EOF

        # OTHER than two first, PREV + NEXT, please
        else
            let "NR -= 1"
            INDEXFILE_PREV="${INDEXFILE_BASENAME}_$NR.html"
            let "NR += 2"
            INDEXFILE_NEXT="${INDEXFILE_BASENAME}_$NR.html"

            cat <<EOF 
[ 
<a href="${INDEXFILE_PREV}">Prev</a> |
<a href="${INDEXFILE_NEXT}">Next</a> 
]
EOF
        fi
        
    fi
}


#################################################################
function _html_generate_index_title()
{
    cat <<EOF
  <td>
   <a class="header" href="$FALLBACKDIR"><span id="head"><abbr title=": $PIC_DIR_BASE :">: $PIC_DIR_BASE :</abbr></span></a>
  </td>
EOF
}


#################################################################
function _html_generate_index_arrows_plus_title()
{
    local INDEX_NR=$1
    local INDEXFILE_PREV
    local INDEXFILE_NEXT
    local PREV
    local NEXT
    local TMP

    #
    # the ALL page has NO ARROWS!
    #
    if [ "$INDEX_NR" = "all" ]; then
        _html_generate_index_title
    #
    # FIRST PAGE!
    #
    elif [ "$INDEX_NR" = 1 ]; then
        let "NEXT = INDEX_NR + 1"
        cat <<EOF
  <td>
    &lt;&lt;
    &nbsp;&nbsp;&nbsp;&nbsp;
  </td>

  <td>
    &lt;
    &nbsp;&nbsp;&nbsp;&nbsp; 
  </td>

`_html_generate_index_title`

  <td>
    &nbsp;&nbsp;&nbsp;&nbsp; 
   <a href="${INDEXFILE_BASENAME}_${NEXT}.html">&gt;</a>
  </td>

  <td>
    &nbsp;&nbsp;&nbsp;&nbsp; 
   <a href="${INDEXFILE_BASENAME}_${INDEX_NR_TOT}.html">&gt;&gt;</a>
  </td>
EOF
    #
    # LAST index-page!
    #
    elif [ "$INDEX_NR" = "$INDEX_NR_TOT" ]; then
        let "NEXT_LAST_INDEX_PAGE = INDEX_NR_TOT - 1"
        cat <<EOF
  <td>
   <a href="${INDEXFILE_BASENAME}_1.html">&lt;&lt;</a>
    &nbsp;&nbsp;&nbsp;&nbsp;
  </td>

  <td>
   <a href="${INDEXFILE_BASENAME}_${NEXT_LAST_INDEX_PAGE}.html">&lt;</a>
    &nbsp;&nbsp;&nbsp;&nbsp; 
  </td>

`_html_generate_index_title`

  <td>
    &nbsp;&nbsp;&nbsp;&nbsp; 
    &gt;
  </td>

  <td>
    &nbsp;&nbsp;&nbsp;&nbsp; 
    &gt;&gt;
  </td>
EOF
    #
    # SOMEWHERE IN THE MIDDLE...
    #
    else
        let "PREV = INDEX_NR - 1"
        INDEXFILE_PREV="${INDEXFILE_BASENAME}_${PREV}.html"
        let "NEXT = INDEX_NR + 1"
        INDEXFILE_NEXT="${INDEXFILE_BASENAME}_${NEXT}.html"
        cat <<EOF
  <td>
   <a href="${INDEXFILE_BASENAME}_1.html">&lt;&lt;</a>
    &nbsp;&nbsp;&nbsp;&nbsp;
  </td>

  <td>
   <a href="${INDEXFILE_PREV}">&lt;</a>
    &nbsp;&nbsp;&nbsp;&nbsp; 
  </td>

`_html_generate_index_title`

  <td>
    &nbsp;&nbsp;&nbsp;&nbsp; 
   <a href="${INDEXFILE_NEXT}">&gt;</a>
  </td>

  <td>
    &nbsp;&nbsp;&nbsp;&nbsp; 
   <a href="${INDEXFILE_BASENAME}_${INDEX_NR_TOT}.html">&gt;&gt;</a>
  </td>
EOF
    fi

}

#################################################################
#_html_generate_index_head(indexfile_number)
function _html_generate_index_head()
{
    cat <<EOF > $INDEXFILE
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
`_html_generate_meta_header index`
<title> : $PIC_DIR_BASE : </title>
</head>

<div align="center">

<!--                                                      -->
<!-- Just a small workaround for CSS Activate me all over -->
<!--                                                      -->
<table border="$TABLE_BORDER" cellpadding="$TABLE_CELLPADDING_TITLE" cellspacing="$TABLE_CELLSPACING_TITLE">
 <tr>
`_html_generate_index_arrows_plus_title $1`
 </tr>
</table>

<br>

`_html_generate_indexfile_list $1`

<table border="$TABLE_BORDER" cellpadding="$TABLE_CELLPADDING" cellspacing="$TABLE_CELLSPACING">
EOF
}


#################################################################
#_html_generate_index_image(picture_filenames)
function _html_generate_index_image()
{
    local FN="" FILES="" BACKSPACE="" j="1" k="1" TMP="" RESO=""

    _print_status_adj_backspace $#
    TOT_FOR_THIS_ROUND=$#

    # Now we parse the VARIABLE, to set the POS.
    for FN in "$*" ; do
      set -- $FN        # Parses variables and sets positional parameters.
    done

    # While we got stuff dooo..
    while [ $# -ge "1" ]; do
        echo -e '  <tr>'  >> $INDEXFILE

        _count_amount_of_args_to_give $*
        
        j=$(_count_which_element_we_are $1)

        # For the pic + link
        for i in $ARG; do 

            IDENT=$(_return_picture_data $i)
            RESO=$(echo $IDENT | awk '{ print $2 }')
            RESO_X=$(echo $RESO | awk 'BEGIN { FS = "x"} {print $1}')
            RESO_Y=$(echo $RESO | awk 'BEGIN { FS = "x"} {print $2}')

            #
            # START of Pictures white area TD...
            #
            cat <<EOF >> $INDEXFILE
     <td align="center">
EOF
            #
            # [START] Extra Table hack
            #
            if [ $RESO_X -lt $RESO_Y ]; then
                cat <<EOF >> $INDEXFILE
     <!-- [START] Extra Table hack to fix border for Verticaly Orientated pics...  -->
     <table border="$TABLE_BORDER" cellpadding="$TABLE_CELLPADDING_TITLE" cellspacing="$TABLE_CELLSPACING_TITLE">
     <tr>
     <td>&nbsp;</td>
     <td>

EOF
            fi

            cat <<EOF >> $INDEXFILE
      <div class="shadow">
       <div class="content">
EOF
            # If we got some wicked media type, say avi or xpm, make some adjustments...
            if [ -z "`echo $i|grep -i \.avi`" -a -z "`echo $i|grep -i \.xpm`" ]; then
                # PICTURE section
                cat <<EOF >> $INDEXFILE
        <a href="$PIC_HTML_DIR/`echo ${i} | _extension_remove`.html">
         <img src="$PIC_TN_DIR/`echo ${i} | _extension_remove`.png"
              alt="[$j/$TOT] $IDENT" 
            title="[$j/$TOT] $IDENT"
           border="2">
        </a>
EOF
            else
                # AVI section
                cat <<EOF >> $INDEXFILE
        <a href="$PIC_HTML_DIR/`echo ${i} | _extension_remove`.html">
         <img src="$PIC_TN_DIR/`echo ${i} | _extension_remove`.png"
              alt="[$j/$TOT] $IDENT" 
            title="[$j/$TOT] $IDENT"
           border="2">
        </a>
EOF
            fi
                #
                # End of thumbnail index code...
                #
                cat <<EOF >> $INDEXFILE
       </div>
      </div>
EOF
            #
            # [END] Extra Table hack
            #
            if [ $RESO_X -lt $RESO_Y ]; then
                cat <<EOF >> $INDEXFILE

     </td>
     <td>&nbsp;</td>
     </tr>
     </table>
     <!-- [END] Extra Table hack to fix border for Verticaly Orientated pics...  -->
EOF
            fi    
            
            #
            # END of Pictures white area TD...
            #
            cat <<EOF >> $INDEXFILE
     </td>
EOF
            # inc current counter for next round
            let "j+=1"
        done

        echo -e '  </tr>' >> $INDEXFILE
        echo -e '  <tr>' >> $INDEXFILE

        # Check if we have been asked to remove the image names
        # on the main thumbnail-page...
        if [ $SKIP_PICTURE_NAME ]; then
            # For the text
            for i in $ARG; do 
                IDENT=$(_return_picture_data $i)
                RESO=$(echo $IDENT | awk '{ print $2 }')
                SIZE=$(echo $IDENT | awk '{ print $3" "$4 }')

                cat <<EOF >> $INDEXFILE
     <td align="center"> <small> ($RESO $SIZE) </small> </td>
EOF
                # get rid of used ARG.
                shift

                _print_status $k $TOT_FOR_THIS_ROUND
                echo -n -e $BACKSPACE
                let "k+=1"
            done
        # OK, show all information
        else
            # For the text
            for i in $ARG; do 
                IDENT=$(_return_picture_data $i)
                NAME=$(echo $IDENT | awk '{ print $1 }')
                RESO=$(echo $IDENT | awk '{ print $2 }')
                SIZE=$(echo $IDENT | awk '{ print $3" "$4 }')

                # Show long filenames a bit shorter unless told otherwise...
                if [ -z $SKIP_MAX_CHARACTERS ]; then
                    if [ `echo $NAME | wc -c` -gt $MAX_CHAR_AMOUNT ]; then
                        TMP=$(echo $NAME| cut -b -${MAX_CHAR_AMOUNT})
                        NAME="${TMP}..."
                    fi
                fi

                cat <<EOF >> $INDEXFILE
     <td align="center"> <b>$NAME</b> <br> <small> ($RESO $SIZE) </small> </td>
EOF
                _print_status $k $TOT_FOR_THIS_ROUND
                echo -n -e $BACKSPACE
                let "k+=1"
            done
        fi            
        
        # Clear used args...
        for i in $ARG; do 
            shift
        done
        
        echo -e '  </tr>' >> $INDEXFILE
    done
}

#################################################################
function _html_generate_index_other_media()
{
    TOT_VID=$( _list_media | wc -l )

    if [ $TOT_VID -gt 0 ]; then
        echo -e "  <br>" >> $INDEXFILE
        
        # Creating the PICS.HTML files...scratch me please.. :)
        for i in `_list_media`; do
            echo -e "  <a href=\"${i}\"> \c" >> $INDEXFILE
            echo -e "[${i}]</a>" >> $INDEXFILE
        done
    fi
}

#################################################################
function _html_generate_index_tail()
{
    cat <<EOF >> $INDEXFILE
</table>

`_html_generate_index_next_and_previous_link $1`
`_html_insert_one_br_if_we_got_one_index`
`_html_generate_copyright_text`

<br>
<b>Image Amount: `_list_tot_images_amount` | Dir Size: `_get_tot_data_size` Mb</b>
<br>
<br>

<font size="-1" color="black">
<i>tn ($VERSION) created: $(date '+%d.%m.%Y W%V %H:%M:%S')</i>
</font>

<br>
<small><small>[ <a href="http://penti.org/~sederlok/tn/" target="_top">Source</a> ]</small></small>
</div>

</body>
</html>
EOF
}

########################################################################
# _html_generate_picture_pages(pic_place, pic_mode, pic_present)
#
# This func creates the following files:
#
#   (1) Image
#   (2) Slideshow
#
# HTML files for EACH PICTURE that we are asked to create a TN of.
#
# There are three different types of files PER each of those two main
# file types mentioned above, they are:
#
#   (1) The First
#   (2) XYZ amount of middle pages
#   (3) the Last Page.
#
########################################################################
function _html_generate_picture_pages()
{
    local PIC_PLACE=$1    # first, middle, last
    local PIC_MODE=$2     # slideshow_start, slideshow_stop
    local PIC_PRESENT=$3  # <filename>
    local OUTPUT_DIR IDENT

    # Depending on if it's the FIRST, MIDDLE och LAST page that we
    # are generating we will get slighly different args...
    case $PIC_PLACE in
        first) PIC_NEXT=$4;;
        middle)PIC_NEXT=$4; PIC_PREVIOUS=$5;;
        last) PIC_PREVIOUS=$4;;
    esac 

    # Remove the extensions from selected filenames...
    local PIC_PREVIOUS_CLEAN=$(echo $PIC_PREVIOUS | _extension_remove)
    local PIC_PRESENT_CLEAN=$(echo $PIC_PRESENT | _extension_remove)
    local PIC_NEXT_CLEAN=$(echo $PIC_NEXT | _extension_remove)

    case $PIC_MODE in
        slideshow_start) OUTPUT_DIR=$PIC_HTML_DIR;;
        slideshow_stop)  OUTPUT_DIR=$PIC_HTML_SLIDES_DIR;;
    esac

    IDENT=$(_return_picture_data $PIC_PRESENT)      
    IDENT_HTML=$(_return_picture_data_for_main_img_html $PIC_PRESENT)

    #
    # HEAD time...
    #
    cat << EOF
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
`_html_generate_meta_header picture`
EOF
    #
    # SlideShow / Stop SlideShow Refresh-Part
    #
    case $PIC_MODE in

        slideshow_stop)

            case $PIC_PLACE in

                # Last Picture in series should POINT TO FIRST pic's
                # normal Page (that is the normal NON Slideshow Page
                # (thus preventing a eternal loop)....
                last) cat <<EOF
<meta http-equiv="refresh"  content="${REFRESH}; URL=$TO_ROOT/$PIC_HTML_DIR/${PIC_FIRST}.html">
EOF
                ;;

                # The FIRST & MIDDLE pages should always point to NEXT SLIDESHOW page...
                *) cat <<EOF
<meta http-equiv="refresh"  content="${REFRESH}; URL=$TO_ROOT/$OUTPUT_DIR/${PIC_NEXT_CLEAN}.html">
EOF
                ;;
            esac
            ;;
    esac

    #
    # HEADer continues...
    #
    cat << EOF
`_html_generate_title $COUNTER ${PIC_PRESENT}`
</head>
<body>
<div align="center"> 

<!-- ARROW SECTION -->
<!--               -->
<!-- << < Up > >>  -->
<!--               -->
EOF
    #
    #  <<  <  UP  >  >>
    #
    case $PIC_PLACE in

        first) cat <<EOF;;
&lt;&lt; 
&nbsp;&nbsp;&nbsp;&nbsp;
&lt;
&nbsp;&nbsp;&nbsp;&nbsp;
<a href="$TO_ROOT/`_return_pictures_index_filename $COUNTER`">Up</a>
&nbsp;&nbsp;&nbsp;&nbsp;
`_html_generate_arrows ${PIC_NEXT} "&gt;"`
&nbsp;&nbsp;&nbsp;&nbsp;
`_html_generate_last_pic_link $PIC_LAST $PIC_NEXT`
EOF
        middle) cat <<EOF;;
`_html_generate_first_pic_link $PIC_FIRST $PIC_PREVIOUS`
&nbsp;&nbsp;&nbsp;&nbsp;
`_html_generate_arrows $PIC_PREVIOUS "&lt;"`
&nbsp;&nbsp;&nbsp;&nbsp;
<a href="$TO_ROOT/`_return_pictures_index_filename $COUNTER`">Up</a>
&nbsp;&nbsp;&nbsp;&nbsp;
`_html_generate_arrows ${PIC_NEXT} "&gt;"`
&nbsp;&nbsp;&nbsp;&nbsp;
`_html_generate_last_pic_link $PIC_LAST $PIC_NEXT`
EOF
        last) cat <<EOF;;
`_html_generate_first_pic_link $PIC_FIRST $PIC_PREVIOUS`
&nbsp;&nbsp;&nbsp;&nbsp;
`_html_generate_arrows $PIC_PREVIOUS "&lt;"`
&nbsp;&nbsp;&nbsp;&nbsp;
<a href="$TO_ROOT/`_return_pictures_index_filename $COUNTER`">Up</a>
&nbsp;&nbsp;&nbsp;&nbsp;
&gt;
&nbsp;&nbsp;&nbsp;&nbsp;
&gt;&gt;
EOF
    esac

cat << EOF

<!--  ------------ -->
<!--  | MAIN PIC | -->
<!--  ------------ -->
<table border="$TABLE_BORDER" cellpadding="$TABLE_CELLPADDING">
 <tr>
  <td>
`_html_generate_avi_text ${PIC_PRESENT}`
   <div class="shadow"><div class="content">
   <a href="${TO_ROOT}/${PIC_PRESENT}">
   <img src="$TO_ROOT/`_adjust_filename_if_other_than_normal_pic ${PIC_PRESENT} big`" `_html_generate_fake_picture_width $IDENT`
   alt="$IDENT [$COUNTER/$TOT]" 
   title="$IDENT [$COUNTER/$TOT]">
   </a>
   </div></div>
  </td>
 </tr>
</table>

<font size="-1"> $IDENT_HTML [$COUNTER/$TOT] </font>
<br>

EOF
    cat << EOF
<!--                              -->
<!--  SlideShow / Stop SlideShow  -->
<!--                              -->

EOF
    #       
    # SLIDESHOW / STOP SLIDESHOW
    #       
    case $PIC_MODE in
        slideshow_start) echo "<a href=\"$TO_ROOT/$PIC_HTML_SLIDES_DIR/${PIC_PRESENT_CLEAN}.html\">SlideShow</a>";;
        slideshow_stop)  echo "<a href=\"$TO_ROOT/$PIC_HTML_DIR/${PIC_PRESENT_CLEAN}.html\">Stop SlideShow</a>";;
    esac
    
    cat << EOF
<!--  --------------------- -->
<!--  | p-left | p-right  | -->
<!--  --------------------- -->
<!--                        -->
<table border="$TABLE_BORDER" cellpadding="$TABLE_CELLPADDING">
<tr>
EOF
    # +--------+...
    # | p-left |...
    # +--------+...
    case $PIC_PLACE in
        first)  ;;
        middle) _html_generate_table_code_for_tn_et_link ${PIC_PREVIOUS} ${PIC_PREVIOUS_CLEAN} Prev;;
        last)   _html_generate_table_code_for_tn_et_link ${PIC_PREVIOUS} ${PIC_PREVIOUS_CLEAN} Prev;;
    esac
    #       ...+----------+
    #       ...| p-right  |
    #       ...+----------+
    case $PIC_PLACE in
        first)  _html_generate_table_code_for_tn_et_link ${PIC_NEXT} ${PIC_NEXT_CLEAN} Next;;
        middle) _html_generate_table_code_for_tn_et_link ${PIC_NEXT} ${PIC_NEXT_CLEAN} Next;;
        last)   ;;
    esac 

    cat << EOF
</tr>
</table>
EOF
    #
    # TAIL OF HTML... then we are done!
    #
    cat << EOF
`_html_generate_indexfile_list stepback $COUNTER`
<br>
`_html_generate_copyright_text`

</div>
</body>
</html>
EOF

}

#################################################################
# Wrapper function which just takes the output from the main
# Picture HTML generator and stores it to the right file... 
#################################################################
function _html_generate_picture_pages_wrapper()
{
    local PIC_MODE=$2     # slideshow_start, slideshow_stop
    local PIC_PRESENT=$3  # <filename>
    local OUTPUT_DIR=""

    # Remove the extensions from selected filenames...
    local PIC_PREVIOUS_CLEAN=$(echo $PIC_PREVIOUS | _extension_remove)
    local PIC_PRESENT_CLEAN=$(echo $PIC_PRESENT | _extension_remove)
    local PIC_NEXT_CLEAN=$(echo $PIC_NEXT | _extension_remove)

    case $PIC_MODE in
        slideshow_start) OUTPUT_DIR=$PIC_HTML_DIR;;
        slideshow_stop)  OUTPUT_DIR=$PIC_HTML_SLIDES_DIR;;
    esac

    # Call the HTML code generator, 
    # pipe all it's output the present HTML file...
    _html_generate_picture_pages $@ > $OUTPUT_DIR/${PIC_PRESENT_CLEAN}.html
}


#################################################################
function _clean_up_and_exit()
{
    # if some of the files where to small to be faked
    # report the names of those...
    if [ -n "$TMP2" -a -s "$TMP2" ]; then
        cat $TMP1 $TMP2 | uniq
        echo
    fi
    /bin/rm -f $TMP1 $TMP2
}

#################################################################
function _reso_change()
{
    local i j TOT

    # Total picture count...
    TOT=$( _list_tot_images_amount )

    # Just a counter...
    j=1

    echo -e " Ok, using \"$NEW_RESO\" as prefered resolution.\n"
    
    for i in `_list_images`; do
        echo " [$j/$TOT] Down-sizing $i";
        convert -size $NEW_RESO $i -resize $NEW_RESO\> +profile '*' $i; 

        let "j+=1" # inc it baby
    done
}

#################################################################
function _ask_new_reso()
{
    echo -e "Please give your prefered resolution: \c"
    read NEW_RESO
}

#################################################################
function _ask_convert_pic_size()
{
    echo -e "
`_greeting`

 So you want to change the resolution of your pics, The default
 choices are:

  1 = 800x600
  2 = 1280x960
  3 = 1600x1200
  4 = user definer (example 450x450)

  5 = exit

 Your choice: \c"

    read ANSWER    
    echo
    
    case $ANSWER in
        1)  NEW_RESO="800x600"; _reso_change;;
        2)  NEW_RESO="1280x960"; _reso_change;;
        3)  NEW_RESO="1600x1200"; _reso_change;;
        4)  _ask_new_reso; _reso_change;;
        5) echo -e " Bye, bye...\n";exit 1;;
    esac
}

#################################################################
# _user_rc()                            Source users own rc file.
#################################################################
function _user_rc()
{
    if [ -z $SKIP_RC_SOURCING ]; then
        if [ -e "$HOME/${TN_RC_FILE}" ]; then
            if [ -x "$HOME/${TN_RC_FILE}" ]; then
                echo -e " [1/$TOT_STEPS] => Sourcing users \"$HOME/${TN_RC_FILE}\" file..."
                . $HOME/${TN_RC_FILE}
            else
                echo -e " [1/$TOT_STEPS] => Found a \"$HOME/${TN_RC_FILE}\" file but it's NOT executable, ie I will NOT use it."
            fi
        fi
    fi
}

#################################################################
function _pwd_rc()
{
    # Look for rc files, unless told otherwise...
    if [ -z $SKIP_RC_SOURCING ]; then
        # Do we have a ${TN_RC_FILE} file?
        if [ -e "${TN_RC_FILE}" ]; then
            # Yes, but does it have exe perms...
            if [ -x "${TN_RC_FILE}" ]; then
                # Has user forced us to run pwd rc's ?
                if [ $FORCE ]; then
                    echo -e " [1/$TOT_STEPS] => Sourcing present working dirs ${TN_RC_FILE} file (`pwd`/${TN_RC_FILE})"
                    . ${TN_RC_FILE} 
                else
                    echo -e " [1/$TOT_STEPS] => Found a ${TN_RC_FILE} file in present working dir (`pwd`/${TN_RC_FILE})"
                    echo -e " [1/$TOT_STEPS] => Do you want me to source it? [y/n]: \c"
                    
                    read ANSWER
                    case $ANSWER in
                        "y"|"Y")echo -e " [1/$TOT_STEPS] => Ok, souring it..."; . ${TN_RC_FILE} ;;
                        *) echo -e " [1/$TOT_STEPS] => Ok, I'm NOT going to source it...";;
                    esac
                fi
            else
                echo -e " [1/$TOT_STEPS] => Found a ${TN_RC_FILE}-file present working dirs but it's NOT executable, ie I will NOT use it."
            fi
        fi
    fi

    # Override if user has given fake width from prompt
    if [ -n "$FAKE_PICTURE_WIDTH_SWITCH" ]; then
        FAKE_PICTURE_WIDTH=$FAKE_PICTURE_WIDTH_SWITCH
    elif [ -n "$FORCE_FAKE_PICTURE_WIDTH_SWITCH" ]; then
        FAKE_PICTURE_WIDTH=$FORCE_FAKE_PICTURE_WIDTH_SWITCH
    fi
}

#################################################################
# think piped to...
function _extension_remove()
{
    sed 's/\.[^.]*$//'
}

#################################################################
# think piped to...   The "head -1" is there for Avi files...
#
# Clean up
#  Turku.jpg JPEG 450x331+0+0 DirectClass 8-bit 28.2kb 0.000u 0:01
# to:
#  Turku.jpg 450x331 28.2kb 
#
function _clean_identify_output()
{
    head -1 | \
    awk '{ 
            sub(/ ([0-9]+).([0-9]+)u/, "");      # 0.000u  <= removes the following
            sub(/ ([0-9]+)\-bit/, "");           # 8-bit
            sub(/ ([0-9]+)c/, "", $0);           # 256c
            sub(/ [0-9]\:[0-9][0-9]/, " ");      # 0:01
            sub(/\[[0-9]\] /, " ");              # Turku2.jpg[2]
            sub(/ ([0-9]+)x([0-9]+)\+0\+0/, ""); # 450x331+0+0
            sub(/ [[:alpha:]]+Class/, "");       # DirectClass
            sub(/ [[:upper:]]+ /, " ");          # JPEG
            sub(/kb /, " kb");                   # INTkb => INT kb
            sub(/mb /, " mb");                   # INTmb => INT mb

            print
    }'
}

#################################################################
function _extension_get()
{
    awk '{ 
       sub(/.*\./, "", $0) 
       print 
    }'
}

#################################################################
function _list_images()
{
    ls $1 *.[Jj][Pp][Gg]   \
        *.[Jj][Pp][Ee][Gg] \
        *.[Gg][Ii][Ff]     \
        *.[Pp][Nn][Gg]     \
        *.[Xx][Pp][Mm]     \
        *.[Aa][Vv][Ii]     \
        2>/dev/null
}

#################################################################
function _list_media()
{
    ls $1 *.[Aa][Vv][Ii]   \
        *.[Mm][Pp][Gg]     \
        *.[Mm][Pp][Ee][Gg] \
        *.3[Gg][Pp]        \
        *.[Ww][Mm][Vv]     \
        *.[Mm][Pp]3        \
        *.[Oo][Gg][Gg]     \
        *.[Aa][Ss][Ff]     \
        *.[Ss][Ww][Ff]     \
        *.[Pp][Pp][Ss]     \
        2>/dev/null
}

#################################################################
function _list_tot_images_amount()
{
    _list_images | wc -l
} 

#################################################################
function _get_tot_data_size()
{
    _list_images "-l" | \
        awk '{x += $5} {y=x/1000000} END {printf "%3.2f", y}'
}

#################################################################
# _no_convert                               no program, bad news.
#################################################################
function _no_convert()
{
    cat <<EOF

 [ ERROR ]

 I can't seem to find the " convert " - program,
 get it, or help me ($0) find it..."

 Download site: 
  o http://studio.imagemagick.org/www/convert.html

EOF
}

#################################################################
#  _old_convert           Tell (l)user about old convert program.
#################################################################
function _old_convert()
{
    cat <<EOF

 [ ERROR ]

 The "convert" program that you have is _too_old_,
 please upgrade to at least 6.2.3.

 Your program is locate here:   $IDENTIFY
 And the current version is:    $PROGVER

 Download site: 
  o http://studio.imagemagick.org/www/convert.html
     
EOF
}

#################################################################
function _check_convert_version()
{
    ONE=$(echo $PROGVER   | awk 'BEGIN { FS = "."} {print $1}')
    TWO=$(echo $PROGVER   | awk 'BEGIN { FS = "."} {print $2}')
    THREE=$(echo $PROGVER | awk 'BEGIN { FS = "."} {print $3}')
    
    # ONE  less than# 6.2.3 => ONE.TWO.THREE 
    if [ $ONE -lt 6 ]; then
        echo ONE MINDRE
        _old_convert
        exit 1
    else
        if [ $TWO -lt 2 ]; then
            echo TWO MINDRE
            _old_convert
            exit 1
        else
            
            if [ $THREE -lt 3 ]; then
                echo THREE MINDRE
                _old_convert
                exit 1
            fi
        fi
    fi
}

#################################################################
function _bootup()
{
    # Got Images?
    if [ `_list_tot_images_amount` = "0" ]; then
        cat <<EOF
Get me some IMAGES to work on pal...or else... :)
EOF
        exit 1
    fi

    # Got awk?
    which awk  2>/dev/null 1>/dev/null
    if [ $? != 0 ]; then
        cat <<EOF
 [ ERROR ]

 I can't seem to find the " awk " - program,
 get it, or help me ($0) find it...
EOF
        exit 1
    fi

    # Got Identify?
    which identify  2>/dev/null 1>/dev/null
    if [ $? != 0 ]; then
        cat <<EOF
 [ ERROR ]

 I can't seem to find the " identify " - program,
 get it, or help me ($0) find it..."

 Download site:
 o http://studio.imagemagick.org/www/convert.html 
EOF
        exit 1
    fi

    # OWN identify?
    if [ -x $HOME/bin/identify ]; then
        IDENTIFY=$HOME/bin/identify 
        PROGVER=$($IDENTIFY | head -1 | awk '{print $3 }')
        echo " [ => We are using our own version of IDENTIFY $PROGVER <= ]"
    else
        IDENTIFY=`which identify`
    fi
 
    # OWN convert?
    if [ -x $HOME/bin/convert ]; then
        CONVERT=$HOME/bin/convert 
        PROGVER=$($CONVERT | head -1 | awk '{print $3 }')
        _check_convert_version
        echo " [ => We are using our own version of CONVERT $PROGVER <= ]"
    else
        which convert  2>/dev/null 1>/dev/null
        if [ $? != 0 ]; then
            _no_convert # inform (l)user
            exit 1
        # Ok, we got the program, now check the version...
        else
            CONVERT=`which convert`
            PROGVER=$($CONVERT | head -1 | awk '{print $3 }')
            _check_convert_version
        fi
    fi
    
    # OK, WE SEEM TO HAVE ALL WE NEED, let's get started!
    echo -e "\n `_greeting` \n"

    # if we have been given some -s switches, show 'em...
    if [ -n "$GIVEN_ARGS" ]; then
        echo " [0/$TOT_STEPS] Given switches: $GIVEN_ARGS"
    fi

    # tmp files are sexy!
    TMP1=$(mktemp $TMP.XXXXXX) || exit 1
    TMP2=$(mktemp $TMP.XXXXXX) || exit 1
}

#################################################################
function _pwd()
{
    # Inform user if we are NOT faking pic size but showing it 
    # as big as it is...
    if [ $USE_ORIGINAL_PICTURE_WIDTH ]; then
        if [ -n "$FORCE_FAKE_PICTURE_WIDTH_SWITCH" -o -n "$FAKE_PICTURE_WIDTH_SWITCH" ]; then 
            echo -e "\n tn ERROR: -o must be used WITHOUT the -w or -W switch, bailing out...\n"
            exit 1
        fi
    else
        echo -e " [1/$TOT_STEPS] => Going to fake the image resolution in the HTML files (width=$FAKE_PICTURE_WIDTH)"
    fi

    TOT=$( _list_tot_images_amount )
    echo -e " [1/$TOT_STEPS] => Present working dir is: \"`pwd`\" and contains \"$TOT\" image(s)"
}

#################################################################
function _clean_dir()
{
    local REMOVE=""

    INDEXFILE_BASENAME=$(echo $INDEXFILE|sed 's/\..*//g')

    if [ $ONLY_CLEAN ]; then
        /bin/rm -rf $PIC_BASE ${INDEXFILE_BASENAME}* 2>/dev/null
        exit 0
    else
        echo -e " [1/$TOT_STEPS] => Removing old tn files: \c"
    fi

    # Now for the remove logic...
    if [ -z "$SKIP_TN_CREATION" ]; then
        REMOVE="$REMOVE $PIC_TN_DIR"
    fi

    # Now for the remove logic...
    if [ -z "$SKIP_PIC_IDENT_DATA_FILE" ]; then
        REMOVE="$REMOVE $PIC_IDENT_DATA_FILE"
    fi

    if [ -z "$SKIP_TN_HTML_CREATION" -a -z "$SKIP_HTML_CREATION" ]; then
        REMOVE="$REMOVE $PIC_HTML_DIR $PIC_HTML_SLIDES_DIR"
    fi

    if [ -z "$SKIP_HTML_CREATION" ]; then

        if [ -z "$SKIP_HTML_INDEX_CREATION" ]; then

            if [ -z "$SKIP_HTML_MULTI_CREATION" ]; then
                REMOVE="$REMOVE ${INDEXFILE_BASENAME}_[1-9]* ${INDEXFILE_BASENAME}.*"
            fi
            
            if [ -z "$SKIP_HTML_INDEX_ALL_CREATION" ]; then
                REMOVE="$REMOVE ${INDEXFILE_BASENAME}_all*"
            fi
        fi
    fi

    echo "$REMOVE"
    /bin/rm -fr $REMOVE
}

#################################################################
function _print_status_adj_backspace()
{
    if [ $1 -lt 10 ]; then
        BACKSPACE="${BACKSPACE}\\b\\b\\b\\b"
    elif [ $1 -lt 100 ]; then
        BACKSPACE="${BACKSPACE}\\b\\b\\b\\b\\b"
    elif [ $1 -lt 1000 ]; then
        BACKSPACE="${BACKSPACE}\\b\\b\\b\\b\\b\\b"
    elif [ $1 -lt 10000 ]; then
        BACKSPACE="${BACKSPACE}\\b\\b\\b\\b\\b\\b\\b"
    fi
}

#################################################################
function _print_status()
{
    if [ $1 -lt 10 ]; then
        if [ $1 -eq 1 ]; then
            BACKSPACE="${BACKSPACE}\\b\\b"
        fi
        echo -n " [$1/$2]"

    elif [ $1 -lt 100 ]; then
        if [ $1 -eq 10 ]; then
            BACKSPACE="${BACKSPACE}\\b"
        fi
        echo -n " [$1/$2]"

    elif [ $1 -lt 1000 ]; then
        if [ $1 -eq 100 ]; then
            BACKSPACE="${BACKSPACE}\\b"
        fi
        echo -n " [$1/$2]"

    elif [ $1 -lt 10000 ]; then
        if [ $1 -eq 1000 ]; then
            BACKSPACE="${BACKSPACE}\\b"
        fi
        echo -n " [$1/$2]"
    fi
}

#################################################################
# _generate_a_list_of_all_pics() -> Creates $ALL_PICS_LIST
function _generate_a_list_of_all_pics()
{
    local i

    for i in `_list_images` ; do
        ALL_PICS_LIST="$ALL_PICS_LIST ${i}"
    done
}


#################################################################
function _count_amount_of_args_to_give()
{
    local TMP=""
    local i=1
    
    if [ "$#" -gt "$TABLE_ROW_PICTURE_AMOUNT" ]; then

        while [ "$i" -le "$TABLE_ROW_PICTURE_AMOUNT" ]; do
            TMP="$TMP $1"
            let "i+=1"
            shift
        done

        ARG=${TMP}
        
    else
        while [ "$#" -gt "0" ]; do
            TMP="$TMP $1"
            let "i+=1"
            shift
        done
        
        ARG=${TMP}
    fi
}

#################################################################
function _fetch_picture_creation_data()
{
    local TMP
    
    # If user wanted picture creation data, add it...
    if [ -z $SKIP_PICTURE_CREATION_DATA ]; then
            TMP=$(ls --full-time -l $1 | awk '{print $6" "$7}' | sed 's#\..*##g')
            echo "$TMP"
    fi
}


#################################################################
function _count_index_page_nr()
{
    local TMP

    let "TMP = $1 / $INDEXFILE_NR_PIC_PER_PAGE"
    let "REMAINDER = $1 % $INDEXFILE_NR_PIC_PER_PAGE"
    
    if [ $REMAINDER != 0 ]; then
        let "TMP += 1"
    fi

    # return index page for given int
    echo $TMP
}

#################################################################
function _return_pictures_index_filename()
{
    local TMP=$(_count_index_page_nr $1)

    if [ $INDEX_NR_TOT -gt 1 ]; then
        TMP="${INDEXFILE_BASENAME}_${TMP}.html"
    else
        TMP="${INDEXFILE}"
    fi
    
    # returns full INDEX Filename for given number
    echo $TMP
}

#################################################################
# Make AVI and XPM files show up as pictures work around...
#################################################################
function _adjust_filename_if_other_than_normal_pic()
{
    if [ -n "`echo $1|grep -i \.avi`" -o -n "`echo $1|grep -i \.xpm`" ]; then 
        if [ -n "$2" ]; then 
            echo "$PIC_TN_DIR/`echo ${1} | _extension_remove`_name_hack.png"
        else
            echo "`echo ${1} | _extension_remove`.jpg"
        fi
    else
        echo ${1}
    fi
}

#################################################################
function _count_which_element_we_are()
{
    declare -a ARRAY=($ALL_PICS_LIST)
    ARRAY_TOT_IMAGES_AMOUNT=${#ARRAY[@]}
    
    local SEEK="$1" i="" j=""
    
    for (( i = 0 ; i < ARRAY_TOT_IMAGES_AMOUNT ; i++ )); do
        
        if [ -n "`echo  "${ARRAY[$i]}"  | grep $SEEK`" ]; then
            j="$i"
            let "j += 1"
            echo  $j
            break
        fi
    done
}


#################################################################
function _generate_thumbnails()
{
    local j="1"

    _clean_dir 
    mkdir $PIC_BASE $PIC_TN_DIR $PIC_HTML_DIR $PIC_HTML_SLIDES_DIR 2>/dev/null

    # Total picture count..
    TOT=$( _list_tot_images_amount )

    # make the thumbnails only is user has asked us to do so.
    if [ -z $SKIP_TN_CREATION ]; then

        echo -e " [2/$TOT_STEPS] => Creating new thumbnails ($TN_RESO) with something like:"
        echo -e "          $CONVERT -size $TN_RESO <image> -resize $TN_RESO +profile '*' <image_thumb>\n"

        # This take both pictures and avi files into account
        for i in `_list_images`; do

            echo -e "  [$j/$TOT] Converting ${i} => \c"

            # AVI's
            if [ -n "`echo $i|grep -i "\.avi" `" ]; then

                echo -e "`echo $i | _extension_remove`.png "
                
                $CONVERT -size $TN_RESO ${i}[0] -resize $TN_RESO +profile '*' \
                    $PIC_TN_DIR/`echo $i| _extension_remove`.png

                # also create a bigger temp picture from the avi file..
                $CONVERT -size $FAKE_PICTURE_WIDTH ${i}[0] -resize $FAKE_PICTURE_WIDTH +profile '*' \
                    $PIC_TN_DIR/`echo $i| _extension_remove`_name_hack.png
            # XPM's
            elif [ -n "`echo $i|grep -i "\.xpm" `" ]; then
                
                echo -e "`echo $i | _extension_remove`.png "
                
                $CONVERT -size $TN_RESO $i -resize $TN_RESO +profile '*' \
                    $PIC_TN_DIR/`echo $i| _extension_remove`.png

                # also create a bigger temp picture from the avi file..
                $CONVERT -size $FAKE_PICTURE_WIDTH $i -resize $FAKE_PICTURE_WIDTH +profile '*' \
                    $PIC_TN_DIR/`echo $i| _extension_remove`_name_hack.png

            # PICTURE's
            else
                echo -e "`echo $i | _extension_remove`.png "
                
                $CONVERT -size $TN_RESO $i -resize $TN_RESO +profile '*' \
                    $PIC_TN_DIR/`echo $i| _extension_remove`.png
            fi
            
            # inc it baby
            let "j+=1"
        done 
    fi

    # Just to get nicer output...print an empty line if we are 
    # skipping the HTML creation part...
    if [ $SKIP_HTML_INDEX_CREATION ]; then
        echo 
    fi
}

#################################################################
# _generate_pictures_data_file() -> creates $PIC_IDENT_DATA_FILE
function _generate_pictures_data_file()
{
    # Generate HTML pages unless told otherwise...
    if [ -z "$SKIP_HTML_CREATION" ]; then

        local i FILE_CREATION_DATA IDENT_FILE_DATA 
        local CURRENT_ROUND=1 BACKSPACE="" 

        # Make sure that we end up with a data file...
        if [ -e "$PIC_IDENT_DATA_FILE" -a -n "$SKIP_PIC_IDENT_DATA_FILE" ]; then
            echo -e "\n [3/$TOT_STEPS] => Skipping identify picture data file generation..."
        # ok, no ident file always create it...
        else
            # Get statistics up & running....
            TOT_PIC=$(_list_tot_images_amount)
            _print_status_adj_backspace $TOT_PIC

            echo -e "\n [3/$TOT_STEPS] => Generating the picture data file:\c"

            for i in $ALL_PICS_LIST ; do

                IDENT_FILE_DATA=$($IDENTIFY $i | _clean_identify_output)
                FILE_CREATION_DATA=$(ls -l --time-style='+%Y-%m-%d %H:%M:%S' $i |awk '{print $6" "$7}')

                echo "$IDENT_FILE_DATA $FILE_CREATION_DATA" >> $PIC_IDENT_DATA_FILE

                    # Update [X/Y] stats...
                _print_status $CURRENT_ROUND $TOT_PIC
                echo -n -e $BACKSPACE
                
                let "CURRENT_ROUND += 1"

            done
            echo 
        fi
    fi
}

#################################################################
# _return_picture_data(picture) -> Retuns something like:
#
#         2003_11_lootan_havet.jpg 800x600 121.074 kb
#
function _return_picture_data()
{
    local RE=$1
    grep "$RE" $PIC_IDENT_DATA_FILE
}

function _return_picture_data_for_main_img_html()
{
    local RE=$1
    _return_picture_data ${RE} |\
    awk '{print "<b>" $1 "</b><br>" $2" "$3" "$4" "$5" "$6 }'
}


#################################################################
function _generate_index_base_args()
{
    TOT_PIC=$(_list_tot_images_amount)

    # Calculcate total number of INDEX files to create
    let "INDEX_NR_TOT = TOT_PIC / INDEXFILE_NR_PIC_PER_PAGE"

    # If we got a remainder from the division, add one more index page to
    # contain the "left over" files
    let "REMAINDER = $TOT_PIC % $INDEXFILE_NR_PIC_PER_PAGE"

    if [ $REMAINDER != 0 ]; then
        let "INDEX_NR_TOT += 1"
    fi

    # Prevent divide by zero...
    if [ "$INDEX_NR_TOT" = 0 ]; then
        INDEXFILE_NR_TOT=1
    fi
}


#################################################################
function _generate_index_pages()
{
    if [ -z "$SKIP_HTML_CREATION" ]; then
        if [ -z "$SKIP_HTML_INDEX_CREATION" ]; then

            local TMP_INDEX_NR_TOT

            _generate_index_base_args

            INDEXFILE_BASENAME=$(echo $INDEXFILE|sed 's/\..*//g')
            INDEXFILE_NR=1

            # Fake it to the uses so that he know what it multi + all index
            # page that we are going to be creating...
            TMP_INDEX_NR_TOT=$INDEX_NR_TOT
            let "TMP_INDEX_NR_TOT += 1"

            # Now we parse the VARIABLE, to set the POS.
            for FN in "$ALL_PICS_LIST" ; do
                set -- $FN        # Parses variables and sets positional parameters.
            done

            if [ -z "$SKIP_HTML_MULTI_CREATION" ]; then
                # minus one if we are skipping the index ALL...
                if [ -n "$SKIP_HTML_INDEX_ALL_CREATION" ]; then
                    let "TMP_INDEX_NR_TOT -= 1"
                fi

                # Do not create multiple pages if all images can fit on 
                # one page...
                if [ $INDEX_NR_TOT -gt 1 ]; then

                    #################################################################
                    # Create the multiple index files...
                    while [ $INDEXFILE_NR -le $INDEX_NR_TOT ]; do
                        INDEXFILE="${INDEXFILE_BASENAME}_${INDEXFILE_NR}.html"

                        # Take from $* the filenames and give them to the sepparate
                        # index files (note: indata is $1 not $i....)
                        for (( i = 0 ; i < INDEXFILE_NR_PIC_PER_PAGE ; i++ )); do
                            CURRENT_ROUND="$CURRENT_ROUND $1"
                            shift
                        done
                        
                        # Inform what's going on to user...
                        echo -e " [4/$TOT_STEPS] => Generating \"$INDEXFILE\" ($INDEXFILE_NR/$TMP_INDEX_NR_TOT):\c"

                        # pipes output to current $INDEXFILE
                        _html_generate_index_head  $INDEXFILE_NR
                        _html_generate_index_image $CURRENT_ROUND

                        # Place the VID list only on the last Multi and All page
                        if [ $INDEXFILE_NR -eq $INDEX_NR_TOT ]; then
                            _html_generate_index_other_media
                        fi

                        _html_generate_index_tail $INDEXFILE_NR
                        
                        CURRENT_ROUND=""
                        let "INDEXFILE_NR += 1"
                        echo
                    done
                fi
            fi

            if [ -z "$SKIP_HTML_INDEX_ALL_CREATION" ]; then
                # Keep to original INDEXFILE-name if we can fit all images
                # on one page...
                if [ $INDEX_NR_TOT -gt 1 ]; then
                    INDEXFILE="${INDEXFILE_BASENAME}_all.html"
                fi

                # one out of one step is we are skipping the multiple index's...
                if [ -n "$SKIP_HTML_MULTI_CREATION" ]; then
                    TMP_INDEX_NR_TOT=1
                fi

                #################################################################
                # Create the index file that contains ALL files in one...
                echo -e " [5/$TOT_STEPS] => Generating \"$INDEXFILE\" ($INDEXFILE_NR/$TMP_INDEX_NR_TOT):\c"

                # Re-set all psition arguments for the last time...
                for FN in "$ALL_PICS_LIST" ; do
                    set -- $FN        # Parses variables and sets positional parameters.
                done

                # Generate the ALL index page...
                _html_generate_index_head all
                _html_generate_index_image $*
                _html_generate_index_other_media
                _html_generate_index_tail all

                echo 
            fi
        fi
    fi
}


#################################################################
function _generate_picture_pages()
{
    if [ -z "$SKIP_HTML_CREATION" ]; then
        if [ -z "$SKIP_TN_HTML_CREATION" ]; then

            local FN="" FILES="" BACKSPACE="" COUNTER="1"
            local TMP_INDEX_NR_TOT

            echo -e " [6/$TOT_STEPS] => Generating the SlideShow & Plain HTML files:\c"

            _generate_index_base_args

            # Now we parse the VARIABLE, to set the POS.
            for FN in "$ALL_PICS_LIST" ; do
                set -- $FN  
            done

            # Some Variables that will be useful a bit later...
            PIC_FIRST=$(echo $* | awk '{ print $1  }' | _extension_remove )
            PIC_LAST=$(echo $*  | awk '{ print $NF }' | _extension_remove )

            # Stats up & running...
            TOT_PIC=$( _list_tot_images_amount )
            _print_status_adj_backspace $TOT_PIC

            # Now we do the mangeling itself ;-)
            while [ $# -ge "1" ]; do
                
                PIC_PRESENT=${1}
                PIC_NEXT=${2}
                
                IDENT=$(_return_picture_data $PIC_PRESENT)      
                
                # ====================== (1/3) ============================
                # 1st picture has only have a *_NEXT_* link...
                if [ $# -eq $TOT_PIC ]; then

                    _html_generate_picture_pages_wrapper first slideshow_start $PIC_PRESENT $PIC_NEXT
                    _html_generate_picture_pages_wrapper first slideshow_stop  $PIC_PRESENT $PIC_NEXT

                    _print_status $COUNTER $TOT_PIC
                    echo -n -e $BACKSPACE
                    
                # ========================= (2/3) =========================
                # Last Picture. Does NOT have a NEXT, only PREVIOUS link + pic.
                elif [ $# -eq "1" ]; then

                    _html_generate_picture_pages_wrapper last slideshow_start $PIC_PRESENT $PIC_PREVIOUS
                    _html_generate_picture_pages_wrapper last slideshow_stop  $PIC_PRESENT $PIC_PREVIOUS

                    _print_status $COUNTER $TOT_PIC
                    echo -n -e $BACKSPACE
                    
                    # We're outta here... last lap == EXIT LOOP
                    break
                    
                # =========================== (3.1) =======================
                # If it isn't the FIRST or LAST picture, zen do the normal
                # tango!
                else
                    _html_generate_picture_pages_wrapper middle slideshow_start $PIC_PRESENT $PIC_NEXT $PIC_PREVIOUS
                    _html_generate_picture_pages_wrapper middle slideshow_stop  $PIC_PRESENT $PIC_NEXT $PIC_PREVIOUS

                    _print_status $COUNTER $TOT_PIC
                    echo -n -e $BACKSPACE
                fi

                # Get the Previous pic...
                PIC_PREVIOUS=$PIC_PRESENT

                # Get next picture...
                shift

                # Inc our index number...
                let "COUNTER+=1"
            done
        fi
        echo
        echo
    fi
}

#################################################################
function _usage()
{
    cat <<EOF

`_greeting`

Usage:
 `basename $0` [ -h(elp) ] [ -v(ersion) ] [ -c(lean) ] [-C(onvert) ] [-o(riginal) ]
                [ -n(o) ( rc | cr | tn | data | html | name ) ]
Where:

 -h (help)          = This help message

 -v (version)       = Prints out the program version

 -c (clean)         = Cleans the present dir from tn stuff

 -C (Convert)       = Converts your pictures to a wanted size

 -f (force)         = If present working dir has a .tnrc-file, 
                      source it without prompting for anything 
                      (be careful!)    

 -i (index pics)    = override INDEXFILE_NR_PIC_PER_PAGE with given
                      integer value.

 -o (original)      = Use the images original size on the "single" 
                      image page instead of the normal faked size.             

 -w (give width)    = Give FAKE image size which is placed in the 
                      HTML files (this can also be set via the rc-
                      file(s))

 -W (give Width)    = FORCE FAKE image size regardless if image is 
                      smaller than the faked image size (image will 
                      be shown with bigger pixels...)

 -s (skip) rc       = Skip possible rc files in pwd

           cr       = Skip print $AUTHOR as copy-right holder

           tn       = Skip the creation of the image thumbails
                      I.e use this to win some time if your images
                      have _not_ changed.

           data     = Skip the pictures creation data

           html     = Skip the creation all _HTML_ pages

           index    = Skip the creation all _index_ HTML pages

           all      = Skip the creation of the "All" index file
                      (ie the index file that has all images in 
                      one single page).

           multi    = Skip the creation of the "Multiple" index files.

           tn_html  = Skip the creation of the tn html pages.

           name     = Skip print out the pictures names on the 
                      main thumbnail page.

           ident    = Skip the re-generaion of the picture ident data file,
                      re-use the existing file (if present)  instead.

           max_char = Skip chopping the filenames on the index pages.

Example:
 `basename $0` -s tn -s rc -f

EOF
}

#################################################################
function _skip_arg_choices()
{
    for i in $*; do 
        case $i in
            rc      ) SKIP_RC_SOURCING=1; GIVEN_ARGS="SKIP_RC_SOURCING $GIVEN_ARGS ";;
            cr      ) SKIP_COPYRIGHT=1;   GIVEN_ARGS="SKIP_COPYRIGHT $GIVEN_ARGS";; 
            tn      ) SKIP_TN_CREATION=1; TOT_STEPS=4; GIVEN_ARGS="SKIP_TN_CREATION $GIVEN_ARGS ";; 
            data    ) SKIP_PICTURE_CREATION_DATA=1; GIVEN_ARGS="SKIP_PICTURE_CREATION_DATA $GIVEN_ARGS ";;
            html    ) SKIP_HTML_CREATION=1 ; TOT_STEPS=3; GIVEN_ARGS="SKIP_HTML_CREATION $GIVEN_ARGS";; 
            index   ) SKIP_HTML_INDEX_CREATION=1 ; TOT_STEPS=3; GIVEN_ARGS="SKIP_HTML_INDEX_CREATION $GIVEN_ARGS";; 
            all     ) SKIP_HTML_INDEX_ALL_CREATION=1 ; TOT_STEPS=3; GIVEN_ARGS="SKIP_HTML_INDEX_ALL_CREATION $GIVEN_ARGS";; 
            multi   ) SKIP_HTML_MULTI_CREATION=1 ; TOT_STEPS=3; GIVEN_ARGS="SKIP_HTML_MULTI_CREATION $GIVEN_ARGS";; 
            tn_html ) SKIP_TN_HTML_CREATION=1 ; TOT_STEPS=3; GIVEN_ARGS="SKIP_TN_HTML_CREATION $GIVEN_ARGS";; 
            name    ) SKIP_PICTURE_NAME=1 ; TOT_STEPS=4; GIVEN_ARGS="SKIP_PICTURE_NAME $GIVEN_ARGS";; 
            max_char) SKIP_MAX_CHARACTERS=1 ; GIVEN_ARGS="SKIP_MAX_CHARACTERS $GIVEN_ARGS";; 
            ident   ) SKIP_PIC_IDENT_DATA_FILE=1; GIVEN_ARGS="SKIP_PIC_IDENT_DATA_FILE $GIVEN_ARGS";; 
            *       ) echo 'ERROR: -n need "rc", "cr", "tn" or "html" as parameter'; _usage; exit 1;;
        esac
    done
}

# ------------------ [ Start of Main ] --------------------------
# MAIN (Param parser....)
if [ $# != 0 ]; then
    while getopts "hvcCdfow:W:s:i:" Option; do
        case $Option in
            # Help
            h ) _usage; exit 0;;
            # Version
            v ) echo $VERSION; exit ;;
            # Clean, get rid of tn stuff
            c ) ONLY_CLEAN=1 ; _clean_dir ; exit ;;
            # Convert, change picture size
            C ) _ask_convert_pic_size; exit ;;       
            # Force, force pwd tnrc sourcing...
            f ) FORCE=1;GIVEN_ARGS="FORCE_TNRC_EXECUTION $GIVEN_ARGS";;
            # give from prompt INDEXFILE_NR_PIC_PER_PAGE
            i ) INDEXFILE_NR_PIC_PER_PAGE=${OPTARG}; GIVEN_ARGS="INDEXFILE_NR_PIC_PER_PAGE $GIVEN_ARGS";;
            # Use the Original images size...
            o ) USE_ORIGINAL_PICTURE_WIDTH=1;GIVEN_ARGS="USE_ORIGINAL_PICTURE_WIDTH $GIVEN_ARGS";;
            # Give FAKE image Size...(images size must be bigger than fake)
            w ) FAKE_PICTURE_WIDTH_SWITCH=${OPTARG};GIVEN_ARGS="FAKE_PICTURE_WIDTH $GIVEN_ARGS";;
            # FORCE give FAKE image Size...(fake all images sizes)
            W ) FORCE_FAKE_PICTURE_WIDTH_SWITCH=${OPTARG};GIVEN_ARGS="FORCE_FAKE_PICTURE_WIDTH $GIVEN_ARGS";;
            # no_pwd_rc, answer always not to pwd rc question.
            s ) _skip_arg_choices ${OPTARG};;
            # All else, bad input...
            * ) echo "ERROR: bad input"; _usage; exit 1;;
        esac
    done
    shift $(($OPTIND - 1))
fi

#################################################################
# BOOOOOOOOOOOOTUP happends here!
#################################################################
_bootup            
_user_rc           # Check if user has a " ~/${TN_RC_FILE} " file
_pwd_rc            # Check if user has specific "${TN_RC_FILE}" for pic dir...
_pwd               

_generate_a_list_of_all_pics
_generate_thumbnails
_generate_pictures_data_file
_html_generate_css_file
_generate_index_pages
_generate_picture_pages
_clean_up_and_exit

exit 0
