function secondlayer = deleteFemToSecondLayer( secondlayer, oldToNewFEMCell )
%secondlayer = deleteFemToSecondLayer( secondlayer, oldToNewFEMCell )
%   After deleting cells from the FEM layer of a mesh, call this to delete
%   every secondlayer cell which has a vertex in any of the deleted FEM cells.
%   oldToNewFEMCell maps old FEM cell indexes to new FEM cell indexes,
%   mapping the deleted cell indexes to zero.

    numcells = length( secondlayer.cells );
    numedges = size( secondlayer.edges, 1 );
    
    secondlayer.vxFEMcell = oldToNewFEMCell( secondlayer.vxFEMcell );
    testVxs = secondlayer.vxFEMcell ~= 0;
    [ newToOldVx, oldToNewVx ] = makeRenumbering( testVxs );
    secondlayer.vxFEMcell = secondlayer.vxFEMcell( testVxs );

    % vxBaryCoords
    secondlayer.vxBaryCoords = secondlayer.vxBaryCoords( testVxs, : );

    % cell3dcoords
    secondlayer.cell3dcoords = secondlayer.cell3dcoords( testVxs, : );
    
    testCell = zeros( 1, numcells, 'int8' );
    for ci=1:numcells
        testCell(ci) = all( testVxs( secondlayer.cells(ci).vxs ) );
    end
    [ newToOldCell, oldToNewCell ] = makeRenumbering( testCell );
    
    testEdge = zeros( 1, numedges, 'int8' );
    for ei=1:numedges
        testEdge(ei) = ...
            testCell( secondlayer.edges( ei, 3 ) ) ...
            || ( (secondlayer.edges( ei, 4 ) ~= 0) ...
                 && testCell( secondlayer.edges( ei, 4 ) ) );
    end
    [ newToOldEdge, oldToNewEdge ] = makeRenumbering( testEdge );
   
    % edges
    secondlayer.edges = secondlayer.edges( testEdge==1, : );
    numedges = size( secondlayer.edges, 1 );
    secondlayer.edges(:,1:2) = renumberArray( secondlayer.edges( :, 1:2 ), oldToNewVx );
    for ei=1:numedges
        ci1 = secondlayer.edges(ei,3);
        if ci1==0
            fprintf( 1, 'deleteFemToSecondLayer: error, edge %d invalid: ', ei );
            fprintf( 1, ' %d', secondlayer.edges(ei,:) );
            fprintf( '\n' );
        end
        ci2 = secondlayer.edges(ei,4);
        ci1a = oldToNewCell(ci1);
        if ci2 ~= 0
            ci2a = oldToNewCell(ci2);
        else
            ci2a = 0;
        end
        if ci1a==0
            ci1a = ci2a;
            ci2a = 0;
        end
        secondlayer.edges(ei,3:4) = [ ci1a, ci2a ];
    end

    % cells
    secondlayer.cells = secondlayer.cells( testCell==1 );
    % cellcolor
    if ~isempty( secondlayer.cellcolor )
        secondlayer.cellcolor = secondlayer.cellcolor( testCell==1, : );
    end
    numcells = length( secondlayer.cells );
    % cells().vxs
    % cells().edges
    for ci=1:numcells
        secondlayer.cells(ci).vxs = oldToNewVx( secondlayer.cells(ci).vxs );
        secondlayer.cells(ci).edges = oldToNewEdge( secondlayer.cells(ci).edges );
    end

    ok = checkclonesvalid( secondlayer );
end

