import re


def break_down(compound, forgiving=True):
    """
    Breaks a string representing a chemical formula down into constituent parts.
    Things in parentheses are considered one part.
    Any string of a capital letter followed by lower case letters is considered to be
        an irriducible element.
    Any number is considered to quantify the element imediately proceeding it.
    Space is ignored
    Other characters raise a ValueError unless forgiving=True

    Example:
        >>> break_down('CH3(CH2)5CHO')
        >>> {'C':2, 'H':4', 'CH2':5, 'O':1}

    This function is called recursively by get_elements.
    """
    parts = {}
    number = ""
    element = ""
    subcompound = ""
    nest = 0
    N = len(compound)
    addit = False
    for i, char in enumerate(compound):
        if char == "(":
            if nest == 0:
                addit = True
            else:
                subcompound += char
            nest += 1
        elif nest > 0:
            if char == ")":
                nest -= 1
            if nest == 0:
                element = subcompound
                subcompound = ""
            else:
                subcompound += char
        else:
            if re.search("[/.0-9]", char):
                number += char
            elif re.search("[a-z]", char):
                element += char
            elif re.search("[A-Z\-\+]", char):
                addit = True
            elif re.search("\S", char):
                print(
                    "Not quite sure what you're talking about, mate, when you say ",
                    char,
                )
                if not forgiving:
                    raise ValueError
        if i == N - 1:
            addit = True
        # print('char = ' + char + '\nelement = ' + element + '\naddit = ' + str(addit))
        if addit:

            if len(number) > 0:
                try:
                    n = int(number)
                except ValueError:
                    n = float(number)
                number = ""
            else:
                n = 1
            if len(element) > 0:
                if element in parts:
                    parts[element] += n
                else:
                    parts[element] = n
            if nest == 0:
                element = char
                if i == N - 1 and re.search("[A-Z\-\+]", char):
                    if element in parts:
                        parts[element] += 1
                    else:
                        parts[element] = 1
            addit = False

    return parts