#!/bin/bash

# wilt - the renumbering script
# e.g. fix the question numbers in the emacs FAQ

# wilt is copyright (c) 1998 by W. L. Estes <wlestes@uncg.edu>

# wilt is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.

# wilt is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with wilt; see the file COPYING.  If not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.

OPTIONS="F:hv"

function usage() {
cat <<EOF
Usage:
$0 [ -F fieldsep ] [ files ]
$0 -h | -v
EOF
}

function version () {
cat << EOF
This is version 1.0 of $PROGNAME.
$PROGNAME is licensed under the terms of the GNU GPL. See the file
COPYING for details. There is absolutely no warranty.
EOF
}

while getopts "$OPTIONS" OPT ; do
case "$OPT" in
F) WILT_FS="$OPTARG" ;;
h) usage ; exit 0 ;;
v) version ; exit 0 ;;
*) usage ; exit 1 ;;
esac
done

shift $[$OPTIND - 1]
if [ -z $WILT_FS ] ; then WILT_FS=":" ; fi

exec awk -F $WILT_FS '
BEGIN {
found=0
OFS=FS
submarker = "\\."
section = "[1-9][0-9]*"
matching = "^" section "(" submarker section ")*$"
}

$1 ~ matching {
level = split($1,levels,submarker)
if (found!=0) {
level=setLevel(levels,level,oldlevels,oldlevel)
}
$1=sprintArray(levels,level)
copyArray(levels,oldlevels,level)
oldlevel=level
found=1
}

{print}

# print elements 1..howfar of array foo
# we shadow OFS for convenience of metaphor
function sprintArray(foo,howfar,OFS,retval,i) {
OFS="."
if (howfar>0) {
retval=sprintf("%d",foo[1])
for (i=2; i<=howfar; i++) {
retval=retval sprintf ("%s%d",OFS,foo[i])
}
}
return retval
}

# fix the section number in levels so it "properly" follows that of
# oldlevels

function setLevel(levels,_level,oldlevels,_oldlevel,retval) {

if (_level==_oldlevel) {
copyArray(oldlevels,levels,_oldlevel-1)
levels[_level] = oldlevels[_oldlevel]+1
retval=_level
}  # levels same length as oldlevels
else
if (_level>_oldlevel) {
retval=_level=_oldlevel +1
copyArray(oldlevels,levels,_oldlevel)
levels[_level]=1
}  # levels longer than oldlevels
else
if (_level<_oldlevel) {
copyArray(oldlevels,levels,_level-1)
levels[_level]=oldlevels[_level]+1
retval=_level
} # levels shorter than oldlevels

return retval
}

# copy elements 1..level of array
function copyArray(levels,oldlevels, level,i) {
for (i=1; i<=level; i++) {
oldlevels[i]=levels[i]
}
}
' $@

