#!/usr/bin/env python3
# pylint: disable=C0112,C0114,C0116,C0301,R0903
# -*- Python -*- See copyright, etc below
######################################################################

import argparse
import re

#######################################################################

class VlSphinxExtract:
    debug = 0
    SkipBasenames = {}

    def process(self, filename):
        with open(filename) as fhr:
            fhw = None
            for line in fhr:
                # =for VL_SPHINX_EXTRACT "file_to_write_to"
                match = re.search(r'VL_SPHINX_EXTRACT +"([^"]+)"', line)
                if match:
                    outname = match.group(1)
                    print("Writing %s" % outname)
                    fhw = open(outname, "w")
                    fhw.write(
                        ".. comment: generated by vl_sphinx_extract from " +
                        filename + "\n")
                    fhw.write(".. code-block::\n")
                elif re.match(r'^[=a-zA-Z0-9_]', line):
                    fhw = None
                elif fhw:
                    fhw.write(line)


#######################################################################

parser = argparse.ArgumentParser(
    allow_abbrev=False,
    formatter_class=argparse.RawDescriptionHelpFormatter,
    description="""Read a file and extract documentation data.""",
    epilog=
    """ Copyright 2021-2021 by Wilson Snyder.  This package is free software;
you can redistribute it and/or modify it under the terms of either the GNU
Lesser General Public License Version 3 or the Perl Artistic License
Version 2.0.

SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0""")

parser.add_argument('--debug',
                    action='store_const',
                    const=9,
                    help='enable debug')
parser.add_argument('path', help='path to extract from')
Args = parser.parse_args()

o = VlSphinxExtract()
o.debug = Args.debug
o.process(Args.path)

######################################################################
# Local Variables:
# compile-command: "./vl_sphinx_extract --debug ../../bin/verilator"
# End:
