"""HTML -> greppable plain text. Pure stdlib: the task images have no bs4 and no internet to get it. Whitespace inside
/ is preserved -- these documents carry their worked examples in code
blocks, and a collapsed one ("mbarrier_init(&bar,1);// Initialize barrier") is unreadable.
"""
import re
import sys
from html.parser import HTMLParser

DROP = {"script", "style", "nav", "head", "noscript", "svg", "form"}
BLOCK = {"p", "div", "li", "tr", "br", "section", "article"}
HEAD = {"h1", "h2", "h3", "h4", "h5", "h6"}


class T(HTMLParser):
    def __init__(self):
        super().__init__(convert_charrefs=True)
        self.out, self.skip, self.pre = [], 0, 0

    def handle_starttag(self, tag, attrs):
        if tag in DROP:
            self.skip += 1
        elif tag in ("pre", "code"):
            if tag == "pre":
                self.out.append("\n")
            self.pre += 1
        elif self.pre:
            if tag == "br":
                self.out.append("\n")
        elif tag in HEAD:
            self.out.append("\n\n### ")
        elif tag in BLOCK:
            self.out.append("\n")
        elif tag in ("td", "th"):
            self.out.append("  ")

    def handle_endtag(self, tag):
        if tag in DROP and self.skip:
            self.skip -= 1
        elif tag in ("pre", "code"):
            if self.pre:
                self.pre -= 1
            if tag == "pre":
                self.out.append("\n")
        elif not self.pre and tag in HEAD | {"table"}:
            self.out.append("\n")

    def handle_data(self, d):
        if self.skip:
            return
        if self.pre:
            self.out.append(d)          # verbatim: newlines and indentation are the content
        elif d.strip():
            self.out.append(d)


def convert(src):
    p = T()
    p.feed(src)
    t = "".join(p.out)
    # collapse runs of spaces only OUTSIDE code: do it line-wise, leaving indented lines alone
    lines = []
    for ln in t.splitlines():
        lines.append(ln if ln[:1] in (" ", "\t") else re.sub(r"[ \t]{2,}", " ", ln).rstrip())
    t = "\n".join(lines)
    return re.sub(r"\n{3,}", "\n\n", t).strip() + "\n"


if __name__ == "__main__":
    sys.stdout.write(convert(open(sys.argv[1], encoding="utf-8", errors="ignore").read()))