function writeStructToFile(filename,S,TopStr)
%writes Structure of any structure to text file. Execute text file in
%MATLAB to rebuild the structure. Only works for fields of numeric and
%strings, and further structures
%eg. writeStructToFile('testfile.txt',myStruct,'newStructName')
%eg. writeStructToFile('TextSimParams.txt',SimParams,'SimParams')
names = fieldnames(S);
for i=1:length(names)
if isstruct(eval(['S.' names{i}]))
preStr=[TopStr,'.',names{i}];
eval(['writeStructToFile(''',filename,''',S.',names{i},',''',preStr,''')']);
else
fid=fopen(filename,'a');
fieldIsString=eval(['ischar(','S.',names{i},')']);
fieldIsNum=eval(['isnumeric(','S.',names{i},')']);
fieldIsCell=eval(['iscell(','S.',names{i},')']);
if(fieldIsString)
fwrite(fid,[TopStr,'.',names{i},' = ']);
eval(['fwrite(fid,['''''''',S.',names{i},','''''''']);']);
fwrite(fid,sprintf('\n'));
end
if(fieldIsNum)
[rows,cols]=eval(['size(S.',names{i},')']);
fwrite(fid,[TopStr,'.',names{i},' = [']);
for ir=1:rows
for ic = 1:cols
eval(['fwrite(fid,num2str(S.',names{i},'(ir,ic)));'])
if(ic~=cols)
fwrite(fid,',');
else
if(ir~=rows)
fwrite(fid,';...');
else
fwrite(fid,'];');
end
fwrite(fid,sprintf('\n'));
end
end
end
fwrite(fid,sprintf('\n'));
end
if(fieldIsCell)
error('Cells not implimented yet');
end
fclose(fid);
end
end
end