#!/usr/bin/env python3
import collections
import lzma
import sys


def open_formula(path):
    return lzma.open(path, "rt") if path.endswith(".xz") else open(path, "rt")


path = sys.argv[1]
nvars = 0
defined = set()
unit_first = collections.Counter()
occ = collections.Counter()
pos = collections.Counter()
neg = collections.Counter()
input_refs = collections.Counter()
with open_formula(path) as f:
    for line in f:
        if not line or line[0] == "c":
            continue
        if line[0] == "p":
            nvars = int(line.split()[2])
            continue
        xs = [int(x) for x in line.split()]
        if xs and xs[-1] == 0:
            xs.pop()
        if not xs:
            continue
        if len(xs) == 1:
            unit_first[abs(xs[0])] += 1
        else:
            defined.add(abs(xs[0]))
            for x in xs[1:]:
                input_refs[abs(x)] += 1
        for x in xs:
            occ[abs(x)] += 1
            if x > 0:
                pos[abs(x)] += 1
            else:
                neg[abs(x)] += 1

primary = [v for v in range(1, nvars + 1) if v not in defined]
unused = [v for v in range(1, nvars + 1) if occ[v] == 0]
print("nvars", nvars, "defined_nonunit_first", len(defined), "primary", len(primary), "unused", len(unused), "unit_vars", len(unit_first))
print("first 100 primary:", primary[:100])
print("primary ranges:")
ranges = []
if primary:
    a = b = primary[0]
    for v in primary[1:]:
        if v == b + 1:
            b = v
        else:
            ranges.append((a, b, b - a + 1))
            a = b = v
    ranges.append((a, b, b - a + 1))
for r in ranges[:200]:
    print(r)
print("range count", len(ranges))
print("top primary occurrences")
for v in sorted(primary, key=lambda x: occ[x], reverse=True)[:100]:
    print(v, "occ", occ[v], "pos", pos[v], "neg", neg[v], "inputrefs", input_refs[v], "unit", unit_first[v])
