#!/bin/bash

# Format command line argument output into LaTeX
# Assumes the presence of a compile model called "example"

./example help-all | sed -e 's, \([a-zA-Z]\), {\1,' -e 's,$,},' \
                         -e 's,>=,\$\\\\\ge\$,g' -e 's,<=,\$\\\\\le\$,g' >> file.tmp \
                         -e 's,>,\$>\$,g' -e 's,<,\$<\$,g' >> file.tmp \
                         -e 's,=,}{,' -e 's,^}$,%,' -e 's,^  ,,' \
                         -e 's,_,\\\\\_,g' -e 's,<\(.*\)>,\1,' \
                         -e 's,"\([a-zA-Z0-9]*\)",``\1'\'\'',g' \
                         -e 's,method}{ ,method= ,' \
                         -e 's,\\\verbcmdarg{Analysis method,{Analysis method,'

echo '\begin{description}'

indent=0
oldIndent=0
buffer=()
while IFS='' read line
do

  if [ "$line" == "%" ]; then

    indent=`echo "${buffer[0]}" | sed 's,^\([ ]*\).*$,a\1a,' | wc -c`
    let indent=indent-3

    if [ $indent -gt $oldIndent ]; then

      blank=""
      i=0; while [ $i -lt $indent ]; do
        blank=" $blank"
        let ++i
      done

      #echo "${blank}\\begin{description}"
      #echo "%"

    fi

    if [ $indent -lt $oldIndent ]; then

      blank=""
      i=0; while [ $i -lt $oldIndent ]; do
        blank=" $blank"
        let ++i
      done

      #echo "${blank}\\end{description}"
      #echo "%"

    fi

    oldIndent=$indent

    buffer[0]=`echo "${buffer[0]}" | sed 's,\({.*}{.*}\),\\\hiercmdarg\1,'`

    blank=""
    i=0; while [ $i -lt $indent ]; do
      blank=" $blank"
      let ++i
    done

    cleanBuffer=`echo ${buffer[0]}`
    [ ${#buffer[@]} -eq 2 ] && buffer[0]="${blank}\\hiershortcmd$cleanBuffer"
    [ ${#buffer[@]} -eq 3 ] && buffer[0]="${blank}\\hierlongcmd$cleanBuffer"

    displayIndent=""
    let nIndent=indent/2
    i=0
    while [ $i -lt $nIndent ]; do
      displayIndent="\\\indentarrow${displayIndent}"
      let ++i
    done

    buffer[0]=`echo "${buffer[0]}" | sed 's,{,{'$displayIndent'}{,'`

    i=0
    while [ $i -lt ${#buffer[@]} ]
    do
      echo "${buffer[$i]}"
      let ++i
    done
    echo "%"

    buffer=()

  else
    buffer=("${buffer[@]}" "$line")
  fi

done < file.tmp

echo '\end{description}'

rm -f file.tmp
