#!/bin/bash

# Garder les chapitres dans le sommaire malgré export
# Aller directement jusqu'au chapitre en cours
# Beamer et affichage <2-> automatique lorsque qu'on a des sous-items
# Tikz geogebra et overlay
# Rajouter page de titre pour chapitre et (éventuellement partie) 
# cela revient a placer les arbres au bon endroit
# Background et fond, police, couleurs des lettres et du fond
# Planches avec le meme titre '1 pour définition, 1 pour figure...'
# Interjections Au boulot, Votre attention s'il vous plait, Expérimentons, À vos plumes
# Pour des messages intermediaires, utiliser par exemple echo Entering recursive routine $floor >&2


# Repertoire temporaire - doit etre present
TMPDIR=tmp

# Emacs
EMACS=emacs

# Fichier entree
infile=$1

# Fonction recursive pour exploration de l arbre
function tree_excursion() 
{ 
    # Reads current floor
    local floor=$1

    # Reads parent subject in floor
    local parent_subject="$2"
    local PARENT_SUBJECT="$(echo $parent_subject | sed -e 's/é/É/g' -e 's/è/È/g' -e 's/à/À/g' |  tr 'a-z' 'A-Z' )"
    
    # Reads parent index in floor
    local parent_index=$3

    # Reads grandparent index in previous floor
    local grand_parent_index=$4

    # Reads grandparent index in previous floor
    local grand_grand_parent_index=$5

    # File containing list of numbers for first chapters
    local nlist=(01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18)

    # From floor, we know how many stars we have
    case $floor in
        1)
            local parent_pattern=""
            local child_pattern="*"
            ;;

        2)
            local parent_pattern="\*"
            local child_pattern="\*\*"
            local list=(I- II- III- IV- V- VI- VII- VIII- IX- X- XI- XII-)
            ;;

        3)
            local parent_pattern="\*\*"
            local child_pattern="\*\*\*"
            local plist=(I- II- III- IV- V- VI- VII- VIII- IX- X- XI- XII-)
            local list=(A- B- C- D- E- F- G- H- I- J- K- L- M- N- O-)
            ;;

        4)
            local parent_pattern="\*\*\*"
            local child_pattern="\*\*\*\*"
            local plist=(A- B- C- D- E- F- G- H- I- J- K- L- M- N- O-)
            local list=(1\) 2\) 3\) 4\) 5\) 6\) 7\) 8\) 9\) 10\) 11\) 12\))
            ;;

        5)
            return
            ;;
    esac
    
    # Variable to save numbering of sections
    local numtmp=$6-${nlist[$((parent_index-1))]}
    local numtmp2=$numtmp
    while [ ${#numtmp2} -lt 15 ]; do
        numtmp2=$numtmp2-00
    done

    # File to save tree
    local pfile=$TMPDIR/$numtmp2.atree

    # From parent_subject, we need to keep the children only
    if [ $floor -eq 1 ]; then
	# Removes first line of org input file 
        awk 'NR>1{ print $0}' $infile > $TMPDIR/tmp.$floor

	# Keeps lines with child pattern
        sed -n "/^$child_pattern /p" $TMPDIR/tmp.$floor > $TMPDIR/current.$floor
    else
	# Filters lines from parent_subject to next parent pattern
        sed -n "/$parent_subject/,/^$parent_pattern /p" $TMPDIR/tmp.$((floor-1)) > $TMPDIR/tmp.$floor

	# We keep a copy for later use
        cp $TMPDIR/tmp.$floor $TMPDIR/current.1.$floor
	
	# Keeps lines with child pattern
        sed -n "/^$child_pattern /p" $TMPDIR/tmp.$floor > $TMPDIR/current.$floor
    fi

    # Number of children
    local nchildren=$(wc -l $TMPDIR/current.$floor | awk '{print $1}')

    # Writes parent node (even if no child) - Removes dash
    if [ $nchildren -ne 0 ]; then
        cat utils_tex/tikzheader.tex | sed "s/{Title}/[plain]/" > $pfile
        if [ $floor -eq 1 ]; then
            echo -n "node[concept,style={rectangle,rounded corners},scale=0.61,font=\\Large,text=white]{\hypertarget{$floor"_"$grand_parent_index"_"$parent_index}{\bf $PARENT_SUBJECT}}" | sed 's/^[\*][\*]* //g' >> $pfile
        else
            if [ $floor -gt 2 ]; then
                text="${plist[$parent_index-1]} {\bf $PARENT_SUBJECT}"
            else
                text="{\bf $PARENT_SUBJECT}"
            fi
            echo -n "node[concept,style={rectangle,rounded corners},scale=0.61,font=\\Large,text=white]{\hypertarget{$floor"_"$grand_parent_index"_"$parent_index}{\hyperlink{$((floor-1))"_"$grand_grand_parent_index"_"$grand_parent_index}{$text}}}" | sed 's/^[\*][\*]* //g' >> $pfile
        fi
    fi

    # echo ===================  >&2
    # echo $PARENT_SUBJECT >&2
    
    # Loops over children grids if any
    local itmp=1
    local ichild=0
    local ichildtheoretical=1; while [ $ichildtheoretical -le $nchildren ]; do

        # Go to line for each child
        local child_subject="$(sed -n "$ichildtheoretical"p $TMPDIR/current.$floor | sed 's/^[\*][\*]* //g')"
        local safe_child_subject=$(printf '%s\n' "$child_subject" | sed 's/[[\.*^$/]/\\&/g')

        # Attention aux crochets doubles primordial
        if [[ "$child_subject" != *":noexport:"* ]]; then 




        ichild=$((ichild+1))

        echo >> $pfile

        local angle=$(echo "scale=0;360/$nchildren*($ichild-1)" | bc)
        if [ $floor -gt 1 ]; then
            text="${list[$ichild-1]} ${child_subject/:noexport:/}"
        else
            text="${child_subject/:noexport:/}"
        fi

	
	#echo $ichild Child subject $text >&2
	
	# Avec graphique - mettre un test
#        echo -n "child[grow=$angle,visible on=<$((ichild+1))->]{node[concept,style={rectangle,rounded corners},scale=0.675,font=\\Large,color=black,text=LightGray]{\includegraphics[width=2.5cm]{tmp.png} \\ \hyperlink{$((floor+1))"_"$parent_index"_"$ichild}{$text}}}" >> $pfile

        if [ 1 -eq 0 ]; then

        if [ $itmp -eq 1 ]; then
            if [[ "$child_subject" != *":noexport:"* ]]; then 
                echo -n "child[grow=$angle,visible on=<$((itmp+1))->]{node[concept,style={rectangle,rounded corners},scale=0.675,font=\\Large,color=black,text=LightGray]{\hyperlink{$((floor+1))"_"$parent_index"_"$ichild}{$text}}}" >> $pfile
                itmp=$((itmp+1))
                # Tout le temps visible
            else
                echo -n "child[grow=$angle]{node[concept,style={rectangle,rounded corners},scale=0.675,font=\\Large,color=black,text=LightGray]{\hyperlink{$((floor+1))"_"$parent_index"_"$ichild}{$text}}}" >> $pfile
            fi
        else
            echo -n "child[grow=$angle,visible on=<$((itmp+1))->]{node[concept,style={rectangle,rounded corners},scale=0.675,font=\\Large,color=black,text=LightGray]{\hyperlink{$((floor+1))"_"$parent_index"_"$ichild}{$text}}}" >> $pfile
            itmp=$((itmp+1))
        fi
        else

                            echo -n "child[grow=$angle]{node[concept,style={rectangle,rounded corners},scale=0.675,font=\\Large,color=black,text=LightGray]{\hyperlink{$((floor+1))"_"$parent_index"_"$ichild}{$text}}}" >> $pfile

        fi


        # echo ======================= >&2
        # echo $child_subject >&2

            
#            echo GO in >&2      # 

            # Recursive excursion for content children
            tree_excursion $((floor+1)) "$child_subject" $ichild $parent_index $grand_parent_index $numtmp

            # Writes corresponding section except "title" node
            if [ $floor -ne 1 ]; then

                # Updates global index of content part
                ipart=$((ipart+1))
                
                # Name of file to save content of current part
                local numtmp3=$numtmp-${nlist[$((ichild-1))]}
                while [ ${#numtmp3} -lt 15 ]; do
                    numtmp3=$numtmp3-00
                done
                local cfile=$TMPDIR/$numtmp3.content

                #
                sed -n "/$safe_child_subject/,/^[*][*]*/p" $TMPDIR/current.1.$floor > $TMPDIR/current.2.$floor
                sed -n "/$safe_child_subject/,/^[*][*]*/p" $TMPDIR/current.2.$floor | awk 'NR>2{ print l} {l=$0}' >> $cfile.tmp

                # Check if file is empty and gets contents 
                if [ -s $cfile.tmp ]; then

                    # Splits part containing %%% subparts of a same frame
                    rm -f $cfile; rm -f $TMPDIR/F*
                    awk '/%%%/{x="'$TMPDIR'/F"++i;}{print > x;}' $cfile.tmp
		    # If splitting was effective
                    if [ $? -eq 0 ]; then
                        for i in 1 2 3 4 5 6 7 8 9 10; do
                            if [ -e $TMPDIR/F$i ]; then
                                sed  '/%%%/d' $TMPDIR/F$i > $TMPDIR/F$i.tmp
                                echo "\begin{frame}" >> $cfile
                                echo "\frametitle{\hypertarget{$((floor+1))"_"$parent_index"_"$ichild}{\hyperlink{$floor"_"$grand_parent_index"_"$parent_index}{${list[$ichild-1]} $child_subject}}}" >> $cfile
                                $EMACS --batch --no-init-file --no-site-file -l init.el --visit $TMPDIR/F$i.tmp -f org-latex-export-to-latex
                                sed -n '/tableofcontents/,/Emacs/p' $TMPDIR/F$i.tex | awk 'NR>2{ print l} {l=$0}' >> $cfile
				echo "\end{frame}" >> $cfile
                            fi
                        done
		    # If not	
                    else
                        echo "\begin{frame}" >> $cfile
                        echo "\frametitle{\hypertarget{$((floor+1))"_"$parent_index"_"$ichild}{\hyperlink{$floor"_"$grand_parent_index"_"$parent_index}{${list[$ichild-1]} $child_subject}}}" >> $cfile
                        $EMACS --batch --no-init-file --no-site-file -l init.el --visit $cfile.tmp -f org-latex-export-to-latex
                        sed -n '/tableofcontents/,/Emacs/p' $cfile.tex | awk 'NR>2{ print l} {l=$0}' >> $cfile
                        echo "\end{frame}" >> $cfile
                    fi

                fi
                
            fi

        fi

        # Updates content child index
        ichildtheoretical=$((ichildtheoretical+1))
        
    done

       
    # Closes tikz path of mindmap
    if [ $nchildren -ne 0 ]; then
        echo ";" >> $pfile
        cat utils_tex/tikzfooter.tex >> $pfile
    fi

}

# Nettoyage preliminaire
#=======================

rm -f $TMPDIR/*content*
rm -f $TMPDIR/*tree 
rm -f $TMPDIR/tmp

# Parcours recursif de l'arbre
#=============================

ipart=0
document_title=$(sed -n '1p' $infile) 
tree_excursion 1 "$document_title" 1 0 0 00

# On ajoute les differents fichiers
#==================================

# Entete
sed "s/Presentation Template/$document_title/" utils_tex/zheader.tex 

# Corps - Attention sur windows, on utilise winbash et le ls ne donne pas la meme chose
for file in $(ls $TMPDIR/*{atree,content}); do
    cat $file
done

# Fin de document
cat utils_tex/zfooter.tex

# On nettoie $TMPDIR
if [ 1 -eq 1 ]; then
    rm -f $TMPDIR/current.*
    rm -f $TMPDIR/*.tmp $TMPDIR/F* $TMPDIR/*.tex $TMPDIR/tmp* $TMPDIR/grep
fi
