function filewrite(fn,s,m);

% Function filewrite(fn,s)
%          filewrite(fn,s,m)
% 
% writes string s into a file with name fn.
% 
% The optional third argument holds the mode for
% writing, either "w", "wt", "a" or "at".
% The mode is "w" by default. See also the help text
% of fopen().
% 
% The function is an extended companion to standard
% function fileread().
% 
% 
% (c) 2026 fabien van mook
% 
% 2026.08.20 release of this file within package "fvm-hgeo" under GNU GPLv3+

% This program is free software: you can redistribute it
% and/or modify it under the terms of the GNU General Public
% License as published by the Free Software Foundation, either
% version 3 of the License, or (at your option) any later
% version.
% 
% This program is distributed in the hope that it will be
% useful, but WITHOUT ANY WARRANTY; without even the implied
% warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
% PURPOSE. See the GNU General Public License for more
% details.
% 
% You can read the GNU General Public License on
% <https://www.gnu.org/copyleft/gpl.html>.


if ( (nargin < 3) || isempty(m) ),
  m = "w";
endif;

if (! strcmp(m,{"w", "wt", "a", "at"})),
  warning(["writing mode \"" m "\" is not accepted; default \"w\" is used instead"]);
  m = "w";
endif;

% get the directory name from fn, 
% and make the directory if it does not exist yet:
d = fileparts(fn);
if ( (length(d) > 0) && (! isfolder(d)) ),
  [success,msg] = mkdir(d);
  if (! success),
    error(["unable to create directory \"" d "\" before writing file \"" fn "\": " msg]);
  endif;
endif;

[fid,msg] = fopen(fn,m);
if (fid == -1),
  error(["unable to open file \"" fn "\" for writing: " msg]);
endif;
fprintf(fid,"%s",s);
fclose(fid);

endfunction;
