'Helper method for copying datasets.'

def _copy_datasets(self, trans, dataset_ids, target_histories, imported=False):

    user = trans.get_user()
    done_msg = error_msg = ''
    invalid_datasets = 0
    if ((not dataset_ids) or (not target_histories)):
        error_msg = 'You    must    provide    both    source    datasets    and    target    histories.'
    else:
        for history in target_histories:
            if (user != history.user):
                error_msg = (error_msg + ('You    do    not    have    permission    to    add    datasets    to    %i    requested    histories.        ' % len(target_histories)))
        for dataset_id in dataset_ids:
            decoded_id = self.decode_id(dataset_id)
            data = self.hda_manager.get_accessible(decoded_id, trans.user)
            data = self.hda_manager.error_if_uploading(data)
            if (data is None):
                error_msg = (error_msg + 'You    tried    to    copy    a    dataset    that    does    not    exist    or    that    you    do    not    have    access    to.        ')
                invalid_datasets += 1
            else:
                for hist in target_histories:
                    dataset_copy = data.copy(copy_children=True)
                    if imported:
                        dataset_copy.name = ('imported:    ' + dataset_copy.name)
                    hist.add_dataset(dataset_copy)
        trans.sa_session.flush()
        num_datasets_copied = (len(dataset_ids) - invalid_datasets)
        done_msg = ('%i    dataset%s    copied    to    %i    histor%s.' % (num_datasets_copied, iff((num_datasets_copied == 1), '', 's'), len(target_histories), iff((len(target_histories) == 1), 'y', 'ies')))
        trans.sa_session.refresh(history)
    if (error_msg != ''):
        status = ERROR
        message = error_msg
    else:
        status = SUCCESS
        message = done_msg
    return (status, message)
