function barcodeGen = keeplongestbitmask(barcodeGen)
% As the name suggests, in a bitmasks, there might be several continuous
% segments, this function kills shorter segments and keeps just the longest
% one

% For each cell in barcodeGen, replace rawBitmask with a mask that keeps
% only the longest continuous run of 1s.

for c = 1:numel(barcodeGen)

    bm = barcodeGen{c}.rawBitmask;   % ensure column vector

    % --- find all runs of ones ---
    d = diff([0 bm 0]);               % pad with 0's to detect transitions
    starts = find(d == 1);
    ends   = find(d == -1) - 1;

    if isempty(starts)
        % no 1's at all — rewrite as all zeros and continue
        newMask = zeros(size(bm));
        barcodeGen{c}.rawBitmask = newMask;
        continue
    end

    % --- lengths of each run ---
    lens = ends - starts + 1;

    % --- longest run ---
    [~, idx] = max(lens);
    keepStart = starts(idx);
    keepEnd   = ends(idx);

    % --- create new mask ---
    newMask = zeros(size(bm));
    newMask(keepStart:keepEnd) = 1;

    % overwrite in the struct
    barcodeGen{c}.rawBitmask = newMask;
end

end
