#!/bin/bash
export ALL
PAGES=$1 ; OFFSET=$2 ; IDXSTART=$3
echo PAGES=$PAGES OFFSET=$OFFSET IDXSTART=$IDXSTART

[[ -z $COURSE   ]] && COURSE=LFD420
[[ -z $PAGES    ]] && PAGES=260
[[ -z $OFFSET   ]] && OFFSET=12
[[ -z $IDXSTART ]] && IDXSTART=242
PAGES=191 ; COURSe=LFS465 ; OFFSET=10 IDXSTART=191
 
echo PAGES=$PAGES OFFSET=$OFFSET IDXSTART=$IDXSTART

# The INDEX
echo pdftk "$COURSE".pdf cat $IDXSTART-$PAGES output "$COURSE"_IDX.pdf
pdftk "$COURSE".pdf cat $IDXSTART-$PAGES output "$COURSE"_IDX.pdf

# The TOC
echo pdftk "$COURSE".pdf cat 1-$OFFSET output "$COURSE"_TOC.pdf
pdftk "$COURSE".pdf cat 1-$OFFSET output "$COURSE"_TOC.pdf

# The CHAPTERS
grep chapter *toc | sed \
    -e s/[a-z]//g \
    -e s/[A-Z]//g \
    -e s/'\\'/\ /g \
    -e s/{/\ /g  \
    -e s/}/\ /g  \
    -e s/')'/\ /g  \
    -e s/'('/\ /g  \
    -e s/'\*'//g \
    -e s/'-'//g \
    > /dev/shm/stage1

echo last line >> /dev/shm/stage1

cat /dev/shm/stage1 | while read LINE ; do
    CHAP="$(echo $LINE | awk '{print $1}')"
    PAGE="$(echo $LINE | awk '{print $2}')"
#    echo CHAP=$CHAP PAGE=$PAGE
    if [[ $CHAP -gt 1 ]] ; then
	p1=$(($PPAGE     + $OFFSET ))
	p2=$(($PAGE - 1  + $OFFSET ))
	ch=$((CHAP-1))
	echo pdftk "$COURSE".pdf cat $p1-$p2 output "$COURSE"_CHAPTER_$ch.pdf
	pdftk "$COURSE".pdf cat $p1-$p2 output "$COURSE"_CHAPTER_$ch.pdf
    fi
# The last chapter

    if [[ "$(echo $LINE | grep last)" ]] ; then
	p1=$(($PPAGE  + $OFFSET ))
	p2=$(($IDXSTART - 1 ))
	ch=$PCHAP
	echo pdftk "$COURSE".pdf cat $p1-$p2 output "$COURSE"_CHAPTER_$ch.pdf
	pdftk "$COURSE".pdf cat $p1-$p2 output "$COURSE"_CHAPTER_$ch.pdf
    fi
    PPAGE=$PAGE
    PCHAP=$CHAP
done

