#!/bin/sh

VERSION="0.5.1"

check_init()
{

# you may define latex2man from the system
# LATEX2MAN="${LATEX2MAN:-latex2man}"

TEXT_BROWSER="${TEXT_BROWSER:-links}"
PDFLATEX="${PDFLATEX:-pdflatex}"
HTLATEX="${HTLATEX:-htlatex}"

# we rely on directory structure:
# PREFIX/bin/devdoc
# PREFIX/share/devdoc/<filez>

# analogue for ../../
tmp_dir="$(local_which $0)"
tmp_dir="${tmp_dir%/*}"
tmp_dir="${tmp_dir%/*}"

base_dir="$(cd $tmp_dir ; pwd -P )"
bin_DIR="${base_dir}/bin"
render_DIR="${base_dir}/share/devdoc"

RENDER_DIR="${RENDER_DIR:-"${render_DIR}"}"
CSS_LOCAL="${CSS_LOCAL:-${RENDER_DIR}/texdoc.css}"
TUNE_GENERATOR="${TUNE_GENERATOR:-"${RENDER_DIR}/man_latex.pl"}"
STY_LATEX2MAN="${STY_LATEX2MAN:-"${RENDER_DIR}/latex2man.sty"}"
STY_LOCAL="${STY_LOCAL:-"${RENDER_DIR}/devdoc.sty"}"
TARGETS="html man"

base_OUTPUT="$(pwd)/var"

# maximum level of nested subdirectories to search documentation for.
DOCDEPTH="10"
# theme for non-standalone html files
HTML_TEMPLATE="default"
# entire dir with templates for non-standalone html files
TEMPLATE_DIR="${RENDER_DIR}/${HTML_TEMPLATE}-template"
# additional params to latex2man, with -C option
L2M_OPTIONS=
# base directory of doc sources
SUBDIR=

    if test -n "${LATEX2MAN}" -a ! -x "$(local_which ${LATEX2MAN})" ; then
        printf "%s\n" "\
Variable LATEX2MAN is set up, but no working latex2man was found.

The inner version of latex2man may be used,
no need to set up LATEX2MAN variable with it.
" 1>&2
        exit 1
    fi

    if test -z "${LATEX2MAN}" ; then
        LATEX2MAN=${bin_DIR}/devdoc-latex2man
    fi

    if test ! -x "${LATEX2MAN}" ; then
        printf "%s\n" "\
Inner executable file latex2man was not found.
It is expected to be in the same binary directory as devdoc itself:
${LATEX2MAN}

Check your installation of devdoc.
" 1>&2
        exit 2
    fi

}

local_which()
{
    arg="$1"

    if test -x "${arg}" ; then
        printf "%s\n" "${arg}"
        return 0
    fi

    IFS=:
    for dir in ${PATH} ; do
        if test -x "${dir}/${arg}" ; then
            printf "%s\n" "${dir}/${arg}"
            return 0
        fi
    done
    return 1
}


check_prepare()
{
    if test -z "${base_OUTPUT}" ; then
        error "No correct output directory was set"
    fi
    html_OUTPUT="${base_OUTPUT}/html"
    man_OUTPUT="${base_OUTPUT}/man"
    pdf_OUTPUT="${base_OUTPUT}/pdf"
    txt_OUTPUT="${base_OUTPUT}/txt"
    odt_OUTPUT="${base_OUTPUT}/odt"
    tex_OUTPUT="${base_OUTPUT}/tex"

    base_LOG="${base_OUTPUT}/log"
    html_LOG="${base_LOG}/html"
    man_LOG="${base_LOG}/man"
    pdf_LOG="${base_LOG}/pdf"
    txt_LOG="${base_LOG}/txt"
    odt_LOG="${base_LOG}/odt"
    tex_LOG="${base_LOG}/tex"

    case " ${TARGETS} " in
        *' html '*)
            if test ! -d "${TEMPLATE_DIR}" ; then
                printf "%s\n" "\
Template files for html generation are not found. Expected to be here:
${TEMPLATE_DIR}

