# outline.py - prints outline of headers in a web page
#              a solution to Miller/Ranum Exercise 5.17
# cmc, 2/7/2015

import urllib.request

def outline(pagename, encoding='utf-8'):

    pagefile = None
    try:
        pagefile = urllib.request.urlopen(pagename)
        pagedata = pagefile.read()
    except OSError as err:
        print("url error: " + str(err))
        return
    finally:
        if pagefile: pagefile.close()

    pagetext = pagedata.decode(encoding)

    done = False
    current = 0
    length = len(pagetext)
    while current < length and not done:
        findresult = findheader(pagetext[current:])
        if findresult != None:
            head = findresult[0]
            current = current + findresult[1]
            if head:
                headtext = getheadtext(pagetext[current:],head)
                printhead(head, headtext)
            while pagetext[current] != '>':
                current = current + 1            
        else:
            done = True

def findheader(text):
    ltext = text.lower()
    current = 0
    n = len(text)
    while current < n and not ltext[current:].startswith('<h'):
        current = current + 1
    if current + 3 >= n:
        return None
    if not ltext[current+2].isdigit():
        return (None, current)
    return (ltext[current+1:current+3], current)

def getheadtext(text, head):
    start = 1
    n = len(text)
    ltext = text.lower()
    while ltext[start-1] != '>':
        start = start + 1
    endtag = '</'+head+'>'
    finish = start
    while not ltext[finish:].startswith(endtag):
        finish = finish + 1
    return text[start:finish]

def printhead(head, headtext):
    indent = ' ' * 3
    times = int(head[1]) - 1
    print(indent*times + head.upper() + '. ' + headtext)

def main():
    page = input("enter url: ")
    outline(page)
        
main()
