#! /bin/sh

usage() {
    cat <<EOF >&2
$0 [options] file ...
    -T title
    -H header
    -F footer
    -s style
    -e encoding
    -L language
    -l lines_per_page
    -p output_prefix
EOF
         "file ..." >&2
    exit 2
}

#
# parse arg
#

header=""
footer=""
style=""
title=""
encoding="US-ASCII"
language="en"
prefix=""
lines="21"
orig_args="$0 $*"

args=`getopt H:F:T:s:e:L:l:p: $*`
[ $? -ne 0 ] && usage

set -- $args
while [ $# -gt 0 ]; do
    case "$1" in
        -H)
            header="$2"; shift
            ;;
        -F)
            footer="$2"; shift
            ;;
        -T)
            title="$2:"; shift
            ;;
        -s)
            style="$2"; shift
            ;;
        -e)
            encoding="$2"; shift
            ;;
        -L)
            language="$2"; shift
            ;;
        -l)
            lines="%2"; shift
            ;;
        -p)
            prefix="$2/"; shift
            ;;
        --)
            shift; break
            ;;
    esac
    shift
done

[ $# -eq 0 ] && usage


#
# put
#

page=1
while [ $# -gt 0 ]; do
    file=`printf "%s%03d.html" "$prefix" $page`
    exec > $file
    echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"'
    echo ' "http://www.w3.org/TR/REC-html40/strict.dtd">'
    printf '<html lang="%s">\n<head>\n' "$language"
    printf \
      '<meta http-equiv="Content-Type" content="text/html; charset=%s" />\n' \
      "$encoding"
    [ x$style != x ] && printf '<link rel="stylesheet" href="%s" />\n' "$style"
    printf '<!-- %s -->\n' "$orig_args"
    printf '<title>%s page%3d</title>\n' "$title" "$page"
    printf '</head>\n<body>\n'
    [ x$header != x ] && cat $header
    printf '<div class="bar">\n'
    [ $page != 1 ] && \
        printf '<span class="prev"><a href="%03d.html">&lt;&lt;</a></span>' \
            $(($page - 1))
    [ $# != 1 ] && \
        printf '<span class="next"><a href="%03d.html">&gt;&gt;</a></span>' \
            $(($page + 1))
    echo
    echo '</div>'
    echo '<pre>'
    case "$encoding" in
        "EUC-JP")
            head -$lines $1 | \
                LANG=C perl -p \
                    -e 's@([\0-\x7F])\010.@<b>\1</b>@g;
                        s@([\x80-\xFF]{2})\010..@<b>\1</b>@g'
            ;;
        *)
            head -$lines $1
            ;;
    esac
    echo '</pre>'
    [ x$footer != x ] && cat $footer
    echo '</body>'
    echo '</html>'
    shift; page=$(($page + 1))
done
