def import_committees_from_legislators(current_term, abbr):
    """ create committees from legislators that have committee roles """

    # for all current legislators
    for legislator in db.legislators.find({'roles': {'$elemMatch': {
            'term': current_term, settings.LEVEL_FIELD: abbr}}}):

        # for all committee roles
        for role in legislator['roles']:
            if (role['type'] == 'committee member' and
                    'committee_id' not in role):

                spec = {settings.LEVEL_FIELD: abbr,
                        'chamber': role['chamber'],
                        'committee': role['committee']}
                if 'subcommittee' in role:
                    spec['subcommittee'] = role['subcommittee']

                committee = db.committees.find_one(spec)

                if not committee:
                    committee = spec
                    committee['_type'] = 'committee'
                    # copy LEVEL_FIELD from legislator to committee
                    committee[settings.LEVEL_FIELD] = \
                        legislator[settings.LEVEL_FIELD]
                    committee['members'] = []
                    committee['sources'] = []
                    if 'subcommittee' not in committee:
                        committee['subcommittee'] = None
                    insert_with_id(committee)

                for member in committee['members']:
                    if member['leg_id'] == legislator['leg_id']:
                        break
                else:
                    committee['members'].append(
                        {'name': legislator['full_name'],
                         'leg_id': legislator['leg_id'],
                         'role': role.get('position') or 'member'})
                    for source in legislator['sources']:
                        if source not in committee['sources']:
                            committee['sources'].append(source)
                    db.committees.save(committee, safe=True)

                    role['committee_id'] = committee['_id']

        db.legislators.save(legislator, safe=True)
create committees from legislators that have committee roles