import BeautifulSoup
from BeautifulSoup import Tag, NavigableString


BeautifulSoup.BeautifulSoup.QUOTE_TAGS['pre'] = None

soup = BeautifulSoup.BeautifulSoup(file('res.html'))

hs = soup.findAll(['h%d' % i for i in range(4)])
ll = 2
toc = Tag(soup, 'div')
toc['class'] = 'toc'
soup.insert(0, toc)
t = Tag(soup, 'h1')
t.insert(0, NavigableString('Table of Contents'))
toc.insert(0, t)
t = Tag(soup, 'ul')
t['class'] = 'toc'
toc.insert(1, t)
for i in range(len(hs)):
	h = hs[i]
	h['id'] = 'chapter%d' % i
	l = int(h.name[1])
	h.name = 'h%d' % (l - 1)
	if l > ll:
		t = Tag(soup, 'ul')
		t2.insert(9999999, t)
	elif l < ll:
		for j in range(ll - l):
			t = t.parent.parent
	t2 = Tag(soup, 'li')
	t3 = Tag(soup, 'a')
	t3['href'] = '#chapter%d' % i
	t4 = NavigableString(h.renderContents())
	t.insert(9999999, t2)
	t2.insert(0, t3)
	t3.insert(0, t4)
	ll = l

cns = soup.findAll(attrs={'class': lambda x: x and 'cn' in x.split()})
for i in range(len(cns)):
	if cns[i].name not in ['h%d' %i for i in range(1, 4)]:
		cns[i]['id'] = 'cn%s' % i
for i in soup.findAll(attrs={'class': lambda x: x and 'system-messages' in x.split()}):
	i.extract()
print """<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>The Definitive Guide to Django: Web Development Done Right</title>
<meta name="author" content="Adrian Holovaty, Jacob Kaplan-Moss"/>
<link rel="stylesheet" type="text/css" href="boom.css"/>
</head>
<body>"""
print str(soup).replace('\xe2\x84\xa2', '<sup>TM</sup>')
print """</body>
</html>"""
