import re


def check_labels(labels, alllabs):
    """ Check that all labels are present in all cif files, handling regular expressions if needed.
    Returns
    -------
    list of labels to test,
    list of labels to omit,
    list of missing labels
    """
    
    test = set()
    omit = set()
    missing = set()
    
    for l in labels:
        # Iterate over labels, either adding to `test` or `omit` sets
        if any( [i in l for i in ['*','$','^','.','?','{','}','|','[',']','\\']] ):
            # Treat label as regex (approximately)
            if l[0] == '#':     # omit label l
                found = False
                for a in alllabs:
                    if re.search(l[1:], a):     # Regex matches
                        omit.add(a)
                        found = True
                if not found:
                    # omitted label did not occur in any file
                    missing.add(l)
            else:           # Find centres based on regex       
                found = False
                for a in alllabs:
                    if re.search(l, a):     # Regex matches
                        test.add(a)
                        found = True
                if not found:
                    # label not present in any file
                    missing.add(l)
        elif l[0] == '#':      # Omit centre with # prepending name
            if l[1:] in alllabs:
                omit.add(l[1:])
            else:
                missing.add(l)
            continue
        else:
            if l in alllabs:
                test.add(l)
            else:
                missing.add(l)
                
    return list(test), list(omit), list(missing)