This function accomplishes several tasks:
		1) Auto-number headings if that option is enabled
		2) Add an [edit] link to sections for logged in users who have enabled the option
		3) Add a Table of contents on the top for users who have enabled the option
		4) Auto-anchor headings

		It loops through all headlines, collects the necessary data, then splits up the
		string and re-inserts the newly formatted headlines.

def formatHeadings(self, text, isMain):
		"""
		This function accomplishes several tasks:
		1) Auto-number headings if that option is enabled
		2) Add an [edit] link to sections for logged in users who have enabled the option
		3) Add a Table of contents on the top for users who have enabled the option
		4) Auto-anchor headings

		It loops through all headlines, collects the necessary data, then splits up the
		string and re-inserts the newly formatted headlines.
		"""
		doNumberHeadings = False
		showEditLink = True # Can User Edit

		if text.find(u"__NOEDITSECTION__") != -1:
			showEditLink = False
			text = text.replace(u"__NOEDITSECTION__", u"")

		# Get all headlines for numbering them and adding funky stuff like [edit]
		# links - this is for later, but we need the number of headlines right now
		matches = _headerPat.findall(text)
		numMatches = len(matches)

		# if there are fewer than 4 headlines in the article, do not show TOC
		# unless it's been explicitly enabled.
		enoughToc = self.show_toc and (numMatches >= 4 or text.find(u"<!--MWTOC-->") != -1)

		# Allow user to stipulate that a page should have a "new section"
		# link added via __NEWSECTIONLINK__
		showNewSection = False
		if text.find(u"__NEWSECTIONLINK__") != -1:
			showNewSection = True
			text = text.replace(u"__NEWSECTIONLINK__", u"")
		# if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
		# override above conditions and always show TOC above first header
		if text.find(u"__FORCETOC__") != -1:
			self.show_toc = True
			enoughToc = True
			text = text.replace(u"__FORCETOC__", u"")
		# Never ever show TOC if no headers
		if numMatches < 1:
			enoughToc = False

		# headline counter
		headlineCount = 0
		sectionCount = 0 # headlineCount excluding template sections

		# Ugh .. the TOC should have neat indentation levels which can be
		# passed to the skin functions. These are determined here
		toc = []
		head = {}
		sublevelCount = {}
		levelCount = {}
		toclevel = 0
		level = 0
		prevlevel = 0
		toclevel = 0
		prevtoclevel = 0
		refers = {}
		refcount = {}
		wgMaxTocLevel = 5

		for match in matches:
			headline = match[2]
			istemplate = False
			templatetitle = u''
			templatesection = 0
			numbering = []

			m = _templateSectionPat.search(headline)
			if m:
				istemplate = True
				templatetitle = b64decode(m[0])
				templatesection = 1 + int(b64decode(m[1]))
				headline = _templateSectionPat.sub(u'', headline)

			if toclevel:
				prevlevel = level
				prevtoclevel = toclevel

			level = matches[headlineCount][0]

			if doNumberHeadings or enoughToc:
				if level > prevlevel:
					toclevel += 1
					sublevelCount[toclevel] = 0
					if toclevel < wgMaxTocLevel:
						toc.append(u'\n<ul>')
				elif level < prevlevel and toclevel > 1:
					# Decrease TOC level, find level to jump to

					if toclevel == 2 and level < levelCount[1]:
						toclevel = 1
					else:
						for i in range(toclevel, 0, -1):
							if levelCount[i] == level:
								# Found last matching level
								toclevel = i
								break
							elif levelCount[i] < level:
								toclevel = i + 1
								break
					if toclevel < wgMaxTocLevel:
						toc.append(u"</li>\n")
						toc.append(u"</ul>\n</li>\n" * max(prevtoclevel - toclevel, 0))
				else:
					if toclevel < wgMaxTocLevel:
						toc.append(u"</li>\n")

				levelCount[toclevel] = level

				# count number of headlines for each level
				sublevelCount[toclevel] += 1
				for i in range(1, toclevel+1):
					if sublevelCount[i]:
						numbering.append(to_unicode(sublevelCount[i]))

			# The canonized header is a version of the header text safe to use for links
			# Avoid insertion of weird stuff like <math> by expanding the relevant sections
			canonized_headline = self.unstrip(headline)
			canonized_headline = self.unstripNoWiki(canonized_headline)

			# -- don't know what to do with this yet.
			# Remove link placeholders by the link text.
			#	 <!--LINK number-->
			# turns into
			#	 link text with suffix
	#		$canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
	#							"\$this->mLinkHolders['texts'][\$1]",
	#							$canonized_headline );
	#		$canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
	#							"\$this->mInterwikiLinkHolders['texts'][\$1]",
	#							$canonized_headline );

			# strip out HTML
			canonized_headline = _tagPat.sub(u'', canonized_headline)
			tocline = canonized_headline.strip()
			# Save headline for section edit hint before it's escaped
			headline_hint = tocline
			canonized_headline = self.escapeId(tocline)
			refers[headlineCount] = canonized_headline

			# count how many in assoc. array so we can track dupes in anchors
			if canonized_headline not in refers:
				refers[canonized_headline] = 1
			else:
				refers[canonized_headline] += 1
			refcount[headlineCount] = refers[canonized_headline]

			numbering = '.'.join(numbering)

			# Don't number the heading if it is the only one (looks silly)
			if doNumberHeadings and numMatches > 1:
				# the two are different if the line contains a link
				headline = numbering + u' ' + headline

			# Create the anchor for linking from the TOC to the section
			anchor = canonized_headline;
			if refcount[headlineCount] > 1:
				anchor += u'_' + unicode(refcount[headlineCount])

			if enoughToc:
				toc.append(u'\n<li class="toclevel-')
				toc.append(to_unicode(toclevel))
				toc.append(u'"><a href="#w_')
				toc.append(anchor)
				toc.append(u'"><span class="tocnumber">')
				toc.append(numbering)
				toc.append(u'</span> <span class="toctext">')
				toc.append(tocline)
				toc.append(u'</span></a>')

	#		if showEditLink and (not istemplate or templatetitle != u""):
	#			if not head[headlineCount]:
	#				head[headlineCount] = u''
	#
	#			if istemplate:
	#				head[headlineCount] += sk.editSectionLinkForOther(templatetile, templatesection)
	#			else:
	#				head[headlineCount] += sk.editSectionLink(mTitle, sectionCount+1, headline_hint)

			# give headline the correct <h#> tag
			if headlineCount not in head:
				head[headlineCount] = []
			h = head[headlineCount]
			h.append(u'<h')
			h.append(to_unicode(level))
			h.append(u' id="w_')
			h.append(anchor)
			h.append('">')
			h.append(matches[headlineCount][1].strip())
			h.append(headline.strip())
			h.append(u'</h')
			h.append(to_unicode(level))
			h.append(u'>')

			headlineCount += 1

			if not istemplate:
				sectionCount += 1

		if enoughToc:
			if toclevel < wgMaxTocLevel:
				toc.append(u"</li>\n")
				toc.append(u"</ul>\n</li>\n" * max(0, toclevel - 1))
			#TODO: use gettext
			#toc.insert(0, u'<div id="toc"><h2>' + _('Table of Contents') + '</h2>')
			toc.insert(0, u'<div id="toc"><h2>Table of Contents</h2>')
			toc.append(u'</ul>\n</div>')

		# split up and insert constructed headlines

		blocks = _headerPat.split(text)

		i = 0
		len_blocks = len(blocks)
		forceTocPosition = text.find(u"<!--MWTOC-->")
		full = []
		while i < len_blocks:
			j = i/4
			full.append(blocks[i])
			if enoughToc and not i and isMain and forceTocPosition == -1:
				full += toc
				toc = None
			if j in head and head[j]:
				full += head[j]
				head[j] = None
			i += 4
		full = u''.join(full)
		if forceTocPosition != -1:
			return full.replace(u"<!--MWTOC-->", u''.join(toc), 1)
		else:
			return full