from pathlib import Path
import re


def count_examples(base_directory, languages):
    """
    Get the number of examples by language and total number of examples.

    :param base_directory: The path to the VTK example source files.
    :param languages: Folder and language name.
    :return: Language name and number of examples.
    """
    examples_count = dict()
    total = 0
    for k, v in languages.items():
        fn = Path(base_directory, k + '.md')
        # Does the directory exist?
        if not fn.is_file():
            raise RuntimeError(f'Non-existent folder: {str(fn)}')
        pattern = re.compile(r'^[\[][a-zA-Z0-9_ \-]+[\]][(]/' + k + '/')
        examples_count[v] = 0

        # Open and read the file counting the examples in it.
        subtotal = 0
        with open(fn) as f:
            for line in f:
                m = pattern.match(line)
                if m:
                    subtotal += 1
        examples_count[v] = subtotal
        total += subtotal
    examples_count['Total'] = total
    return examples_count