function r = kvpairs2struct(c);

% Function r = kvpairs2struct(c)
% 
% converts a row cellarray with a series of key-value 
% pairs to a structure, without attempting to make
% a structure array. Thus, each key in the cellarray
% becomes a field holding the value, whatever the value
% is. Each key must be a character vector (or string).
% 
% (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>.


r = struct();

if (! iscell(c)) || (size(c,1) > 1) || (mod(size(c,2),2) != 0),
  error("kvpairs2struct() expects the input of a row cellarray with an even number of elements");
endif;

for ic = [1:2:size(c,2)],
  if ischar(c{1,ic}),
    k = c{1,ic};
    v = c{1,ic+1};
    if isfield(r,k),
      warning("kvpairs2struct(): the value at key '%s' is overwritten because the key appears again at element %d of the input cellarray",k,ic);
    endif;
    r.(k) = v;
  else,
    error("kvpairs2struct(): element %d in the input cellarray is expected to be a key, but it is not a string",ic);
  endif;
endfor;

endfunction;
