function varmerge(srcfile,dstfile,varname,report_id)
%VARMERGE Copies a variable from one MAT-file to another

% Copyright 2010 The MathWorks, Inc.

% Check if the destination file already contains a variable with this name.
try
    if ~isempty(whos('-file',dstfile,varname))
        % Yes, we're overwriting an existing value.  Save the original value in
        % a backup file.
        backupname = [ dstfile '~' ];
        value = load(dstfile,'-mat',varname); %#ok<NASGU>
        if exist(backupname,'file')
            save(backupname,'-struct','value','-append');
        else
            save(backupname,'-struct','value');
        end
    end
catch E
    % Don't treat this as a fatal error.
    disp(E.message);
end

try
    if isempty(whos('-file',srcfile,varname))
        % This is a deletion.
        deletevar(dstfile,varname);
    else
        % Copy the new value into the destination file.
        value = load(srcfile,'-mat',varname); %#ok<NASGU>
        save(dstfile,'-struct','value','-append');
    end
catch E
    % Failed.  Report the error prominently.
    if nargin>3 && ~isempty(report_id)
        c = com.mathworks.comparisons.compare.concr.MatDataComparison.getComparison(report_id);
        if ~isempty(c)
            c.doErrorDialog(E.message);
            return;
        end
    end
    errordlg(E.message);
    return;
end

% Refresh the report.
if nargin>3 && ~isempty(report_id)
    c = com.mathworks.comparisons.compare.concr.MatDataComparison.getComparison(report_id);
    if ~isempty(c)
        c.doRefresh;
    end
end
end




