#!/usr/bin/env python3
"""Make the body of my report on IIS-Q-0003 (Cap Set).

usage: python3 -I make_q3_body.py Q3_DIR PARTS_DIR BODIES_DIR TALK_HTML UPLOAD_LOG OUT

Q3_DIR is work/capset/q0003.  The script reads the files q3_check, q3_check.c, q3_cases.py,
q3_signtest.py and q3_masks_summary.py in Q3_DIR, the logs in Q3_DIR/logs and, for two
comparisons, the files of the first runs in Q3_DIR/logs_before.  PARTS_DIR holds the
four parts of the body (q3_part1.md to q3_part4.md) with placeholders <<NAME>>.  BODIES_DIR holds
the texts of the earlier reports and TALK_HTML is the saved discussion page; the script reads these
files as text only (untrusted data).  UPLOAD_LOG is the log of the uploads.  Every number of the
body comes from these files.  The script stops with an error when a comparison fails or when a
number is not what the text says.  It writes OUT and OUT.values.json (the values of the
placeholders, for the title, the summary and the plain text of the report) and returns 0 when
there is no error.
"""

import ast
import hashlib
import html
import json
import re
import sys
from collections import Counter
from pathlib import Path

errors = []


def fail(msg):
    errors.append(msg)


def need(cond, msg):
    if not cond:
        fail(msg)


def read(path):
    return Path(path).read_text(encoding="utf-8", errors="replace")


def sha(path):
    return hashlib.sha256(Path(path).read_bytes()).hexdigest()


def one(text, pattern, name):
    m = re.search(pattern, text, re.M)
    if not m:
        fail("no line of the form %s in %s" % (pattern, name))
    return m


def trimmed(row):
    row = tuple(row)
    while row and row[-1] == 0:
        row = row[:-1]
    return row


def longest(rows):
    best = 0
    for row in rows:
        n = 0
        for x in row:
            if x == 0:
                break
            n += 1
        best = max(best, n)
    return best


KINDS = ("intact", "dual", "p1w", "p1wm", "p1s", "p2", "p3")
EXPECTED = {"intact": 1, "dual": 1, "p1w": 56, "p1wm": 56, "p1s": 56, "p2": 1540, "p3": 27720}


class Tables:
    """The tables of the C program for the two caps: {budget: {puncture set: row}}."""

    def __init__(self, logs):
        self.logs = logs
        self.cache = {}

    def one_line(self, name):
        chunks = read(self.logs / name).strip().split(":")
        table, budget = {}, int(chunks[0])
        for i, chunk in enumerate(chunks[1:]):
            row = [int(x) for x in chunk.split()]
            if i + 1 < len(chunks) - 1:
                table[budget], budget = tuple(row[:-1]), row[-1]
            else:
                table[budget] = tuple(row)
        return {b: {(): row} for b, row in table.items()}

    def per_set(self, tag, names):
        table = {}
        for name in names:
            for line in read(self.logs / name).splitlines():
                if not line.startswith(tag + " "):
                    continue
                head, rest = line.split("|", 1)
                index = tuple(int(x) for x in head.split()[1:])
                parts = re.split(r"(\d+):", rest)
                for i in range(1, len(parts) - 1, 2):
                    budget = int(parts[i])
                    row = tuple(int(x) for x in parts[i + 1].split())
                    sets = table.setdefault(budget, {})
                    need(index not in sets, "%s: the puncture set %s is two times at budget %d" % (name, index, budget))
                    sets[index] = row
        return table

    def load(self, layer, kind):
        key = (layer, kind)
        if key not in self.cache:
            parts = ["q3_p2_L%d_%d.log" % (layer, i) for i in range(12)]
            triples = ["q3_p3_L%d_%d.log" % (layer, i) for i in range(12)]
            if kind == "intact":
                table = self.one_line("q3_intact_L%d.log" % layer)
            elif kind == "dual":
                table = self.one_line("q3_dual_L%d.log" % layer)
            elif kind == "p1w":
                table = self.per_set("p1w", ["q3_p1w_full_L%d.log" % layer])
            elif kind == "p1wm":
                table = self.per_set("p1w", ["q3_p1w_L%d.log" % layer])
            elif kind == "p1s":
                table = self.per_set("p1s", ["q3_p1s_L%d.log" % layer])
            elif kind == "p2":
                table = self.per_set("p2", ["q3_p2_low_L%d.txt" % layer] + parts)
            elif kind == "p3":
                table = self.per_set("p3", triples)
            else:
                raise ValueError(kind)
            self.cache[key] = table
        return self.cache[key]


RE_SAMPLES = re.compile(r"^samples (\d+), direct method (\d+), disagreements between the two methods (\d+), full enumeration not done (\d+)$")
RE_FORMULA = re.compile(r"^formula tested (\d+) mismatches (\d+) overlap mismatches (\d+)$")
RE_KLINE = re.compile(r"^k (\d+) samples (\d+) max split (\d+) max unsplit (\d+)$")
RE_LOST = re.compile(r"^\s+lost position \S+ : representations (\d+),")
RE_TRIPLES = re.compile(r"^triples with two signs lost \(split and unsplit\) (\d+)$")


def empty_scan():
    return {"samples": 0, "direct": 0, "disagree": 0, "notdone": 0, "formula": 0, "mism": 0,
            "overlap": 0, "triples": 0, "lost": Counter(), "kmax": {}}


def add_scan(a, b):
    out = empty_scan()
    for key in ("samples", "direct", "disagree", "notdone", "formula", "mism", "overlap", "triples"):
        out[key] = a[key] + b[key]
    out["lost"] = a["lost"] + b["lost"]
    out["kmax"] = dict(a["kmax"])
    for k, v in b["kmax"].items():
        out["kmax"][k] = max(out["kmax"].get(k, 0), v)
    return out


def scan(logs, names):
    s = empty_scan()
    for name in names:
        with open(logs / name, encoding="utf-8", errors="replace") as handle:
            for line in handle:
                line = line.rstrip("\n")
                m = RE_SAMPLES.match(line)
                if m:
                    s["samples"] += int(m.group(1))
                    s["direct"] += int(m.group(2))
                    s["disagree"] += int(m.group(3))
                    s["notdone"] += int(m.group(4))
                m = RE_FORMULA.match(line)
                if m:
                    s["formula"] += int(m.group(1))
                    s["mism"] += int(m.group(2))
                    s["overlap"] += int(m.group(3))
                m = RE_KLINE.match(line)
                if m:
                    k = int(m.group(1))
                    s["kmax"][k] = max(s["kmax"].get(k, 0), int(m.group(3)), int(m.group(4)))
                m = RE_LOST.match(line)
                if m:
                    s["lost"][int(m.group(1))] += 1
                m = RE_TRIPLES.match(line)
                if m:
                    s["triples"] += int(m.group(1))
    return s


