function [K,f,renumber] = eliminateEquations( K, f, ...
    rowsToElim, stitchrows, oppositePairs, stitchPairs, oppMoves, rowsToFix, fixedMoves )
%(K,f] = eliminateEquations( K, f, rowsToElim, stitchrows, oppositePairs, stitchPairs, oppMoves )
%    For each i in rowsToElim, delete row i of f and row and column i of K.
%    For each array in stitchrows, impose the constraint that the
%    corresponding set of variables are all equal.  (OBSOLETE -- never
%    used.)
%    For each pair [i,j] in oppositePairs, impose the condition that the
%    corresponding variables x and y have the property that o-x = o+y,
%    where o is the corresponding member of oppMoves.  When o=0, this is
%    the condition that x and y are equal and opposite.
%    For each pair [i,j] in stitchPairs, impose the condition that the
%    corresponding variables are equal.  If any vertex appears in both
%    oppositePairs and stitchPairs, remove it from stitchPairs and ensure
%    that its partner in stitchPairs appears in oppositePairs.

    if nargin < 6
        stitchPairs = [];
    end
    if nargin < 7
        oppMoves = [];
    end
    if nargin < 8
        fixedMovesMap = false( size(f) );
    end
    if nargin < 9
        fixedMoves = [];
    end
    [oppstitch,osi,osj] = intersect( oppositePairs(:), stitchPairs(:) );
    if ~isempty(oppstitch)
        orows = mod( osi-1, size(oppositePairs,1) ) + 1;
        zeroopp = oppositePairs( orows, : );
        srows = mod( osj-1, size(stitchpairs,1) ) + 1;
        zerostitched = stitchpairs( srows, : );
        oppositePairs( orows, : ) = [];
        stitchpairs( srows, : ) = [];
        rowsToElim = unique( [ rowsToElim, zeroopp(:)', zerostitched(:)' ] );
    end
    for i=1:length(stitchrows)
        r = stitchrows{i};
        nr = 1/length(r);
        K(:,r(1)) = nr * sum( K(:,r), 2 );
        f(r(1)) = nr * sum( f(r) );
        rowsToElim = [ rowsToElim; r(2:end) ];
    end
    K(:,stitchPairs(:,1)) = 2*(K(:,stitchPairs(:,1)) + K(:,stitchPairs(:,2)));
    f(stitchPairs(:,1)) = 2*(f(stitchPairs(:,1)) + f(stitchPairs(:,2)));
    rowsToElim = [ rowsToElim; stitchPairs(:,2) ];
    if (nargin >= 5) && ~isempty(oppositePairs)
        o1 = oppositePairs(:,1);
        o2 = oppositePairs(:,2);
        K(o1,:) = K(o1,:) - K(o2,:);
        Koppsum = K(o1,o1) + K(o1,o2);
        K(:,o1) = K(:,o1) - K(:,o2);
        f(o1) = f(o1) - f(o2) + Koppsum * oppMoves;
        rowsToElim = [ rowsToElim; o2 ];
    end
    
    if ~isempty( fixedMoves )
        rowsToElim = [ rowsToElim; rowsToFix ];
        f = f - K(:,rowsToFix) * fixedMoves;
    end

    if isempty(rowsToElim)
        if nargout >= 3
            renumber = [];
        end
    else
        remainingRows = eliminateVals( size(K,1), rowsToElim );
        K = K(remainingRows,remainingRows);
        f = f(remainingRows);
        if nargout >= 3
            renumber = remainingRows;
        end
    end
end
