function okflag = writestruct(S,filename_input,n)
% function okflag = writestruct(S,filename_input[,n])
% writes a structure to a .m file.
% which can then be read by S = eval(filename_input)
% optional argument n

% F. Felici SPC 2018
if nargin==2
  n = 6; % default precision
end
textlines  = struct2str(S);
flag = writestructfile(textlines,filename_input);
okflag = ~flag;

end

function flag = writestructfile(textlines,filename_input)
% write to file
if ~strcmp(filename_input(end-1:end),'.m')
  fname = sprintf('%s.m',filename_input);
else
  fname = filename_input;
end
fid = fopen(fname,'w+');
[~,filename]=fileparts(filename_input); % get filename from filename_input with path
fprintf(fid,'function S = %s\n',filename);
fprintf(fid,'%% function S = %s\n%%\n',filename);
fprintf(fid,'%% File written automatically using struct2m.m \n');
fprintf(fid,'%% DATE: %s \n\n',date);
fprintf(fid,'S = ... \n');
for ii=1:(numel(textlines)-1)
  fprintf(fid,'%s\n',textlines{ii});
end
fprintf(fid,'%s;\n',textlines{end}); % last one with suppressing semicolon

% final semicolon
flag = fclose(fid);
end