def author(form, k, p, anti):
    """The bound of the text of iis:2611.00054 for one case."""
    if form == "split":
        if k <= 30:
            return 12
        if k == 32:
            return 15
        if k == 34:
            return 12 if anti else 13
        if k == 36:
            return (14 if p == 0 else 12) if anti else 15
        if k == 38:
            return 14 if (anti or p <= 1) else 15
        if k == 42:
            return 15 if anti else 12
        return 15
    if k <= 32:
        return 12
    if k == 34:
        return 9 if p == 0 else 12 + p
    if k in (36, 38):
        return 15
    if k in (40, 42):
        return 14
    if k == 44:
        return 13
    if k == 46:
        return 15 if p == 3 else 14
    return 15


def talk_messages(path):
    """The messages of the saved discussion page: (author, text)."""
    out = []
    t = read(path)
    for m in re.finditer(r'<div class="msg__b">', t):
        start = m.start()
        nxt = t.find('<div class="msg__b">', start + 10)
        block = t[start: nxt if nxt > 0 else len(t)]
        if '<div class="prose msg__x">' not in block:
            continue
        who = re.search(r'<a href="/agents/([^"]+)"><b>', block)
        body = block.split('<div class="prose msg__x">', 1)[1].split("</article>", 1)[0]
        body = re.sub(r"<br\s*/?>", "\n", body)
        body = re.sub(r"</(p|li|div|pre|h\d)>", "\n", body)
        body = html.unescape(re.sub(r"<[^>]+>", "", body))
        out.append((who.group(1) if who else "", re.sub(r"\s+", " ", body).strip()))
    return out


# (label, source, quotation, check, result).  The source is ("body", file) or ("talk", first words).
# The check is None, ("rows", kind, budget), ("pairs", kind, budget), ("other", kind, budget) or
# ("max", kind, budgets).
QUOTES = [
    ("Report iis:2611.00034, dual masks, budget 37", ("body", "iis_2611.00034.md"),
     "solo budget 37 depths 1–4: 308,45738,41580,0.", ("rows", "dual", 37), None),
    ("Report iis:2611.00034, intact cap, budget 39", ("body", "iis_2611.00034.md"),
     "Intact budget 39, depths 1–4: 308,47278,847980,0.", ("rows", "intact", 39), None),
    ("Report iis:2611.00034, two punctures, budget 35", ("body", "iis_2611.00034.md"),
     "308,45738,10716,0 (280 pairs) or 308,45738,10998,0 (1260 pairs)", ("pairs", "p2", 35), None),
    ("Report iis:2611.00016, intact cap, budget 40", ("body", "iis_2611.00016.md"),
     "For A at budget 40 the counts at depths 1–7 are 308,47278,2105460,71190,16884,2814,0.", ("rows", "intact", 40), None),
    ("Report iis:2611.00016, dual masks, budget 36", ("body", "iis_2611.00016.md"),
     "For each of A,B at budget 36 they are 308,45738,4620,0.", ("rows", "dual", 36), None),
    ("Report iis:2611.00018, intact cap, budget 42", ("body", "iis_2611.00018.md"),
     "A counts through depth 7 at 42: 308,47278,3763620,4061190,42084,2814,0.", ("rows", "intact", 42), None),
    ("Report iis:2611.00018, one puncture, budget 37", ("body", "iis_2611.00018.md"),
     "Each of the 56 punctures of B had 308,46783,429330,900,0 through depth 5 at 37.", ("rows", "p1w", 37), None),
    ("Message M-49, two punctures, budget 36", ("talk", "Three punctures, partial"),
     "(308,46441,71284,78,0) for 1260 projective pairs and (308,46441,74088,0,0) for 280", ("pairs", "p2", 36), None),
    ("Message M-50, dual masks, budget 43", ("talk", "Three-puncture progress"),
     "308,47278,4227300,14524230,1125684,14574,0", ("rows", "dual", 43), None),
    ("Message M-50, intact cap, budget 43", ("talk", "Three-puncture progress"),
     "308,47278,4217220,15552390,757764,9534,0", ("rows", "intact", 43), None),
    ("Message M-50, one puncture, budget 42", ("talk", "Three-puncture progress"),
     "308,47278,4250130,26175870,4217712,196044,16350,1080,120,0", ("rows", "p1w", 42), None),
    ("Message M-51, one puncture, budget 41", ("talk", "(111,110,16) progress"),
     "308,47278,3744480,7531500,360522,7134,0", ("rows", "p1w", 41), None),
    ("Message M-52, two punctures, budget 37", ("talk", "Completion of the (111,110,16) exclusion"),
     "308,47125,283416,648,0,0; the other 1260 have 308,47125,284272,502,16,0", ("other", "p2", 37), None),
    ("Message M-56, three punctures, budgets 34, 35 and 36", ("talk", "Extendible-109 branch completed"),
     "Per-depth maxima B=34: 308,44007,8148,5,0,0; B=35: 308,46210,42030,141,3,0; B=36: 308,46923,176476,834,27,0.", ("max", "p3", (34, 35, 36)), None),
    ("Report iis:2611.00054, Lemma 1", ("body", "iis_2611.00054.md"),
     "For nonzero z the intact ordered sum multiplicity is N=16−k/2+4i+3h, and N(0)=k.", None,
     "Lemma 1 in Section 7 gives the same formula."),
    ("Report iis:2611.00054, the result", ("body", "iis_2611.00054.md"),
     "Every branch leaves fewer than 16 positions.", None,
     "The model in Section 8 gives at most 15 free positions in each case."),
    ("Report iis:2611.00054, the old directions", ("body", "iis_2611.00054.md"),
     "there are ≤6 old projective directions (.00016)", None,
     "Rule 4 in Section 7 gives the same bound of 6 old directions."),
    ("Report iis:2611.00054, the sentence of note (a)", ("body", "iis_2611.00054.md"),
     "hence are external to A and use ≤6 more directions by the dual test", None,
     "My dual table gives 3 directions at the budgets 39 and 38."),
    ("Report iis:2611.00054, the sentence of note (b)", ("body", "iis_2611.00054.md"),
     "Otherwise every internal triple needs at least one shared hit and thus there are ≤p such positions: ≤12+p.", None,
     "A triple can be free only for p=0."),
    ("Report iis:2611.00054, the sentence of note (c)", ("body", "iis_2611.00054.md"),
     "old S-internal holes must be A-external, i=1,h=0, dual budget 33 permits three directions.", None,
     "An old hole has h=1 at k=46, and the dual table at budget 33 gives 2 directions."),
    ("Report iis:2611.00054, the sentence of note (d)", ("body", "iis_2611.00054.md"),
     "again give ≤4+8+3", None,
     "The model gives at most 11 positions for the unsplit form from k=48."),
    ("Message M-55, a sign fact", ("talk", "Solo follow-up, profile (112,109,16)"),
     "a shared deleted endpoint a can hit z ONLY at z=−a", None,
     "Rule 7 in Section 7 states this fact for the positions of group X."),
]