HTML_TEMPLATE can assign another name for html templates.
Preinstalled templates are located in ${RENDER_DIR}/<name>-template.
" 1>&2
                exit 3
            fi
            mkdir -p ${html_OUTPUT}
            cp -pRf ${TEMPLATE_DIR}/* ${html_OUTPUT}/
        ;;
    esac

    if test -n "${SUBDIR}" ; then
        if test ! -d "${SUBDIR}" ; then
                printf "%s\n" "\
Base directory for source documentation is set up (with -b):
${SUBDIR}
but directory is incorrect. Check it.
" 1>&2
                exit 4
        fi
    fi

    depth_error=
    if ! test "${DOCDEPTH}" -eq "${DOCDEPTH}" 2> /dev/null ; then
        depth_error=1
    fi
    if test "${DOCDEPTH}" -gt "1000" 2> /dev/null ; then
        depth_error=1
    fi
    if test "${DOCDEPTH}" -lt "0" 2> /dev/null ; then
        depth_error=1
    fi
    if test -n "${depth_error}" ; then
        printf "%s\n" "\
Incorrect value of -D option: must be integer number between 0 and 1000
" 1>&2
                exit 5
    fi
}

print_version()
{
    echo "${VERSION}"
    exit 0
}

print_help()
{
    echo "\
Usage:
devdoc [options] [--] DIRLIST ... FILELIST
devdoc --help | --version

Render to html or man pages source .tex files, written in subset of LaTeX, supported by latex2man.
"
    exit 0
}

error()
{
    echo "Error:" 1>&2
    echo "$@" 1>&2
    exit 1
}

back_path()
{
    subpath="${1}"

    found_back_path=
    backup_IFS="${IFS}"
    IFS=/
    for first_element in ${subpath} ; do
        if test -z "${first_element}" ; then
            continue
        fi
        if test "${first_element}" = '.' ; then
            continue
        fi
        found_back_path="${found_back_path}../"
    done
    IFS="${backup_IFS}"

    printf "%s\n" "${found_back_path}"
}

html_web_body()
{
    # strip off headers to embed the generated code to a containing web page
    source_file="$1"

    sed \
        -e '/versionhead/s/^/\n/' \
        -e '/Authors/s/^/\n/' \
        -e '/Table of Contents/s/^/\n/' \
        "${source_file}" | \
    sed \
        -e '1,/versionhead/d' \
        -e '/Authors/,$d' \
        -e '/Table of Contents/,$d' | \
    sed \
        -e '1i <div class="article">' \
        -e '$a </div>'
}

html_top()
{
    title_text="${1}"
    static_path="${2}"

    # add relative paths of needed depth to links in header (.css)
    # and add title
    sed \
        -e "s%<title>.*</title>%<title>${title_text}</title>%" \
        -e "s% href=\"_static/% href=\"${static_path}_static/%g" \
        -e "s% data=\"_static/% data=\"${static_path}_static/%g" \
        "${TEMPLATE_DIR}"/_static/up.template
}

html_bottom()
{
    static_path="${1}"

    # add bottom template
    sed \
        -e "s% href=\"_static/% href=\"${static_path}_static/%g" \
        -e "s% data=\"_static/% data=\"${static_path}_static/%g" \
        "${TEMPLATE_DIR}"/_static/down.template
}

html_navigation_bottom()
{
    link="${1}"
    text="${2}"

    sed \
        -e "s% class=\"prev\" href=\".*\"% class=\"prev\" href=\"${link}\"%g" \
        -e "s%<p [ ]*class=\"prev\">[ ]*Previous[ ]*</p>%<p class=\"prev\">${text}</p>%g" \
        -e "s%<a [ ]*href=\".*\">[ ]*Home[ ]*</a>%<a href=\"${home_LINK}\">Home</a>%g" \
        "${TEMPLATE_DIR}"/_static/down.navig.template
}

html_navigation_top()
{
    link="${1}"
    text="${2}"

    sed \
        -e "s% class=\"prev\" href=\".*\"% class=\"prev\" href=\"${link}\"%g" \
        -e "s%<p [ ]*class=\"prev\">[ ]*Previous[ ]*</p>%<p class=\"prev\">${text}</p>%g" \
        -e "s%<a [ ]*href=\".*\">[ ]*Home[ ]*</a>%<a href=\"${home_LINK}\">Home</a>%g" \
        "${TEMPLATE_DIR}"/_static/up.navig.template
}

html_navigation_init_next()
{
    link="${1}"
    editfile="${2}"
    text="${3}"

    sed \
        -e "s% class=\"next\" href=\".*\"% class=\"next\" href=\"${link}\"%g" \
        -e "s%<p [ ]*class=\"next\">[ ]*Next[ ]*</p>%<p class=\"next\">${text}</p>%g" \
        "${editfile}" > "${editfile}.tmp"
    mv "${editfile}.tmp" "${editfile}"
}

html_toc_top()
{
    cat "${TEMPLATE_DIR}"/_static/up.toc.template
}

html_toc_bottom()
{
    cat "${TEMPLATE_DIR}"/_static/down.toc.template
}

html_save_toc()
{
    targetfile="${1}"
    content="${2}"

    if test -n "${targetfile}" -a -n "${content}" ; then
        # troubles with sed insertion of multi-line block
        content="$(
( html_toc_top ; printf "%s\n" "${content}" ; html_toc_bottom ) | tr '\n' '|' | sed -e 's/|/\\n/g'
)"

        sed -e "\%<!-- TOC -->%a \
${content}" "${targetfile}" > "${targetfile}.middle"
        mv "${targetfile}.middle" "${targetfile}"
    fi
}

html_header_num()
{
    num2="$1"
    num4="$2"

    num2_part=
    num4_part=
    if test "${num2}" -gt 0 ; then
        num2_part="${num2}."
    fi
    if test "${num4}" -gt 0 ; then
        num4_part="${num4}."
    fi

    printf "%s" "<span class=\"headernum\">${num2_part}${num4_part} </span>"
}

html_toc_entry()
{
    local link="$1"
    local text="$2"
    local level="$3"
    local numlevel_array="$4"

    local style=
    case "${level}" in
        '2'|'4')
            style="toclevel${level}"
        ;;
    esac

    printf "%s\n" "    <li class=\"${style}\">$(html_header_num ${numlevel_array})<a href=\"${link}\">${text}</a></li>"
}

html_insert_header_number()
{
    parsing_line="$1"
    nums="$2"

    insertion="$(html_header_num ${nums})"
    printf "%s\n" "${parsing_line}" | sed -e "s%<h[0-9][^>]*>%&${insertion}%"
}

render_html_web()
{
    input_file="$1"
    name_to_generate="$2"
    output_subdir="$3"

    mkdir -p ${html_LOG}/${output_subdir} ${html_OUTPUT}/${output_subdir}
    if test -n "${L2M_OPTIONS}" ; then
        cmd_options="-C${L2M_OPTIONS}"
    fi

    error_file="${html_LOG}/${output_subdir}/${name_to_generate}-embed-stderr.log"
    source_to_embed="${html_OUTPUT}/${output_subdir}/${name_to_generate}-embed.html"
    target_file="${html_OUTPUT}/${output_subdir}/${name_to_generate}.html"
    rm "${error_file}" 2>/dev/null
    # whether we should split single html into several linked pages
    multi_html="$(sed \
        -n -e '/%% AUTOSPLIT %%/p' \
            ${input_file}
            )"

    ${LATEX2MAN} ${cmd_options} -t${TUNE_GENERATOR} -H -c${CSS_LOCAL} \
        "${input_file}" \
        "${source_to_embed}" \
        2> "${error_file}"

    if test -f "${error_file}" ; then
        cat "${error_file}" 1>&2
    fi
    if test ! -f "${source_to_embed}" ; then
        printf "%s\n" "${source_to_embed} was not generated." 1>&2
        return 1
    fi

    # extract title
    namet="$(sed \
        -n -e '/<title>/p' \
            ${source_to_embed}
            )"
    namet=${namet#*<title>}
    namet=${namet%</title>*}
    nested_path="$(back_path ${output_subdir})"
    html_top "${namet}" "${nested_path}" > "${target_file}"

    if test -n "${multi_html}" ; then
        # we should parse entire page and split it to multiple output files

        current_level="0"
        previous_level="0"
        previous_target=
        current_target="${target_file}"
        previous_link=
        current_link="${name_to_generate}.html"
        home_LINK="${name_to_generate}.html"
        current_text=
        previous_text=
        # name of upper level section
        upper_current_text=
        upper_previous_text=
        # end-to-end numeration of headers
        level2_num=0
        level4_num=0

        # TOC block
        top_toc_file="${html_OUTPUT}/${output_subdir}/${name_to_generate}.html"
        top_toc_content_tmp="${html_OUTPUT}/${output_subdir}/${name_to_generate}.html.toctmp"
        : > "${top_toc_content_tmp}"
        # no arrays, so explicit variables for each of possible levels for TOC
        # only one level is actual now: level2 for h2 headers
        # levels h1, h2, h3 are possible theoretically
        level2_toc_file=
        level2_toc_content=

        html_web_body "${source_to_embed}" | while IFS='' read -r parsing_line ; do
            case "${parsing_line}" in
                # template for '<h2 ', '<h2>', '<h3 ', '<h3>' and so on
                "<h"[1-4]" "*|"<h"[1-4]">"*)
                    ## transfer to new target file

                    # detect level
                    previous_level="${current_level}"
                    level_line="${parsing_line#<h[1-4]}"
                    level_line="${parsing_line%${level_line}}"
                    current_level="${level_line#<h}"

                    ## we need to close the current file before switching to the next one
                    # if new level is more then old one, add table of contents
                    level2_toc_flag=
                    if test "${current_level}" -gt "${previous_level}" ; then
                        printf "%s\n\n" "<!-- TOC -->" >> "${current_target}"
                        case "${previous_level}" in
                            '2')
                                level2_toc_flag=1
                            ;;
                        esac
                    fi
                    # close mandatory <div class="sectiontext"
                    if test ! "${current_level}" = '2' ; then
                        # do not emit this before new h2, as that div had been present in original single-html
                        printf "%s\n" "</div>" >> "${current_target}"
                    fi
                    # add bottom navigation template
                    html_navigation_bottom "${previous_link}" "${upper_previous_text}${previous_text}" >> "${current_target}"
                    # add generic bottom template
                    html_bottom "${nested_path}" >> "${current_target}"
                    # print finished file name
                    printf "%s\n" "${current_target}"

                    upper_previous_text="${upper_current_text}"
                    case "${current_level}" in
                        '2')
                            upper_current_text=
                            level2_num=$((level2_num + 1))
                            level4_num=0
                        ;;
                        '4')
                            if test -n "${level2_toc_flag}" ; then
                                upper_current_text="${current_text}. "
                            fi
                            level4_num=$((level4_num + 1))
                        ;;
                    esac

                    # detect text for next target
                    previous_text="${current_text}"
                    text_line="${parsing_line%%</*}"
                    current_text="${text_line##*>}"

                    # new file to write
                    current_text_stub="$(printf "%s\n" "${current_text}" | tr '[:upper:]' '[:lower:]' | tr ' ' '_')"
                    previous_target="${current_target}"
                    current_target="${html_OUTPUT}/${output_subdir}/${name_to_generate}-${current_text_stub}.html"
                    # links inside markup
                    previous_link="${current_link}"
                    current_link="${name_to_generate}-${current_text_stub}.html"

                    # edit 'next' links in previous file
                    html_navigation_init_next "${current_link}" "${previous_target}" "${upper_current_text}${current_text}"
                    # add generic up template with new page name
                    html_top "${current_text}" "${nested_path}" > "${current_target}"
                    # add up navigation template
                    html_navigation_top "${previous_link}" "${upper_previous_text}${previous_text}" >> "${current_target}"

                    # print the original line with header and number
                    html_insert_header_number "${parsing_line}" "${level2_num} ${level4_num}" >> "${current_target}"
                    # need local sectiontext tag for each separate page and subheader
                    if test "${current_level}" != '2' ; then
                        printf "%s\n" '<div class="sectiontext">' >> "${current_target}"
                    fi

                    if test -n "${level2_toc_flag}" ; then
                        # new toc appeared
                        level2_toc_file="${previous_target}"
                        level2_toc_flag=
                    fi
                    # add up to the actual TOCs
                    case "${current_level}" in
                        '2')
                            #chapter ended. Need to write down the previous toc, if present
                            html_save_toc "${level2_toc_file}" "${level2_toc_content}"
                            level2_toc_content=
                            level2_toc_file=

                            html_toc_entry "${current_link}" "${current_text}" '2' "${level2_num} ${level4_num}" >> "${top_toc_content_tmp}"
                        ;;
                        '4')
                            if test -n "${level2_toc_file}" ; then
                                level2_toc_content="${level2_toc_content}
$(html_toc_entry "${current_link}" "${current_text}" '4' "${level2_num} ${level4_num}" )"
                            fi
                            # always add to top level toc
                            html_toc_entry "${current_link}" "${current_text}" '4' "${level2_num} ${level4_num}" >> "${top_toc_content_tmp}"
                        ;;
                    esac
                ;;
                *)
                    printf "%s\n" "${parsing_line}" >> "${current_target}"
                ;;
            esac
        done

        # close last page
        if test -z "${level2_toc_file}" -a -z "${top_toc_file}" ; then
            html_navigation_bottom "${previous_link}" >> "${current_target}"
            html_bottom "${nested_path}" >> "${current_target}"
        fi
        printf "%s\n" "${current_target}"
        # write down last inner TOC
        html_save_toc "${level2_toc_file}" "${level2_toc_content}"
        # write down top level TOC
        html_save_toc "${top_toc_file}" "$( cat "${top_toc_content_tmp}" )"
        rm "${top_toc_content_tmp}"

    else
        # generate single page

        html_web_body "${source_to_embed}" \
            >> "${target_file}"
        html_bottom "${nested_path}" >> "${target_file}"

        printf "%s\n" "${target_file}"
    fi

    rm -f "${source_to_embed}"
}

render_html_standalone()
{
    input_file="$1"
    name_to_generate="$2"
    output_subdir="$3"

    mkdir -p ${html_LOG}/${output_subdir} ${html_OUTPUT}/${output_subdir}

    error_file="${html_LOG}/${output_subdir}/${name_to_generate}-standalone-stderr.log"
    rm "${error_file}" 2>/dev/null

    ${LATEX2MAN} -t${TUNE_GENERATOR} -H -c${CSS_LOCAL} \
        "${input_file}" \
        "${html_OUTPUT}/${output_subdir}/${name_to_generate}-middle.html" \
        2> "${error_file}"

    if test -f "${error_file}" ; then
        cat "${error_file}" 1>&2
    fi

    sed \
        -e "s/<head>/\n<head>\n/" \
        -e '\@text/css@d' \
        "${html_OUTPUT}/${output_subdir}/${name_to_generate}-middle.html" | \
    sed \
        -e "\@<head>@a\
<meta content='text/html; charset=utf-8' http-equiv='Content-Type' />\n\
<style type='text/css'>\n\
$(cat ${CSS_LOCAL} | sed -e 's/$/\\/' ) \n\
</style>\n" \
         > "${html_OUTPUT}/${output_subdir}/${name_to_generate}.html"
    rm "${html_OUTPUT}/${output_subdir}/${name_to_generate}-middle.html"

    printf "%s\n" "${html_OUTPUT}/${output_subdir}/${name_to_generate}.html"
}

render_txt()
{
    input_file="$1"
    name_to_generate="$2"
    output_subdir="$3"

    if test ! -x "$(local_which ${TEXT_BROWSER})" ; then
        printf "%s\n" "\
Executable file links is unavailable.
You can point to it or another text browser, supporting option -dump,
with TEXT_BROWSER shell variable.
" 1>&2
        return 1
    fi

    if test ! -f "${html_OUTPUT}/${output_subdir}/${name_to_generate}.html" ; then
        printf "%s\n" "\
Plain text rendering requires available html format here:
${html_OUTPUT}/${output_subdir}/${name_to_generate}.html

Build html variant before the text one.
" 1>&2
        return 2
    fi

    mkdir -p ${txt_LOG}/${output_subdir} ${txt_OUTPUT}/${output_subdir}


    ${TEXT_BROWSER} -dump "${html_OUTPUT}/${output_subdir}/${name_to_generate}.html" \
        > "${txt_OUTPUT}/${output_subdir}/${name_to_generate}.txt"

    printf "%s\n" "${txt_OUTPUT}/${output_subdir}/${name_to_generate}.txt"
}

render_man()
{
    input_file="$1"
    name_to_generate="$2"
    output_subdir="$3"

    chapter="${name_to_generate##*.}"
    if test -n "${chapter}" ; then
        mansubdir="/man${chapter}"
    fi

    mkdir -p ${man_LOG}/${output_subdir} ${man_OUTPUT}${mansubdir}

    error_file="${man_LOG}/${output_subdir}/${name_to_generate}-man-stderr.log"
    rm "${error_file}" 2>/dev/null

    ${LATEX2MAN} -t${TUNE_GENERATOR} \
        "${input_file}" \
        ${man_OUTPUT}${mansubdir}/${name_to_generate} \
        2> "${error_file}"

    if test -f "${error_file}" ; then
        cat "${error_file}" 1>&2
    fi

    printf "%s\n" "${man_OUTPUT}${mansubdir}/${name_to_generate}"
}

render_pdf()
{
    input_file="$1"
    name_to_generate="$2"
    output_subdir="$3"

    if test ! -x "$(local_which ${PDFLATEX})" ; then
        printf "%s\n" "\
Executable file pdflatex is unavailable.
You can point to it or another renderer from .tex to .pdf
with PDFLATEX shell variable.
" 1>&2
        return 1
    fi

    mkdir -p ${pdf_LOG}/${output_subdir} ${pdf_OUTPUT}/${output_subdir}

    (
        cd ${pdf_LOG}/${output_subdir}/

        cp -f "${STY_LOCAL}" ./devdoc.sty

        error_file="${name_to_generate}-latex2latex-stderr.log"
        log_file="${name_to_generate}-latex2latex-stdout.log"
        rm "${error_file}" "${log_file}" 2>/dev/null

        # remove conditional parts for non-latex or not of needed case
        ${LATEX2MAN} -t${TUNE_GENERATOR} -L \
            "${input_file}" \
            "${name_to_generate}.tex" \
            > "${log_file}" \
            2> "${error_file}"

        if test -f "${error_file}" ; then
            cat "${error_file}" 1>&2
        fi

        # hack to prevent handling '--' as long dash by Latex
        # nested Latex macroses are not allowed, so \Opt{-{}-help} does not work
        # symbols -\,- in source file are rendered wrong for non-latex formats
        sed \
            -e 's/--/-{}-/g' \
            "${name_to_generate}.tex" \
            > "tmp.${name_to_generate}.tex"
        mv "tmp.${name_to_generate}.tex" "${name_to_generate}.tex"

        error_file="${name_to_generate}-latex2pdf-stderr.log"
        log_file="${name_to_generate}-latex2pdf-stdout.log"
        rm "${error_file}" "${log_file}" 2>/dev/null

        ${PDFLATEX} \
            "${name_to_generate}.tex" \
            > "${log_file}" \
            2> "${error_file}"

        if test -f "${error_file}" ; then
            cat "${error_file}" 1>&2
        fi

        if test -f "${name_to_generate}.pdf" ; then
            mv ${name_to_generate}.pdf ${pdf_OUTPUT}/${output_subdir}/
            printf "%s\n" "${pdf_OUTPUT}/${output_subdir}/${name_to_generate}.pdf"
        fi
    )
}

render_odt()
{
    input_file="$1"
    name_to_generate="$2"
    output_subdir="$3"

    if test ! -x "$(local_which ${HTLATEX})" ; then
        printf "%s\n" "\
Executable file htlatex is unavailable.
You can point to it or another renderer from .tex to .pdf
with HTLATEX shell variable.
" 1>&2
        return 1
    fi

    mkdir -p ${odt_LOG}/${output_subdir} ${odt_OUTPUT}/${output_subdir}

    (
        cd ${odt_LOG}/${output_subdir}/

        cp -f "${STY_LOCAL}" ./devdoc.sty

        error_file="${name_to_generate}-latex2latex-stderr.log"
        log_file="${name_to_generate}-latex2latex-stdout.log"
        rm "${error_file}" "${log_file}" 2>/dev/null

        # remove conditional parts for non-latex or not of needed case
        ${LATEX2MAN} -t${TUNE_GENERATOR} -L \
            "${input_file}" \
            "${name_to_generate}.tex" \
            > "${log_file}" \
            2> "${error_file}"

        if test -f "${error_file}" ; then
            cat "${error_file}" 1>&2
        fi

        # hack to prevent handling '--' as long dash by Latex
        # nested Latex macroses are not allowed, so \Opt{-{}-help} does not work
        # symbols -\,- in source file are rendered wrong for non-latex formats
        sed \
            -e 's/--/-{}-/g' \
            "${name_to_generate}.tex" \
            > "tmp.${name_to_generate}.tex"
        mv "tmp.${name_to_generate}.tex" "${name_to_generate}.tex"

        error_file="${name_to_generate}-latex2odt-stderr.log"
        log_file="${name_to_generate}-latex2odt-stdout.log"
        rm "${error_file}" "${log_file}" 2>/dev/null

        ${HTLATEX} \
            "${name_to_generate}.tex" \
            "xhtml,ooffice" "ooffice/! -cmozhtf" "-coo -cvalidate" \
            > "${log_file}" \
            2> "${error_file}"

        if test -f "${error_file}" ; then
            cat "${error_file}" 1>&2
        fi

        if test -f "${name_to_generate}.odt" ; then
            mv ${name_to_generate}.odt ${odt_OUTPUT}/${output_subdir}/
            printf "%s\n" "${odt_OUTPUT}/${output_subdir}/${name_to_generate}.odt"
        fi
    )
}

render_texhtml()
{
    input_file="$1"
    name_to_generate="$2"
    output_subdir="$3"

    if test ! -x "$(local_which ${HTLATEX})" ; then
        printf "%s\n" "\
Executable file htlatex is unavailable.
You can point to it or another renderer from .tex to .pdf
with HTLATEX shell variable.
" 1>&2
        return 1
    fi

    mkdir -p ${html_LOG}/${output_subdir} ${html_OUTPUT}/${output_subdir}

    (
        cd ${html_LOG}/${output_subdir}/

        cp -f "${STY_LOCAL}" ./devdoc.sty

        error_file="${name_to_generate}-latex2latex-stderr.log"
        log_file="${name_to_generate}-latex2latex-stdout.log"
        rm "${error_file}" "${log_file}" 2>/dev/null

        # remove conditional parts for non-latex or not of needed case
        ${LATEX2MAN} -t${TUNE_GENERATOR} -L \
            "${input_file}" \
            "${name_to_generate}.tex" \
            > "${log_file}" \
            2> "${error_file}"

        if test -f "${error_file}" ; then
            cat "${error_file}" 1>&2
        fi

        # hack to prevent handling '--' as long dash by Latex
        # nested Latex macroses are not allowed, so \Opt{-{}-help} does not work
        # symbols -\,- in source file are rendered wrong for non-latex formats
        sed \
            -e 's/--/-{}-/g' \
            "${name_to_generate}.tex" \
            > "tmp.${name_to_generate}.tex"
        mv "tmp.${name_to_generate}.tex" "${name_to_generate}.tex"

        error_file="${name_to_generate}-latex2html-stderr.log"
        log_file="${name_to_generate}-latex2html-stdout.log"
        rm "${error_file}" "${log_file}" 2>/dev/null

        ${HTLATEX} \
            "${name_to_generate}.tex" \
            > "${log_file}" \
            2> "${error_file}"

        if test -f "${error_file}" ; then
            cat "${error_file}" 1>&2
        fi

        if test -f "${name_to_generate}.html" ; then
            mv "${name_to_generate}.html" ${html_OUTPUT}/${output_subdir}/
            printf "%s\n" "${html_OUTPUT}/${output_subdir}/${name_to_generate}.html"
        fi
    )
}

process_file()
{
    input_file="$1"
    input_name="$( basename "${input_file}" )"
    output_subdir="$2"

    name_to_generate="${input_name%.*}"

    for single_target in ${TARGETS} ; do
        case ${single_target} in
            sinhtml)
                render_html_standalone "${input_file}" "${name_to_generate}" "${output_subdir}"
            ;;
            txt)
                render_txt "${input_file}" "${name_to_generate}" "${output_subdir}"
            ;;
            html)

                render_html_web "${input_file}" "${name_to_generate}" "${output_subdir}"
            ;;
            man)
                # for man pages explicitly include chapter_num in file name

                chapter_num="$(grep -e '\\begin{Name}' "${input_file}"  \
                    | head -1 | cut -d'{' -f3 | cut -d'}' -f1)"
                if test -n "${chapter_num}" ; then
                    chapter_num=".${chapter_num}"

                    #let's check whether filename already ends with man chapter
                    if test "${name_to_generate}" = "${name_to_generate%${chapter_num}}" ; then
                        name_to_generate="${name_to_generate}${chapter_num}"
                    fi
                fi

                render_man  "${input_file}" "${name_to_generate}" "${output_subdir}"
            ;;
            pdf)
                render_pdf  "${input_file}" "${name_to_generate}" "${output_subdir}"
            ;;
            odt)
                render_odt  "${input_file}" "${name_to_generate}" "${output_subdir}"
            ;;
            texhtml)
                render_texhtml  "${input_file}" "${name_to_generate}" "${output_subdir}"
            ;;
        esac
    done
}

get_subdir()
{
    target_path="$1"
    arg_path="$2"

    working_path=
    if test -n "${SUBDIR}" ; then
        working_path="${SUBDIR}"
    else
        working_path="${arg_path}"
    fi
    subdir="${target_path#${working_path}}"
    if test "${subdir}" != "${target_path}" ; then
        subdir="${subdir#/}"
    else
        subdir="."
    fi

    printf "%s\n" "${subdir}"
}

process_resource()
{
    while read arg <&0 ; do
        if test -f "${arg}" ; then
            path_arg="$(cd "$(dirname "${arg}")" && pwd -P)"
            resource_file="${path_arg}/$(basename "${arg}")"
            subdir="$(get_subdir "${path_arg}")"

            process_file "${resource_file}" "${subdir}"
        fi
        if test -d "${arg}" ; then
            path_arg="$(cd "${arg}" && pwd -P)"
            find ${path_arg} -maxdepth "${DOCDEPTH}" -type f -name "*.tex" | while read filename ; do
                path_file="$(dirname ${filename})"
                subdir="$(get_subdir "${path_file}" "${path_arg}" )"

                process_file "${filename}" "${subdir}"
            done
        fi
    done
}

# -------------------------- execution -----------------------------------------

check_init "${@}"

in_opt_cycle=1
input_args=

while test -n "$1" ; do
    arg="$1"
    shift

    if test -n "${in_opt_cycle}" ; then
        checked_arg="${arg#-}" || true
        if test "$checked_arg" != "${arg}" ; then
            case ${checked_arg} in
                t)
                    TEMPLATE_DIR="${1}"
                    shift || error "No argument for option -t"
                ;;
                o)
                    base_OUTPUT="${1}"
                    shift || error "No argument for option -o"
                ;;
                f)
                    TARGETS="$(echo "$1" | tr ',' ' ')"
                    shift || error "No argument for option -f"
                ;;
                b)
                    SUBDIR="$(cd "$1" ; pwd -P)" || nonfail
                    shift || error "No argument for option -b"
                ;;
                C)
                    L2M_OPTIONS="$1"
                    shift || error "No argument for option -C"
                ;;
                D)
                    DOCDEPTH="$1"
                    shift || error "No argument for option -D"
                ;;
                -version)
                    print_version
                ;;
                -help)
                    print_help
                ;;
                -)
                    in_opt_cycle=
                ;;
                *)
                    error "Unknown option ${arg}"
                ;;
            esac

            # if it was non-terminal option, do not add it to argument array
            continue
        fi
    fi

    # not option
    input_args="${input_args}
${arg}"

done

check_prepare "${@}"

printf "%s\n" "${input_args}" | process_resource

if [ ! -t 0 ] ; then
    while read resource <&0 ; do
        printf "%s\n" "${resource}" | process_resource
    done
fi

if test -d "${html_OUTPUT}" ; then
    crossref ${html_OUTPUT}
fi

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

# Copyright (c) 2017-2020 Random Crew.
#
# Available under ISC License.

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