def order_events(events, d=False):
    """
    Group events that occur on the same day, then sort them alphabetically
    by title, then sort by day. Returns a list of tuples that looks like
    [(day: [events])], where day is the day of the event(s), and [events]
    is an alphabetically sorted list of the events for the day.
    """
    ordered_events = {}
    for event in events:
        try:
            for occ in event.occurrence:
                try:
                    ordered_events[occ].append(event)
                except Exception:
                    ordered_events[occ] = [event]
        except AttributeError:  # no occurrence for this event
            # This shouldn't happen, since an event w/o an occurrence
            # shouldn't get this far, but if it does, just skip it since
            # it shouldn't be displayed on the calendar anyway.
            pass

    if d:
        # return as a dict without sorting by date
        return ordered_events
    else:
        # return ordered_events as a list tuples sorted by date
        return sorted(ordered_events.items())
Group events that occur on the same day, then sort them alphabetically
    by title, then sort by day. Returns a list of tuples that looks like
    [(day: [events])], where day is the day of the event(s), and [events]
    is an alphabetically sorted list of the events for the day.