# Author: Daniel Ortiz Mart\'inez
# *- bash -*

# Given a word graph generated by a stack decoder, this utility exports
# such graph into different formats. The output is written to the
# standard output

#########
function export_wg_graphviz()
{
    # Take parameters
    graph=$1

    # Export wordgraph
    echo "digraph word_graph {"
    echo "rankdir=LR;"
    "${AWK}" 'BEGIN{
                 lineWithFinalStates=1
                }
                {
                 if(FNR==1 && $1=="#") lineWithFinalStates=2
                 else
                 {
                  if(FNR==lineWithFinalStates)
                  {
                   printf "node [shape = doublecircle]; "
                   printf "%s;\n",$0
	           printf "node [shape = circle];\n"
                  }
                  else
                  {
                   printf "%s -> %s [ label = \"%s",$1,$2,$3
                   for(i=4;i<=NF;++i) 
                   {
                    if($i=="|||") printf " /"
                    else
                     printf " %s",$i
                   }
                   printf "\" ];\n"
                  }
                 }
                }' "$graph"
        echo "}"
}

#########

if [ $# -ne 1 -a $# -ne 2 ]; then
    echo "Use: thot_export_wordgraph [<graph_file>]"
    echo "                           <Format: 0-> basic graphviz format>"
else
    if [ $# -eq 1 ]; then
        format=$1
    else
        graph=$1
        format=$2
    fi

    if [ $format -eq 0 ]; then
        export_wg_graphviz "$graph"
    fi
fi
