## Copyright (C) 2025
##
## This file is part of Octave.
##
## Octave 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.
##
## Octave 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 should have received a copy of the GNU General Public License
## along with Octave; see the file COPYING.  If not, see
## <https://www.gnu.org/licenses/>.

## -*- texinfo -*-
## @deftypefn {} {@var{tbl} =} loadobj (@var{s})
## Restore table from saved structure @var{s}.
##
## This function is called automatically when loading a table from .mat file
## to ensure the table type is preserved.
##
## @seealso{saveobj, save, load}
## @end deftypefn

function tbl = loadobj (s)
  if (! isstruct (s))
    error ("loadobj: input must be a structure");
  endif

  ## Check if this is a saved table
  if (isfield (s, "__table_marker__") && s.__table_marker__)
    ## Remove marker fields
    s = rmfield (s, "__table_marker__");
    if (isfield (s, "__table_class__"))
      s = rmfield (s, "__table_class__");
    endif
    
    ## Restore as table
    tbl = struct ();
    fnames = fieldnames (s);
    for i = 1:numel (fnames)
      fname = fnames{i};
      if (! strcmp (fname, "Properties"))
        tbl.(fname) = s.(fname);
      endif
    endfor
    
    ## Restore Properties
    if (isfield (s, "Properties"))
      tbl.Properties = s.Properties;
    else
      ## Ensure Properties exist
      tbl = __ensure_properties__ (tbl);
    endif
  else
    ## Not a table marker, return as-is (might be regular struct)
    tbl = s;
  endif
endfunction

