def handle(self, *args, **options):
        with open('bihar_case_cleanup.csv', 'wb') as f:
            csv_file = csv.writer(f)
            csv_file.writerow(CaseRow.headers)

            blank_case_ids = get_case_ids_in_domain('care-bihar',
                                                    type=('', None))
            task_case_ids = get_case_ids_in_domain('care-bihar', type='task')

            case_ids = set(blank_case_ids) | set(task_case_ids)
            to_save = []

            logger.info("Total cases to process: {}".format(len(case_ids)))
            for i, doc in enumerate(iter_docs(CommCareCase.get_db(), case_ids)):
                case = CommCareCase.wrap(doc)

                if case.type and case.type != "task":
                    continue
    
                parent = None
                if case.indices:
                    parent_id = case.indices[0].referenced_id
                    try:
                        parent = CommCareCase.get(parent_id)
                    except ResourceNotFound:
                        parent = MissingParent(get_id=parent_id, owner_id='Parent Missing')

                case_row = CaseRow(case, parent)

                if case.type != 'task':
                    if case.user_id == MOTECH_ID:
                        case_row.update_type('task')

                if parent and not isinstance(parent, MissingParent) and parent.owner_id != case.owner_id:
                    case_row.update_owner(parent.owner_id)

                if case_row.save:
                    csv_file.writerow(case_row.to_row())
                    to_save.append(case_row.case)

                if len(to_save) > 100:
                    CommCareCase.get_db().bulk_save(to_save)
                    to_save = []

                if i % 100 == 0:
                    logger.info("{current}/{count} cases completed".format(current=i, count=len(case_ids)))

            if to_save:
                CommCareCase.get_db().bulk_save(to_save)
dataset/ETHPy150Open dimagi/commcare-hq/custom/bihar/management/commands/bihar_cleanup_case.py/Command.handle/original