% saves a file of run parameters, s, in the format with a timestamp as the
% first parameter. s is a structure, and all the paramters to save are only
% 1 level deep into the structure i.e. app.A and not app.A.B

%% Common Variables - density is not required

app.a = a;
app.b = b;

app.dx = dx;
app.dy = dy;

app.bcid2type_u=bcid2type_u;
app.bcid2type_v=bcid2type_v;
app.bcid2type_q=bcid2type_q;

app.bcsDq=bcsDq; app.bcsDu=bcsDu; app.bcsDv=bcsDv;
app.bcsOq=bcsOq; app.bcsOu=bcsOu; app.bcsOv=bcsOv;
app.bcsNq=bcsNq; app.bcsNu=bcsNu; app.bcsNv=bcsNv;

app.Fu = Fu;
app.Fv = Fv;

app.add_bnd = add_bnd;

%% Problem Specific Variables

%list of variables that are specific to different test cases, please
%augment list accordingly

ProbSpec = {
    'bcsDrho','bcsOrho','bcsNrho','periodic','uexact','vexact','pexact',...
    'u_inlet','FT','FS','bcsDT','bcsNT', 'bcsDS',...
    'bcsNS','bcsDP','bcsNP','T_swini','S_init','bnd'...
    'P_init','u_init','rho_init','v_init'...
    'bcid2type_rho'
    };
for ii = 1:length(ProbSpec)
    if exist(ProbSpec{ii},'var')
        eval(sprintf('app.%s=%s;',ProbSpec{ii},ProbSpec{ii}));
    end
end

%% User specific Variables

% Mask - related functions, geometries

%% convert app structure to cell
fields = repmat(fieldnames(app), numel(app), 1);
values = struct2cell(app);

%% Convert all cells to strings
idc = cellfun('isclass',values,'cell');
for ii = find(idc)'
    for jj = 1:nnz(idc)
        tempStr = sprintf(' %s ;',values{ii}{:});
        eval(sprintf('app.%s=''%s'';',fields{ii},tempStr))
    end
end
fields = repmat(fieldnames(app), numel(app), 1);
values = struct2cell(app);

%% Convert all function handles to strings
idf = cellfun('isclass',values,'function_handle');
values(idf) = cellfun(@func2str,values(idf), 'UniformOutput', 0);

%% Convert all numerical values to strings

idm = cellfun(@ismatrix,values);
values(idm) = cellfun(@mat2str,values(idm), 'UniformOutput', 0);

idx = cellfun(@isnumeric, values);
values(idx) = cellfun(@num2str, values(idx), 'UniformOutput', 0);

%% Combine field names and values in the same array and timestamp
C = {fields{:}; values{:}};

%% Write fields to file

% Format date and time
[Dnum, Dname] = weekday(date);
timestamp = sprintf('%s\t\t%s\t%s',Dname,datestr(clock,1),datestr(clock,14));

%Check to see if log file will be overwritten

d0=fileparts([pwd,filesep]);
d0=d0(1:strfind(d0,'trunk')+4);
if exist(sprintf('%s/Save/%s/',d0,app.savemat),'dir')
    fid = fopen(sprintf('%s/Save/%s/%s.log',d0,app.savemat,app.savemat), 'w');
else
    fid = fopen(sprintf('%s/Save/%s.log',d0,app.savemat), 'w');
end
fprintf(fid,'\t\t%s\n\n\n',timestamp);
fprintf(fid,sprintf('Current Directory %s\n\n',pwd));
fprintf(fid,'Input Parameters for FluidsSolver2:\n\n');
fmt_str = repmat('\n%s, %s\n', 1,size(C, 2));
fprintf(fid, [fmt_str(1:end - 1),'\n'], C{:});
fclose(fid);

