function m = replaceNodes( m, newm )
%m = replaceNodes( m, newm )
%   Replace m.nodes and m.tricellvxs by newm.nodes and newm.tricellvxs.
%   If newm has prismnodes, replace that also.

    oldnumnodes = size( m.nodes, 1 );
    newnumnodes = size( newm.nodes, 1 );
    oldcentroids = permute( sum( reshape( m.nodes(m.tricellvxs',:), 3, [], 3 ), 1 ), [2 3 1] );
    newcentroids = permute( sum( reshape( newm.nodes(newm.tricellvxs',:), 3, [], 3 ), 1 ), [2 3 1] );
    if oldnumnodes ~= newnumnodes
        renumber = nearestNeighbours( newm.nodes, m.nodes );
        renumberCells = nearestNeighbours( newcentroids, oldcentroids );
    else
        renumber = [];
    end
    m.nodes = newm.nodes;
    m.tricellvxs = newm.tricellvxs;
    m.globalProps.trinodesvalid = true;
    m.decorFEs = [];
    m.decorBCs = [];
    if isfield( newm, 'prismnodes' )
        m.prismnodes = newm.prismnodes;
        m.globalProps.prismnodesvalid = true;
    else
        m.prismnodes = [];
        m.globalProps.prismnodesvalid = false;
    end
    if ~isempty( renumber )
        m.morphogens = m.morphogens( renumber, : );
        m.morphogenclamp = m.morphogenclamp( renumber, : );
        m.mgen_production = m.mgen_production( renumber, : );
        m.fixedDFmap = m.fixedDFmap( renumber, : );
        m.cellbulkmodulus = m.cellbulkmodulus( renumberCells );
        m.cellpoisson = m.cellpoisson( renumberCells );
        m.cellstiffness = m.cellstiffness( :, :, renumberCells );
        m.gradpolgrowth = m.gradpolgrowth( renumberCells, : );
        m.polfreeze = m.polfreeze( renumberCells, : );
        m.polfrozen = m.polfrozen( renumberCells );
        m.polfreezebc = m.polfreezebc( renumberCells, : );
    end
    m = safermfield( m, ...
        'unitcellnormals', ...
        'cellareas', ...
        'celledges', ...
        'edgeends', ...
        'edgecells', ...
        'celldata', ...
        'cellFrames' ...
    );
    m.secondlayer = struct();
    m = setmeshgeomfromnodes( m );
	m.effectiveGrowthTensor = zeros( size(m.tricellvxs,1), 6 );
    m = generateCellData( m );
  % [ok,m] = validmesh(m);
end
        
