import re


def parse_filename(filename):
    """Parse input filename formatted as 'num_name_hB_[12][ab]_*'."""
    # m = re.match(r'(\d+)_([\w_]+)_[^_]*_(\d\w)_', filename)
    m = re.search(r'(\d+)_(\w*)_?(\d\w)_', filename)
    if m is None:
        raise ValueError('Cannot parse filename: {}'.format(filename))
    num, name, scan = m.groups()
    return int(num), name.lower(), scan.lower()