RE_UPLOAD = re.compile(r"=== (\S+)\nHTTP (\d+)\nlocal sha256 ([0-9a-f]{64}); local bytes (\d+)\n\{\n  \"sha256\": \"([0-9a-f]{64})\",\n  \"name\": \"(\S+)\",\n  \"size\": (\d+),\n  \"url\": \"(\S+)\",")

FILES = ["q3_check.c", "q3_crosscheck.py", "collect_tables.py", "run_all.sh", "run_tables.sh",
         "run_replay_check16.sh", "q3_third.py", "run_third.sh", "q3_third_collect.py",
         "q3_tables_py.py", "q3_tables_py_rev1.py", "run_tables_py.sh", "run_tables_py_dual.sh",
         "q3_search_collect.py", "q3_target.py", "q3_target_select.py", "q3_target_collect.py",
         "run_target.sh", "run_tight.sh", "q3_p2_low_summary.py", "q3_cases.py", "run_cases.sh",
         "q3_signtest.py", "run_signtest.sh", "q3_masks_summary.py", "run_masks_test.sh",
         "run_target_climbs.sh", "run_crosscheck.sh", "run_p2_low.sh", "run_search_collect.sh",
         "make_q3_logs_file.py", "make_q3_body.py", "q3_logs_q0003.txt"]
# The path of each uploaded file in the workspace: work/capset/q0003/NAME, or a path in SOURCE_PATH.
SOURCE_PATH = {"make_q3_body.py": "../make_q3_body.py", "make_q3_logs_file.py": "../make_q3_logs_file.py"}


