function okflag = writecell(S,filename_input,n)
% function okflag = writecell(C,filename_input)
% writes a cell to a .m file.
% which can then be read by C = eval(filename_input)
%
% [+GenLib General Purpose Library+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.

% F. Felici SPC 2018

if nargin == 2
  n = 6; % default precision
end

textlines{1} = cell2str(S,n);
flag = writefile(textlines,filename_input);
okflag = ~flag;

end

function flag = writefile(textlines,filename_input)
% write to file
if ~strcmp(filename_input(end-1:end),'.m')
  % append .m if necessary
  fname = sprintf('%s.m',filename_input);
else
  fname = filename_input;
end
fid = fopen(fname,'w+'); assert(fid~=-1,'could not open file %s',fname);
[~,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 writecell.m \n\n');
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
