#! /bin/csh

# Do only these files
foreach FNAME ( Intro Tutorial UserGuide Extended Customization FAQ Reference )

    # Convert LyX file to LaTeX
    lyx --export latex ${FNAME}.lyx

    # Run latex three times to make sure all references are resolved
    latex ${FNAME}.tex
    latex ${FNAME}.tex
    latex ${FNAME}.tex

    # clean up toc files by getting rid of paragraph entries, and fixing up
    # the "LaTeX" and "LyX" encoding
    grep -v \{paragraph\} $FNAME.toc | \
    sed -e s/"\\kern -.1667em\\lower .5ex\\hbox {E}\\kern -.125emX\\spacefactor \\@m {}"/eX/ | \
    sed -e s/"\\kern -.1667em\\lower .25em\\hbox {Y}\\kern -.125emX\\spacefactor \\@m {}"/yX/ | \
    sed -e s/"\\LaTeX {}"/LaTeX/ | \
    sed -e s/"{\[}"/"\("/ | \
    sed -e s/"{\]}"/"\)"/ | \
    sed -e s/"\\textsc {"// | \
    sed -e s/"\\textsf {"// > ${FNAME}.tmp

    # now parse the entries
    cut -f 1 -d \} $FNAME.tmp | sed -e s/"\\contentsline {"// > $FNAME.type
    cut -f 2 -d \} $FNAME.tmp | sed -e s/"{\\numberline {"// > $FNAME.numb
    cut -f 5- -d \{ $FNAME.tmp | cut -f 2- -d \{ | sed -e s/"}"//g > $FNAME.page
    cut -f 4- -d \{ $FNAME.tmp | cut -f 2- -d \} | cut -f 1 -d \{ | sed -e s/"}"//g > $FNAME.text

    # Add intro junk to type files
    sed -e s/subsubsection/"\\noindent \\textbf{~~~~~~~~~ "/ $FNAME.type | \
    sed -e s/subsection/"\\noindent \\textbf{~~~~~~ "/ | \
    sed -e s/section/"\\noindent \\textbf{~~~ "/ | \
    sed -e s/chapter/"\\noindent \\textbf{ "/ > $FNAME.a

    # Add } to numb files
    sed -e s/\\\'/\}/ $FNAME.numb > $FNAME.b
    
    # Add \hfill{} to page
    sed -e s/\\\`/"\\hfill{} "/ $FNAME.page > $FNAME.c

    # Paste 'em together
    paste $FNAME.a $FNAME.b $FNAME.text $FNAME.c >$FNAME.all
end

rm -f *.type *.numb *.page *.text *.tmp *.a *.b *.c *.log *.aux *.dvi *.toc *.tex

# Create tex file
cat > TOC.tex <<EOF1
\\documentclass{article}
\\begin{document}
\\title{LyX Documentation Master Table of Contents}
\\author{by the LyX Team Robot}
\\section*{Introduction}
EOF1
cat >> TOC.tex < Intro.all

cat >> TOC.tex <<EOF2
\\section*{Tutorial}
EOF2
cat >> TOC.tex < Tutorial.all

cat >> TOC.tex <<EOF3
\\section*{User's Guide}
EOF3
cat >> TOC.tex < UserGuide.all

cat >> TOC.tex <<EOF4
\\section*{Extended Features}
EOF4
cat >> TOC.tex < Extended.all

cat >> TOC.tex <<EOF5
\\section*{Customization}
EOF5
cat >> TOC.tex < Customization.all

cat >> TOC.tex <<EOF6
\\section*{FAQ}
EOF6
cat >> TOC.tex < FAQ.all

cat >> TOC.tex <<EOF7
\\section*{Reference Manual}
EOF7
cat >> TOC.tex < Reference.all

cat >> TOC.tex <<EOF8
\\end{document}
EOF8

rm -f *.all
