#!/usr/local/bin/python
# Takes a chapter as input and adds internal links and numbering to all
# of the h1, h2, h3, h4 sections and so forth.
#
import sys
import re
if len(sys.argv) != 3:
print "usage: makechap.py filename num"
sys.exit(1)
filename = sys.argv[1]
num = int(sys.argv[2])
section = 0
subsection = 0
subsubsection = 0
nameindex = 0
name = ""
# Regexs for
,... sections
h1 = re.compile(r".*?[\d\.\s]*(.*?)
", re.IGNORECASE)
h2 = re.compile(r".*?[\d\.\s]*(.*?)
", re.IGNORECASE)
h3 = re.compile(r".*?[\d\.\s]*(.*?)
", re.IGNORECASE)
h4 = re.compile(r".*?[\d\.\s]*(.*?)
", re.IGNORECASE)
data = open(filename).read() # Read data
open(filename+".bak","w").write(data) # Make backup
lines = data.splitlines()
result = [ ]
index = "\n\n"
skip = 0
skipspace = 0
for s in lines:
if s == "":
if not skip:
skip = 1
else:
skip = 0
continue;
if skip:
continue
if not s and skipspace:
continue
if skipspace:
result.append("")
result.append("")
skipspace = 0
m = h1.match(s)
if m:
nameindex += 1
result.append("""%d %s
""" % (nameindex,num,m.group(1)))
result.append("@INDEX@")
section = 0
subsection = 0
subsubsection = 0
name = m.group(1)
skipspace = 1
continue
m = h2.match(s)
if m:
nameindex += 1
section += 1
result.append("""%d.%d %s
""" % (nameindex,num,section, m.group(1)))
if subsubsection:
index += "
\n"
if subsection:
index += "\n"
index += """
%s\n""" % (nameindex,m.group(1))
subsection = 0
subsubsection = 0
skipspace = 1
continue
m = h3.match(s)
if m:
nameindex += 1
subsection += 1
result.append("""%d.%d.%d %s
""" % (nameindex,num,section, subsection, m.group(1)))
if subsubsection:
index += "\n"
if subsection == 1:
index += "\n"
index += """- %s\n""" % (nameindex,m.group(1))
subsubsection = 0
skipspace = 1
continue
m = h4.match(s)
if m:
nameindex += 1
subsubsection += 1
result.append("""
%d.%d.%d.%d %s
""" % (nameindex,num,section, subsection, subsubsection, m.group(1)))
if subsubsection == 1:
index += "\n"
index += """- %s\n""" % (nameindex,m.group(1))
skipspace = 1
continue
result.append(s)
if subsubsection:
index += "
\n"
if subsection:
index += "
\n"
if section:
index += "\n"
index += "\n"
data = "\n".join(result)
data = data.replace("@INDEX@",index);
# Write the file back out
open(filename,"w").write(data)
# Print the TOC data
index = index.replace("#n","%s#n" % filename)
print """\n""" % (filename,num,name)
print index