function str = cell2str(C,n)
% function str = cell2str(C,n)
% Convert cell structure to string such that C = eval(str).
%
% [+GenLib General Purpose Library+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.

% F. Felici SPC 2018

assert(iscell(C),'C must be a cell');
assert(ndims(C)<=2,'Cell arrays with more than 2 dimensions are not supported');

[nrow,ncol] = size(C);

str = '{';
for ii=1:nrow
  for jj=1:ncol
    celldata = C{ii,jj};
    if isstruct(celldata)
      structstrcell = struct2str(celldata,n); % returns cell array of strings
      datastr = '';
      for kk = 1:numel(structstrcell)
        datastr = [datastr,structstrcell{kk},'\n']; %#ok<AGROW>
      end
      datastr = sprintf(datastr);
      % contatenate them to get a single string again
    elseif iscell(celldata)
      datastr = cell2str(celldata,n); % recursive call
    else
      datastr = field2str(celldata,n);
    end
    str = [str,datastr]; %#ok<AGROW>
    if jj == ncol
      str = [str,';']; %#ok<AGROW>
    else
      str = [str,',']; %#ok<AGROW>
    end
  end
end
str = [str,'}'];

end

function datastr = field2str(data,n)

if isnumeric(data) || islogical(data)
  datastr = mat2str(data,n,'class');
elseif ischar(data)
  datastr = ['''',data,''''];
else
  error('%s datatype not supported:',class(data))
end
end
