#!/bin/bash

#--------------------------------------------------------------------------
# Copyright (C) 2001-2002, 2004 by Daniel Käps.
#
# 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.
#
# If you do not have a copy of the GNU General Public License write to
# the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
#--------------------------------------------------------------------------

#--------------------------------------------------------------------------
# TODO 
# - it would be nice if some options could be stored permanently in 
#   a config file
# - necessity of image conversion could be determined by looking 
#   at file modification time stamps
# - auto-detect if viewer is running already
# - compile to specifically created directory, e.g. /tmp/MyLetter/,
#   maybe also /tmp/UID-MyLetter/ (to avoid name conflicts in /tmp)
#
# CHANGES:
# - 2001-10-03: 
#   - added -I INCLUDEDIR option
# - 2002-09-01: 
#   - now use convert -compress zip IMAGE.PNG eps2:IMAGE.png.eps 
#     to create encapsulated postscript for PNG images
# - 2002-09-02:
#   - now, a file "config.tex" is generated which contains
#     some setup variables for use with my "Graphics.tex"
#   - now the option --prepare-images creates either EPS or makes
#     soft links to images files, depending on the output format
# - 2004-04-07:
#   - option help text: sorted and added descriptions
#   - added option '--no-etex'
# - 2004-04-08:
#   - "config.tex" is now created only if the '--config' option is given
#   - improved option parsing
# - 2004-09-30:
#   - introduced marker files for temporary files created by this script
#     (named FILE.texview-created) to avoid accidental removal of
#     source files or images when compilation directory is the same as
#     the directory of .tex source file
#   - added option '--set-viewer'
# - 2004-10-10:
#   - renamed program from 'ViewTex' to 'texview', help text 
#     improvements
# - 2004-10-14:
#   - compilation is done in /tmp/texview-$USER instead of /tmp because
#     compiling in /tmp with TEXINPUTS pointing to current directory 
#     (which is usally the case) is a big security hole. This also 
#     reduces chances of conflicts with same file names when texview
#     is invokeed by different users at the same time.
#   - added directory of source .tex file to search path
# - 2011-01-12:
#   - some fix in command line option processing
#
#--------------------------------------------------------------------------

# stop execution of this script on any unhandled error:
set -e
# remove globbing expressions without match:
shopt -s nullglob

TexView="texview"
TexViewMarkerSuffix=".texview-created"
ProgramName=`basename "$0" .sh`
ProgramVersionString="0.8.2.1 (2011-01-12)"


#--------------------------------------------------------------------------
# variable initialization:

# may setup default viewer as desired:
PSViewProgram="gv -antialias -watch"
PdfViewProgram="xpdf"
HtmlViewProgram="w3m"

# fixed setup defines
ViewProgram="" # shall be empty string
TemporaryDirectory="${TMPDIR:=/tmp}/texview-$USER"
ConfigFile="config.tex"

# default values for program options

OutputFormat=dvips

IsGenerateFiles=false
IsSecondRun=false
IsOpenViewer=false
IsRemoveIntermediateFiles=false
IsRemoveOutputFiles=false
IsIgnoreRemoveOutputFiles=false

IsGotoTemporaryDir=true
IsSymlinkCopy=false

IsUseEtex=true
IsCallTidy=false
IsCreateConfigFile=false

IsPrepareImages=false
IsConvertImagesToEPS=false
IsCreateImageLinks=false
IsConvertPngToGif=false
PngConversion="bmeps"
TiffConversion="bmeps"

# if [ "$OSTYPE" = "cygwin32" ] ; then
#     # HACK under Win32, ImageMagick's convert decompresses PNG images
#     # when converting from PNG to EPS2, which is not desireable, so
#     # as a workaround we convert PNG to JPEG first, and then convert
#     # it to EPS2 using jpeg2ps
#     IsConvertPngToJpeg=true
# fi

#--------------------------------------------------------------------------

