function textlines = struct2str(S)
% generate strings to display structure
fields = fieldnames(S);

textlines{1} = sprintf('struct(...');
for ifield = 1:numel(fields)
  myfieldname = fields{ifield};
  myfieldval = S.(myfieldname);
  
  % write appropriate set of generating strings depending on type
  if isstruct(myfieldval)
    newlines = writeStructString(myfieldname,myfieldval);
  elseif iscell(myfieldval)
    newlines = writeCellString(myfieldname,myfieldval);
  else
    if isnumeric(myfieldval) || islogical(myfieldval)
      datastring = mat2str(myfieldval,20,'class');
    elseif ischar(myfieldval)
      datastring = sprintf('''%s''',myfieldval);
    else
      error('unsupported type')
    end
    newlines{1} = sprintf('''%s'',%s,...',myfieldname,datastring);
  end
  
  % append new text lines for this field
  textlines = {textlines{:},newlines{:}};
  clear newlines
end
% correct final string to close structure declaration
textlines{end} = [textlines{end}(1:end-4),')'];
end

function newlines = writeStructString(fieldname,fieldval)
datastr = struct2str(fieldval); % recursive call
% start-end fixes
datastr{1} = [sprintf('''%s'',',fieldname),datastr{1}];
datastr{end} = [datastr{end},',...'];
newlines = datastr;
end


function  newlines = writeCellString(fieldname,fieldval);
datastr{1} = cell2str(fieldval);
% start-end fixes
datastr{1} = [sprintf('''%s'',',fieldname),'{',datastr{1},'}'];
datastr{end} = [datastr{end},',...'];
newlines = datastr;
end

