'Synchronizes a mailchimp list with the students of a course.'

def handle(self, *args, **options):

    (key, list_id, course_id, nsegments) = self.parse_options(options)
    log.info('Syncronizing    email    list    for    %s', course_id)
    mailchimp = connect_mailchimp(key)
    subscribed = get_subscribed(mailchimp, list_id)
    unsubscribed = get_unsubscribed(mailchimp, list_id)
    cleaned = get_cleaned(mailchimp, list_id)
    non_subscribed = unsubscribed.union(cleaned)
    enrolled = get_enrolled_students(course_id)
    exclude = subscribed.union(non_subscribed)
    to_subscribe = get_student_data(enrolled, exclude=exclude)
    tag_names = set(chain.from_iterable((d.keys() for d in to_subscribe)))
    update_merge_tags(mailchimp, list_id, tag_names)
    subscribe_with_data(mailchimp, list_id, to_subscribe)
    enrolled_emails = set(enrolled.values_list('user__email', flat=True))
    non_enrolled_emails = list(subscribed.difference(enrolled_emails))
    unsubscribe(mailchimp, list_id, non_enrolled_emails)
    subscribed = subscribed.union(set((d['EMAIL'] for d in to_subscribe)))
    make_segments(mailchimp, list_id, nsegments, subscribed)
