function [code, genpoly, parityz, parityza] = bchenc2(msg, N, K)

[nRows nCols] = size(msg);
genpoly = bchgenpoly(N,K);

% nastaveni posuvneho registru
a  = fliplr(logical(genpoly.x)); 
st = length(a)-1;

u = logical(msg.x);

reg = false(nRows, st);
for iCol = 1 : nCols

    % provadena operace XOR mezi vstupem a registrem
    d = (u(:,iCol) | reg(:,st)) & ~(u(:,iCol) & reg(:,st));

    for idxPoly = st : -1 : 2   % provadena operace XOR mezi registrem a generujicim polynomem     
        reg(:,idxPoly) = ( reg(:,idxPoly-1) | (d & a(:,idxPoly)) ) & ...
            ( ~d | ~(reg(:,idxPoly-1) & a(:,idxPoly)) );
    end
    reg(:,1) = d;
end


parity = double(fliplr(reg));
parityz= [parity];
parityza = [msg zeros(1,N-K)];
code = gf([double(u) parity]);