#!/bin/sh

# This should solve issues with debiandoc for Polish quotation if fixed.

#  Called as "fixlatex -l <lang> <infile> <outfile>"

locale=en

while getopts ":l:" opt
do
        case ${opt}
        in 
           l) locale=${OPTARG};;
           \? ) echo "unknown option \`${OPTARG}'"; exit -1;;
        esac
done
shift $((${OPTIND} - 1))

# $1 <infile>
# $2 <outfile>
# (both are different, real files, no stdin/stdout/...)

cp "$1" "$2"
file="$2"

dir=$(echo $locale | tr [A-Z]_ [a-z]-) # change pt_BR to pt-br

# include $dir/LaTeXmacros.sty file with language specific macros and
# LaTeXmacros.sty for general use in all translations
# (these files do not need to exist)
sed '/^\\documentclass/ a\
\\InputIfFileExists{LaTeXmacros.sty}{}{}\
\\InputIfFileExists{'$dir'/LaTeXmacros.sty}{}{}' $file > $file.tmp
mv $file.tmp $file

case $locale in
("zh_TW")
        perl -p \
-e 's/([\x80-\xff])\\textbackslash\{\}/$1\\/g;' \
-e 's/([\x80-\xff])\\textasciitilde\{\}/$1\~/g;' \
-e 's/([\x80-\xff])\\textasciicircum\{\}/$1\^/g;' \
-e 's/([\x80-\xff])\\\}/$1\}/g;' \
-e 's/([\x80-\xff])\\\{/$1\{/g;' \
-e 's/([\x80-\xff])\\\_/$1_/g;' <$1 |
        bg5conv >$2
        ;;
("pl")
	cat $file | \
	# use double quotes ,,text'': LaTeX: "`text"'
	# debiandoc2latex changes "text" to ``text'', so lets change ,, `` ''
	# Use &apos;&apos; for '', if '' really means '' in source
	sed -e "s/\`\`/\"\`/g" -e "s/,,/\"\`/g" -e "s/''/\"'/g" > $file.tmp
	mv $file.tmp $file
	;;

(*)
	: # do nothing
;;
esac

# Correct words in which accents such as '' where replaced by 'e' to be
# compatible with the encoding. (Let's hope that there's no linebreak in
# the text which is to substitute, but it seems to be as in .sgml files.)
# This is related to qref only!
# SGML entities such as &lstrok& are no valid HTML and are replaced
# by [lstrok] in HTML but work in .ps, .pdf
sed -e "s/Bartosz Fenski/Bartosz Fe\\\\\'nski/g" \
    -e 's/Radoslaw Grzanka/Rados\\l aw Grzanka/g' \
    -e 's/Rafal Michaluk/Rafa\\l\\ Michaluk/g' \
    -e 's/Tomasz Z. Napierala/Tomasz Z. Napiera\\l a/g' \
    -e "s/Tomasz Piekos/Tomasz Pi\\\\c eko\\\\\'s/g" \
    -e "s/Pawel Rozanski/Pawe\\\\l\\\\ R\\\\\'o\\\\.za\\\\\'nski/g" \
    -e "s/Krzysztof Scierski/Krzysztof \\\\\'Scierski/g" \
    -e "s/Przemyslaw Adam Smiejek/Przemys\\\\l aw Adam \\\\\'Smiejek/g"\
    -e 's/Bartosz Zapalowski/Bartosz Zapa\\l owski/g'\
    -e 's/pour le francais/pour le fran\\c cais/g' $file > $file.tmp
mv $file.tmp $file

# This makes fragile 
#test -x /usr/share/debiandoc-sgml/fixlatex && /usr/share/debiandoc-sgml/fixlatex -l "$locale" "$file" "$file.tmp"
#test -e $file.tmp && mv $file.tmp $file

