function save_mat(varargin)
%function save_mat(i_mainloop, data_time, data_cmpds, output_file)

% will create a single .mat file with name batchname_matname_runid.mat
% containing possibly several variables

% 1st argument = output directory (with full path)
% 2nd argument = batch name, from output_filename in default_directories.m
% 3rd argument = .mat name to append to batch name
% 4th argument = run_id
% 5th argument = number of file if multiple files needed.  A zero means no
%           multiple tag is added.
% 6th and above = variables to save, in pairs.  The first member of the pair
%           contains the actual data.  The second member of the pair contains the
%           name (as a string) to append to the filename

mat_name = [varargin{2} '_' varargin{3} '_' num2str(varargin{4})];
if varargin{5} > 0
    mat_name = [mat_name '_' num2str(varargin{5})];
end

output_file = fullfile(varargin{1},mat_name);

if exist([output_file '.mat'], 'file')
    first_var = 0;
else
    first_var = 1;
end


for i = 6:2:nargin
    eval([varargin{i+1} ' = varargin{' num2str(i) '};'])
    if first_var
        eval(['save(output_file, ''' varargin{i+1} ''');'])
        first_var = 0;
    else
        eval(['save(output_file, ''-append'', ''' varargin{i+1} ''');'])
    end
end
    
