%-------------------------
% Variables definition
%-------------------------

GMII.TX_ER    % GMII TX_ER signal, 1xL row vector
GMII.TX_EN    % GMII TX_EN signal, 1xL row vector
GMII.TXD      % GMII TXD bus, 1xL row vector
PDB.TYPE      % PDB type field, 1x(L/8) row vector
PDB.PAYLOAD   % PDB payload field, 8x(L/8) matrix

%-------------------------
% PCS encoding procedure
%-------------------------

for i = 0:8:length(GMII.TXD)-1,
  TC = (GMII.TX_EN(i+1:i+8)*2 + GMII.TX_ER(i+1:i+8)) ~= 2;

  if any(TC)
    % There are at least one control byte in the 8-bytes GMII chunk
    % The PDB is a PDB.CTRL
    PDB.TYPE(i/8 + 1) = 1;
      
    if any(~TC(min(find(TC)):max(find(TC))))
      % The control bytes are not contiguous in the GMII chunk.
      % Replace data bytes that lie within control bytes with error code.
      LL=i+min(find(TC));
      UL=i+max(find(TC));
      GMII.TX_ER(LL:UL) = GMII.TX_EN(LL:UL)|GMII.TX_ER(LL:UL);

      TC(min(find(TC)):max(find(TC))) = 1;
    end
    
    % Valid GMII chunk
    % OFS field computation
    OFS = min(find(TC)) - 1
    
    % LEN field computation
    LEN = sum(TC) - 1
    
    % Build the PDB.CTRL payload
    for j = 1:8,
      if TC(j)
        if ~GMII.TX_EN(i+j) & ~GMII.TX_ER(i+j)
          % Normal inter-frame
          CTRL = 1;
        elseif ~GMII.TX_EN(i+j) & GMII.TX_ER(i+j) & (GMII.TXD(i+j) == 1)
          % Assert LPI
          CTRL = 2;
        elseif GMII.TX_EN(i+j) & GMII.TX_ER(i+j)
          % Transmit error propagation
          CTRL = 0;
        else
          % Otherwise, default case (normal inter-frame)
          CTRL = 1
        end
    
        B(j) = LEN + OFS*2^3 + CTRL*2^6;
      else
        B(j) = GMII.TXD(i+j);
      end
    end
    
    % Shift the first control byte
    PDB.PAYLOAD(1,     i/8 + 1) = B(OFS + 1);
    PDB.PAYLOAD(2:end, i/8 + 1) = [B(1:OFS) B(OFS+2:end)].';
  
  else
    % Pure normal data transmission bytes in the GMII chunk
    % The PDB is a PDB.DATA
    PDB.TYPE(i/8 + 1)       = 0;
    PDB.PAYLOAD(:, i/8 + 1) = GMII.TXD(i+1:i+8).';
  end
end
  