def main(argv):
    if len(argv) != 7:
        print(__doc__)
        return 2
    q3, parts, bodies, talk, upload_log, out = (Path(a) for a in argv[1:])
    logs = q3 / "logs"
    tables = Tables(logs)
    fill = {}
    layer_tables = {(layer, kind): tables.load(layer, kind) for layer in (0, 1) for kind in KINDS}

    # A. The hashes of the source, the binary and the file of the 236-cap.
    run = read(logs / "q3_all_run.log")
    hashes = {}
    for key in ("source", "binary", "dump236"):
        m = one(run, r"^%s sha256 ([0-9a-f]{64})$" % key, "q3_all_run.log")
        if m:
            hashes[key] = m.group(1)
    if "source" in hashes:
        need(sha(q3 / "q3_check.c") == hashes["source"], "q3_check.c is not the source of the main run")
    if "binary" in hashes:
        need(sha(q3 / "q3_check") == hashes["binary"], "q3_check is not the binary of the main run")
    for name in ("q3_tables_run.log", "q3_target_run.log", "q3_tight_run.log", "q3_p2_low_run.log", "q3_masks_test.log"):
        m = one(read(logs / name), r"^binary sha256 ([0-9a-f]{64})$", name)
        if m and "binary" in hashes:
            need(m.group(1) == hashes["binary"], "%s names a different binary" % name)
    need("dump236 is identical to work/capset/cap236.txt" in run, "the main run does not confirm the file of the 236-cap")
    fill["BINARY_HASH"] = hashes.get("binary", "?")
    fill["DUMP_HASH"] = hashes.get("dump236", "?")

    facts = read(logs / "q3_facts.log")
    for line in ("layer %d size 112", "points with the negative in the cap: 112 of 112", "collinear triples in the cap: 0",
                 "spectrum: value 4 count 616, value -23 count 112, other count 0",
                 "set where the transform of D takes value -23: size 112, vectors that differ from the cap: 0",
                 "internal directions: D vectors perpendicular to z: 22 x112",
                 "internal directions: ordered pairs of cap points with sum z: 1 x112",
                 "external directions: D vectors perpendicular to z: 40 x616",
                 "external directions: ordered pairs of cap points with sum z: 20 x616",
                 "external projective directions: 308, edge count histogram: 10 x308"):
        count = sum(facts.count(((line % layer) if "%d" in line else line) + "\n") for layer in ((0, 1) if "%d" in line else (0,)))
        need(count == 2, "the facts log does not give the line %r for the two caps" % line)

    # B. The replay of check16.py.
    replay = read(logs / "replay_check16.log")
    body54 = read(bodies / "iis_2611.00054.md")
    m = one(replay, r"^source sha256 ([0-9a-f]{64})$", "replay_check16.log")
    replay_hash = m.group(1) if m else "?"
    need(replay_hash in body54, "the text of iis:2611.00054 does not give the hash of check16.py")
    need("exit code 0" in replay, "the replay did not end with exit code 0")
    m = one(replay, r"^real ([0-9,]+)$", "replay_check16.log")
    fill["REPLAY_TIME"] = m.group(1).replace(",", ".") if m else "?"
    fill["REPLAY_HASH"] = replay_hash
    kind_of = {"dual": "dual", "0": "intact", "1": "p1wm", "2": "p2", "3": "p3"}
    theirs = {}
    for line in replay.splitlines():
        m = re.match(r"^(\S+) (\d+) (\[.*\])$", line)
        if m and m.group(1) in kind_of:
            theirs[(kind_of[m.group(1)], int(m.group(2)))] = Counter({trimmed(t): c for t, c in ast.literal_eval(m.group(3))})
    need(len(theirs) == 17, "the replay has %d rows, not 17" % len(theirs))
    need(Counter(kind for kind, b in theirs) == Counter({"dual": 3, "intact": 3, "p1wm": 5, "p2": 3, "p3": 3}),
         "the kinds of the rows of the replay are not 3, 3, 5, 3, 3")
    replay_comp = replay_diff = 0
    for (kind, b), counter in sorted(theirs.items()):
        for layer in (0, 1):
            replay_comp += 1
            mine = Counter(trimmed(r) for r in layer_tables[(layer, kind)].get(b, {}).values())
            if mine != counter:
                replay_diff += 1
                fail("replay: kind %s, budget %d, cap %d: my rows are not the rows of check16.py" % (kind, b, layer))
    fill["REPLAY_ROWS"] = len(theirs)
    fill["REPLAY_COMPARISONS"] = replay_comp
    fill["REPLAY_DIFF"] = replay_diff

    # C. The tables on the two caps.
    two_comp = two_diff = 0
    for kind in KINDS:
        t0, t1 = layer_tables[(0, kind)], layer_tables[(1, kind)]
        need(set(t0) == set(t1), "kind %s: the budgets are not the same on the two caps" % kind)
        for b in sorted(set(t0) | set(t1)):
            counters = []
            for layer in (0, 1):
                sets = layer_tables[(layer, kind)].get(b, {})
                need(len(sets) == EXPECTED[kind], "kind %s: budget %d on cap %d has %d puncture sets, not %d" % (kind, b, layer, len(sets), EXPECTED[kind]))
                counters.append(Counter(trimmed(r) for r in sets.values()))
            two_comp += 1
            if counters[0] != counters[1]:
                two_diff += 1
                fail("kind %s: the rows at budget %d are not the same on the two caps" % (kind, b))
    for layer in (0, 1):
        for b, sets in layer_tables[(layer, "p1wm")].items():
            for index, row in sets.items():
                need(layer_tables[(layer, "p1w")].get(b, {}).get(index) == row,
                     "one puncture, cap %d, budget %d: the main log and the full log are not the same" % (layer, b))
    fill["TWO_CAPS_COMPARISONS"] = two_comp
    fill["TWO_CAPS_DIFF"] = two_diff

    kinds2 = [("Intact cap", "no puncture", "intact"), ("Dual mask", "no erasure", "dual"),
              ("One puncture", "weak rule", "p1w"), ("One puncture", "strict rule (`p1s`)", "p1s"),
              ("Two punctures", "strict rule", "p2"), ("Three punctures", "strict rule", "p3")]
    lines = []
    for name, rule, kind in kinds2:
        t = layer_tables[(0, kind)]
        cells = ", ".join("%d:%d" % (b, longest(t[b].values())) for b in sorted(t))
        rows = max(len(Counter(trimmed(r) for r in sets.values())) for sets in t.values())
        lines.append("| %s | %s | %s | %d | %d |" % (name, rule, cells, rows, EXPECTED[kind]))
    fill["TABLE_TABLES"] = "\n".join(lines)

    amap = {"dual": "dual", "intact endpoints": "intact", "one puncture": "p1wm", "two": "p2", "three": "p3"}
    numbers = []
    for m in re.finditer(r"(?m)^- (dual|intact endpoints|one puncture|two|three): ((?:\d+:\d+,? ?)+)[;.]$", body54):
        for b, n in re.findall(r"(\d+):(\d+)", m.group(2)):
            numbers.append((amap[m.group(1)], int(b), int(n)))
    need(len(numbers) == 17, "the text of iis:2611.00054 gives %d numbers in the five lists, not 17" % len(numbers))
    disagree = 0
    for kind, b, n in numbers:
        t = layer_tables[(0, kind)]
        if b not in t or longest(t[b].values()) != n:
            disagree += 1
            fail("the number of the author %s %d:%d is not in my tables" % (kind, b, n))
    fill["N_AUTHOR"] = len(numbers)
    fill["N_DISAGREE"] = disagree

    # D. The table of two punctures by index.
    p2_0, p2_1 = layer_tables[(0, "p2")], layer_tables[(1, "p2")]
    by_budget = {b: sum(1 for i, r in p2_0[b].items() if p2_1[b].get(i) != r) for b in p2_0}
    need(sorted(by_budget) == list(range(30, 39)), "the budgets of the table of two punctures are not 30 to 38")
    low, high = [by_budget[b] for b in range(30, 34)], [by_budget[b] for b in range(34, 39)]
    low_run = read(logs / "q3_p2_low_run.log")
    for b in range(30, 34):
        m = re.search(r"^budget %d : .* : sets with the same row on the two layers (\d+) of 1540$" % b, low_run, re.M)
        if m:
            need(1540 - int(m.group(1)) == by_budget[b], "the summary of the low budgets gives another number at budget %d" % b)
        else:
            fail("the log of the low budgets has no line for budget %d" % b)
    # The scripts run_p2_low.sh and run_search_collect.sh were written after the first run of
    # their commands.  The directory logs_before holds the files of the first runs.
    before = q3 / "logs_before"
    first_run = read(logs / "q3_p2_low_run_first.log")
    keep = lambda t: [l for l in t.splitlines() if not re.match(r"^(start |end |real |user |sys )", l)]
    need(first_run and keep(first_run) == keep(low_run), "the first run of the low budgets and the run with the script do not have the same lines")
    for layer in (0, 1):
        need(read(before / ("q3_p2_low_L%d.txt" % layer)) == read(logs / ("q3_p2_low_L%d.txt" % layer)),
             "the table of the low budgets of cap %d is not the same in the two runs" % layer)
    need(read(before / "q3_search_collected.log") == read(logs / "q3_search_collected.log"),
         "the collection of the direct tests is not the same in the two runs")
    for name in ("q3_crosscheck_L0.log", "q3_crosscheck_L1.log", "q3_target_crosscheck_L0.log", "q3_target_crosscheck_L1.log"):
        need(read(before / name) == read(logs / name), "the crosscheck log %s is not the same in the two runs" % name)
    target_before = q3 / "target_before"
    for layer in (0, 1):
        for seed in (1, 2, 3, 4):
            for ext in ("txt", "log"):
                name = "target_L%d_S%d.%s" % (layer, seed, ext)
                need(read(target_before / name) == read(q3 / "target" / name), "the file %s of the climbs is not the same in the two runs" % name)
    def span(values):
        lo, hi = min(values), max(values)
        return "%d at each budget" % lo if lo == hi else "from %d to %d" % (lo, hi)
    fill["P2_LOW_RANGE"] = span(low)
    fill["P2_HIGH_RANGE"] = span(high)
    rows37 = Counter(trimmed(r) for r in p2_0[37].values())
    need(sorted((longest([r]), c) for r, c in rows37.items()) == [(4, 280), (5, 1260)],
         "the rows at budget 37 for two punctures are not 280 pairs with 4 directions and 1260 pairs with 5 directions")

    # E. The Python program for the tables.
    py = read(logs / "q3_tables_py_collected.log")
    sym = []
    for layer in (0, 1):
        m = one(py, r"^layer %d: (\d+) signed permutation matrices preserve the cap, (\d+) with an odd number of sign changes, (\d+) different permutations of the classes$" % layer,
               "q3_tables_py_collected.log")
        if m:
            sym.append(tuple(int(x) for x in m.groups()))
    if len(sym) == 2:
        need(sym[0] == sym[1], "the symmetries of the two caps are not the same")
        fill["NSYM"], fill["NODD"], fill["NCLS"] = sym[0]
    else:
        fill["NSYM"] = fill["NODD"] = fill["NCLS"] = "?"
    blocks = []
    for line in py.splitlines():
        f = [x.strip() for x in line.split(" : ")]
        if len(f) == 9 and f[0] in ("0", "1") and f[1] in KINDS and f[3].isdigit():
            blocks.append((int(f[0]), f[1], f[2]) + tuple(int(x) for x in f[3:]))
    need(len(blocks) == 14, "the Python tables log has %d block lines, not 14" % len(blocks))
    for layer, kind, mode, done, sets_done, sets_expected, same, diff, all_sets in blocks:
        need(sets_done == sets_expected, "python tables, cap %d, kind %s: %d sets of %d are done" % (layer, kind, sets_done, sets_expected))
        need(same + diff == done, "python tables, cap %d, kind %s: %d + %d is not %d" % (layer, kind, same, diff, done))
        need(all_sets == EXPECTED[kind], "python tables, cap %d, kind %s: %d puncture sets of the kind, not %d" % (layer, kind, all_sets, EXPECTED[kind]))
    m = one(py, r"^python tables: logs (\d+), complete logs (\d+), incomplete logs (\d+), parts (\d+), work items (\d+) of (\d+), sets (\d+) of (\d+), table rows (\d+), rows same as q3_check (\d+), rows different (\d+), seconds of the longest complete part (\d+), problems (\d+)$",
           "q3_tables_py_collected.log")
    if m:
        g = [int(x) for x in m.groups()]
        need(g[0] == g[1] and g[2] == 0 and g[12] == 0, "the summary of the Python tables is not complete")
        need(g[4] == g[5] == sum(b[3] for b in blocks), "the work items of the summary are not the sum of the blocks")
        need(g[6] == g[7] == sum(b[4] for b in blocks), "the sets of the summary (%d, %d) are not the sum of the blocks (%d)" % (g[6], g[7], sum(b[4] for b in blocks)))
        need(g[8] == g[9] and g[10] == 0, "the summary of the Python tables has rows that are different")
        py_sum = g
    else:
        py_sum = None
    # The logs of the 12 parts: each row is one puncture set and one budget.
    re_part = re.compile(r"^python tables part (\d+) of (\d+): items (\d+), sets (\d+), table rows (\d+), rows same as q3_check (\d+), rows different (\d+), orbits with one row in q3_check (\d+), seconds (\d+)$", re.M)
    run1, run2 = read(logs / "q3_tables_py_run.log"), read(logs / "q3_tables_py_run2.log")
    m = re.search(r"^script sha256 ([0-9a-f]{64})$", run1, re.M)
    rev1 = sha(q3 / "q3_tables_py_rev1.py")
    if m:
        need(m.group(1) == rev1, "q3_tables_py_rev1.py is not the script of the first run")
    m = re.search(r"^script sha256 ([0-9a-f]{64})$", run2, re.M)
    if m:
        need(m.group(1) == sha(q3 / "q3_tables_py.py"), "q3_tables_py.py is not the script of the second run")
    m = re.search(r"^revision 1 sha256 ([0-9a-f]{64})$", run2, re.M)
    if m:
        need(m.group(1) == rev1, "the second run names another revision 1")
    need("collect exit 0" in run2, "the collection of the second run did not end with exit code 0")
    start1 = re.search(r"^start (\S+)$", run1, re.M)
    start2 = re.search(r"^start (\S+)$", run2, re.M)
    part_sum = [0, 0, 0, 0]
    orbits = 0
    for i in range(12):
        text = read(logs / ("q3_tables_py_P%d.log" % i))
        m = re_part.search(text)
        need(m is not None and int(m.group(1)) == i and int(m.group(2)) == 12, "the log of part %d has no final line of part %d of 12" % (i, i))
        need(re.search(r"^exit 0$", text, re.M) is not None, "the log of part %d has no exit code 0" % i)
        start = re.search(r"^start (\S+)$", text, re.M)
        need(start is not None and start.group(1) == (start2.group(1) if start2 and i in (2, 3) else start1.group(1) if start1 else ""),
             "the log of part %d does not come from the expected run" % i)
        row_lines = [l for l in text.splitlines() if l.startswith("ROW ")]
        need(all(l.endswith("same as q3_check True") for l in row_lines), "part %d has a puncture set with a row that is different" % i)
        budgets = sum(len(re.findall(r" : (\d+): ", l)) for l in row_lines)
        if m:
            need(len(row_lines) == int(m.group(3)) and budgets == int(m.group(5)) and int(m.group(6)) + int(m.group(7)) == int(m.group(5)),
                 "the final line of part %d is not the sum of its rows" % i)
            for j in range(4):
                part_sum[j] += int(m.group(3 + j))
            orbits += int(m.group(8))
    need(orbits == sum(b[3] for b in blocks if b[2] == "orbits"), "the orbits with one row (%d) are not the %d representatives of the mode orbits" % (orbits, sum(b[3] for b in blocks if b[2] == "orbits")))
    fill["PY_ORBITS"] = orbits
    need(py_sum is not None and part_sum == py_sum[4:5] + py_sum[6:7] + py_sum[8:10], "the summary of the Python tables is not the sum of the 12 parts")
    if py_sum is not None:
        fill["PY_ITEMS"], fill["PY_SETS"], fill["PY_ROWS"] = part_sum[0], part_sum[1], part_sum[2]
        fill["PY_SAME"], fill["PY_DIFF"] = part_sum[3], py_sum[10]
    else:
        for key in ("PY_ITEMS", "PY_SETS", "PY_ROWS", "PY_SAME", "PY_DIFF"):
            fill[key] = "?"
    names3 = {"dual": "Dual mask", "intact": "Intact cap", "p1s": "One puncture, strict rule",
              "p1w": "One puncture, weak rule", "p2": "Two punctures", "p3": "Three punctures"}
    modes3 = {"all": "all sets", "orbits": "one set of each orbit"}
    fill["TABLE_PY"] = "\n".join("| %d | %s | %s | %d | %d | %d | %d |" % (b[0], names3[b[1]], modes3[b[2]], b[3], b[8], b[6], b[7]) for b in blocks)
    need(modes3.keys() == {b[2] for b in blocks}, "the Python tables log has a mode that I do not know")

    # F. The direct tests of the C program.
    both = lambda pattern: [pattern % layer for layer in (0, 1)]
    groups = {
        "climb": both("q3_climb_L%d.log"), "hunt": both("q3_hunt_L%d.log"), "mono": both("q3_mono_L%d.log"),
        "cross": both("q3_cross_L%d.log"),
        "one": both("q3_one_identity_L%d.log") + both("q3_one_overlap0_L%d.log"),
        "target": both("q3_target_L%d.log"), "tight": both("q3_tight_L%d.log"),
        "pairs": ["q3_pairs_L%d_S%d.log" % (layer, seed) for layer in (0, 1) for seed in (5, 6, 7)],
    }
    scanned = {name: scan(logs, names) for name, names in groups.items()}
    total = empty_scan()
    for s in scanned.values():
        total = add_scan(total, s)
    climb = add_scan(scanned["climb"], scanned["hunt"])
    fill["CLIMB_SAMPLES"] = climb["samples"]
    fill["CLIMB_FAILURES"] = climb["disagree"] + climb["notdone"]
    fill["CLIMB_FORMULA"] = climb["formula"]
    fill["CLIMB_MAX"] = max(climb["kmax"].values())
    pairs = scanned["pairs"]
    fill["PAIRS_SAMPLES"] = pairs["samples"]
    fill["PAIRS_FAILURES"] = pairs["disagree"] + pairs["notdone"]
    fill["PAIRS_MAX"] = max(pairs["kmax"].values())
    need(min(pairs["kmax"]) >= 26, "the logs of the random matrices have a sample with an overlap below 26")
    search = read(logs / "q3_search_collected.log")
    search_logs = groups["climb"] + groups["pairs"] + groups["hunt"]
    seen = set()
    for line in search.splitlines():
        f = [x.strip() for x in line.split(" : ")]
        if len(f) == 14 and f[0] in search_logs and f[1].isdigit():
            seen.add(f[0])
            s = scan(logs, [f[0]])
            need(int(f[1]) == s["samples"] and int(f[3]) == s["formula"] and int(f[11]) == max(s["kmax"].values() or [0]),
                 "the search log %s is not the same as the raw log" % f[0])
    need(seen == set(search_logs), "the search log does not have the ten lines of the climb, random matrix and hunt logs")
    m = one(search, r"^logs (\d+), samples (\d+), failures (\d+)$", "q3_search_collected.log")
    if m:
        need(int(m.group(1)) == len(search_logs) and int(m.group(2)) == climb["samples"] + pairs["samples"] and int(m.group(3)) == 0,
             "the last line of the collection of the direct tests is not the sum of its lines")
    fill["MONO_SAMPLES"] = scanned["mono"]["samples"]
    fill["MONO_MAX"] = max(scanned["mono"]["kmax"].values())
    fill["CROSS_SAMPLES"] = scanned["cross"]["samples"]
    fill["CROSS_MAX"] = max(scanned["cross"]["kmax"].values())
    need(set(scanned["cross"]["kmax"]) == {32}, "the cross test does not have the overlap 32 only")
    need(set(scanned["cross"]["lost"]) <= {0}, "the cross test has a lost position with a representation")
    fill["CROSS_K"] = 32
    fill["ONE_SAMPLES"] = scanned["one"]["samples"]
    fill["ONE_MAX"] = max(scanned["one"]["kmax"].values())
    need(sorted(scanned["one"]["kmax"].items()) == [(0, 1), (112, 3)], "the tests of the identity map do not give 1 position at k=0 and 3 at k=112")
    for key, name in (("TARGET", "target"), ("TIGHT", "tight")):
        text = read(logs / ("q3_%s_collected.log" % name))
        rows = {}
        for line in text.splitlines():
            f = [x.strip() for x in line.split(" : ")]
            if len(f) == 14 and f[0].isdigit():
                rows[int(f[0])] = (int(f[1]), int(f[12]))
        m = one(text, r"^matrices (\d+), matrices that do not satisfy a rule (\d+)$", "q3_%s_collected.log" % name)
        if m and rows:
            count, bad = int(m.group(1)), int(m.group(2))
            need(count == sum(r[0] for r in rows.values()), "the %s log: the number of matrices is not the sum of the table" % name)
            most = max(r[1] for r in rows.values())
            ks = sorted(k for k, r in rows.items() if r[1] == most)
            need(count == scanned[name]["samples"] and most == max(scanned[name]["kmax"].values()), "the %s log and the raw %s logs are not the same" % (name, name))
            fill[key + "_MATRICES"], fill[key + "_BAD"], fill[key + "_MAX"] = count, bad, most
            if key == "TARGET":
                need(ks == [32], "the selected matrices do not have the largest number of free positions at k=32 only")
                fill["TARGET_K"] = ", ".join(str(k) for k in ks) if most else "none"
        else:
            for suffix in ("_MATRICES", "_BAD", "_MAX", "_K"):
                fill[key + suffix] = "?"
    for layer in (0, 1):
        sign_name = "q3_signtest_L%d.log" % layer
        text = read(logs / sign_name)
        m = one(text, r"^layer %d, matrices tested (\d+), puncture sets tested (\d+)$" % layer, sign_name)
        if m:
            fill["SIGN_MATRICES"] = fill.get("SIGN_MATRICES", 0) + int(m.group(1))
            fill["SIGN_SETS"] = fill.get("SIGN_SETS", 0) + int(m.group(2))
        m = one(text, r"^violations: S1 (\d+), S2 (\d+), S3 (\d+)$", "q3_signtest_L%d.log" % layer)
        if m:
            fill["SIGN_VIOL"] = fill.get("SIGN_VIOL", 0) + sum(int(x) for x in m.groups())
        m = one(text, r"^model violations: (\d+)$", "q3_signtest_L%d.log" % layer)
        if m:
            fill["SIGN_MODEL"] = fill.get("SIGN_MODEL", 0) + int(m.group(1))
        m = one(text, r"^largest direct count with an antipodal pair: (\d+)$", "q3_signtest_L%d.log" % layer)
        if m:
            fill["SIGN_MAX"] = max(fill.get("SIGN_MAX", 0), int(m.group(1)))
    sign_run = read(logs / "q3_signtest_run.log")
    m = one(sign_run, r"^script sha256 ([0-9a-f]{64})$", "q3_signtest_run.log")
    if m:
        need(m.group(1) == sha(q3 / "q3_signtest.py"), "q3_signtest.py is not the script of the sign test")
    m = one(sign_run, r"^model log sha256 ([0-9a-f]{64})$", "q3_signtest_run.log")
    if m:
        need(m.group(1) == sha(logs / "q3_cases.log"), "the model log of the sign test is not the model log")
    fill["FORMULA_TESTED"] = total["formula"]
    fill["FORMULA_MISMATCH"] = total["mism"]
    fill["OVERLAP_MISMATCH"] = total["overlap"]
    fill["SAMPLES_TOTAL"] = total["samples"]
    need(total["disagree"] == 0 and total["notdone"] == 0, "the two methods of the C program do not agree in all samples")
    need(total["mism"] == 0 and total["overlap"] == 0, "a mismatch of the formula or of the overlap")
    need(total["triples"] == 0, "a triple loses two signs")
    maxpos = max(total["kmax"].values())
    fill["MAX_POSITIONS"] = maxpos
    need([k for k, v in total["kmax"].items() if v == maxpos] == [32], "the largest number of free positions is not at k=32 only")
    need(fill.get("SIGN_MAX", 0) <= maxpos, "the sign test has more free positions than the direct tests")

    crosscheck = 0
    for name in ("q3_crosscheck_L0.log", "q3_crosscheck_L1.log", "q3_target_crosscheck_L0.log", "q3_target_crosscheck_L1.log"):
        text = read(logs / name)
        lines = [l for l in text.splitlines() if l.startswith("matrix ")]
        m = one(text, r"^matrices (\d+), matrices with the same four numbers (\d+)$", name)
        need(lines and all(l.endswith("agree True") for l in lines), "%s has a matrix where the two programs do not agree" % name)
        if m:
            need(int(m.group(1)) == int(m.group(2)) == len(lines), "%s: the last line is not the number of the matrix lines" % name)
        crosscheck += len(lines)
    fill["CROSSCHECK"] = crosscheck

    # G. The two solvers.
    third = read(logs / "q3_third_collected.log")
    solver_rows = re.findall(r"^(z3|highs) : both layers : instances (\d+), test 1 found (\d+), test 2 proved (\d+), agree (\d+), no decision (\d+), disagree (\d+)$", third, re.M)
    need(sorted(r[0] for r in solver_rows) == ["highs", "z3"], "the solver log has not one summary line for each solver")
    for solver, instances, found, proved, agree, none, disagree_s in solver_rows:
        need(int(proved) == 0 and int(disagree_s) == 0, "the solver %s proves a bound or disagrees" % solver)
        fill["SOLVER_INSTANCES"] = int(instances)
        fill["Z3_FOUND" if solver == "z3" else "HIGHS_FOUND"] = int(found)

    # H. The masks of two classes.
    masks = read(logs / "q3_masks_test.log")
    m = one(masks, r"^summary script sha256 ([0-9a-f]{64})$", "q3_masks_test.log")
    if m:
        need(m.group(1) == sha(q3 / "q3_masks_summary.py"), "q3_masks_summary.py is not the script of the mask test")
    mask_lines = []
    for line in masks.splitlines():
        m = re.match(r"^(.+): 308 directions; marks in one direction: (.+); total marks (\d+)$", line)
        if not m:
            continue
        pieces = re.findall(r"(\d+) in (\d+) directions", m.group(2))
        need(sum(int(a) * int(b) for a, b in pieces) == int(m.group(3)), "the mask %s: the total of marks is not the sum" % m.group(1))
        mask_lines.append((m.group(1), m.group(2), int(m.group(3))))
    need(len(mask_lines) == 6, "the mask test has %d masks, not 6" % len(mask_lines))
    need(all(masks.endswith(l + ": True\n") or (l + ": True\n") in masks for l in (
        "two classes (0,1) is a subset of one class 0, strict rule", "two classes (0,1) is a subset of one class 1, strict rule",
        "weak rule is a subset of the strict rule", "strict rule is a subset of the intact cap")), "a relation of the masks is not True")
    need("exit code 0" in masks, "the mask test did not end with exit code 0")
    fill["TABLE_MASKS"] = "\n".join("| %s | %s | %d |" % (name[0].upper() + name[1:], marks, total_marks) for name, marks, total_marks in mask_lines)

    # I. The model of the cases.
    model = read(logs / "q3_cases.log")
    m = one(model, r"^script sha256 ([0-9a-f]{64})$", "q3_cases.log")
    if m:
        need(m.group(1) == sha(q3 / "q3_cases.py"), "q3_cases.py is not the script of the model log")
    for tag, kind in (("T0", "intact"), ("D", "dual"), ("W", "p1w"), ("S", "p1s"), ("T2", "p2"), ("T3", "p3")):
        m = one(model, r"^table %s: (.+)$" % tag, "q3_cases.log")
        if m:
            t = layer_tables[(0, kind)]
            entries = {int(b): (int(n), int(s)) for b, n, s in re.findall(r"(\d+):(\d+)\((\d+) sets\)", m.group(1))}
            mine = {b: (longest(t[b].values()), len(t[b])) for b in sorted(layer_tables[(0, kind)])}
            need(entries == mine, "the table %s of the model is not my table for the kind %s" % (tag, kind))
    types = {}
    for m in re.finditer(r"^k (\d+): B (\d+), positions in no cap (.*?), positions internal to a cap (.*?), shared positions (.*)$", model, re.M):
        k, budget = int(m.group(1)), int(m.group(2))
        need(budget == 56 - k // 2, "the budget of k=%d is not 56-k/2" % k)
        types[k] = [re.findall(r"N=(\d+):h=(\d+)", m.group(i)) for i in (3, 4, 5)]
    need(sorted(types) == list(range(26, 113, 2)), "the model log has not one line of types for each even k from 26 to 112")
    for k, cells in types.items():
        need(all(int(n) > 0 for n, h in cells[2]), "a shared position has N=0 at k=%d" % k)
    fill["TABLE_TYPES"] = "\n".join("| %d | %s | %s | %s |" % (
        k, *(("; ".join("N=%s, h=%s" % (n, h) for n, h in cells) or "none") for cells in types[k])) for k in range(26, 65, 2))
    re_case = re.compile(r"^  (split|unsplit) k=(\d+) (.*): X directions <= (\S+), Y directions <= (\S+), dual <= (\d+), intact <= (\d+): positions <= (\d+)   \[(.*)\]$")
    re_label = re.compile(r"^U (not )?antipodal, (?:p=(\d+)|points in S: (.+?))(?:, b in A (\d))?$")
    in_s = {"none": 0, "u": 1, "the pair": 2, "all three": 3}
    cases = {}
    no_constraint = 0
    for line in model.splitlines():
        m = re_case.match(line)
        if not m:
            continue
        form, k = m.group(1), int(m.group(2))
        lm = re_label.match(m.group(3))
        if not lm:
            fail("a case line has a label that I do not know: %s" % m.group(3))
            continue
        anti = lm.group(1) is None
        p = int(lm.group(2)) if lm.group(2) is not None else in_s[lm.group(3)]
        w = int(lm.group(4) or 0)
        key = (form, k, p, anti, w)
        need(key not in cases, "the case %s is two times in the model log" % (key,))
        cases[key] = int(m.group(8))
        if m.group(4) == "none" or m.group(5) == "none":
            no_constraint += 1
    expected_keys = {(form, k, p, anti, w) for k in range(26, 113, 2) for form in ("split", "unsplit")
                     for anti in (False, True)
                     for p in range(0, (2 if anti else 3) if form == "split" else 4)
                     for w in (range(0, 2) if form == "split" else (0,))}
    need(set(cases) == expected_keys, "the model log has %d cases, not the %d expected cases" % (len(cases), len(expected_keys)))
    fill["N_CASES"] = len(cases)
    fill["N_NOCONSTRAINT"] = no_constraint
    summary = {"split": {}, "unsplit": {}}
    for form in summary:
        m = re.search(r"^  %s: (.+)$" % form, model, re.M)
        if m:
            summary[form] = {int(a): int(b) for a, b in re.findall(r"(\d+):(\d+)", m.group(1))}
        for k in range(26, 113, 2):
            need(summary[form].get(k) == max(v for (f, kk, p, a, w), v in cases.items() if f == form and kk == k),
                 "the summary of the %s form at k=%d is not the largest case" % (form, k))
    m = one(model, r"^largest count in all cases: (\d+)$", "q3_cases.log")
    model_max = max(cases.values())
    need(int(m.group(1)) == model_max, "the largest count of the model is not the largest case")
    fill["MODEL_MAX"] = model_max
    where = sorted(key for key, v in cases.items() if v == model_max)
    fill["MODEL_WHERE"] = "the %s form at $k=%d$, $U$ %s antipodal, $p=%d$%s" % (
        where[0][0], where[0][1], "not" if not where[0][3] else "", where[0][2], ", $b$ in $A$" if where[0][4] else "") if len(where) == 1 else "%d cases" % len(where)
    for key, value in cases.items():
        need(value <= author(*key[:2], key[2], key[3]), "the model gives %d for the case %s, the text of the author gives %d" % (value, key, author(key[0], key[1], key[2], key[3])))
    fill["MODEL_MAX_HIGH"] = max(v for form in summary for k, v in summary[form].items() if k >= 66)
    fill["MODEL_MAX_48"] = max(v for k, v in summary["unsplit"].items() if k >= 48)
    lines = []
    for k in range(26, 65, 2):
        cells = []

        def span(values):
            return str(values[0]) if min(values) == max(values) else "%d–%d" % (min(values), max(values))

        a_split = [author("split", k, p, anti) for anti in (False, True) for p in range(0, 2 if anti else 3)]
        a_unsplit = [author("unsplit", k, p, anti) for anti in (False, True) for p in range(0, 4)]
        for form, anti in (("split", False), ("split", True), ("unsplit", False), ("unsplit", True)):
            cells.append(span([v for (f, kk, p, a, w), v in cases.items() if f == form and kk == k and a == anti]))
        lines.append("| %d | %s | %s | %s | %s | %s | %s |" % (k, span(a_split), cells[0], cells[1], span(a_unsplit), cells[2], cells[3]))
    fill["TABLE_CASES"] = "\n".join(lines)

    # J. The quotations.
    sources = {}

    def source(spec):
        if spec[0] == "body":
            return read(bodies / spec[1])
        hits = [(who, text) for who, text in talk_messages(talk) if text.startswith(spec[1])]
        if len(hits) != 1:
            fail("the discussion page has %d messages that start with %r" % (len(hits), spec[1]))
            return ""
        need(hits[0][0] == "ExactMargin", "the author of the message %r is not ExactMargin" % spec[1])
        return hits[0][1]

    quote_diff = 0
    rendered = []
    for label, spec, quote, check, result in QUOTES:
        text = sources.setdefault(spec, source(spec))
        ok = quote in text
        if not ok:
            fail("the quotation is not in the text of %s: %s" % (label, quote))
        if check:
            kind = check[1]
            tuples = [trimmed(int(x) for x in t.split(",")) for t in re.findall(r"\d+(?:,\d+){2,}", quote)]
            for layer in (0, 1):
                table = layer_tables[(layer, kind)]
                if check[0] == "max":
                    need(len(tuples) == len(check[2]), "the quotation %s has not %d rows" % (label, len(check[2])))
                    for b, t in zip(check[2], tuples):
                        rows = list(table[b].values())
                        n = max(len(r) for r in rows)
                        top = trimmed(max((r[d] if d < len(r) else 0) for r in rows) for d in range(n))
                        if top != t:
                            ok = False
                elif check[0] == "rows":
                    b = check[2]
                    counter = Counter(trimmed(r) for r in table.get(b, {}).values())
                    if set(counter) != set(tuples):
                        ok = False
                else:
                    b = check[2]
                    counter = Counter(trimmed(r) for r in table.get(b, {}).values())
                    counts = []
                    for m in re.finditer(r"\d+(?:,\d+){2,}", quote):
                        after = quote[m.end(): m.end() + 24]
                        c = re.match(r"\)? for (\d+)", after) or re.match(r" \((\d+) pairs\)", after)
                        counts.append(int(c.group(1)) if c else None)
                    if check[0] == "other":
                        m = re.search(r"the other (\d+) have", quote)
                        second = int(m.group(1)) if m else -1
                        counts = [len(table.get(b, {})) - second, second]
                    if set(counter) != set(tuples) or len(counts) != len(tuples) or any(counter.get(t) != c for t, c in zip(tuples, counts)):
                        ok = False
        if not ok:
            quote_diff += 1
            fail("the quotation does not agree with my tables: %s" % label)
        rendered.append(('- %s: "%s" %s' % (label, quote, result or "")).rstrip())
    fill["N_QUOTES"] = len(QUOTES)
    fill["QUOTE_DIFF"] = quote_diff
    fill["QUOTES"] = "\n".join(rendered)

    # K. The uploaded files.
    table8 = []
    if Path(upload_log).exists():
        entries = RE_UPLOAD.findall(read(upload_log))
        need([e[5] for e in entries] == FILES, "the upload log has %d files and they are not the %d files of the list in order" % (len(entries), len(FILES)))
        for fname, status, local_sha, local_bytes, server_sha, name, size, url in entries:
            need(status == "201" and local_sha == server_sha and int(local_bytes) == int(size) and fname == name,
                 "the upload of %s is not complete" % fname)
            need(url == "https://isitsolved.com/files/%s/%s" % (server_sha, name), "the address of %s on the site does not contain its SHA-256" % fname)
            table8.append("| `%s` | `%s` |" % (name, local_sha[:16]))
    else:
        fail("the upload log %s is not found" % upload_log)
    fill["TABLE_FILES"] = "\n".join(table8) if table8 else "NO UPLOAD LOG"

    # L. The body.
    texts = [read(parts / ("q3_part%d.md" % i)) for i in (1, 2, 3, 4)]
    body = "\n\n".join(t.strip("\n") for t in texts) + "\n"
    names = sorted(set(re.findall(r"<<([A-Z0-9_]+)>>", body)))
    for name in names:
        if name not in fill:
            fail("no value for <<%s>>" % name)
        else:
            body = body.replace("<<%s>>" % name, str(fill[name]))
    for name in sorted(fill):
        if name not in names:
            fail("the value %s is not used in the parts" % name)
    if re.search(r"<<[^>]*>>", body):
        fail("a placeholder is left in the body")
    need("\n\n\n" not in body, "the body has two empty lines in a row")
    need(QUOTES[15][2] in texts[0], "part 1 does not have the quotation %r of the text of the author" % QUOTES[15][2])
    for quote in [q[2] for q in QUOTES[17:20]]:
        need(quote in texts[2], "part 3 does not have the quotation %r of the text of the author" % quote)
    need("≤4+8+3" in QUOTES[20][2] and "≤4+8+3" in texts[2], "part 3 does not have the bound of the text of the author")
    for name in sorted(fill):
        value = str(fill[name])
        if "?" in value or "NO UPLOAD" in value:
            fail("the value of %s is not known" % name)
    out.write_text(body, encoding="utf-8")
    values = {name: value for name, value in sorted(fill.items())
              if isinstance(value, int) or (isinstance(value, str) and len(value) <= 120)}
    Path(str(out) + ".values.json").write_text(json.dumps(values, indent=1) + "\n", encoding="utf-8")
    print("body chars %d; lines %d; placeholders filled %d; values %d"
          % (len(body), body.count("\n"), len(names), len(values)))
    for e in errors:
        print("ERROR: " + e)
    return 1 if errors else 0


if __name__ == "__main__":
    sys.exit(main(sys.argv))
