function barcodeGen = expand_mask(barcodeGen, buff,edges)
% Expands masked region bitmask by 'buff' digits on each side.
% usefull when masking peaks but still some steep boundaries remain
% usefull also when original bitmask is short on the sides
% buff: number of positions to expand on both sides (e.g., 2)
% edges (0/1) just inserts 6px bitmask on the edges, harmless if they are
% there already
if nargin < 3
    edges=0;
end
if nargin < 2
    buff = 2;
end
for b = 1:length(barcodeGen)
bitmask=barcodeGen{b}.rawBitmask;
L = length(bitmask);
expandedMask = bitmask; 

if edges==1
bitmask(1:6)=0;
bitmask(end-5:end)=0;
end    

% Find where bitmask is zero
zeroIdx = find(~bitmask);

% Mark which positions should be masked after padding
extraMask = false(size(bitmask));
for i = 1:length(zeroIdx)
    idx = zeroIdx(i);
    lower = max(1, idx - buff);
    upper = min(L, idx + buff);
    extraMask(lower:upper) = true;
end

% Final expanded mask: set positions to 0 where extraMask is true
expandedMask(extraMask) = false;
barcodeGen{b}.rawBitmask=expandedMask;
end
end

