## Copyright (C) 2025
##
## This file is part of Octave.
##
## Ensure that a table has a Properties structure with all required fields.

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

  ## Get field names (excluding Properties)
  fnames = fieldnames (tbl);
  fnames = fnames(! strcmp (fnames, "Properties"));

  ## Initialize Properties if missing
  if (! isfield (tbl, "Properties"))
    tbl.Properties = struct ();
  endif

  ## Ensure VariableNames exists and matches actual fields
  if (! isfield (tbl.Properties, "VariableNames") || ...
      isempty (tbl.Properties.VariableNames))
    tbl.Properties.VariableNames = fnames;
  endif

  ## Ensure other Properties fields exist
  if (! isfield (tbl.Properties, "RowNames"))
    tbl.Properties.RowNames = {};
  endif

  if (! isfield (tbl.Properties, "Description"))
    tbl.Properties.Description = "";
  endif

  if (! isfield (tbl.Properties, "VariableDescriptions"))
    num_vars = numel (tbl.Properties.VariableNames);
    tbl.Properties.VariableDescriptions = cell (1, num_vars);
  endif

  if (! isfield (tbl.Properties, "VariableUnits"))
    num_vars = numel (tbl.Properties.VariableNames);
    tbl.Properties.VariableUnits = cell (1, num_vars);
  endif
endfunction


