% function [] = ExportWorkspace2CSV(fname)
% writes the workspace to comma delimited file of name fname
% recursively expands structures to reveal numeric fields as required
function [] = exportvars2plaintext(fname, varargin)

if nargin <1 || isempty(fname)
	
	[f,p] = uiputfile( {'*.txt;*.csv;', 'Text Files (*.txt, *.csv)';...
		'*.*',  'All Files (*.*)' },....
		'Save as');
	
	fname = [p,'\',f];
end

tic

vars = evalin('base','who;');


% Parse Varargin
select = parse_varargs(varargin,'select',{'*'},'cell');
exclude = parse_varargs(varargin,'exclude',{},'cell');

% Convert Selects to Regular Expressions
select = strcat('^',strrep(select,'*','.*'),'$');
exclude = strcat('^',strrep(exclude,'*','.*'),'$');

for k = length(vars):-1:1

	sl = regexp( vars{k}, select );
	ex = regexp( vars{k}, exclude );
		
	if  any([ex{:}]) || ~any([sl{:}])
		vars(k) = [];		% Remove Exclude or not selected
	end
	
end

% Expand Variables
var_info = getvarinfo(vars);

file = fopen(fname,'w');

for k = 1:length(var_info)
	
	if var_info(k).size(1) > 1
		str = num2str(evalin('base',var_info(k).name)')';
	else
		str = num2str(evalin('base',var_info(k).name))';
	end
 	
	%str = num2str(evalin('base',var_info(k).name))';
	str(end+1,:) = 10;
	
	fprintf(file,'%s\n%s\n',var_info(k).name, str);	

end

fclose(file);
toc


    % subfunction to reveal numeric properties of varname
    % recursively expands structures as required
    function [varinfo ] = getvarinfo(vars)

		varinfo = [];
		
		for i = 1:length(vars)
			
			if evalin('base',['isstruct(', vars{i}, ')'] ) || evalin('base',['isobject(', vars{i}, ')'] )
			
				fields = evalin('base',['fieldnames(', vars{i}, ')']);

				for j=1:length(fields)
					fields{j} = [vars{i},'.',fields{j}];
				end
				
				varinfo = [varinfo, getvarinfo( fields)];
				
			elseif( evalin('base',['isnumeric(', vars{i}, ')' ]) || evalin('base',['ischar(', vars{i}, ')' ])	)
				
				varinfo(end+1).name = vars{i};
				varinfo(end).size = evalin('base',['size(', vars{i}, ')']);
				varinfo(end).class = evalin('base',['class(', vars{i}, ')']);
				
			end
	
			
		end
		
	
		