import re


def parse_deck_const(deck_abspath):
    """Parse constants in control cards and equations from TRNSYS deck file

    Finds all constants in a TRNSYS deck file and stores constant name and
    value in a dict.

    Args:
        deck_abspath: absolute path to TRNSYS deck file

    Returns:
        A dict containing all found constants and their values

    """

    const_dict = {}

    f = open(deck_abspath, 'r')

    split_blocks_pat = re.compile(r'[*][-]+')
    equa_pat = re.compile(r'[*]\sEQUATIONS\s"(.+?)"')
    const_pat = re.compile(r'\b(\w+)\b\s=\s(\d+\.*\d*)\s')

    with f:
        data = f.read()
        blocks = split_blocks_pat.split(data)
        for block in blocks:
            if block[0] == 'V':
                match_par = const_pat.findall(block)
                if match_par:
                    group = "Control Cards"
                    const_dict[group] = {}
                    for (m,v) in match_par:
                        const_dict[group][m] = v
            else:
                match_eq = equa_pat.findall(block)
                if match_eq:
                    group = match_eq[0]
                    match_par = const_pat.findall(block)
                    if match_par:
                        const_dict[group] = {}
                        for (m,v) in match_par:
                            const_dict[group][m] = v

    return const_dict