%

% Copyright 2018 The MathWorks, Inc.

classdef RestoreVariable < handle
    properties (SetAccess = immutable)
        exists (1,:) logical;
        prevValues (1,:) cell;
        vars (1,:) string;
        ws = 'base';
    end

    methods
        function this = RestoreVariable(vars)
            if nargin == 0
                vars = string.empty;
            end

            this.vars = vars;
            this.exists = ...
                arrayfun(@(var) evalin(this.ws, "exist('" + var + "', 'var')"), this.vars);
            this.prevValues(this.exists) = ...
                arrayfun(@(var) evalin(this.ws, var), this.vars(this.exists), 'Uniform', false);
        end

        function delete(this)
            % restore existing values
            cellfun(@(var, val) assignin(this.ws, var, val), ...
                this.vars(this.exists), this.prevValues(this.exists));
            % clear otherwise
            arrayfun(@(var) evalin(this.ws, "clear " + var), this.vars(~this.exists));
        end
    end
end
