function [cGenAll, outConsensus] = bargroup_splitter( cGenAll, outConsensus, bgroup,bars_to_remove)
%REWORK_BGROUP Remove selected bars from a given group and refresh consensus
%
%   [cGenAll, outConsensus] = rework_bgroup(bgroup, cGenAll, outConsensus, bars_to_remove)
%
%   Inputs:
%       bgroup          - index of the group to modify
%       cGenAll         - cell array of structs (with fields .idx, .comparisonStruct, etc.)
%       outConsensus    - cell array of consensus matrices
%       bars_to_remove  - vector of idx values (not row indices) to remove
%
%   Outputs:
%       cGenAll         - updated structure with removed bars and refreshed .rawBarcode/.rawBitmask
%       outConsensus    - updated consensus matrices with rows removed

    % --- Validate inputs ---
    if bgroup > numel(cGenAll) || bgroup > numel(outConsensus)
        error('Invalid bgroup index.');
    end

    % Extract current group
    thisStruct = cGenAll{bgroup};
    thisConsensus = outConsensus{bgroup};

    % Which indices to remove? (match bars_to_remove with .idx values)
    removeMask = ismember(thisStruct.idx, bars_to_remove);

    % --- Remove from idx ---
    thisStruct.idx(removeMask) = [];

    % --- Remove from comparisonStruct ---
    if isfield(thisStruct, 'comparisonStruct')
        thisStruct.comparisonStruct(removeMask) = [];
    end

    % --- Remove rows from outConsensus ---
    thisConsensus(removeMask, :) = [];

    % --- Compute new rawBarcode ---
    if isempty(thisConsensus)
        % if everything was removed, fallback to empty
        newBarcode = [];
        newBitmask = [];
    else
        newBarcode = nanmean(thisConsensus, 1); % nanmean across rows
        newBitmask = ones(size(newBarcode));

        % mark leading NaNs
        firstValid = find(~isnan(newBarcode), 1, 'first');
        if ~isempty(firstValid) && firstValid > 1
            newBitmask(1:firstValid-1) = 0;
        end

        % mark trailing NaNs
        lastValid = find(~isnan(newBarcode), 1, 'last');
        if ~isempty(lastValid) && lastValid < numel(newBarcode)
            newBitmask(lastValid+1:end) = 0;
        end
    end

    % --- Assign new fields ---
    thisStruct.rawBarcode = newBarcode;
    thisStruct.rawBitmask = newBitmask;

    % Save back into cGenAll and outConsensus
    cGenAll{bgroup} = thisStruct;
    outConsensus{bgroup} = thisConsensus;
end
