function m = makeedges( m, ee, ec, ce )
%m = makeedges( m, ee, ec, ce )
%   Construct m.edgeends, m.edgecells, m.celledges, and m.seams
%   from m.tricellvxs.
    if nargin < 2
        ee = ~isfield(m,'edgeends') || isempty(m.edgeends) || (m.edgeends(1,1)==0);
    end
    if nargin < 3
        ec = ~isfield(m,'edgecells') || isempty(m.edgecells) || (m.edgecells(1,1)==0);
    end
    if nargin < 4
        ce = ~isfield(m,'celledges') || isempty(m.celledges) || (m.celledges(1,1)==0);
    end
    if ~(ee || ec || ce), return; end

    numnodes = size(m.nodes,1);
    numcells = size(m.tricellvxs,1);
    edges = sparse(zeros(numnodes,numnodes));
    if ee, m.edgeends = int32([]); end
    for i=1:numcells
        vs = m.tricellvxs(i,:);
        [edges,e3] = ...
            recordedge(edges, i, vs(1), vs(2));
        [edges,e1] = ...
            recordedge(edges, i, vs(2), vs(3));
        [edges,e2] = ...
            recordedge(edges, i, vs(3), vs(1));
        if ce, m.celledges(i,:) = [e1,e2,e3]; end
    end
    m.seams = false( size(m.edgeends,1), 1 );

function [edges,ei] = recordedge( edges, c, v1, v2 )
    numedges = size(m.edgeends,1);
    if v1 > v2
        temp = v2; v2 = v1; v1 = temp;
    end
    ei = edges(v1,v2); % full(edges(v1,v2));
    if ei
        if ec, m.edgecells(ei,2) = c; end
    else
        numedges = numedges+1;
        ei = numedges;
        edges(v1,v2) = ei;
        if ee, m.edgeends(numedges,:) = int32( [v1,v2] ); end
        if ec, m.edgecells(ei,:) = int32( [c,0] ); end
    end
end

end