CommonHelpString()
{
    IsFullHelp="$1"

    #--------------------------------------------------------------------------
    if $IsFullHelp ; then cat <<.
NAME

    texview - One-step LaTeX source compiliation, output viewing, and temp. 
              file cleanup

.
    fi

    cat <<.
SYNOPSIS

    $ProgramName OPTIONS FILE

.

    if $IsFullHelp ; then cat <<.
DESCRIPTION

    Texview manages compilation of a LaTeX source file, viewing the
    output with a default or specified viewer, and cleaning up
    generated files, all by issuing just a single command.
    Handled output formats are PostScript (via latex/elatex/dvips), 
    PDF (via pdflatex/pdfelatex) and HTML (via tex4ht). For PostScript 
    output, images can be converted to EPS files by calling specialized
    conversion programs if requested.

.
fi

    #--------------------------------------------------------------------------
    cat <<.
OPTIONS

  output format:
    -ps,   --dvips             generate PostScript output (default)
    -pdf,  --pdftex            generate PDF (Portable Document Format) output
    -html, --tex4ht            generate HTML output via 'tex4ht'

  actions:
    -c, --compile              compile source
        --run-twice            run two times to resolve simple references
    -v, --view                 open the viewer
        --clean-intermediate   delete intermediate files
        --clean-output         delete output files
        --clean                delete intermediate and output files

  directory options:
    -I INCLUDEDIR              specify additional include directory
    -s, --current-dir          place temporary files into current directory
                               (default is to put them into 
                               "$TemporaryDirectory")
        --symlink-copy         make copies instead of symlinks

  special:
        --no-etex              use tex (latex, pdflatex) versions instead of
                               default etex (elatex, pdfelatex)
        --html-tidy            run 'htmltidy' to clean up HTML code generated
                               by 'tex4ht'
        --config               create a file called "$ConfigFile" containing
                               some setup variables
    -e, --set-viewer PROGRAM   use PROGRAM as viewer instead of default

  image options:
    -i, --prepare-images       prepare images found in the directory of the 
                               LaTeX input file
    -gif, --convert-png-to-gif convert PNG to GIF (for Web-browsers 
                               supporting GIF but not PNG)
        --png-with-bmeps       PNG to EPS conversion using 'bmeps' (default)
        --png-with-convert     PNG to EPS conversion using 'convert'
        --png-with-jpeg2ps     PNG to JPEG to EPS conversion using 'jpeg2ps'
        --tiff-with-bmeps      TIFF to EPS conversion using 'bmeps' (default)
        --tiff-with-convert    TIFF to EPS conversion using 'convert'
        --tiff-with-jpeg2ps    TIFF to JPEG to EPS conversion using 
                               'jpeg2ps'
        --tiff-with-tiff2ps    TIFF to EPS conversion using 'tiff2ps'

  program options:
        --help                 display short help text
        --man                  display complete help
    -V, --version              output version information and exit

.

    #--------------------------------------------------------------------------
    if [ $IsFullHelp = "false" ] ; then cat <<.
To display examples, notes and copying conditions, use the "--man" option.
.
    fi

    if $IsFullHelp ; then cat <<.
NOTES

  1 The file name of the input LaTeX file must have the extension 
    ".tex".

  2 Input search paths:

  2.1 The directory of the source file is added added automatically 
      to the TEXINPUTS environment variable.

  2.2 pdflatex: setting TEXINPUTS seems to cause some systems to
      be unable to find 'pdftex.cfg'.

      This problem may be solved by also adding the path to
      'pdftex.cfg' to TEXINPUTS via -I /path/to/pdftexconfig/ (try
      'locate "pdftex.cfg"' to know where it is on your system).

  3 Image conversion notes:
  
  3.1 If option '--prepare-images' is given, _all_ JPEG, PNG and
      TIFF images found in the .tex input file's directory will
      be considered. Images are "detected" only based on filename
      extensions (".jpg", ".jpeg" for JPEG, ".tif", ".tiff" for
      TIFF, ".png" for PNG; note that image extensions must be 
      lowercase).

  3.2 The actions implied by the '--prepare-images' option depend
      on the choosen output format.

      For PostScript output, PNG, JPEG and TIFF images are
      converted to EPS. The conversion programs used for PNG and
      TIFF type images depend on the specified options; JPEG
      images are converted to the EPS format with the program
      'jpeg2ps'.

      For HTML/tex4ht, conversion of PNG and JPEG type images is
      not required in general, but for tex4ht the images should
      be in the same directory (or a relative-addressed
      directory) to avoid having the absolute paths coded into
      the HTML. Therefore, symlinks to the image files will be
      created in the compilation directory.  Alternatively, the
      image files can be copied to the compilation directory when
      option '--symlink-copy' is given.

  4 The viewer setup currently used by default is:
      - PS output: $PSViewProgram 
      - PDF output: $PdfViewProgram
      - HTML output: $HtmlViewProgram

.

    #--------------------------------------------------------------------------
    cat <<.
EXAMPLES

  1 Most simplest usage: compile .dvi/.ps in /tmp, display and cleanup:
      $TexView letter.tex

  2 Specify image conversion and additional TeX input directory:
      $TexView -i -I ~/MyLatexLib Article.tex --ps
      $TexView -i -I ~/MyLatexLib Article.tex --pdf
      $TexView -i -I ~/MyLatexLib Article.tex --tex4ht

  3 Multiple compilation cycles (default (PS) output):
    compile and open viewer:
      $TexView -i -I ~/MyLatexLib Article.tex --compile --view

    leave viewer open, edit Article.tex, then compile again:
      $TexView -i -I ~/MyLatexLib Article.tex --compile

    finally, clean up output and temporary files:
      $TexView -i -I ~/MyLatexLib Article.tex --clean

    The last '--clean' step may be realized by the instance started 
    in the first step by sending it to the background, and closing the 
    viewer when done. For this, add '--clean' (which is identical
    to not specifying the three options '--compile', '--view',
    '--clean'.

  4 Use of different viewers or viewer-options:

    Use 'acroread' instead of default 'xpdf':
      $TexView --set-viewer acroread --pdf letter.tex

    Use viewer 'gv' (Ghostview) with some arguments:
      $TexView --set-viewer 'gv -landscape -watch -antialias' \\
          --ps letter.tex

.

    #--------------------------------------------------------------------------
    cat <<.
PREREQUISITES

  1 for PS output and viewing:
    latex/elatex
    gv (or alternative viewer)

  2 for PDF output and viewing:
    pdflatex/pdfelatex
    xpdf (or alternative viewer)

  3 for HTML output and viewing: 
    tex4ht (ht), latex/elatex
    w3m (or alternative viewer)
    ModifyFiles, tex4ht-post-process, htmltidy

  4 for image conversions: 
    jpeg2ps, bmeps, convert, tiff2ps

SEE ALSO

    programs mentioned under 'Prerequisites'
    \`\`Compressed Images in PostScript and PDF with LaTeX'' HOWTO

AUTHOR

    Daniel Käps (kaeps AT informatik.uni-leipzig.de)

COPYRIGHT

    Copyright © 2004 Daniel Käps.
    This is free software; see the source for copying conditions. 
    There is NO warranty; not even for MERCHANTABILITY or FITNESS 
    FOR A PARTICULAR PURPOSE.

.
    fi

}

#-------------------------------------------------------------

ShortHelpString()
{
CommonHelpString false
}

#-------------------------------------------------------------

LongHelpString()
{
CommonHelpString true

}

#--------------------------------------------------------------------------

error_echo()
{
    echo "$ProgramName: $@" >&2
}

#--------------------------------------------------------------------------

# no-operation:
no_op()
{
    # dummy statement:
    return 0
}

#--------------------------------------------------------------------------

add_texinput_path()
{
    Directory="$1"
    if [ -z "$TEXINPUTS" ] ; then
        export TEXINPUTS="$Directory:"`kpsepath tex | sed "s,!!,,g"`
    else
        export TEXINPUTS="$Directory:$TEXINPUTS"
    fi
    # DEBUG: echo "NOTE: input path: $TEXINPUTS"
}

#--------------------------------------------------------------------------
# option parsing

while [ -n "$1" ]
do
    # transform options like --optionname into -optionname
    Option=${1/#--/-}
    case "$Option" in

        "-dvips"|"-ps")
            OutputFormat="dvips"
            ;;
        "-pdftex"|"-pdf")
            OutputFormat="pdftex"
            ;;
        "-tex4ht"|"-html")
            OutputFormat="tex4ht"
            ;;

        "-compile"|"-c")
            IsGenerateFiles=true
            ;;
        "-run-twice")
            IsSecondRun=true
            ;;
        "-view"|"-v")
            IsOpenViewer=true
            ;;
        "-clean-intermediate")
            IsRemoveIntermediateFiles=true
            ;;
        "-clean-output")
            IsRemoveOutputFiles=true
            ;;
        "-keep-output")
            IsIgnoreRemoveOutputFiles=true
            ;;
        "-clean")
            IsRemoveIntermediateFiles=true
            IsRemoveOutputFiles=true
            ;;

        "-I")
            shift 1
            Directory="$1"
            add_texinput_path "$Directory"
            ;;
        "-current-dir"|"-s")
            IsGotoTemporaryDir=false
            ;;
        "-symlink-copy")
            IsSymlinkCopy=true
            ;;

        "-no-etex")
            IsUseEtex=false ;;
        "-html-tidy")
            IsCallTidy=true ;;
        "-config")
            IsCreateConfigFile=true ;;
        "-set-viewer"|"-e")
            shift
            ViewProgram="$1"
            ;;

        "-prepare-images"|"-i")
            IsPrepareImages=true
            ;;
        "-convert-png-to-gif"|"-gif")
            IsConvertPngToGif=true
            ;;
        "-png-with-bmeps")
            PngConversion="bmeps" ;;
        "-png-with-convert")
            PngConversion="convert" ;;
        "-png-with-jpeg2ps")
            PngConversion="jpeg2ps" ;;
        "-tiff-with-bmeps")
            TiffConversion="bmeps" ;;
        "-tiff-with-convert")
            TiffConversion="convert" ;;
        "-tiff-with-jpeg2ps")
            TiffConversion="jpeg2ps" ;;
        "-tiff-with-tiff2ps")
            TiffConversion="tiff2ps" ;;

        "-help")
            ShortHelpString
            exit 1 ;;
        "-man"|"-manual")
            LongHelpString
            exit 1 ;;
        "-version"|"-V")
            echo -e "$ProgramVersionString\n"
            exit 1
            ;;

        "-"*)
            error_echo "unrecognized option: \"$1\""
            error_echo "Try ``--help'' for more information."
            exit 1
            ;;
        *)
            ArgumentArray[${#ArgumentArray[*]}]="$1"
            ;;
     esac
     shift 1
done

#--------------------------------------------------------------------------

if [ ${#ArgumentArray[*]} != 1 ] ; then
    error_echo "only exactly one input file allowed."
    echo -e "$UsageString"
    exit 1
fi

if $IsPrepareImages ; then
    if [ "$OutputFormat" == "dvips" ] ; then
        IsConvertImagesToEPS=true
    else
        IsCreateImageLinks=true
    fi
fi

# if no action was specified, the default is to do everything
if [ $IsGenerateFiles == false -a $IsGenerateFiles == false -a $IsOpenViewer == false -a $IsRemoveIntermediateFiles == false -a $IsRemoveOutputFiles == false ]
then
    IsGenerateFiles=true
    IsOpenViewer=true
    IsRemoveIntermediateFiles=true
    IsRemoveOutputFiles=true
fi

if $IsIgnoreRemoveOutputFiles ; then
    IsRemoveOutputFiles=false
fi

# use viewer set by default if no '--set-viewer' option was given:
case "$OutputFormat" in
    dvips)
        no_op ${ViewProgram:=$PSViewProgram}
        ;;
    pdftex)
        no_op ${ViewProgram:=$PdfViewProgram}
        ;;
    tex4ht)
        no_op ${ViewProgram:=$HtmlViewProgram}
        ;;
    *)
        error_echo "Error: unsupported output format \"$OutputFormat\""
        exit 1
        ;;
esac

#--------------------------------------------------------------------------

# SYNOPSIS 
#     symlink_or_copy SOURCE DEST
#
# If $IsSymlinkCopy is true, the specified files are copied from SOURCE
# to DEST, if it is false, a symbolic link is created.
symlink_or_copy()
{
    Source="$1"
    Dest="$2"
    DestMarkerFilename="$Dest$TexViewMarkerSuffix"
    if [ -e "$DestMarkerFilename" -o ! -e "$Dest" ] ; then
        if [ -e "$DestMarkerFilename" ] ; then
            rm "$DestMarkerFilename"
            rm "$Dest"
        fi

        if $IsSymlinkCopy ; then
            # we must check for the return value of 'cp' - return of error
            # may indicate that $Source and $Dest are the same file, in which case
            # we don't want to create the "$Dest.texview-created" marker file.
            if cp "$Source" "$Dest" ; then
                echo "The file \"$Dest\" is a temporary file created by $TexView" \
                    "and will be removed by the $TexView cleanup." \
                    >"$DestMarkerFilename"
            fi
        else
            if ln -s "$Source" "$Dest" ; then
                echo "The symlink \"$Dest\" is a temporary symlink created by $TexView "\
                    "and will be removed by the $TexView cleanup." \
                    >"$DestMarkerFilename"
            fi
        fi
    else
        if cmp --quiet "$Source" "$Dest" ; then
            echo "not copying \"$Source\" to \"$Dest\""
        else
            error_echo "file \"$Dest\" exists already, please check if your compiling in" \
                "the correct directory!"
        fi
    fi

}

# SYOPSIS 
#     remove_symlink_or_copy SOURCE DEST
#
# If $IsSymlinkCopy is true, the specified file in DEST is removed or
# when false, the specified link in DEST is removed.
remove_symlink_or_copy()
{
    Source="$1"
    Dest="$2"
    DestMarkerFilename="$Dest$TexViewMarkerSuffix"
    if [ -e "$DestMarkerFilename" ] ; then
        rm "$DestMarkerFilename"
        rm "$Dest"
    fi
}

#--------------------------------------------------------------------------

tempfile_remove_handler()
{
    set +e
    
    #--------------------------------------------------------------------------
    # remove intermediate files
    
    if $IsRemoveIntermediateFiles ; then
        if $IsCreateConfigFile ; then
            rm "$ConfigFile"
        fi
        rm "$Basename.aux" "$Basename.log" 
        case "$OutputFormat" in
            dvips)
                rm "$Basename.dvi" "$Basename.toc" "texput.log"
                ;;
            pdftex)
                rm "$Basename.out" "$Basename.toc"
                ;;
            tex4ht)
                rm \
                    "$Basename.css" "$Basename.dvi" \
                    "$Basename.idv" "$Basename.lg" "$Basename.otc" \
                    "$Basename.toc" "$Basename.xref" \
                    "tex4ht.tmp"
                remove_symlink_or_copy "$InputFile" "${Basename}.tex"
                ;;
            *)
                error_echo "Error: unsupported output format \"$OutputFormat\""
                exit 1
                ;;
        esac
    
        if $IsPrepareImages ; then
            for Path in $InputDirectory/*.tif $InputDirectory/*.tiff $InputDirectory/*.jpg $InputDirectory/*.jpeg $InputDirectory/*.png
            do
                File=`basename "$Path"`
                if $IsConvertImagesToEPS ; then
                    rm "$File.eps"
                fi
            done
        fi
    fi
    
    #--------------------------------------------------------------------------
    # remove output files:
    
    if $IsRemoveOutputFiles ; then
        case "$OutputFormat" in
            dvips)
                rm "$Basename.ps" ;;
            pdftex)
                rm "$Basename.pdf" ;;
            tex4ht)
                rm "$Basename.html" ;;
            *)
                error_echo "Error: unsupported output format \"$OutputFormat\""
                exit 1
                ;;
        esac
    
        if $IsPrepareImages ; then
            for Path in $InputDirectory/*.tif $InputDirectory/*.tiff $InputDirectory/*.jpg $InputDirectory/*.jpeg $InputDirectory/*.png
            do
                File=`basename "$Path"`
                if $IsCreateImageLinks ; then
                    remove_symlink_or_copy "$Path" "$File"
                fi
            done
        fi
    
        if $IsPrepareImages ; then
            if $IsConvertPngToGif ; then
                for Path in $InputDirectory/*.png
                do
                    File=`basename "$Path"`
                    rm "$File.gif"
                done
            fi
        fi

        if $IsGotoTemporaryDir ; then
            rmdir "$TemporaryDirectory"
        fi
    fi
    
    set -e

}

#--------------------------------------------------------------------------

trap tempfile_remove_handler EXIT

#--------------------------------------------------------------------------
# change to temporary directory (if desired)

if $IsGotoTemporaryDir ; then
    InputFile="${ArgumentArray[0]}"
    # make input file name an absolute path: if $InputFile doesn't start
    # with a slash (/), it should be a relative path - the current working
    # directory will be added (this constructed path should be interpreted
    # correctly even if $InputFile started with e.g. '../')
    if [ `echo "$InputFile" | grep -c '^/'` -eq "0" ]
    then
        InputFile=`pwd`/"$InputFile"
    fi
    mkdir --parents "$TemporaryDirectory"
    cd "$TemporaryDirectory"
else
    InputFile="${ArgumentArray[0]}"
fi

InputDirectory=`dirname "$InputFile"`
Basename=`basename "$InputFile" .tex`

#--------------------------------------------------------------------------
# prepare images
# - convert images from e.g. JPEG, PNG, TIFF to EPS for PostScript 
#   output
# - or create symlinks to image files in input directory - (may be 
#   required for 'tex4ht')

if $IsPrepareImages ; then if $IsGenerateFiles
then

    # TIFF files
    for Path in $InputDirectory/*.tif $InputDirectory/*.tiff
    do
        File=`basename "$Path"`
        if $IsConvertImagesToEPS ; then
            if [ "$TiffConversion" = "jpeg2ps" ] ; then
                # HACK if tiff2ps doesn't write compressed TIFFs
                echo "convert \"$Path\" \"jpeg:$File.jpg\""
                convert "$Path" "jpeg:$File.jpg"
                # alternative to 'convert': use 'nconvert'
                # nconvert -in tiff -out jpeg -o "$File.jpg" "$Path"
                jpeg2ps -o "$File.eps" "$File.jpg"
                rm "$File.jpg"

            elif [ "$TiffConversion" = "convert" ] ; then
                echo "TIFF->EPS: convert -compress zip \"$Path\" \"eps2:$File.eps\""
                convert -compress zip "$Path" "eps2:$File.eps"

            elif [ "$TiffConversion" = "bmeps" ] ; then
                echo "TIFF->EPS: cat \"$Path\" | bmeps -p3 -c -e8f -ttiff >\"$File.eps\""
                cat "$Path" | bmeps -p3 -c -e8f -ttiff >"$File.eps"

            elif [ "$TiffConversion" = "tiff2ps" ] ; then
                echo "TIFF->EPS: tiff2ps  -2 -e -s \"$Path\" >\"$File.eps\""
                tiff2ps -2 -e -s "$Path" >"$File.eps"

            fi
        elif $IsCreateImageLinks ; then
            symlink_or_copy "$Path" "$File"
        fi
    done

    # PNG files
    for Path in $InputDirectory/*.png
    do  

        File=`basename "$Path"`

        if $IsConvertImagesToEPS ; then

            if [ "$PngConversion" = "jpeg2ps" ] ; then
                # HACK if ImageMagick's convert is broken:
                echo "convert \"$Path\" \"jpeg:$File.jpg\""
                convert "$Path" "jpeg:$File.jpg"
                # alternative to 'convert': use 'nconvert'
                # nconvert -in png -out jpeg -o "$File.jpg" "$Path"
                jpeg2ps -o "$File.eps" "$File.jpg"
                rm "$File.jpg"

            elif [ "$PngConversion" = "convert" ] ; then
                echo "PNG->EPS: convert -compress zip \"$Path\" \"eps2:$File.eps\""
                convert -compress zip "$Path" "eps2:$File.eps"

            elif [ "$PngConversion" = "bmeps" ] ; then
                echo "PNG->EPS: cat \"$Path\" | bmeps -p3 -c -e8f -tpng >\"$File.eps\""
                cat "$Path" | bmeps -p3 -c -e8f -tpng >"$File.eps"

            else
                error_echo "Feature not implemented for PNG-conversion \"$PngConversion\""
                exit 1
            fi

        elif $IsCreateImageLinks ; then
            symlink_or_copy "$Path" "$File"
        fi

        # some (very) old browsers do not support PNG images
        # so convert PNGs to GIF if that is desired
        if $IsConvertPngToGif ; then
            echo "PNG->GIF: convert \"$Path\" \"gif:$File.gif\""
            convert "$Path" "gif:$File.gif"
        fi
    done

    # JPEG files
    for Path in $InputDirectory/*.jpg $InputDirectory/*.jpeg
    do  
        File=`basename "$Path"`
        if $IsConvertImagesToEPS ; then
            jpeg2ps -o "$File.eps" "$Path"

        elif $IsCreateImageLinks ; then
            symlink_or_copy "$Path" "$File"
        fi

    done
fi ; fi

#--------------------------------------------------------------------------
# create "config.tex" file

if $IsCreateConfigFile ; then 
    echo -n "" >"$ConfigFile"
    echo -e "\\def\\OutputFormat{$OutputFormat}\n" >>"$ConfigFile"
    echo -e "\\def\\BaseDirectory{$InputDirectory}\n" >>"$ConfigFile"
    echo -e "\\def\\IsConvertPngToGif{$IsConvertPngToGif}\n" >>"$ConfigFile"
    if [ "$OutputFormat" = "tex4ht" ] ; then
        echo -e "\\usepackage[html,3.2]{tex4ht}\n" >>"$ConfigFile"
    fi
fi

#--------------------------------------------------------------------------
# compile LaTeX source

# add current directory to TEXINPUTS variable:
# - the current directory is usually contained in `kpsepath tex`
#   already
# - pdflatex: setting TEXINPUTS seems to cause some systems to be unable
#   to find 'pdftex.cfg' (see Note (2.2))
add_texinput_path "$InputDirectory"
# DEBUG echo "$TEXINPUTS"

if $IsUseEtex ; then
    LatexProgram='elatex'
    PdfLatexProgram='pdfelatex'
else
    LatexProgram='latex'
    PdfLatexProgram='pdflatex'
fi

if $IsGenerateFiles ; then 
    case "$OutputFormat" in
        dvips)
            "$LatexProgram" "$InputFile"
            if $IsSecondRun ; then
                "$LatexProgram" "$InputFile"
            fi
            dvips -o "$Basename.ps" "$Basename.dvi"
            ;;
        pdftex)
            "$PdfLatexProgram" "$InputFile"
            if $IsSecondRun ; then
                "$PdfLatexProgram" "$InputFile"
            fi
            ;;
        tex4ht)
            # must copy (or symlink) the TeX file for 'tex4ht':
            symlink_or_copy "$InputFile" "${Basename}.tex"
            ht "$LatexProgram" "${Basename}"

            # filter output of tex4ht:
            ModifyFiles -v tex4ht-post-process "${Basename}.html"

            # run program to clean up HTML, emit warnings, and 
            # indent HTML code
            if $IsCallTidy ; then
                ModifyFiles -v "tidy -q -i -ascii; echo -n ''" "${Basename}.html"
            fi
            ;;
        *)
            error_echo "Error: unsupported output format \"$OutputFormat\""
            exit 1
            ;;
    esac
fi

#--------------------------------------------------------------------------
# open viewer

if $IsOpenViewer ; then

    case "$OutputFormat" in
        dvips)
            $ViewProgram "$Basename.ps"
            ;;
        pdftex)
            $ViewProgram "$Basename.pdf"
            ;;
        tex4ht)
            $ViewProgram "$Basename.html"
            ;;
        *)
            error_echo "Error: unsupported output format \"$OutputFormat\""
            exit 1
            ;;
    esac
fi

#--------------------------------------------------------------------------
# clean up of temporary and output files is done automatically 
# by the 'EXIT' handler as set up above

#--------------------------------------------------------------------------
