#!/bin/bash
#set -xv
#LaTeX text corpus  
<<comment
\documentclass[a4paper,12pt]{book}
\usepackage[utf8]{inputenc}
\usepackage{graphicx}
\begin{document}
\author{TeXstudio Team}
\title{Simple Book Example}
\date{January 2013}
\frontmatter
\maketitle
\tableofcontents
\chapter{Worste Latex doc ever}
\chapter{I've wrote some bad data before}
\chapter{but this is ... pretty bad}
\chapter{Even for me.}
\mainmatter
\backmatter
\end{document}
comment
# Input LaTeX file same as corpus comment above.
latex_file="main.tex"

# Output directory for chapters
output_dir="chapters"

# Create the output directory if it doesn't exist
mkdir -p "$output_dir"

# Set the Internal Field Separator (IFS) to handle multi-line data
IFS=''

#Chapter counter
 i=0
 
# Read the LaTeX file
while IFS= read -r line; do

  # Check if the line contains \chapter command
if [[ $line == *"\chapter"* ]]; then
    # Extract the chapter text within curly braces
    chapter_text=$(echo "$line" | grep -oP '(?<=\{).*(?=\})')

    # Generate a chapter filename
    chapter_filename=$(echo "$chapter_text" | tr -dc '[:alnum:][:space:]._-')

    # Save the chapter to the output directory
    #echo "$chapter_text" > "$output_dir/$chapter_filename.txt"
    
    #Assign text to varables varNumber on the fly
    chapterVar=$chapter_text$i
    
    declare "$chapterVar"="$chapter_text"
    #Increment counter
    i=$((i+1))

fi
done < "$latex_file"

#<<comment
# Print the chapter texts variables
for (( c=0; c<=i; c++ ))
do 
  chapterVar=$chapter_text$c
  echo "Variable:  $chapterVar: ${!chapterVar}"
done
#comment

exit

