function outp = mfs_eset2nset(cmp, eset, setnam)

# usage: nset = mfs_eset2nset(cmp, eset)
#        cmpx = mfs_eset2nset(cmp, eset, setnam)
#
# Input  cmp      Structure with component data
#        eset(:)  Array with element idenfifiers or name of an existing
#                 element set
#        setnam   Name for node set
#
# Output nset(:)  Array with identifiers of nodes referenced
#                 by elements in eset
#        cmp      Structure with component data
#
# The function creates a node set from an element set. If a name is specified
# for the node set, the node set is stored in the component. Otherwise, the
# list of the identifiers of the nodes in the set is returned.
#
# -----------------------------------------------------------------------------

# Copyright (c) 2023 by Johannes Wandinger

# Check arguments

  if (nargin < 2 || nargin > 3 || nargout != 1)
     print_usage();
  end

  if (! isstruct(cmp))
     error("mfs_eset2nset: first argument must be a structure\n");
  end

  if (! isfield(cmp, "type"))
     error("mfs_eset2nset: first argument must be a component\n");
  elseif(! strcmp(cmp.type, "solid"))
     error("mfs_eset2nset: only solid components supported\n");
  end

  if (nargin == 3) 
     if(! ischar(setnam))
        error("mfs_eset2nset: node set name must be a string\n");
     elseif (isfield(cmp.nset, setnam))
        error("mfs_eset2nset: node set %s already exists\n", 
              setnam);
     end
  end

# Get element indices

  if (ischar(eset))
     if (isfield(cmp.eset, eset))
        ix = cmp.eset.(eset);
     else
        error("mfs_eset2nset: element set %s does not exist\n",
              eset);
     end
  else
     ix = lookup(cmp.elements.index(:, 1), eset, "m");
  end

  ixelt = cmp.elements.index(ix, 2);

# Get nodal points

  nodes = [];

  for ix = ixelt
      nodes = [nodes, cmp.elements.elem(ix).nodes];
  end

# Build node set

  nset = unique(nodes);

# Output data

  if (nargin == 2)
     outp = cmp.nodes.ids(nset);
  else
     outp = cmp;
     outp.nset.(setnam) = nset;
  end

end
