#! /usr/bin/env python
"""Find Eigen usages in source files, for detecting un-initialized vectors and arrays."""

import re
import glob
from collections import OrderedDict


def find_usages() -> None:
    """
    Find the modules referenced by each module under 'sources'.

    :return: dictionary with keys being module names and values being the
        dependencies
    """
    source_files = glob.glob("sources/*/*.h")
    source_files.extend(glob.glob("sources/*/*.cpp"))
    source_files.extend(glob.glob("sources/*/*.c"))
    patterns = [
        re.compile(r".*Eigen\s*::\s*[(Vector)(Matrix)]+\w{,3}\s+\w+.*", re.I),  # Eigen::Vector?? X;
        re.compile(r".*\w\s*=\s*Eigen\s*::\s*[(Vector)(Matrix)]+\w{,3}.*")]  # a = Eigen::Vector??;
    for src in source_files:
        targets = OrderedDict()
        with open(src, "r") as src_file:
            content = src_file.readlines()
        for nl, line in enumerate(content):
            for p in patterns:
                if (len(re.findall(p, line)) > 0):
                    targets[nl+1] = line
        if len(targets) > 0:
            print(src)
            for nl, line in targets.items():
                print(nl, line, end="")
            print()


if __name__ == "__main__":
    find_usages()
